<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>Jack Altiere</title>
	
	<link>http://www.jaltiere.com</link>
	<description>.NET Software Development</description>
	<lastBuildDate>Tue, 04 May 2010 14:43:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/JackAltiere" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="jackaltiere" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Ninject with MVC and ValidationAttributes</title>
		<link>http://www.jaltiere.com/index.php/2010/05/04/ninject-with-mvc-and-validationattributes/</link>
		<comments>http://www.jaltiere.com/index.php/2010/05/04/ninject-with-mvc-and-validationattributes/#comments</comments>
		<pubDate>Tue, 04 May 2010 14:40:01 +0000</pubDate>
		<dc:creator>Jack Altiere</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[ninject]]></category>
		<category><![CDATA[service locator]]></category>

		<guid isPermaLink="false">http://www.jaltiere.com/index.php/2010/05/04/ninject-with-mvc-and-validationattributes/</guid>
		<description><![CDATA[I was recently working on an MVC application and I ran into a problem.&#160; I was creating a ValidationAttribute and I needed to have access to my repository in this attribute.&#160; The use case is that I want to add a release of an application, and I want to make sure that the ID being [...]]]></description>
			<content:encoded><![CDATA[<p>I was recently working on an MVC application and I ran into a problem.&#160; I was creating a ValidationAttribute and I needed to have access to my repository in this attribute.&#160; The use case is that I want to add a release of an application, and I want to make sure that the ID being passed in is actually a valid application.&#160; My first pass at this was to try and use property injection, like this:</p>
<pre class="brush: csharp;">public class ApplicationIDValidAttribute : ValidationAttribute
{
    [Inject]
    public IRepository&lt;Application&gt; AppRepo { set; private get; }

    public override bool IsValid(object value)
    {
        // Don't force required here, they can use the required attribute.
        if (value == null)
        {
            return true;
        }

        int appID;
        if (!Int32.TryParse(value.ToString(), out appID))
        {
            return false;
        }

        // This did not work, AppRepo was not injected
        var app = AppRepo.LoadApplicationById(appID);

        return (app != null);
    }
}</pre>
<p>The problem here is that because of the way attributes are instantiated, this injection method does not work.&#160; In the above code sample, when this gets executed my AppRepo is null.</p>
<h3>Service Locator</h3>
<p>
  <br />The solution to my problem ended up being the use of a service locator to handle my injection.&#160; I could have went with the <a href="http://commonservicelocator.codeplex.com/" target="_blank">Common Service Locator</a> library, but that isn’t exactly what I want.&#160; I already know what DI container I want to use, so completely abstracting that layer away isn’t what I need.&#160; I ended up creating a library to handle the wiring up of Ninject, and to basically act as a wrapper to access the Ninject kernel.&#160; </p>
<pre class="brush: csharp;">public static class Container
{
    private static IKernel _kernel;

    public static void Initialize(IKernel kernel)
    {
        _kernel = kernel;
    }

    public static T Get&lt;T&gt;()
    {
        return _kernel.Get&lt;T&gt;();
    }

    public static object Get(Type type)
    {
        return _kernel.Get(type);
    }
}</pre>
<p>
  <br />Then, I could wire up my service locator in my global.asax file, like this:</p>
<pre class="brush: csharp;">// This is in my global.asax.cs file
// Required because I inherited from NinjectHttpApplication
protected override IKernel CreateKernel()
{
    var kernel =  new StandardKernel(new DataModule());

    // Gives my wrapper class access to the kernel instance
    Container.Initialize(kernel);

    return kernel;
}

// This is my data module for reference.
public class DataModule : NinjectModule
{
    public override void Load()
    {
        Bind(typeof (IRepository&lt;&gt;)).To(typeof (Repository&lt;&gt;));
    }
}</pre>
<p>Then, to close the loop, I can wire up my attribute like this:</p>
<pre class="brush: csharp;">public class ApplicationIDValidAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        // Don't force required here, they can use the required attribute.
        if (value == null)
        {
            return true;
        }

        int appID;
        if (!Int32.TryParse(value.ToString(), out appID))
        {
            return false;
        }

        var repo = Container.Get&lt;IRepository&lt;Application&gt;&gt;();
        var app = repo.LoadApplicationById(appID);

        return (app != null);
    }
}</pre>
<h3>Don’t Abuse It</h3>
<p>
  <br />I try to only use my service locator container when I have to.&#160; I use standard property or constructor injection whenever possible, but this does provide a nice way to be able to inject into my ValidationAttribute classes.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.jaltiere.com%2findex.php%2f2010%2f05%2f04%2fninject-with-mvc-and-validationattributes%2f"><img border="0" alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.jaltiere.com%2findex.php%2f2010%2f05%2f04%2fninject-with-mvc-and-validationattributes%2f" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.jaltiere.com/index.php/2010/05/04/ninject-with-mvc-and-validationattributes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery Grid Data with jqGrid</title>
		<link>http://www.jaltiere.com/index.php/2010/04/27/jquery-grid-data-with-jqgrid/</link>
		<comments>http://www.jaltiere.com/index.php/2010/04/27/jquery-grid-data-with-jqgrid/#comments</comments>
		<pubDate>Tue, 27 Apr 2010 13:08:40 +0000</pubDate>
		<dc:creator>Jack Altiere</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[jqGrid]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://www.jaltiere.com/index.php/2010/04/27/jquery-grid-data-with-jqgrid/</guid>
		<description><![CDATA[Creating a grid of data is a common task when building a dynamic website.&#160; I recently started looking for a good grid component that would play nice with both JQuery and ASP.NET MVC.&#160; The solution I ended up with is jqGrid.&#160;&#160;&#160; I’m going to walk through a simple example of setting up a grid and [...]]]></description>
			<content:encoded><![CDATA[<p>Creating a grid of data is a common task when building a dynamic website.&#160; I recently started looking for a good grid component that would play nice with both JQuery and ASP.NET MVC.&#160; The solution I ended up with is <a href="http://www.trirand.com/blog/" target="_blank">jqGrid</a>.&#160;&#160;&#160; I’m going to walk through a simple example of setting up a grid and populating it via JSON with an MVC controller.&#160; I’ll also show how to add, edit and delete rows to the grid.</p>
<h3>Setup    </p>
</h3>
<p>First, I created a simple User table and generated my Linq to SQL classes.&#160; I just want to show a simple grid of users, showing ID, First Name, Last Name, Email address and Birthday.&#160; When we are done, the finished grid will look something like this:</p>
<p><a href="http://www.jaltiere.com/wp-content/uploads/2010/04/grid1.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="grid" border="0" alt="grid" src="http://www.jaltiere.com/wp-content/uploads/2010/04/grid_thumb1.png" width="502" height="155" /></a> </p>
<p>One thing that I like about this grid is that it supports <a href="http://jqueryui.com/" target="_blank">jQuery UI</a> right out of the box.&#160; After downloading jQuery UI and jqGrid and following the installation instructions, just reference the relevent .css and .js files to get started, which I did in a master page:</p>
<pre class="brush: xml;">&lt;link href=&quot;../../Content/jquery-ui-1.8.custom.css&quot; rel=&quot;Stylesheet&quot; type=&quot;text/css&quot; /&gt;
&lt;link href=&quot;../../Content/ui.jqgrid.css&quot; rel=&quot;Stylesheet&quot; type=&quot;text/css&quot; /&gt;
&lt;script src=&quot;http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;../../Scripts/jquery-ui-1.8.custom.min.js&quot; type=&quot;text/javascript&quot; &gt;&lt;/script&gt;
&lt;script src=&quot;../../Scripts/grid.locale-en.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;../../Scripts/jquery.jqGrid.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;../../Scripts/grid.custom.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;</pre>
<h3>HTML </p>
</h3>
<p>The first thing I want to do is set up my grid on the client site.&#160; This requires two parts.&#160; The first is the HTML landing spot for the grid, pager and search box, which looks like this:</p>
<pre class="brush: xml;">&lt;div id=&quot;search&quot;&gt;&lt;/div&gt;
&lt;table id=&quot;grid&quot; class=&quot;scroll&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot;&gt;&lt;/table&gt;
&lt;div id=&quot;pager&quot; class=&quot;scroll&quot; style=&quot;text-align:center;&quot;&gt;&lt;/div&gt;</pre>
<h3>Javascript&#160; </h3>
<p>
  <br />The next part is the Javascript that takes care of configuring our grid and hooking it up to the HTML elements on the page.</p>
<pre class="brush: js;">    $(document).ready(function() {
        jQuery(&quot;#grid&quot;).jqGrid({
            url: '/Home/SampleGridData/',
            datatype: 'json',
            mtype: 'POST',
            colNames: ['Id', 'First Name', 'Last Name', 'Email', 'Birthday'],
            colModel: [
              { name: 'UserID', index: 'UserID', width: 60, align: 'center', editable: true, editrules: { edithidden: false} },
              { name: 'FirstName', index: 'FirstName', width: 200, align: 'center', sortable: true, editable: true, edittype: 'text', editrules: { required: true} },
              { name: 'LastName', index: 'LastName', width: 200, align: 'center', sortable: true, editable: true, edittype: 'text', editrules: { required: true} },
              { name: 'Email', index: 'Email', width: 200, align: 'center', sortable: true, editable: true, edittype: 'text', editrules: { required: true, email: true} },
              { name: 'Birthday', index: 'Birthday', width: 200, align: 'center', sortable: true, editable: true, editrules: { required: true }
            ],
            pager: jQuery('#pager'),
            rowNum: 10,
            rowList: [5, 10, 20, 50],
            sortname: 'UserID',
            sortorder: &quot;asc&quot;,
            viewrecords: true,
            imgpath: '/Content/Images',
            caption: 'JqGrid Sample',
            scrollOffset: 0
        });

        jQuery(&quot;#grid&quot;).jqGrid('navGrid', '#pager',
            { edit: true, add: true, del: true, search: false },
            { url: &quot;/Home/EditSampleGrid&quot;, closeAfterEdit: true, beforeShowForm: function(formid) { $(&quot;#tr_UserID&quot;, formid).hide(); $(&quot;#Birthday&quot;).datepicker(); } },
            { url: &quot;/Home/AddSampleGrid&quot;, closeAfterAdd: true, beforeShowForm: function(formid) { $(&quot;#tr_UserID&quot;, formid).hide(); $(&quot;#Birthday&quot;).datepicker(); } },
            { url: &quot;/Home/DeleteSampleGrid&quot; }, {});

        $(&quot;#search&quot;).filterGrid(&quot;#grid&quot;, {
            gridModel: false,
            filterModel: [{
                label: 'Search',
                name: 'search',
                stype: 'text'
            }]
       });
 });</pre>
<p>This really isn’t as bad as it looks. Once you start getting into jqGrid, I suggest spending some time getting familiar with <a href="http://www.trirand.com/jqgridwiki/doku.php" target="_blank">the wiki</a>, I spent a lot of time there learning how the plugin works.&#160; I will explain some of the important pieces.&#160; First, the url above is set to /Home/SampleGridData.&#160; This means that I have a method in my home controller called SampleGridData that is supplying me with the data to fill the grid.&#160; The format that jqGrid expects is pretty particuliar, you can see from <a href="http://www.secondpersonplural.ca/jqgriddocs/_2eb0f6jhe.htm" target="_blank">the documentation</a> what is expected.&#160; </p>
<h3>Grid Configuration</h3>
<p>
  <br />There are a lot of options available to configure in the grid.&#160; I want to quickly touch on some of the options I used in this sample.&#160; A lot of your configuration is going to happen in the colModel section.&#160; Here you can set up the width of your fields, the data types, etc.&#160; More importantly, you can set up which columns are hidden, and what the validation rules are for your columns.&#160; I didn’t show it, but you can also set up custom field validation as well as custom data formatting rules.&#160; I used the editrules section for each column to mark any fields as required that I wanted, and I also took advantage of being able to set up my Email field as type ‘email’&#8217;.&#160; This allows the grid to check to see if the input is in the correct format.&#160; You can also make any column sortable by just applying the sortable: true parameter.</p>
<h3>C#</h3>
<p>
  <br />This method is what I’m using to initially load the grid data.&#160; As you can see, the code is fairly straight forward:</p>
<pre class="brush: csharp;">public ActionResult SampleGridData(string sidx, string sord, int page, int rows, string search)
{
    var db = new BlogSamplesDataContext();

    var pageIndex = Convert.ToInt32(page) - 1;
    var pageSize = rows;
    var totalRecords = db.Users.Count();
    var totalPages = (int)Math.Ceiling(totalRecords / (float)pageSize);

    // This is possible because I'm using the LINQ Dynamic Query Library
    var users = db.Users
            .OrderBy(sidx + &quot; &quot; + sord)
            .Skip(pageIndex * pageSize)
            .Take(pageSize).AsQueryable();

    var jsonData = new
    {
        total = totalPages,
        page = page,
        records = totalRecords,
        rows = (
            from User u in users
            select new {
                i = u.UserID,
                cell = new[] { u.UserID.ToString(), u.FirstName, u.LastName, u.Email, u.Birthday.Value.ToShortDateString() }
        }).ToArray()
    };

    return Json(jsonData);
}</pre>
<p>For the sake of the example I’m doing everything in the controller rather than implementing a repository, which I would normally do.&#160; One thing to point out, I did not choose the parameter names in this method. (with the exception of search, but we’ll get to that later)&#160; This is the data that jqGrid is going to post to my controller to handle sorting, paging, filtering, etc.</p>
<p>You may notice above that my OrderBy statement is taking a string parameter.&#160; This is possible through the <a href="http://msdn.microsoft.com/en-us/vcsharp/bb894665.aspx" target="_blank">LINQ Dynamic Query Library</a>, which allows you to use string based expressions rather than type safe Lambda expressions in your queries.&#160; Using this library allows me to use the sorting and ordering columns that are passed in from the grid directly.&#160; Make sure that your client indexes match your database column names or this will not work!&#160; </p>
<h3>Adding A Record</h3>
<p>
  <br />Now that the grid is successfully loading data, the next step is adding records from the grid.&#160; This actually isn’t very hard using jqGrid.&#160;&#160; If you press the Add icon in the bottom left of the grid, you will be presented with a dialog with all the fields set up, like this one:</p>
<p><a href="http://www.jaltiere.com/wp-content/uploads/2010/04/add.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="add" border="0" alt="add" src="http://www.jaltiere.com/wp-content/uploads/2010/04/add_thumb.png" width="391" height="227" /></a> </p>
<p>This form is constructed using the properties set up in the ‘colModel’ section of the grid call.&#160; Every field set up with the property of editable: true will be displayed on this form.&#160;&#160; If you notice, the ID field is not showing up in this example, although it was marked as an editable field in my grid setup.&#160; The reason for this is that I wanted to send the UserID to the controller, but I didn’t want the user to be able to edit it.&#160; To accomplish this, I added a little bit of jQuery to my grid setup and hid the column.&#160; At the same time, I leveraged jQuery UI and made my Birthday field a <a href="http://jqueryui.com/demos/datepicker/" target="_blank">datepicker</a>.&#160; I handled both of these things using the beforeShowForm event available in the grid.</p>
<pre class="brush: js;">{ url: &quot;/Home/EditSampleGrid&quot;, closeAfterEdit: true, beforeShowForm: function(formid) { $(&quot;#tr_UserID&quot;, formid).hide(); $(&quot;#Birthday&quot;).datepicker(); } },
{ url: &quot;/Home/AddSampleGrid&quot;, closeAfterAdd: true, beforeShowForm: function(formid) { $(&quot;#tr_UserID&quot;, formid).hide(); $(&quot;#Birthday&quot;).datepicker(); } },</pre>
<p>
  <br />The grid assigns ID’s in this way according to your column indexes.&#160; Since my ID field is named UserID, I can access it’s row with the selector of $(“#tr_UserID”) and my birthday textbox with the selector of $(“#Birthday”).&#160; As you can see from the client code, I’m setting up a method in my Home controller called AddSampleGrid to process my grid data.</p>
<pre class="brush: csharp;">public ActionResult AddSampleGrid(string FirstName, string LastName, string Email, string Birthday)
{
    try
    {
        var db = new BlogSamplesDataContext();

        DateTime bDay;
        if (!DateTime.TryParse(Birthday, out bDay))
            bDay = DateTime.MinValue;

        var user = new User
                       {
                           FirstName = FirstName,
                           LastName = LastName,
                           Email = Email,
                           Birthday = bDay
                       };

        db.Users.InsertOnSubmit(user);
        db.SubmitChanges();

        return Json(true);
    }
    catch (Exception)
    {
        // Do some error logging stuff, handle exception, etc.
        return Json(false);
    }
}</pre>
<p>&#160;</p>
<p>The grid will pass the parameters according to their name on the colModel, so catching them and setting them up is a breeze. </p>
<h3>Editing a Record</h3>
<p>
  <br />Editing a record is basically the same process as adding, the only difference is that you are sending the ID along with the rest of the data.&#160; You could easily combine the two operations into the same controller method if you want, although I normally separate them.&#160; I’m using the same trick to hide the ID field from the edit form, but the key here is that it’s actually being sent to the controller so we can use it to figure out which record is being edited.</p>
<p>The dialog for editing records is nice in jqGrid.&#160; It allows you to edit the highlighted row, and you can also use the navigation errors on the bottom left of the dialog to cycle between records.</p>
<p><a href="http://www.jaltiere.com/wp-content/uploads/2010/04/edit.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="edit" border="0" alt="edit" src="http://www.jaltiere.com/wp-content/uploads/2010/04/edit_thumb.png" width="340" height="217" /></a> </p>
<p>The controller method for editing a record is similar to the add method, we just have to load the correct user and edit the fields as shown here.</p>
<pre class="brush: csharp;">public ActionResult EditSampleGrid(int UserID, string FirstName, string LastName, string Email, string Birthday)
{
    try
    {
        var db = new BlogSamplesDataContext();

        DateTime bDay;
        if (!DateTime.TryParse(Birthday, out bDay))
            bDay = DateTime.MinValue;

        var query = from u in db.Users
                    where u.UserID.Equals(UserID)
                    select u;

        var user = query.First();
        user.FirstName = FirstName;
        user.LastName = LastName;
        user.Email = Email;
        user.Birthday = bDay;

        db.SubmitChanges();

        return Json(true);
    }
    catch (Exception)
    {
        // Do some error logging stuff, handle exception, etc.
        return Json(false);
    }
}</pre>
<p>
  <br />If you notice, I’m passing the birthday as a string.&#160; This is intentional, I just find that this makes dealing with dates much easier because you don’t have to convert between a Javascript date and a .NET date.</p>
<h3>Deleting a Record<br />
  <br /></h3>
<p>
  <br />Deleting a record is trivial with jqGrid.&#160; The grid will pass a parameter called id, and you can use that to delete the record in question in your controller.</p>
<pre class="brush: csharp;">public ActionResult DeleteSampleGrid(int id)
{
    try
    {
        var db = new BlogSamplesDataContext();
        var query = from u in db.Users
                    where u.UserID.Equals(id)
                    select u;

        var user = query.First();

        db.Users.DeleteOnSubmit(user);
        db.SubmitChanges();

        return Json(true);
    }
    catch (Exception)
    {
        // Do some error logging stuff, handle exception, etc.
        return Json(false);
    }
}</pre>
<h3>Filtering</h3>
<p>
  <br />The last part I want to talk about is implementing a grid filter.&#160; Out of the box, the grid supports a filter that allows you to search specific fields.&#160; You can see an example of this here:</p>
<p><a href="http://www.jaltiere.com/wp-content/uploads/2010/04/defaultfilter.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="defaultfilter" border="0" alt="defaultfilter" src="http://www.jaltiere.com/wp-content/uploads/2010/04/defaultfilter_thumb.png" width="372" height="145" /></a> </p>
<p>While this is nice, I generally like to implement a more generic filter.&#160;&#160; I want the user to just have to type in what they are looking for, and I’ll search all the relevant fields.&#160; This is pretty easy, and it’s what I was using the search parameter for in the original SampleGridData method.&#160; With just a quick check to see if I have a search string and a minor modification to the data call, I can quickly filter the grid on any field I want to.</p>
<pre class="brush: csharp;">if (!string.IsNullOrEmpty(search))
{
    // This is possible because I'm using the LINQ Dynamic Query Library
    var users = (from u in db.Users
             where u.FirstName.Contains(search)
                       || u.LastName.Contains(search)
                       || u.Email.Contains(search)
             select u).OrderBy(sidx + &quot; &quot; + sord)
                      .Skip(pageIndex*pageSize)
                      .Take(pageSize)
                      .AsQueryable();

    var totalRecords = users.Count();
    var totalPages = (int)Math.Ceiling(totalRecords / (float)pageSize);
}</pre>
<p>If this is the way you want to go, be sure to turn off the default search parameter.&#160; You can toggle all of the icons on the bottom left through these grid options:</p>
<pre class="brush: js;">jQuery(&quot;#grid&quot;).jqGrid('navGrid', '#pager',
{ edit: true, add: true, del: true, search: false },</pre>
<p></p>
<h3>Final Thoughts</h3>
<p>
  <br />All in all, I feel that jqGrid is a nice plugin that allows you to quickly and easily set up grid data on your site.&#160; If you are already using jQuery UI, the fact that this grid integrates well with it is just icing on the cake.&#160; I’ve only scratched the surface with what is possible using this plugin, so be sure to check out the product wiki.&#160; The good news is that this product is well documented, and there are a lot of examples available to get you up and going.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.jaltiere.com%2findex.php%2f2010%2f04%2f27%2fjquery-grid-data-with-jqgrid%2f"><img border="0" alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.jaltiere.com%2findex.php%2f2010%2f04%2f27%2fjquery-grid-data-with-jqgrid%2f" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.jaltiere.com/index.php/2010/04/27/jquery-grid-data-with-jqgrid/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Blog Setup</title>
		<link>http://www.jaltiere.com/index.php/2010/04/12/blog-setup/</link>
		<comments>http://www.jaltiere.com/index.php/2010/04/12/blog-setup/#comments</comments>
		<pubDate>Mon, 12 Apr 2010 19:15:41 +0000</pubDate>
		<dc:creator>Jack Altiere</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[blog]]></category>
		<category><![CDATA[setup]]></category>

		<guid isPermaLink="false">http://www.jaltiere.com/?p=145</guid>
		<description><![CDATA[I have been trying different combinations of tools / plugins for my blog, and now that I’m finally happy with the setup I have I thought I’d share how I’m doing things. First, I host my own instance of WordPress to handle the site.&#160; There are several different blog engines available, but WordPress is the [...]]]></description>
			<content:encoded><![CDATA[<p>I have been trying different combinations of tools / plugins for my blog, and now that I’m finally happy with the setup I have I thought I’d share how I’m doing things.</p>
<p>First, I host my own instance of <a href="http://wordpress.org/" target="_blank">WordPress</a> to handle the site.&#160; There are several different blog engines available, but WordPress is the only one that I have any real experience with.&#160; It meets all of my requirements for a blog engine.</p>
<ol>
<li>There are a lot of free templates available.&#160; This is important to me, because I’d like to have a decent looking site and I’m by not a good graphic artist. </li>
<li>It’s easy to update.&#160; WordPress used to be a pain to upgrade, but now it is very easy.&#160; You can upgrade to a new version with the click of a link from the administrative interface. </li>
<li>There are plenty of nice third party plugins and widgets available.&#160; I want to focus on writing content, not playing around with my website. </li>
<li>It’s written in PHP, so it’s easy to get in there and modify stuff if I absolutely have to.</li>
</ol>
<p>Next, I publish all of my content with <a href="http://download.live.com/writer?wa=wsignin1.0" target="_blank">Windows Live Writer</a>.&#160; This tool is simple, and it integrates well with WordPress.&#160; It does have one quirk that I had to get around however.&#160; I want to be able to edit content from more than 1 computer, and I don’t want to have to carry around a USB drive to accomplish this.&#160; To solve the first part of the problem, I’m using <a href="https://www.mesh.com/" target="_blank">Live Mesh</a>.&#160; With this, you can set up folders that are shared across as many PC’s as you want to.&#160; You get 5 GB of space for free, and it’s a snap to install.&#160; I installed Mesh on the computers I would potentially be writing content with, and then I created a Mesh folder called My Weblog Posts.&#160; In this folder I have a Drafts folder and a Recent Posts folder.&#160; This is important, because it addresses the pain point I have with Live Writer.</p>
<p>In Live Writer, you can’t specify where you want your drafts to be saved.&#160; By default drafts get saved to Documents / My Weblog Posts / Drafts.&#160; What I did was delete this directory after installing Live Writer.&#160; Then I created a symbolic link to the directory I set up in Mesh, which ends up sitting on my Desktop with instructions found <a href="http://www.howtogeek.com/howto/windows-vista/using-symlinks-in-windows-vista/" target="_blank">here</a>.&#160; I’ve done this on both Windows&#160; 7 and Vista machines.&#160; Make sure you run cmd.exe as an Administrator so you have sufficient privileges to create the link.&#160; So when I’m done, my Documents directory has a link to my Mesh folder structure to save Drafts, as seen by the icon next to the folder below.</p>
<p><a href="http://www.jaltiere.com/wp-content/uploads/2010/04/symlink.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="symlink" border="0" alt="symlink" src="http://www.jaltiere.com/wp-content/uploads/2010/04/symlink_thumb.png" width="142" height="25" /></a> </p>
<p>I give credit to <a href="http://www.codethinked.com/" target="_blank">Justin Etheridge</a> for this idea, this came out of a conversation we had at the <a href="http://live.visitmix.com/?wa=wsignin1.0" target="_blank">Mix 10 conference</a> last month.&#160; I don’t remember exactly how he does it, but our conversation inspired my new setup.</p>
<p>Another thing that I have changed around a lot is my code syntax highlighter.&#160; I finally settled on using a product called (strangely enough) <a href="http://alexgorbatchev.com/wiki/SyntaxHighlighter" target="_blank">SyntaxHighlighter</a>.&#160; If you are reading my blog on an aggregator such as Google Reader you are missing out, but this is what the code looks like on my actual site:</p>
<p><a href="http://www.jaltiere.com/wp-content/uploads/2010/04/syntax.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="syntax" border="0" alt="syntax" src="http://www.jaltiere.com/wp-content/uploads/2010/04/syntax_thumb.png" width="541" height="121" /></a> </p>
<p>This tool does a fantastic job, and it supports a lot of different languages.&#160; To make this even easier to use, I found a WordPress plugin called <a href="http://www.viper007bond.com/wordpress-plugins/syntaxhighlighter/" target="_blank">SyntaxHighlighter Evolved</a> that automatically puts the required Javascript calls in my theme so I don’t have to edit my template by hand.&#160; I also use a Live Writer plugin called <a href="http://precode.codeplex.com/Wikipage" target="_blank">PreCode</a> that allows me to copy and paste stuff directly into Live Writer and be formatted with the correct “pre” tags for the language I’m pasting.&#160; It fixed indentation with the click of a button, which is helpful since I often don’t include the namespace information, etc. when posting fragments.&#160; It also allows you to choose what the target language is from a drop down list.&#160; This has made pasting code snippets a breeze, I wish I would have stumbled across this sooner.</p>
<p>For image editing, I use <a href="http://www.getpaint.net/" target="_blank">Paint.Net</a>.&#160; If you aren’t already using this tool I highly recommend it.&#160; It’s everything that Paint SHOULD be.</p>
<p>Lastly, I use <a href="http://www.google.com/analytics/" target="_blank">Google Analytics</a> to look at how traffic to my site is looking.&#160; They added a new feature called Intelligence that allows you to set up custom daily, weekly, and monthly alerts.&#160; This allows you to get email if certain criteria happen.&#160; For example, you can set up daily alerts to let you know that you got 50 new visitors, or that you got 500 visits, or that someone reached your site by using the keyword jquery in a search 10 times.&#160; It really is a cool feature, and they have a few pre-canned alerts you can use to get you started.</p>
<p>That’s my setup.&#160; I’m able to edit drafts on any of my PC’s and I finally have a syntax highlighting product that I’m happy with.&#160; One thing I should point out, my method of sharing drafts should only be used for drafts.&#160; I think that this would break down if you tried to edit posts that are already published from a different PC because of how Live Writer generates an ID for each post.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jaltiere.com/index.php/2010/04/12/blog-setup/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JQuery delegates</title>
		<link>http://www.jaltiere.com/index.php/2010/04/08/jquery-delegates/</link>
		<comments>http://www.jaltiere.com/index.php/2010/04/08/jquery-delegates/#comments</comments>
		<pubDate>Thu, 08 Apr 2010 13:03:11 +0000</pubDate>
		<dc:creator>Jack Altiere</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[delegate]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://www.jaltiere.com/?p=138</guid>
		<description><![CDATA[I’ve had a few projects where I needed to update information on a site at a regular interval, and it’s always a better user experience if you do it asynchronously.&#160;&#160;&#160; I always like to come up with a functional example, so I’m going to write a quick MVC page that displays all the images in [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve had a few projects where I needed to update information on a site at a regular interval, and it’s always a better user experience if you do it asynchronously.&#160;&#160;&#160; I always like to come up with a functional example, so I’m going to write a quick MVC page that displays all the images in a directory.&#160; The catch is that I want add any pictures to the page that are added to this directory without having to refresh the page.&#160;&#160; Another thing I’d like to do is use the data capabilities in JQuery to store additional information about each image.</p>
<p>First I wanted to create a class to hold the additional data so that I can make a strongly typed view with it.&#160; This is what I came up with:</p>
<pre class="brush: csharp;">[Serializable]
public class UploadedImage
{
    public int Id { get; set; }
    public string ImageName { get; set; }
    public string ImagePath { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }
}</pre>
<p>
  <br />After creating my class, I created my strongly typed view to accept a List&lt;UploadedImage&gt;.&#160; The next step was to add the controller method to display the view.&#160; In this method, I wanted to load the initial list of images present in the directory and pass them to the view.</p>
<pre class="brush: csharp;">public ActionResult Timer()
{
    var photos = new List&lt;UploadedImage&gt;();
    var dir = new DirectoryInfo(ConfigurationParser.GetAppSettingString(&quot;PhotoDirectory&quot;));
    var counter = 1;
    foreach (var file in dir.GetFiles())
    {
        var img = Image.FromFile(file.FullName);
        var photo = new UploadedImage
                        {
                            Id = counter,
                            ImageName = file.Name,
                            ImagePath = string.Format(&quot;../../Content/Images/Photos/{0}&quot;, file.Name),
                            Height = img.Height,
                            Width = img.Width
                        };
        photos.Add(photo);
        counter ++;
    }

    ViewData.Model = photos;
    return View();
}</pre>
<p>
  <br />This is pretty self explanatory, I just loaded the photos from the directory, gathered some information about them, and assigned each an arbitrary ID.&#160; The last step was to put them all in a list and pass them to the view. </p>
<p>Since the focus of this exercise is JQuery, the bulk of our work is going to take place in the view.&#160; I’m not doing anything complicated to display the images.&#160; All I”m doing is using an unordered list to display all of the thumbnails, and creating a div that I will use to display additional information about the image in a pop-up when it is clicked.</p>
<pre class="brush: csharp;">&lt;h2&gt;JQuery Delegate Example&lt;/h2&gt;

    &lt;ul class=&quot;thumbnails&quot;&gt;
        &lt;% foreach (var item in Model) { %&gt;
        &lt;li&gt;&lt;a href=&quot;#&quot;&gt;&lt;img id=&quot;img&lt;%= item.Id %&gt;&quot; src=&quot;&lt;%=Html.Encode(item.ImagePath) %&gt;&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/li&gt;
        &lt;% } %&gt;
    &lt;/ul&gt;

    &lt;div id=&quot;popupContact&quot;&gt;
    &lt;a id=&quot;popupContactClose&quot;&gt;x&lt;/a&gt;
    &lt;span id=&quot;imgName&quot;&gt;&lt;/span&gt;
    &lt;p id=&quot;contactArea&quot;&gt;  

    &lt;/p&gt;
&lt;/div&gt;
&lt;div id=&quot;backgroundPopup&quot;&gt;&lt;/div&gt;  </pre>
<p>
  <br />That leaves us with the client code.&#160; The first obstacle we have to overcome is that we need a way to monitor the photo directory to figure out when new images are added.&#160; I ended up using a JQuery plugin I found called <a href="http://benalman.com/projects/jquery-dotimeout-plugin/" target="_blank">doTimeout</a> that works really well.&#160; This sets up the framework for the polling operation, to close the loop I created a web service to pass back the list of images in the directory.</p>
<pre class="brush: csharp;">[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List&lt;UploadedImage&gt; LoadImages()
{
    var photos = new List&lt;UploadedImage&gt;();
    var dir = new DirectoryInfo(ConfigurationParser.GetAppSettingString(&quot;PhotoDirectory&quot;));
    foreach (var file in dir.GetFiles())
    {
        var img = Image.FromFile(file.FullName);
        var photo = new UploadedImage
        {
            ImageName = file.Name,
            ImagePath = string.Format(&quot;../../Content/Images/Photos/{0}&quot;, file.Name),
            Height = img.Height,
            Width = img.Width
        };
        photos.Add(photo);
    }

    return photos;
}</pre>
<p>
  <br />This method is in my .asmx web service.&#160; The important thing to point out is that I specified that the response was going to be in JSON.&#160; I can just return my List&lt;UploadedImage&gt; type, and it will be automatically be put into JSON where my client code can access it.</p>
<p>Before I worry about setting up the timer, I want to be able to attach data from the controller to my JSON objects.&#160; My reasoning for this is because I don’t want to have to use unnecessary web service calls to retrieve this information if I already have it.&#160; The reason I want to collect this data is that I want to display it in the pop up when someone clicks on an image.&#160; To do this, I am going to use the jQuery.data() method.&#160; When I wrote this code, it felt a little clunky, so if anyone has an idea for a better way to accomplish this leave me a comment.</p>
<pre class="brush: js;">var images = new Array();

$(document).ready(function() {
    // This is messy, I wonder if there is a better way to do this?
    &lt;% foreach (var item in Model) { %&gt;
        images[images.length] = &quot;&lt;%= item.ImageName %&gt;&quot;;
        $(&quot;#img&lt;%= item.Id %&gt;&quot;).data('info', {
                Id: &lt;%= item.Id %&gt;,
                Name: &quot;&lt;%= item.ImageName %&gt;&quot;,
                Width: &lt;%= item.Width %&gt;,
                Height: &lt;%= item.Height %&gt;
        });
    &lt;% } %&gt;
});</pre>
<p>
  <br />In addition to setting my data information, I’m populating an array that I had set up to keep track of what images are already displayed.&#160; It’s easy to go off down a rabbit hole when you are coming up with an example, so rather than do it the right way and only bringing back images that were uploaded since the last time I checked, I’m just pulling&#160; them all back for simplicity’s sake and adding ones that aren’t there yet.&#160; The other thing I added that isn’t shown here is some code to display my pop up.&#160;&#160; </p>
<p>The next thing to do is to set up the loop and poll the directory for new images, and then display any images that were added.</p>
<pre class="brush: js;">// Load the photos every 10 seconds.
$.doTimeout('tmrPhotoSearch', 10000, function() {
    $.ajax({
        type: &quot;POST&quot;,
        contentType: &quot;application/json; charset=utf-8&quot;,
        url: &quot;../DataService.asmx/LoadImages&quot;,
        data: &quot;{}&quot;,
        dataType: &quot;json&quot;,
        success: function(result) {
            ProcessImages(result.d);
        }
    });
    return true;
});

function ProcessImages(result)
{
    var max = 0;
    var data;
    $(&quot;.thumbnails a img&quot;).each(function() {
        data = $(this).data('info');
        if (data) {
            if (data.Id &gt; max)
                max = data.Id
        }
    });
    max++;

    var item = '';
    var id = 0;
    $.each(result, function(key, value) { 

        if (jQuery.inArray(value.ImageName, images) == -1) {
            item = &quot;&lt;li&gt;&lt;a href='#'&gt;&lt;img id='img&quot; + max + &quot;' src='&quot; + value.ImagePath + &quot;' alt='' /&gt;&lt;/a&gt;&lt;/li&gt;&quot;;
            $(&quot;.thumbnails&quot;).append(item);

            images[images.length] = value.ImageName;

            id = &quot;#img&quot; + max;
            $(id).data('info', {
                    Id: max,
                    Name: value.ImageName,
                    Width: value.Width,
                    Height: value.Height
            }); 

            max++;
        }
    });
}  </pre>
<p></p>
<p>One thing about the web service call I should point out, be sure to include an empty data parameter if you don’t have any parameters.&#160; If you don’t, the content-length header won’t be generated and you could run into problems.&#160; Notice that my service is looking for a JSON result back, and on success it’s calling my ProcessImages method, passing in the web service response.&#160;&#160; The first part of my processing method is hokey, it’s just figuring out what the max ID is that already exists and adding 1 to it.&#160; I would definitely not do it this way for a real app, and I would certainly have more error handling built in.&#160; With JQuery, I’m able to loop through the results directly with the .each method since my JSON has already been translated.&#160; All I do is check each image, and add any that are not already present dynamically to the DOM at the end of the list with the append method.&#160; I also update my array to put the new image in there so it’s not added more than 1 time, and I add all the meta data using the .data method like before.</p>
<p>The last bit of logic is to set up my event for displaying the pop up when an image is clicked.&#160; I added this to my $(document).ready function to attach the click event.&#160; I’m also retrieving the information from the JQuery cache about the clicked image and showing it in the popup.</p>
<pre class="brush: js;">$(&quot;.thumbnails a img&quot;).click(function() {
    var data = $(this).data('info');
    var html = &quot;&lt;b&gt;&quot; + data.Name + &quot;&lt;/b&gt;&lt;br/&gt;&lt;br/&gt;&quot;
             + &quot;&lt;i&gt;ID: &quot; + data.Id + &quot;&lt;/i&gt;&lt;br/&gt;&quot;
             + &quot;&lt;i&gt;Height: &quot; + data.Height + &quot;&lt;/i&gt;&lt;br/&gt;&quot;
             + &quot;&lt;i&gt;Width: &quot; + data.Width + &quot;&lt;/i&gt;&lt;br/&gt;&quot;;
    $(&quot;#imgName&quot;).html(html);
    loadPopup();
});</pre>
<p>After putting a few sample images in my photo folder and running this, you can see that it grabs the 3 images that are there and shows them.</p>
<p><a href="http://www.jaltiere.com/wp-content/uploads/2010/04/3photos.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="3photos" border="0" alt="3photos" src="http://www.jaltiere.com/wp-content/uploads/2010/04/3photos_thumb.png" width="423" height="192" /></a> </p>
<p>We can also see that clicking on one of these images successfully brings up our popup window with the attributes we put in the JQuery cache.</p>
<p><a href="http://www.jaltiere.com/wp-content/uploads/2010/04/popup.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="popup" border="0" alt="popup" src="http://www.jaltiere.com/wp-content/uploads/2010/04/popup_thumb.png" width="383" height="349" /></a> </p>
<p>The next thing to do is make sure that the timer is running.&#160; The best way to do that in my opinion is with <a href="http://getfirebug.com/" target="_blank">Firebug</a>.&#160; Firebug is a tremendous tool, and a great way to <a href="http://encosia.com/2009/09/21/updated-see-how-i-used-firebug-to-learn-jquery/" target="_blank">learn JQuery</a> quickly. Using the “Net” tab, I can watch my asynchronous requests being sent off to the web service.</p>
<p><a href="http://www.jaltiere.com/wp-content/uploads/2010/04/firebug.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="firebug" border="0" alt="firebug" src="http://www.jaltiere.com/wp-content/uploads/2010/04/firebug_thumb.png" width="465" height="241" /></a> </p>
<p>Now I’m going to keep the page up and drop an image into the directory.&#160;&#160; You can see below that the image was added successfully to the page, but we have a problem.</p>
<p><a href="http://www.jaltiere.com/wp-content/uploads/2010/04/4photos.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="4photos" border="0" alt="4photos" src="http://www.jaltiere.com/wp-content/uploads/2010/04/4photos_thumb.png" width="494" height="195" /></a> </p>
<p>When we click the new image, our pop up doesn’t work.&#160; Although it took a little while to get here, this is actually the point of my example.&#160; The problem is with our click event on the images.&#160; When the event was wired up, the 4th image didn’t exist yet, so it obviously wasn’t selected by the JQuery selector statement, therefore no event gets attached to it.&#160; </p>
<p>The solution to this problem is the <a href="http://api.jquery.com/delegate/" target="_blank">JQuery delegate method</a>.&#160; Basically what this is doing is attaching the event to a parent DOM element, so any future elements that fit the selector that you add automatically get the event attached.&#160; To get this to work, all we have to do is change our click event to look like this:</p>
<pre class="brush: js;">$(&quot;.thumbnails&quot;).delegate(&quot;a img&quot;, &quot;click&quot;, function() {
    var data = $(this).data('info');
    var html = &quot;&lt;b&gt;&quot; + data.Name + &quot;&lt;/b&gt;&lt;br/&gt;&lt;br/&gt;&quot;
             + &quot;&lt;i&gt;ID: &quot; + data.Id + &quot;&lt;/i&gt;&lt;br/&gt;&quot;
             + &quot;&lt;i&gt;Height: &quot; + data.Height + &quot;&lt;/i&gt;&lt;br/&gt;&quot;
             + &quot;&lt;i&gt;Width: &quot; + data.Width + &quot;&lt;/i&gt;&lt;br/&gt;&quot;;
    $(&quot;#imgName&quot;).html(html);
    loadPopup();
});</pre>
<p>
  <br />After this change, I removed the 4th image from the directory and ran the page again. This time when I added the 4th image and clicked it, the popup appeared like we expected it to.</p>
<p><a href="http://www.jaltiere.com/wp-content/uploads/2010/04/popup4.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="popup4" border="0" alt="popup4" src="http://www.jaltiere.com/wp-content/uploads/2010/04/popup4_thumb.png" width="491" height="356" /></a> </p>
<p>There are a few things I’d like to point out before wrapping up.&#160; First, the delegate method is only available in JQuery 1.4.2 and later.&#160; I think the version of JQuery that came with my MVC install was 1.4.1, so keep this in mind if you have a problem.&#160; In fact, probably the best way to get JQuery is through a <a href="http://en.wikipedia.org/wiki/Content_delivery_network" target="_blank">content delivery network</a>. (I use the minified version specified <a href="http://www.asp.net/ajaxLibrary/cdn.ashx" target="_blank">here</a>) The other thing that I’d like to point out is that the same capability is available in the <a href="http://api.jquery.com/live/" target="_blank">JQuery .live method</a>.&#160; This method was introduced in version 1.3 of JQuery.&#160; The difference is that the delegate method allows you to bind to a specific DOM element, where the live method binds to the root of the DOM tree.&#160; This makes the delegate method faster, since it doesn’t have to bubble up as far.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.jaltiere.com%2f%3fp%3d138"><img border="0" alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.jaltiere.com%2f%3fp%3d138" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.jaltiere.com/index.php/2010/04/08/jquery-delegates/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Making web service calls with JQuery</title>
		<link>http://www.jaltiere.com/index.php/2010/04/05/making-web-service-calls-with-jquery/</link>
		<comments>http://www.jaltiere.com/index.php/2010/04/05/making-web-service-calls-with-jquery/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 02:21:54 +0000</pubDate>
		<dc:creator>Jack Altiere</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[web service]]></category>

		<guid isPermaLink="false">http://www.jaltiere.com/?p=124</guid>
		<description><![CDATA[JQuery is an amazing Javascript library.&#160;&#160; If you haven’t used it yet, you are REALLY missing out.&#160; This article is going to talk about how you can use JQuery to make an AJAX call from an MVC application, and how you can receive JSON rather than XML from the web service. First we’ll deal with [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://jquery.com/">JQuery</a> is an amazing Javascript library.&#160;&#160; If you haven’t used it yet, you are REALLY missing out.&#160; This article is going to talk about how you can use JQuery to make an AJAX call from an MVC application, and how you can receive <a href="http://www.json.org/">JSON</a> rather than XML from the web service.</p>
<p>First we’ll deal with the why.&#160; Why would we want to receive JSON rather than XML to our web service?&#160; To me, the answer to that starts with the fact that if we’re making an AJAX call, we’re going to do something with the results in client code.&#160; It makes sense to use a format that is inherently understood by Javascript, which is what the client code is going to be written in most of the time.&#160; The fact that we can send JSON data to our .NET web service allows us to pass objects back and forth from .NET and Javascript easily.</p>
<p>Our use case is going to be relatively simple, I want to be able to add a user to our database from an HTML form, and update the user interface when the task is done asynchronously.&#160; I have a sample database with a very simple user table set up for this example.&#160; I created a .dbml file with LINQ to SQL for my data layer:</p>
<p><a href="http://www.jaltiere.com/wp-content/uploads/2010/04/data.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="data" border="0" alt="data" src="http://www.jaltiere.com/wp-content/uploads/2010/04/data_thumb.png" width="208" height="187" /></a>&#160;</p>
<p>I created an index view for my form, the code looks like this:</p>
<pre class="brush: xml;">&lt;fieldset&gt;
    &lt;legend&gt;Enter User Information&lt;/legend&gt;

    &lt;p&gt;
    &lt;label for=&quot;FirstName&quot;&gt;First Name&lt;/label&gt;
    &lt;input type=&quot;text&quot; id=&quot;FirstName&quot; /&gt;
    &lt;/p&gt;

    &lt;p&gt;
    &lt;label for=&quot;LastName&quot;&gt;Last Name&lt;/label&gt;
    &lt;input type=&quot;text&quot; id=&quot;LastName&quot; /&gt;
    &lt;/p&gt;

    &lt;p&gt;
    &lt;label for=&quot;Email&quot;&gt;Email&lt;/label&gt;
    &lt;input type=&quot;text&quot; id=&quot;Email&quot; /&gt;
    &lt;/p&gt;

    &lt;p&gt;
    &lt;label for=&quot;Phone&quot;&gt;Phone&lt;/label&gt;
    &lt;input type=&quot;text&quot; id=&quot;Phone&quot; /&gt;
    &lt;/p&gt;

&lt;/fieldset&gt;

&lt;br /&gt;

&lt;div class=&quot;buttons&quot;&gt;
    &lt;button type=&quot;submit&quot; class=&quot;positive&quot; name=&quot;save&quot; id=&quot;btnSave&quot;&gt;
        &lt;img src='&lt;%= Url.Content(&quot;~/Content/Images/apply.png&quot;) %&gt;' alt=&quot;&quot;/&gt;
        Save
    &lt;/button&gt;
&lt;/div&gt; 

&lt;br /&gt;&lt;br /&gt;
&lt;div id=&quot;result&quot;&gt;&lt;/div&gt;</pre>
<p></p>
<p>The div at the bottom is where I plan to show if my service call was successful or not.&#160; One thing I did here was use a tip I picked up by <a href="http://encosia.com/about-dave-ward/">Dave Ward</a> at <a href="http://www.encosia.com">Encosia.com</a> and make the ID’s of my inputs match the property names on my user object.&#160; This makes life easier on us later.&#160; Then, to fix up the look and feel of the site a little, I just add a little CSS:</p>
<pre class="brush: css;">fieldset {
    border: 1px solid #226078;
    background: #62B1D0;
    width: 320px;
    padding: 2px;
}
fieldset legend {
    border: 1px solid #226078;
    font-family: Tahoma;
    font-size: 9pt;
    font-weight: bold;
    background: #0776A0;
    color: #FF8500;
    padding: 6px;
}

label {
    display: block;
    float: left;
    font-family: Tahoma;
    font-size: 8pt;
    font-weight: bold;
    color: #024C68;
    width: 150px;
}

label:after { content: &quot;: &quot; }</pre>
<p>
  <br />This makes my end UI look (slightly) more presentable.&#160; I know, you envy my crazy user interface skills. </p>
<p><a href="http://www.jaltiere.com/wp-content/uploads/2010/04/interface.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="interface" border="0" alt="interface" src="http://www.jaltiere.com/wp-content/uploads/2010/04/interface_thumb.png" width="502" height="382" /></a> </p>
<p>The next thing to do is set up the JQuery code so that our button click even sends an asynchronous request to the web service.</p>
<pre class="brush: js;">&lt;script language=&quot;javascript&quot; type=&quot;text/javascript&quot;&gt;
    $(document).ready(function() {
        $(&quot;#btnSave&quot;).click(function(event) {
            var user = {};

            // Use JQuery to iterate over the text fields and build the object.
            $(':text').each(function() {
                user[this.id] = this.value;
            });

            // Create a data transfer object (DTO) with the proper structure.
            var DTO = { 'user': user };

            $.ajax({
                type: &quot;POST&quot;,
                contentType: &quot;application/json; charset=utf-8&quot;,
                url: &quot;DataService.asmx/AddUser&quot;,
                data: JSON.stringify(DTO),
                dataType: &quot;json&quot;,
                success: function(result) {
                    if (result.d)
                        $(&quot;#result&quot;).html(&quot;&lt;span style='color:#529214'&gt;User added successfully.&lt;/span&gt;&quot;);
                    else {
                        $(&quot;#result&quot;).html(&quot;&lt;span style='color:#d12f19'&gt;Operation failed.&lt;/span&gt;&quot;);
                    }
                }
            });
        });
    });
&lt;/script&gt;</pre>
<p>
  <br />In the above code, you will see why we named the textboxes the same as the user object properties.&#160; I used the JQuery each construct to loop through all the text boxes and populate the user object.&#160; This is a much cleaner way to populate the object than manually setting every property.&#160; The ajax call is pretty straight forward, I’m using the stringify method in the <a href="http://www.json.org/js.html" target="_blank">json2js</a> library to turn my string into valid JSON, and lastly I’m wrapping my user object in a data transfer object to make the client code a little cleaner.&#160; (another tip from Dave Ward)&#160; On success of the asynchronous call, I’m parsing the result to determine whether the user was added successfully or not.&#160; </p>
<p>Since I used LINQ to SQL to generate my objects, I decided to make it easy on myself by adding the “add user” logic in a partial user class.</p>
<pre class="brush: csharp;">public partial class User
{
    public void Add()
    {
        var db = new BlogSamplesDataContext();
        db.Users.InsertOnSubmit(this);
        db.SubmitChanges();
    }
}</pre>
<p></p>
<p>The last step is to create a web service called DataService.asmx with a web method called AddUser that takes a parameter called user.</p>
<pre class="brush: csharp;">[System.Web.Script.Services.ScriptService]
public class DataService : WebService
{
    [WebMethod]
    public bool AddUser(User user)
    {
        try
        {
            user.Add();
        }
        catch (Exception ex)
        {
            // Error logging can happen here.
            return false;
        }

        return true;
    }
}</pre>
<p>
  <br />Make sure you uncomment the line in the web service that allows the service to be called from scripts..for whatever reason I forget to do that a lot.</p>
<p>I was trying to walk the line between “simple enough to get my point across” and “complex enough to show value” for this example.&#160;&#160; The key is that you can pass full objects from client code to .NET web service code with the use of JSON, and you can make asynchronous calls to web methods fairly easily using JQuery.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.jaltiere.com%2f%3fp%3d124"><img border="0" alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.jaltiere.com%2f%3fp%3d124" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.jaltiere.com/index.php/2010/04/05/making-web-service-calls-with-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Parsing POP email messages</title>
		<link>http://www.jaltiere.com/index.php/2010/03/29/parsing-pop-email-messages/</link>
		<comments>http://www.jaltiere.com/index.php/2010/03/29/parsing-pop-email-messages/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 02:33:15 +0000</pubDate>
		<dc:creator>Jack Altiere</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[POP]]></category>

		<guid isPermaLink="false">http://www.jaltiere.com/?p=114</guid>
		<description><![CDATA[I was recently tasked with coming up with a way to parse a pop email account and automatically save off the message and any attachments that came in the email.&#160; While it didn’t sound like too bad of a task, I know from my limited experience that parsing MIME content can be a pain in [...]]]></description>
			<content:encoded><![CDATA[<p>I was recently tasked with coming up with a way to parse a pop email account and automatically save off the message and any attachments that came in the email.&#160; While it didn’t sound like too bad of a task, I know from my limited experience that parsing <a href="http://en.wikipedia.org/wiki/MIME" target="_blank">MIME content</a> can be a pain in the rear.&#160; I thought it would be interesting to share what I came up with in a sample application.</p>
<p>First, I knew that I had no desire to reinvent the wheel and write my own MIME parser if I could find one that works.&#160; After some searching and some trial and error I ended up finding a .NET library that seems to work great from <a href="http://www.lesnikowski.com/mail/" target="_blank">here</a>.&#160; The full version of this library isn’t free, but the trial version is fully functional, it just rewrites the email subjects once in a while to tell you to buy the full version.&#160; (as a side note, I will probably end up buying this product, it worked exactly like I wanted it to)&#160; </p>
<p>Since I felt like showing this would go better if I had a sample app, I decided to write a little one page website that takes emails from an approved list of addresses, and posts any photo attachments in a little photo album.&#160; I decided I wanted a SQL Server backend, and that I would just use LINQ to SQL for data access.&#160; The plan is to just take the body of the email and make it the image caption and attach 1 image per email.&#160;&#160; It would also be nice to resize the image if it’s too big.</p>
<p>First, the backend.&#160; For the sake of simplicity I just created 2 tables…one to handle user validation and one to store the photos.&#160; After creating the LINQ to SQL classes for these two tables, my .dbml design view looked like this:</p>
<p><a href="http://www.jaltiere.com/wp-content/uploads/2010/03/dblayout.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="dblayout" border="0" alt="dblayout" src="http://www.jaltiere.com/wp-content/uploads/2010/03/dblayout_thumb.png" width="492" height="248" /></a> </p>
<p>After that, I wanted to set up my mail parsing library.&#160; Like I mentioned above, I just wrapped a 3rd party utility, so my code for this isn’t too complex.</p>
<pre class="brush: csharp;">public class MailParser
{
    private readonly string _popServer;
    private readonly string _username;
    private readonly string _password;
    private readonly IMessageProcessor _messageProcessor;

    public MailParser(IMessageProcessor messageProcessor)
    {
        _popServer = ConfigurationParser.GetAppSettingString(&quot;MailServer&quot;);
        _username = ConfigurationParser.GetAppSettingString(&quot;MailUserName&quot;);
        _password = ConfigurationParser.GetAppSettingString(&quot;MailPassword&quot;);
        _messageProcessor = messageProcessor;
    }

    public void ProcessMessages()
    {
        var messages = new List&lt;IMail&gt;();

        using (var pop3 = new Pop3())
        {
            pop3.Connect(_popServer);
            pop3.Login(_username, _password);

            foreach (var uid in pop3.GetAll())
            {
                // Add the email message to the list to be processed.
                var message = new MailBuilder().CreateFromEml(pop3.GetMessageByUID(uid));
                messages.Add(message);

                // Delete the message from the server.
                pop3.DeleteMessageByUID(uid);
            }
            pop3.Close(true);

            // We have snagged all of the messages from the server, now process them.
            foreach (var message in messages)
            {
                _messageProcessor.ProcessMessage(message);
            }
        }
    }

}

public interface IMessageProcessor
{
    void ProcessMessage(IMail message);
}

public class MessageProcessor : IMessageProcessor
{
    private readonly PhotoDBDataContext _db = new PhotoDBDataContext();

    public void ProcessMessage(IMail message)
    {
        var fromAddresses = message.From;
        var body = message.HtmlData ?? message.TextData;

        if (fromAddresses.Count == 0)
            return;

        // I only want to process emails from a list of valid email addresses.
        var address = (fromAddresses[0].Address.IsNullOrEmpty()) ? string.Empty : fromAddresses[0].Address;
        var user = ValidateUser(address);
        if (user == null)
            return;

        // If there are no attachments ignore the message.
        if (message.Attachments.Count == 0)
            return;

        // Process the attachments. (only supporting 1 attachment per email)
        var counter = 0;
        foreach (var att in message.Attachments)
        {
            if (counter &gt; 0)
                break;

            // Make sure that the attachment is a valid image.
            if (!att.ContentType.MimeType.ToString().ToLower().Equals(&quot;image&quot;))
                return;

            var photo = new Photo
                            {
                                Caption = body.Text,
                                DateUploaded = DateTime.Now,
                                UserID = user.UserID,
                                ImageData = att.Data,
                                ContentType = att.ContentType.ToString(),
                                FileName = att.FileName
                            };

            _db.Photos.InsertOnSubmit(photo);
            _db.SubmitChanges();

            counter ++;
        }
    }

    private User ValidateUser(string email)
    {
        var query = from u in _db.Users
                    where u.EmailAddress.Equals(email)
                    select u;

        return query.FirstOrDefault();
    }

}</pre>
<p>The code should be fairly straight forward.&#160; I created a message processing interface, because it is conceivable that I would want to reuse this and processes messages differently.&#160; You may notice the ConfigurationParser references, that is just a class I wrote to wrap the access of configuration variables allowing me to load them strongly typed.&#160;&#160; All I am doing is looping over the messages on the POP server, loading them into a list to process, and deleting the original message from the server.&#160; I’ll throw out the standard disclaimer here and say that this is an example application!&#160; I would definitely consider persisting messages into some sort of a queue to process before deleting them from the mail server if this were a production application.</p>
<p>Using LINQ to SQL it’s a snap to validate the user and make sure we’re only posting pictures from trusted email addresses. (I know, we would have to think about how to protect this against spoofing if this were a real app)&#160; Notice how I’m also using the MIME type to make sure that we only accept image attachments.&#160; Lastly, I’m only processing the first attachment to make sure to only accept one image per email, I did this because I’m using the message body as the caption of the photo.</p>
<p>Now that images are being scraped from the email account and stored in the database, I thought I’d close the loop on this sample application and put a quick web page up to display the album.&#160;&#160; I created a new ASP.NET MVC 2 web application, and then went through the same steps as above to create my LINQ to SQL classes.&#160; The first thing I wanted to do was create a strongly typed view.&#160; The way I do this is to right-click in the HomeController.cs file and select Add View.&#160;&#160; You will get a dialog like this one:</p>
<p><a href="http://www.jaltiere.com/wp-content/uploads/2010/03/strongtypedview.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="strongtypedview" border="0" alt="strongtypedview" src="http://www.jaltiere.com/wp-content/uploads/2010/03/strongtypedview_thumb.png" width="437" height="428" /></a> </p>
<p>All I did was name the view, select my LINQ to SQL generated Photo class, and choose List as the View content.&#160; This basically says that the view will have access to a collection of photos.&#160; It’s trivial to pull the list of photos out of the database with LINQ:</p>
<pre class="brush: csharp;">public ActionResult Index()
{
    var db = new PhotoDBDataContext();
    var photos = (from p in db.Photos
                  select p).ToList();

    ViewData.Model = photos;
    return View();
}</pre>
<p></p>
<p>I wanted to do is to display an image straight from an MVC controller.&#160; I’m not going to post all the code I used to accomplish this, but the short version: I modified a guide I found <a href="http://blogs.msdn.com/miah/archive/2008/11/13/extending-mvc-returning-an-image-from-a-controller-action.aspx">here</a>.&#160; One requirement that I still haven’t addressed is that I never resized the images.&#160; Since I took the images straight from the POP account and put them in the database, I have no idea how big they really are.&#160; Rather than go way off track and figure out how to do this, I used a method I read about <a href="http://www.xdevsoftware.com/blog/post/Resize-Image-in-ASPNET-C.aspx">here</a> to resize my images from a byte array if needed.&#160; Now I wanted to come up with a clever way to be able to thumbnail images on the fly, so I changed the default route in the global.asax file to look like this:</p>
<pre class="brush: csharp;">public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute(&quot;{resource}.axd/{*pathInfo}&quot;);

    routes.MapRoute(
        &quot;Default&quot;, // Route name
        &quot;{controller}/{action}/{photoID}/{thumbnail}&quot;, // URL with parameters
        new { controller = &quot;Home&quot;, action = &quot;Index&quot;, photoID = UrlParameter.Optional, thumbnail = false } // Parameter defaults
    );

}</pre>
<p>
  <br />What this allows me to do is use a URL like mysite.com/Home/Images/1 to show the full image and mysite.com/Home/Images/1/true if I want to show the thumbnail of the same image.&#160; My controller method for the image creation looks like this:</p>
<pre class="brush: csharp;">public ActionResult Images(int photoID, bool thumbnail)
{
    var db = new PhotoDBDataContext();
    var photo = (from p in db.Photos
                 where p.PhotoID.Equals(photoID)
                 select p).SingleOrDefault();

    if (photo == null)
        throw new Exception(&quot;Photo not loaded&quot;);

    var bytes = (thumbnail)
                    ? ResizeFromStream(100, new MemoryStream(photo.ImageData.ToArray()), photo.FileName)
                    : photo.ImageData.ToArray();

    var image = bytes;
    var contentType = photo.ContentType;
    return this.Image(image, contentType);
}</pre>
<p></p>
<p>The view ended up being trivial:</p>
<pre class="brush: csharp;">&lt;%@ Page Title=&quot;&quot; Language=&quot;C#&quot; MasterPageFile=&quot;~/Views/Shared/Site.Master&quot; Inherits=&quot;System.Web.Mvc.ViewPage&lt;IEnumerable&lt;BlogSamples.DisplayPhotos.Photo&gt;&gt;&quot; %&gt;

&lt;asp:Content ID=&quot;Content1&quot; ContentPlaceHolderID=&quot;TitleContent&quot; runat=&quot;server&quot;&gt;
    Photo Album - Jaltiere.Com
&lt;/asp:Content&gt;

&lt;asp:Content ID=&quot;Content2&quot; ContentPlaceHolderID=&quot;MainContent&quot; runat=&quot;server&quot;&gt;

    &lt;div id=&quot;container&quot;&gt;
        &lt;ul&gt;

        &lt;% foreach (var item in Model) { %&gt;

            &lt;li&gt;
            &lt;a href=&quot;Home/Images/&lt;%= Html.Encode(item.PhotoID) %&gt;&quot; target=&quot;_blank&quot; style=&quot;background-image: url('Home/Images/&lt;%= Html.Encode(item.PhotoID) %&gt;/true')&quot;&gt;
            &lt;span&gt;&lt;%= Html.Encode(item.Caption) %&gt;&lt;br /&gt;&lt;i&gt;uploaded &lt;%= Html.Encode(item.DateUploaded.ToShortDateString()) %&gt;&lt;/i&gt;&lt;/span&gt;&lt;/a&gt;
            &lt;/li&gt;

        &lt;% } %&gt;

        &lt;/ul&gt;
    &lt;/div&gt;

&lt;/asp:Content&gt;</pre>
<p>And with a little CSS magic…</p>
<pre class="brush: css;">body {
    text-align:center;
    font-family: tahoma, arial, sans-serif;
    font-size: 8pt;
}

#container {
    position:relative;
    width:770px;
    height:396px;
    margin:20px auto 0 auto;
    border:1px solid #aaa;
} 

ul {
    padding:0;
    margin:0;
    list-style-type:none;
}

li {
  display: inline;
  float: left;
  width: 101px;
  height: 101px;
  margin: 4px;
}

li a {
  display: block;
  width: 101px;
  height: 101px;
  background-position: center;
  background-repeat: no-repeat;
  text-decoration: none;
}

li { height: 115px; }
li a span {
  font-size: 9px;
  position: relative;
  top: 103px;
  color: #666;
  display: block;
  text-align: center;
}
li a:hover span { color: red; }</pre>
<p>You get a functional photo album:</p>
<p>&#160;<a href="http://www.jaltiere.com/wp-content/uploads/2010/03/gallery1.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="gallery" border="0" alt="gallery" src="http://www.jaltiere.com/wp-content/uploads/2010/03/gallery_thumb1.png" width="502" height="176" /></a> </p>
<p>This article kind of took off on me and turned out to be more MVC than POP mail parsing, but it was a fun little exercise.&#160; Things to take away:</p>
<ol>
<li>I recommend the mail parsing library I used, I found it to be intuitive and easy to use. </li>
<li>LINQ to SQL makes data access easy. (coming from a guy with a big stored procedure background) </li>
<li>MVC is much more fun to work with than Webforms in my opinion. </li>
<li>I freely admit that I am definitely not a designer, so my web layout is not very good. </li>
</ol>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.jaltiere.com%2f%3fp%3d114"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.jaltiere.com%2f%3fp%3d114" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.jaltiere.com/index.php/2010/03/29/parsing-pop-email-messages/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
