I would like to download a PDF report from our Microsoft Report Server using my C# code. I don't know why, but I' m doing something wrong. I always get an error back that the authentication failed (HTTP 401).
public static async Task<Stream> DownloadWebDocument(string url) {
if (string.IsNullOrEmpty(url))
throw new ArgumentNullException(nameof(url));
WebRequest request = WebRequest.Create(url);
request.Method = "GET";
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
request.Credentials = new NetworkCredential("MyUsername", "MyPassword", "MyDomain");
//request.Headers.Add("Authorization", $"Basic {Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("MyUsername:MyPassword"))}");
try {
using WebResponse response = await request.GetResponseAsync();
return response.GetResponseStream();
} catch (Exception ex) {
var a = ex.Message;
throw;
}
//return await DownloadWebDocument(uri);
}
This code always runs into the exception. But why?
PS:
As requested, here's the stack trace. There is no inner exception.
bei System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
bei System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
bei System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
bei DE.ZA.TrailerLoadingAssistant.Web.Code.WebHelper.<DownloadWebDocument>d__0.MoveNext() in C:\Users\Reichelt\source\repos\DE.ZA.TrailerLoading\DE.ZA.TrailerLoadingAssistant.Web\Code\WebHelper.cs:Zeile 28.
I realized, that if I use request.Credentials = CredentialCache.DefaultCredentials, it works. So there must be something wrong with my credentials. But it's definitely no typo.
I've had this problem and it seemed someone was changing the network permissions. One week using Credentials would work then the next week using DefaultCredentials worked. Really strange, so I put in a Try/Catch and resort to the DefaultCredentials if the Service Account fails, see the code comment:
public class SRSHelper
{
private ReportingService2005 rsServ;
private ReportingExecution2005 rsExec = new ReportingExecution2005();
private ReportParameter[] reportParameters;
private ExecutionInfo execInfo = null;
public SRSHelper(string reportUserName, string decryptedPassword, string reportDomain, string reportServerURL)
{
rsServ = new ReportingService2005(reportServerURL);
rsExec.Url = reportServerURL + #"ReportExecution2005.asmx";
System.Net.NetworkCredential creds = new System.Net.NetworkCredential();
creds.UserName = reportUserName;
creds.Password = decryptedPassword;
creds.Domain = reportDomain;
rsExec.Credentials = creds;
rsServ.Credentials = creds;
}
public ReportParameter[] GetSRSReportParameters(string reportName)
{
string report = "/Reporting/" + reportName;
bool forRendering = false;
string historyID = null;
ParameterValue[] values = null;
DataSourceCredentials[] credentials = null;
try
{
return rsServ.GetReportParameters(report, historyID, forRendering, values, credentials);
}
catch
{
//If the Service Account credentials fail to work - try the users credentials - XYZ vendor regularly change things around or the network fails or for some reason beyond our control we have to change the settings.
rsExec.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
rsServ.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
return rsServ.GetReportParameters(report, historyID, forRendering, values, credentials);
}
}
Actually I use different method to render my report as PDF document:
public static byte[] DownloadAsPDF(string ReportServer, string ReportPath)
{
ReportViewer ReportViewer1 = new ReportViewer();
ReportViewer1.ServerReport.ReportServerCredentials = new
CustomReportCredentials("MyUsername", "MyPassword", "MyDomain");
ReportViewer1.ProcessingMode =
Microsoft.Reporting.WebForms.ProcessingMode.Remote;
ReportViewer1.ServerReport.ReportServerUrl = new Uri(ReportServer);
ReportViewer1.ServerReport.ReportPath = ReportPath;
byte[] bytes = ReportViewer1.ServerReport.Render("PDF");
return bytes;
}
public class CustomReportCredentials :
Microsoft.Reporting.WebForms.IReportServerCredentials
{
// local variable for network credential.
private string _UserName;
private string _PassWord;
private string _DomainName;
public CustomReportCredentials(string UserName, string PassWord,
string DomainName)
{
_UserName = UserName;
_PassWord = PassWord;
_DomainName = DomainName;
}
public System.Security.Principal.WindowsIdentity ImpersonationUser
{
get
{
return null; // not use ImpersonationUser
}
}
public ICredentials NetworkCredentials
{
get
{
// use NetworkCredentials
return new NetworkCredential(_UserName, _PassWord,
_DomainName);
}
}
public bool GetFormsCredentials(out Cookie authCookie, out string
user, out string password, out string authority)
{
authCookie = null;
user = password = authority = null;
return false;
}
}
Related
//i have left out some parameters for readability
public static string MailForCandidate(string username, string FromAddr, string ToAddr, string strSubject)
{
try
{
MailMessage msg = new MailMessage();
string strMailBody = "Test body";
msg.To = ToAddr;
msg.From = FromAddr;
msg.BodyFormat = MailFormat.Html;
msg.Priority = MailPriority.High;
msg.Subject = strSubject;
msg.Body = strMailBody.ToString();
SmtpMail.SmtpServer = ConfigurationManager.AppSettings["mailServer"].ToString();
try
{
SmtpMail.Send(msg);
msg = null;
return "";
}
catch (Exception ex)
{
Util.Common.LogErrorMessage(ex);
msg = null;
return username;
}
}
catch (Exception ex)
{
throw ex;
}
}
I have the above function that i'm using to send emails from an IIS hosted .NET 3.5 asp.net application.
The emails are sent at the click of a button and the recipients are being read from a database table.
The problem i'm having is that some recipients get their emails with out any issue, others take far too long to receive their emails (sometimes after 24 hours) at which time the event they are supposed to participate in has expired (and this has legal implications to my company). And then finally, others do not receive the email completely.
The above MailForCandidate function is being called from SendCandidateMail below.
private void SendCandidateMail(int intEmailType)
{
try
{
ArrayList arrPending = new ArrayList();
ArrayList arrUnsent = new ArrayList();
string strCandidatename = string.Empty;
string stractualname = string.Empty;
int intUnsentCandCount = 0;
if (hdnUnsentNames.Value.Trim() != string.Empty)
{
arrUnsent.AddRange(hdnUnsentNames.Value.Split(','));
}
if (hdnPendingNames.Value.Trim() != string.Empty)
{
arrPending.AddRange(hdnPendingNames.Value.Split(','));
}
hdnUnsentNames.Value = string.Empty;
hdnPendingNames.Value = string.Empty;
if (!string.IsNullOrEmpty(hdnUnsent.Value) && !string.Empty.Equals(hdnUnsent.Value))
{
string[] strUnsIds = hdnUnsent.Value.Split('~');
for (int i = 0; i < strUnsIds.Length; i++)
{
DataSet dtsetCandidate = CandidatesListBL.GetCandidateDetails(Convert.ToInt32(strUnsIds[i]));
stractualname = arrUnsent[i].ToString();
if (dtsetCandidate.Tables[0].Rows.Count > 0)
{
if (dtsetCandidate.Tables[0].Rows[0]["Time"].ToString() != "0")
{
//i have left out some parameters for readability
strCandidatename = SendMail.MailForCandidate(dtsetCandidate.Tables[0].Rows[0]["User_Id"].ToString(), intEmailType);
}
else
strCandidatename = SendMail.MailForCandidateNoTime(dtsetCandidate.Tables[0].Rows[0]["User_Id"].ToString(), intEmailType);
if (strCandidatename.Trim().Equals(string.Empty))
{
hdnUnsentNames.Value = hdnUnsentNames.Value + stractualname + ",";
intUnsentCandCount = intUnsentCandCount + 1;
if (Convert.ToInt32(EnumMaster.EmailType.Customized) != intEmailType)
{
CandidatesListBL.UpdateCandidateStatus(Convert.ToInt32(strUnsIds[i]), "Sent");
CandidatesListBL.UpdateDateSent(Convert.ToInt32(strUnsIds[i]));
}
}
}
}
hdnUnsent.Value = string.Empty;
}
}
catch (Exception ex)
{
WESMessage.DisplayMessage(this, this.UpdatePanel1, DanielHac.TamperProofString.QueryStringEncode("MailFailed"), this.strinfo);
Common.LogErrorMessage(ex);
}
}
Below is what is being logged in the error log text file.
01/22/2017 3:23:04 PM ==> Exception Message: Thread was being aborted.
01/22/2017 3:23:04 PM ==> Exception Source: App_Code
Exception Target Site: System.String MailForCandidate(System.String, System.String, System.String, System.Collections.ArrayList, System.String, System.String, System.String, System.String, System.String, System.String, UserSession, System.String, System.String, Int32, Int32)
Exception Stack Trace: at WES.Util.SendMail.MailForCandidate(String strUserID, String username, String password, ArrayList alFiles, String FromName, String FromAddr, String ToAddr, String title, String strSubject, String strCustomMsg, UserSession UserObj, String strDeadLine, String strTime, Int32 intOfficeId, Int32 intMailType)
at Pages_ExerciseDetails.SendCandidateMail(Int32 intEmailType)
Exception To String: System.Threading.ThreadAbortException: Thread was being aborted.
at WES.Util.SendMail.MailForCandidate(String strUserID, String username, String password, ArrayList alFiles, String FromName, String FromAddr, String ToAddr, String title, String strSubject, String strCustomMsg, UserSession UserObj, String strDeadLine, String strTime, Int32 intOfficeId, Int32 intMailType)
at Pages_ExerciseDetails.SendCandidateMail(Int32 intEmailType)
And
01/22/2017 3:23:04 PM ==> Exception Message: Thread was being aborted.
01/22/2017 3:23:04 PM ==> Exception Source: App_Web_kxc2lbj5
Exception Target Site: Void SendCandidateMail(Int32)
Exception Stack Trace: at Pages_ExerciseDetails.SendCandidateMail(Int32 intEmailType)
at Pages_ExerciseDetails.ibtnSend_Click(Object sender, EventArgs e)
Exception To String: System.Threading.ThreadAbortException: Thread was being aborted.
at Pages_ExerciseDetails.SendCandidateMail(Int32 intEmailType)
at Pages_ExerciseDetails.ibtnSend_Click(Object sender, EventArgs e)
Also
01/22/2017 3:23:04 PM ==> Exception Message: Request timed out.
101/22/2017 3:23:04 PM ==> Exception Source: Exception Target Site:
Exception Stack Trace: Exception To String: System.Web.HttpException:
Request timed out.
Then
101/22/2017 3:31:35 PM ==> Exception Message: Exception of type
'System.Exception' was thrown. 01/22/2017 3:31:35 PM ==> Exception
Source: App_Web_kxc2lbj5 Exception Target Site: Void
SendCandidateMail(Int32) Exception Stack Trace: at
Pages_ExerciseDetails.SendCandidateMail(Int32 intEmailType) Exception
To String: System.Exception: Exception of type 'System.Exception' was
thrown. at Pages_ExerciseDetails.SendCandidateMail(Int32
intEmailType)
I'm find it hard to troubleshot because it is occurring in production ONLY. In QA and Dev, emails are just going fine using the same SMTP server.
I will just post my comment here as the answer.
I resolved this bu just discarding the obsolete system.web.mail. I
re-wrote the code using System.Net.Mail & all issues are resolved,
performs even much faster.
I have an android app which is making api requests to my server running Spring MVC. The RestController works fine when I make a request from the browser but it responds with 404 when I am making requests from android. Not sure why
Here is code snippet from Android app making requests
public class AsyncFetch extends AsyncTask<Pair<String, String>, String, String> {
public ProgressDialog pdLoading;
private HttpURLConnection conn;
private String urlStr;
private String requestMethod = "GET";
public AsyncFetch(String endpoint, Context ctx)
{
pdLoading = new ProgressDialog(ctx);
Properties reader = PropertiesReader.getInstance().getProperties(ctx, "app.properties");
String host = reader.getProperty("host", "10.0.2.2");
String port = reader.getProperty("port", "8080");
String protocol = reader.getProperty("protocol", "http");
String context = reader.getProperty("context", "");
this.urlStr = protocol+"://"+host+":"+port+context+endpoint;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(Pair<String, String>... params) {
URL url;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod(requestMethod);
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made`enter code here`
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
Spring MVC Controller
#RestController
public class ApiController {
#RequestMapping(value = "homefeed", method=RequestMethod.GET)
public String homefeed(#RequestParam(value="userId", required = false) Integer id, #RequestParam(value="search", required = false) String search, #RequestParam(value="page", required = false, defaultValue = "0") Integer page) { ... }
}
localhost:8080/api/homefeed -- works
127.0.0.1:8080/api/homefeed -- works
My Public IP:8080/api/homefeed -- does not works
10.0.2.2:8080/api/homefeed -- android emulator to localhost -- does not work
10.0.2.2:8080/Some resource other than the api endpoint -- works
Any help is highly appreciable, have wasted quiet some time in debugging.
I'm adding confirmation email feature to my ASP.NET WebAPI project. The server can send email fine, however, the confirmation link always return "Invalid token".
I checked some reasons as pointed out here
http://tech.trailmax.info/2015/05/asp-net-identity-invalid-token-for-password-reset-or-email-confirmation/
but it seems that none of them is the root cause
Below is my code:
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
IdentityResult result;
result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
try
{
await userManager.AddToRoleAsync(user.Id, "Player");
//Generate email confirmation token
//var provider = new DpapiDataProtectionProvider("GSEP");
var provider = new MachineKeyProtectionProvider();
userManager.UserTokenProvider = new DataProtectorTokenProvider<GSEPUser>(provider.Create("EmailConfirmation"));
var code = await userManager.GenerateEmailConfirmationTokenAsync(user.Id);
code = System.Web.HttpUtility.UrlEncode(code);
EmailHelper emailHelper = new EmailHelper();
string callBackUrl = emailHelper.GetCallBackUrl(user, code);
EmailMessage message = new EmailMessage();
message.Body = callBackUrl;
message.Destination = user.Email;
message.Subject = "GSEP Account confirmation";
emailHelper.sendMail(message);
}
catch (Exception e)
{
return Ok(GSEPWebAPI.App_Start.Constants.ErrorException(e));
}
}
And now is EmailHelper
public class EmailHelper
{
public string GetCallBackUrl(GSEPUser user, string code)
{
var newRouteValues = new RouteValueDictionary(new { userId = user.Id, code = code });
newRouteValues.Add("httproute", true);
UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext, RouteTable.Routes);
string callbackUrl = urlHelper.Action(
"ConfirmEmail",
"Account",
newRouteValues,
HttpContext.Current.Request.Url.Scheme
);
return callbackUrl;
}
public void sendMail(EmailMessage message)
{
#region formatter
string text = string.Format("Please click on this link to {0}: {1}", message.Subject, message.Body);
string html = "Please confirm your account by clicking this link: link<br/>";
html += HttpUtility.HtmlEncode(#"Or click on the copy the following link on the browser:" + message.Body);
#endregion
MailMessage msg = new MailMessage();
msg.From = new MailAddress("myemail#example.com");
msg.To.Add(new MailAddress(message.Destination));
msg.Subject = message.Subject;
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));
SmtpClient smtpClient = new SmtpClient("smtp-mail.outlook.com", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("myemail#example.com", "mypassword!");
smtpClient.Credentials = credentials;
smtpClient.EnableSsl = true;
smtpClient.Send(msg);
}
}
And 2 MachineKey class
public class MachineKeyProtectionProvider : IDataProtectionProvider
{
public IDataProtector Create(params string[] purposes)
{
return new MachineKeyDataProtector(purposes);
}
}
public class MachineKeyDataProtector : IDataProtector
{
private readonly string[] _purposes;
public MachineKeyDataProtector(string[] purposes)
{
_purposes = purposes;
}
public byte[] Protect(byte[] userData)
{
return MachineKey.Protect(userData, _purposes);
}
public byte[] Unprotect(byte[] protectedData)
{
return MachineKey.Unprotect(protectedData, _purposes);
}
}
I also added machineKey tag in Web.config as some instruction pointed out.
And finally is my confirmation email API
[AllowAnonymous]
[HttpGet]
public async Task<IHttpActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return Ok("Confirm error");
}
IdentityResult result;
try
{
result = await UserManager.ConfirmEmailAsync(userId, code);
}
catch (InvalidOperationException ioe)
{
// ConfirmEmailAsync throws when the userId is not found.
return Ok("UserID not found");
}
if (result.Succeeded)
{
return Ok("Confirmation succesfully");
}
else
{
return Ok(result.Errors);
}
}
Please show me where am I go wrong
I know this is an old thread. But I though of adding the answer as it could help others.
You are using the below code
string callbackUrl = urlHelper.Action(
"ConfirmEmail",
"Account",
newRouteValues,
HttpContext.Current.Request.Url.Scheme
);
and the UrlHelper.Action already does the url encoding for you in the latest MVC versions. So here in your code you are doing the encoding twice (one inside the Register and another inside GetCallBackUrl using urlHelper.Action) and that is why you are getting the invalid token error.
I'm new to FTP and asp.net my code works only during local host test however during live test on go-daddy i get error. any help would be great thank you.
I'm currently hosting 2 web site all the pages and code is in AMUS folder
Unable to connect to the remote server
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.WebException: Unable to connect to the remote server
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[WebException: Unable to connect to the remote server]
System.Net.FtpWebRequest.GetRequestStream() +839
DBMiddleTier.addImageFTP(FileUpload file) +360
Admin_CrudOperation.imgAddProduct_Click(Object sender, ImageClickEventArgs e) +96
System.Web.UI.WebControls.ImageButton.OnClick(ImageClickEventArgs e) +115
System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +120
System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
My code
//method to add image ftp
public string addImageFTP(FileUpload file)
{
string filename = Path.GetFileName(file.FileName);
Bitmap src = Bitmap.FromStream(file.PostedFile.InputStream) as Bitmap;
Bitmap result = new Bitmap(src, 300, 300);
string saveName = savePath + filename;
result.Save(saveName, ImageFormat.Jpeg);
System.Net.FtpWebRequest request = System.Net.WebRequest.Create("ftp://***.***.***.*/AMUS/images/" + filename) as System.Net.FtpWebRequest;
//this example assumes the FTP site uses anoymous login on
//NetWorkCredentials provides credentials for password-based authentication such as digest, basic, NTLM
request.Credentials = new System.Net.NetworkCredential("Username", "Password");
//Copy the contents of the file to the request stream
byte[] fileContents = null;
if (file.HasFile)
{
//fileContents = FileUploadControl.FileBytes;
fileContents = File.ReadAllBytes(saveName);
}
else
{
string res = "you need to provide a file";
return res;
}
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
request.ContentLength = fileContents.Length;
//GetReequestStream: retrieves the stream used to upload data to an FTP server.
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
return "Successful Upload";
}
/// <summary>
/// ftpClient.upload("etc/test.txt", #"C:\Users\metastruct\Desktop\test.txt");
/// </summary>
/// <param name="remoteFile"></param>
/// <param name="localFile"></param>
public void uploadFile(string remoteFile, string localFile)
{
try
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
/* Establish Return Communication with the FTP Server */
ftpStream = ftpRequest.GetRequestStream();
/* Open a File Stream to Read the File for Upload */
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
/* Buffer for the Downloaded Data */
byte[] byteBuffer = new byte[bufferSize];
int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
/* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
try
{
while (bytesSent != 0)
{
ftpStream.Write(byteBuffer, 0, bytesSent);
bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
}
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Resource Cleanup */
localFileStream.Close();
ftpStream.Close();
ftpRequest = null;
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
return;
}
/// <summary>
/// ftp.uploadFolderContents("httpdocs/omid", #"E:\omid");
/// </summary>
/// <param name="remoteFolder"></param>
/// <param name="localFolder"></param>
/// <returns></returns>
public bool uploadFolderContents(string remoteFolder, string localFolder)
{
bool rslt = false;
try
{
string[] files = Directory.GetFiles(localFolder);
string[] dirs = Directory.GetDirectories(localFolder);
foreach (string file in files)
{
uploadFile(remoteFolder + "/" + Path.GetFileName(file), file);
}
foreach (string dir in dirs)
{
createFolder(remoteFolder + "/" + Path.GetFileName(dir));
uploadFolderContents(remoteFolder + "/" + Path.GetFileName(dir), dir);
}
rslt = true;
}
catch (Exception)
{
rslt = false;
}
return rslt;
}
/// <summary>
/// ftpClient.createDirectory("etc/test");
/// </summary>
/// <param name="newDirectory"></param>
public void createFolder(string newDirectory)
{
try
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + newDirectory);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Resource Cleanup */
ftpResponse.Close();
ftpRequest = null;
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
return;
}
You would think with all the posts here that this would be easy to figure out. :| Well here is what should be a simple example. NOTE The web service is VB and the client is c#. The wb service sends and receives fine when called from JQuery. From .NET There is a problem,
If the service asks for a parameter as show below then the client's getresponse method gets error 500 Internal server error
The Web Service
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, XmlSerializeString:=False)> _
Public Function Test(WebInfo As GetUserID) As Person
Dim Someone As New Person
Someone.Name = "Bob"
Someone.FavoriteColor = "Green"
Someone.ID = WebInfo.WebUserID.ToString()
Return Someone
End Function
The Web Client (set up to be send and receive JSON)
public Person Test(int UserID, string url) {
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url + "test.asmx/Test");
webRequest.Method = "POST";
webRequest.ContentType = "application/json; charset=utf-8";
StreamWriter sw = new StreamWriter(webRequest.GetRequestStream());
sw.Write("{'WebInfo':{'WebUserID':1}}"); // this works from JQuery
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Person));
Person someone = (Person)jsonSerializer.ReadObject(responseStream);
return someone;
}
Has anyone out there done this successfully?
Thanks
Here is a method that makes calls to a JSON web service, allowing the developer to both send and receive complext data types. The object passed in can be any data type or class. The result is a JSON string, and or any error message the methods type is shown below
public class WebServiceCallReturn {
public string JSONResponse { get; set; }
public string SimpleResponse { get; set; }
public string Error { get; set; }
}
public WebServiceCallReturn WebServiceJSONCall(string uri, string requestType, object postData = null) {
WebServiceCallReturn result = new WebServiceCallReturn();
// create request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.ContentType = "application/json; charset=utf-8";
webRequest.Method = requestType;
webRequest.Accept = "application/json; charset=utf-8";
// add json data object to send
if (requestType == "POST") {
string json = "{ }";
if (postData != null) {
try { // the serializer is fairly robust when used this way
DataContractJsonSerializer ser = new DataContractJsonSerializer(postData.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, postData);
json = Encoding.UTF8.GetString(ms.ToArray());
} catch {
result.Error = "Error serializing post";
}
}
webRequest.ContentLength = json.Length;
StreamWriter sw;
try {
sw = new StreamWriter(webRequest.GetRequestStream());
} catch (Exception ex) {
// the remote name could not be resolved
result.Error = ex.Message;
return result;
}
sw.Write(json);
sw.Close();
}
// read response
HttpWebResponse webResponse;
try {
webResponse = (HttpWebResponse)webRequest.GetResponse();
} catch (Exception ex) {
// The remote server returned an error...
// (400) Bad Request
// (403) Access forbidden (check the application pool)
// (404) Not Found
// (405) Method not allowed
// (415) ...not the expected type
// (500) Internal Server Error (problem with IIS or unhandled error in web service)
result.Error = ex.Message;
return result;
}
Stream responseStream = webResponse.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
string resultString = sr.ReadToEnd();
sr.Close();
responseStream.Close();
result.JSONResponse = resultString;
return result;
}
This method could be used as follows
public SomeCustomDataClass Getsomeinformation(int userID) {
UserInfoClass postData = new UserInfoClass();
postData.WebUserID = userID;
SomeCustomDataClass result = new SomeCustomDataClass();
string uri = URL + "SomeServices.svc/GetSomething";
WebServiceCallReturn webReturn = WebServiceJSONCall(uri, "POST", postData);
if (webReturn.Error == null) {
//resultString = CleanJSON(resultString);
JavaScriptSerializer serializer = new JavaScriptSerializer();
try {
result = serializer.Deserialize<SomeCustomDataClass>(webReturn.JSONResponse);
} catch {
result.Error = "Error deserializing";
}
} else {
result.Error = webReturn.Error;
}
return result;
}
Hope that helps someone