in

ASP.NET Weblogs

Li Chen's Blog

  • Understanding asynchronous programming in ASP.NET

    I recently posted about asynchronous programing patterns in .NET. Like .net framework, ASP.NET has supported asynchronous programming since 1.x. C# and VB.NET introduced the new async and await keywords in the upcoming Visual Studio 11. This is also supported in the upcoming ASP.NET 4.5. On the other hand, there is currently an open source project from the ASP.NET team called SignalR. It uses synchronous programming model to support long running comet-like request in ASP.NET. SigalR can be used in ASP.NET 4.0 today. The purpose of this post is to talk about a little bit of history so that we can put new projects/features in perspective.

    In asynchronous programming, the callee will create another thread to handle the execution and return immediately the the caller. The caller can go on with another task, or wait, join, or be called back from the callee. So one may ask what does asynchronous programming have to do with ASP.NET. Which is the caller and which is the callee?

    It turns out that the caller is ASP.NET and the callee is the asynchronous HttpHandler. When IIS calls into ASP.NET, ASP.NET immediately posts the request to the CLR ThreadPool and returns a pending status to IIS. This frees the IIS thread so that it can be used to handle static contents. In the request is handled by an IHttpHandler in ASP.NET, a thread will handle the entire life cycle of the request. If the request is handled by an IHttpAsyncHandler, ASP.NET will call the BeginProcessRequest method of the handler and return the thread to the thread pool as soon as the method exists. If the handler simply creates another thread in the BeginProcessRequest method and immediately returns, there is really no benefits since we are simply replace one thread with another. If the handler make an asynchronous call to another class that is IO blocking and immediately returns, there is real benefit because the ASP.NET thread is no longer blocked by the IO and can be returned to the thread-pool to server other requests. Even though there is not a thread associated with the request, the connection remains open until the call-back delegate passed into the BeginProcessRequest method is called. This powerful method allows an asynchronous ASP.NET application to handle far more requests than synchronous application if IO blocking is a concern. On the other hand, it is possible for an application to keep a connection open for a long time with allocating a thread, and allocates thread only on events. That is why SignalR can work today. What is the cost to keep those connections open? The TCP/IP stack needs to keep connection info. IIS and ASP.NET also need to keep the context info. That’s say we need in average 5kB to keep a connection open. Then 1GB of memory would allow us to keep 200,000 connections open. This is unusually large number for synchronous asp.net applications. That is why SignalR implementations often configure much larger number of connections than the 5000 default in IIS7.

    References:

    [1] Performing Asynchronous Work, or Tasks, in ASP.NET Applications.

    [2] ASP.NET Thread Usage on IIS 7.5, IIS 7.0, and IIS 6.0

    Posted May 14 2012, 01:54 AM by dotneteer with no comments
    Filed under: ,
  • A review of asynchronous programming patterns in .net

    In Visual Studio 11, C# and VB.NET will gain new keywords like async and await for asynchronous programming. Before we dive into it, I will first give a brief preview on what we have so far.

    IAsyncResult Pattern

    IAsyncResult pattern has existed since .net 1.x. The class that implements pattern would implement Beginxxx and Endxxx methods.For example, the WebRequest class has BeginGetResponse and EndGetResponse in additional to synchronous GetResponse method.  Here is the signature of the BeginGetResponse method:

    public virtual IAsyncResult BeginGetResponse( AsyncCallback callback, Object state )

    The caller of the method needs to supply a callback function which will be call when the asynchronous operation is over. The callee will usually create another thread to do the actual operation and immediate an IAsyncResult to the caller. Here are the members of IAsyncResult:

    Member Description
    AsyncState An optional application-specific object that contains information about the asynchronous operation.
    AsyncWaitHandle A WaitHandle that can be used to block application execution until the asynchronous operation completes.
    CompletedSynchronously A value that indicates whether the asynchronous operation completed on the thread used to call BeginOperationName instead of completing on a separate ThreadPool thread.
    IsCompleted A value that indicates whether the asynchronous operation has completed.

    The caller of Beginxxx method can do one of the following:

    1. Wait on the AsyncWaitHandle if the caller needs to do processing after the async operation.
    2. Poll the IsCompleted and AsyncState for completion and possibly the progress.
    3. Do nothing. Wait for the callback to be called.
    4. Call the Endxxx method. If it is called before the completion of the async operation, the calling thread will block until the asynchronous operation is complete.

    Event-based Asynchronous Pattern

    Since .net 2.0, we gain another asynchronous pattern – the Event-based Asynchronous Pattern (EAP). EAP was created to allow a richer event model. The class that implement EAP can raised multiple events during a single asynchronous operation so that the callee does not have to poll the class.

    The class that implements EAP uses xxxAsync naming conversion for its asynchronous methods. The class can optionally implements xxxCancelAsync methods or simply a CancelAsync method to allow caller to cancel the asynchronous operation. When a caller calls a xxxAsync method, the method will immediately return. The caller needs to subscribe one of the events exposed by the class for notifications of completion and progress. WebClient and BackgroundWorker are two typical components that use this pattern. For library designers, MSDN has a nice article descripting when to use which pattern.

    Task-based Asynchronous Pattern

    .Net framework 4.0 introduced yet another way to run asynchronous operation – the Task class in the Task Parallel Library.  Although the task parallel library is about parallel execution and is much more than asynchronous programming, the .net framework 4.5 uses it as the base for yet another asynchronous pattern – the Task-based Asynchronous Patterns (TAP). The class that implements TAP would expose xxxAsync methods, just like EAP. However, the xxxAsync methods return Task<TResult>. The callee can then use the members of Task<TResult> to check completion or progress, wait or continue with another operation. This pattern is the basis for the async and await keywords in Visual Studio 11; the methods that support TAP can be marked using the async keywoard and then consumed asynchronously with the await keyword. That is why only methods return Task, Task<TResult> or void (that is, no results) can be marked with async.

    [Edited 5/23/2012]

    Found this MSDN Magazine article that discusses these patterns in more detail: http://msdn.microsoft.com/en-us/magazine/ff959203.aspx.

    Posted May 14 2012, 12:31 AM by dotneteer with 1 comment(s)
    Filed under:
  • Created my first Windows Phone app

    After getting a Lumia 900 last week, I decided to write an app for myself. One of the complaint that I had is that I need a minimum 4 taps to dial a number from a contact list, something I would like to avoid when I am driving. I can pin a few my most frequently used numbers to a tile; from there I can dial them with 2 taps. I set out to write an app and hope I can dial 30-40 number in 2 taps. The hear is the idea:

    1. I group my phone number in groups, such as family, friends, colleagues, etc.
    2. I display the groups using the panorama control and phone numbers within each list in a list control.
    3. I need a tap from the tile to start the application. I may or may not need a swipe to get to a contact. I do another tap to dial the phone number.

    It turned out that I need another tap after I tap the phone number. The reason is that the PhoneCallTask does not trust me; it prompted me to confirm if I really wanted to dial the number. I hope Microsoft can make this a policy that can be granted when the application is installed.

    I am an experienced WPF and Silverlight developer. This is my first Windows Phone app. I hoped I can write this app is a couple of hours, but it turned out that I spent almost a whole day to learn unique features in Windows Phone. The WindowsPhoneGeek.com site is immensely helpful. So here are a list of things that I learnt through this simple app:

    1. Panorama control and data binding to panorama control.
    2. Windows Phone Toolkit ContextMenu control and reference the tapped item from the context menu click handler.
    3. Application bar icon button and menu.
    4. WP7 navigation framework and pass an object from a page to another page.
    5. WP7 built-in theme resources.
    6. PhoneNumberChooserTask and PhoneCallTask.
    7. WP7 application and page events.
    8. WP7 icons, application icon, background icon, marketplace icon.
    9. WP7 Isolated Storage.

    These appear to be minimum to get started with an app. I was able to deploy my app to my phone. I cannot deploy to my app to marketplace yet. That is because I unlocked my phone with my employer’s account but I could not possibly release my app to the marketplace using my my employers account. I either have to pay $99 to get my own account, or release my source code to make arrangement to have someone else release the app for me.

    [Edited 5/3/2012 to add some pictures]

    First page

    Categories

  • Experimenting with Visual Studio 11 Beta

    Windows 8 is coming soon. You need Visual Studio 11 beta to develop Windows 8 applications. That said, Visual Studio 11 also offers many new features even if you do not specifically program for Windows 8:

    • .NET Framework 4.5
    • ASP.NET 4.5
    • ASP.NET MVC 4

    What is the best way to start experimenting with Visual Studio 11 Beta? .Net Framework 4.5 is a highly compatible in-place update of .Net Framework 4.0. If you uninstall .Net Framework 4.5 beta, you will have to reinstall .Net Framework 4.0. For this reason, I would suggest you not to experiment with Visual Studio 11 beta on your main work machine. Fortunately, there is a way that allows you to experiment with Visual Studio 11 with satisfactory performance without a spare machine.

    If your operating system is Windows 7, you can dual-boot your machine off a VHD. You secondary OS will resides in a VHD so it will not mess up your primary OS, yet your machine will boot from the VHD natively so the performance is much better than running a virtual machine. In my case, I installed a copy of Windows 8 consumer preview on VHD by following this blog. I then install Visual Studio 11 Beta on top of it. I then get a Windows 8 Preview/Visual Studio 11 Beta combo that I can experiment with. The performance is only slightly (let’s say 10%) worse than a dedicated machine. I can still access the files in my native file system. Is there inconvenience in dual boot? The inconvenience can be managed if you rearrange your data to live in the cloud.

  • 5 days after getting a Nokia Lumia 900

    My experience has been very pleasant so far. This Windows Phone is always very responsive and stable. I also like the idea of charging through mini USB connector rather than a flimsy proprietary connector. My primary focus this week is to be able to dial a contact quickly. The other focus is to find a list of apps both for usage and fun.

    Clean up the contact list

    Windows phone requires me to use a Windows Live account (a Hotmail account, in my case) as a cloud account. The phone maintains bi-directional automatic sync with my Hotmail. When I add other accounts such as GMail and Facebook to my phone, and import the contacts from my old phone, Windows Phone synced them all to my Hotmail contact. The result is that my contact list is flooded with over 400 contacts, many of them are duplicates. So my first task is to clean up the list. Fortunately, it is fairly easy to combine contacts in Hotmail. I was able to get it down to about 100.

    Windows phone does not automatically sync Hotmail categories as group. I had to create several groups on the phone and add contacts to groups. Windows phone also allow me to link contacts for phone/email to my Facebook and Linked-in contacts. The result is that I have a much more organized list now and is easier to navigate through groups. However, it still requires a minimum of 4 clicks to dial a number through the contact list.

    Apps, Apps and Apps

    Many journal articles claim that Windows Phone has far less apps than iPhone and Android. This is not a big concern to me as long as I can find enough good apps. Currently, there are a bout 80,000 apps for Windows Phone. I need only 20-30 good apps. So here is a list of apps that I downloaded this week:

     
    • Adobe Reader.
    • Facebook and Twitter: these are actually written by Microsoft, nothing fancy but do the job.
    • Nokia Drive, Nokia Maps and Nokia Transit: these are from Nokia collection.
    • Translator: This from Microsoft, actually quite powerful and fun to use.
    • Unit Convert: A simple utility from Microsoft.
    • SkyDrive
    • CNN and ESPN: these are actually written by Nokia.
    • Level and the Unite game: these are from Microsoft demonstrating gyro sensors. Pretty fun.
    • Nokia Creative Studio: An Instagram-like app created by Nokia that makes me wonder how possibly Instagram worthed $1 billion.
    • Endomondo Sports Track: Use the GSP to track my walking statistics.
    • Mobile Magnifier: I could not find one as good as the iPhone equivalent that I saw. I hope someone will create a better one.

    Lastly, I have a problem that cannot be solved by an app. I would like to block some spamming phone numbers. Windows Phone does not allow me to do that. I cannot find an app because Windows Phone does not have an API to do that. Samsung has implemented in hardware in some Windows Phones. For now, I just have to hit the volume key to reject a call.

  • Bought a Nokia Lumia 900

    I am sick of my Samsung Galaxy. I considered it as a half-done project with beta software. I saw a fantastic deal for Lumia 900 on Amazon Wireless for $49. In addition, Nokia is offering a $100 instant rebate to make up for a post-launch bug by April 21. The phone is currently ranked #1 on Amazon wireless and has a incredible customer rating. So I decided to give it a try.

    nokia_lumia_900_matteblack_l

    The phone arrived 2 days later. The construction and screen of the phone looks really nice. When I set the date/time of the clock, I really like the very large number and how it scrolls. The phone feels more responsive than Galaxy. However, I have also found a few places that could be polished:

    1. Outlook setup. The small company that I work with uses a self-sign certificate on the Exchange server. The Outlook in WP7 does not have an option for me to ignore the certificate error warning. So it took me a couple of hours to figure out how to access our Exchange server. Basically, I use browser to visit the Outlook Web Access. I will see the certificate warning in my Internet Explorer. From there, I bring up the property page, click “Certificates”, then Details and click “Copy to File…”. I export the certificate as a .p7b file and then email to my hotmail account. I open the email in my phone, and then open the .p7b attachment and installed the certificate. I was able to access our Exchange server from then on. I think an option to skip certificate error could be nice.
    2. Marketplace: In the search results, there isn’t any indication whether an application is already installed.
    3. Contacts: The phone imported by Hotmail contacts. I also imported the contact list from my old phone using the Contact Transfer application under Nokia collection. When I tried to dial the phone, both email and phone contacts show up. I think the phone can certainly filter out the contacts that do not have phone number. Right now it seems there are too many contacts. I am going to try the grouping feature try to group the contacts.

    So much for my first day of experience with Lumia 900. Lastly, I would like to share this very useful article that I found:

    10 things you never knew your Lumia could do.

  • Getting Started with Prism (aka Composite Application Guidance for WPF and Silverlight)

    Overview

    Prism is a framework from the Microsoft Patterns and Practice team that allow you to create WPF and Silverlight in a modular way. It is especially valuable for larger projects in which a large number of developers can develop in parallel.

    Prism achieves its goal by supplying several services:

    · Dependency Injection (DI) and Inversion of control (IoC): By using DI, Prism takes away the responsibility of instantiating and managing the life time of dependency objects from individual components to a container. Prism relies on containers to discover, manage and compose large number of objects. By varying the configuration, the container can also inject mock objects for unit testing. Out of the box, Prism supports Unity and MEF as container although it is possible to use other containers by subclassing the Bootstrapper class.

    · Modularity and Region: Prism supplies the framework to split application into modules from the application shell. Each module is a library project that contains both UI and code and is responsible to initialize itself when loaded by the shell. Each window can be further divided into regions. A region is a user control with associated model.

    · Model, view and view-model (MVVM) pattern: Prism promotes the user MVVM. The use of DI container makes it much easier to inject model into view. WPF already has excellent data binding and commanding mechanism. To be productive with Prism, it is important to understand WPF data binding and commanding well.

    · Event-aggregation: Prism promotes loosely coupled components. Prism discourages for components from different modules to communicate each other, thus leading to dependency. Instead, Prism supplies an event-aggregation mechanism that allows components to publish and subscribe events without knowing each other.

    Architecture

    In the following, I will go into a little more detail on the services provided by Prism.

    Bootstrapper

    In a typical WPF application, application start-up is controls by App.xaml and its code behind. The main window of the application is typically specified in the App.xaml file. In a Prism application, we start a bootstrapper in the App class and delegate the duty of main window to the bootstrapper. The bootstrapper will start a dependency-injection container so all future object instantiations are managed by the container.

    Out of box, Prism provides the UnityBootstrapper and MefUnityBootstrapper abstract classes. All application needs to either provide a concrete implementation of one of these bootstrappers, or alternatively, subclass the Bootstrapper class with another DI container.

    A concrete bootstrapper class must implement the CreateShell method. Its responsibility is to resolve and create the Shell object through the DI container to serve as the main window for the application.

    The other important method to override is ConfigureModuleCatalog. The bootstrapper can register modules for the application. In a more advance scenario, an application does not have to know all its modules at compile time. Modules can be discovered at run time. Readers to refer to one of the Open Modularity Quick Starts for more information.

    Modules

    Once modules are registered with or discovered by Prism, they are instantiated by the DI container and their Initialize method is called. The DI container can inject into a module a region registry that implements IRegionViewRegistry interface. The module, in its Initialize method, can then call RegisterViewWithRegion method of the registry to register its regions.

    Regions

    Regions, once registered, are managed by the RegionManager. The shell can then load regions either through the RegionManager.RegionName attached property or dynamically through code.

    When a view is created by the region manager, the DI container can inject view model and other services into the view. The view then has a reference to the view model through which it can interact with backend services.

    Service locator

    Although it is possible to inject services into dependent classes through a DI container, an alternative way is to use the ServiceLocator to retrieve a service on demard. Prism supplies a service locator implementation and it is possible to get an instance of the service by calling:

    ServiceLocator.Current.GetInstance<IServiceType>()

    Event aggregator

    Prism supplies an IEventAggregator interface and implementation that can be injected into any class that needs to communicate with each other in a loosely-coupled fashion. The event aggregator uses a publisher/subscriber model.

    A class can publishes an event by calling eventAggregator.GetEvent<EventType>().Publish(parameter) to raise an event.

    Other classes can subscribe the event by calling eventAggregator.GetEvent<EventType>().Subscribe(EventHandler, other options).

    Getting started

    The easiest way to get started with Prism is to go through the Prism Hands-On labs and look at the Hello World QuickStart. The Hello World QuickStart shows how bootstrapper, modules and region works.

    Next, I would recommend you to look at the Stock Trader Reference Implementation. It is a more in depth example that resemble we want to set up an application.

    Several other QuickStarts cover individual Prism services. Some scenarios, such as dynamic module discovery, are more advanced.

    Apart from the official prism document, you can get an overview by reading Glen Block’s MSDN Magazine article.

    I have found the best free training material is from the Boise Code Camp.

    To be effective with Prism, it is important to understands key concepts of WPF well first, such as the DependencyProperty system, data binding, resource, theme and ICommand. It is also important to know your DI container of choice well. I will try to explorer these subjects in depth in the future.

    Testimony

    Recently, I worked on a desktop WPF application using Prism. I had a wonderful experience with Prism. The Prism is flexible enough even in the presence of third party controls such as Telerik WPF controls. We have never encountered any significant obstacle.

  • Getting started with ASP.NET Web API quickly

    Web API is a feature of ASP.NET MVC 4. It is an API for writing REST web services. One might ask why we need another API. After all, we already have WCF Rest Service a few years ago. It is also fairly easy to return JSON from an ASP.NET MVC controller using JsonResult. For a long answer, it is best read ScottGu;s blog or the WCF site. The short answer is that Microsoft want a way to make it extremely easy to create REST services and to provide lots of features. ASP.NET MVC is the best place. Currently, the .Net REST/Json story is fragmented and there are several Json serializers in .Net. ASP.NET Web API represents the future, consolidated API for this feature.

    It is fairly easy to get started with ASP.NET Web API. For those who likes to watch video, Jon Galloway’s 6 short videos provides a very quick start and it takes only 24 minutes to watch them all. For those who like read and type, the ASP.NET site has 7 short chapters that can be read in an hour or two. Many bloggers are blogging the Web API. I would recommend Stephen Walter’s blog for a quick introduction. Finally, I strongly recommend looking into some of the samples.

  • Experimenting with ASP.NET 4.5 beta

    The next version of ASP.NET is 4.5. The official information is at http://www.asp.net/vnext.

    There are two ways to experiment with ASP.NET 4.5 beta. The first is to install Visual Studio 11 beta. The second way is to install ASP.NET MVC 4 beta on Visual Studio 2010 to experiment with a subset of the features. Visual Studio 11 beta contains .Net Framework 4.5 beta. .Net Framework 4.5 is a highly compatible in-place update of .Net Framework 4.0. If you uninstall .Net Framework 4.5 beta, you will have to reinstall .Net Framework 4.0. For this reason, I would suggest you to experiment with Visual Studio 11 beta on an experimental machine, perhaps on a Windows 8 consumer preview VHD.

    On the other hand, ASP.NET MVC 4 beta consists of a set of new assemblies that can run side-by-side with MVC 3. It also has a new set of templates for MVC 4 projects. The only thing that affects MVC 3 work is that it changes the intelligence for web pages (.cshtml and .vbhtml) to support web pages 2 features. You need to build your web application before you edit any .cshtml or .vbhtml pages to overcome a bug.

    The following features can be experimented with ASP.NET MVC 4 beta on VS 2010:

    Not part of ASP.NET MVC 4 beta, there is an exciting open source framework from the ASP.NET team called SignalR that be experimented in VS 2010. SignalR allows developing long polling Comet type of applications using .NET. The ASP.NET team has also created an open source chat application called JabbR as a case study.

    In future blogs, I will blog my experiment with each of these exciting new areas.

  • Uploading large files to WCF web services

    Recently, we need to allow users to upload large files to a web service. Fortunately, WCF does support this scenario (see MSDN: Large Data and Streaming). MSDN recommends:

    The most common scenario in which such large data content transfers occur are transfers of binary data objects that:

    • Cannot be easily broken up into a message sequence.
    • Must be delivered in a timely manner.
    • Are not available in their entirety when the transfer is initiated.

    For data that does not have these constraints, it is typically better to send sequences of messages within the scope of a session than one large message.

    Since our files do not have these constraints, we decide to break them up into sequences of segments, and pass the segments to the web service as byte arrays. There are several remaining issues: 

    Firstly, by default, WCF uses Base64 encoding to encode byte arrays, resulting 4:3 ratio in encoding overhead. To avoid this overhead, WCF support both MTOM and Binary encoding. MTOM is a widely supported format that sends large binary data as MIME attachments after the soap message. Binary encoding is a WCF proprietary encoding format. It is extremely easy to use either formats. Just change the messageEncoding attribute in the binding element in the configuration from Text to Mtom or Binary.

    Secondly, experiment shows that high level handshake through web service is fairly slow. Better performance can be achived by using a larger chunk size. By default, the maximum message size is 65536 and maximum array size is 8192. In order to transmit larger chunks, we need to increase the maximum message and array size. This can be done by increasing the maxBufferSize and maxReceivedMessageSize attributes of the binding element and the maxArrayLength attribute of the readerQuotas element. Note that increasing the maximum sizes also increases the risk of denial of service attack so select the size carefully.

    image

    Thirdly, although it is possible to configure the IIS to automatically compress HTTP responses, HTTP clients cannot be configured to automatically compress the HTTP requests. WCF has a sample custom compression encoder. It is fairly easy to use the compression encoder. Just reference the GZipEncoder.dll on both the server and the client side. The configuration settings can be extracted from the sample. The only thing that is not apparent from the sample is how to increase the message size. The maxReceivedMessageSize  attribute can be configured on the httpTransport element:

    image

    To change the maxArrayLength in readerQuotas, I actually have to make a modification to the sample code:image

    The finish proof-of-concept application can be downloaded here.

     

    
    							
    Posted Feb 20 2012, 05:36 AM by dotneteer with no comments
    Filed under:
More Posts Next page »