Archives

Archives / 2012
  • While Lumia 900 is already good, Lumia 920 is even more fluid

    I got my Lumia 900 in April, 2012. A few month later, I was disappointed when the news broke out that Lumia 900 would not be able to upgrade to Windows Phone 8. Luckily, AT&T allows early upgrade to Lumia 920 so that I can continue developing software for latest Windows Phone OS without waiting for my two year commitment to end.

    Lumia 900 was known for excellent software optimization so that the phone felt very fast even with a single core processor. Now Lumia 920, with its Snapdragon S4 processor, feels blazingly fast. The most obvious improvement is acquiring GPS signal; it is almost instant now when I start an app that needs GPS. 

    Apart from being faster and more fluid, I also like the new tile size options that allows me to organize my start screen better. The new phone has a slightly larger display size (4.5” vs. 4.2”) though the physical dimension remains the same. The phone has a larger storage (32GB vs. 16GB) that allows me stored more free Nokia Drive offline maps on my phone so that I can use the GPS without using my monthly data plan.

    So much for my first impression, I will tell more story when I start developing for Windows Phone 8.

  • Implementing set operations in TSQL

    SQL excels at operating on dataset. In this post, I will discuss how to implement basic set operations in transact SQL (TSQL). The operations that I am going to discuss are union, intersection and complement (subtraction).

     

    union intersect subtract
    Union Intersection Complement (subtraction)

    Implementing set operations using union, intersect and except

    We can use TSQL keywords union, intersect and except to implement set operations. Since we are in an election year, I will use voter records of propositions as an example. We create the following table and insert 6 records into the table.

    Voters 1, 2, 3 and 4 voted for proposition 30 and voters 4 and 5 voted for proposition 31.

    The following TSQL statement implements union using the union keyword. The union returns voters who voted for either proposition 30 or 31.

    The following TSQL statement implements intersection using the intersect keyword. The intersection will return voters who voted only for both proposition 30 and 31.

    The following TSQL statement implements complement using the except keyword. The complement will return voters who voted for proposition 30 but not 31.

    Implementing set operations using join

    An alternative way to implement set operation in TSQL is to use full outer join, inner join and left outer join.

    The following TSQL statement implements union using full outer join.

    The following TSQL statement implements intersection using inner join.

    The following TSQL statement implements complement using left outer join.

    Which one to choose?

    To choose which technique to use, just keep two things in mind:

    1. The union, intersect and except technique treats an entire record as a member.
    2. The join technique allows the member to be specified in the “on” clause. However, it is necessary to use Coalesce function to project sets on the two sides of the join into a single set.
  • Upgrading to Windows 8

    As MSDN members can download Windows 8 now, it is time for me to upgrade to Windows 8. Although I upgraded successfully, my journey is a long story. Hopefully my experience can save you some time.

    1. I had a 120GB SSD that has only 11GB free space left. I am not terribly comfortable with the limited space. So I ordered a 240GB SSD. I used Windows 7 to do an Windows image backup to an external drive. I then booted from the Windows 7 DVD and restored my image to the new drive. It took only 30 minutes to backup, but several hours to restore. After restoring, I went to Computer Management to expand my C drive to use the remaining free space on my new SSD.
    2. I then tried to download Windows 8 from MSDN. I am running Windows 7 Ultimate. I was not sure which edition of Windows 8 to download. According to this chart, I can upgrade from Windows 7 Ultimate to Windows 8 pro, but I can only find Windows 8 pro volume licensing edition in MSDN which I am not entitled to download. It turns our that both Windows 8 and Windows 8 pro uses the same media; the activation key decides which edition to activate.
    3. The Windows 8 upgrader asked me to uninstall Microsoft Security Essential. This is because Windows 8 has Windows Defender built in.
    4. The Windows 8 user interface is not entirely intuitive. Fortunately, there is a short video from Mike Halsey that allows one to get familiar quickly.
    5. After the upgrade, there is a message asking me to uninstall Virtual Clone Drive. This is because Windows 8 has a built-in feature to mount ISO and VHD files. This is a nice edition.

    So much for my first day of experiments. See you next time.

  • Applying algorithms to real-life problem

    Today I encountered a real-life problem. My wife got some fresh pecan. After we cracked the pecan and took the large pieces, there are some smaller pieces of pecan and shell fragments left in the bowl. My wife asked kids to separate the pecan from the shell. There were three proposals:

    1) Pick the pecan out. The trouble is that we have more pecan pieces than shell pieces. The time for this approach is proportional to number of pecan pieces.

    2) Pick the shell out. It is not clear whether the time would be small because we still need to scan (with our eye) among pecans to find shell. In additional, it is hard to be sure that we are free of shells at the end.

    3) Pour them in water and hope one is heavier than water and the other is lighter. This idea was never tested.

    Then I proposed the 4th approach: grab a few pieces in my palm and apply 1) or 2), which ever way is faster. This works out really well.

    The key is that after I scan the pecan and shells in my palm I never scan the same pieces again. The fast algorithms, whether searching a word in a string, or sorting a list, or finding the quickest time when traveling from point A to point B, are all by finding a smart way to minimize the operations on the same data.

  • Is recursion really bad?

    After my previous post about the stack space, it appears that there is perception from the feedback that recursion is bad and we should avoid deep recursion. After writing a compiler, I know that the modern computer and compiler are complex enough and one cannot automatically assume that a hand crafted code would out-perform the compiler optimization. The only way is to do some prototype to find out.

    So why recursive code may not perform as well? Compilers place frames on a stack. In additional to arguments and local variables, compiles also need to place frame and program pointers on the frame, resulting in overheads.

    So why hand-crafted code may not performance as well? The stack used by a compiler is a simpler data structure and can grow and shrink cleanly. To replace recursion with out own stack, our stack is allocated in the heap that is far more complicated to manage. There could be overhead as well if the compiler needs to mark objects for garbage collection. Compiler also needs to worry about the memory fragmentation.

    Then there is additional complexity: CPUs have registers and multiple levels of cache. Register access is a few times faster than in-CPU cache access and is a few 10s times than on-board memory access. So it is up to the OS and compiler to maximize the use of register and in-CPU cache.

    For my particular problem, I did an experiment to rewrite my c# version of recursive code with a loop and stack approach. So here are the outcomes of the two approaches:

      Recursive call Loop and Stack
    Lines of code for the algorithm 17 46
    Speed Baseline 3% faster
    Readability Clean Far more complex

    So at the end, I was able to achieve 3% better performance with other drawbacks. My message is never assuming your sophisticated approach would automatically work out better than a simpler approach with a modern computer and compiler. Gage carefully before committing to a more complex approach.

  • What if we run out of stack space in C# or Python?

    Supposing we are running a recursive algorithm on a very large data set that requires, say, 1 million recursive calls. Normally, one would solve such a large problem by converting recursion to a loop and a stack, but what if we do not want to or cannot rewrite the algorithm?

    Python has the sys.setrecursionlimit(int) method to set the number of recursions. However, this is only part of the story; the program can still run our of stack space. C# does not have a equivalent method.

    Fortunately, both C# and Python have option to set the stack space when creating a thread. In C#, there is an overloaded constructor for the Thread class that accepts a parameter for the stack size:

    Thread t = new Thread(work, stackSize);

    In Python, we can set the stack size by calling:

    threading.stack_size(67108864)

    We can then run our work under a new thread with increased stack size.

  • Fun with Python

    I am taking a class on Coursera recently. My formal education is in physics. Although I have been working as a developer for over 18 years and have learnt a lot of programming on the job, I still would like to gain some systematic knowledge in computer science. Coursera courses taught by Standard professors provided me a wonderful chance.

    The three languages recommended for assignments are Java, C and Python. I am fluent in Java and have done some projects using C++/MFC/ATL in the past, but I would like to try something different this time. I first started with pure C. Soon I discover that I have to write a lot of code outside the question that I try to solve because the very limited C standard library. For example, to read a list of values from a file, I have to read characters by characters until I hit a delimiter. If I need a list that can grow, I have to create a data structure myself, something that I have taking for granted in .Net or Java. Out of frustration, I switched to Python. I was pleasantly surprised to find that Python is very easy to learn. The tutorial on the official Python site has the exactly the right pace for me, someone with experience in another programming. After a couple of hours on the tutorial and a few more minutes of toying with IDEL, I was in business. I like the “battery supplied” philosophy that gives everything that I need out of box. For someone from C# or Java background, curly braces are replaced by colon(:) and tab spaces. Although I tend to miss colon from time to time, I found that the idea of tab space is actually very nice once I get use to them. I also like to feature of multiple assignment and multiple return parameters. When I need to return a by-product, I just add it to the list of returns.

    When would use Python? I would use Python if I need to computer anything quick. The language is very easy to use. Python has a good collection of libraries (packages). The REPL of the interpreter allows me test ideas quickly before committing them into script. Lots of computer science work have been ported from Lisp to Python. Some universities are even teaching SICP in Python.

    When wouldn’t I use Python? I mostly would not use it in a managed environment, such as Ironpython or Jython. Both .Net and Java already have a rich library so one has to make a choice which library to use. If we use the managed runtime library, the code will tie to the particular runtime and thus not portable. If we use the Python library, then we will face the relatively long start-up time. For this reason, I would not recommend to use Ironpython for WP7 development. The only situation that I see merit with managed Python is in a server application where I can preload Python so that the start-up time is not a concern. Using Python as a managed glue language is an over-kill most of the time. A managed Scheme could be a better glue language as it is small enough to start-up very fast.

  • 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

  • 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.

  • 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.

     

    
    
  • LINQ and IEnumerable may surprise you

    Let us examine the following code snippet:

        class Candidate
        {
            public string Name { get; set; }
            public bool Hired { get; set; }
        }
        class Program
        {
            static void Main(string[] args)
            {
                string[] names = { "Adam", "Byron", "Charles" };
                var candidates = names.Select(n => new Candidate()
                {
                    Name = n,
                    Hired = false
                });
                //now modify the value of each object
                foreach (var candidate in candidates)
                {
                    candidate.Hired = true;
                }
                //noew print the value of each object
                foreach (var candidate in candidates)
                {
                    Console.WriteLine(string.Format("Name:{0} Hired:{1}", 
                        candidate.Name, candidate.Hired));
                }
                Console.Read();
            }
        }
    

    Basically, I create an IEnumerable<Candidate> from LINQ, and them loop through the results to modify each object. At the end, you might expect each candidate hired. Wrong! Here is the output:

    image

    What happened was LINQ actually delayed the object generation until enumeration. When we enumerate again to print the objects, LINQ actually generated a new set of objects. If you use ToList() to convert the IEnumerable to List, you will get the expected result:

                var candidates = names.Select(n => new Candidate()
                {
                    Name = n,
                    Hired = false
                }).ToList();
    

    ToList() will instantiate the objects immediately and the subsequent enumeration will be on the same objects. That is why you cannot find the .ForEach() extension method on IEnumerable<T>. You have to convert it to IList<T> to use the method.

  • Upgrading database to SQL Server 2008

    There are minor syntax changes in Transact-SQL that prevent applications written for earlier SQL Server versions from running in SQL Server 2008. It is possible to set the Compatibility Level of a database to support earlier versions of Transact-SQL. The following statement will alter the database to run at full SQL Server 2008 mode:

    Alter Database Set COMPATIBILITY_LEVEL = 100

    One of the typical problem is that older, non-ANSI style outer join using *= or =* does not work in SQL 2008. It is possible to do a quick assessment of offending queries in stored procedures, functions and views using the following SQL statements:

    select r.ROUTINE_NAME from INFORMATION_SCHEMA.ROUTINES r where r.ROUTINE_DEFINITION like '%*=%' or r.ROUTINE_DEFINITION like '%=*%'

    select v.TABLE_NAME from INFORMATION_SCHEMA.VIEWS v where v.VIEW_DEFINITION like '%*=%' or v.VIEW_DEFINITION like '%=*%'