LINQ

Introduction to The One ASP.NET Platform/Ecosystem

December 25, 2012 .NET, .NET Framework, .NET Framework 4.5, ADO.NET, All, ASP.NET, ASP.NET 4.5, ASP.NET AJAX, ASP.NET MVC, ASP.NET MVP, C#.NET, Community, HTML, HTML5, IIS, JavaScript, JavaScript, jQuery, JQuery Mobile, KnowledgeBase, LINQ, Microsoft, MSDN, SignalR, Updates, VB.NET, VisualStudio, VS2012, WCF, Web, Web API No comments

Introduction

ASP.NET has travelled a long way through evolutions. Earlier when ASP.NET 1.0 was released as part of .NET Framework 1.0 in Jan 2002, there was only ASP.NET – a framework for building dynamic web applications and it provided lots of flexibility web developers in building robust, dynamic web applications.  ASP.NET was and is the successor to Microsoft’s Active Server Pages (ASP) technology.

ASP.NET is built on the Common Language Runtime (CLR), allowing programmers to write ASP.NET code using any supported .NET language. The ASP.NET SOAP extension framework allows ASP.NET components to process SOAP messages.

From that, today we reached ASP.NET 4.5 and platform/web framework has changed a lot through the 10 years of journey.

Before going further lets go through a quick summery of additions in each releases:

ASP.NET 1.0 (January 16, 2002)

  • Object-oriented Web application development supporting inheritance, polymorphism and other standard OOP features
  • Support for generic HTML controls and ASP.NET dynamic web controls
  • Event based programming
  • The developer can make use of DLL class libraries and other features of the Web server to build more robust applications that do more than simply rendering HTML.
  • Integrated development support using Visual Studio .Net 2002

ASP.NET 1.1 (April 24, 2003)

  • With ASP.NET 1.1 – an update to .NET framework 1.0 called as .Net framework 1.1 – we received support for Mobile Web Controls, Automatic input validation
  • Integrated development support using Visual Studio .Net 2003

ASP.NET 2.0 (November 7, 2005)

ASP.NET 2.0 introduced major updates to ASP.NET framework with introduction of Master pages and new data controls.

The interesting features included in this release were:

  • Integrated development support using Visual Studio 2005
  • New data controls (GridView, FormView, DetailsView)
  • New technique for declarative data access (SqlDataSource, ObjectDataSource, XmlDataSource controls)
  • Navigation controls
  • Master pages
  • Login controls
  • Themes
  • Skins
  • Web parts
  • Personalization services
  • Full pre-compilation
  • New localization technique
  • Support for 64-bit processors
  • Provider class model
  • Web Sites projects are introduced. An alternative to Web Application project model in earlier versions.
  • ASP.NET AJAX has been introduced as a separate installer. Included ScriptManager, UpdatePanel etc.

ASP.NET 3.5 (November 19, 2007)

This was an incremental update to ASP.NET 2.0 and .NET Framework 2.0. Base level the Runtime was depending on .NET Framework 2.0 and set of additional runtime extension components been introduced in this release.

The interesting features included in this release were:

  • Integrated development support using Visual Studio 2008
  • New data controls (ListView, DataPager, LinqDataSource)
  • ASP.NET AJAX included as part of the framework
  • Support for HTTP pipelining and syndication feeds.
  • WCF support for RSS, JSON, POX and Partial Trust
  • All the .NET Framework 3.5 changes, like LINQ etc.

With .NET Framework 3.5 Service Pack 1, some more features been introduced

  • Integrated development support using Visual Studio 2008 – Service Pack 1
  • Incorporation of ASP.NET Dynamic Data
  • Entity Framework support
  • Support for controlling browser history in an ASP.NET AJAX application
  • Ability to combine multiple JavaScript files into one file for more efficient downloading
  • New namespaces System.Web.Abstractions and System.Web.Routing
  • JQuery is included as part of the template.
  • ASP.NET MVC is born

Now ASP.NET framework is spitted in to three based on the purpose

ASP.NET Core Services – all the major ASP.NET runtime components has been built in to this and will act as a base layer for all other ASP.NET components such as Web Forms, MVC, Dynamic Data etc.

Now we have three Presentation Frameworks/Components that utilizes the ASP.NET Core runtime components

  1. ASP.NET Web Forms – based on traditional ASP.NET web application model – dynamic *.aspx pages with code behind file.
  2. ASP.NET MVC – based on MVC model – *.aspx pages for View, no code behind file. Simply depended on Controller and model.
  3. ASP.NET Dynamic data – the quick and easy – rapid application development model with help of LINQ and Entity Framework. ASP.NET Dynamic Data helps you quickly build a fully customizable, data-driven application without writing code. Dynamic Data provides a rich scaffolding framework that is easily extensible by using the traditional ASP.NET programming model.

ASP.NET 4.0 (April 12, 2010)

The .NET Framework version 4 includes enhancements for ASP.NET 4 in targeted areas. Visual Studio 2010 and Microsoft Visual Web Developer Express also include enhancements and new features for improved Web development.

The interesting features included in this release were:

  • Integrated development support using Visual Studio 2010
  • jQuery Included with Web Forms and MVC
  • Content Delivery Network Support
  • Setting Meta Tags with the Page.MetaKeywords and Page.MetaDescription Properties
  • ASP.NET MVC 3.0 with Web Pages and razor support
  • IISExpress Support through Service Pack1
  • and more… You can read about it in detail on the MSDN page What’s New in ASP.NET 4 and Visual Web Developer

 

ASP.NET 4.5 (August 15, 2012)

This was a long awaited release since ASP.NET 4.0, which includes the new improved support for Web Pages, MVC and new Web API support. With the release of .NET Framework 4.5 and Visual Studio 2012, decided to go away from Service Packs and release incremental updates whenever available.

The interesting features included in this release were:

  • Async support – HttpRequest, Response, HTTP Modules and Handlers are capable of handling Async request and responses.
  • AntiXSS library is integrated
  • WebSockets protocol support
  • Lazy request validation
  • ASP.NET Web Forms – Model binding similar to ASP.NET MVC
  • HTML5 support
  • ASP.NET MVC 4, Web Pages 2.0, Web API, ASP.NET MVC 4 – Mobile Web Templates using jQuery Mobile
  • and more… You can read about it in detail on the MSDN page What’s New in ASP.NET 4.5 and Visual Web Developer

ASP.NET and Web Tools 2012.2 update

This .2 update adds a number of new templates and features including:

  • Enhancements to Web Publishing
  • New Web API functionality
  • New templates for Facebook Application and Single Page Application
  • Real-time communication via ASP.NET SignalR
  • Extensionless Web Forms via ASP.NET Friendly URLs
  • Support for the new Windows Azure Authentication
  • and more… You can read about it in detail on the MSDN page What’s New in ASP.NET and Web Tools 2012.2 Update

SignalR

SignalR is a new member of the ASP.NET family that facilitates adding real-time functionality to web applications using WebSockets and other down-level transports. SignalR is a self-contained library installed via NuGet that is targeting a 1.0 RTW as part of the Fall Update. This will include item templates for adding SignalR connections and hubs to an ASP.NET application as well as a full project template that integrates with ASP.NET MVC and ASP.NET Web API.

[ Quoted from http://aspnet.codeplex.com  ]

THE ONE ASP.NET PLATFORM

Now the ASP.NET ecosystem would look as in the image, with 2012.2 release: Single platform – multiple, extensible solutions

All the parts of ASP.NET, all the subsystems are all part of the larger ASP.NET community 

[Image courtesy Scott Hanselman’s blog]

Scott Hanselman of Microsoft Quotes:

The idea behind One ASP.NET is that we want folks to be able to make apps that have real-time components with SignalR, clean, simple APIs with Web API, all in one pages with KnockoutJS, pages with MVC, Web Forms or Web Pages, as well as existing ASP.NET systems like OData, ASMX, and more.

We want open source projects like JSON.NET, KnockoutJS, SignalR, Backbone, MongoDB, Scaffolding, NHIbernate, Ninject (and the list goes on) to all play in the same ASP.NET LEGO sandbox.

We’ll put all these subcomponents on NuGet and they’ll live alongside community components and you’ll be able to build ASP.NET applications starting from some base template and add just the pieces you want. We are getting there. We want folks to use the parts they want, and swap out the parts they don’t. Everything should work together.

ScottGu Quotes
The new runtime functionality is delivered to ASP.NET via additional NuGet packages. This means that installing this update does not make any changes to the existing ASP.NET binaries, and thus does not cause any compatibility issues with existing projects. New projects will contain the new functionality and existing projects can be updated with the new NuGet packages.

You can further read about it through Scott Hanselman’s article and ScottGu’s blog 
 

Conclusion

Now with ASP.NET 4.5 and Updates we reached a place where we have a vast variety of technologies to choose from, to develop rich, dynamic web applications for Desktop browsers as well as for mobile browsers.

ASP.NET Ecosystem is growing and is moving in the right pace with the release to open source development of most of the components through http://aspnet.codeplex.com/ 

It is challenging and interesting for ASP.NET developers to be able to develop using such cutting edge technologies.

Information Sources & Courtesy: Wikipedia, MSDN and Microsoft Developer blogs

Sorting a List in ASC/DESC order using LINQ

April 23, 2011 .NET, .NET Framework, All, C#.NET, General, LINQ, Microsoft No comments

Most of the developers are unaware of the capabilities of .NET 3.5 and above. Still going for old way of sorting calling List.Sort and implementing a delegate or lambda expression to specify the sort expression.  But the slight problem is what you will do for “ASCENDING”  and “DESCENDING” order sorting. You have to specify the delegate logic for sorting in Ascending and another logic for sorting in descending order.

I am providing you some sample code to give a clear picture. The sample code consists of the following and also read through the inline comments in the code.

Sample Code 1 : Sorting using List.Sort and delegate function to implement the comparison logic.

Sample Code 2 : Sorting using Linq 2 Objects => “OrderBy” and “OrderByDescending()” extension methods.

</p>
<p>using System;<br />
using System.Collections;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Web;</p>
<p>using WebApplication1;</p>
<p>namespace WebApplication1<br />
{<br />
    /// &lt;summary&gt;<br />
    ///<br />
    /// &lt;/summary&gt;<br />
    public class CustomerTest<br />
    {</p>
<p>        public void TestCustomerSort()<br />
        {</p>
<p>            //Normal way using delegates or lambda expression and custom sorting logic. </p>
<p>            List&lt;Customer&gt; normalSortASC = GetCustomerSortedNormalWay(SortDir.ASC);</p>
<p>            List&lt;Customer&gt; normalSortDESC = GetCustomerSortedNormalWay(SortDir.DESC);</p>
<p>            //LINQ way.. LinQ does sorting for you, just utilize the LinQ-2-Objects classes firmly that's all.<br />
            List&lt;Customer&gt; linqSortASC = GetCustomerSortedLinqWay(SortDir.ASC);</p>
<p>            List&lt;Customer&gt; linqSortDESC = GetCustomerSortedLinqWay(SortDir.DESC);</p>
<p>            HttpContext.Current.Response.Write(&quot;Test Success&quot;);<br />
        }</p>
<p>        /// &lt;summary&gt;<br />
        /// Gets the dummy customer data.<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public List&lt;Customer&gt; GetDummyCustomerData()<br />
        {<br />
             List&lt;Customer&gt; customers = new List&lt;Customer&gt;();</p>
<p>            customers.Add(new Customer()<br />
                              {<br />
                                  CustomerID =  &quot;CA1&quot;,<br />
                                  ContactName =  &quot;Alpha&quot;<br />
                              });</p>
<p>            customers.Add(new Customer()<br />
            {<br />
                CustomerID = &quot;AA3&quot;,<br />
                ContactName = &quot;Beta&quot;<br />
            });</p>
<p>            customers.Add(new Customer()<br />
            {<br />
                CustomerID = &quot;AA1&quot;,<br />
                ContactName = &quot;Gamma&quot;<br />
            });</p>
<p>            customers.Add(new Customer()<br />
            {<br />
                CustomerID = &quot;A11&quot;,<br />
                ContactName = &quot;Zetta&quot;<br />
            });</p>
<p>            return customers;<br />
        }</p>
<p>        /// &lt;summary&gt;<br />
        /// Gets the customer sorted normal way.<br />
        /// &lt;/summary&gt;<br />
        /// &lt;param name=&quot;order&quot;&gt;The order.&lt;/param&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public List&lt;Customer&gt; GetCustomerSortedNormalWay(SortDir order)<br />
        {<br />
            List&lt;Customer&gt; customers = GetDummyCustomerData();</p>
<p>             switch(order)<br />
             {<br />
                 case SortDir.ASC:<br />
                     customers.Sort(delegate(Customer a, Customer b)<br />
                                                    {<br />
                                                        return a.CustomerID.CompareTo(b.CustomerID);<br />
                                                    });</p>
<p>                      //---OR --- Using lambda expression like this.  </p>
<p>                     customers.Sort((a, b) =&gt; a.CustomerID.CompareTo(b.CustomerID)); //awkward isn't it. need to specify the two objects to compare against a</p>
<p>                     break;</p>
<p>                 case SortDir.DESC:<br />
                     customers.Sort(delegate(Customer a, Customer b)<br />
                     {<br />
                         return b.CustomerID.CompareTo(a.CustomerID); // Reversing the sort based on &quot;b&quot;<br />
                     });</p>
<p>                     //---OR --- Using lambda expression like this.  </p>
<p>                     customers.Sort((a, b) =&gt; b.CustomerID.CompareTo(a.CustomerID)); //awkward isn't it. need to specify the two objects to compare against and reverse the comparison logic. not looking good and confusing. </p>
<p>                     break;</p>
<p>                 default:<br />
                     customers = GetCustomerSortedNormalWay(SortDir.ASC);<br />
                     break;<br />
             }</p>
<p>            return customers;<br />
        }</p>
<p>        /// &lt;summary&gt;<br />
        /// Gets the customer sorted LINQ way.<br />
        /// &lt;/summary&gt;<br />
        /// &lt;param name=&quot;order&quot;&gt;The order.&lt;/param&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public List&lt;Customer&gt; GetCustomerSortedLinqWay(SortDir order)<br />
        {<br />
            List&lt;Customer&gt; customers = GetDummyCustomerData();</p>
<p>            switch (order)<br />
            {<br />
                case SortDir.ASC:<br />
                    customers = (customers.OrderBy(c =&gt; c.CustomerID)).ToList(); // Just a simple line. Specifying just specify sort key as &quot;CustomerID&quot;, and linq does the fancy sorting for you.</p>
<p>                    break;</p>
<p>                case SortDir.DESC:<br />
                    customers = (customers.OrderByDescending(c =&gt; c.CustomerID)).ToList(); // Just a simple line ca;; &quot;OrderByDescending&quot; and just specify sort key as &quot;CustomerID&quot;, and linq does the fancy sorting for you.<br />
                    break;</p>
<p>                default:<br />
                    customers = GetCustomerSortedNormalWay(SortDir.ASC);<br />
                    break;<br />
            }</p>
<p>            return customers;<br />
        }</p>
<p>    }</p>
<p>    /// &lt;summary&gt;<br />
    /// Sort Direction - Enum dictionary<br />
    /// &lt;/summary&gt;<br />
    public enum SortDir<br />
    {<br />
        ASC,<br />
        DESC,<br />
        Default<br />
    }<br />
}</p>
<p>

 

My intension with the post is not saying that still following old ways of sorting is bad. But just to let you remind you about the alternative ways of doing it in .NET 3.5 and .NET 4.0.  If newer .NET frameworks have a better way of doing it, why don’t we utilize that and increase our productivity.

Using linq2Objects saves our precious time as well and number of lines we write also minimized and helps us in managing the source code in more better way.

 

Hope this is helpful for the needed..

Use LoadDataOptions class in LINQ for immediate filtering and loading of relational data

November 17, 2010 .NET, All, General, LINQ, Microsoft 1 comment

LINQ is one of the nice feature every .NET developer would love to appreciate Microsoft for. I do not wish to explain much about linq, I am getting in to topic with a belief that you will have minimum understanding of LINQ and how it helps in data access from .NET Framework 3.5 onwards.

Consider the following example on linQ using Northwind Database.

 

</p>
<p>            NorthwindDataContext db = new NorthwindDataContext();</p>
<p>            //Normal linq query fetch only ORDER Information<br />
            var orderQuery = from order in db.Orders<br />
                             select order;</p>
<p>            List&lt;Order&gt; orderList = orderQuery.ToList();<br />

 

LINQ will not load/fetch all relative information to Order class Since it is using Lazy loading. if we consider the above example it will return only Order information.

When you query for an object, you actually retrieve only the object you requested. The related objects are not automatically fetched at the same time. (For more information, see Querying Across Relationships (LINQ to SQL).)

The DataLoadOptions class  in System.Data.Linq namespace provides two methods to achieve immediate loading of specified related data. The LoadWith method allows for immediate loading of data related to the main target. The AssociateWith method allows for filtering related objects.

So I modified my above query to use DataLoadOptions to load associated Customer,Employee,Order_Details,Shipper information also within each Order object.

Now the modified code looks like

 

</p>
<p>using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Text;<br />
using System.Data.Linq;</p>
<p>namespace LINQSampleApp<br />
{<br />
    class Program<br />
    {<br />
        static void Main(string[] args)<br />
        {</p>
<p>            NorthwindDataContext db = new NorthwindDataContext();</p>
<p>            //Normal linq query fetch only ORDER Information<br />
            var orderQuery = from order in db.Orders<br />
                             select order;</p>
<p>            List&lt;Order&gt; orderList = orderQuery.ToList();</p>
<p>            //LINQ doesn't load/fetch all relational information to Order class.<br />
            //Since it's using Lazy loading, if we consider the above example it will return only<br />
            //Order information.</p>
<p>            /*<br />
             * Consider the Scenario:<br />
             * ---------------------------<br />
             * Suppose I would have to fetch all Order information and order<br />
             * details information and customer information within the ORDER entity<br />
             * because Order_Details, Customers are child or relational data for the order<br />
             * We could do this with a single select query like above.<br />
             * But we have to specify the explicit information about relational data to be loaded/retrieved<br />
             * within DataLoadOptions class. DataLoadOptions we configures the relational data mappins and<br />
             * conditions for filling child entities.<br />
             *<br />
             * Look in to the following example.<br />
             * */</p>
<p>            db.Dispose();<br />
            //disposing previous data context. Because it will not allow us to specify LoadOptions after fetching information.<br />
            //Keep in mind, create loadoptions and assign it before the execution of main query.</p>
<p>            NorthwindDataContext db1 = new NorthwindDataContext();</p>
<p>            //Creating an instance of DataLoadOptions class<br />
            DataLoadOptions loadOptions = new DataLoadOptions();</p>
<p>            //Specifying the mappings using Load() method to load relational data to the parent entity</p>
<p>            //Specifying to load associated Customer information to each instance of Order class<br />
            loadOptions.LoadWith&lt;Order&gt;( c =&gt; c.Customer);</p>
<p>            //Specifying to load associated Employee information to each instance of Order class<br />
            loadOptions.LoadWith&lt;Order&gt;(c =&gt; c.Employee);</p>
<p>            //Specifying to load associated Order_Details information to each instance of Order class<br />
            loadOptions.LoadWith&lt;Order&gt;(c =&gt; c.Order_Details);</p>
<p>            //Specifying to load associated Shipper_Details information to each instance of Order class<br />
            loadOptions.LoadWith&lt;Order&gt;(c =&gt; c.Shipper);</p>
<p>            //Assign the loadOptions class to NorthwindDataContext instance 'db'<br />
            db1.LoadOptions = loadOptions;</p>
<p>            //Now lets run our old query again</p>
<p>            var orderFullQuery = from order in db1.Orders<br />
                             select order;</p>
<p>            List&lt;Order&gt; orderFullList = orderFullQuery.ToList();</p>
<p>            Console.ReadLine();<br />
        }<br />
    }<br />
}</p>
<p>

 

Quite interesting is it?.  With a single fetch we can get all relational necessary data for the object requested.

More information read from MSDN Reference about LoadDataOptions class

Courtesy : MSDN Library