Building Windows Phone Apps with Visual Studio 2010

December 15, 2011 Leave a comment

Building Applications for Windows Phone “Mango” Jump Start” was hosted by Microsoft Learning as a follow-up to last year’s Windows Phone 7 Jump Start sessions.

This course is specially tailored for developers looking to build cool applications and games for the new Windows Phone Mango Platform.

During this module focused on how to create Windows Phone applications using Visual Studio. This introductory content covers how to create Windows Phone solutions, edit program source files, and add and manage program resources, build and run the solution. Next, it demonstrate options for debugging solutions using the Windows Phone Emulator or an actual

  1. Mango Jump Start (02): Silverlight on Windows Phone—Introduction
  2. Mango Jump Start (03): Silverlight on Windows Phone—Advanced
  3. Mango Jump Start (04): Using Expression to Build Windows Phone Interfaces
  4. Mango Jump Start (05): Windows Phone Fast Application Switching
  5. Mango Jump Start (06): Windows Phone Multi-tasking & Background Tasks
  6. Mango Jump Start (07): Using Windows Phone Resources
    (Bing Maps, Camera, etc.)
  7. Mango Jump Start (08a): Application Data Storage on Windows Phone | Part 1
  8. Mango Jump Start (08b): Application Data Storage on Windows Phone | Part 2
  9. Mango Jump Start (09): Using Networks with Windows Phone
  10. Mango Jump Start (10): Tiles & Notifications on Windows Phone
  11. Mango Jump Start (11a): XNA for Windows Phone | Part 1
  12. Mango Jump Start (11b): XNA for Windows Phone | Part 2
  13. Mango Jump Start (12): Selling a Windows Phone Application

Video Resource

The entire course on building and selling apps for Windows Phone Mango is available in HD quality video on Channel 9.

Checklist for C# Source Code

December 15, 2011 Leave a comment
Category Description
Declarations 1.    Naming. Is variable naming according to company standard?

2.    Naming. Are all variable and function names clear and meaningful?

3.    Strong Types. Are all variables and function arguments of correct size and type?

4.    Scope. No public variables, properties or methods that could be private or protected?

5.    Scope. No variables whose scope could be narrower?

6.    Are all variables and functions used? This does not apply to public declarations in assemblies and libraries.

7.    Proper usage of namespaces.

8.    Proper function-/operator overloading.

9.       Proper usage of copy constructor and assignment operator?

Variables 1.    Initialisation. Are all variables properly initialised?

2.    Values assigned are always within the range of valid values for the type.

Expressions 1.    Arithmetic. No Division by zero, over-/underflow? Also for intermediate results?

2.    Arithmetic. Are all variables in calculations of compatible types?

3.    Arithmetic. No inadvertent (implicit) type conversions?

4.    Boolean expression. Never test for value true or false explicitly.

5.    Boolean expression. Use type bool for holding results.

6.    Operator precedence. Correctly used? Maybe use parentheses for clarification?

Control flow 1.    Return value. Do all control paths in a function yield a correct result or throw an exception otherwise?

2.    Error Handling. Correct usage of error handling?

3.    Error Handling. Try to limit catch (…) {} as much as possible.

4.    Error Handling. No uncaught errors or exceptions?

5.    Loops. No infinite loops? Do all loops terminate?

6.    Loops. Is all indexing in loops correct? (E.g. lower/upper bounds, step size)

7.    Program termination. Can the program terminate properly?

8.    Statements. Do switch- statements cover all necessary possibilities?

APIs 1.    Documentation. Are all properties/methods documented?

2.    Documentation. Is all documentation accurate and up-to-date?

3.    Documentation. Is the documentation accessible and easy to understand?

4.    Documentation. Are examples available for more complex parts?

5.    Arguments. Are all incoming arguments checked for validity? (Unless stated otherwise in the documentation)

6.    Arguments. Correct values for default arguments?

7.    Arguments. Do all outgoing arguments have correct values upon exit?

Formatting 1.    Restrictions. No lines exceed company standard maximum line length?

2.    Restrictions. No functions exceed company standard maximum # of lines?

3.    Complexity. No functions or expressions that should be split into smaller parts?

4.    Indenting. Proper indenting? Correct line continuation?

Miscellaneous 1.    Resources. No memory leaks?

2.    Threading. No deadlocks, race conditions?

3.    Quality. Algorithms, efficiency, maintainability, …

4.    Common sense?

Request Validation – Preventing Script Attacks

This paper describes the request validation feature of ASP.NET where, by default, the application is prevented from processing unencoded HTML content submitted to the server. This request validation feature can be disabled when the application has been designed to safely process HTML data.

Applies to ASP.NET 1.1 and ASP.NET 2.0.

Request validation, a feature of ASP.NET since version 1.1, prevents the server from accepting content containing un-encoded HTML. This feature is designed to help prevent some script-injection attacks whereby client script code or HTML can be unknowingly submitted to a server, stored, and then presented to other users. We still strongly recommend that you validate all input data and HTML encode it when appropriate.

For example, you create a Web page that requests a user’s e-mail address and then stores that e-mail address in a database. If the user enters <SCRIPT>alert(“hello from script”)</SCRIPT> instead of a valid e-mail address, when that data is presented, this script can be executed if the content was not properly encoded. The request validation feature of ASP.NET prevents this from happening.

Why this feature is useful

Many sites are not aware that they are open to simple script injection attacks. Whether the purpose of these attacks is to deface the site by displaying HTML, or to potentially execute client script to redirect the user to a hacker’s site, script injection attacks are a problem that Web developers must contend with.

Script injection attacks are a concern of all web developers, whether they are using ASP.NET, ASP, or other web development technologies.

The ASP.NET request validation feature proactively prevents these attacks by not allowing unencoded HTML content to be processed by the server unless the developer decides to allow that content.

What to expect: Error Page

The screen shot below shows some sample ASP.NET code:

Running this code results in a simple page that allows you to enter some text in the textbox, click the button, and display the text in the label control:

However, were JavaScript, such as <script>alert("hello!")</script> to be entered and submitted we would get an exception:

The error message states that a potentially dangerous Request.Form value was detected and provides more details in the description as to exactly what occurred and how to change the behavior. For example:

Request validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case.

Disabling request validation on a page

To disable request validation on a page you must set the validateRequest attribute of the Page directive to false:

<%@ Page validateRequest="false" %>

Caution: When request validation is disabled, content can be submitted to a page; it is the responsibility of the page developer to ensure that content is properly encoded or processed.

Disabling request validation for your application

To disable request validation for your application, you must modify or create a Web.config file for your application and set the validateRequest attribute of the <pages /> section to false:

<configuration> <system.web> <pages validateRequest="false" /> </system.web> </configuration>

If you wish to disable request validation for all applications on your server, you can make this modification to your Machine.config file.

Caution: When request validation is disabled, content can be submitted to your application; it is the responsibility of the application developer to ensure that content is properly encoded or processed.

The code below is modified to turn off request validation:

Now if the following JavaScript was entered into the textbox <script>alert("hello!")</script> the result would be:

To prevent this from happening, with request validation turned off, we need to HTML encode the content.

How to HTML encode content

If you have disabled request validation, it is good practice to HTML-encode content that will be stored for future use. HTML encoding will automatically replace any ‘<’ or ‘>’ (together with several other symbols) with their corresponding HTML encoded representation. For example, ‘<’ is replaced by ‘&lt;’ and ‘>’ is replaced by ‘&gt;’. Browsers use these special codes to display the ‘<’ or ‘>’ in the browser.

Content can be easily HTML-encoded on the server using the Server.HtmlEncode(string) API. Content can also be easily HTML-decoded, that is, reverted back to standard HTML using the Server.HtmlDecode(string) method.

Resulting in:

Enhance your Website with ASP.NET AJAX Extensions

AJAX (Asynchronous JavaScript and XML) is arguably one of the most hyped technology acronyms around. The primary advantage of using AJAX is that page refreshes can be minimized, allowing users to get the information they need quickly and easily through a more rich and functional interface. Ajax accomplishes this by using JavaScript and an XmlHttp object to send data asynchronously from the browser to the Web server and back. So, although AJAX has a lot of marketing-hype surrounding it, the benefits it offers can’t be denied.

Microsoft’s ASP.NET AJAX Extensions provide developers with a quick and simple way to add AJAX functionality into any ASP.NET Website, without requiring in-depth knowledge of JavaScript or other AJAX technologies. This article will demonstrate how you can add AJAX capabilities into a new or existing Website by using a new ASP.NET AJAX server-side control called the UpdatePanel. You’ll see how the UpdatePanel control can be used to allow portions of a page to be updated without requiring the entire page to be posted back to the server and reloaded in the browser. Additional topics covered include:

  • The role of the ScriptManager control
  • Nesting UpdatePanel controls
  • Triggering asynchronous requests
  • Providing progress indicators to end users
  • Interacting with the UpdatePanel on the client-side, using the PageRequestManager class.

Let’s get started by discussing how to get the ASP.NET AJAX Extensions installed and configured.

Installing the ASP.NET AJAX extensions

Before you can use the ASP.NET AJAX UpdatePanel control you need to install the ASP.NET AJAX Extensions, available from http://ajax.asp.net/, on your development machine. Once installed, a new Website template titled “ASP.NET AJAX-Enabled Website” will appear when you first create a new Website using Visual Studio .NET 2005 or Web Developer Express. Select this template when you want to add ASP.NET AJAX functionality into Web pages.

The ASP.NET AJAX Extensions rely upon special HTTP handlers and modules to handle and respond to asynchronous requests sent from a browser. By creating a new ASP.NET AJAX Website in Visual Studio .NET, a web.config file will automatically be created that contains references to a ScriptResource.axd handler as well as a ScriptModule module. The ScriptResource handler dynamically loads JavaScript files into pages that leverage AJAX features while ScriptModule manages HTTP module functionality that is related to request and response messages.

If you’d like to upgrade an existing Website and add ASP.NET AJAX functionality into it you’ll need to ensure that you manually update your site’s web.config file with the proper entries. The easiest way to do this is to create a new ASP.NET AJAX-Enabled Website (as mentioned earlier) and then copy the AJAX-specific portions of web.config to your original web.config file. You’ll of course need to ensure that the ASP.NET AJAX Extensions are also installed on your production server before deploying the updated site.

Adding AJAX functionality into ASP.NET Web Forms

Before the ASP.NET AJAX Extensions were released, developers had to rely on custom AJAX libraries to AJAX-enable a Web site. While these libraries were quite powerful and worked in cross-browser scenarios, they often required a familiarity with JavaScript, and even XML or Web Service technologies. Some of the frameworks were/are susceptible to CSRF (Cross Site Request Forgery) attacks, whereby a hacker could hi-jack AJAX messages and potentially steal information. Fortunately, the ASP.NET AJAX Extensions offer a secure AJAX framework that includes a new server control called the UpdatePanel that hides JavaScript complexities.

The UpdatePanel control allows you to focus on the functionality of your application rather than on programming and understanding AJAX-specific technologies. It performs asynchronous postback operations that update a portion of a page rather than the entire page itself. This technique is often referred to as “partial-page updates“. The UpdatePanel control works by intercepting postback requests triggered by the page and converting them into asynchronous postback calls, which are then sent to the server using the browser’s XmlHttp object. It relies on client-side scripts managed by the ASP.NET AJAX framework to perform this asynchronous functionality.

Before using the UpdatePanel control you must first add into your page an important ASP.NET AJAX control, called the ScriptManager. The ScriptManager handles loading all of the necessary client-side scripts that are required by the UpdatePanel and other AJAX controls in order to make asynchronous AJAX calls. You can drag a ScriptManager control onto a page from the VS.NET toolbox or add it directly into the source code as shown next:

ScriptManager ID=”ScriptManager1″ runat=”server” />

Once a ScriptManager control is added, an UpdatePanel control can then be defined in the page. The UpdatePanel acts as a container in much the same way as the standard ASP.NET Panel control. However, content embedded within the UpdatePanel is wrapped within a template named ContentTemplate. Any content placed within the ContentTemplate is automatically AJAX-enabled. This means that button click or other postback events triggered by controls in the template will be intercepted and converted into asynchronous AJAX calls to the server.

Displaying progress

Although the UpdatePanel is simple to use, you must take the end user into account when using it, especially if you don’t know how long an asynchronous postback may take to complete. Long requests may cause an end user to think that their request has failed or hung and they may start the request again, navigate to a different page or even close the browser. The solution is to provide them with a visual progress indicator so that they know that their request is being processed.

The ASP.NET AJAX Framework includes the UpdateProgress control that can be used to provide users with a visual indication of whether or not their request is still being processed. Listing 2 shows an example of using the UpdateProgress control to display an animated image to an end user, while a Web Service is called that retrieves album information.

You’ll see that the UpdateProgress control has a ProgressTemplate that contains the content to show to the end user, while the UpdatePanel asynchronous postback is processed. Any content type of content (images, flash movies, videos, etc.) can be placed inside of the template. In cases where you’d like the content to take up a fixed amount of space on the page as opposed to dynamically being added, you can set the DynamicLayout property to false.

The UpdateProgress control shown in Listing 2 is embedded directly within the target UpdatePanel. However, it can be embedded elsewhere in the page and linked to the appropriate UpdatePanel by setting its AssociatedUpdatePanelID property to the ID of the UpdatePanel. In cases where quick partial-page updates may occur, and you don’t want the UpdateProgress control to show its content, you can set the DisplayAfter property to the number of milliseconds that you’d like it to wait before displaying progress content. DisplayAfter defaults to a value of 500 milliseconds.

Using triggers

While controls inside of an UpdatePanel control can cause it to perform asynchronous postbacks, other controls defined outside of the UpdatePanel can also act as “triggers” that cause the UpdatePanel to refresh itself with new data. Two types of triggers exist for UpdatePanels including the AsynchronousPostBackTrigger control and PostBackTrigger control.

An AsynchronousPostBackTrigger causes an UpdatePanel‘s content to be updated asynchronously when a specific control’s event is fired such as a Button’s click event or a DropDownList‘s SelectedIndexChanged event. A PostBackTrigger causes a regular postback operation to occur that reloads the entire page. When AJAX-enabling your Websites you’ll normally want to use the AsynchronousPostBackTrigger to stop postback operations from occurring.

In cases where you’d like to prevent controls defined within an UpdatePanel‘s ContentTemplate from triggering an asynchronous postback operation, you can set the UpdatePanel‘s ChildrenAsTriggers property to false and the UpdateMode to “Conditional”. Any events raised by child controls in the ContentTemplate of the control will be ignored, while events raised by triggers such as the one shown in Listing 4 will cause a partial-page update to occur, if needed.

Handling UpdatePanel events on the client

The UpdatePanel control handles all asynchronous requests to the server, so you don’t have to worry about writing JavaScript code. This is great from a productivity and maintenance standpoint but there will be times when you want to know when an UpdatePanel request is going to start, or when data has returned and is about to be updated in the page. For example, you may want to access data returned by an UpdatePanel and use it to make another asynchronous postback request. Or, you may want to animate the UpdatePanel as a request is started so that the end user sees what is happening and knows when content in a particular area of a page has been refreshed. All of this can be done by using a JavaScript class provided by the ASP.NET AJAX script library, called the PageRequestManager.

The PageRequestManager lives in the Sys.WebForms namespace in the ASP.NET AJAX script library and allows you to tie into requests and responses processed by one or more UpdatePanels in a page. It’s responsible for managing partial-page updates that occur within a page as well as managing the client page life-cycle. By using it you can tie into several different events and act upon them. PageRequestManager also exposes properties and methods that can be used to check if asynchronous requests are in process. It can also be used to abort existing requests and even cancel pending requests.

Events exposed by the PageRequestManager class include initializeRequest, beginRequest, pageLoading, pageLoaded and endRequest. The following table provides more details about these events and when they are fired.

Event Description
initializeRequest Raised when an asynchronous postback is first initialized. This event can be used to cancel requests in cases where another request is already in process.
beginRequest Raised when an asynchronous postback begins. This event can be used to animate an UpdatePanel container within a page to provide users with a visual cue that an asynchronous postback request is starting.
pageLoading Raised after data is received from an asynchronous postback request but before the data is updated in the page. This event can be used in cases where you’d like to change data returned from the server using JavaScript or provide an effect on the UpdatePanel to signify that content is about to be updated.
pageLoaded Raised when data in a page is updated after a synchronous or asynchronous request.
endRequest Raised after an asynchronous postback request is completed. Any errors that occurred during the request can be processed here.

To access the PageRequestManager you can call its getInstance() method on the client-side as shown next:

var prm = Sys.WebForms.PageRequestManager.getInstance();

Once the PageRequestManager object is available, you can define event handlers for the different events that it exposes and attach to them. Listing 6 shows how to attach an event handler to the endRequest event and access data returned from the asynchronous postback request.

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest);

function EndRequest(sender, eventArgs)
{
if (eventArgs.get_error() != undefined &&
eventArgs.get_error().httpStatusCode == ‘500’)
{
var errorMessage = eventArgs.get_error().message;
eventArgs.set_errorHandled(true);
alert(errorMessage);
}
else
{
GetMap($get(“hidField”).value);
}
}

Notice that the parameter signature for the EndRequest() event handler mirrors the one found in the .NET framework where the sender of the event as well as any event arguments are passed as parameters. The eventArgs parameter can be used to check if any errors occurred during the request by calling the error property which can be used to access the HTTP status code of the request. If a 500 error is found then the code accesses the error message by calling the message property, marks that the error has been handled and shows the error message to the end user. If no error occurs, a hidden field, named hidField, which is returned from the asynchronous postback, is accessed to get a value needed by a GetMap() method, which is used to display a Virtual Earth map.

The PageRequestManager can also be used to abort or cancel asynchronous postback requests by handling the initRequest event. Listing 7 shows an example of canceling a request in cases where an UpdatePanel is in the process of making a request and the end user is impatiently clicking a Refresh button.

Sys.Application.add_init(Init);
var prm = null;

function Init(sender)
{
prm = Sys.WebForms.PageRequestManager.getInstance();
//Ensure EnablePartialRendering isn’t false which will prevent
//accessing an instance of the PageRequestManager
if (prm)
{
if (!prm.get_isInAsyncPostBack())
{
prm.add_initializeRequest(InitRequest);
}
}
}

function InitRequest(sender,args)
{
if (prm.get_isInAsyncPostBack() & args.get_postBackElement().id ==
‘btnRefresh’) {
//Could abort current request by using:  prm.abortPostBack();
//Cancel most recent request so that previous request will complete
//and display
args.set_cancel(true);
alert(“A request is currently being processed.  Please ” +
“wait before refreshing again.”);
}
}

Conclusion

The ASP.NET AJAX Framework provides a simple and productive way to add AJAX functionality into new or existing Websites. With a minimal amount of effort you can make your applications perform more efficiently and provide end users with a richer experience than traditional Web applications by using partial-page updates.

In this article you’ve seen how the ScriptManager and UpdatePanel controls can be used to make asynchronous postbacks from the browser to the server and how different types of triggers can initiate the requests. You’ve also seen how UpdatePanel controls can be nested to provide a master-details style view of data and how the UpdateMode and ChildrenAsTriggers properties can control how and when an UpdatePanel‘s content is updated. Finally, you’ve seen how the PageRequestManager client-side class can be used to notify you of partial-page update requests and responses

Windows Phone 7 Development Tools

Windows Phone 7 Development Tools

At the heart of Windows Phone 7 Series development is Silverlight.  This enables you to bring your existing development skills in building Windows Phone 7 applications.

Windows Phone Developer Tools CTP, Microsoft’s developer toolset for Windows Phone 7 Series, is now available for download.

The Windows Phone Developer Tools CTP contains what you need to get started with Windows Phone 7 development.  Specifically, it includes the following:

  • CTP of Visual Studio 2010 Express for Windows Phone – This allows you to develop and debug your phone application in a familiar development environment.  If you are already using the release candidate of Visual Studio 2010, the Windows Phone 7 Series Add-in for Visual Studio lets you create applications alongside your web, cloud and desktop applications.
  • Windows Phone 7 Series Emulator – This is integrated with Visual Studio so you can see your app in action and debug it as you would with any other VS project.
  • Silverlight – Microsoft has extended our platform technologies from the web, desktop and console to the phone giving developers a broader application development experience.  With your existing development skills you can start developing applications for the phone today.  Or if you have a great app already, Silverlight lets you write once and optimize everywhere, including the phone.
  • XNA Game Studio – This enables you to build games spanning the phone, desktop and Xbox 360.

Expression Blend for Windows Phone, a professional design tool for building immersive mobile experiences in Silverlight, is not a part of the Windows Phone Developer Tools CTP, but you can download it.

Windows Mobile

What is Windows Mobile?

Windows Mobile is a combination of the Windows CE operating system, a new user interface and applications.

  • Smartphone – Windows Mobile Standard Edition – a cell phone first. Does not have a touch screen.
  • Pocket PC – Windows Mobile Professional – a data input device using a touch screen.
  • Size – small handheld devices however some are much larger
  • Combined devices – cell phone, PDA, media player, camera, etc.
  • Applications such as calendar, contacts, tasks, messaging, and office (excel, word, powerpoint)

What Are Windows Mobile’s Features?

Windows Mobile offers:

  • Cell phone – voice calling
  • Cellular based data – EvDO, 1xRTT, GPRS, EDGE and UMTS
  • Wi-Fi – 802.11b as well as 802.11g
  • Storage – internal storage and expansion via microSD, miniSD or SD flash
  • Connectivity – Supports TCP/IP, web browser, IMAP and POP3 e-mail, native Exchange support
  • Ability to display Word, Excel, and PowerPoint files – Pocket PCs can edit Word and Excel files

What isn’t Windows Mobile?

  • Is not the same operating system and functionality of Windows that you have on your desktop PC
  • Doesn’t run standard Windows applications including ActiveX controls designed for the PC.
  • Limited browser functionality – subset of JavaScript and limited screen size affect usability of desktop websites.
  • Slower devices – most Windows Mobile devices CPUs run at 200-400MHz
  • Limited storage – The internal flash storage is significantly smaller than your PC’s hard drive.  Usually
  • You will have anywhere from 32MB to 128MB of internal storage

System Architecture

  • Uses a ARM based RISC processor
  • 32 process spaces each with 32 MB of ram
  • Internal storage is flash memory and it is shared between the boot ROM and installed programs or stored data
  • No swap file
  • Processes are paged in and out of the address space to execute – this allows for fast switching between applications
  • Uses a registry hive to store application configuration data
  • Has an internal database for applications such as calendar, contacts, tasks, messaging, etc.

LINQ Cast & LINQ over Dataset

  1. When to use OfType & Cast
  2. What support C# provides to query over datasets and data tables (LINQ to dataset).
  3. Implications of anonymous types.

OfType & Cast

public static void CastOperator()

{

ArrayList list = new ArrayList();

list.Add(1);

list.Add(2);

list.Add(“ASP.NET 3.5 Unleashed”);

IEnumerable<int> numbers = list.Cast<int>();

foreach (int number in numbers)

{

Console.WriteLine(number);

}

}

When you run the cast operator, you get an exception because the cast operator tries to cast every element in the collection to the specified type. If it does not cast, it will throw an exception. In contrast, the OfType operator will return objects that can be cast to the right type and skips the rest from the collection.

public static void OfTypeOperator()

{

ArrayList list = new ArrayList();

list.Add(1);

list.Add(2);

list.Add(“ASP.NET 3.5 Unleashed”);

IEnumerable<int> numbers = list.OfType<int>();

foreach (int number in numbers)

{

Console.WriteLine(number);

}

}

LINQ Over Dataset

Out-of-the-box, datasets, datatables and dataviews do not have the necessary infrastructure to work in a LINQ query. This is where Microsoft introduced the new extension called System.Data.DataSetExtensions.dll, which includes DataTable extensions, DataRow extensions and TypedTableBasedExtesions. To make a data table LINQ aware, you simply need to call the AsEnumerable extension, which will return an EnumerableRowCollection consisting of DataRows. Another very useful extension method is DataRowExtensions.Field(), which allows you to do safe casting in a LINQ query and helps prevent runtime exceptions. Once you apply the filter on a datatable using the LINQ query, the result is simply EnumerableRowCollection. In order to return back a table, we can use the new copytodatatable extension method on the result.

public static void DataSetExample(DataTable books)

{

var implicittype = from book in books.AsEnumerable()

where book.Field<string>(“Author”) == “Stephen Walther”

select book;

var datatable = implicittype.CopyToDataTable();

}

Anonymous Types

The C# 3.0 language includes the ability to dynamically create new unnamed classes. This type of class is known as an anonymous type. An anonymous type has no name and is generated by the compiler based on the initialization of the object being instantiated. Since the class has no type name, any variable assigned to an object of an anonymous type must have some way to declare it. This is the purpose of the new C# 3.0 var keyword. Anonymous types allow you to define class on-the-fly using object initialization syntax and assigning to var keyword. At compile time, the C# compiler will generate a unique class which is not accessible from your code. All anonymous classes derive from System.Object and therefore inherit all the properties and methods of the object class. Anonymous classes are provided with overridden versions of Equals(), GetHashCode and ToString(). The ToString implementation for an anonymous book class would look something like this:

public class Book

{

public string Title { get; set; }

public string Author { get; set; }

}

public override string ToString()

{

StringBuilder builder = new StringBuilder();

builder.Append(“{ BookTitle = “);

builder.Append(this.<BookTitle>i__Field);

builder.Append(“,  BookAuthor = “);

builder.Append(this.<BookAuthor>i__Field);

builder.Append(” }”);

return builder.ToString();

}

Any comments or questions to this post are welcome.

LINQ Query Operators

AsEnumerable Operator

I found the AsEnumerable operator to be really important in understanding where the query gets executed, meaning is it going to get converted to SQL and the query would be performed on SQL server or LINQ to objects would be used and query would be performed in memory. The ideal use I have found for AsEnumerable would be when I know that a certain functionality is not available in SQL server, I can perform part of the query using LINQ to SQL (Iqueryable) and the rest executed as LINQ to objects (IEnumerable<T>). Basically, AsEnumerable is a hint to perform this part of the execution using LINQ to objects. This is how the prototype looks:

public static IEnumerable<T> AsEnumerable<T>(
this IEnumerable<T> source);

The prototype operates on the source of IEnumerable<T> and also returns an IEnumerable<T>. This is because standard query operators operate on IEnumerable<T>, whereas LINQ to SQL operates on IQueryable<T>, which also happens to implement IEnumerable<T>. So when you execute an operator like on an IQueryable <T> (domain objects), it uses a LINQ to SQL implementation for the where clause. As a result, the query gets executed on SQL Server. But what if we knew in advance that a certain operator would fail on SQL Server since SQL Server has no implementation for it. It’s good to use the AsEnumerable operator to tell the query engine to perform this part of the query in memory using LINQ to objects. Let’s see an example:


 
public static void AsEnumerableExample()
    {
        NorthwindDataContext db = new NorthwindDataContext();
        var firstproduct = (from product in db.Products
                       where product.Category.CategoryName == "Beverages"
                       select product
                       ).ElementAt(0);
        Console.WriteLine(firstproduct.ProductName);
    }

When you run this query, it would throw an exception saying that elementat is not supported because SQL Server does not know how to execute elementAt. In this case, when I add as enumerable, the query would execute fine as follows:

 
public static void AsEnumerableExample()
    {
        NorthwindDataContext db = new NorthwindDataContext();
        var firstproduct = (from product in db.Products
                       where product.Category.CategoryName == "Beverages"
                       select product
                       ).AsEnumerable().ElementAt(0);
        Console.WriteLine(firstproduct.ProductName);
    }

DefaultIfEmpty

The DefaultIfEmpty operator returns a default element if the input sequence is empty. If the input sequence is empty, the DefaultIfEmpty operator returns a sequence with a single element of default (T) which, for reference types, is null. Furthermore, the operator also allows you to specify the default operator that will be returned.

 
public static void DefaultIfEmptyExample()
    {
        string[] fruits = { "Apple",  "pear",  "grapes",  "orange" };
        string banana = fruits.Where(f => f.Equals("Banana")).First();
        Console.WriteLine(banana);
    }

The above example throws an exception because the first operator requires that sequence not be empty. Therefore if we were to use defaultifEmpty, this is how it would look:

 
public static void DefaultIfEmptyExample1()
    {
        string[] fruits = { "Apple",  "pear",  "grapes",  "orange" };
        string banana =
            fruits.Where(f => f.Equals("Banana")).DefaultIfEmpty("Not Found").First();
        Console.WriteLine(banana);
    }

Another interesting use of DefaultIfEmpty is to perform a left outer join using GroupJoin. Here is an example that illustrates that:

 
public class Category
{
    public string CategoryName { get; set; }
}
public class Product
{
    public string ProductName { get; set; }
    public string CategoryName { get; set; }
}

public static void LeftOuterJoin()
    {
        Category[] categories = {
                                    new Category{CategoryName="Beverages"},
                                    new Category{CategoryName="Condiments"},
                                    new Category{CategoryName="Dairy Products"},
                                    new Category{CategoryName="Grains/Cereals"}
                                };
        Product[] products = {
                                 new Product{ProductName="Chai",
                                     CategoryName="Beverages"},
                                 new Product{ProductName="Northwoods Cranberry Sauce",
                                     CategoryName="Condiments"},
                                 new Product{ProductName="Butter",
                                     CategoryName="Dairy Products"},
                             };
        var prodcategory =
            categories.GroupJoin(
                                products,
                                c => c.CategoryName,
                                p => p.CategoryName,
                                (category,  prodcat) => prodcat.DefaultIfEmpty()
                                .Select(pc => new { category.CategoryName,
                                    ProductName = pc != null ? pc.ProductName : "No" })
                                ).SelectMany(s => s);

        foreach (var product in prodcategory)
        {
            Console.WriteLine("Category :{0},  Product = {1}",  product.CategoryName,
                product.ProductName);
        }
    }

In the example above, I am using left outer join to list all categories, regardless of whether they have any products or not.

OrderBy Operators

The order operator allows collections to be ordered using orderby, orderbydescending, thenby and thenbydescending. Here is what the prototype looks like:

public static IOrderedEnumerable<T> OrderBy<T,  K>(
this IEnumerable<T> source,
Func keySelector)
where
K : IComparable<K>
 

The operator takes an IEnumerable<T> and orders the collection based on the key selector that will return the key value for each element in the sequence. The only important point that is worth mentioning is that the sorting of orderby and orderbydescending is considered unstable, meaning that if two elements return the same key based on the key selector, the order of the output could be the maintained or could be different. You should never rely on the order of elements coming out of an orderby call other than the field specified in the orderby clause.

Another interesting point that I found was that orderby, orderbydescending and orderbyascending take as an input source IEnumerable, as you can see from the prototype. However, the return type is IORderedEnumerable. The problem with that is if you want to order by more than 1 column, you cannot pass IOrderedEnumerable since orderby takes IEnumerable. The solution to this is to use the ThenBy or ThenByDescending operators, which take IOrderedEnumerble. Let’s proceed to an example:

 
public static void OrderByOperators()
    {
        Book[] books =
        {
            new Book{Title="ASP.NET 2.0 Website Programming: Problem -
                Design - Solution",
                Author="Marco Bellinaso"},
            new Book{Title="ASP.NET 2.0 Unleashed", Author="Stephen Walther"},
            new Book{Title="Pro ASP.NET 3.5 in C# 2008,  Second Edition",
                Author="MacDonald and Mario Szpuszta"},
            new Book{Title="ASP.NET 3.5 Unleashed ", Author="Stephen Walther"},
        };
        IEnumerable orderedbooks =
              books.OrderBy(b => b.Author).ThenBy(b => b.Title);

    }

In the above example, I make use of both orderby and thenby. Since orderby only works on IEnumerable<T>, I make use of the thenby extension method as well. The second prototype for orderby takes in Icomparable and does not require the return type of the keyselector delegate to return a Collection that implements IComparable. Here is what the prototype looks like:

public static IOrderedEnumerable<T> OrderBy<T,  K>(
this IEnumerable<T> source,
Func keySelector,
IComparer comparer);
interface IComparer<T> {
int Compare(T x,  T y);
}

The compare method will return a greater int if the second argument is greater than the first, equal to zero if both arguments are equal and less than zero if the first argument is less than the second. Let’s see an example of that:

 
public class LengthComparer : IComparer
{
    public int Compare(string title1,  string title2)
    {
        if (title1.Length < title2.Length) return -1;
        else if (title1.Length > title2.Length) return 1;
        else return 0;
    }
}

I have created a custom comparer which compares the book title based on the title‘s length. When the length of the first title is less than the second title‘s length, I return -1. If it’s greater, I return 1. Otherwise, I return 0 for being equal. This is how I make use of the comparer in my LINQ query.

public static void OrderByUsingCustomComparer()
    {
        Book[] books =
        {
            new Book{Title="ASP.NET 2.0 Website Programming: Problem -
                 Design - Solution",
                Author="Marco Bellinaso"},
            new Book{Title="ASP.NET 2.0 Unleashed", Author="Stephen Walther"},
            new Book{Title="Pro ASP.NET 3.5 in C# 2008,  Second Edition",
                Author="MacDonald and Mario Szpuszta"},
            new Book{Title="ASP.NET 3.5 Unleashed ", Author="Stephen Walther"},
        };
        IEnumerable orderedbooks = books.OrderBy(b => b.Title,
            new LengthComparer());
    }

Query operators such as SelectMany, Concat, Object Initializers, OrderBy, AsEnumerable, defaultifempty and how to do left joins in LINQ to SQL.

Standard Query Operators

The list of standard query operators is huge. I will cover a few of them that I found interesting and that require a bit of understanding.

Select Many and Concat Operators

The SelectMany operator is used to create one to many projections. The SelectMany operator will return zero or more inputs for every input element. The prototype is as follows:

public static IEnumerable<S> SelectMany<T,  S>(
this IEnumerable<T> source,
Func<T,  IEnumerable<S>> selector);

The operator takes an input sequence of T and a selector delegate that takes an element of type T. It returns an IEnumerable of S, an intermediate output sequence. Let’s see an example:

 
public static void SelectManyOperator()
    {
        string[] items = { "this",  "is",  "a",  "test" };
        IEnumerable<char> characters = items.SelectMany(s => s.ToCharArray());
        foreach (char character in characters)
        {
            Console.WriteLine(character);
        }
    }
 
 
public static void ConcatAndSelectManyOperator()
    {
        string[] books = {
                           "ASP.NET 2.0 Website Programming: Problem -
                            Design - Solution",
                           "Pro ASP.NET 3.5 in C# 2008,  Second Edition",
                           "ASP.NET 2.0 Unleashed",
                           "ASP.NET 3.5 Unleashed "
                         };
        IEnumerable concatbooks = books.Take(2).Concat(books.Skip(2));
        IEnumerable selectmanybooks = new[]{
                                                      books.Take(2),
                                                      books.Skip(2)
                                                  }.SelectMany(b => b);

    }

Using concat or selectmany would yield the same results, but the advantage of selectmany is that it allows you to merge more than two sequences to return a single sequence back.

Object Initializers

There is a C# language feature in the upcoming “Orcas” version known as object initializers. Object initializers basically allow the assignment of multiple properties or fields in a single expression. For example, a common pattern for object creation is:

 
Customer customer = new Customer();
customer.Name = “Roger”;
customer.Address = “1 Wilco Way”;

In this case, there is no constructor of Customer that takes a name and address; however, there are two properties, Name and Address, that can be set once an instance is created. Object initializers allow the same creation with the following syntax:

 
Customer customer = new Customer() 
    { Name = “Roger”, Address = “1 Wilco Way” };

In our earlier CustomerTuple example, we created the CustomerTuple class by calling its constructor. We can achieve the same result via object initializers:

 
var locals = 
    customers
        .Where(c => c.ZipCode == 91822)
        .Select(c => 
             new CustomerTuple { Name = c.Name, Address = c.Address });

Notice that object initializers allow the parentheses of the constructor to be omitted. In addition, both fields and settable properties can be assigned within the body of the object initializer.

We now have a succinct syntax for creating queries in C#. However, we also have an extensible way to add new operators (Distinct, OrderBy, Sum, and so on) through extension methods and a distinct set of language features useful in their own right.

The language design team now had several prototypes to get feedback on. So we organized a usability study with many participants who had experience with both C# and SQL. The feedback was almost universally positive, but it was clear there was something missing. In particular, it was difficult for the developers to apply their knowledge of SQL because the syntax we thought was ideal didn’t map very well to their domain expertise.

LINQ – In-Memory Collections (Cached Anonymous Delegate Method)

LINQ – In-Memory Collections

In this article we will cover only the querying of in-memory collections.

This article has been designed to give you a core understanding of LINQ that we will rely heavily on in subsequent parts of this series.

Before diving into the code it is essential to define what LINQ actually is. LINQ is not C# 3.0, and vice versa. LINQ relies heavily on the new language enhancements introduced in C# 3.0; however, LINQ essentially is the composition of many standard query operators that allow you to work with data in a more intuitive way regardless of the data source.

The benefits of using LINQ are significant – queries are a first class citizen within the C# language, benefit from compile time checking of queries, and the ability to debug (step through) queries. We can expect the next Visual Studio IDE to take full advantage of these benefits – certainly the March 2007 CTP of Visual Studio Orcas does!

In-Memory Collections

The best way to teach new technologies is to just to show you an example and then explain what the heck is going on! – That will be my approach throughout this series; hopefully it is a wise decision.

For our first example we will compose a query to retrieve all the items in a generic List collection (Fig. 1).

Figure 1: Selecting all the items in a generic List collection

private static List<string> people = new List<string>()
{
  "Granville", "John", "Rachel", "Betty",
  "Chandler", "Ross", "Monica"
};
public static void Example1()
{
  IEnumerable<string> query = from p in people select p;
  foreach (string person in query)
  {
    Console.WriteLine(person);
  }
}

The code example given in Fig. 1 is very basic and its functionality could have been replicated easier by simply enumerating through the items in the List via a foreach loop.

In Fig.1 we compose a query that will return each of the items in the people List collection by aliasing the people collection with a variable p and then selecting p (p is of type string remember as the people List is a collection of immutable string objects).

You may notice that query is of type IEnumerable<string> – this is because we know that query will hold an enumeration of type string. When we foreach through the query the GetEnumerator of query is invoked.

At this time it is beneficial to look at exactly what the compiler generated code looks like (Fig. 2).

Figure 2: Compiler generated code for Fig. 1

public static void Example1()
{
  IEnumerable<string> query = people.Select<string, string>(delegate (string p)
  {
    return p;
  });
  foreach (string person in query)
  {
    Console.WriteLine(person);
  }
}

Fig. 2 reveals that our query has actually been converted by the compiler to use an extension method (in this case just the Select extension method is used) taking a delegate as its argument.

You will find that queries and lambda expressions are simply a facade that we deal with in order to make our lives easier – under the covers the compiler is generating the appropriate code using delegates. Be aware of this internal compiler behavior!

Also be aware that a cached anonymous delegate method is generated at compile time as well (Fig. 3) – we will discuss this particular feature in future articles.

Figure 3: Compiler generated cached anonymous delegate method

[CompilerGenerated]
private static Func<string, string> <>9__CachedAnonymousMethodDelegate1;

We will now take a look at a more complex query of the same collection which retrieves a sequence of all strings in the List whose length is greater than 5(Fig. 4).

Figure 4: A more complex query

public static void Example2()
{
  IEnumerable<string> query = from p in people where p.Length > 5
  orderby p select p;
 
  foreach (string person in query)
  {
    Console.WriteLine(person);
  }
}

The example in Fig. 4 relies on the use of two other standard query operators – Where and orderby to achieve the desired results.

If we examine the code generated by the compiler for the Example2 method you will see that shown in Fig. 5 – notice as well that we now have another two cached anonymous delegate methods (Fig. 6) – each of which having the type signature of their corresponding delegates (Where delegate and orderby delegate).

Figure 5: Compiler generated code for Fig. 4

public static void Example2()
{
  IEnumerable<string> query = people.Where<string>(delegate (string p)
  {
    return (p.Length > 5);
  }).OrderBy<string, string>(delegate (string p)
  {
    return p;
  });
  foreach (string person in query)
  {
    Console.WriteLine(person);
  }
}

Figure 6: Cached anonymous delegate methods for their respective Where and orderby delegates defined in Fig. 5

[CompilerGenerated]
private static Func<string, bool> <>9__CachedAnonymousMethodDelegate4;
[CompilerGenerated]
private static Func<string, string> <>9__CachedAnonymousMethodDelegate5;

The type signature of the Where delegate (Fig. 5) is Funcdelegate takes a string argument and returns a bool depending on whether the string was greater than 5 characters in length. Similarly the orderby delegate (Fig. 5) takes a string argument and returns a string.

LINQ Execution

October 7, 2009 Leave a comment

How LINQ leverages differed execution and what benefits and impacts it can have to a developer.

Differed and Immediate Execution

By default, LINQ query expressions are not evaluated until you iterate over the contents. The benefit of this differed execution allows the same LINQ query to be executed multiple times, giving you the latest results. However, there would be times when differed execution behavior would not be acceptable due to performance reasons of the query being executed every time. To prevent this behavior, the .NET Framework defines a number of extension methods such as ToArray<T>(), ToDictionary<TSource, TKey>() and ToList<T>() to capture the results in a strongly typed container which would not reflect new changes made to the original collection. Here is an example:

public static void DifferedAndImmediateExecution()
    {
        int[] numbers = { 1,  2,  3,  4,  5,  6 };
        var lessthan4 = from n in numbers
                        where n < 4
                        select n;

        Console.WriteLine("Original array with items less than 4");
        foreach (int n in lessthan4)
        {
            Console.WriteLine("{0} < 4", n);
        }
        //differed execution
        numbers[2] = 7;//assigning new value
        Console.WriteLine(
            "Results based on differed execution after change number[2] = 7");
        foreach (int n in lessthan4)
        {
            Console.WriteLine("{0} < 4",  n);
        }

        //immediate execution
        numbers = new int[] { 1,  2,  3,  4,  5,  6 };
        var lessthan4immediate = numbers.Where(n => n < 4).Select(n => n).ToArray<int>();
        numbers[2] = 7;//assigning new value
        Console.WriteLine(
            "Results based on immediate execution after change number[2] = 7");
        foreach (int n in lessthan4immediate)
        {
            Console.WriteLine("{0} < 4",  n);
        }
    }

As you can see that, new changes are reflected on differed queries whereas new changes are not reflected on immediate execution because the results are cached in a strongly typed container. However, the query does not run until you iterate over the collection.

One of the downsides I have observed with differed execution is that bugs are harder to trace because enumerating the query could happen much further down in your code. This is where the exception would be thrown. However, you may forget that it is the original query that is the problem. So if differed execution is not the desired behavior you want, use the non-deferred extension methods like ToArray, ToList, ToDictionary or ToLookup to force the query to be executed. Let’s see an example for that:

public static void DelayedExceptions()
    {
        string[] blob = {"Resharper", "is", "great"};
        IEnumerable<string> sentence = blob.Select(s => s.Substring(0,  5));
        foreach (string word in sentence)
        {
            Console.WriteLine(word);
        }
    }
 
Any comments or questions to this post are welcome.