Getting Deep into .net

January 25, 2012

Dynamic Theme Switching in Silverlight Prism App

Filed under: How To,Prsim,Silverlight 4 — goldytech @ 5:10 pm
Tags:

 

INTRO

In my recent consulting assignment I was asked the question by one of the developer , that how can we get dynamic theming working in Prism application.My answer was that you can implement in the same manner as you do in the standard Silverlight application. But then he further asked that there are various regions in the RegionManager and how each views loaded in the different content regions can get unified theme , this encouraged me to try this out and see how it works.I started working on it and viola my answer was correct , there is no difference in implementing dynamic theming in prism specific app. In this blog post I explain you the same. I assume that readers are already aware of Prism library. If you are not then I strongly recommend that you acquire the knowledge of the same. In my example you will see the very basics of Prism app but the library has much more to offer.

GETTING STARTED

I created a very simple PRISM application which had only one Module (ModuleA). This module is loaded on demand when you click on the menu link which is under the ShellView.The application default gets loaded in the BlueTheme but it allows you to change the theme on the fly from the Themes menu. See the screen shot below of both themes.

 

blueThemeBlackTheme

 

The application has two content regions (MainContent and FooterContent).

Code Snippet
  1. <menu:Menu Grid.Row="0" HorizontalAlignment="Left" VerticalAlignment="Top">
  2.             <menu:MenuItem Header="Modules">
  3.                 <menu:MenuItem Header="Load Module A" Command="{Binding LoadModuleCommand}"/>
  4.             </menu:MenuItem>
  5.             <menu:MenuItem Header="Themes">
  6.                 <menu:MenuItem Header="Blue" Command="{Binding Path=ChangeThemeCommand}"
  7.                                        CommandParameter="BureauBlue.xaml"
  8.                                        IsChecked="{Binding IsBlueThemeSelected}"/>
  9.                 <menu:MenuItem Header="Black" Command="{Binding Path=ChangeThemeCommand}"
  10.                                        CommandParameter="ExpressionLight.xaml"
  11.                                        IsChecked="{Binding IsBlackThemeSelected}"/>
  12.             </menu:MenuItem>
  13.  
  14.         </menu:Menu>
  15.         <ContentControl prism:RegionManager.RegionName="MainContentRegion" Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="12" />
  16.         <ContentControl prism:RegionManager.RegionName="FooterContentRegion" Grid.Row="2" Margin="12"/>

 
Let me show you the code which does the magic of dynamic theming.

Code Snippet
  1. public DelegateCommand<string> ChangeThemeCommand
  2.         {
  3.             get
  4.             {
  5.                 if (_changeThemeCommand == null)
  6.                 {
  7.                     _changeThemeCommand = new DelegateCommand<string>(x =>
  8.                     {
  9.                         Application.Current.Resources.MergedDictionaries.RemoveAt(0);
  10.                         var theme = Application.GetResourceStream(new System.Uri("/Shell;component/Assets/" + x, System.UriKind.Relative));
  11.                         var rd = (ResourceDictionary)(XamlReader.Load(new StreamReader(theme.Stream).ReadToEnd()));
  12.                         Application.Current.Resources.MergedDictionaries.Add(rd);
  13.                         if (x == "BureauBlue.xaml")
  14.                         {
  15.                             IsBlueThemeSelected = true;
  16.                         }
  17.                         else
  18.                         {
  19.                             IsBlackThemeSelected = true;
  20.                         }
  21.                     }, y => _moduleLoaded);//only allow to change themes when module is loaded
  22.                 }
  23.  
  24.                 return _changeThemeCommand;
  25.             }
  26.         }

The ChangeThemeCommand is DelegateCommand of String type. The command argument excepts the filename of theme. All theme files are located in Assets folders of the Shell project. The default theme is initialized in the App.xaml file with special syntax. It removes the current theme and loads the selected theme and merges it into the Resource Dictionary.

Code Snippet
  1. <Application.Resources>
  2.         <ResourceDictionary>
  3.             <ResourceDictionary.MergedDictionaries>
  4.                 <ResourceDictionary Source="/Shell;component/Assets/BureauBlue.xaml" />
  5.             </ResourceDictionary.MergedDictionaries>
  6.         </ResourceDictionary>
  7.     </Application.Resources>

This special syntax allows to access the files across different assemblies or xap files via relative paths.

CLOSURE

This was super simple to implement it and I highly recommend the devs to implement this feauture in their apps. Last a ninja tip. Always mark your assemblies in the module projects to CopyLocal=false if they are already referenced it in the Shell project. Download the sample code from here.

November 30, 2011

Windows Phone geocoding with Rx

Filed under: How To,Reactive Extensions,WindowsPhone — goldytech @ 4:38 pm
Tags:
INTRODUCTION

I had heard lot about Reactive Extensions (Rx) in the past but never got a chance to play with it until recently one of my project requirements were idle to make use of this great library.In this post I share my experience on how I used this library. Before we jump into code I would like to summarize the definition of Rx for the readers who haven’t known about it.

WHAT IS RX

Up till now we had heard that computers came up with multiprocessors and gigabytes of memory but now we are hearing the same for even mobile devices. The new models do come with dual core processers and enough memory. As a developer you need to adopt some special programming techniques to unleash this power. You must write concurrent and asynchronous code to scale up to the hardware. When we talk about the asynchronous programming lot of caution needs to be taken for threading and deadlock issues. Fortunately Rx.NET does all this heavy lifting for you and gives you a fluent api for Async programming with LINQ flavour.Rx.NET is developed at Microsoft Labs and comes for full .net Framework, Silverlight, Windows Phone and JavaScript.
Rx is based on the Observer pattern from the world of object oriented programming. This pattern is based on the Observable collection, known as a Subject. You register or subscribe as an Observer for this Subject and you get notified whenever there is a change in the collection. Let me explain you this with example code.

var numbers = Observable.Range(1,50);
numbers.Subscribe(x =>
textBlock1.Text += String.Format(" OnNext: {0}", x),
ex => textBlock1.Text += String.Format(" OnError: {0}", ex.Message),
() => textBlock1.Text += " OnCompleted");

In the above example the numbers collection is between 1 to 50. I subscribe to this collection for getting notifications. This is achieved by specifying the first argument of the subscribe method which is OnNext action method. The second argument is OnError , which is again the action method, you can handle the errors here and finally the OnCompleted, where you can do the cleanup if required or do the final processing.
Rx is entirely based on the LINQ and support all its extension methods like Where,Take,Skip etc. LINQ works with collections that implement IEnumerable,which are known as enumerable collections. Rx works with collections that implement an extension to IEnumerable, IQueryable, which is refer to as observable collections. Hope you must have got the fair idea of Rx by now for further study I would redirect you to Rx official site where there are great tutorials and samples to get you started.

USING Rx IN WINDOWS PHONE FOR GEOCODING

As mentioned above Rx library is available for Windows Phone 7 also, It is part of the SDK itself and you don’t need a separate download. All you need to add reference to your project two assemblies.
1)Microsoft.Phone.Reactive
2)System.Observable
In the sample application we display the GPS status and its coordinates coming from the location emulator. The user clicks on the Start button and then clicks on the location emulator to see the coordinates getting changed in the phone emulator. See the screenshot below for more clarity.

GeoCodewithRxDemo

To capture the latitude and longitudes you need to handle the PositionChanged event of GeoCoordinateWatcher class. The eventargs of this event is of prime importance to us as we will be using it to get the positions. See the code below.

var positions = Observable.FromEvent>(watcher, "PositionChanged").Where(g => !Double.IsNaN(g.EventArgs.Position.Location.Latitude) && !Double.IsNaN(g.EventArgs.Position.Location.Longitude));


positions.ObserveOnDispatcher().Subscribe(geo =>
{
this.txtPositon.Text = string.Format("{0:###.0000N;###.0000S;0}, {1:###.0000E;###.0000W;0}"
, geo.EventArgs.Position.Location.Latitude
, geo.EventArgs.Position.Location.Longitude
);

});

In the above code one thing to look is the Observable.FromEvent(watcher, “StatusChanged”). I am telling the Rx to Capture all the values coming from the observable collection of GeoPositionChangedEventArgs on the watcher object which is of type GeoCoordinate and the event name is PostionChanged. This will dump all the values of incoming coordinates in the positions variable. And then further I am interested in this collection so I will subscribe to it and will be notified whenever this collection gets changed. If you remember on the top I mentioned that Rx goes hand in hand with Linq and supports all its extension methods. Here in the above code I using Where to get only valid lats and longs which is having proper double values rest will be discarded. On receiving the notification that is onNext Action method ,I simply update my TextBlock Text in proper format of gps position.To avoid the cross thread issues I am using the ObserveOnDispatcher extension method.

CONCLUSION

I have barely scratched the surface of Rx there is a lot to it. I strongly recommend that all devs should acquire its knowledge and used it in their projects.Rx makes Async programming breeze which makes it as an idle choice to work with webservices.
Download the sample code of this post from here.

Cheers :)

October 10, 2011

How to create Tag Cloud in Silverlight

Filed under: How To,Silverlight 4 — goldytech @ 2:25 pm
Tags:

 

WHAT IS A TAG CLOUD

A tag cloud is a collection of texts that gets classified into the level of the importance. Text with greater importance are shown in the bigger size followed by the preceding importance , in short they are arranged in descending order. The importance is identified by one of the property usually a numeric value. It is one of the popular way for data visualizations. It is really gaining great heights in Business Intelligence 2.0 world. In this post I shall teach you how you can create tag cloud in Silverlight.

SCENARIO

To showcase my example we will take the top ten stocks that were traded on the stock exchange by their last trading price. See the screen shot below.

top10stocks

As you can see from the above picture. The company names text font size are appearing based on their last trading price. I have taken only two colors (Magenta and Blue) but the developer can implement a random color logic also here.

SILVERLIGHT IMPLEMENTAION

To generate the tag cloud in Silverlight is super simple. I have taken a wrap panel control available in Silverlight toolkit. I then add each textblock as children of this wrap panel. All this is done using MVVM Light Toolkit version 4 , which is still in Beta state but it is pretty stable. Let us dive into the code to have better idea.

public class MainViewModel :ViewModelBase

    {
        public MainViewModel()
        {

         
            GenerateCommand=new RelayCommand(()=>
                                {
                                    var stocks = GetStocks();
                                    double minLastPrice = stocks.Min(a => a.LastPrice);
                                    double maxLastPrice = stocks.Max(b => b.LastPrice);
                                    double diffLastPrice = maxLastPrice - minLastPrice;
                                    const double minFontSize = 15.0;
                                    const double maxFontSize = 40.0;
                                    const double diffFontSize = maxFontSize - minFontSize;
                                    for (int i = 0; i < stocks.Count(); i++)
                                    {
                                        Messaging.RaiseAddTextBlock.Send(new TextBlock { Text = stocks[i].Company, Foreground = i % 2 == 0 ? new SolidColorBrush(Colors.Magenta) : new SolidColorBrush(Colors.Blue), Margin = new Thickness(3), FontSize = minFontSize + stocks[i].LastPrice * diffFontSize / diffLastPrice });
                                    }
                                });
           

          
        }

        public RelayCommand GenerateCommand { get; private set; }       

        private List<Stock> GetStocks()
        {
            var stocks = new List<Stock>
        {
            new Stock { Company = "TATAPOWER", LastPrice= 105.25},
            new Stock { Company = "TATAMOTORS", LastPrice= 169.90},
            new Stock { Company = "DLF", LastPrice= 228.55},
            new Stock { Company = "SESAGOA", LastPrice= 214.35},
            new Stock { Company = "IDFC", LastPrice= 121.15},
            new Stock { Company = "TATASTEEL", LastPrice= 434.70},
            new Stock { Company = "INFY", LastPrice= 2597.50},
            new Stock { Company = "STER", LastPrice= 117.40},
            new Stock { Company = "RELIANCE", LastPrice=829.20},
            new Stock { Company = "WIPRO", LastPrice= 344.65}
          
        };
            return stocks;
        }

    }
}

The above code is not a brainer and it is self explanatory . The only thing that needs to be considered is the FontSize property of the textblock where I put the logic of displaying the size as per the LastPrice property of the stock class. The datasource of my Tag Cloud is hard coded collection but it could be dynamic also.

CLOSURE

Silverlight as a platform as a tremendous potential to develop BI apps. You can create great data visualizations from the toolkit available or from the third party controls from the different vendors. I encourage developer to explore this area and create a appealing user experience for your BI users. Download the sample code from here and enjoy Smile.

September 16, 2011

What is stored for developers in Windows 8

Filed under: Windows 8 — goldytech @ 1:46 pm

Now that the BUILD conference comes to end. It time to reflect what were the announcements made in it. I would especially give my thoughts from the developer perspective. I will summarize it in few points that matter most to the developers.

  • SILVERLIGHT IS ALIVE AND KICKING : I think Microsoft has silent its critics who were telling that Silverlight is dead and HTML 5 and JavaScript would be native development technology for Windows 8. With new version of Silverlight about to release by this fall. Tons of new features and improvements have been done in new version and I’m looking forward to develop my first production app. Microsoft has also given importance to new trend where the competition is heading that is HTML 5 and JavaScript. The developer has the option to develop in this language also. My old friends of C++ don’t get disheartened your skills are still in demand and you can program on Windows 8. So this summarizes that there is not one technology on which you can develop apps. Folks at Microsoft has kept their promise of backward compability.

 

  • WINDOWS RUNTIME (WINRT): Welcome to this new acronym. Uptill now you must have heard about .net framework but to develop the apps for Win8 you would require to enter new arena of Windows Runtime. This still will be managed code according to the speculations it is the subset of .net framework only where MS has picked and choose the namespaces and classes which could very well gel with new platform. Tim has a great blog post mystifying the facts and speculations of new runtime. You can read it over here.

 

  •  METRO STYLE APPS : Get yourself acquainted with this new style. As windows 8 natively support touch input natively. All the apps that you would be developing should support this style. This is something that is derived from Windows Phone 7. I had always loved Metro theme, smooth and fluid. All the apps should be touch centric and chromeless. You need to get your application certified before publishing it to the store. There are guidelines available and once you follow them there are 100 % chances that your application would pass in one attempt. As mentioned above keeping the backward compability in mind you can still continue to develop the apps in traditional old style like desktop or standard web apps running in the browser. MS has committed that whatever that is running in Windows 7 will run in Windows 8. All you need is to switched to the desktop mode. You have Visual Studio 2011 IDE for doing the development of this types of apps. It comes with preinstalled templates and each template comes with lot of boiler plate code to get you quickly started. Blend 5 now support HTML authoring also.

 

  • HARDWARE AGNOSTIC : This is the perhaps the best feature I like about new platform. As windows 8 runs equally well on all the form factors (various screen sizes ranging from dual monitors to tablets). It will run on Intel based processers as well as ARM based. I was mesmerized when I saw the demo where Steven Sinofsky showing Win8 running on ATOM based processor with 1 GIG of RAM. Awesome simply awesome. Imagine here the opportunities that lies for you as a developer, your app running on laptops,desktops and now even tables or slates. You can always monetize your efforts and earn few extra bucks besides your day job. I am not saying that it will make you millionaire Smile , but opportunity is definitely there.

 

I have been in this industry now for more than decade and this is probably the best time I am having in my career span. Lot of excitement times ahead and huge opportunities for developers to seize.

So start brushing up your skills

HAPPY CODING

August 5, 2011

Creating Fault Tolerant Silverlight Applications

 

INTRODUCTION

As an enterprise application developer you have to face lot of challenges. You are responsible for designing and developing highly scalable and fault tolerant systems. The systems that you develop are life line for your enterprise any downtime in it can cause a rippling effects and sometimes even loss of revenue. Your worries get more when you come to know that the application that you are working on shall be deployed on shared hosting environment. Though you have the SLA with the hosting company of  99.9 % uptime but servers do get crash and they backup or failover servers gets replaced so that your users get minimum downtime. I recently overcome this challenge and wants to share my experience with the community. The application that I developed was deployed on shared hosting environment with SQL Server on a separate box. The hosting company had a failover mechanism in place where by which if the server on which my database was running had some problems it will be taken over by the failover server. Now the question over here how will my application know that the main server is down and I have to switch over to the failover server because the connection string was already hardcoded in the web.config file which was pointing to the main server.This application was developed using Silverlight and WCF Ria Services. I took up this challenge and in the end came out with the elegant solution. So keep reading.

SOLUTION

I need to device a solution by which my app knows that which sql server it needs to point out before retrieving or submitting the data. For the  readers information both the database servers were always sync with the data , there was bi-directional synchronization mechanism already in place by the hosting company. So I was assured that my users would never get any stale data. After doing a bit of head scratching I found the way out. As I was using Entity Framework ,Visual Studio generates code based on your logical model when the solution was build. This generated code can be found under your .edmx file. It has the extension .designer.cs . Refer to the figure below.

VsCodegenerated

If you open this file you would find one partial class which inherits from the ObjectContext. As this class was partial I can always extend it in other class and use its existing partial methods. In my case I used the partial method OnContextCreated . The code of this this extended partial class is shown below.

Class1

Class2

The above code is no teaser. In the OnContextCreated method I check for the main server connection is working or not by calling the function CheckIfSqlServerisRunning() . If this function returns me false then I call another function which gets me the alternate connection for the failover sql server. CheckIfSqlServerisRunning function will return me true if I am able to open the connection successfully else it will return false. But the real potatoes and meat is in GetAlternativeConnection function. This function builds up the dynamic Sql connection string using SqlConnectionStringBuilder class and then I use the EntityConnectionStringBuilder class to make the Entity connection string.

The OnContextCreated method will be called whenever your domain service methods wants to perform any database operations and that is the catch. You always ensure that you give a valid sql connection to the service so it doesn’t fails and your user can get data seamlessly without knowing from which database server the data is coming from. You change the connection on the fly if the main server is down.

CONCLUSION

As the saying goes “WITH GREAT POWER COMES GREAT RESPONSIBILITIES” , the same thing applies to a developer. You carry a loads of responsibilities on your shoulder for the enterprise to become successful. Any bad code written by you can not only ruin you but your organization too. So first think and then code.

HAPPY CODING.

June 27, 2011

How to work with Hierarchal data in Entity Framework

Filed under: .NET,Entity Framework,How To — goldytech @ 12:12 pm
Tags:

 

INTRODUCTION

A couple of years back I blogged about how to retrieve the hierarchal data using T-SQL features. You can read that blog post here. Today life brought to me the same cross roads and I decided to take new route , so instead of using the T-SQL approach I preferred to go towards the Entity Framework. Microsoft has recently done some great enhancements in this data access framework especially with the release of version 4.1 , you can also take the advantage of code first approach. In this post I show you how you can get hierarchal data from your database using Entity Framework. So let us get started.

GETTING STARTED

In this post I am using the same example which I used for my earlier post. We have same employee table but this time it is self referencing table. The EmployeeId column, which is the primary key in the table is referencing to the ManagerId column (Allow null is set to true) in the same table. See the screen shot below.

Self referncing Employee table

The following is the sample data in this table

Employee table data

In the above screen shot you must observe that the ManagerId for the first row is null, which means this is the root in the hierarchy.

So now when you import this table into your model using the Entity Framework wizard , as this is self referencing table the wizard will create two navigational properties called Employee1 and Employee2 respectively. Refer to the screen shot below.

InitialModel

These two properties does not make any sense to the developers, so let us try to rename it. Right click on the Employee1 property and select properties from the context menu. In the properties window you will see that the multiplicity is set to multiple, which means that the association is of Many type. Check out the screen shot below.

Employee1 property

In the same manner let us also rename Employee2 property , if you right click this property and see the properties window you will find that multiplicity of this column is set to 0..1 , which means that the association end can be null or one. We will rename this column to Manager as seen in the screen shot below.

Employee2

Let me explain you further about the database relationships. Any relationship in the database has three characteristics.

  1. Degree : is the number of entity types that participates in the relationship. Unary and Binary relationship are most common.
  2. Multiplicity : is the number of entity types on each end of the relationship. Few examples are 0..1 (zero or one), 1 (one) and * (many).
  3. Direction : This can be unidirectional or bidirectional

In our example Degree is of unary type , as only Employee entity is involved in the relationship. Multiplicity is 0..1 and * and direction is bidirectional.

I hope that the above discussion have cleared your concepts about the database relationships, let us see now some code which displays the hierarchal data.

 Code

The above code loops through employee entity and checks whether the manager property is null and based on that writes the output . See the output for this code below.

ProgramOutput

CLOSURE

Anything new that comes out from Microsoft stable excites me. I always make a point to utilize the new technology whenever I get new project or opportunity. This blog post was also the result of the same passion. I encourage developers to keep the learning passion always alive because if that dies then consider your career to be finish. Let me know your thoughts on it in the form of comments.

KEEP LEARNING

May 21, 2011

Assembly Caching in Silverlight

Filed under: Silverlight 4 — goldytech @ 6:42 am
Tags: ,

Performance is key to any application and Silverlight application is no different. In this post I will show you how you can increase the performance of your app by using assembly caching feature in Silverlight.

What is Assembly Caching

You can gain the substantial performance in your application if your download time of the xap file can be reduced. Assembly caching feature allow to reduce this size of  xap file by partitioning your external assemblies in separate zip files.If you view the properties of your Silverlight project. You would find a checkbox with the text “ Reduce XAP size by using application library caching ”. See the screen shot below.

AssemblyCachningCheckbox

Once this checkbox is checked then instead of creating a single large xap file it will create separate zip (see the diagram below) files of all the external assemblies and the xap file will only contain Silverlight core assemblies.

ExternalAssemblies

Importance of Assembly Caching

This feature does not reduce the initial download time of your application, but it really helps when it comes to deploying the updates for your app. If this feature is off then the user has to download the entire application including the external assemblies with every update. But when this feature is on the user will only download the xap file without the external assemblies getting downloaded because these assemblies are cached in the user’s browser cache. These files only get downloaded when these files are changed on the server.

How it works

Every assembly which is getting cached corresponds to the external part manifest file on the same path from where it is being referenced. This file can be identified by the following name [AssemblyName].extmap.xml. So for example if we talk about System.ServiceModel.Web.Extensions assembly, its corresponding manifest file name will be in the same location with the filename as System.ServiceModel.Web.Extensions.extmap.xml. The AppManifest.xaml file , located in xap file references these external assemblies. The content of this file is listed below.

<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" EntryPointAssembly="TestBizApp"
EntryPointType="TestBizApp.App" RuntimeVersion="4.0.50826.0">
<Deployment.Parts>
<AssemblyPart x:Name="TestBizApp" Source="TestBizApp.dll" />
<AssemblyPart x:Name="System.Windows.Controls.Data.DataForm.Toolkit"
Source="System.Windows.Controls.Data.DataForm.Toolkit.dll" />
</Deployment.Parts>
<Deployment.ExternalParts>
<ExtensionPart Source="System.ComponentModel.DataAnnotations.zip" />
<ExtensionPart Source="System.ServiceModel.DomainServices.Client.zip" />
<ExtensionPart Source="System.ServiceModel.DomainServices.Client.Web.zip" />
<ExtensionPart Source="System.ServiceModel.Web.Extensions.zip" />
<ExtensionPart Source="System.Windows.Controls.Data.Input.zip" />
<ExtensionPart Source="System.Windows.Controls.zip" />
<ExtensionPart Source="System.Windows.Controls.Navigation.zip" />
<ExtensionPart Source="System.Windows.Data.zip" />
</Deployment.ExternalParts>
</Deployment>

Closure

Every developer must think upfront for gaining performance improvements. He or she must leave no stone unturned to gain any performance improvements. If your project is referenced to your own external assembly you must try to cached it that also. For this the assembly should be signed. Alex Golesh has utility to generate the extmap files of your custom assemblies.

PS : Assembly Caching feature is not available for Out of Browser Silverlight Apps.

HAPPY CODING

March 27, 2011

Introduction to JQuery

Filed under: .NET,How To,JavaScript,JQuery — goldytech @ 1:52 pm
Tags:

 

I recently gave the lecture on JQuery in my company. I thought it is good idea to share the same with the community. so here are the slide decks and sample source code. The sample source code can be downloaded from here. You can view the slides from here.

March 4, 2011

How to add Computed Properties in WCF Ria Services on client

Filed under: How To,Silverlight 4,WCF — goldytech @ 1:51 pm
Tags:

 

Customers have become very demanding these days, but thanks to the technology that we can satisfy them. I met one of our clients for the new project. The project was complex in the sense that it involved lot of calculations. The prime requirement of the client was that the end user must immediately see the output of the calculations once all the required input is provided by them. My first choice for any LOB apps is Silverlight 4 + WCF Ria services. So the big question was that how can I get this done. After doing a bit research I found out that it was pretty straight forward with WCF Ria Services framework. So here we go I will outline the solution with sample scenario.

The scenario is pretty simple. We have customer Entity mapped to Customer table in the database. Following are its columns.

  • FirstName
  • LastName
  • DateOfBirth

Now here is the twist we need to calculate the Age of the customer. As this property needs to be computed we don’t have it in our database but this should be calculated after user enters date of birth. So to accomplish this follow the steps mentioned below

  1. Add a new partial  class  of the same name in your client project. Please ensure that this class namespace is same as your Domain Service namespace.
  2. This class must be inherited from the Entity class available in System.ServiceModel.DomainServices.Client namespace.
  3. Add a read only property “Age” of integer type. Write your age calculation logic in the get block of this property.
  4. Raise the property event when the DateOfBirth property is changed.

ComputedPropertyCode

Hope you would find this useful. Awaiting your valuable feedback.

Cheers

January 24, 2011

Architecting Asp.net apps

Filed under: Asp.net,How To — goldytech @ 2:41 pm
Tags: , ,

 

INTRODUCTION

Writing a scalable and maintainable application is not like walking in a park. You need to run that extra mile to make it happen. The foundation  architecture and design pattern plays crucial role here. You can run into various issues if your initial foundation is not strong enough. “Fail planning is plan to Fail”. I think this phrase summarises it all. In this blog post I will do a walkthrough of architecting mission critical apps which are life line of the enterprise. So let us get started.

BUSINESS CASE

To prove my point I shall not be giving a fictious business case, but this would be some real example. Infact this is the project which I worked upon couple of years back. I was developing an Human Resources Management System. In the payroll module of this system there various earnings given to the employees like Basic Salary,Hra, Dearness Allowance etc. The basic salary was fixed and the HRA was calculated based on Employee Grades (Executive, Manager and Clerks). Below is the table which tells how hra should be calculated.

Employee Grade Hra Percentage (Basic Salary)
Executive 35%
Manager 25%
Clerk 15%

In the system there should be a page where Hra should be applied based on the selection of Employee Grade from the dropdown list. See the below screen shot.

The grid output

I have a disclaimer to be made here. The above screen shot is not from the actual application that I wrote. I developed this page just for this blog post keeping things very simple. I hope the business case is clear in your mind now so now let us get into some coding. I will first show you the anti pattern which most of developers will adopt to get this output and later on I will discuss about how this should be implemented with Separation of Concerns using Logical Layered Architecture.

THE ANTI PATTERN

The quick and dirty way to achieve this would be done in this simple 3 steps

  1. Drag the GridView control on the form.
  2. Bind it to some Datasource control like SQLDatasource or ObjectDataSource
  3. In the RowDataBound of gridview write your business logic to calculate the hra

This would solve the purpose but you will run into problems once the application starts growing. Everything here is tightly coupled. Your core business logic is written in the code behind file. So let us write the code that will differentiate men from boys.

SEPRATION OF CONCERNS WITH LAYERED ARCHITECTURE

The below diagram represents an N layered architecture for mission critical asp.net apps.

NLayer

Using solution folder feature I have separated my solution to represent each layer. I have also added the unit tests project in the solution. All units tests are done using Mock objects which proves that the most of the code is written using abstraction rather than concretions. I have implemented few design patterns in the model layer which has my business logic encapsulated into it.In the upcoming sections I shall be talking about them.

  • STRATEGY PATTERN : This pattern belongs to Behaviour patterns group. It encapsulates the algorithm within it for which the behaviour can be changed at run time. It means here that the strategy interface will encapsulate the behaviour which can be changed by the classes that will implement this interface. So let us look at the code below.

IHraInerface

So now IHra interface is ready let us look at the classes which implements this interface.

ExecutiveHraStrategy

The above code is of ExecutiveHraStrategy class which implements the IHra interface. As you can see the entire business logic of calculating the hra is encapsulated. In the same manner I have implemented the Manager and Clerk Hra in different classes implementing the same interface. This adheres to Single Responsibility principle.

  • FACTORY PATTERN : The factory method pattern belongs to creational group. The factory pattern involves a static class with static method which returns the class instance based on the argument specified in the static method. Look at the code below

HraFactory

  • DEPENDENCY INJECTION : This design pattern helps in decoupling , this can be achieved if you have code against abstractions rather than the concrete implementations. This injection ensures that all the dependency objects required for the class to function are already in place. There are three ways to do this
    1. via Constructor
    2. via Property
    3. via Method

See the code below how my service class gets all its dependency in the constructor. Notice here that it is based on abstraction (Interface) rather than concrete class. This enable us to do my unit testing based on mock objects. More on this in further section.

DependencyInjection

UNIT TESTS

As mentioned above in my solution there is a project of Unit Tests. I am a big fan of Test Driven Development. I have used N-Unit framework to accomplish this. Using abstractions enable me to use mock objects. My service class depends on database to get the the data and do the calculations but whereas when I am writing my unit tests I really don’t require to connect to the live database and test my Hra calculation logic. I just need mock data to get this thing done. See the code below.

MockImplementation

Let me show you now the test method code which uses this mock object to check the hra calculations.

Testmethod

CLOSURE

It really makes lot of sense to spend few hours in planning architecture before starting the project. I hope you must have enjoy reading this post. I would love to hear from you. Download the sample code from here.

Next Page »

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 47 other followers