Twitter POST problems using api 1.1 - c#

We've just changed to Twitter api 1.1, and now Tweeting doesn't work & returns an error "The remote server returned an error: (400) Bad Request." Researching on SO about this suggests that it's something to do with authentication, but we are sending the accessToken & secret which we've just got from the login page. It all worked fine with api 1.0. The code is -
public void Tweet(Action<string> response, string message)
{
StringBuilder sb = new StringBuilder();
sb.Append("POST&");
sb.Append(Uri.EscapeDataString(_postUrl));
sb.Append("&");
string oauthNonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
string timeStamp = MakeTimestamp();
var dict = new SortedDictionary<string, string>
{
{ "oauth_consumer_key", _oAuthConfig.ConsumerKey },
{ "oauth_nonce", oauthNonce },
{ "oauth_signature_method", "HMAC-SHA1" },
{ "oauth_timestamp", timeStamp },
{ "oauth_token", _accessToken },
{ "oauth_version", "1.0" },
};
foreach (var keyValuePair in dict)
{
sb.Append(Uri.EscapeDataString(string.Format("{0}={1}&", keyValuePair.Key, keyValuePair.Value)));
}
string encodedMessage = EscapeAdditionalChars(Uri.EscapeDataString(message));
sb.Append(Uri.EscapeDataString("status=" + encodedMessage));
string signatureBaseString = sb.ToString();
// create the signature
string signatureKey = Uri.EscapeDataString(_oAuthConfig.ConsumerSecret) + "&" + Uri.EscapeDataString(_accessTokenSecret);
var hmacsha1 = new HMACSHA1(new ASCIIEncoding().GetBytes(signatureKey));
string signatureString = Convert.ToBase64String(hmacsha1.ComputeHash(new ASCIIEncoding().GetBytes(signatureBaseString)));
// create the headers
string authorizationHeaderParams = String.Empty;
authorizationHeaderParams += "OAuth ";
authorizationHeaderParams += "oauth_consumer_key=\"" + _oAuthConfig.ConsumerKey + "\", ";
authorizationHeaderParams += "oauth_nonce=\"" + oauthNonce + "\", ";
authorizationHeaderParams += "oauth_signature=\"" + Uri.EscapeDataString(signatureString) + "\", ";
authorizationHeaderParams += "oauth_signature_method=\"" + "HMAC-SHA1" + "\", ";
authorizationHeaderParams += "oauth_timestamp=\"" + timeStamp + "\", ";
authorizationHeaderParams += "oauth_token=\"" + _accessToken + "\", ";
authorizationHeaderParams += "oauth_version=\"" + "1.0" + "\"";
string messageToPost = EscapeAdditionalChars(SpacesToPlusSigns(message));
// initialise the WebClient
WebClient client = new WebClient();
client.Headers [HttpRequestHeader.Authorization] = authorizationHeaderParams;
client.UploadDataCompleted += (s, eArgs) =>
{
if (eArgs.Error == null)
response(DefaultSuccessMessage());
else
response(eArgs.Error.Message);
};
try
{
Uri uri = new Uri(_postUrl);
try
{
client.UploadDataAsync(uri, "POST", Encoding.UTF8.GetBytes("status=" + messageToPost));
}
catch (WebException e)
{
Log.Info("TwitterService->Tweet web error: " + e.Message);
response(DefaultErrorMessage());
}
catch (Exception e)
{
// Can happen if we had already favorited this status
Log.Info("TwitterService->Tweet error: " + e.Message);
response(DefaultErrorMessage());
}
}
catch (WebException e)
{
Log.Info("TwitterService->Tweet web error 2: " + e.Message);
response(DefaultErrorMessage());
}
catch (Exception e)
{
Log.Info("TwitterService->Tweet error 2: " + e.Message);
response(DefaultErrorMessage());
}
}
Basically, I'd like to be able to Tweet without using any 3rd party libraries such as Twitterizer (even TweetStation seems to be broken with api 1.1) - surely it can't be that difficult!
Any help much appreciated, as it feels a bit like a brick wall at the moment - I'm also fairly new to c#, which doesn't help...
Edited to show code which wasn't clear previously.

Finally found the solution, as usual with most of these things, it was pretty simple. Code below -
public void Tweet(Action<string> response, string message)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat ("status={0}", PercentEncode(message));
string content = sb.ToString();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_postUrl);
request.Headers.Add("Authorization", AuthorizeRequest(_accessToken, _accessTokenSecret, "POST", new Uri(_postUrl), content));
request.ContentType = "application/x-www-form-urlencoded";
request.ServicePoint.Expect100Continue = false;
request.Method = "POST";
try
{
try
{
using (Stream stream = request.GetRequestStream())
{
Byte[] streamContent = Encoding.UTF8.GetBytes("status=" + PercentEncode(message));
stream.Write(streamContent, 0, streamContent.Length);
}
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
string contents = "";
using (Stream stream = webResponse.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
contents = reader.ReadToEnd();
}
Console.WriteLine("Twitter response: " + contents);
response(DefaultSuccessMessage());
}
catch (WebException e)
{
Log.Info("TwitterService->Tweet web error: " + e.Message);
response(DefaultErrorMessage());
}
catch (Exception e)
{
// Can happen if we had already favorited this status
Log.Info("TwitterService->Tweet error: " + e.Message);
response(DefaultErrorMessage());
}
}
catch (WebException e)
{
Log.Info("TwitterService->Tweet web error 2: " + e.Message);
response(DefaultErrorMessage());
}
catch (Exception e)
{
Log.Info("TwitterService->Tweet error 2: " + e.Message);
response(DefaultErrorMessage());
}
}
private string AuthorizeRequest(string oauthToken, string oauthTokenSecret, string method, Uri uri, string data)
{
string oauthNonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var headers = new Dictionary<string, string>()
{
{ "oauth_consumer_key", _oAuthConfig.ConsumerKey },
{ "oauth_nonce", oauthNonce },
{ "oauth_signature_method", "HMAC-SHA1" },
{ "oauth_timestamp", MakeTimestamp() },
{ "oauth_token", oauthToken },
{ "oauth_verifier", PercentEncode(_authorizationVerifier) },
{ "oauth_version", "1.0A" }
};
var signatureHeaders = new Dictionary<string,string>(headers);
// Add the data and URL query string to the copy of the headers for computing the signature
if (data != null && data != "")
{
var parsed = HttpUtility.ParseQueryString(data);
foreach (string k in parsed.Keys)
{
signatureHeaders.Add(k, PercentEncode(parsed [k]));
}
}
var nvc = HttpUtility.ParseQueryString(uri.Query);
foreach (string key in nvc)
{
if (key != null)
signatureHeaders.Add(key, PercentEncode(nvc [key]));
}
string signature = MakeSignature (method, uri.GetLeftPart(UriPartial.Path), signatureHeaders);
string compositeSigningKey = MakeSigningKey(_oAuthConfig.ConsumerSecret, oauthTokenSecret);
string oauth_signature = MakeOAuthSignature(compositeSigningKey, signature);
headers.Add ("oauth_signature", PercentEncode(oauth_signature));
return HeadersToOAuth(headers);
}
private static string PercentEncode (string s)
{
var sb = new StringBuilder ();
foreach (byte c in Encoding.UTF8.GetBytes (s))
{
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~')
sb.Append ((char) c);
else
{
sb.AppendFormat ("%{0:X2}", c);
}
}
return sb.ToString ();
}
private static string MakeTimestamp ()
{
return ((long) (DateTime.UtcNow - _unixBaseTime).TotalSeconds).ToString ();
}
private static string MakeSignature (string method, string base_uri, Dictionary<string,string> headers)
{
var items = from k in headers.Keys orderby k
select k + "%3D" + PercentEncode (headers [k]);
return method + "&" + PercentEncode (base_uri) + "&" +
string.Join ("%26", items.ToArray ());
}
private static string MakeSigningKey (string consumerSecret, string oauthTokenSecret)
{
return PercentEncode (consumerSecret) + "&" + (oauthTokenSecret != null ? PercentEncode (oauthTokenSecret) : "");
}
private static string MakeOAuthSignature (string compositeSigningKey, string signatureBase)
{
var sha1 = new HMACSHA1 (Encoding.UTF8.GetBytes (compositeSigningKey));
return Convert.ToBase64String (sha1.ComputeHash (Encoding.UTF8.GetBytes (signatureBase)));
}
private static string HeadersToOAuth (Dictionary<string,string> headers)
{
return "OAuth " + String.Join (",", (from x in headers.Keys select String.Format ("{0}=\"{1}\"", x, headers [x])).ToArray ());
}
With Twitter api 1.0, I used a WebClient to post, that doesn't work with api 1.1, and it seems that the reason for this is that you can't set the ContentType or the ServicePoint.Expect100Continue properties - without these set as I've set them, the request is sent back as (401) unauthorized. Nothing to do with encoding problems in the end.
Thanks to others for the various helper methods.

I had exactly the same problem:
This is exactly what you need to do here:
Authenticate and request a user's timeline with Twitter API 1.1 oAuth
I have created a project for this at : https://github.com/andyhutch77/oAuthTwitterTimeline
It also includes an MVC, Web app and console demo.

I ran into this problem, or at least one striking similiar (from my noob perspective), recently for an app I am building. What seemed to solve it for me (after looking at the tool at dev.twitter.com) was simply to get rid of the quotes around the parameter names, so that (in your case):
I notice that you do in fact not have quotes around your parameter names. However, it confuses me that you send authentication details twice (hence my wrongheaded post.) It works for me without doing this, and I googled it briefly and found: https://dev.twitter.com/discussions/12322#comment-27120, which confirms this can be a problem generating an Authetication Error.

400 means you are not authenticated. I recommend getting user context.
https://dev.twitter.com/docs/auth/oauth#user-context

Related

How to add a contact to Yahoo using Oauth-2 in Asp.Net C#

I've been wrestling with this for a while now and can't seem to find a solution. The closest I've come is PHP code for Oauth-1 by Joe Chung (https://github.com/joechung/oauth_yahoo), but I can't get my head wrapped around it.
I'm using Asp.Net, and this code is in the ContactController. I have no trouble Getting contacts from Yahoo. The problem is Adding a contact to a user's Yahoo address book. The program proceeds through the Yahoo login process, and there are no errors. But the contact is not saved. I hope someone can take a look at this and tell me what I'm missing.
Thanks.
private string AddYahooContact(string responseFromServer, string contactIdForYahoo)
{
// Some of this from http://www.yogihosting.com/implementing-yahoo-contact-reader-in-asp-net-and-csharp/
responseFromServer = responseFromServer.Substring(1, responseFromServer.Length - 2);
string accessToken = "", xoauthYahooGuid = "", refreshToken = "";
string[] splitByComma = responseFromServer.Split(',');
foreach (string value in splitByComma)
{
if (value.Contains("access_token"))
{
string[] accessTokenSplitByColon = value.Split(':');
accessToken = accessTokenSplitByColon[1].Replace('"'.ToString(), "");
}
else if (value.Contains("xoauth_yahoo_guid"))
{
string[] xoauthYahooGuidSplitByColon = value.Split(':');
xoauthYahooGuid = xoauthYahooGuidSplitByColon[1].Replace('"'.ToString(), "");
}
else if (value.Contains("refresh_token"))
{
string[] refreshTokenSplitByColon = value.Split(':');
refreshToken = refreshTokenSplitByColon[1].Replace('"'.ToString(), "");
}
}
// How to build contactUrl from https://developer.yahoo.com/social/rest_api_guide/contacts-resource.html#contacts-xml_request_put
// This is Yahoo's address to add a contact
string contactUrl = "https://social.yahooapis.com/v1/user/" + xoauthYahooGuid + "/contacts";
// Much of this from https://developer.yahoo.com/dotnet/howto-rest_cs.html
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(contactUrl);
webRequest.Method = "POST";
webRequest.Headers["Authorization"] = "Bearer " + accessToken;
webRequest.ContentType = "application/x-www-form-urlencoded"; // Tried "application/x-www-form-urlencoded & application/xml" & "text/xml".
// Create the data we want to send
string yahooContact = BuildYahooContact(contactIdForYahoo);
byte[] byteData = UTF8Encoding.UTF8.GetBytes(yahooContact);
webRequest.ContentLength = byteData.Length;
using (Stream postStream = webRequest.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
responseFromServer = "";
try
{
using (HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
responseFromServer = reader.ReadToEnd();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return yahooContact;
}
private string BuildYahooContact(string contactIdForYahoo)
{
Guid contactId = Guid.Parse(contactIdForYahoo);
Models.Contact contact = GetContactForId(contactId); // And find the contact
string firstName = "";
string lastName = "";
if (contact.FullName != null)
{
int index = contact.FullName.IndexOf(" ");
if (index > 0)
{
firstName = contact.FullName.Substring(0, index);
lastName = (contact.FullName.Substring(index + 1));
}
else
{
lastName = contact.FullName;
}
}
StringBuilder data = new StringBuilder();
data.Append("<contact>");
data.Append("<fields><type>name</type><value>");
data.Append("<givenName>" + firstName + "</givenName><middleName/>");
data.Append("<familyName>" + lastName + "</familyName>");
data.Append("<prefix/><suffix/><givenNameSound/><familyNameSound/>");
data.Append("</value></fields>");
data.Append("<fields><type>address</type>");
data.Append("<value><street>" + contact.Address + "</street>");
data.Append("<city>" + contact.City + "</city>");
data.Append("<stateOrProvince>" + contact.State + "</stateOrProvince>");
data.Append("<postalCode>" + contact.Zip + "</postalCode>");
data.Append("<country>United States</country>");
data.Append("<countryCode>US</countryCode>");
data.Append("</value></fields>");
data.Append("<fields><type>notes</type><value>" + contact.Note + "</value></fields>");
data.Append("<fields><type>link</type><value>" + contact.Website + "</value></fields>");
data.Append("<fields><type>email</type><value>" + contact.Email + "</value></fields>");
data.Append("<fields><type>phone</type><value>" + contact.BusinessPhone + "</value><flags>WORK</flags></fields>");
data.Append("<fields><type>phone</type><value>" + contact.BestPhone + "</value><flags>MOBILE</flags></fields>");
data.Append("<fields><type>phone</type><value>" + contact.SecondPhone + "</value><flags>PERSONAL</flags></fields>");
data.Append("<categories><category><name>GoGoContract</name></category></categories>");
data.Append("</contact>");
return data.ToString();
}

Read Credentials by txt file and try login c#?

I would create a loop for function and print message in catch for all logins failed and print "sucessful connected with...." for all good logins.
Now i tried with that code, but i get only one error in textbox of catch
Button1:
if (openFileDialog1.FileName != string.Empty)
{
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
int count = 0;
string lineoflistemail;
while ((lineoflistemail = reader.ReadLine()) != null)
{
UserData d = new UserData();
string[] parts = lineoflistemail.Split(':');
count = parts.Length;
d.UserName = parts[0].Trim();
d.Password = parts[1].Trim();
data.Add(d);
}
foreach(UserData ud in data)
{
textBox1.Text += ("LOL" + ud.UserName + ud.Password + Environment.NewLine);
}
Second button code:
if (data.Count() == 0)
{
MessageBox.Show("Load user info first");
return;
}
for( hola = 0; hola < data.Count(); hola++)
{
var url = #"https://mail.google.com/mail/feed/atom";
var encoded = TextToBase64(data[0].UserName + ":" + data[1].Password);
var myweb = HttpWebRequest.Create(url) as HttpWebRequest;
myweb.Method = "POST";
myweb.ContentLength = 0;
myweb.Headers.Add("Authorization", "Basic " + encoded);
var response = myweb.GetResponse();
var stream = response.GetResponseStream();
textBox1.Text += ("Connection established with");
MessageBox.Show(hola.ToString());
}
}
catch (Exception ex)
{
textBox1.Text += ("Error connection. Original error: " + ex.Message);
}
}
The problem is that your try...catch is outside of your for loop. The first exception will exit the for loop, append the message to textBox1, then exit the button handler.
If you want to keep looping through even if there is an error, move the try...catch inside of the loop. Here's an example:
for( hola = 0; hola < data.Count(); hola++)
{
var url = #"https://mail.google.com/mail/feed/atom";
var encoded = TextToBase64(data[0].UserName + ":" + data[1].Password);
var myweb = HttpWebRequest.Create(url) as HttpWebRequest;
myweb.Method = "POST";
myweb.ContentLength = 0;
myweb.Headers.Add("Authorization", "Basic " + encoded);
try
{
var response = myweb.GetResponse();
var stream = response.GetResponseStream();
textBox1.Text += ("Connection established with");
MessageBox.Show(hola.ToString());
}
catch (Exception ex)
{
textBox1.Text += ("Error connection. Original error: " + ex.Message);
}
}

How can I structure a try/catch with a variable definition

Writing in C# and I'm getting JSONReaderExceptions here:
var container = JsonConvert.DeserializeObject<HistoryResponseContainer> (responseData);
It's always something like a unterminated line or unrecognized character.
I know I need to catch and throw these errors, but it breaks if I try and define "container" inside a try/catch statement. Here's the whole method.
foreach (String StationID in StationIDList) {
string url = #"http://api.wunderground.com/api/" + wundergroundkey + "/history_" + Date + "/q/pws:" + StationID + ".json";
Uri uri = new Uri (url);
WebRequest webRequest = WebRequest.Create (uri);
WebResponse response = webRequest.GetResponse ();
StreamReader streamReader = new StreamReader (response.GetResponseStream ());
String responseData = streamReader.ReadToEnd ();
var container = JsonConvert.DeserializeObject<HistoryResponseContainer> (responseData);
foreach (var observation in container.history.observations) {
CurrentData.Write (StationID + " ");
// This makes easier access to the date. not perfect, but better.
DateTime date = observation.date.Value;
DateTime utc = observation.utcdate.Value;
// whatever you want to do with each observation
if (date.Minute == 0 || date.Minute % 5 == 0) {
CurrentData.Write (date.Hour + ":" + date.Minute + " " + observation.wdird + " " + observation.wspdi);
}//end if
CurrentData.Write ("\n");
} //End foreach observation
} //end foreach station
Put your second foreach loop inside try (because you're using your "container"). Otherwise it won't be defined if an exception is raised and you only "try/catch" your container instanciation:
foreach (String StationID in StationIDList)
{
string url = #"http://api.wunderground.com/api/" + wundergroundkey + "/history_" + Date + "/q/pws:" + StationID + ".json";
Uri uri = new Uri (url);
WebRequest webRequest = WebRequest.Create (uri);
WebResponse response = webRequest.GetResponse ();
StreamReader streamReader = new StreamReader (response.GetResponseStream ());
String responseData = streamReader.ReadToEnd ();
try
{
var container = JsonConvert.DeserializeObject<HistoryResponseContainer> (responseData);
foreach (var observation in container.history.observations)
{
CurrentData.Write (StationID + " ");
DateTime date = observation.date.Value;
DateTime utc = observation.utcdate.Value;
if (date.Minute == 0 || date.Minute % 5 == 0)
{
CurrentData.Write (date.Hour + ":" + date.Minute + " " + observation.wdird + " " + observation.wspdi);
}
CurrentData.Write ("\n");
}
}
catch(JsonReaderException ex)
{
// ...
}
}
I know I need to catch and throw these errors,
No you need just catch and handle these errors.
but it pukes if I try and define "container" inside a try/catch statement.
What do you mean here ? You need this:
try
{
// your code that throws exception
}
catch(JsonReaderException ex)
{
// handle your exception
}

ASPX get response headers back

I would appreciate some help because I am really new to C#. I need to return the response headers back, I need the 3 numbers of status code only actually. The code of the page for the web service is `
<%# Page Language="C#" ContentType="application/json;charset=utf-8"%>
<%# Import Namespace="System.Net" %>
<%# Import Namespace="System.IO" %>
<%# Import Namespace="System.Xml" %>
<%# Import Namespace="System.Web" %>
<%# Import Namespace="Newtonsoft.Json" %>
<%# Import Namespace="Newtonsoft.Json.Linq" %>
<%# Import Namespace="System.Collections.Generic" %>
<%# Import Namespace="log4net" %>
<script runat="server">
static readonly ILog m_Log = LogManager.GetLogger("getWebRequest");
String appUrlEncoded = "application/x-www-form-urlencoded";
String appJson = "application/json";
String textXml = "text/xml";
String appXml = "application/xml";
String textPlain = "text/plain";
/************************ fetchURL *******************/
String fetchURL(string url, string protocol, string enctype, string parameters,
string readWriteTimeout, string conTimeout,
string userName, string password, JObject CustomHeaders, JToken JsonContent)
{
m_Log.Debug("fetchURL(" + url + ", " + protocol + ", " + enctype + ", " + parameters + ", " +
readWriteTimeout + ", " + conTimeout + ", " + userName + ", " + password + ") in");
String result = "";
String method ="GET";
String loginCredentials = userName + ":" + password;
// Accepting self-signed certificates
ServicePointManager.ServerCertificateValidationCallback += delegate(
object
sender,
System.Security.Cryptography.X509Certificates.X509Certificate
pCertificate,
System.Security.Cryptography.X509Certificates.X509Chain pChain,
System.Net.Security.SslPolicyErrors pSSLPolicyErrors)
{
return true;
};
try
{
if (protocol.EndsWith("get") || protocol.EndsWith("delete"))
{
url = url + (String.IsNullOrEmpty(parameters) ? "" : ("?" + parameters));
}
method = protocol.ToUpper();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.ContentType = enctype;
request.Timeout = Int32.Parse(conTimeout);
request.ReadWriteTimeout = Int32.Parse(readWriteTimeout);
if (loginCredentials.Length>1)
{
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(loginCredentials)));
}
if (CustomHeaders != null)
{
//Custom HTTP headers
JEnumerable<JProperty> children = CustomHeaders.Children<JProperty>();
foreach (JProperty child in children)
{
string strKey = child.Name;
string strValue = "";
if (child == null || child.Value == null)
continue;
if (child.Value.Type.Equals(JsonTokenType.String))
{
strValue = (String)((JValue)child.Value).Value;
}
else
{
strValue = child.Value.ToString();
}
m_Log.Debug("request key: '" + strKey + "' -- value: '" + strValue + "'");
if (strKey.Trim().Equals("Accept"))
{
request.Accept = strValue;
}
else if (strKey.Trim().Equals("Connection"))
{
request.Connection = strValue;
}
else if (strKey.Trim().Equals("Content-Length"))
{
request.ContentLength = strValue.Length;
}
else if (strKey.Trim().Equals("Content-Type"))
{
request.ContentType = strValue;
}
else if (strKey.Trim().Equals("Expect"))
{
request.Expect = strValue;
}
else if (strKey.Trim().Equals("If-Modified-Since"))
{
request.IfModifiedSince = DateTime.Parse(strValue);
}
else if (strKey.Trim().Equals("Referer"))
{
request.Referer = strValue;
}
else if (strKey.Trim().Equals("Transfer-Encoding"))
{
request.TransferEncoding = strValue;
}
else if (strKey.Trim().Equals("User-Agent"))
{
request.UserAgent = strValue;
}
else
{
request.Headers.Add(strKey, strValue);
}
}
}
if (method.Equals("POST") || method.Equals("PUT"))
{
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
if (enctype.Equals(appJson))
{
if (JsonContent != null)
{
if (JsonContent is JObject)
{
JObject obj = (JObject)JsonContent;
m_Log.Debug(enctype + " encoding JObject: " + obj.ToString());
byte[] bytes = encoding.GetBytes(obj.ToString());
writeStream.Write(bytes, 0, bytes.Length);
}
else
{
JObject obj = new JObject();
obj.Add(new JProperty("content", JsonContent));
m_Log.Debug(enctype + " encoding: " + obj.ToString());
byte[] bytes = encoding.GetBytes(obj.ToString());
writeStream.Write(bytes, 0, bytes.Length);
}
}
}
else if (enctype.Equals(appUrlEncoded))
{
m_Log.Debug(enctype + " encoding parameters: " + parameters);
byte[] bytes = encoding.GetBytes(parameters);
writeStream.Write(bytes, 0, bytes.Length);
}
writeStream.Close();
}
}
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
StreamReader input = new StreamReader(webResponse.GetResponseStream());
result = "";
result += convertToJson(input, webResponse.ContentType);
}
catch (Exception e)
{
Dictionary<string, string> d1 = new Dictionary<string, string>();
string value = "error.com.genesyslab.composer.servererror message= " + e.Message.ToString();
d1.Add("errorMsg", value);
result = Newtonsoft.Json.JavaScriptConvert.SerializeObject(d1);
Response.AppendToLog("GeneralException:" + result);
}
m_Log.Debug("result: " + result);
m_Log.Debug("fetchURL() out");
return result;
}
string parseResultData(StreamReader reader, JsonTextReader jsonReader, string initialData)
{
m_Log.Debug("parseResultData(" + initialData + ") In");
string json = "";
try
{
jsonReader.Read();
// JSON string
json += initialData;
Response.AppendToLog("ContentTypeUnkJSON");
m_Log.Debug("parseResultData() Out");
return json;
}
catch (JsonReaderException)
{
m_Log.Debug("parseResultData() JsonReaderException");
// not a valid JSON - check for XML
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(initialData);
reader.Close();
json = Newtonsoft.Json.JavaScriptConvert.SerializeXmlNode(doc.DocumentElement);
Response.AppendToLog("ContentTypeUnkXML");
m_Log.Debug("parseResultData() Out");
return json;
}
catch (Exception e)
{
m_Log.Debug("parseResultData() Exception: " + e.Message);
Response.AppendToLog("ContentTypeUnkTEXT");
Response.AppendToLog("Exception Occured: " +e.Message.ToString());
Dictionary<string, string> d1 = new Dictionary<string, string>();
d1.Add("result", initialData);
string jsonText = Newtonsoft.Json.JavaScriptConvert.SerializeObject(d1);
return jsonText;
}
}
}
/**************convertToJson****************************/
string convertToJson(StreamReader reader, string contentType)
{
m_Log.Debug("convertToJson(" + contentType + ") In");
string json = "";
string data = reader.ReadToEnd();
// Parse into a JSON string
TextReader txReader = new StringReader(data);
Newtonsoft.Json.JsonTextReader jsonReader = new JsonTextReader(txReader);
if (contentType != null && contentType.Length != 0)
{
Response.AppendToLog("Content-Type:" + contentType.ToString());
if (contentType.ToLower().StartsWith(textXml) ||
contentType.ToLower().StartsWith(appXml))
{
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(data);
reader.Close();
json = Newtonsoft.Json.JavaScriptConvert.SerializeXmlNode(doc.DocumentElement);
m_Log.Debug("convertToJson() Out");
return json;
}
catch (XmlException e)
{
Response.AppendToLog("ContentTypeXMLFalse");
m_Log.Error("convertToJson() Error in decoding XML: " + e.Message);
throw new XmlException("Error in decoding XML: " + e.Message, e);
}
}
else if (contentType.ToLower().StartsWith(appJson))
{
jsonReader.Read();
// JSON string
json += data;
Response.AppendToLog("ContentTypeJSON");
m_Log.Debug("convertToJson() ContentTypeJSON Out");
return json;
}
else if (contentType.ToLower().StartsWith(textPlain))
{
Response.AppendToLog("ContentTypeTEXT");
Dictionary<string, string> d1 = new Dictionary<string, string>();
d1.Add("result", data);
d1.Add("headers", "");
string jsonText = Newtonsoft.Json.JavaScriptConvert.SerializeObject(d1);
Response.AppendToLog("ContentTypeTEXT:" + jsonText);
m_Log.Debug("convertToJson() ContentTypeTEXT Out");
return jsonText;
}
else
{
Response.AppendToLog("unknown Content-Type:" + contentType);
m_Log.Debug("convertToJson() unknown Content-Type Out");
return (parseResultData(reader, jsonReader, data));
}
}
else
{
Response.AppendToLog("Content-Type NULL");
m_Log.Debug("convertToJson() Content-Type NULL");
return( parseResultData(reader, jsonReader, data) );
}
}
</script>
<%
log4net.Config.XmlConfigurator.Configure();
m_Log.Debug("_________________________________________________");
m_Log.Debug("getWebRequest() In");
// extract parameters
String WebUrl ="";
String Protocol= "";
String EncType = "";
Boolean AuthenAccess = false;
String UserName ="";
String Password ="";
String readWriteTimeout = "20000"; // timeout in milliseconds
String conTimeout = "20000"; // timeout in milliseconds
Stream ins = HttpContext.Current.Request.InputStream;
StreamReader reader = new StreamReader(ins);
string jsonStr = reader.ReadToEnd();
JObject requestObj = JObject.Parse(jsonStr);
m_Log.Debug("requestObj: " + requestObj.ToString());
WebUrl = (string)requestObj["WebUrl"];
Protocol = (string)requestObj["Protocol"];
EncType = (string)requestObj["Enctype"];
AuthenAccess = (Boolean)requestObj["AuthenAccess"];
if (AuthenAccess)
{
UserName = (string)requestObj["UserName"];
Password = (string)requestObj["Password"];
}
// the value passed from the block property overrides the
// global value in the composer.properties
String timeout = (string)requestObj["Timeout"];
if (timeout != null && timeout.Trim().Length > 0)
{
try
{
int timeoutInt = Int32.Parse(timeout);
if (timeoutInt != -1)
{
conTimeout = Convert.ToString(timeoutInt * 1000);
readWriteTimeout = Convert.ToString(timeoutInt * 1000);
}
}
catch (FormatException)
{
// ignore an invalid value
}
}
String ParamStr = "";
int QueryPos = WebUrl.IndexOf('?');
if ((Protocol.EndsWith("get") || Protocol.EndsWith("delete")) && (QueryPos > 0))
{
String QueryString = WebUrl.Substring(QueryPos + 1, WebUrl.Length - (QueryPos + 1));
WebUrl = WebUrl.Substring(0, QueryPos);
String[] Pairs = QueryString.Split('&');
foreach (String Pair in Pairs)
{
string strKey = "";
string strValue = "";
int Pos = Pair.IndexOf('=');
if (Pos == -1)
{
strKey = Pair;
strValue = null;
}
else
{
try
{
strKey = Server.UrlDecode(Pair.Substring(0, Pos));
strValue = Server.UrlDecode(Pair.Substring(Pos + 1, Pair.Length - (Pos + 1)));
}
catch (Exception ex)
{
m_Log.Error("Exception parsing queryString:" + ex.Message);
}
}
if (!ParamStr.Equals(""))
{
ParamStr = ParamStr + "&";
}
ParamStr = ParamStr + Server.UrlEncode(strKey) + "=" + Server.UrlEncode(strValue);
}
}
JObject Parameters = (JObject)requestObj["Parameters"];
if (Parameters != null)
{
JEnumerable<JProperty> children = Parameters.Children<JProperty>();
foreach (JProperty child in children)
{
string strKey = child.Name;
string strValue = "";
if (child == null || child.Value == null)
continue;
if (child.Value.Type.Equals(JsonTokenType.String))
{
strValue = (String)((JValue)child.Value).Value;
}
else
{
strValue = child.Value.ToString();
}
// add to map
if (!ParamStr.Equals(""))
{
ParamStr = ParamStr + "&";
}
ParamStr = ParamStr + Server.UrlEncode(strKey) + "=" + Server.UrlEncode(strValue);
}
}
m_Log.Debug("ParamStr: " + ParamStr);
JObject CustomHeaders = (JObject)requestObj["CustomHeaders"];
JToken JsonContent = (JToken)requestObj["JsonContent"];
//relative path processing
string relativePath = "http://localhost:";
if (WebUrl.StartsWith("."))
{
int slashindex = WebUrl.IndexOf("/");
if (slashindex != -1)
{
int n = WebUrl.Length;
WebUrl = WebUrl.Substring(slashindex + 1, n - slashindex-1);
}
relativePath += HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
relativePath = relativePath + HttpContext.Current.Request.RawUrl.ToString();
int boundary = relativePath.IndexOf("include");
if(boundary !=-1){
relativePath = relativePath.Substring(0, boundary);
}
WebUrl = relativePath + WebUrl;
m_Log.Debug("urlStr: " + WebUrl);
}
m_Log.Debug("WebUrl: " + WebUrl);
if (WebUrl.Length > 0)
{
Response.Write(fetchURL(WebUrl, Protocol, EncType, ParamStr, readWriteTimeout, conTimeout,
UserName, Password, CustomHeaders, JsonContent));
}
m_Log.Debug("getWebRequest() Out");
%>
`
As you can see I have inserted a "header" key-value pair in my returned json repsonse. How do I attach the value of the repsonse headers in the headers property? I have tried webResponse.Headers with no luck.
Thank you very much in advance!

Sending/Fowarding Emails with duplicate subject line using WebDav in C#

I have some code that uses the WEBDAV 'SEARCH' method to retrieve emails from an an Exchange Mailboxs 'Inbox' folder - my code takes the the innerXML of the HTTPWebRquests WEBresponse.
Using 'selectingSingleNode' on these namsspaces:
'urn:schemas:httpmail' & urn:schemas:mailheader
Alows me to extract the elements:
f:textdescription
d:fromd:subject
f:datareceived...and so on
I then create a collection of these details in a list and using the 'Subject' along with the URI use the 'PUT' method to recreate these messages in the 'draft's folder before using the 'MOVE' to send the mails (puts them in the sent items using '/##DavMailSubmissionURI##/"' statement.
The problem i have is the nature of the emails i am dealing with tend to come in with the same subject line so it gets confused with which emails have been sent/or not.
Does anyone know of a way around this, I dont know why the 'PUT' relies on the Subject line for the URI to the mail resource rather than say the HREF tag which is unique. Any ideas:
Code is below:
public class EmailReaderWebDav
{
public enum enmHTTPType
{
HTTP,
HTTPS,
}
private String strServer { get; set; } //"mail1" ------ Exchange server name
public String strPassword { get; set; } //"password" ------ Account Domain Password
public String strDomain { get; set; } //"mydocmian" ------ Domain
public String strMailBox { get; set; } //"mymailbox" ------ UserName
public String mailFolder { get; set; } //"inbox" ------ Mail Folder
private String httpProtocol { get; set; } //http:// ? or https://
private String mailboxURI { get; set; } //httpprotocol// + strserver + "/exhange/" + strmailbox
public List<MailStruct > ListOfEmailDetails { get; private set; }
private String strQuerySearch { get; set; }
public EmailReaderWebDav(String serverName, String domain, String mailBox, String password, String mailmailFolder,enmHTTPType HTTPType)
{
strServer = serverName;
strDomain = domain;
strMailBox = mailBox;
strPassword = password;
mailFolder = mailmailFolder;
httpProtocol = (HTTPType == enmHTTPType.HTTPS) ? "https://" : "http://";
mailboxURI = httpProtocol + strServer + "/exchange/" + strMailBox + "/inbox/";
}
public void forwardEmails(List<MailStruct> emailsToSend)
{
emailsToSend.ForEach(x => SendEmail(x,enmHTTPType.HTTP ));
}
public void MakeListofEmailsToForward()
{
String tmpQuery =
"<?xml version=\"1.0\"?>"
+ "<D:searchrequest xmlns:D = \"DAV:\" >"
+ "<D:sql>"
+ " SELECT "
+ "\"urn:schemas:mailheader:to\","
+ "\"urn:schemas:mailheader:from\","
+ "\"urn:schemas:mailheader:subject\","
+ "\"urn:schemas:httpmail:datereceived\","
+ "\"urn:schemas:httpmail:textdescription\""
+ " FROM \"" + mailboxURI + "\""
+ " WHERE \"DAV:ishidden\" = false AND \"DAV:isfolder\" = false"
+ "</D:sql>"
+ "</D:searchrequest>";
// Search Request to get emails from target folder.
HttpWebRequest SearchRequest = MakeWebRequest("SEARCH", "text/xml", mailboxURI);
Byte[] bytes = Encoding.UTF8.GetBytes((String)tmpQuery);
SearchRequest.ContentLength = bytes.Length;
Stream SearchRequestStream = SearchRequest.GetRequestStream();
SearchRequestStream.Write(bytes, 0, bytes.Length);
SearchRequestStream.Close();
// get the webresponse from the searchrequest.
WebResponse SearchResponse = MakeWebResponse(SearchRequest);
String EmailsInXML = extractXMLFromWebResponse(SearchResponse);
ListOfEmailDetails = extractMailPropertiesFromXMLString(EmailsInXML);
}
public void SendEmail(MailStruct mailToForward, enmHTTPType HTTPType)
{
String submissionUri = httpProtocol + strServer + "/" + "exchange" + "/" + strMailBox + "/##DavMailSubmissionURI##/";
String draftsUri = httpProtocol + strServer + "/" +"exchange" + "/" + strMailBox + "/Drafts/" + mailToForward.Subject + ".eml";
String message = "To: " + mailToForward.To + "\n"
+ "Subject: " + mailToForward.Subject + "\n"
+ "Date: " + mailToForward.Received
+ "X-Mailer: mailer" + "\n"
+ "MIME-Version: 1.0" + "\n"
+ "Content-Type: text/plain;" + "\n"
+ "Charset = \"iso-8859-1\"" + "\n"
+ "Content-Transfer-Encoding: 7bit" + "\n"
+ "\n" + mailToForward.MailBody;
// Request to put an email the drafts folder.
HttpWebRequest putRequest = MakeWebRequest("PUT", "message/rfc822",draftsUri );
Byte[] bytes = Encoding.UTF8.GetBytes((String)message);
putRequest.Headers.Add("Translate", "f");
putRequest.Timeout = 300000;
putRequest.ContentLength = bytes.Length;
Stream putRequestStream = putRequest.GetRequestStream();
putRequestStream.Write(bytes, 0, bytes.Length);
putRequestStream.Close();
// Put the message in the Drafts folder of the sender's mailbox.
HttpWebResponse putResponse = MakeWebResponse(putRequest);
putResponse.Close();
// Request to move the email from the drafts to the mail submission Uri.
HttpWebRequest moveRequest = MakeWebRequest("MOVE", "text/xml", draftsUri);
moveRequest.Headers.Add("Destination", submissionUri);
// Put the message in the mail submission folder.
HttpWebResponse moveResponse = MakeWebResponse(moveRequest);
moveResponse.Close();
}
private CredentialCache getCredentials(String URI)
{
CredentialCache tmpCreds = new CredentialCache();
tmpCreds.Add(new Uri(URI), "NTLM", new NetworkCredential(strMailBox, strPassword,strDomain ));
ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate pCertificate, System.Security.Cryptography.X509Certificates.X509Chain pChain, System.Net.Security.SslPolicyErrors pSSLPolicyErrors)
{
return true;
};
return tmpCreds;
}
private HttpWebRequest MakeWebRequest(String method,String contentType,String URI)
{
HttpWebRequest tmpWebRequest;
tmpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URI);
tmpWebRequest.Credentials = getCredentials (URI);
tmpWebRequest.Method = method;
tmpWebRequest.ContentType = contentType ;
return tmpWebRequest ;
}
private HttpWebResponse MakeWebResponse(HttpWebRequest webRequest)
{
HttpWebResponse tmpWebresponse = (HttpWebResponse)webRequest.GetResponse();
return tmpWebresponse;
}
WebResponse getMailsFromWebRequest(String strRootURI, String strQuerySearch)
{
HttpWebRequest SEARCHRequest;
WebResponse SEARCHResponse;
CredentialCache MyCredentialCache;
Byte[] bytes = null;
Stream SEARCHRequestStream = null;
try
{
MyCredentialCache = new CredentialCache();
MyCredentialCache.Add(new Uri(strRootURI ), "NTLM", new NetworkCredential(strMailBox.ToLower(), strPassword, strDomain));
SEARCHRequest = (HttpWebRequest)HttpWebRequest.Create(strRootURI );
ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate pCertificate, System.Security.Cryptography.X509Certificates.X509Chain pChain, System.Net.Security.SslPolicyErrors pSSLPolicyErrors)
{
return true;
};
SEARCHRequest.Credentials = MyCredentialCache;
SEARCHRequest.Method = "SEARCH";
SEARCHRequest.ContentType = "text/xml";
bytes = Encoding.UTF8.GetBytes((string)strQuerySearch);
SEARCHRequest.ContentLength = bytes.Length;
SEARCHRequestStream = SEARCHRequest.GetRequestStream();
SEARCHRequestStream.Write(bytes, 0, bytes.Length);
SEARCHResponse =(HttpWebResponse ) SEARCHRequest.GetResponse();
SEARCHRequestStream.Close();
SEARCHRequest.Timeout = 300000;
System.Text.Encoding enc = System.Text.Encoding.Default;
if (SEARCHResponse == null)
{
Console.WriteLine("Response returned NULL!");
}
else
{
Console.WriteLine(SEARCHResponse.ContentLength);
}
return SEARCHResponse;
}
catch (Exception ex)
{
Console.WriteLine("Problem: {0}", ex.Message);
return null;
}
}
private String extractXMLFromWebResponse(WebResponse SearchResponse)
{
String tmpStream;
using(StreamReader strmReader = new StreamReader(SearchResponse.GetResponseStream(), System.Text.Encoding.ASCII))
{
tmpStream = strmReader.ReadToEnd();
strmReader.Close();
}
return tmpStream;
}
private List<MailStruct > extractMailPropertiesFromXMLString(String strXmlStream)
{
List<MailStruct> tmpListOfMailProperties = new List<MailStruct>();
XmlDocument doc = new XmlDocument();
doc.InnerXml = strXmlStream ;
XmlNamespaceManager xmlNameSpaces = new XmlNamespaceManager(doc.NameTable);
xmlNameSpaces.AddNamespace("a", "DAV:");
xmlNameSpaces.AddNamespace("f", "urn:schemas:httpmail:");
xmlNameSpaces.AddNamespace("d", "urn:schemas:mailheader:");
XmlNodeList mailNodes = doc.SelectNodes("//a:propstat[a:status='HTTP/1.1 200 OK']/a:prop", xmlNameSpaces);
foreach (XmlElement node in mailNodes)
{
tmpListOfMailProperties.Add(new MailStruct()
{
MailBody = node.SelectSingleNode("//f:textdescription",xmlNameSpaces ).InnerText ,
from = node.SelectSingleNode ("//d:from",xmlNameSpaces ).InnerText ,
To = "dfoster#liquidcapital.com",
Subject = node.SelectSingleNode("//d:subject",xmlNameSpaces ).InnerText.ToString () ,
Received = node.SelectSingleNode ("//f:datereceived",xmlNameSpaces ).InnerText.ToString ()
}
);
}
return tmpListOfMailProperties;
}
public struct MailStruct
{
public String To { get; set; }
public String from { get; set; }
public String Subject { get; set; }
public String Received { get; set; }
public String MailBody { get; set; }
}
}
}
Using just the subject to identify email is, indeed, not a good way. If I remember it's correct, there are no automatic / obvious email id for exchange / webdav?
If you parse the subject to pick message, I would also pick more information of the email envelope - Like it size, length to create my own id. The best step should be that you create some sort of hash (check Cryptography) out of the whole message body OR i.e. first character of first xx word in the email body (heavier processing though). That will end up in same hash value everytime you call it on same email envelope. Of until the email content is leaved unchanged.
Looks like you're working with Exchange 2003. Be aware that WebDAV is no longer supported in Exchange Version 2010... and with 2007 and newer you can use a WSDL to do everything you need. All you need is an Exchange 2007 CAS to do this.
What I mentioned is a better longer term approach and has less headaches than parsing unsupported WEBDAV XML
To answer your question, there is a property that is unique per message. Use MFCMapi (on codeplex) to look for it. The property will be named "MessageURL" or something like that. Use that property in the URL for your webdav calls.

Categories