Monday, October 12, 2009

Using gmail from C# and inspecting HttpRequests

This post can help you with two things

  1. Sending mail via gmail or google apps through C#.
  2. Inspecting the contents of an HttpRequest as a string similar to HttpRequest.SaveAs.


Today while working on a code for fun project at lunchtime we wanted to see the HttpContext.Request.  Initially we were calling HttpRequest.SaveAs(context.Server.MapPath("Request.txt"),true) and life was good.  When we deployed to our test server hosted by Verio, an awesome company, we got an access denied exception when trying to write.  Our corporate firewall prevented us from changing the folder permissions, and we couldn't figure out how to do it through our ftp client, FileZilla.  We decided to email the request to ourselves with the following code:

SmtpClient mailer = new SmtpClient("smtp.gmail.com", 587);
//mailer.EnableSsl = true;
mailer.Credentials = new NetworkCredential("emailAddress@yourDomain.com", "YourPassword");
mailer.Send("sender@sender.com", "recipient@recipient.com", "snazzySubject", Request.RequestAsString());

Running that code we get: System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 216.239.59.109:587.  This is our firewall blocking us again.

At home I got "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first."

Uncommenting the mailer.EnableSsl line above and rerunning fixed the problem and my email arrived!

//End point #1 and begin point #2
Here is the code duplicating the request.saveAs functionality:  RequestAsString is an extension method.  In my code I put it in the System.Web namespace so it shows up for me when using System.Web.


/// <summary>
/// Turns an HttpRequest into a string for inspection.  Similar to request.SaveAs.
/// </summary>
/// <param name="request">The request to turn to a string.</param>
/// <returns>A string to inspect the HttpRequest.</returns>
public static string RequestAsString(this HttpRequest request)
{
    StringBuilder returnValue = new StringBuilder()
        .Append(request.HttpMethod + " " + request.RawUrl);
    if (returnValue.ToString().EndsWith("?"))
    {
        returnValue.Length = returnValue.Length - 1;
    }
    returnValue.Append(" " + request.ServerVariables["SERVER_PROTOCOL"])
        .Append(Environment.NewLine)
        .Append(TurnNamedValuesToLists(request.Headers, ": ", Environment.NewLine))
        .Append(Environment.NewLine)
        .Append(request.ContentEncoding.GetString(request.BinaryRead(request.ContentLength)));

    return returnValue.ToString();
}

/// <summary>
/// Splits out a NameValueCollection.
/// </summary>
/// <param name="target">The collection to be split.</param>
/// <param name="seperator">Seperates the key from the value in the output.</param>
/// <param name="terminator">Put at the end of the key and the value.</param>
/// <returns>A string of all the key value pairs.</returns>
private static string TurnNamedValuesToLists(NameValueCollection target, string seperator, string terminator)
{
    StringBuilder returnValue = new StringBuilder();
    string[] keys = target.AllKeys;

    foreach (var key in keys)
    {
        returnValue.Append(key + seperator + (string)target[key] + terminator);
    }
    return returnValue.ToString();
}

7 comments:

Anonymous said...

Dear Author blog.davidsilvasmith.com !
Absolutely casual concurrence

Anonymous said...

I want to quote your post in my blog. It can?
And you et an account on Twitter?

David Smith said...

Feel free to quote me. I'm @DavidSilvaSmith on Twitter.

Anonymous said...

Whats's Up i'm new to this, I stumbled upon this website I have found It truly useful & its helped me a great deal. I should be able to contribute & help others like it has helped me.

Thank You, See Ya Around

Anonymous said...

Whats's Up im fresh to this, I came upon this forum I have found It vastly useful and it's helped me out a great deal. I should be able to contribute & support others like its helped me.

Cheers, See Ya Around

Anonymous said...

Great post. Data professional player taking turns!

Anonymous said...

Truly extremely eye-catching post. Comprehend guru this specific technique.