If I run my program and strUploadIP doens't exits in my network my whole application is stuck
FileInfo toUpload = new FileInfo(strFile);
FtpWebRequest req = (FtpWebRequest)WebRequest.Create(#"ftp://" + **strUploadIP** + #"/" + strUser);
req.Method = WebRequestMethods.Ftp.MakeDirectory;
req.Credentials = new NetworkCredential(strUusername, strUpassword);
try
{
using (var resp = (FtpWebResponse)req.GetResponse())
{
Console.WriteLine(resp.StatusCode);
}
}
how can I get to try catch this or something?
You should add a try/catch to handle any errors.
FtpWebRequest req = (FtpWebRequest)WebRequest.Create(#"ftp://" + **strUploadIP** + #"/" + strUser);
req.Method = WebRequestMethods.Ftp.MakeDirectory;
req.Credentials = new NetworkCredential(strUusername, strUpassword);
try {
using (var resp = (FtpWebResponse)req.GetResponse()) {
Console.WriteLine(resp.StatusCode);
}
} catch {
// TODO: Handle exception
}
Related
---------SSIS Script task Failing---------
I have this method in SSIS Script task which calls a web services but in response, I am getting The remote server returned an error: (500) Internal Server Error.
There is nothing else in the stack trace. When I use the same XML request in a Soap UI I get a valid response. In Soap UI I use Basic Authentication.
Can anyone help me out here. What could be the issue here?
public void GetWebServiceData(DataRow row)
{
FileInfo MyFileinfo = new FileInfo(configuration_file_location + "\\Test1\\Test.xml");
using (StreamReader myReader = MyFileinfo.OpenText())
{
myXmlMessage = myReader.ReadToEnd();
}
try
{
myXmlMessage = AddContractToXml(policyNumber, myXmlMessage);
int timeout = 1800000;
HttpWebRequest req = WebRequest.Create(new Uri(web_service_url))
as HttpWebRequest;
req.Method = "POST";
req.ContentType = "text/xml;charset=UTF-8";
byte[] formData = UTF8Encoding.UTF8.GetBytes(myXmlMessage.ToString());
req.ContentLength = formData.Length;
req.Timeout = timeout;
ICredentials credentials = new NetworkCredential(user_name, user_password);
WebProxy myProxy = new WebProxy(proxy_server, proxy_port);
req.Proxy = myProxy;
req.Proxy.Credentials = CredentialCache.DefaultCredentials;
req.Credentials = credentials;
using (Stream post = req.GetRequestStream())
{
post.Write(formData, 0, formData.Length);
}
using (HttpWebResponse resp = req.GetResponse()
as HttpWebResponse)
{
using (StreamReader reader =
new StreamReader(resp.GetResponseStream()))
{
XmlDocument myXmlDoc = new XmlDocument();
myXmlDoc.Load(reader);
XslCompiledTransform myXslTrans = new XslCompiledTransform();
/* loading XSLT */
myXslTrans.Load(configuration_file_location + "\\Test1\\TestMonitoring.xslt");
/* creating Output Stream */
XmlTextWriter myWriter = new XmlTextWriter(web_service_output_transform_location + policyNumber + ".xml", null);
/* XML transformation */
myXslTrans.Transform(myXmlDoc, null, myWriter);
myWriter.Close();
}
}
}
catch (WebException webExcp)
{
string exMessage = webExcp.Message;
if (webExcp.Response != null)
{
using (StreamReader responseReader = new StreamReader(webExcp.Response.GetResponseStream()))
{
exMessage = responseReader.ReadToEnd();
if (!Directory.Exists(log_location + DateTime.Now.ToString("ddMMyyyy")))
Directory.CreateDirectory(log_location + DateTime.Now.ToString("ddMMyyyy"));
FileStream file = new FileStream(log_location + "//" + DateTime.Now.ToString("ddMMyyyy") + "//" + policyNumber + ".xml", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(file);
writer.Write(exMessage);
writer.Close();
file.Close();
}
}
Dts.TaskResult = (int)ScriptResults.Failure;
return;
}
catch (Exception e)
{
Dts.TaskResult = (int)ScriptResults.Failure;
return;
}
finally
{
}
}
I have an issue sending big file to an FTP site and I would like to check the file size after the transfer (sometimes it works sometimes it fails). The transfer is within an SSIS and I'm using Dts.Connections in C#.
My code:
public long TransferFile(string file)
{
long filesize = 0L;
try
{
string[] newfile = new[] { file };
ConnectionManager ftpCM = Dts.Connections["ftp_server"];
string remoteDir = Dts.Variables["FtpWorkingDirectory"].Value.ToString();
FtpClientConnection ftpClient = new FtpClientConnection(ftpCM.AcquireConnection(null));
ftpClient.UsePassiveMode = true;
ftpClient.Connect();
ftpClient.Retries = 10;
ftpClient.SetWorkingDirectory(remoteDir);
ftpClient.SendFiles(newfile, remoteDir, true, false);
ftpClient.Close();
}
catch (Exception ex)
{
throw ex;
}
return filesize;
}
I found examples using FtpWebRequest but I don't have the ftp uri available so I don't see how to use this method. How can I get this file size?
UPDATE:
Adding this:
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpCM.ConnectionString + remoteDir + "/" + file));
request.Proxy = null;
DtsProperty ServerUsername = ftpCM.Properties["ServerUserName"];
DtsProperty ServerPassword = ftpCM.Properties["ServerPassword"];
request.Credentials = new NetworkCredential(ServerUsername.GetValue(ftpCM).ToString(), ServerPassword.GetValue(ftpCM).ToString());
request.Method = WebRequestMethods.Ftp.GetFileSize;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
filesize = response.ContentLength;
response.Close();
I get error: The property ServerPassword is write-only.
The final solution was to store the username and password in Variables instead of connection parameters.
And with the following code:
public long TransferFile(string file)
{
long filesize = 0L;
try
{
string[] newfile = new[] { file };
ConnectionManager ftpCM = Dts.Connections["ftp_server"];
string remoteDir = Dts.Variables["FtpWorkingDirectory"].Value.ToString();
string ServerUsername = Dts.Variables["ServerUsername"].Value.ToString();
string ServerPassword = Dts.Variables["ServerPassword"].Value.ToString();
FtpClientConnection ftpClient = new FtpClientConnection(ftpCM.AcquireConnection(null));
ftpClient.UsePassiveMode = true;
ftpClient.ServerUserName = ServerUsername;
ftpClient.ServerPassword = ServerPassword;
ftpClient.Connect();
ftpClient.Retries = 10;
ftpClient.SetWorkingDirectory(remoteDir);
ftpClient.SendFiles(newfile, remoteDir, true, false);
ftpClient.Close();
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpCM.ConnectionString + remoteDir + "/" + Path.GetFileName(file)));
request.Proxy = null;
request.Credentials = new NetworkCredential(ServerUsername, ServerPassword);
request.Method = WebRequestMethods.Ftp.GetFileSize;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
filesize = response.ContentLength;
response.Close();
}
catch (Exception ex)
{
throw ex;
}
return filesize;
}
I've integrated an option for users to pay via PayPal their online shopping on the web shop that I'm creating. The problem came up suddenly when I started to get this error:
You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
And the code for the Http call is as following:
public string HttpCall(string NvpRequest)
{
string url = pEndPointURL;
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost.ToString());
}
}
catch (Exception e)
{
}
//Retrieve the Response returned from the NVP API call to PayPal.
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse(); // this is the line where the exception occurs...
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
return result;
}
Can someone help me out with this? It worked fine a day ago, now its giving me this error?
Okay so if anyone is interested, I was able to fix the error by adding the following line before creating the web request (I was able to fix it by going down to Tls12 like this):
`ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12`;
Cheers :-)
Edit try this:
public string HttpCall(string NvpRequest)
{
string url = pEndPointURL;
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
// Try using Tls11 if it doesnt works for you with Tls
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = WebRequestMethods.Http.Post;
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost.ToString());
}
}
catch (Exception e)
{
}
//Retrieve the Response returned from the NVP API call to PayPal.
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
return result;
}
public string HttpCall(string NvpRequest) //CallNvpServer
{
string url = pendpointurl;
//To Add the credentials from the profile
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode( BNCode );
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost);
}
}
catch (Exception e)
{
/*
if (log.IsFatalEnabled)
{
log.Fatal(e.Message, this);
}*/
}
//Retrieve the Response returned from the NVP API call to PayPal
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
//Logging the response of the transaction
/* if (log.IsInfoEnabled)
{
log.Info("Result :" +
" Elapsed Time : " + (DateTime.Now - startDate).Milliseconds + " ms" +
result);
}
*/
return result;
}
After a number of hours wasted, it turned out to be the Tls protocol version.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
WebClient client = new WebClient();
string postData = "client_id=" + "b408123adf1e3a950876d84475587ca2"
+ "&client_secret=" + "d74a342169f5f5b369622d582f77b09e"
+ "&grant_type=password&username=" + "biksad" //your username
+ "&password=" + "369789";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://soundcloud.com/biksad/tracks") as HttpWebRequest;
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(filePath, "#" + fileName, "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "biksad");
form.Add("track[sharing]", "public");
form.Add("oauth_token", tokenInfo);
form.Add("format", "json");
form.Add("Filename", fileName);
form.Add("Upload", "Submit Query");
string lblInfo;
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
lblInfo = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
lblInfo = ex.ToString();
}
I want to upload an audio file from my server to my soundcloud account. I got this error:
Cannot close stream until all bytes are written.
How can I detect "form" values correctly(track[title],track[sharing]...etc.)?
this link will show you what all the fields on that POST mean
http://developers.soundcloud.com/docs/api/reference#tracks
you can also use this tool they provide to look at what the URL should contain:
http://developers.soundcloud.com/console
the problem is the httpwebrequest method in my c# program. visual studio gives it a metric of 60, thats pretty lame.. so how can i program it more efficient? (:
my actual code:
public string httpRequest(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Proxy = WebRequest.DefaultWebProxy;
request.MediaType = "HTTP/1.1";
request.ContentType = "text/xml";
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using(StreamReader streamr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
String sresp = streamr.ReadToEnd();
return sresp;
}
thanks for helping. ;)
Well, firstly I wouldnt let a number rule my code :)
However, using WebClient may simplify things quite a bit - less code to be counted. I'm not at a PC but that looks like a single DownloadString call, plus a few request headers.
http://msdn.microsoft.com/en-us/library/fhd1f0sw(v=VS.100).aspx
Oh, and add some using statements around all the IDisposable objects you create.
Here's the code I use in a social networking class I built which interacts with Twitter, Facebook, Tumblr, etc. Modify as you see fit. Also, I don't know what "metric" it would be given by VS, but if you're referring to the "Calculate Code Metrics" a 60 is still good. 20 to 100 is considered to be well maintainable, so I wouldn't worry too much.
protected string Request(
string Method,
Uri Endpoint,
string[][] Headers,
string Params) {
try {
ServicePointManager.Expect100Continue = false;
HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(Endpoint);
Request.Method = Method;
if (Method == "POST") {
Request.ContentLength = Params.Length;
Request.ContentType = "application/x-www-form-urlencoded";
};
for (byte a = 0, b = (byte)Headers.Length; a < b; a++) {
Request.Headers.Add(Headers[a][0], Headers[a][1]);
};
if (!String.IsNullOrWhiteSpace(Params)) {
using (StreamWriter Writer = new StreamWriter(Request.GetRequestStream())) {
Writer.Write(Params);
};
};
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
Request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointDelegate);
using (StreamReader Reader = new StreamReader(Response.GetResponseStream())) {
string R = Reader.ReadToEnd();
try {
Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Headers[0][1] + "</p><p>" + Params + "</p><p>" + R + "</p>");
} catch (Exception) {
Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Params + "</p><p>" + R + "</p>");
};
return (R);
};
} catch (WebException Ex) {
try {
if (Ex.Status != WebExceptionStatus.Success) {
using (StreamReader Reader = new StreamReader(Ex.Response.GetResponseStream())) {
string R = Reader.ReadToEnd();
try {
Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Headers[0][1] + "</p><p>" + Params + "</p><p>" + R + "</p>");
} catch (Exception) {
Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Params + "</p><p>" + R + "</p>");
};
return (R);
};
};
} catch (Exception) {
// Ignore
};
return (string.Empty);
} catch (Exception) {
return (string.Empty);
};
}
private IPEndPoint BindIPEndPointDelegate(
ServicePoint ServicePoint,
IPEndPoint RemoteEndPoint,
int Retries) {
if (String.IsNullOrWhiteSpace(this.IPEndpoint)) {
return new IPEndPoint(IPAddress.Any, 5000);
} else {
return new IPEndPoint(IPAddress.Parse(this.IPEndpoint), 5000);
};
}