<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:copyright="http://blogs.law.harvard.edu/tech/rss" xmlns:image="http://purl.org/rss/1.0/modules/image/">
    <channel>
        <title>C#</title>
        <link>http://geekswithblogs.net/WinAZ/category/10364.aspx</link>
        <description>C#</description>
        <language>en-US</language>
        <copyright>Joe Mayo</copyright>
        <managingEditor>jmayo@mayosoftware.com</managingEditor>
        <generator>Subtext Version 0.0.0.0</generator>
        <item>
            <title>DataSprings Blog Post</title>
            <link>http://geekswithblogs.net/WinAZ/archive/2011/06/06/datasprings-blog-post.aspx</link>
            <description>&lt;p&gt;Here's a blog post by DataSprings on how to use LINQ to Twitter: &lt;a href="http://bit.ly/jjmLZY"&gt;http://bit.ly/jjmLZY&lt;/a&gt;.  It demonstrates how to authenticate with OAuth and how to use several of the APIs.&lt;/p&gt;
&lt;p&gt;Joe&lt;/p&gt; &lt;img src="http://geekswithblogs.net/WinAZ/aggbug/145745.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Joe Mayo</dc:creator>
            <guid>http://geekswithblogs.net/WinAZ/archive/2011/06/06/datasprings-blog-post.aspx</guid>
            <pubDate>Tue, 07 Jun 2011 00:32:14 GMT</pubDate>
            <comments>http://geekswithblogs.net/WinAZ/archive/2011/06/06/datasprings-blog-post.aspx#feedback</comments>
            <wfw:commentRss>http://geekswithblogs.net/WinAZ/comments/commentRss/145745.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/WinAZ/services/trackbacks/145745.aspx</trackback:ping>
        </item>
        <item>
            <title>Displaying Search Results With LINQ to Twitter and ASP.NET MVC</title>
            <link>http://geekswithblogs.net/WinAZ/archive/2011/04/28/displaying-search-results-with-linq-to-twitter-and-asp.net-mvc.aspx</link>
            <description>&lt;p&gt;Sometimes, the way that &lt;a title="LINQ to Twitter Site on CodePlex.com" target="_blank" href="http://linqtotwitter.codeplex.com/"&gt;LINQ to Twitter&lt;/a&gt; materializes queries into entities isn’t immediately clear.  It’s easy to get confused until you see the patterns or make a correlation between the Twitter API results and their representations as LINQ to Twitter entities.  In this post, I’ll explain some of the logic behind the design of LINQ to Twitter entities and demonstrate an example of one of the more oddly designed entity types, Search.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note: They'll be talking about MVC3 during multiple sessions at &lt;a href="http://northamerica.msteched.com/?mtag=gwb_jmayo"&gt;Tech-Ed&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;h4&gt;Basic Concepts&lt;/h4&gt;
&lt;p&gt;When designing LINQ to Twitter entities, the fundamental concepts were to have as much parity with Twitter API results as possible and do the minimum amount of customization required to obtain materialized results.  The reasoning weighed heavily towards the ability to match results to the official Twitter API documentation, quicker development, and easier debugging. &lt;/p&gt;
&lt;p&gt;The similarities between class entities and Twitter API XML results are in the areas of object structure and identifiers.  The object structure matches the XML queries as close as possible and identifier names are close to XML element names.  Occasionally, I’ve diverged from Twitter API formats, especially in naming conventions, where I felt the Twitter API element names were much less meaningful.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;&lt;strong&gt;Note:&lt;/strong&gt;  A common FAQ is the confusion with ID, UserID, and ScreenName on both the User entity and in the User.Identifier.  The fields on the User entity are input (sent to Twitter), but the User.Identifier fields are output (returned from Twitter).  This design decision was made so that you can see what values were used to compose the query, as opposed to what Twitter returned.  A common scenario is for queries to be made without ID, UserID, or ScreenName because the query is being made on behalf of the authenticated user. This means that ID, UserID, and ScreenName are blank on the entity.  As always, you would read the results of a materialized query from User.Identifier.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The Twitter API results format preference in LINQ to Twitter is XML. This decision comes from the fact that LINQ to Twitter was originally conceived as the example in my book, LINQ Programming/McGraw Hill, of how to build a LINQ provider.  In that case, it was more instructive to use LINQ to XML to translate Twitter API results into objects.  Some Twitter APIs don’t support XML and only JSON or ATOM is an option.  At the time I wrote the Search API, raw XML wasn’t available, but ATOM was.  Being a specialized XML format, I chose ATOM for Search.&lt;/p&gt;
&lt;p&gt;Considering the pattern of designing entities as close to the Twitter API results as possible, a legacy of choosing XML first, and Search supporting ATOM, the Search entity models the Twitter API results in ATOM format. Before diving too far into the example, the next section introduces the technology to be used with a couple architectural hints.&lt;/p&gt;
&lt;h4&gt;Technology/Architecture&lt;/h4&gt;
&lt;p&gt;A lot of my current work is done with ASP.NET MVC and feedback indicates that this is a very popular Web development option among other developers. I know, I just set myself up for trolls to flame me for my technology choice. Perhaps I should qualify my choice by acknowledging that ASP.NET Web Forms is still a live and viable technology that a lot of people love and like. Anyway, the following example will be in ASP.NET MVC3 with the Razor template engine.&lt;/p&gt;
&lt;p&gt;I’ll be moving LINQ to Twitter queries into a Repository.  I could have used LINQ to Twitter in the controllers, but that would have been lazy (I’ll be lazy elsewhere this time). I’ll translate the Search entities into a custom ViewModel.  Hopefully, this will provide a useful example of one option available (there are more) for moving data around your application.&lt;/p&gt;
&lt;p&gt;You can get started by creating a new MVC 3 project.  I won’t go into all the details of getting started because there are tons of introductory blog posts and articles across the Web, showing how to start an MVC project. Let’s start with the repository.&lt;/p&gt;
&lt;h4&gt;Building a Repository&lt;/h4&gt;
&lt;p&gt;A common practice in application development is to separate concerns so your application is easier to build and maintain. One pattern for separating data management from the rest of the application is called Repository, which this application uses.  Repositories are often used to abstract relational database operations, but are also used for other types of data such as text file, Excel, Web Service, or XML (and more).  For the purposes of this application, Twitter is a data source.  We’ll build the repository to return LINQ to Twitter Search entities, materialized from a query to the Twitter API.  Here’s the repository:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
using LinqToTwitter;
using System.Collections.Generic;
using System.Linq;

namespace TwitterSearchMVC.Models
{
    public class SearchRepository
    {
        public List&amp;lt;AtomEntry&amp;gt; Search(string tag)
        {
            using (var twitterCtx = new TwitterContext())
            {
                var searchResults =
                    (from search in twitterCtx.Search
                     where search.Type == SearchType.Search &amp;amp;&amp;amp;
                           search.Hashtag == tag
                     select search)
                    .SingleOrDefault();

                return searchResults.Entries;
            }
        }
    }
}&lt;/pre&gt;
&lt;p&gt;The code above is just a class, SearchRepository, with a single method, Search, for performing the search.  If you needed more specialized operations with search, you could add more methods, but this is all we need for this demo. The query is a typical search query, using the LINQ to Twitter Type idiom and filtering via a tag. Search queries can filter by any normal or advanced criteria that Twitter offers, but the tag is all we need for the demo.&lt;/p&gt;
&lt;p&gt;Now, you have data access code isolated in a repository. We also know that the data will be delivered in the form of a LINQ to Twitter Search entity. Next, let’s look at a similar object, the ViewModel.&lt;/p&gt;
&lt;h4&gt;Designing a ViewModel&lt;/h4&gt;
&lt;p&gt;The purpose of the ViewModel is to represent the data that will be displayed in the UI.  One of the first questions you might have is “Why can’t I just bind the LINQ to Twitter Search entity to the UI?”.  After all, demos from many very well-known people bind DB entities to the UI and if they do it then it must be right? Not quite; remember that those are demos in a blog post that are intentionally as short as possible or are trying to demonstrate something and proper architecture isn’t germane to the purpose of their post/article. However, when you’re writing a real-world application, these architectural details, like ViewModels, Repositories, and more become very important.&lt;/p&gt;
&lt;p&gt;There are a few reasons why you should use ViewModels, rather than binding data objects; revolving around the shape of the data, display characteristics, and validation.  What you bind to the UI should be a whole different object than what comes from the data source.  First, consider that your UI can have multiple items, including a header, menu, and data display.  The display of the data might be hierarchical or flat.  On the other hand the objects from the data source often have a different shape.  In addition to data shape, you can annotate ViewModel properties with information specific to the UI, like DisplayName.  You can also specify validation rules in your ViewModel that help UI controls manage user input, such as whether a field is required, string length, or email pattern.  All of these ViewModel details are associated with the UI or communicating with UI controls and don’t belong on your data object.  With that in mind, please review the following SearchViewModel:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
using System.ComponentModel;

namespace TwitterSearchMVC.Models
{
    public class SearchViewModel
    {
        [DisplayName("Tweet ID")]
        public string ID { get; set; }

        [DisplayName("User Name")]
        public string Source { get; set; }

        [DisplayName("Tweet Text")]
        public string Content { get; set; }
    }
}&lt;/pre&gt;
&lt;p&gt;The first thing you should notice about the SearchViewModel is that it only has a few properties, as opposed to the multitude of properties available on the Search entity.  This brings up another important issue is that you don’t need to be overloading View processing resources by moving all the data around everywhere. It’s common that you’ll only be displaying a sub-set or specialization of the data returned from a repository.  As I mentioned earlier, you can annotate ViewModel properties to make them work better in the  UI.  In this case, if you were using a 3rd party control like Telerik Grid, the DisplayName attribute would specify the column headings in the grid.&lt;/p&gt;
&lt;p&gt;Now that we have data from the data source and a ViewModel for the UI, I’ll show you how to build a controller that translates between the two.&lt;/p&gt;
&lt;h4&gt;Constructing a Controller&lt;/h4&gt;
&lt;p&gt;In the controller, I’m going to translate from AtomEntry to SearchViewModel, and display the results. Here’s the controller:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;using LinqToTwitter;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using TwitterSearchMVC.Models;

namespace LinqToTwitterSearchMvc.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            List&amp;lt;SearchViewModel&amp;gt; searchVM = PopulateSearchViewModel();
            return View(searchVM);
        }

        public List&amp;lt;SearchViewModel&amp;gt; PopulateSearchViewModel()
        {
            List&amp;lt;AtomEntry&amp;gt; searchList =
                new SearchRepository().Search("LinqToTwitter");

            var searchVM =
                (from search in searchList
                 select new SearchViewModel
                 {
                     ID = search.ID,
                     Source = search.Source,
                     Content = search.Content
                 })
                .ToList();

            return searchVM;
        }
    }
}&lt;/pre&gt;
&lt;p&gt;Notice that I used a method named PopulateSearchViewModel to get a list of ViewModel objects.  The logic uses a LINQ to Objects query to project the data into a form that can be easily displayed in the view.&lt;/p&gt;
&lt;p&gt;Now, let’s look a the view.&lt;/p&gt;
&lt;h4&gt;Designing a View&lt;/h4&gt;
&lt;p&gt;As mentioned earlier, I’m using the MVC Razor view engine. I normally use Telerik MVC Extensions, which are a free download via CodePlex.com, but this is just a demo.  So, I went with List scaffolding via the View wizard (you can open the View wizard by right-clicking on View(…) in the controller code and selecting Add View). The example creates a strongly typed View using a List type scaffolding to display results, shown below:&lt;/p&gt;
&lt;p&gt;@model IEnumerable&amp;lt;TwitterSearchMVC.Models.SearchViewModel&amp;gt;&lt;/p&gt;
&lt;p&gt;@{ &lt;br /&gt;
    ViewBag.Title = "Index"; &lt;br /&gt;
}&lt;/p&gt;
&lt;p&gt;&amp;lt;h2&amp;gt;Index&amp;lt;/h2&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;p&amp;gt; &lt;br /&gt;
    @Html.ActionLink("Create New", "Create") &lt;br /&gt;
&amp;lt;/p&amp;gt; &lt;br /&gt;
&amp;lt;table&amp;gt; &lt;br /&gt;
    &amp;lt;tr&amp;gt; &lt;br /&gt;
        &amp;lt;th&amp;gt; &lt;br /&gt;
            Source &lt;br /&gt;
        &amp;lt;/th&amp;gt; &lt;br /&gt;
        &amp;lt;th&amp;gt; &lt;br /&gt;
            Content &lt;br /&gt;
        &amp;lt;/th&amp;gt; &lt;br /&gt;
        &amp;lt;th&amp;gt;&amp;lt;/th&amp;gt; &lt;br /&gt;
    &amp;lt;/tr&amp;gt;&lt;/p&gt;
&lt;p&gt;@foreach (var item in Model) { &lt;br /&gt;
    &amp;lt;tr&amp;gt; &lt;br /&gt;
        &amp;lt;td&amp;gt; &lt;br /&gt;
            @Html.DisplayFor(modelItem =&amp;gt; item.Source) &lt;br /&gt;
        &amp;lt;/td&amp;gt; &lt;br /&gt;
        &amp;lt;td&amp;gt; &lt;br /&gt;
            @Html.DisplayFor(modelItem =&amp;gt; item.Content) &lt;br /&gt;
        &amp;lt;/td&amp;gt; &lt;br /&gt;
        &amp;lt;td&amp;gt; &lt;br /&gt;
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) | &lt;br /&gt;
            @Html.ActionLink("Details", "Details", new { id=item.ID }) | &lt;br /&gt;
            @Html.ActionLink("Delete", "Delete", new { id=item.ID }) &lt;br /&gt;
        &amp;lt;/td&amp;gt; &lt;br /&gt;
    &amp;lt;/tr&amp;gt; &lt;br /&gt;
}&lt;/p&gt;
&lt;p&gt;&amp;lt;/table&amp;gt;&lt;/p&gt;
&lt;p&gt;The UI will show a list of tweets that contain “LinqToTwitter”.  The actual results that are assigned to the Source and Content properties of the SearchViewModel contain HTML anchor tags that you’ll need to parse out yourself.  In many cases, LINQ to  Twitter returns the string data given to it from Twitter.  At other times, LINQ to Twitter will interpret the proper type of data, i.e. int, DateTime, etc., and set the value in the entity properly. You can also set a breakpoint in your code and examine the other fields returned from the LINQ to Twitter query for more information.&lt;/p&gt;
&lt;h4&gt;Summary&lt;/h4&gt;
&lt;p&gt;Hopefully, you now understand that there are patterns and reasons for the approach taken by LINQ to Twitter in translating Twitter API results into entities.  I explained some important architectural considerations when building applications, particularly from the ASP.NET MVC perspective. You saw how to take data from LINQ to Twitter entities and translate the data into ViewModel objects for display in the UI.  The result is a quick application that shows you another way to use LINQ to Twitter in an MVC application.&lt;/p&gt;
&lt;p&gt;&lt;a title="Joe Mayo on Twitter" target="_blank" href="http://twitter.com/#!/JoeMayo"&gt;@JoeMayo&lt;/a&gt;&lt;/p&gt; &lt;img src="http://geekswithblogs.net/WinAZ/aggbug/145069.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Joe Mayo</dc:creator>
            <guid>http://geekswithblogs.net/WinAZ/archive/2011/04/28/displaying-search-results-with-linq-to-twitter-and-asp.net-mvc.aspx</guid>
            <pubDate>Thu, 28 Apr 2011 14:27:15 GMT</pubDate>
            <comments>http://geekswithblogs.net/WinAZ/archive/2011/04/28/displaying-search-results-with-linq-to-twitter-and-asp.net-mvc.aspx#feedback</comments>
            <wfw:commentRss>http://geekswithblogs.net/WinAZ/comments/commentRss/145069.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/WinAZ/services/trackbacks/145069.aspx</trackback:ping>
        </item>
        <item>
            <title>TechEd 2011</title>
            <link>http://geekswithblogs.net/WinAZ/archive/2011/04/16/teched-2011.aspx</link>
            <description>&lt;p&gt;Now that Mix11 is over, Microsoft’s next big conference is &lt;a target="_blank" href="http://northamerica.msteched.com/?mtag=gwb_jmayo"&gt;Tech-Ed&lt;/a&gt; 2011, which happens May 16th through May 19th in Atlanta, GA.  Each of Microsoft’s conferences have a theme; Mix is about the Web, PDC is about new and upcoming technologies, and there are many more.  The focus of &lt;a target="_blank" href="http://northamerica.msteched.com/?mtag=gwb_jmayo"&gt;Tech-Ed&lt;/a&gt; is on current Microsoft technologies.  In other words, you would go there to learn about the software that you can use today to get your work done.  If you haven’t been there yet, Atlanta is a nice city and the surrounding communities are beautiful, especially in the Spring.  It should be a good time.&lt;/p&gt;
&lt;p&gt;Reviewing the list of sessions, I saw several on MVC 3, Async and Concurrent Programming, and more. What I’m going to try to do over the next month is write about the technologies being presented at &lt;a target="_blank" href="http://northamerica.msteched.com/?mtag=gwb_jmayo"&gt;Tech-Ed&lt;/a&gt; 2011.  I already mentioned a couple that are near and dear to my geek heart, but I’ll try to hit a breadth of topics that I think are cool and maybe you will too.&lt;/p&gt;
&lt;p&gt;&lt;a target="_blank" href="http://twitter.com/#!/JoeMayo"&gt;@JoeMayo&lt;/a&gt;&lt;/p&gt; &lt;img src="http://geekswithblogs.net/WinAZ/aggbug/144914.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Joe Mayo</dc:creator>
            <guid>http://geekswithblogs.net/WinAZ/archive/2011/04/16/teched-2011.aspx</guid>
            <pubDate>Sat, 16 Apr 2011 20:31:51 GMT</pubDate>
            <comments>http://geekswithblogs.net/WinAZ/archive/2011/04/16/teched-2011.aspx#feedback</comments>
            <wfw:commentRss>http://geekswithblogs.net/WinAZ/comments/commentRss/144914.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/WinAZ/services/trackbacks/144914.aspx</trackback:ping>
        </item>
        <item>
            <title>JustCode Provides Reflector Alternative</title>
            <link>http://geekswithblogs.net/WinAZ/archive/2011/03/19/justcode-provides-reflector-alternative.aspx</link>
            <description>&lt;p&gt;If you've been a loyal Reflector user, you've probably been exposed to the debacle surrounding RedGate's decision to no longer offer a free version.  Since then, the race has begun for a replacement with a provider that would stand by their promises to the community.  Mono has an ongoing free alternative, which has been available for a long time.  However, other vendors are stepping up to the plate, with their own offerings.&lt;/p&gt;
&lt;h4&gt;If Not Reflector, Then What?&lt;/h4&gt;
&lt;p&gt;One of these vendors is Telerik.  In their recent Q1 2011 release of &lt;a href="http://www.telerik.com/products/justcode/whats-new-full-story.aspx" target="_blank"&gt;JustCode&lt;/a&gt;, Telerik offers a decompilation utility rivaling what we've become accustomed to in Reflector.  Not only does Telerik offer a usable replacement, but they've (in my opinion), produced a product that integrates more naturally with visual Studio than any other product ever has.  Telerik's decompilation process is so easy that the accompanying demo in this post is blindingly short (except for the presence of verbose narrative).&lt;/p&gt;
&lt;p&gt;If you want to follow along with this demo, you'll need to have Telerik JustCode installed.  If you don't have JustCode yet, you can &lt;a href="http://www.telerik.com/purchase/individual-justcode.aspx" target="_blank"&gt;buy it&lt;/a&gt; or download a &lt;a href="http://www.telerik.com/account/your-products/trial-product-versions/trial-single-download.aspx?pmvid=0&amp;amp;pid=717" target="_blank"&gt;trial&lt;/a&gt; at the Telerik Web site .&lt;/p&gt;
&lt;h4&gt;A Tall Tale; Prove It!&lt;/h4&gt;
&lt;p&gt;With JustCode, you can view code in the .NET Framework or any other 3rd party library (that isn't well obfuscated).  This demo depends on&lt;a href="http://linqtotwitter.codeplex.com/" target="_blank"&gt; LINQ to Twitter&lt;/a&gt;, which you can download from CodePlex.com and create a reference or install the package online as described in my previous post on &lt;a href="http://geekswithblogs.net/WinAZ/archive/2011/03/18/a-gentle-introduction-to-nuget.aspx" target="_blank"&gt;NuGet&lt;/a&gt;.  Regardless of the method, you'll have a project with a reference to LINQ to Twitter.  Use a Console Project if you want to follow along with this demo.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note:&lt;/em&gt;&lt;/strong&gt;&lt;em&gt;  If you've created a Console project, remember to ensure that the Target Framework is set to .NET Framework 4.  The default is .NET Framework 4 Client Profile, which doesn't work with LINQ to Twitter.  You can check by double-clicking the Properties folder on the project and inspecting the Target Framework setting.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Next, you'll need to add some code to your program that you want to inspect. Here, I add code to instantiate a TwitterContext, which is like a LINQ to SQL DataContext, but works with Twitter:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
var l2tCtx = new TwitterContext();&lt;/pre&gt;
&lt;p&gt;If you're following along add the code above to the Main method, which will look similar to this:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
using LinqToTwitter;

namespace NuGetInstall
{
    class Program
    {
        static void Main(string[] args)
        {
            var l2tCtx = new TwitterContext();
        }
    }
}&lt;/pre&gt;
&lt;p&gt;The code above doesn't really do anything, but it does give something that I can show and demonstrate how JustCode decompilation works.&lt;/p&gt;
&lt;p&gt;Once the code is in place, click on &lt;em&gt;TwitterContext &lt;/em&gt;and press the &lt;strong&gt;F12&lt;/strong&gt; (Go to Definition) key.  As expected, Visual Studio opens a metadata file with prototypes for the &lt;em&gt;TwitterContext &lt;/em&gt;class.  Here's the result:&lt;/p&gt;
&lt;p&gt;&lt;img height="684" width="1024" src="/images/geekswithblogs_net/WinAZ/11529/o_TwitterContextMetaData.png" alt="Pressing F12 on Types Without Code Shows MetaData in Visual Studio" /&gt;&lt;/p&gt;
&lt;p&gt;Opening a metadata file is the normal way that Visual Studio works when navigating to the definition of a type where you don't have the code.  The scenario with &lt;em&gt;TwitterContext &lt;/em&gt;happens because you don't have the source code to the file.  Visual Studio has always done this and you can experiment by selecting any .NET type, i.e. a string type, and observing that Visual Studio opens a metadata file for the .NET String type. The point I'm making here is that JustCode works the way Visual Studio works and you'll see how this can make your job easier.&lt;/p&gt;
&lt;p&gt;In the previous figure, you only saw prototypes associated with the code. i.e. Notice that the default constructor is empty.  Again, this is normal because Visual Studio doesn't have the ability to decompile code.  However, that's the purpose of this post; showing you how JustCode fills that gap.&lt;/p&gt;
&lt;p&gt;To decompile code, right click on &lt;em&gt;TwitterContext &lt;/em&gt;in the metadata file and select &lt;em&gt;JustCode Navigate -&amp;gt; Decompile&lt;/em&gt; from the context menu.  The shortcut keys are &lt;strong&gt;Ctrl+1&lt;/strong&gt;.  After a brief pause, accompanied by a progress window, you'll see the metadata expand into full decompiled code. Notice below how the default constructor now has code as opposed to the empty member prototype in the original metadata:&lt;/p&gt;
&lt;p&gt;&lt;img height="684" width="1024" src="/images/geekswithblogs_net/WinAZ/11529/o_TwitterContextDecompiled.png" alt="" /&gt;&lt;/p&gt;
&lt;h4&gt;And Why is This So Different?&lt;/h4&gt;
&lt;p&gt;Again, the big deal is that Telerik JustCode decompilation works in harmony with the way that Visual Studio works.  The navigate to functionality already exists and you can use that, along with a simple context menu option (or shortcut key) to transform prototypes into decompiled code.&lt;/p&gt;
&lt;p&gt;Telerik is filling the the Reflector/Red Gate gap by providing a supported alternative to decompiling code.  Many people, including myself, used Reflector to decompile code when we were stuck with buggy libraries or insufficient documentation.  Now we have an alternative that's officially supported by a company with an excellent track record for customer (developer) service, Telerik.  Not only that, JustCode has &lt;a href="http://www.telerik.com/products/justcode.aspx" target="_blank"&gt;several other IDE productivity tools&lt;/a&gt; that make the deal even sweeter.&lt;/p&gt;
&lt;p&gt;Joe&lt;/p&gt; &lt;img src="http://geekswithblogs.net/WinAZ/aggbug/144443.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Joe Mayo</dc:creator>
            <guid>http://geekswithblogs.net/WinAZ/archive/2011/03/19/justcode-provides-reflector-alternative.aspx</guid>
            <pubDate>Sun, 20 Mar 2011 05:04:08 GMT</pubDate>
            <comments>http://geekswithblogs.net/WinAZ/archive/2011/03/19/justcode-provides-reflector-alternative.aspx#feedback</comments>
            <wfw:commentRss>http://geekswithblogs.net/WinAZ/comments/commentRss/144443.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/WinAZ/services/trackbacks/144443.aspx</trackback:ping>
        </item>
        <item>
            <title>Released LINQ to Twitter Beta v2.0.20</title>
            <link>http://geekswithblogs.net/WinAZ/archive/2011/03/06/released-linq-to-twitter-beta-v2.0.20.aspx</link>
            <description>&lt;p&gt;I released LINQ to Twitter Beta v2.0.20: &lt;a href="http://goo.gl/1i97X"&gt;http://goo.gl/1i97X&lt;/a&gt;.  Most of the items were bug fixes.  A couple items were new: Geo Search and I finished adding Asynch support for non-Silverlight APIs.&lt;/p&gt;
&lt;p&gt;Joe&lt;/p&gt; &lt;img src="http://geekswithblogs.net/WinAZ/aggbug/144218.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Joe Mayo</dc:creator>
            <guid>http://geekswithblogs.net/WinAZ/archive/2011/03/06/released-linq-to-twitter-beta-v2.0.20.aspx</guid>
            <pubDate>Mon, 07 Mar 2011 03:24:29 GMT</pubDate>
            <comments>http://geekswithblogs.net/WinAZ/archive/2011/03/06/released-linq-to-twitter-beta-v2.0.20.aspx#feedback</comments>
            <wfw:commentRss>http://geekswithblogs.net/WinAZ/comments/commentRss/144218.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/WinAZ/services/trackbacks/144218.aspx</trackback:ping>
        </item>
        <item>
            <title>Debugging Windows Service Timeout Error 1053</title>
            <link>http://geekswithblogs.net/WinAZ/archive/2011/03/03/debugging-windows-service-timeout-error-1053.aspx</link>
            <description>&lt;p&gt;If you ever receive an Error 1053 for a timeout when starting a Windows Service you've written, the underlying problem might not have anything to do with a timeout.  Here's the error so you can compare it to what you're seeing:&lt;/p&gt;
&lt;p&gt;---------------------------&lt;br /&gt;
Services&lt;br /&gt;
---------------------------&lt;br /&gt;
Windows could not start the Service1 service on Local Computer.&lt;/p&gt;
&lt;p&gt; &lt;/p&gt;
&lt;p&gt;Error 1053: The service did not respond to the start or control request in a timely fashion.&lt;/p&gt;
&lt;p&gt;&lt;br /&gt;
---------------------------&lt;br /&gt;
OK   &lt;br /&gt;
---------------------------&lt;/p&gt;
&lt;p&gt;Searching the Web for a solution to this error in your Windows Service will result in a lot of wasted time and advice that won't help.  Sometimes you might get lucky if your problem is exactly the same as someone else's, but this isn't always the case.  One of the solutions you'll see has to do with a known error on Windows Server 2003 that's fixed by a patch to the .NET Framework 1.1, which won't work.  As I write this blog post, I'm using the .NET Framework 4.0, which is a tad bit past that timeframe.&lt;/p&gt;
&lt;p&gt;Most likely, the basic problem is that your service is throwing an exception that you aren't handling.  To debug this, wrap your service initialization code in a try/catch block and log the exception, as shown below:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
using System;
using System.Diagnostics;
using System.ServiceProcess;

namespace WindowsService
{
    static class Program
    {
        static void Main()
        {
            try
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
			    { 
				    new Service1() 
			    };
                ServiceBase.Run(ServicesToRun);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("Application", ex.ToString(), EventLogEntryType.Error);
            }
        }
    }
}&lt;/pre&gt;
&lt;p&gt;After you uninstall the old service, redeploy the service with modifications, and receive the same error message as above; look in the Event Viewer/Application logs.  You'll see what the real problem is, which is the underlying reason for the timeout.&lt;/p&gt;
&lt;p&gt;Joe&lt;/p&gt; &lt;img src="http://geekswithblogs.net/WinAZ/aggbug/144171.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Joe Mayo</dc:creator>
            <guid>http://geekswithblogs.net/WinAZ/archive/2011/03/03/debugging-windows-service-timeout-error-1053.aspx</guid>
            <pubDate>Thu, 03 Mar 2011 19:20:37 GMT</pubDate>
            <comments>http://geekswithblogs.net/WinAZ/archive/2011/03/03/debugging-windows-service-timeout-error-1053.aspx#feedback</comments>
            <slash:comments>1</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/WinAZ/comments/commentRss/144171.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/WinAZ/services/trackbacks/144171.aspx</trackback:ping>
        </item>
        <item>
            <title>LINQ to Twitter Queries with LINQPad</title>
            <link>http://geekswithblogs.net/WinAZ/archive/2011/02/24/linq-to-twitter-queries-with-linqpad.aspx</link>
            <description>&lt;p&gt;&lt;a target="_blank" href="http://www.linqpad.net/"&gt;LINQPad &lt;/a&gt;is a popular utility for .NET developers who use LINQ a lot.  In addition to standard SQL queries, LINQPad also supports other types of LINQ providers, including &lt;a target="_blank" href="http://linqtotwitter.codeplex.com/"&gt;LINQ to Twitter&lt;/a&gt;.  The following sections explain how to set up LINQPad for making queries with LINQ to Twitter.&lt;/p&gt;
&lt;p&gt;LINQPad comes in a couple versions and this example uses LINQPad4, which runs on the .NET Framework 4.0.&lt;/p&gt;
&lt;p&gt;1. The first thing you'll need to do is set up a reference to the LinqToTwitter.dll. From the Query menu, select query properties. Click the Browse button and find the LinqToTwitter.dll binary. You should see something similar to the Query Properties window below.&lt;/p&gt;
&lt;p&gt;&lt;img alt="LINQPad References Page" width="703" height="477" src="/images/geekswithblogs_net/WinAZ/11529/o_LinqPadReferences.png" /&gt;&lt;/p&gt;
&lt;p&gt;2. While you have the query properties window open, add the namespace for the LINQ to Twitter types.  Click the &lt;em&gt;Additional Namespace Imports &lt;/em&gt;tab and type in &lt;strong&gt;LinqToTwitte&lt;/strong&gt;r. The results are shown below:&lt;/p&gt;
&lt;p&gt;&lt;img alt="LINQPad Namespaces Page" width="703" height="477" src="/images/geekswithblogs_net/WinAZ/11529/o_LinqPadNamespaces.png" /&gt;&lt;/p&gt;
&lt;p&gt;3. The default query type, when you first start LINQPad, is C# Expression, but you'll need to change this to support multiple statements.  Change the Language dropdown, on the Main window, to C# Statements.&lt;/p&gt;
&lt;p&gt;4. To query LINQ to Twitter, instantiate a &lt;em&gt;TwitterContext&lt;/em&gt;, by typing the following into the LINQPad Query window:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
var ctx = new TwitterContext();&lt;/pre&gt;
&lt;p&gt;Note: If you're getting syntax errors, go back and make sure you did steps #2 and #3 properly.&lt;/p&gt;
&lt;p&gt;5. Next, add a query, but don't materialize it, like this:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
var tweets =
	from tweet in ctx.Status
	where tweet.Type == StatusType.Public
	select new
	{
		tweet.Text,
		tweet.Geo,
		tweet.User
	};&lt;/pre&gt;
&lt;p&gt;6. Next, you want the output to be displayed in the LINQPad grid, so do a &lt;em&gt;Dump&lt;/em&gt;, like this:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
tweets.Dump();&lt;/pre&gt;
&lt;p&gt;The following image shows the final results:&lt;/p&gt;
&lt;p&gt; &lt;img alt="LINQ to Twitter Query in LINQPad" width="1059" height="728" src="/images/geekswithblogs_net/WinAZ/11529/o_LinqPadQuery.png" /&gt;&lt;/p&gt;
&lt;p&gt;That was an unauthenticated query, but you can also perform authenticated queries with LINQ to Twitter's support of OAuth.  Here's an example that uses the &lt;em&gt;PinAuthorizer &lt;/em&gt;(type this into the LINQPad Query window):&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
var auth = new PinAuthorizer
{
	Credentials = new InMemoryCredentials
	{
		ConsumerKey = "&lt;your twitter="" consumer="" key=""&gt;&lt;/your&gt;",
		ConsumerSecret = "&lt;your twitter="" consumer="" secret=""&gt;&lt;/your&gt;"
	},
	UseCompression = true,
	GoToTwitterAuthorization = pageLink =&amp;gt; Process.Start(pageLink),
	GetPin = () =&amp;gt;
	{
		// this executes after user authorizes, which begins with the call to auth.Authorize() below.
		Console.WriteLine("\nAfter you authorize this application, Twitter will give you a 7-digit PIN Number.\n");
		Console.Write("Enter the PIN number here: ");
		return Console.ReadLine();
	}
};

// start the authorization process (launches Twitter authorization page).
auth.Authorize();

var ctx = new TwitterContext(auth, "https://api.twitter.com/1/", "https://search.twitter.com/");

var tweets =
	from tweet in ctx.Status
	where tweet.Type == StatusType.Public
	select new
	{
		tweet.Text,
		tweet.Geo,
		tweet.User
	};

tweets.Dump();&lt;/pre&gt;
&lt;p&gt;This code is very similar to what you'll find in the LINQ to Twitter downloadable source code solution, in the LinqToTwitterDemo project.  For obvious reasons, I changed the value assigned to &lt;em&gt;ConsumerKey &lt;/em&gt;and &lt;em&gt;ConsumerSecret&lt;/em&gt;, which you'll have to obtain by visiting &lt;a href="http://dev.twitter.com/"&gt;http://dev.twitter.com&lt;/a&gt; and registering your application.&lt;/p&gt;
&lt;p&gt;One tip, you'll probably want to make this easier on yourself by creating your own DLL that encapsulates all of the OAuth logic and then call a method or property on you custom class that returns a fully functioning TwitterContext.  This will help avoid adding all this code every time you want to make a query.&lt;/p&gt;
&lt;p&gt;Now, you know how to set up LINQPad for LINQ to Twitter, perform unauthenticated queries, and perform queries with OAuth.&lt;/p&gt;
&lt;p&gt;Joe&lt;/p&gt; &lt;img src="http://geekswithblogs.net/WinAZ/aggbug/144103.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Joe Mayo</dc:creator>
            <guid>http://geekswithblogs.net/WinAZ/archive/2011/02/24/linq-to-twitter-queries-with-linqpad.aspx</guid>
            <pubDate>Thu, 24 Feb 2011 18:31:55 GMT</pubDate>
            <comments>http://geekswithblogs.net/WinAZ/archive/2011/02/24/linq-to-twitter-queries-with-linqpad.aspx#feedback</comments>
            <wfw:commentRss>http://geekswithblogs.net/WinAZ/comments/commentRss/144103.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/WinAZ/services/trackbacks/144103.aspx</trackback:ping>
        </item>
        <item>
            <title>A Basic Thread</title>
            <link>http://geekswithblogs.net/WinAZ/archive/2011/02/21/a-basic-thread.aspx</link>
            <description>&lt;p&gt;Most of the programs written are single-threaded, meaning that they run on the main execution thread. For various reasons such as performance, scalability, and/or responsiveness additional threads can be useful. .NET has extensive threading support, from the basic threads introduced in v1.0 to the Task Parallel Library (TPL) introduced in v4.0. To get started with threads, it's helpful to begin with the basics; starting a Thread.&lt;/p&gt;
&lt;h4&gt;Why Do I Care?&lt;/h4&gt;
&lt;p&gt;The scenario I'll use for needing to use a thread is writing to a file.  Sometimes, writing to a file takes a while and you don't want your user interface to lock up until the file write is done. In other words, you want the application to be responsive to the user.&lt;/p&gt;
&lt;h4&gt;How Would I Go About It?&lt;/h4&gt;
&lt;p&gt;The solution is to launch a new thread that performs the file write, allowing the main thread to return to the user right away.  Whenever the file writing thread completes, it will let the user know.  In the meantime, the user is free to interact with the program for other tasks. The following examples demonstrate how to do this.&lt;/p&gt;
&lt;h4&gt;Show Me the Code?&lt;/h4&gt;
&lt;p&gt;The code we'll use to work with threads is in the &lt;em&gt;System.Threading &lt;/em&gt;namespace, so you'll need the following using directive at the top of the file:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
using System.Threading;&lt;/pre&gt;
&lt;p&gt;When you run code on a thread, the code is specified via a method.  Here's the code that will execute on the thread:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
        private static void WriteFile()
        {
            Thread.Sleep(1000);
            Console.WriteLine("File Written.");
        }&lt;/pre&gt;
&lt;p&gt;The call to &lt;em&gt;Thread.Sleep(1000)&lt;/em&gt; delays thread execution. The parameter is specified in milliseconds, and 1000 means that this will cause the program to sleep for approximately 1 second.  This method happens to be &lt;em&gt;static&lt;/em&gt;, but that's just part of this example, which you'll see is launched from the static &lt;em&gt;Main &lt;/em&gt;method.  A thread could be instance or static. &lt;/p&gt;
&lt;p&gt;Notice that the method does not have parameters and does not have a return type. As you know, the way to refer to a method is via a delegate.  There is a delegate named &lt;em&gt;ThreadStart &lt;/em&gt;in &lt;em&gt;System.Threading&lt;/em&gt; that refers to a method without parameters or return type, shown below:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
            ThreadStart fileWriterHandlerDelegate =
                new ThreadStart(WriteFile);&lt;/pre&gt;
&lt;p&gt;I'll show you the whole program below, but the &lt;em&gt;ThreadStart &lt;/em&gt;instance above goes in the &lt;em&gt;Main &lt;/em&gt;method. The thread uses the &lt;em&gt;ThreadStart &lt;/em&gt;instance, &lt;em&gt;fileWriterHandlerDelegate&lt;/em&gt;, to specify the method to execute on the thread:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
            Thread fileWriter = new Thread(fileWriterHandlerDelegate);&lt;/pre&gt;
&lt;p&gt;As shown above, the argument type for the &lt;em&gt;Thread &lt;/em&gt;constructor is the &lt;em&gt;ThreadStart &lt;/em&gt;delegate type. The &lt;em&gt;fileWriterHandlerDelegate &lt;/em&gt;argument is an instance of the &lt;em&gt;ThreadStart &lt;/em&gt;delegate type. This creates an instance of a thread and what code will execute, but the new thread instance, &lt;em&gt;fileWriter&lt;/em&gt;, isn't running yet. You have to explicitly start it, like this:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
            fileWriter.Start();&lt;/pre&gt;
&lt;p&gt;Now, the code in the &lt;em&gt;WriteFile &lt;/em&gt;method is executing on a separate thread. Meanwhile, the main thread that started the &lt;em&gt;fileWriter &lt;/em&gt;thread continues on it's own.  You have two threads running at the same time.&lt;/p&gt;
&lt;h4&gt;Okay, I'm Starting to Get Glassy Eyed. How Does it All Fit Together?&lt;/h4&gt;
&lt;p&gt;The example below is the whole program, pulling all the previous bits together. It's followed by its output and an explanation.&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
using System;
using System.Threading;

namespace BasicThread
{
    class Program
    {
        static void Main()
        {
            ThreadStart fileWriterHandlerDelegate =
                new ThreadStart(WriteFile);

            Thread fileWriter = new Thread(fileWriterHandlerDelegate);

            Console.WriteLine("Starting FileWriter");

            fileWriter.Start();

            Console.WriteLine("Called FileWriter");
            Console.ReadKey();
        }

        private static void WriteFile()
        {
            Thread.Sleep(1000);
            Console.WriteLine("File Written");
        }
    }
}&lt;/pre&gt;
&lt;p&gt;And here's the output:&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Courier New"&gt;Starting FileWriter&lt;br /&gt;
Called FileWriter&lt;br /&gt;
File Written&lt;/span&gt;&lt;/p&gt;
&lt;h4&gt;So, Why are the Printouts Backwards?&lt;/h4&gt;
&lt;p&gt;The output above corresponds to &lt;em&gt;Console.Writeline&lt;/em&gt; statements in the program, with the second and third seemingly reversed. In a single-threaded program, "File Written" would print before "Called FileWriter". However, this is a multi-threaded (2 or more threads) program.  In multi-threading, you can't make any assumptions about when a given thread will run.  In this case, I added the &lt;em&gt;Sleep &lt;/em&gt;statement to the &lt;em&gt;WriteFile &lt;/em&gt;method to greatly increase the chances that the message from the main thread will print first. Without the &lt;em&gt;Thread.Sleep&lt;/em&gt;, you could run this on a system with multiple cores and/or multiple processors and potentially get different results each time.&lt;/p&gt;
&lt;h4&gt;Interesting Tangent but What Should I Get Out of All This?&lt;/h4&gt;
&lt;p&gt;Going back to the main point, launching the &lt;em&gt;WriteFile &lt;/em&gt;method on a separate thread made the program more responsive.  The file writing logic ran for a while, but the main thread returned to the user, as demonstrated by the print out of "Called FileWriter".  When the file write finished, it let the user know via another print statement. This was a very efficient use of CPU resources that made for a more pleasant user experience.&lt;/p&gt;
&lt;p&gt;Joe&lt;/p&gt; &lt;img src="http://geekswithblogs.net/WinAZ/aggbug/144042.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Joe Mayo</dc:creator>
            <guid>http://geekswithblogs.net/WinAZ/archive/2011/02/21/a-basic-thread.aspx</guid>
            <pubDate>Tue, 22 Feb 2011 05:30:07 GMT</pubDate>
            <comments>http://geekswithblogs.net/WinAZ/archive/2011/02/21/a-basic-thread.aspx#feedback</comments>
            <slash:comments>1</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/WinAZ/comments/commentRss/144042.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/WinAZ/services/trackbacks/144042.aspx</trackback:ping>
        </item>
        <item>
            <title>An MVC 3 Contact Form</title>
            <link>http://geekswithblogs.net/WinAZ/archive/2010/10/30/an-mvc-3-contact-form.aspx</link>
            <description>&lt;p&gt;Many sites have a contact form, instead of posting email addresses.  Admittedly, email addresses are convenient for customers because they can use a mailto link that brings up their email client and allow them to start typing, archive the communication, and manage the thread.  When I first started &lt;a target="_blank" href="http://www.csharp-station.com/"&gt;C# Station&lt;/a&gt;, that’s what I did; posted my email address for everyone.  Holy cow, what a mistake.  I received so much spam that my inbox was unusable. Fortunately, spam is more manageable these days, but it’s still a problem.  Therefore, C# Station takes a balanced approach by allowing people to contact me, yet protect my email address.  The following shows how I built the new contact form with ASP.NET MVC 3.&lt;/p&gt;
&lt;h4&gt;The Controller&lt;/h4&gt;
&lt;p&gt;Previously, I blogged about the organization of my site and how the &lt;em&gt;About&lt;/em&gt; page was the last menu item. What I’m doing now is hanging the &lt;em&gt;Contact&lt;/em&gt; menu item off &lt;em&gt;About&lt;/em&gt;, along with other miscellaneous subjects like &lt;em&gt;Terms&lt;/em&gt;, &lt;em&gt;Contribute&lt;/em&gt;, and &lt;em&gt;LinkToMe&lt;/em&gt;. Therefore, I created an &lt;em&gt;About&lt;/em&gt; controller to group these items together:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
using System.Web.Mvc;
using CssMvc.Library;
using CssMvc.Models;

namespace CssMvc.Controllers
{
    public class AboutController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Contact()
        {
            return View(new ContactViewModel());
        }

        [HttpPost]
        public ActionResult Contact(ContactViewModel contactVM)
        {
            if (!ModelState.IsValid)
            {
                return View(contactVM);
            }

            var contact = new Contact
            {
                From = contactVM.From,
                Subject = contactVM.Subject,
                Message = contactVM.Message
            };

            new Email().Send(contact);

            return RedirectToAction("ContactConfirm");
        }

        public ActionResult ContactConfirm()
        {
            return View();
        }

        public ActionResult LinkToMe()
        {
            return View();
        }

        public ActionResult Contribute()
        {
            return View();
        }

        public ActionResult Terms()
        {
            return View();
        }
    }
}&lt;/pre&gt;
&lt;p&gt;As you can see, there is a parameterless &lt;em&gt;Contact&lt;/em&gt; action whose purpose is to display a &lt;em&gt;Contact&lt;/em&gt; view. There’s also a &lt;em&gt;Contact&lt;/em&gt; action, with a &lt;em&gt;ContactViewModel&lt;/em&gt; parameter that I’ll return to later. Right now, take a look at the parameterless &lt;em&gt;Contact&lt;/em&gt;, which shows a blank contact form, it passes a new instance of &lt;em&gt;ContactViewModel&lt;/em&gt;, which is empty, to the &lt;em&gt;View&lt;/em&gt;.  If you’ve been working with ASP.NET MVC, this is nothing different than what you’ve seen before.  Let’s take an closer look at &lt;em&gt;ContactViewModel&lt;/em&gt;.&lt;/p&gt;
&lt;h4&gt;The Model&lt;/h4&gt;
&lt;p&gt;“Model” is one of those overloaded and overused buzzwords that software engineers love to sprinkle into conversation. Okay, I love to say “Model”  because it makes me sound like I know what I’m talking about. Anyway, I like to suffix my model names with &lt;em&gt;ViewModel&lt;/em&gt;, which is what plenty of other people do too.  Since I wanted  a form with contact data, I called my object &lt;em&gt;ContactViewModel&lt;/em&gt; and coded it like this:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
using System.ComponentModel.DataAnnotations;

namespace CssMvc.Models
{
    public class ContactViewModel
    {
        [Required]
        [DataType(DataType.EmailAddress)]
        public string From { get; set; }

        [Required]
        public string Subject { get; set; }

        [Required]
        public string Message { get; set; }
    }
}&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;ContactViewModel&lt;/em&gt; doesn’t show anything new. The annotations feature was introduced in MVC 2.  It’s a simple &lt;em&gt;ViewModel&lt;/em&gt;, but it does reflect what I want to show on my screen.  As you know, email messages have many more fields than shown here.  The trick is to only use what you need in the &lt;em&gt;ViewModel&lt;/em&gt; and let’s its purpose be presentation driven. Speaking of presentation, let’s see what the form looks like.&lt;/p&gt;
&lt;h4&gt;The View&lt;/h4&gt;
&lt;p&gt;So far, if already accustomed to MVC 2, you haven’t seen anything new. However, now I’ll show you the &lt;em&gt;View&lt;/em&gt;, which uses the new MVC 3 Razor view engine. This view displays a &lt;em&gt;Contact&lt;/em&gt; form that lets the user enter a &lt;em&gt;From&lt;/em&gt; address, &lt;em&gt;Subject&lt;/em&gt;, and &lt;em&gt;Message&lt;/em&gt;; the same data items you saw in the &lt;em&gt;ContactViewModel&lt;/em&gt;:&lt;/p&gt;
&lt;p&gt;@model CssMvc.Models.ContactViewModel&lt;/p&gt;
&lt;p&gt;@{ &lt;br /&gt;
    View.Title = "Contact Joe Mayo"; &lt;br /&gt;
    Layout = "~/Views/Shared/_Layout.cshtml"; &lt;br /&gt;
}&lt;/p&gt;
&lt;p&gt;@using (Html.BeginForm()) { &lt;br /&gt;
    @Html.ValidationSummary(true) &lt;br /&gt;
    &amp;lt;fieldset&amp;gt; &lt;br /&gt;
        &amp;lt;legend&amp;gt;Contact Joe Mayo&amp;lt;/legend&amp;gt; &lt;br /&gt;
        &amp;lt;div class="editor-label"&amp;gt; &lt;br /&gt;
            @Html.LabelFor(model =&amp;gt; model.From) &lt;br /&gt;
        &amp;lt;/div&amp;gt; &lt;br /&gt;
        &amp;lt;div class="editor-field"&amp;gt; &lt;br /&gt;
            @Html.TextBoxFor(model =&amp;gt; model.From) &lt;br /&gt;
            @Html.ValidationMessageFor(model =&amp;gt; model.From) &lt;br /&gt;
        &amp;lt;/div&amp;gt; &lt;br /&gt;
        &amp;lt;div class="editor-label"&amp;gt; &lt;br /&gt;
            @Html.LabelFor(model =&amp;gt; model.Subject) &lt;br /&gt;
        &amp;lt;/div&amp;gt; &lt;br /&gt;
        &amp;lt;div class="editor-field"&amp;gt; &lt;br /&gt;
            @Html.TextBoxFor(model =&amp;gt; model.Subject) &lt;br /&gt;
            @Html.ValidationMessageFor(model =&amp;gt; model.Subject) &lt;br /&gt;
        &amp;lt;/div&amp;gt; &lt;br /&gt;
        &amp;lt;div class="editor-label"&amp;gt; &lt;br /&gt;
            @Html.LabelFor(model =&amp;gt; model.Message) &lt;br /&gt;
        &amp;lt;/div&amp;gt; &lt;br /&gt;
        &amp;lt;div class="editor-field"&amp;gt; &lt;br /&gt;
            @Html.TextBoxFor(model =&amp;gt; model.Message) &lt;br /&gt;
            @Html.ValidationMessageFor(model =&amp;gt; model.Message) &lt;br /&gt;
        &amp;lt;/div&amp;gt; &lt;br /&gt;
        &amp;lt;p&amp;gt; &lt;br /&gt;
            &amp;lt;input type="submit" value="Send" /&amp;gt; &lt;br /&gt;
        &amp;lt;/p&amp;gt; &lt;br /&gt;
    &amp;lt;/fieldset&amp;gt; &lt;br /&gt;
}&lt;/p&gt;
&lt;p&gt;Besides my personal branding, the first thing you might notice is that the Razor view engine is much cleaner than the ASPX view engine. Binding directives, “&amp;lt;%= … %&amp;gt;”, are replaced by "@…”. The helpers and logic are the same.  MVC 3 has more helpers, but I’m not covering those in this post.&lt;/p&gt;
&lt;p&gt;Notice the &lt;em&gt;@model&lt;/em&gt; directive at the top of the View. This is the new way to specify that this is a strongly typed view.  It’s new for the latest release of MVC 3 also because the strongly typed view syntax was more verbose in the previous MVC3 release. @ScottGu does a good job of covering &lt;a target="_blank" href="http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx"&gt;Razor&lt;/a&gt; in his blog and in subsequent posts.&lt;/p&gt;
&lt;p&gt;A code block, denoted by “@{ … }”, follows the &lt;em&gt;@model&lt;/em&gt; directive, where you can write multiple lines of code.  &lt;em&gt;View.Title&lt;/em&gt; demonstrates a new feature in Razor, using the new dynamic type feature added to C# 4.0.  There is no &lt;em&gt;Title&lt;/em&gt; property on &lt;em&gt;View&lt;/em&gt;. Behind the scenes, the syntax is really &lt;em&gt;View[“Title”]&lt;/em&gt;, which you would have used in MVC 2; more discussion later to round out the picture and show how this is used.  &lt;em&gt;Layout&lt;/em&gt; is analogous to an ASPX Master page and I’ll discuss that in a moment.&lt;/p&gt;
&lt;p&gt;A very nice feature of Razor is that you don’t need to block off normal code with &lt;em&gt;&amp;lt;%&lt;/em&gt; and &lt;em&gt;%&amp;gt;&lt;/em&gt;. As demonstrated by the &lt;em&gt;using&lt;/em&gt; statement, all you need to do is use the &lt;em&gt;@&lt;/em&gt; prefix, as in &lt;em&gt;@using&lt;/em&gt;, and Razor will recognize the difference between code and HTML. This was a normal &lt;em&gt;*.cshtml&lt;/em&gt; View page; layout pages, which I breezed over, use similar syntax.&lt;/p&gt;
&lt;h4&gt;The Layout Page&lt;/h4&gt;
&lt;p&gt;Instead of Master pages, Razor has Layout pages. Many of the concepts between Master and Layout are the same, except for the syntax. In your VS 2010 project structure, Layout pages reside in Views\Shared, just like Master pages.  Here’s the (work in progress) Layout page for C# Station:&lt;/p&gt;
&lt;p&gt;&amp;lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "&lt;a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&amp;quot;"&gt;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&lt;/a&gt;&amp;gt; &lt;br /&gt;
&amp;lt;html xmlns="&lt;a href="http://www.w3.org/1999/xhtml&amp;quot;"&gt;http://www.w3.org/1999/xhtml"&lt;/a&gt;&amp;gt; &lt;br /&gt;
&amp;lt;head&amp;gt; &lt;br /&gt;
    &amp;lt;title&amp;gt;@View.Title&amp;lt;/title&amp;gt; &lt;br /&gt;
    &amp;lt;link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /&amp;gt; &lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;/p&gt;
&lt;p&gt;&amp;lt;body&amp;gt; &lt;br /&gt;
    &amp;lt;div class="page"&amp;gt;&lt;/p&gt;
&lt;p&gt;        &amp;lt;div id="header"&amp;gt; &lt;br /&gt;
            &amp;lt;div id="title"&amp;gt; &lt;br /&gt;
                &amp;lt;h1&amp;gt;C# Station&amp;lt;/h1&amp;gt; &lt;br /&gt;
            &amp;lt;/div&amp;gt;&lt;/p&gt;
&lt;p&gt;            &amp;lt;div id="logindisplay"&amp;gt; &lt;br /&gt;
                @Html.Partial("_LogOnPartial") &lt;br /&gt;
            &amp;lt;/div&amp;gt;&lt;/p&gt;
&lt;p&gt;            &amp;lt;div id="menucontainer"&amp;gt;&lt;/p&gt;
&lt;p&gt;                &amp;lt;ul id="menu"&amp;gt; &lt;br /&gt;
                    &amp;lt;li&amp;gt;@Html.ActionLink("Home", "Index", "Home")&amp;lt;/li&amp;gt; &lt;br /&gt;
                    &amp;lt;li&amp;gt;@Html.ActionLink("About", "Index", "About")&amp;lt;/li&amp;gt; &lt;br /&gt;
                    &amp;lt;li&amp;gt;@Html.ActionLink("Contact", "Contact", "About")&amp;lt;/li&amp;gt; &lt;br /&gt;
                &amp;lt;/ul&amp;gt;&lt;/p&gt;
&lt;p&gt;            &amp;lt;/div&amp;gt; &lt;br /&gt;
        &amp;lt;/div&amp;gt;&lt;/p&gt;
&lt;p&gt;        &amp;lt;div id="main"&amp;gt; &lt;br /&gt;
            @RenderBody() &lt;br /&gt;
            &amp;lt;div id="footer"&amp;gt; &lt;br /&gt;
            &amp;lt;/div&amp;gt; &lt;br /&gt;
        &amp;lt;/div&amp;gt; &lt;br /&gt;
    &amp;lt;/div&amp;gt; &lt;br /&gt;
&amp;lt;/body&amp;gt; &lt;br /&gt;
&amp;lt;/html&amp;gt;&lt;/p&gt;
&lt;p&gt;If you recall from the last section, I discussed how the &lt;em&gt;Title&lt;/em&gt; in &lt;em&gt;View.Title&lt;/em&gt; was using the dynamic typing features in C#. In the &lt;em&gt;&amp;lt;head&amp;gt;&lt;/em&gt; you can see how &lt;em&gt;&amp;lt;title&amp;gt;&lt;/em&gt; is set, using this dynamic type.  This  is easier to type, read, and eliminates needing to explicitly use string indexes.&lt;/p&gt;
&lt;p&gt;Again, you can see how the &lt;em&gt;@Url&lt;/em&gt; and &lt;em&gt;@Html&lt;/em&gt; syntax helps reduce typing and results in cleaner code.&lt;/p&gt;
&lt;p&gt;The linkage between View and Layout occurs at &lt;em&gt;@RenderBody()&lt;/em&gt;.  The View specifies what the &lt;em&gt;Layout&lt;/em&gt; is and the Layout page specifies where where the contents of the view are rendered. There are more Layout features that allow you to define where parts of the View render for more sophisticated scenarios, but what you’re seeing here covers many situations, is minimal syntax, and very simple.&lt;/p&gt;
&lt;p&gt;Next, we’ll take a step back to the controller so we can round out the discussion with the business logic that makes this &lt;em&gt;Contact&lt;/em&gt; form work.&lt;/p&gt;
&lt;h4&gt;The Business Logic&lt;/h4&gt;
&lt;p&gt;Clicking the input button, from the code in the previous section on The View, posts the form contents to the &lt;em&gt;Contacts&lt;/em&gt; action in the &lt;em&gt;About&lt;/em&gt; controller, repeated here for your convenience:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
        [HttpPost]
        public ActionResult Contact(ContactViewModel contactVM)
        {
            if (!ModelState.IsValid)
            {
                return View(contactVM);
            }

            var contact = new Contact
            {
                From = contactVM.From,
                Subject = contactVM.Subject,
                Message = contactVM.Message
            };

            new Email().Send(contact);

            return RedirectToAction("ContactConfirm");
        }&lt;/pre&gt;
&lt;p&gt;I can validate the model because of the annotations in &lt;em&gt;ContactViewModel&lt;/em&gt;. If the model is valid, I populate the business object, of type &lt;em&gt;Contact&lt;/em&gt;, which is passed to the &lt;em&gt;Send&lt;/em&gt; method of an instance of another custom business object named &lt;em&gt;Email&lt;/em&gt;. Here’s &lt;em&gt;Contact&lt;/em&gt;:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
namespace CssMvc.Library
{
    public class Contact
    {
        public string From { get; set; }

        public string Subject { get; set; }

        public string Message { get; set; }
    }
}&lt;/pre&gt;
&lt;p&gt;You can see that &lt;em&gt;Contact&lt;/em&gt; looks nearly identical to &lt;em&gt;ContactViewModel&lt;/em&gt;. A common question is “Why duplicate the same object in two places?”. Really, this isn’t duplication. &lt;em&gt;ContactViewModel&lt;/em&gt; has annotations that are only meaningful in the presentation layer. You don’t want annotations in your business objects because it makes them only usable in a context that understands the annotations. Before you ding me for splitting hairs, there’s more to the value of separating the ViewModel from the business model.&lt;/p&gt;
&lt;p&gt;You can’t see it in this example, because both objects contain the same fields, but in most scenarios the ViewModel differs in content and structure from the business model.  The business logic will often return a set of data in a shape that is either flat or separated from different calls into business logic. However, the ViewModel should shape the data for how it will appear on the screen.  If you let me wave my hands for a moment -- you could have some basic information, such as a &lt;em&gt;Product&lt;/em&gt; defined by fields in a &lt;em&gt;ProductViewModel&lt;/em&gt;, and then have details of that product in a &lt;em&gt;List&amp;lt;ProductDetailViewModel&amp;gt;&lt;/em&gt;. Coming from your repository, this data might be separate and you would need to combine it into a single ViewModel object, in a form that mirrors the HTML layout in the View. &lt;/p&gt;
&lt;p&gt;Another aspect to be aware of is that the business model will often contain more data than the view requires. Model binding is an automatic process (can be custom, but that’s orthogonal to the point I’m trying to make) and you don’t want to waste CPU cycles on trying to bind business object fields that aren’t being used.&lt;/p&gt;
&lt;p&gt;You might then wonder, “What if you wrote the business logic to return the data in the right shape?”.  However, that’s just plain bass-ackwards to proper architecture and design because the business logic shouldn’t have any knowledge of the presentation layer.  Besides, like annotations, that would tie your business logic to a particular implementation, precluding reuse. To continue the focus on separate business logic, here’s the &lt;em&gt;Email&lt;/em&gt; implementation:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
using System.Configuration;
using System.Net.Mail;

namespace CssMvc.Library
{
    public class Email
    {
        public void Send(Contact contact)
        {
            MailMessage mail = new MailMessage(
                contact.From,
                ConfigurationManager.AppSettings[Keys.ContactToEmail],
                contact.Subject,
                contact.Message);

            new SmtpClient().Send(mail);
        }
    }
}&lt;/pre&gt;
&lt;p&gt;My mail server configuration is in &lt;em&gt;Web.config&lt;/em&gt; &lt;em&gt;system.net\mailSettings&lt;/em&gt; and &lt;em&gt;Keys&lt;/em&gt; is a class I use to add a set of &lt;em&gt;const&lt;/em&gt; &lt;em&gt;string&lt;/em&gt; fields to avoid &lt;em&gt;string&lt;/em&gt; typos in my code. Frequently, I’ll encounter a need to send email in different configurations, so it’s just easy to create an &lt;em&gt;Email&lt;/em&gt; class and group the different email methods in one place.&lt;/p&gt;
&lt;p&gt;Notice the&lt;em&gt; CssMvc.Library&lt;/em&gt; namespace (&lt;em&gt;Css&lt;/em&gt; means C# Station, in case you were subliminally confused with some other meaning), which implies a separation between the MVC code and the business logic. In fact, the separation is explicit because I put the business logic in a separate class library. This is handy for a number of reasons, but I’ll leave that for another discussion; I personally like the explicit separation between presentation and business logic.&lt;/p&gt;
&lt;h4&gt;Summary&lt;/h4&gt;
&lt;p&gt;You’ve seen how I created a simple &lt;em&gt;Contact&lt;/em&gt; form, combining current MVC 2 coding techniques with new MVC 3 features. The most noticeable change in MVC 3 is the Razor view engine.  As you see, the coding experience is quicker and cleaner.  I’d also like to give honorable mention to the clever use of dynamic typing, as demonstrated with the&lt;em&gt; View.Title&lt;/em&gt; property, which makes &lt;em&gt;View&lt;/em&gt; model dictionary access easier to create and read.  I finally got around to discussing my views on separation of presentation and business logic by describing why I think the ViewModel should be separate from the business model and how I place business logic into a separate library.  Most of the code shown here is on the Happy Path, except for field validation, but it simplified the example and hopefully let me share something you might find useful.&lt;/p&gt;
&lt;p&gt;Joe&lt;/p&gt; &lt;img src="http://geekswithblogs.net/WinAZ/aggbug/142531.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Joe Mayo</dc:creator>
            <guid>http://geekswithblogs.net/WinAZ/archive/2010/10/30/an-mvc-3-contact-form.aspx</guid>
            <pubDate>Sun, 31 Oct 2010 00:27:57 GMT</pubDate>
            <comments>http://geekswithblogs.net/WinAZ/archive/2010/10/30/an-mvc-3-contact-form.aspx#feedback</comments>
            <slash:comments>2</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/WinAZ/comments/commentRss/142531.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/WinAZ/services/trackbacks/142531.aspx</trackback:ping>
        </item>
        <item>
            <title>Named Arguments Can Improve Readability</title>
            <link>http://geekswithblogs.net/WinAZ/archive/2010/10/11/named-arguments-can-improve-readability.aspx</link>
            <description>&lt;p&gt;Using named arguments everywhere is tedious and unnecessary, but can be applied as needed to improve the readability of your code.  Here’s an example, using Directory.Delete() that helps document the meaning of a bool argument:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
Directory.Delete(pathToDelete, recursive: true);&lt;/pre&gt;
&lt;p&gt;If Directory.Delete was your own code, you could re-write the parameter to use an Enum and get away from the bool code smell.  However, Directory is a class in the .NET Framework’s System.Diagnostics namespace, which demonstrates a situation that you can’t change yourself.  There might be other ways to make this code self documenting, but now that we have named arguments, it’s pretty easy to add the name whenever you think it might help.&lt;/p&gt;
&lt;p&gt;Joe&lt;/p&gt; &lt;img src="http://geekswithblogs.net/WinAZ/aggbug/142235.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Joe Mayo</dc:creator>
            <guid>http://geekswithblogs.net/WinAZ/archive/2010/10/11/named-arguments-can-improve-readability.aspx</guid>
            <pubDate>Mon, 11 Oct 2010 17:04:27 GMT</pubDate>
            <comments>http://geekswithblogs.net/WinAZ/archive/2010/10/11/named-arguments-can-improve-readability.aspx#feedback</comments>
            <wfw:commentRss>http://geekswithblogs.net/WinAZ/comments/commentRss/142235.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/WinAZ/services/trackbacks/142235.aspx</trackback:ping>
        </item>
    </channel>
</rss>
