advanced web statistics

Json.NET and Generic HttpWebRequest Responses FTW

Working on a Windows Phone 7 mobile app recently, I found myself writing a bunch of similar / redundant code for HttpWebRequest response handling. By "a bunch" I mean in the neighborhood of 3 methods.... Hello Generics!!!

If I find myself writing the same handler more than once and the only difference is the type of object I am returning I ALWAYS (at least try to) write a generic method to take care of the heavy lifting.  There are a plethora of reasons to use Generics when the opportunity presents itself and I'm not going to start listing them.  Those of you that understand .NET Generics will get it.  If you are a .NET developer and currently developing applications targeting version 2.0 or greater and aren't familiar with Generics, then I highly suggest you educate yourself: Generics in the .NET Framework.

If you are still with me and are familiar with the System.Net namespace and the HttpWebRequest class (as it pertains to Silverlight and/or Windows Phone 7), I'd like to share the following response handler for dealing with Asynchronous requests:

private static T ProcessFamiliarRequestResponse<T>(IAsyncResult asyncResult)
{
    HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
    HttpWebResponse httpWebResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);

    using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
    {
        return JsonWorker.TooEasyToDeserializeJsonObject<T>(streamReader.ReadToEnd());
    }
}

If this doesn't make sense to you I highly suggest reading up on WebClient and HttpWebRequest usage.  If you are familiar, I hope you can appreciate that this is one point of entry into handling an infinite number of requests (within reason).

It gets cleaner: Enter Json.NET.  Personally, I like to create clean POCO's to return data to the consumer.  I have seen way too many examples creating objects that conform EXACTLY to the Json format returned from any given request.  For instance:

public class Employee
{
    public string employee_first_name { get; set; }
    public string employee_last_name { get; set; }
    public string employee_job_description { get; set; }
}

Gross (imo).  .NET is so much better than this.  I take pride in the code that I deliver and personally believe the following class is much cleaner (and not to mention, conforms to .NET naming conventions):

public class Employee
{
    [JsonProperty("employee_first_name")]
    public string FirstName { get; set; }

    [JsonProperty("employee_last_name")]
    public string LastName { get; set; }

    [JsonProperty("employee_job_description")]
    public string JobDescription { get; set; }
}

This way you can map your neatly-defined POCO properties to their disgusting origins.  The following generic method for deserializing your Json results works fairly well (pre-supposing you decorated your POCO(s) with the JsonProperty attribute OR left it repulsive and/or primitive):

public static class JsonWorker
{
    public static T DeserializeJsonObject<T>(string result)
    {
        return JsonConvert.DeserializeObject<T>(result);
    }
}

If you want to take it a step further, you could add the following method to your JsonWorker class to serialize your objects. Think storing application state in IsolatedStorage or updating your light-weight, client-side database (via Sterling (which is AWESOME!!!)):

public static string WayEasierToSerializeObjectToJson(object randomPOCO)
{
    return JsonConvert.SerializeObject(randomPOCO);
}

Easy.

Tags: C#, Code, Windows Phone

Microsoft Office Interop Outlook & C# For Outlook Searches

I had a need yesterday to query a bunch of Outlook e-mails: 44,743 to be exact.  This was the result of a clients mailing list account being setup incorrectly and we just found out about it!  An e-mail account was setup strictly for the mailing list and it was never properly setup as an Outlook account locally.  No big deal.  When the hosting provider contacted us to clean it up I noticed that there were a BUNCH of bad e-mail addresses (Return to sender, bad account, etc...).  At first I started to click on individual e-mails, copy the bad e-mail address to a .txt file, then search that folder for the same e-mail address and delete the results.  That takes FOOOOORRREEEEVVVVEEEEERRRRRRR.  Then I realized I could dork around with Outlook via a C# console application and harvest the e-mails and output them in a sorted Excel spreadsheet.

Enter Microsoft.Office.Core and Microsoft.Office.Interop.Outlook namespaces. I decided it would be best to create a little C# console application utilizing these namespaces to search the e-mail, write a little regular expression pattern (by write I mean copy & paste one from the interwebs) to parse out e-mail addresses, and add e-mail addresses that didn't have the host name or the reply e-mail account in it to a List<string> (if it didn't already contain it!).  It was pretty easy.

First:

using Outlook = Microsoft.Office.Interop.Outlook;
using Microsoft.Office.Interop.Outlook;

I'm not going to bore you with the entire application unless you really want it.  I'll just get you to the point where you can start to do stuff with your e-mails.

Now you need to instantiate your Outlook object.

Outlook.Application application = new Application();
Outlook.NameSpace nameSpace = application.GetNamespace("MAPI");
Outlook.MAPIFolder mapiFolder = nameSpace.GetDefaultFolder(OlDefaultFolders.olFolderJunk);

It might be worth mentioning the olFolderJunk business you see there.  In the interest of time I didn't want to mess around with trying to navigate to the folder that I actually stored these e-mails in since I have a bunch of subfolders in Outlook due to using multiple accounts and a handful of rules and what-not.  So in the interest of time I moved all the e-mails to the junk folder since I could easily access it.  I think the correct syntax would be something like:

nameSpace.Folders["FOLDER"].Folders["SUB"].Folders["YOU_GET_IT"];

Moving on.  Once you finally get access to your designated folder you need to start being able to do stuff with the items in that folder.  It's as easy as enumerating the, you guessed it; MailItem objects a la:

foreach (MailItem mailItem in mapiFolder.Items)
{
   // do stuff
}

Easy.  The properties are fairly braindead as well.  MailItem Object Members

Have fun.  I'll probably use this in the future as well.

Tags: C#, Code

Guid Extension Methods

Another "Late Pass" series entry.  I've just recently started using extension methods and seeing how useful they can be.  Extension methods have been pretty fun to write so far.  It's nice to find yourself wanting a piece of functionality and then having the power to now do it.

My first extension method deals with Guids.  I tend to use Guids a lot and there is no real way to convert something to a Guid.  Let's say you have a QueryString value that is a unique identifier (i.e. Guid) and you want to check for it, convert it to a Guid, then do something with it (i.e. retrieve employee information, etc...) I've found that to do this I'd need to some variation of the following:

string s = Request.QueryString["Guid"];
Guid guid == Guid.Empty;

if (!string.IsNullOrEmpty(s))
   try
   {
      guid = new Guid(s);
   }
   catch (FormatException)
   {
      guid = Guid.Empty;
   }

if (guid != Guid.Empty)
{
   
// do stuff with Guid g
}

Enter my first extension method: IsGuid(). This provides a less verbose method of doing business.

if (s.IsGuid())
{
   Guid guid = new Guid(s);
   // do stuff with guid

There is another option:

Guid guid = Request.QueryString["Guid"].ConvertToGuid();

if (guid != Guid.Empty)
{
   // do stuff with Guid

Here is the code for the extension methods. First you will you need a RegularExpression for the format of the Guid.  That's easy enough as Guids have the same format 8-4-4-4-12 (would provide a link to where I found this regular expression but I forgot where I got it 8^( )

private static readonly Regex _guidRegex = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled); 

Now the actual methods:

public static bool IsGuid(this string value)
{
   return !string.IsNullOrEmpty(value) ? 
            _guidRegex.IsMatch(value) : false;
}

public static Guid ConvertToGuid(this string value)
{
   return string.IsNullOrEmpty(value) ? Guid.Empty : 
      (_guidRegex.IsMatch(value) ? new Guid(value) : Guid.Empty);

Again, I apologize for the line breaks.  I need to implement a new CSS layout.  By implement I mean find a free one that isn't a complete mess.

I'll be posting more extension methods in the future.  Too bad I missed the bus a couple of months ago!

Easy.

Tags: .NET, C#, Code

Generic Enum Helper Class

This is another installment in my recent "Late Pass" series.  I've been working with enums a lot lately and as I usually do in my spare time, I visit http://www.dotnetkicks.com to read up on cool stuff related to technology I am currently using.  I'm wanting to bind the contents of the enum to a dropdown / radiobutton list.  The first article I came across seemed like it would work.  That was until I stumbled upon this article by Christopher Bennage.  It's short and sweet but really helpful.

A repost of the original code:

public static class Enum<T>
{
   public static T Parse(string value)
   {
      return (T) Enum.Parse(typeof (T), value);
   }

   public static IList<T> GetValues()
   {
      IList<T> list = new List<T>();

      foreach (var value in Enum.GetValues(typeof (T)))
         list.Add((T) value);

      return list;
   }

Sample enum:

public enum DataProvider
{
   SqlServer = 1,
   Access = 2,
   MySql = 3,
   Oracle = 4

Let's bind those values to a dropdownlist and let our users choose:

private void InitializeDataProviderDropDownList()
{
   selectDataProvider.DataSource = Enum<DataProvider>.GetValues();
   selectDataProvider.DataBind();

Let's add a button and process the selected value:

DataProvider dataProvider = Enum<DataProvider>.Parse(selectDataProvider.SelectedValue);

switch (dataProvider)
{
   case DataProvider.Access:
      Response.Write("Access");
      break;

   case DataProvider.MySql:
      Response.Write("MySql");
      break;

   case DataProvider.Oracle:
      Response.Write("Oracle");
      break;

   default:
      Response.Write("SqlServer");
      break;

I realize that this is a stupid use of the functionality at-hand. By this I mean if the end-result were actually to Response.Write the SelectedValue I would be going about doing it the wrong way. This would be extremely useful for methods that take an enum as a parameter.  I'll definitely be using this in the future.

Easy.

Tags: C#, Code

Coding For Fun - HTML Calendar Challenge

I figured coming up with a solution to Jacob Carpenter's HTML Calendar Challenge would be a good entry to resurface with ;)   I have been extremely busy with work and haven't had a whole lot of time to code-for-fun.  Coding for fun / free is something that I love to do.  This challenge was the perfect opportunity for this.

My solution presupposes that the actual days of the week were hard-coded into the calendar.  If this isn't the case I may lose some points ;)

Here is my HTML.

<table cellpadding="3" cellspacing="2">
   
<tr style="font-weight: bold; text-transform: uppercase;">
      
<td>Sunday</td>
      
<td>Monday</td>
      
<td>Tuesday</td>
      
<td>Wednesday</td>
      
<td>Thursday</td>
      
<td>Friday</td>
      
<td>Saturday</td>
   
</tr>

<asp:PlaceHolder ID="ph" runat="server" />

</table> 

The first thing I do is create the first day of the current month.  Pretty basic.  I then need to find the start of that week (whether or not it is the current month or previous).  We can do this with DateTime.AddDays().  I created a static int that takes the DayOfWeek as a parameter.  Depending on what the first day of the current month is, we now know how far to go back to get the date for Sunday of that week.  Again, I am presupposing the week starts on Sunday. Some folks like Monday, etc...

I then have a _continue bool.  While this is true I keep adding weeks (WebControls.TableRow).  I just add 7*counter to the AddDays (there is no AddWeeks so 7 days = 1 week).  While I am creating my TableRow I check to see if any of the cells contain the previous or next month.  I compare the current date to my _firstOfMonth.Date.Month.  This lets me set the class of "prevMonth". I do the same if the end of the month falls midweek and I have to buffer out the week with next month dates.  This also sets _continue to false.  Easy.

I could probably stream-line this (and probably will here-and-there over the next couple of days) but when all was said and done it took me a little over 45 minutes from reading Jacob's post to create a solution, test it, blog about it, etc...

Here is the code-behind.

private bool _continue = true;
private DateTime _firstOfMonth;

protected void Page_Load(object sender, EventArgs e)
{
   DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
   ph.Controls.Add(Week(month.AddDays(GoBack(dt.DayOfWeek))));

   int counter = 1;
   _firstOfMonth = dt;

   while (_continue)
   {
      DateTime current = month.AddDays(7*counter);
      ph.Controls.Add(Week(current.AddDays(GoBack(current.DayOfWeek))));

      ++counter;
   }
}

private static int GoBack(DayOfWeek dayOfWeek)
{
   switch (dayOfWeek)
   {
      case DayOfWeek.Sunday: return 0;
      case DayOfWeek.Monday: return -1;
      case DayOfWeek.Tuesday: return -2;
      case DayOfWeek.Wednesday: return -3;
      case DayOfWeek.Thursday: return -4;
      case DayOfWeek.Friday: return -5;
      case DayOfWeek.Saturday: return -6;
      default: return 0;
   }
}

private TableRow Week(DateTime startDate)
{
   bool containsNextMonth = false;
   TableRow row = new TableRow();

   for (int i = 0; i < 7; ++i)
   {
      TableCell cell = new TableCell();
      DateTime cellDate = startDate.AddDays(i);
      cell.Text = cellDate.Date.Day.ToString();

      if (cellDate.Date.CompareTo(DateTime.Today.Date) == 0)
         cell.Attributes.Add("class", "today");

      if (cellDate.Date.Month < _firstOfMonth.Date.Month)
         cell.Attributes.Add("class", "prevMonth");

      if (cellDate.Date.Month > _firstOfMonth.Date.Month)
      {
         cell.Attributes.Add("class", "nextMonth");
         containsNextMonth = true;
      }

      row.Cells.Add(cell);
   }

   _continue = !containsNextMonth;

   return row;
}

I love little projects like this because I get to hack in the weeds of low-level stuff.  Of course I could've used the asp:Calendar but the fact of the matter is it sucks.  Have you ever tried to roll your own JavaScript handlers into one of those?  Postbacks are a given, a cost of doing business.  I'm sure there are others like me out there that would take from this a little more intimate understanding of what goes into creating a calendar control.

If anyone who reads this teaches a web programming course this would be a perfect weekly assignment.  It could even be used as an interview question.  Not necessarily having to create a solution on the spot, but more of thinking out loud as to how you would go about creating a solution.

Thanks Jacob for the idea and creating a fun little distraction.

Finished product

HTML source

<table cellpadding="3" cellspacing="2">
    <tr style="font-weight: bold; text-transform: uppercase;">
        <td>Sunday</td>
        <td>Monday</td>
        <td>Tuesday</td>
        <td>Wednesday</td>
        <td>Thursday</td>
        <td>Friday</td>
        <td>Saturday</td>
    </tr>   
<tr>
 <td class="prevMonth">30</td><td class="prevMonth">31</td><td>1</td><td>2</td><td>3</td><td>4</td>
<td>5</td>
</tr>
<tr>
 <td>6</td><td>7</td><td>8</td><td>9</td><td>10</td><td>11</td>
<td>12</td>
</tr><tr>
 <td>13</td><td>14</td><td class="today">15</td><td>16</td><td>17</td><td>18</td><td>19</td>
</tr>
<tr>
<td>20</td><td>21</td><td>22</td><td>23</td><td>24</td>
<td>25</td><td>26</td>
</tr>
<tr>
<td>27</td><td>28</td><td>29</td><td>30</td><td class="nextMonth">1</td><td class="nextMonth">2</td><td class="nextMonth">3</td>
</tr>
   
</table> 

If this were for a project I would have added proper tabs and newlines to make the HTML look neat and more organic.

UPDATE
I realized this morning that both previous and next months can be less than the current month (December). November (11) is less than December (12) and January (1) is less than December.  I will update the code with _previousMonth and _nextMonth as int.

Easy.

Tags: C#, Code

Download My Reorder List / Drag and Drop VS 2005 Project

I apologize for not posting this sooner.  If it weren't for a very loyal (and patient!) visitor I would've probably forgot about this. 

Long story short: I have done about 20 clean installs of Windows Vista Ultimate over the last 3 weeks and pretty much didn't bother transferring all of my old files in the case that I would have to reinstall Ultimate again.  It's been 3 weeks without a hitch so I figure now is as great of a time as ever.

So, for those of you that are still interested you can download the "ActualReorderList" project.  It's a Visual Studio 2005 (C#) project.  The data comes from a ProdutGroup class with candy-coded data (i.e. not coming from a database).  I plan on adding this functionality in the future but for now just want to get the point across.

Let me know what you think.

@ Chetan: Thanks for the reminder :-)

Related Links
An Actual ReorderList Control with Substance Part 1
An Actual ReorderList Control with Substance Part 2

Tags: Code, JavaScript

Chaining of Generic List Methods

I swear this will never get old.  It's not high-tech, but useful.  If you wanted to you could turn this into a 3-line method. I broke out into 2 lines for readability.

private static decimal RetrieveTotalByCode(string code, List<Foo> list)
{
   decimal total = 0m;

   list.FindAll(delegate (Foo predicate)
                     {
                        return predicate.Code.Equals(code);
                     }).ForEach(delegate (Foo foo)
                                 {
                                    total += foo.Property;
                                 });

   return total;
}

I've run into code in the past where there would literally be one method that would sum a property based on a fixed "code".  A perfect example would be sales by region.  You would have a Field in your database (property of an object) that is something like "RegionSold".  What if you had 77 regions? 77 methods?  I know people who would agree.

Here all you have to do is instantiate a List<T> of your Regions and for each region call this method and display to end-user however it is you are displaying to them.

So to person I used to work with, this one's for you.

Tags: C#, Code

ASP:RequiredTextBox Control Source Code

Here is the source for the RequiredTextBox control I wrote about earlier.  You can drop this in your App_Code directory or compile it in a separate Web Control Library (what I did). Plus, if you compile it is a dll (or download the .dll) you can drop it into your Visual Studio 2005 Toolbox and drag it onto your forms for future use.

Read the original entry for demos. If you add any cool controls or extensions let me know about them or share in the comments.

Registering
<%@ Register TagPrefix="asp" Namespace="ControlExtensionLibrary" Assembly="ControlExtensionLibrary" %>

Class
using System;
using System.Web.UI;
using System.Drawing;
using System.ComponentModel;
using System.Web.UI.WebControls;

namespace ControlExtensions
{
   [ToolboxData("<{0}:RequiredTextBox runat=\"server\" />")]
   public class RequiredTextBox : TextBox
   
{
      [Bindable(true)]
      [Category("Validation")]
      [DefaultValue("")]
      [Localizable(true)] 
      public bool IsRequired
      {
         get { return (bool)(ViewState["IsRequired"] ?? false); }
         set { ViewState["IsRequired"] = value; }
      }

      public string ErrorMessage
      {
         get { return (string)ViewState["ErrorMessage"] ?? "*"; }
         set { ViewState["ErrorMessage"] = value; }
      }

      public new string ValidationGroup
      {
         get { return (string)ViewState["ValidationGroup"] ?? ""; }
         set { ViewState["ValidationGroup"] = value; }
      }

      public bool EnableClientScript
      {
         get { return (bool)(ViewState["EnableClientScript"] ?? true); }
         set { ViewState["EnableClientScript"] = value; }
      }

      private RequiredFieldValidator _required;

      protected override void OnInit(EventArgs e)
      {
         if (IsRequired)
         {
            _required = new RequiredFieldValidator();
            _required.ControlToValidate = ID;
            _required.ErrorMessage = string.Format(" {0}", ErrorMessage);
            _required.EnableClientScript = EnableClientScript;

            if (!string.IsNullOrEmpty(ValidationGroup))
               _required.ValidationGroup = ValidationGroup;

            Controls.Add(_required);
         }
      }

      protected override void Render(HtmlTextWriter htmlTextWriter)
      {
         base.Render(htmlTextWriter);

         if (IsRequired)
            _required.RenderControl(htmlTextWriter);
      }
   }

Download
WillAsrariControlExtensionLibrary.091707.zip (.dll)

Tags: C#, Code

Use System.Reflection For Comparing Custom Objects

Account first = new Account("me@willasrari.com", "007", "will");
Account second = new Account("me@willasrari.com", "000007", "will");

For strings, integers, DateTime's, etc... using object.Equals works just fine for comparing two objects.  I can't tell you how many times I have seen someone do the following to compare two custom objects (such as the Account objects above).

public static bool IsEqualTo(Account one, Account two)
{
   bool isEqual = true;

   if (!one.EmailAddress.Equals(two.EmailAddress))
      isEqual = false;
   else if (!one.Password.Equals(two.Password))
      isEqual = false;
   else if (!one.Username.Equals(two.Username))
      isEqual = false;

   return isEqual;

There is a much more graceful way. Enter System.Reflection. <3

public static bool IsEqualTo(object one, object two)
{
   bool isEqual = true;

   foreach (PropertyInfo p in one.GetType().GetProperties())
      if (!p.GetValue(one, null).Equals(p.GetValue(two, null)))
      {
         isEqual = false;
         
         break;
      }
   
   return isEqual;

Easy. Some may say that there is a performance hit using Reflection and that may be true to a certain extent.  I see the first method being an even bigger performance hit since I would have to create a specific IsEqualTo method for EACH object I will be possibly comparing.  For small projects this might not be a big deal but for large projects watch out.

Just clean up the second method (both types are the same) and throw it in a Utility class somewhere.

Tags: C#, Code

ASP.NET In-line Text Editing with AJAX / Database Support

I wrote the the other day about an easier (in my opinion) solution to provide in-line text editing without having to use the ASP.NET AJAX Library.  What that solution didn't include was the very thing the other articles online didn't include: actually editing the data.  Let's face it, changing the value of a label is completely useless unless you are updating a data source whether it be SQL, XML, etc..  I have done just that. I added about 20 minutes to initial 6 minutes to bring us in under a half-hour.  The code doesn't use stored procedures (very Hello World'esque) but at least I use paramterized queries!  The Ajax page (ajax.aspx) simply Response.Writes( 0 = good, 1 = bad).  To each his own. If you want an XML response simply add an XML response.  It is also worth mentioning that XmlHttpRequest is rather misleading and it should be renamed to WebRequest in the future. It isn't meant to be used with XML and it doesn't use XML under the covers. FYI (I'll post the link later).

Also, please add CSS to this. This is very vanilla.  I would never, EVER deploy something like this in production. Maybe beta-testing...

I have included the Visual Studio 2005 website and the database .bak (located in the App_Data folder).  If you have suggestions on how I could make it better let me know.  I will tell you that my next update to this code will be to dynamically generate the div's, labels, and textboxes.  In order to do that (I haven't quite finished scoping it) I am guessing I will use Serialization (XML) and the HtmlTextWriter class.

Have fun!

By the way, from top to bottom: favorite color, favorite band (currently listening), favorite stand-up comedian.

Edit Favorite Color
screen shot

Automatically Focus() and Select()
screen shot

Changed to Blue
screen shot

Successful!
screen shot

Download
AjaxEditing.zip

Tags: AJAX, C#, Code, JavaScript
<< Newer Entries Older Entries >>