Software Architecture – Design Problem Part 2 – DTO- MS Visual Studio 2010 – Net 4-0 – WCF – NHibernate – Silverlight

July 31, 2010

This is second post with reference to Design Architecture discussion on Project based on NHibernate + WCF+Sliverlight.
See the first Post last post here.

In my last post I had identified that we need DTO Objects.
DTO-Data Transfer Objects are customized object that can have different object structure then Objects used in OR Mapping/Nhibernate. When a request for object comes from client (Silverlight project) to server (ASP .Net project) having Service via WCF wire, at Server side, query is run on OR Mapping Object, utiizing full benefits of Lazy loading, business rules are applied, and finally data is ready to be send to client. At this point data is not in customized according to client needs and filtering of properties for objects is required to reduce the size of data being transferred. That where DTO objects comes in action.

Benefits of DTO objects:

1. It is always better from software design perspective to not expose object of data layer direct to client end that is silverlight via WCF.

2. Most important benefit is: filtering of object properties or Change in structure of objects that needs to be transferred across WCF wire. Let suppose you have invoice creation form having fields to be filled as like client, consignee, agent, shipper, sales person, operation manager and many other. So when loading invoice form data from all these entities like agents ……. will travel on WCF wire. Each entity may have a lot of properties, but on client side we only need id and name of all these entities. So we can make various versions of entities according to need for architecture.

3. With DTO approach, UI (silverlight) is only dependent on DTO objects, so the data layer can be changed to any tech like linq2sql,linq2entities or any other thing. Change in Data layer is very flexible with DTO.

Elements of Design Example:
You can download sample here.
Rename the file as sample.zip and then extract.

Solution Explorer will look like as:



This Example will fetch 2 different DTO objects with sample look and feel as below.


There is one entity class for nhibernate named as “Customer” with HBM set in Mapping.hbm.xml.

There are 2 DTO Classes. First DTO with properties as ClientID,ClientCode, Name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization;

namespace WCFNHibernateSilverLightSample.Web.DTOEntities
{
    [DataContract(IsReference = true)] 
    public class DTOCustomer
    {
        #region Fields
        private int _ClientID;
        private string _ClientCode;
        private string _Name;
        #endregion
        #region Constructors
        /// <summary>
        /// Initializes a new instance of the GeneralClientMaster class 
        /// </summary> 
        public DTOCustomer()
        {
        }     
        #endregion

        #region Properties
        /// <summary>
        /// Gets or sets the ClientID for the current GeneralClientMaster
        /// </summary>
        [DataMember]
        public virtual int ClientID
        {
            get { return _ClientID; }
            set { _ClientID = value; }
        }

        /// <summary>
        /// Gets or sets the ClientCode for the current GeneralClientMaster
        /// </summary>
        [DataMember]
        public virtual string ClientCode
        {
            get { return _ClientCode; }
            set { _ClientCode = value; }
        }
        [DataMember]
        public virtual string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }

        #endregion

    }

    
}

Second DTO class has extra parameter of Address as:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization;

namespace WCFNHibernateSilverLightSample.Web.DTOEntities
{
    [DataContract(IsReference = true)]
    public class DTOCustomerVersionWithAddress
    {
        #region Fields
        private int _ClientID;
        private string _ClientCode;
        private string _Name;
        private string _Address;
        #endregion
        #region Constructors
        /// <summary>
        /// Initializes a new instance of the GeneralClientMaster class 
        /// </summary> 
        public DTOCustomerVersionWithAddress()
        {
        }
        #endregion

        #region Properties
        /// <summary>
        /// Gets or sets the ClientID for the current GeneralClientMaster
        /// </summary>
        [DataMember]
        public virtual int ClientID
        {
            get { return _ClientID; }
            set { _ClientID = value; }
        }

        /// <summary>
        /// Gets or sets the ClientCode for the current GeneralClientMaster
        /// </summary>
        [DataMember]
        public virtual string ClientCode
        {
            get { return _ClientCode; }
            set { _ClientCode = value; }
        }
        [DataMember]
        public virtual string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }
        [DataMember]
        public virtual string Address
        {
            get { return _Address; }
            set { _Address = value; }
        }

        #endregion

    }
 
}

A converter class will be required as below to transform “customer” to “DTOCustomer” and “DTOCustomerVersionWithAddress”.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WCFNHibernateSilverLightSample.Web.DTOEntities.DTOConvertor
{
    public class DTOConvertor
    {
        #region CustomerConvertor

        public static DTOCustomer ConvertFromCustomerToDTOCustomer(Customer cust)
        {
            DTOCustomer dtocus = new DTOCustomer();
            dtocus.ClientID =  cust.ClientID;
            dtocus.ClientCode =  cust.ClientCode;
            dtocus.Name =  cust.Name;            
            return dtocus;            
        }
        public static DTOCustomerVersionWithAddress ConvertFromCustomerToDTOCustomerVersionWithAddress(Customer cust)
        {
            DTOCustomerVersionWithAddress dtocus = new DTOCustomerVersionWithAddress();
            dtocus.ClientID = cust.ClientID;
            dtocus.ClientCode = cust.ClientCode;
            dtocus.Name = cust.Name;
            // Note here Transformation of properties from Nhibernate Object to DTO Objects
            // It is really a simple example. Very advance level tranformation can be done.
            dtocus.Address = cust.PostalAddress + " Tel: " + cust.Phone1 + " Fax: " + cust.Fax1 + " Email : " + cust.Email;
            return dtocus;
        }
        #endregion CustomerConvertor
    }
}

The WCF Service code will look like as

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Channels;
using NHibernate;
using WCFNHibernateSilverLightSample.Web.DTOEntities;
using WCFNHibernateSilverLightSample.Web.DTOEntities.DTOConvertor;

namespace WCFNHibernateSilverLightSample.Web
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "GetDataService" in code, svc and config file together.
    public class GetDataService : IGetDataService
    {
        public IList<DTOCustomer> GetCustomer()
        {
            IList<Customer> list;
            IList<DTOCustomer> listDTO =  new List<DTOCustomer>();
            NHibernate.ISession session = NHibernateHelper.OpenSession();
            ICriteria query = session.CreateCriteria(typeof(Customer));
            list = query.List<Customer>();

            foreach(Customer c in list)
            {
                listDTO.Add(DTOConvertor.ConvertFromCustomerToDTOCustomer(c));
            }
            return listDTO;
        }
        public IList<DTOCustomerVersionWithAddress> GetCustomerWithAddress()
        {
            IList<Customer> list;
            IList<DTOCustomerVersionWithAddress> listDTO = new List<DTOCustomerVersionWithAddress>();
            NHibernate.ISession session = NHibernateHelper.OpenSession();
            ICriteria query = session.CreateCriteria(typeof(Customer));
            list = query.List<Customer>();

            foreach (Customer c in list)
            {
                listDTO.Add(DTOConvertor.ConvertFromCustomerToDTOCustomerVersionWithAddress(c));
            }
            return listDTO;
        }
    }
}

You can download sample here.
Rename the file as sample.zip and then extract.

Advertisements

Software Architecture – Problems and Solutions with MVVM Model-View-ViewModel

July 29, 2010

MSDN Flash Newsletter pointed out a very good article dated July 19, 2010 .

Topic: When is the MVVM design pattern applicable to RIA and desktop apps? When is it unnecessary?
By: Robert McCarter
URL: http://msdn.microsoft.com/en-us/magazine/ff798279.aspx

Really a good Reading.


Software Architecture – Isolated Storage Introduction

July 29, 2010

Silverlight application works on client end browser, after downloading from web server.
Silverlight provide isolated storage which provides file system based storage space for storing the data on client side.

Isolated storage can act like cookies in ASP .Net, so used in saving session related data about session and application state. Secondly media data like video/audio files can be saved on client end, for second time fast access and manipulation.

On silverlight page, right click to see the configuration screen for isolated storage as:


Sample Code

Lets follow a simple application for reading and writing to isolated storage which will look like as:


Code to save data will look like as:

            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("data.txt", FileMode.Create, isoStore))
                {
                    using (StreamWriter writer = new StreamWriter(isoStream))
                    {
                        writer.Write(datatowrite.Text);
                    }
                }

            }

Code to read data will look like as:

using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream isoStream =
                    new IsolatedStorageFileStream("data.txt", FileMode.OpenOrCreate, isoFile))
                {
                    using (StreamReader sr = new StreamReader(isoStream))
                    {
                        dataread.Text = sr.ReadToEnd();
                    }
                }

Reference:
www.silverlight.net


Software Architecture – Microsoft SQL Server Express Edition with Advance Features -Licensing Query

July 29, 2010

While Exploring Licensing option for PCMS ERP Pegasus Cargo Management System, i had passed a query to Microsoft-Pakistan.

My Query to Microsoft Licensing Team – Islamabad – Pakistan

We are evaluating to use Microsoft SQL Server Express edition with advance features for our product.

With reference to your link below,
http://msdn.microsoft.com/en-us/library/cc645993.aspx
We have some questions as:

1. Is there any limitation of number of clients connecting to SQL Server express edition with advance features?

2. Secondly, table with title as “Scalability and Performance” in the above link suggests that there is a limitation of “Maximum memory utilized” as “1 GB” for SQL Server Express edition with advance features.. What is the meaning of this limitation, can you please explain it in more detail? Does this memory refer to the size of memory that can be used in system where SQL server will be installed or it is the memory being used by SQL server process in task manager of OS.


Is there any limitation of number of clients connecting to SQL Server express edition with advance features?

Microsoft Answer:- Yes, generally SQL Server allows 32,767 concurrent / simultaneous connections, however for your instance you can check by running the @@MAX_CONNECTIONS function. This function would return you the maximum number of connections on that particular instance, however it can be different from the currently configured maximum number of connections on that particular instance so this is configurable (sp_configure) but staying within the maximum connection limit.

Secondly, table with title as “Scalability and Performance” in the above link suggests that there is a limitation of “Maximum memory utilized” as “1 GB” for SQL Server Express edition with advance features.. What is the meaning of this limitation, can you please explain it in more detail? Does this memory refer to the size of memory that can be used in system where SQL server will be installed or it is the memory being used by SQL server process in task manager of OS.

Microsoft Answer:- This is the maximum memory which SQL Server express can use, regardless of the system memory.


Software Architecture – Design Problem – MS Visual Studio 2010 + .Net 4.0 + WCF + NHibernate + Silverlight

July 28, 2010

Environment: MS Visual Studio 2010 + .Net 4.0 + WCF + NHibernate + Silverlight

This post assumes that you have initial knowledge of WCF, NHibernate, Silverlight.

See the sample code for this solution working here.
Rename file as up.zip for extracting.

Sample Project:

Entities Relation / Tables relation is like:

Region >> Country >> City >> Area

So each region has many countries, Each country has many cities. Each City has many regions.
A typical Silverlight solution is created with 2 projects (One for silverlight(Client side project), other for ASP .Net Web project (server side ) having a WCF Service for data transfer from server side to client side.

Problem Definition:

Lets suppose you want to get list of City with lazy=”false” and fetch=”join”
for all entities So we will get following queries in SQL Profiler:

SELECT this_.CityID as CityID3_2_, this_.CountryID as CountryID3_2_, this_.CityCode as CityCode3_2_, this_.Description as Descript4_3_2_, this_.Active as Active3_2_, country2_.CountryID as CountryID1_0_, country2_.CountryCode as CountryC2_1_0_, country2_.Description as Descript3_1_0_, country2_.Active as Active1_0_, country2_.RegionId as RegionId1_0_, regions3_.RegionID as RegionID0_1_, regions3_.RegionCode as RegionCode0_1_, regions3_.Description as Descript3_0_1_, regions3_.Active as Active0_1_ FROM GeneralCityMaster this_ left outer join GeneralCountryMaster country2_ on this_.CountryID=country2_.CountryID left outer join GeneralRegionMaster regions3_ on country2_.RegionId=regions3_.RegionID

Again get list of City with lazy=”false” and fetch=”select”
for all entities So we will get following queries in SQL Profiler:

SELECT this_.CityID as CityID3_0_, this_.CountryID as CountryID3_0_, this_.CityCode as CityCode3_0_, this_.Description as Descript4_3_0_, this_.Active as Active3_0_ FROM GeneralCityMaster this_

For each country in list, there will be an select from country table as:

exec sp_executesql N'SELECT country0_.CountryID as CountryID1_0_, country0_.CountryCode as CountryC2_1_0_, country0_.Description as Descript3_1_0_, country0_.Active as Active1_0_, country0_.RegionId as RegionId1_0_ FROM GeneralCountryMaster country0_ WHERE country0_.CountryID=@p0',N'@p0 int',@p0=1

For each region in list, there will be an select from region table as:

exec sp_executesql N'SELECT regions0_.RegionID as RegionID0_0_, regions0_.RegionCode as RegionCode0_0_, regions0_.Description as Descript3_0_0_, regions0_.Active as Active0_0_ FROM GeneralRegionMaster regions0_ WHERE regions0_.RegionID=@p0',N'@p0 int',@p0=21

Two Problems:
There are 2 problems with above implementation.

Lazy load is false, so on server side that is ASP .Net / WCF Project, if we need some processing to be done, it is loading all data, no lazy initialization helps us.

Secondly, in both above cases data is joined from all the corresponding tables even if it is not required. Suppose we want to get data of cities only but unfortunately data of country and region is also fetched and transfer of such a heavy data across the WCF wire is very heavy activity.

If you will change lazy=”true” for entities, then WCF will pass following error.

{System.Net.WebException: The remote server returned an error: NotFound.
   at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
   at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
   at System.Net.Browser.AsyncHelper.<>c__DisplayClass2.<BeginOnUI>b__0(Object sendState)}

In order to see the real problem, configure WCF Log as explained
as explained at here

On looking into



Exeption will look like as:

There was an error while trying to serialize parameter http://tempuri.org/:GetCitiesResult. The InnerException message was 'Type 'CountryProxy' with data contract name 'CountryProxy:http://schemas.datacontract.org/2004/07/' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'.  Please see InnerException for more details.

Stack trace will look like as:

System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameterPart(XmlDictionaryWriter writer, PartInfo part, Object graph)
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameter(XmlDictionaryWriter writer, PartInfo part, Object graph)
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeBody(XmlDictionaryWriter writer, MessageVersion version, String action, MessageDescription messageDescription, Object returnValue, Object[] parameters, Boolean isRequest)
System.ServiceModel.Dispatcher.OperationFormatter.SerializeBodyContents(XmlDictionaryWriter writer, MessageVersion version, Object[] parameters, Object returnValue, Boolean isRequest)
System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter writer)
System.ServiceModel.Channels.BodyWriter.WriteBodyContents(XmlDictionaryWriter writer)
System.ServiceModel.Channels.BodyWriterMessage.OnBodyToString(XmlDictionaryWriter writer)
System.ServiceModel.Channels.Message.ToString(XmlDictionaryWriter writer)
System.ServiceModel.Diagnostics.MessageLogTraceRecord.WriteTo(XmlWriter writer)
System.ServiceModel.Diagnostics.MessageLogger.LogInternal(MessageLogTraceRecord record)
System.ServiceModel.Diagnostics.MessageLogger.LogMessageImpl(Message&amp; message, XmlReader reader, MessageLoggingSource source)
System.ServiceModel.Diagnostics.MessageLogger.LogMessage(Message&amp; message, XmlReader reader, MessageLoggingSource source)
System.ServiceModel.Dispatcher.DispatchOperationRuntime.SerializeOutputs(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
System.ServiceModel.Dispatcher.ChannelHandler.DispatchAndReleasePump(RequestContext request, Boolean cleanThread, OperationContext currentOperationContext)
System.ServiceModel.Dispatcher.ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext)
System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(IAsyncResult result)
System.ServiceModel.Dispatcher.ChannelHandler.OnAsyncReceiveComplete(IAsyncResult result)
System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
System.Runtime.InputQueue`1.AsyncQueueReader.Set(Item item)
System.Runtime.InputQueue`1.EnqueueAndDispatch(Item item, Boolean canDispatchOnThisThread)
System.Runtime.InputQueue`1.EnqueueAndDispatch(T item, Action dequeuedCallback, Boolean canDispatchOnThisThread)
System.ServiceModel.Channels.SingletonChannelAcceptor`3.Enqueue(QueueItemType item, Action dequeuedCallback, Boolean canDispatchOnThisThread)
System.ServiceModel.Channels.HttpChannelListener.HttpContextReceived(HttpRequestContext context, Action callback)
System.ServiceModel.Activation.HostedHttpTransportManager.HttpContextReceived(HostedHttpRequestAsyncResult result)
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest()
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest()
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state)
System.Runtime.IOThreadScheduler.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

This exception reflects that when WCF serializer tries to load countries, it fails because of lazy loading being true as country will be a proxy object, so it will pass the exception.

Solution:
After reviewing the suggestions provided by Sowmy Srinivasan’s Blog at:
http://blogs.msdn.com/b/sowmy/archive/2006/03/26/561188.aspx

and discussion on Johan Danforth’s Blog at:
http://weblogs.asp.net/jdanforth/archive/2008/12/22/nhibernate-and-wcf-is-not-a-perfect-match.aspx

I have introduced 3 new classes as:

1. HibernateDataContractSurrogate which implements IDataContractSurrogate which replaces proxy object with forcefully created object by the DataContractSerializer of WCF during serialization.

MSDN Reference:
http://msdn.microsoft.com/en-us/library/ms574969.aspx

2. ReferencePreservingDataContractSerializerOperationBehavior
Which is derived from DataContractSerializerOperationBehavior will extend the functionality provided by DataContract behavior.

3. ReferencePreservingDataContractFormatAttribute which provide attribute that will apply the behavior created above with name
ReferencePreservingDataContractSerializerOperationBehavior

So in short we have modified the behavior of data contract by using IDataContractSurrogate to replace proxy object with forcefully created object.

After this above change of introducing 3 classes, old exception of countryproxy will disappear, but a new exception will be there as below.

There was an error while trying to serialize parameter http://tempuri.org/:GetCitiesResult. The InnerException message was 'Type 'WCFNHibernateSilverLightSample.Web.City' with data contract name 'City:http://schemas.datacontract.org/2004/07/WCFNHibernateSilverLightSample.Web' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'.  Please see InnerException for more details.

Trace as:

System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameterPart(XmlDictionaryWriter writer, PartInfo part, Object graph)
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameter(XmlDictionaryWriter writer, PartInfo part, Object graph)
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeBody(XmlDictionaryWriter writer, MessageVersion version, String action, MessageDescription messageDescription, Object returnValue, Object[] parameters, Boolean isRequest)
System.ServiceModel.Dispatcher.OperationFormatter.SerializeBodyContents(XmlDictionaryWriter writer, MessageVersion version, Object[] parameters, Object returnValue, Boolean isRequest)
System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter writer)
System.ServiceModel.Channels.BodyWriter.WriteBodyContents(XmlDictionaryWriter writer)
System.ServiceModel.Channels.BodyWriterMessage.OnBodyToString(XmlDictionaryWriter writer)
System.ServiceModel.Channels.Message.ToString(XmlDictionaryWriter writer)
System.ServiceModel.Diagnostics.MessageLogTraceRecord.WriteTo(XmlWriter writer)
System.ServiceModel.Diagnostics.MessageLogger.LogInternal(MessageLogTraceRecord record)
System.ServiceModel.Diagnostics.MessageLogger.LogMessageImpl(Message&amp; message, XmlReader reader, MessageLoggingSource source)
System.ServiceModel.Diagnostics.MessageLogger.LogMessage(Message&amp; message, XmlReader reader, MessageLoggingSource source)
System.ServiceModel.Dispatcher.DispatchOperationRuntime.SerializeOutputs(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&amp; rpc)
System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
System.ServiceModel.Dispatcher.ChannelHandler.DispatchAndReleasePump(RequestContext request, Boolean cleanThread, OperationContext currentOperationContext)
System.ServiceModel.Dispatcher.ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext)
System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(IAsyncResult result)
System.ServiceModel.Dispatcher.ChannelHandler.OnAsyncReceiveComplete(IAsyncResult result)
System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
System.Runtime.InputQueue`1.AsyncQueueReader.Set(Item item)
System.Runtime.InputQueue`1.EnqueueAndDispatch(Item item, Boolean canDispatchOnThisThread)
System.Runtime.InputQueue`1.EnqueueAndDispatch(T item, Action dequeuedCallback, Boolean canDispatchOnThisThread)
System.ServiceModel.Channels.SingletonChannelAcceptor`3.Enqueue(QueueItemType item, Action dequeuedCallback, Boolean canDispatchOnThisThread)
System.ServiceModel.Channels.HttpChannelListener.HttpContextReceived(HttpRequestContext context, Action callback)
System.ServiceModel.Activation.HostedHttpTransportManager.HttpContextReceived(HostedHttpRequestAsyncResult result)
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest()
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest()
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state)
System.Runtime.IOThreadScheduler.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

Solution for the above exception is provided at:
http://msdn.microsoft.com/en-us/library/system.servicemodel.serviceknowntypeattribute.aspx

Introduce ServiceKnownType attribute in service contract with a helper class,
So the Service will look like as:

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IGetDataService" in both code and config file together.
    [ServiceContract]
    [ServiceKnownType("GetKnownTypes", typeof(Helper))]
    public interface IGetDataService
    {

        [OperationContract]        
        [ReferencePreservingDataContractFormat]
        IList<City> GetCities();
    }



// This class has the method named GetKnownTypes that returns a generic IEnumerable.
    static class Helper
    {
        public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider)
        {
            System.Collections.Generic.List<System.Type> knownTypes =
                new System.Collections.Generic.List<System.Type>();
            // Add any types to include here.
            knownTypes.Add(typeof(City));
            knownTypes.Add(typeof(Country));
            knownTypes.Add(typeof(Regions));
            knownTypes.Add(typeof(AreaMaster));
            
            return knownTypes;
        }
    }

So now the first problem has been solved. So now in business classes we can use objects with lazy loading working, only required object will be initialized. We have lazy loading true in OR Mapping, so on Server side “WCFNHibernateSilverLightSample.Web” project will access the object model with fully operational benefits of lazy loading.

See the sample code for this solution working here.

But second problem still exists. To solve the second problem, DTO (Data Transfer Objects) are used. DTO object are simple entity objects have the only those properties that needs to be transferred via WCF wire, So OR Mapping Nhibernate object will be different from DTO objects. Once the data is fetched in OR Mapping Nhibernate object, a transformation is done to DTO object and light weight DTO objects are passed with WCF to client end silverlight project.

I will do one more post to demonstrate this second problem in next post.

Both problems must be solved in a Good designed WCF/Sliverlight/Nhibernate project.

Happy Coding.


Software Architecture – C# 4.0- New Feature – Named Parameters and Optional Parameters

July 25, 2010

C# 4.0 introduced two new concepts as Named Parameters and Optional Parameters

Named Parameters:

Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter’s name rather than with the parameter’s position in the parameter list.

Example:

public int CalculateSize(int Lenght , int Width ,  int Height)       
{        return Lenght + Width + Height;
 }

Can be called as

CalculateSize(1, 2, 2);            // call without named parameters
CalculateSize(Lenght:3, Height: 3, Width: 3);
CalculateSize(2, Height: 3, Width: 3); // A unnamed parameter can follow named parameter in argument list
CalculateSize(Lenght:3, Height: 3, 3); // Error: A named parameter can't follow unnamed parameters  in argument list

IntelliSense is shown for named parameters as shown below by specifying parameters name followed by “:”

Optional Parameters:
The definition of a method, constructor, indexer, or delegate can specify that its parameters are required or that they are optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters.
Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. Default values must be constants.
Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters

public int CalculateSize(int Lenght , int Width ,  int Height = 6)
        {
         return Lenght + Width + Height;
       }

Here “Height” is Optional parameter because it default value is specified.

CalculateSize(3, 5); // Height is optional parameter,so can be skipped.
CalculateSize(3, , 5); //  Error: Width is not optional parameter,so can't be skipped
CalculateSize(3);   //Error: Invalid parameters

Optional parameters are shown by square brackets


Software Architecture – What is future of Web with reference to HTML 5-Will it devalue current presentation layer technologies for Web like Flash, Silverlight

July 25, 2010

 
A Cross Referenced Note about HTML5

                                                                     By: Shahzad Sarwar

                                                                     To: Development Team

                                                                     Dated: 25th July 2010

Scope:

What is HTML5?

What are the new features in HTML5?

What is future of Web with reference to HTM 5-Will it devalue current presentation layer technologies for Web like Flash, Silverlight?

What is HTML5?

HTML5 is currently under development as the next major revision of the HTML standard. Like its immediate predecessors, HTML 4.01 and XHTML 1.1, HTML5 is a standard for structuring and presenting content on the World Wide Web. The new standard incorporates features like video playback and drag-and-drop that have been previously dependent on third-party browser plug-ins such as Adobe Flash, Microsoft Silverlight, and Google Gears.

The Web Hypertext Application Technology Working Group (WHATWG) started work on the specification in June 2004 under the name Web Applications 1.0. As of March 2010[update], the specification is in the Draft Standard state at the WHATWG, and in Working Draft state at the W3C. Ian Hickson of Google, Inc. is the editor of HTML5.

Ian Hickson, editor of the HTML5 specification, expects the specification to reach the Candidate Recommendation stage during 2012. The criteria for the specification becoming a W3C Recommendation is “two 100% complete and fully interoperable implementations”. In an interview with TechRepublic, Hickson guessed that this would occur in the year 2022 or later. However, many parts of the specification are stable and may be implemented in products.

What are new Features in HTML5?

In addition to specifying markup, HTML5 specifies scripting application programming interfaces (APIs). Existing document object model (DOM) interfaces are extended and de facto features documented. There are also new APIs, such as:

For more details about new features see these videos by Google.

What is future of Web with reference to HTM 5-Will it devalue current presentation layer technologies for Web like Flash, Silverlight?

Answer is No. Because the features that HTML5 is providing is very small subset of the functionality provided by Flash and Silverlight.

Lets take an example of 2D/3D Graphics support. Although HTML5 has provided Canvas API but it can’t be compared with full support provided by Silverlight or Flash.

Same is the case with Video and Audio support. HTML before HTML5 don’t have audio and video support. Now that support is there in HTML5. But this support is limited and can’t help in all cases.

So in short yes, with HTML5, the standard has grown a lot and there will always space for commercial products who will enhance the standard and will provide more deep implementation of features.

This gap between standard and commercialization of standard in products will always be there.

Wait till all features of HTML5 are implemented in all browsers and enjoy the new world of web.

References:

http://www.youtube.com/watch?v=EdDc7sWjCL4&NR=1

http://www.youtube.com/watch?v=siOHh0uzcuY&feature=channel

http://www.youtube.com/watch?v=aW–Wlf9EFs&feature=channel

http://www.youtube.com/watch?v=AusOPz8Ww80&feature=related

http://dev.w3.org/html5/spec/Overview.html

http://dev.w3.org/html5/html4-differences/