I am having the following code to Save message to Exchange WEBDAV Drafts folder. IT saves the message but If open it in Outlook, Send button is Disabled and the message is readonly. Please help me find what am i missing in this code...
thanks
Bhuvan
strBody = "To: " + strTo + "\n" +
"Subject: " + (string.IsNullOrEmpty(message.Subject) ? "" : message.Subject) + "\n" +
"Date: " + System.DateTime.Now + "\n" +
"X-Mailer: test mailer" + "\n" +
"MIME-Version: 1.0" + "\n" +
"Content-Type: text/html;" + "\n" +
"Charset = \"iso-8859-1\"" + "\n" +
"Content-Transfer-Encoding: 8bit" + "\n" +
"\n" + (string.IsNullOrEmpty(message.HtmlBody) ? "" : message.HtmlBody.Replace("<head />","").Replace("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">",""));
// Create the HttpWebRequest object.
PUTRequest = (System.Net.HttpWebRequest)HttpWebRequest.Create(tgtUri);
// Add the network credentials to the request.
// Use default credentials of the service to access the server.
PUTRequest.Credentials = cred;
// Specify the PUT method.
PUTRequest.Method = "PUT"; //PROPPATCH
// Encode the body using UTF-8.
byte[] bytes = Encoding.UTF8.GetBytes((string)strBody);
// Set the content header length. This must be
// done before writing data to the request stream.
PUTRequest.ContentLength = bytes.Length;
// Get a reference to the request stream.
PUTRequestStream = PUTRequest.GetRequestStream();
// Write the message body to the request stream.
PUTRequestStream.Write(bytes, 0, bytes.Length);
// Close the Stream object to release the connection
// for further use.
PUTRequestStream.Close();
// Set the Content-Type header to the RFC 822 message format.
PUTRequest.ContentType = "message/rfc822";
// PUT the message in the Drafts folder of the
// sender's mailbox.
PUTResponse = (System.Net.HttpWebResponse)PUTRequest.GetResponse();
if (message.Attachments != null)
{
//Do the PROPPATCH
System.Net.HttpWebRequest PROPPATCHRequest;
System.Net.WebResponse PROPPATCHResponse;
System.IO.Stream PROPPATCHRequestStream = null;
string strxml = "<?xml version='1.0'?>" +
"<d:propertyupdate xmlns:d='DAV:'>" +
"<d:set>" +
"<d:prop>" +
"<isCollection xmlns='DAV:'>False</isCollection>" +
"</d:prop>" +
"</d:set>"
+ "<g:remove>"
+ "<g:prop><m:date/></g:prop>"
+ "</g:remove>"
+ "</d:propertyupdate>";
PROPPATCHRequest = (System.Net.HttpWebRequest)HttpWebRequest.Create(tgtUri);
PROPPATCHRequest.Credentials = cred;
PROPPATCHRequest.Headers.Set("Translate", "f");
PROPPATCHRequest.ContentType = "text/xml";
PROPPATCHRequest.ContentLength = strxml.Length;
PROPPATCHRequest.Method = "PROPPATCH";
byte[] PROPPATCHbytes = Encoding.UTF8.GetBytes(strxml);
PROPPATCHRequest.ContentLength = PROPPATCHbytes.Length;
PROPPATCHRequestStream = PROPPATCHRequest.GetRequestStream();
PROPPATCHRequestStream.Write(PROPPATCHbytes, 0, PROPPATCHbytes.Length);
PROPPATCHRequestStream.Close();
PROPPATCHResponse = (System.Net.HttpWebResponse)PROPPATCHRequest.GetResponse();
foreach (KeyValuePair<string, byte[]> attachment in message.Attachments)
{
System.IO.Stream PUTAttachRequestStream = null;
System.Net.HttpWebRequest PUTAttachRequest;
System.Net.WebResponse PUTAttachResponse;
//Attach File: This could be put in a loop to attach more than one file.
string FileName = attachment.Key; //#"2842498_794802035296_Label1.pdf";
string attachURI = tgtUri + "/" + FileName;
PUTAttachRequest = (System.Net.HttpWebRequest)HttpWebRequest.Create(attachURI);
PUTAttachRequest.Credentials = cred;
PUTAttachRequest.Method = "PUT";
PUTAttachRequest.ContentLength = attachment.Value.Length; //binaryData.Length;
PUTAttachRequestStream = PUTAttachRequest.GetRequestStream();
PUTAttachRequestStream.Write(attachment.Value, 0, attachment.Value.Length); //(binaryData, 0, binaryData.Length);
PUTAttachRequestStream.Close();
PUTAttachResponse = (System.Net.HttpWebResponse)PUTAttachRequest.GetResponse();
PUTAttachResponse.Close();
}
PROPPATCHResponse.Close();
}
// Clean up.
PUTResponse.Close();
I found the answer in Akash's blog on msdn. One has to carefully read this to get the actual answer, but the solution worked.
Related
I want to send json request from c# to php file and save data into text file but php file can not read data
this is my code
User user = new User { id = 1, name = "Bob", address = "password", phone = "0111111111", activation = true };
string json = "{\"id\":" + "\"" + user.id + "\""
+ ",\"name\":" + "\"" + user.name + "\""
+ ",\"address\":" + "\"" + user.address + "\""
+ ",\"activation\":" + "\"" + user.activation + "\"}";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:8080/test.php");
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = json.Length;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Close();
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
and php file id
<?php
$data = json_decode(file_get_contents('php://input'), true);
$file = "LogFile.txt";
$handle = fopen($file, 'a') or die('ERROR: Cannot write to file: ' . $file);
date_default_timezone_set('Europe/Amsterdam');
fwrite($handle, $data);
fclose($handle);
echo "SUCCESS";
?>
please what must i do in php file to read right? thank you
This minimal piece of code was all I needed to solve my own problem:
$_data = json_decode(file_get_contents('php://input'), true);
if (isset($_data)) {
$file = "users.txt";
file_put_contents($file, json_encode($_data));
}
I made a web service that can send push notification depending on this tutorial. When i call the function from a web form, it works perfectly. However, when i call the same function from phone i don't receive the notification at all although the response is "Received | Active | Connected". The function is like this :
[WebMethod]
public void SendNotification(string Title, string msg, string url)
{
try
{
string subscriptionUri = GetNotificationUrl();
HttpWebRequest sendNotificationRequest = (HttpWebRequest) WebRequest.Create(subscriptionUri);
sendNotificationRequest.Method = "POST";
string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>" + Title + "</wp:Text1>" +
"<wp:Text2>" + msg + "</wp:Text2>" +
"<wp:Param>" + url + "</wp:Param>" +
"</wp:Toast></wp:Notification>";
byte[] notificationMessage = Encoding.Default.GetBytes(toastMessage);
// Set the web request content length.
sendNotificationRequest.ContentLength = notificationMessage.Length;
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
using (Stream requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
// Send the notification and get the response.
HttpWebResponse response = (HttpWebResponse) sendNotificationRequest.GetResponse();
string notificationStatus = response.Headers["X-NotificationStatus"];
string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
WriteLog(notificationStatus + " | " + notificationChannelStatus + " | " +
deviceConnectionStatus);
}
catch
{
}
}
I am trying to upload an image to a web service via POST.
The API documentation says "to upload files via POST, encoded as "multipart/form-data" and include a POST arg named "image" with the image data. Images must be of type PNG, JPG, or GIF."
This is my code:
Bitmap myImage = new Bitmap("myImage.jpg");
byte[] myFileData = (byte[])(new ImageConverter()).ConvertTo(myImage, typeof(byte[]));
string myBoundary = "------------------------" + DateTime.Now.Ticks;
var newLine = Environment.NewLine;
string myContent =
"--" + myBoundary + newLine +
"content-disposition: form-data; name=\"image\"; filename=\"myImage.jpg\"" + newLine +
"Content-Type: image/jpeg" + newLine +
"Content-Transfer-Encoding: binary" + newLine +
newLine +
Encoding.Default.GetString(myFileData) + newLine +
"--" + myBoundary + "--";
try {
using (var httpClient = new HttpClient())
using (var content = new StringContent(myContent, Encoding.Default, "multipart/form-data, boundary=" + myBoundary))
using (var response = await httpClient.PostAsync("http://my_API_URL", content)) {
string responseData = await response.Content.ReadAsStringAsync();
}
}
catch (Exception myExp) { }
This code raises an exception trying to create the StringContent object.
I am ok for any suggestions. The API that I need to use requires Authentication, which typically is solved using a WebClient and this statement:
client.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("my_API_key:"));
I am OK with using any other form of POST, like WebClient or HttpClient.
Code that finally worked, in case anyone is looking for the same answer:
Bitmap myImage = new Bitmap("myImage.jpg");
byte[] myFileData = (byte[])(new ImageConverter()).ConvertTo(myImage, typeof(byte[]));
string myBoundary = "---------------------------7df3c13714f0ffc";
var newLine = Environment.NewLine;
string myContent =
"--" + myBoundary + newLine +
"Content-Disposition: form-data; name=\"image\"; filename=\"myImage.jpg\"" + newLine +
"Content-Type: image/jpeg" + newLine +
newLine +
Encoding.Default.GetString(myFileData) + newLine +
"--" + myBoundary + "--";
using (var client = new WebClient()) {
try {
client.Headers["Authorization"] = "Basic xxxxxx";
client.Headers["Content-Type"] = "multipart/form-data; boundary=" + myBoundary;
client.UploadString(new Uri(myURL), "POST", myContent);
totalAPICalls++;
}
catch { }
}
Out of no where, my twitter API calls, specificly my first step in the 3-legged auth, stopped working. I've compared the timestamps, keys and everything with the OAuth signature generator tool, and they all match (execpt oauth_nonce but thats the point I guess). Here is my code. Any suggestions or small observations would be appreciated.
protected void RequestToken()
{
string oauthcallback = Request.Url.Host + "/TwitterCallback.aspx";
string oauthconsumerkey = "xxx-consumerkey";
string oauthconsumersecret = "xxx-consumerSecret";
string oauthtokensecret = string.Empty;
string oauthtoken = string.Empty;
string oauthsignaturemethod = "HMAC-SHA1";
string oauthversion = "1.0";
string oauthnonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
string oauthtimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
string url = "https://api.twitter.com/oauth/request_token?oauth_callback=" + oauthcallback;
SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
basestringParameters.Add("oauth_version", oauthversion);
basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
basestringParameters.Add("oauth_nonce", oauthnonce);
basestringParameters.Add("oauth_signature_method", oauthsignaturemethod);
basestringParameters.Add("oauth_timestamp", oauthtimestamp);
basestringParameters.Add("oauth_callback", Uri.EscapeDataString(oauthcallback));
//Build the signature string
string baseString = String.Empty;
baseString += "POST" + "&";
baseString += Uri.EscapeDataString(url.Split('?')[0]) + "&";
foreach (KeyValuePair<string, string> entry in basestringParameters)
{
baseString += Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&");
}
//Remove the trailing ambersand char last 3 chars - %26
//baseString = baseString.Substring(0, baseString.Length - 3);
//Build the signing key
string signingKey = Uri.EscapeDataString(oauthconsumersecret) +
"&" + Uri.EscapeDataString(oauthtokensecret);
//Sign the request
HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
string oauthsignature = Convert.ToBase64String(
hasher.ComputeHash(new ASCIIEncoding().GetBytes(baseString)));
//Tell Twitter we don't do the 100 continue thing
ServicePointManager.Expect100Continue = false;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(#url);
string authorizationHeaderParams = String.Empty;
authorizationHeaderParams += "OAuth ";
authorizationHeaderParams += "oauth_nonce=" + "\"" +
Uri.EscapeDataString(oauthnonce) + "\",";
authorizationHeaderParams += "oauth_signature_method=" + "\"" +
Uri.EscapeDataString(oauthsignaturemethod) + "\",";
authorizationHeaderParams += "oauth_timestamp=" + "\"" +
Uri.EscapeDataString(oauthtimestamp) + "\",";
authorizationHeaderParams += "oauth_consumer_key=" + "\"" +
Uri.EscapeDataString(oauthconsumerkey) + "\",";
authorizationHeaderParams += "oauth_signature=" + "\"" +
Uri.EscapeDataString(oauthsignature) + "\",";
authorizationHeaderParams += "oauth_version=" + "\"" +
Uri.EscapeDataString(oauthversion) + "\"";
webRequest.Headers.Add("Authorization", authorizationHeaderParams);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
//Allow us a reasonable timeout in case Twitter's busy
webRequest.Timeout = 3 * 60 * 1000;
try
{
HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
Stream dataStream = webResponse.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
var uri = new Uri("https://test.dk?" + responseFromServer);
var token = HttpUtility.ParseQueryString(uri.Query).Get("oauth_token"); ;
var tokensecret = HttpUtility.ParseQueryString(uri.Query).Get("oauth_token_secret");
Response.Write(responseFromServer);
Response.Redirect("https://api.twitter.com/oauth/authorize?force_login=true&oauth_token=" + token);
}
catch (Exception ex)
{
Response.Write(ex.GetBaseException());
}
}
The error obviously happens when I do the HTTP request webRequest.GetResponse()
It returns a 401 unauthorized
Apperently you have to include the oauth version number in the URL now, or else it will fall back to the oldest version (or maybe the newest, can't remember).
Providing /oath/1.0/ or /1.0/oauth/ or what ever solved my issue as i recall it (it's been a while).
I get this error "The remote server returned an error: (530) Not logged in." while uploading the file using FtpWebRequest.
Error occurs only when I transfer the files to path having subfolders, otherwise it perfectly works fine.
Uploading large files about 5 to 10 MB, it gets timed out.
void FtpTransfer(string siteName, string portNumber, string ftpUser, string ftpPassword, string destPath)
{
FtpWebRequest request;
DateTime now = DateTime.Now;
string now_string =
(now.Year).ToString()
+ "_" +
(now.Month).ToString("0#")
+ "_" +
(now.Day).ToString("0#");
foreach (object item in listBox1.Items)
{
string srcFile = item.ToString();
lblSource.Text = srcFile;
Uri uri = new Uri(srcFile);
string destFile = srcFile.Replace(lblPath.Text, "").Replace("\\\\", "\\").Replace("\\", "/").Replace("www/","");
Configuration oConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
int timeout = int.Parse(oConfig.AppSettings.Settings["TimeOut"].Value);
if (siteName == "mysite1.co.in" || siteName == "sd1.mysite2.net")
destFile = "ftp://" + siteName + ":" + portNumber + "/" + siteName + "/_test" + destFile; //error here
else
destFile = "ftp://" + siteName + ":" + portNumber + "/" + siteName + destFile; //no error
lblDestn.Text = destFile;
request = (FtpWebRequest)WebRequest.Create(destFile);
request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
request.Timeout = 6000;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true;
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(#srcFile);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
string path = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
System.IO.StreamWriter w = System.IO.File.AppendText(path + "\\log_" + now_string + ".txt");
w.WriteLine(DateTime.Now.ToString("yyy-MM-dd HH:mm:ss")
+ " "
+ srcFile
+ " "
+ destFile
+ " "
+ response.StatusDescription);
w.Close();
response.Close();
}
I am assuming that you have already attempted to do the same operation through a standard FTP client. If not, try that. I would then use Wireshark to make sure that is the response coming from the server and verify that the credentails are being sent. After that is verified, check with the FTP owner and make sure the server is configured appropriately.
I do not exactly know the solution for your problem. but some suggestions:
Use using(...) on IDisposable classes when ever possible. This promotes proper resource releasing and cleanup when you are finished with it. MSDN: Using
You use a timeout of 6000 miliseconds, may you should increase it for huge files or use your local variable timeout (read from you app settings).
Improved code with using:
private void FtpTransfer(string siteName, string portNumber, string ftpUser, string ftpPassword, string destPath)
{
DateTime now = DateTime.Now;
string now_string =
(now.Year).ToString()
+ "_" +
(now.Month).ToString("0#")
+ "_" +
(now.Day).ToString("0#");
foreach (object item in listBox1.Items)
{
string srcFile = item.ToString();
lblSource.Text = srcFile;
Uri uri = new Uri(srcFile);
string destFile = srcFile.Replace(lblPath.Text, "").Replace("\\\\", "\\").Replace("\\", "/").Replace("www/", "");
Configuration oConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
int timeout = int.Parse(oConfig.AppSettings.Settings["TimeOut"].Value);
if (siteName == "mysite1.co.in" || siteName == "sd1.mysite2.net")
destFile = "ftp://" + siteName + ":" + portNumber + "/" + siteName + "/_test" + destFile; //error here
else
destFile = "ftp://" + siteName + ":" + portNumber + "/" + siteName + destFile; //no error
lblDestn.Text = destFile;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(destFile);
request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
request.Timeout = 6000;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true;
// Copy the contents of the file to the request stream.
byte[] fileContents;
using (StreamReader sourceStream = new StreamReader(#srcFile))
{
fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
}
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
string path = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
System.IO.StreamWriter w = System.IO.File.AppendText(path + "\\log_" + now_string + ".txt");
w.WriteLine(DateTime.Now.ToString("yyy-MM-dd HH:mm:ss")
+ " "
+ srcFile
+ " "
+ destFile
+ " "
+ response.StatusDescription);
}
}
}