Saturday, August 28, 2010

Visual Studio Team Foundation Server

FOR VS 2012

First Check the existing workspaces for some "computername" can be queried with this TFS command:

tf.exe workspaces /computer:computername /owner:* /format:detailed /server:serveraddress

You get a list of all workspaces, with the existing mappings. It is the workspace name (behind "Workspace:") and the owner that you need in order to delete the workspace.

Now run this TFS command to remove the workspace "workspacename" for owner "owner":

tf.exe workspace /delete workspacename;owner /server:serveraddress

 

 

FOR VS 2010

Recently came across some issues while upgrading from Visual Source Safe (VSS) 2005 to Visual Studio Team Foundation Server (VSTFS) 2010. Found some workarounds and limitations. I am assuming you are using Visual Studio 2010

On TFS Server Machine

1. If your projects are using .NET framework 3.5 or higher, make sure the respective .NET Framework is installed on the Server

2. Make sure that output folder where TFS will build the projects have write permission

3. If you are using Enterprise Library or any third party tool, they are also installed on the Server.

4.  You may get an error during Build of the project about “Microsoft.WebApplication.targets“, to resolve this issue C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets from local (development) machine which had VS 2010 already installed.

5. If you have some components or dlls for which you do not any installer or they can not be installed in GAC but they are referred in your projects, One way to fix this issue is to copy that dll in to into C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0

Some informative links

http://msdn.microsoft.com/en-us/library/bb668981.aspx

http://www.attrice.info/cm/tfs/

http://blogs.microsoft.co.il/blogs/eranruso/archive/2010/01/25/how-to-configure-build-services-to-a-specific-tfs-2010-collection.aspx

 

On Development Machine

How to Find your workspaces?

Go to Visual Studio Command Prompt, and use one of the following commands

C:\tf works

In order to delete any of the workspace, you can use following command

C:\>tf workspace /delete /server:BUILDSERVER WORKSPACENAME;OWNERNAMEpaces /owner:*

Important: Make sure that the TFS still has the same collectionname and path. If you or administrator deleted a collection directly from TFS you will not be able to delete or clear your old workspace. Microsoft should have provided a way to address this problem.

How to Delete a Collection?

1. Go to Command Prompt

2. Go to C:\Program Files\Microsoft Team Foundation Server 2010\Tools

3. Type C:\TFSConfig Collection /delete /collectionName:[COLLECTION NAME]"

Note: Delete does not delete from TFS, but just marks the item as deleted, in order to fully delete it, you will have to destroy it

 

How to Destroy?

1. Go to Command Prompt the

2. Go to C:\Program Files\Microsoft Team Foundation Server 2010\Tools

3. tf destroy $/<PATH_OF_THE_FOLDER_OR_OBJECT> /collection:[COLLECTION_NAME_WITH_HTTP_ADDRESS]

For more info visit following link

http://msdn.microsoft.com/en-us/library/bb386005.aspx

 

Friday, April 30, 2010

Error: A potentially dangerous Request.Form value

Just came across this error when I upgraded my Blog from .NET 3.5 to .NET 4.0  - A potentially dangerous Request.Form value was detected from the client .....

Ok, so first I thought may be I missed the Page directives. Checked that and it was there, played around with different settings and configurations, but nothing helped.

But finally the solution was revealed:) and it was very simple as you can see below. In .NET 4.0, Microsoft added another parameter “requestValidationMode” in httpruntime which will stop this error. So open your web.config and add following.

 

Code Snippet
  1. <system.web>
  2.  
  3.      <httpRuntimerequestValidationMode="2.0"/>
  4.  
  5. </system.web>

 

 

Remember if your website is still using .NET 2.0 and getting the same error, make sure that the page directive “ValidateRequest” is set to false.

Code Snippet
  1. <%@ Page Language="C#" MasterPageFile="masterPage.master" AutoEventWireup="true" CodeFile="TestPage.aspx.cs" Inherits="TestPage" ValidateRequest="False" %>

Wednesday, February 17, 2010

Convert Number or Money in Words

Many times we come across the situation of converting a number spelled into words or a monetary value spelled into dollars & cents (or equivalent currency).  I found the following code over internet and changed to fit my need (as we all do) and generalized in such a way that it can be used for either just convert a number to words or monetary value to words. You can add different country code if needed.

 

 1: Public Overloads Shared Function ConvertNumberInWords(ByVal value As String) As String
 2:     Return ConvertNumberInWords(value, "")
 3: End Function
 4:  
 5: Public Overloads Shared Function ConvertNumberInWords(ByVal value As String, ByVal countryCode As String) As String
 6:     Dim majorCurrency As String = String.Empty
 7:     Dim minorCurrency As String = String.Empty
 8:  
 9:     Select Case countryCode.ToUpper()
 10:         Case "GBR"
 11:             majorCurrency = "Pound"
 12:             minorCurrency = "Pence"
 13:         Case "USA", "CAN"
 14:             majorCurrency = "Dollar"
 15:             minorCurrency = "Cent"
 16:     End Select
 17:  
 18:     value = value.Replace(",", "").Replace("$", "")
 19:     value = value.TrimStart(CChar("0"))
 20:  
 21:     Dim decimalCount As Int32 = 0
 22:     For x As Int32 = 0 To value.Length - 1
 23:         If value(x).ToString = "." Then
 24:             decimalCount += 1
 25:             If decimalCount > 1 Then Throw New ArgumentException("Only monetary values are accepted")
 26:         End If
 27:  
 28:         If Not (Char.IsDigit(value(x)) Or value(x).ToString = ".") And Not (x = 0 And value(x).ToString = "-") Then
 29:             Throw New ArgumentException("Only monetary values are accepted")
 30:         End If
 31:     Next
 32:  
 33:     Dim returnValue As String = ""
 34:     Dim parts() As String = value.Split(CChar("."))
 35:  
 36:     If parts.Length > 1 Then
 37:         parts(1) = parts(1).Substring(0, 2).ToCharArray 'Truncates -- doesn't round.   
 38:     End If
 39:  
 40:     Dim IsNegative As Boolean = parts(0).Contains("-")
 41:     If parts(0).Replace("-", "").Length > 18 Then
 42:         Throw New ArgumentException("Maximum value is $999,999,999,999,999,999.99")
 43:     End If
 44:  
 45:     If IsNegative Then
 46:         parts(0) = parts(0).Replace("-", "")
 47:         returnValue &= "Minus "
 48:     End If
 49:  
 50:     If parts(0).Length > 15 Then
 51:         returnValue &= HundredsText(parts(0).PadLeft(18, CChar("0")).Substring(0, 3)) & "Quadrillion "
 52:         returnValue &= HundredsText(parts(0).PadLeft(18, CChar("0")).Substring(3, 3)) & "Trillion "
 53:         returnValue &= HundredsText(parts(0).PadLeft(18, CChar("0")).Substring(6, 3)) & "Billion "
 54:         returnValue &= HundredsText(parts(0).PadLeft(18, CChar("0")).Substring(9, 3)) & "Million "
 55:         returnValue &= HundredsText(parts(0).PadLeft(18, CChar("0")).Substring(12, 3)) & "Thousand "
 56:     ElseIf parts(0).Length > 12 Then
 57:         returnValue &= HundredsText(parts(0).PadLeft(15, CChar("0")).Substring(0, 3)) & "Trillion "
 58:         returnValue &= HundredsText(parts(0).PadLeft(15, CChar("0")).Substring(3, 3)) & "Billion "
 59:         returnValue &= HundredsText(parts(0).PadLeft(15, CChar("0")).Substring(6, 3)) & "Million "
 60:         returnValue &= HundredsText(parts(0).PadLeft(15, CChar("0")).Substring(9, 3)) & "Thousand "
 61:     ElseIf parts(0).Length > 9 Then
 62:         returnValue &= HundredsText(parts(0).PadLeft(12, CChar("0")).Substring(0, 3)) & "Billion "
 63:         returnValue &= HundredsText(parts(0).PadLeft(12, CChar("0")).Substring(3, 3)) & "Million "
 64:         returnValue &= HundredsText(parts(0).PadLeft(12, CChar("0")).Substring(6, 3)) & "Thousand "
 65:     ElseIf parts(0).Length > 6 Then
 66:         returnValue &= HundredsText(parts(0).PadLeft(9, CChar("0")).Substring(0, 3)) & "Million "
 67:         returnValue &= HundredsText(parts(0).PadLeft(9, CChar("0")).Substring(3, 3)) & "Thousand "
 68:     ElseIf parts(0).Length > 3 Then
 69:         returnValue &= HundredsText(parts(0).PadLeft(6, CChar("0")).Substring(0, 3)) & "Thousand "
 70:     End If
 71:  
 72:     Dim hundreds As String = parts(0).PadLeft(3, CChar("0"))
 73:     hundreds = hundreds.Substring(hundreds.Length - 3, 3)
 74:  
 75:     If CInt(hundreds) <> 0 Then
 76:         If CInt(hundreds) < 100 AndAlso parts.Length > 1 Then returnValue &= " "
 77:         returnValue &= HundredsText(hundreds) & majorCurrency
 78:         If CInt(hundreds) <> 1 Then returnValue &= IIf(majorCurrency.Length > 0, majorCurrency & "s", "").ToString()
 79:         If parts.Length > 1 AndAlso CInt(parts(1)) <> 0 Then returnValue &= " and "
 80:     Else
 81:         returnValue &= IIf(majorCurrency.Length > 0, " No " & majorCurrency & "s", "").ToString()
 82:         If parts.Length > 1 AndAlso CInt(parts(1)) <> 0 Then returnValue &= " and "
 83:     End If
 84:  
 85:     If parts.Length = 2 Then
 86:         If CInt(parts(1)) <> 0 Then
 87:             returnValue &= HundredsText(parts(1).PadLeft(3, CChar("0")))
 88:             returnValue &= minorCurrency
 89:             If CInt(parts(1)) <> 1 Then returnValue &= IIf(minorCurrency.Length > 0, "s", "").ToString()
 90:         End If
 91:     End If
 92:  
 93:     Return returnValue
 94:  
 95: End Function
 96:  
 97: Private Shared Function HundredsText(ByVal value As String) As String
 98:     Dim Tens As String() = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}
 99:     Dim Ones As String() = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}
 100:  
 101:     Dim returnValue As String = ""
 102:     Dim IsSingleDigit As Boolean = True
 103:  
 104:     If CInt(value(0).ToString) <> 0 Then
 105:         returnValue &= Ones(CInt(value(0).ToString) - 1) & " Hundred "
 106:         IsSingleDigit = False
 107:     End If
 108:  
 109:     If CInt(value(1).ToString) > 1 Then
 110:         returnValue &= Tens(CInt(value(1).ToString) - 1) & " "
 111:         If CInt(value(2).ToString) <> 0 Then
 112:             returnValue &= Ones(CInt(value(2).ToString) - 1) & " "
 113:         End If
 114:     ElseIf CInt(value(1).ToString) = 1 Then
 115:         returnValue &= Ones(CInt(value(1).ToString & value(2).ToString) - 1) & " "
 116:     Else
 117:         If CInt(value(2).ToString) <> 0 Then
 118:             If Not IsSingleDigit Then
 119:                 returnValue &= "and "
 120:             End If
 121:             returnValue &= Ones(CInt(value(2).ToString) - 1) & " "
 122:         End If
 123:     End If
 124:  
 125:     Return returnValue
 126:  
 127: End Function

 

Wednesday, September 23, 2009

What India gave to the World?

Just looking back and thinking as what India has given to the World. Looked around on internet and summarized some of the great contributions. Interestingly all of these contributions are ancient.  Links provide more information on each contribution. Jai ho…

1. Number Zero was invented by Aryabhatta(476-550)

2. Number System developed by Bhaskara I (600-680) based on Aryabhatta work during 7th Century and later popularized by Arabs.

3. The value of "pi" was first calculated by Baudhayana (1114-1185) and he explained the concept of what is known as the Pythagorean Theorem. He discovered this long before the European mathematicians.

4. The World's first University was established in Takshila in 7th Century of BC. More than 10,500 students from all over the world studies more than 60 subjects. This place is now located in Pakistan after India’s Partition.

5. The World’s first residential University was established in Nalanda. It had dormitories for students. It accommodated over 10,000 students and 2,000 teachers. The University of Nalanda was built in 427, it was one of the greatest achievements of ancient India in the field of education.

6. Indians invented the Science of Astronomy during the Gupta period. The book Surya Siddhanta is treated as major reference book of Indian Astronomy written during Gupta Period (280 – 550). Through this book Aryabhatta was first to hold that the earth is a sphere that rotates around its own axis. He also discovered the causes of solar and lunar eclipses, and methods to predict their occurrence.

7. In 5th Century, Bhaskaracharya calculated the time taken by the earth to orbit the sun hundreds of years before it was calculated in west. Time taken by earth to orbit the Sun: 365.258756484 days.

8. Ayurveda (5000 BC during Vedic period) is perhaps the most important contribution to medicine that India has made. It means 'way of life' in Sanskrit. For centuries, Ayurveda has provided diagnoses on curing diseases, through the use of natural substances such as plants, herbs and metals. Today, the magic of Ayurvedic healing can be found in ready-made, packaged bottles the world over.

9. According to the Gemological Institute of America, up until 1896, India was the only source for Diamonds to the world.

10. This ancient text on sexual love- Kama Sutra, was written by Vatsyayana in the mid-4th century. The text was made accessible to the English-speaking world by the orientalist Sir Richard Burton.

11. Patanjali gave the knowledge of Yoga in 150 BCE, it helps to keep a healthy body and sound mind.

12. Swastika, was first found in the Indus Vally Civilization, the difference between Indian Swastika and misused Nazi Swastika is explained in another article I wrote in the past.

13. Guru – literal meaning of Guru is Master, but it is more treated in sense of a spiritual master, and a guide. Now Guru word has become famous all around the world.

14. Chess was originated in India during Gupta empire (280 – 550)

15. Indian Martial Arts – More than 5000 BCE, Martial arts was mentioned and used in Mahabharta. Written evidence is found dated 2BCE

Some other contributions include Indian Spices and Herbs for taste, Bindi, Nose Ring and Salwar-Kameez for fashion or decoration.

Monday, August 17, 2009

Implementing WCF Service Part 6 – Using Fault @ Client

Ok, so you have developed a nice WCF Service with proper implementation of custom fault exception handling, now you want to call this service in a web application or other client application and catch the fault exception in your client code. For simplicity I am using a web page, the following code is self explanatory.

  1: Protected Sub btnGetCustomers_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGetCustomers.Click  
  2:   
  3:         Using wcfSrv As CustomerWcfService.CustomerServiceClient = New CustomerWcfService.CustomerServiceClient("WSHttpBinding_ICustomerService")  
  4:             Try  
  5:                 Dim custArr() As CustomerWcfService.Customer  
  6:                 custArr = wcfSrv.GetCustomers()  
  7:                 For Each cust As CustomerWcfService.Customer In custArr  
  8:                     Response.Write("ID: " & cust.ID.ToString & " Name: " & cust.Name & "<br/>")  
  9:                 Next  
 10:                 lblStatus.Text = "No of Customer Records found: " & custArr.Length.ToString  
 11:   
 12:                 'Custom Fault Exception Response from Service  
 13:             Catch ex As ServiceModel.FaultException(Of CustomerWcfService.ErrorResponse)  
 14:                 lblStatus.Text = "Code:" & ex.Detail.Code.ToString() & " Messgage:" & ex.Detail.Message & " Details:" & ex.Detail.Details  
 15:                 wcfSrv.Abort()  
 16:   
 17:                 'General Fault Exception  
 18:             Catch ex As ServiceModel.FaultException  
 19:                 lblStatus.Text = ex.ToString()  
 20:                 wcfSrv.Abort()   
 21:   
 22:                 'General Exception  
 23:             Catch exp As System.Exception  
 24:                 lblStatus.Text = "Error:" & exp.ToString()  
 25:                 wcfSrv.Abort()  
 26:   
 27:             Finally  
 28:                 wcfSrv.Close()  
 29:             End Try  
 30:   
 31:         End Using  
 32:   
 33:     End Sub  
 34: 

Sunday, August 09, 2009

Convert Array to Generic List

You can happily use .NET Generics in WCF Services. But when you will get the proxy of the respective service, these generics will get converted into Array, even you are using .NET to develop the client application. So now the question is how I should get back from Array to Generic List again.

VB.NET

Simple Example

  Dim someArray() As Integer = {1, 2, 3, 4, 5}

        Dim genericList As New List(Of Integer)

        genericList.AddRange(someArray)

 

Web Service Example

  Dim resp As New MyLookupService.GetCountriesResponse

        Dim reqs As New MyLookupService.GetCountriesRequest

        Dim listData As New List(Of MyLookupService.CountryData)

        Dim arrData As Array

 

        reqs.LoginInfo = loginReq

        resp = srvObj.GetCountries(reqs)

        arrData = resp.CountriesInfo

        listData.AddRange(arrData)

 

        Me.gvwCountry.DataSource = listData

        Me.gvwCountry.DataBind()

 

Alternate Option

        When you Add Service Reference, click on "Advanced..." button on bottom left and Choose Collection Type from Dropdown as "System.Collections.Generic.List" and you are all set. No need to use array.

 

Monday, August 03, 2009

WCF Service Error: The maximum message size quota ...

If you are using a WCF (Web) Service in client application and dealing with large data, at some point you may come across an error message:

{"The maximum message size quota for incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element."}

 

Solutions:

Open your web.config or App.Config file at client and change the values in your bindings. Change the value of following configurations from 65536 (default) to 2147483647. That means it will allow up to 2GB.

<wsHttpBinding>  
    <binding name="WSHttpBinding_IMyService" closeTimeout="00:01:00"  
     openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"  
     bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"  
     maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text"  
     textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">  
     <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"  
      maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />  
     <reliableSession ordered="true" inactivityTimeout="00:10:00"  
      enabled="false" />  
     <security mode="Message">  
      <transport clientCredentialType="Windows" proxyCredentialType="None"  
       realm="" />  
      <message clientCredentialType="Windows" negotiateServiceCredential="true"  
       algorithmSuite="Default" establishSecurityContext="true" />  
     </security>  
    </binding>  
   </wsHttpBinding>  

Thursday, July 30, 2009

Pros and Cons of Data Transfer Objects

Nearly every developer and architect would agree on the following, though relatively loose, definition of the business logic layer (BLL) of a software application: The BLL is the part of the software application that deals with the performance of business-related tasks. Code in the BLL operates on data that attempts to model entities in the problem domain—invoices, customers, orders, and the like. Operations in the BLL attempt to model business processes.

Under the hood of this largely accepted definition lie a number of key details that are left undefined and unspecified. Design patterns exist to help architects and code designers transform loose definitions into blueprints. In general, BLL design patterns have a slightly different focus. They model operations and data and often serve as the starting point for designing the BLL.

In this article, after a brief refresher on procedural and object-based patterns for organizing the BLL, I'll focus on one side of the problem—data transfer objects—that if not effectively addressed at the architecture level, may have a deep impact on the development of the project.

Procedural Patterns for BLL

When it comes to designing the BLL, you can start from the use-cases that have emerged during the analysis phase. Typically, you end up coding one method for each required interaction between the user and the system. Each interaction forms a logical transaction that includes all due steps—from collecting input to performing the task, and from database access to refreshing the user interface. This approach is referred to as the Transaction Script (TS) pattern.

In TS, you focus on the required actions and don't really build a conceptual model of the domain as the gravitational center of the application.

To move data around, you can use any container objects that may suit you. In the Microsoft .NET space, this mostly means using ADO.NET data containers such as DataSets and DataTables. These objects are a type of super-array object, with some search, indexing, and filtering capabilities. In addition, DataSets and DataTables can be easily serialized across tiers and even persisted locally to enable offline scenarios.

The TS pattern doesn't mandate a particular model for data representation (and doesn't prevent any either). Typically, operations are grouped as static methods in one or more entry-point classes. Alternatively, operations can be implemented as commands in a Command pattern approach. Organization of data access is left to the developer and typically results in chunks of ADO.NET code.

The TS pattern is fairly simple to set up; at the same time, it obviously doesn't scale that well, as the complexity of the application grows. In the .NET space, another pattern has gained wide acceptance over the years: the Table Module pattern. In a nutshell, the Table Module pattern suggests a database-centric vision of the BLL. It requires you to create a business component for each database table. Known as the table module class, the business component packages the data and behavior together.

In the Table Module pattern, the BLL is broken into a set of coarse-grained components, each representing an entire database table. Being strictly table-oriented, the Table Module pattern lends itself to using recordset-like data structures for passing data around. ADO.NET data containers or, better yet, customized and typed version of ADO.NET containers are the natural choice.

As the need for a more conceptual view of the problem domain arises, the BLL patterns that have worked for years in the .NET space need to evolve some more. Architects tend to build an entity/relationship model that represents the problem domain and then look at technologies like LINQ-to-SQL and Entity Framework as concrete tools to help.

Object-Based Patterns for BLL

The Table Module pattern is based on objects, but it's not really an object-based pattern for modeling the business logic. It does have objects, but they are objects representing tables, not objects representing the domain of the problem.

In an object-oriented design, the business logic identifies entities and expresses all of the allowed and required interactions between entities. In the end, the application is viewed as a set of interrelated and interoperating objects. The set of objects mapping to entities, plus some special objects performing calculations form the domain model. (In the Entity Framework, you express the domain model using the Entity Data Model [EDM].)

There are various levels of complexity in a domain model that suggest different patterns—typically the Active Record pattern or the Domain Model pattern. A good measure of this complexity is the gap between the entity model you have in mind and the relational data model you intend to create to store data. A simple domain model is one in which your entities map closely to tables in the data model. A not-so-simple model requires mapping to load and save domain objects to a relational database.

The Active Record pattern is an ideal choice when you need a simple domain model; otherwise, when it is preferable to devise entities and relationships regardless of any database notion, the Domain Model pattern is the way to go.

The Active Record pattern is similar to what you get from a LINQ-to-SQL object model (and the defaultgenerated model with the Entity Designer in the Entity Framework Version 1.0). Starting from an existing database, you create objects that map a row in a database table. The object will have one property for each table column of the same type and with the same constraints. The original formulation of the Active Record pattern recommends that each object makes itself responsible for its own persistence. This means that each entity class should include methods such as Save and Load. Neither LINQ-to-SQL nor Entity Framework does this though, as both delegate persistence to an integrated O/RM infrastructure that acts as the real data access layer, as shown in Figure 1.

Figure 1 A Layered Architecture – the Domain Model Pattern Used for the BLL

The Service Layer

In Figure 1, you see a logical section of the BLL named as the "service layer" sitting in between the presentation layer and the layer that takes care of persistence. In a nutshell, the service layer defines an interface for the presentation layer to trigger predefined system actions. The service layer decouples presentation and business logic and represents the façade for the presentation logic to call into the BLL. The service layer does its own job, regardless of how the business logic is organized internally.

As a .NET developer, you are quite familiar with event handlers in Web or Windows forms. The canonical Button1_Click method belongs to the presentation layer and expresses the system's behavior after the user has clicked a given button. The system's behavior—more exactly, the use case you're implementing—may require some interaction with BLL components. Typically, you need to instantiate the BLL component and then script it. The code necessary to script the component may be as simple as calling the constructor and perhaps one method. More often, though, such code is fairly rich with branches, and may need to call into multiple objects or wait for a response. Most developers refer to this code as application logic. Therefore, the service layer is the place in the BLL where you store application logic, while keeping it distinct and separate from domain logic. The domain logic is any logic you fold into the classes that represent domain entities.

In Figure 1, the service layer and domain model blocks are distinct pieces of the BLL, although they likely belong to different assemblies. The service layer knows the domain model and references the corresponding assembly. The service layer assembly, instead, is referenced from the presentation layer and represents the only point of contact between any presentation layer (be it Windows, Web, Silverlight, or mobile) and the BLL. Figure 2 shows the graph of references that connect the various actors. The service layer is a sort of mediator between the presentation layer and the rest of the BLL. As such, it keeps them neatly separated but loosely coupled so that they are perfectly able to communicate. In Figure 2, the presentation layer doesn't hold any reference to the domain model assembly. This is a key design choice for most layered solutions.

Figure 2 Graph of References Between Participant Actors

Introducing Data Transfer Objects

When you have a domain-based vision of the application, you can't help but look seriously into data transfer objects. No multitier solution based on LINQ to SQL or Entity Framework is immune from this design issue. The question is, how would you move data to and from the presentation layer? Put another way, should the presentation layer hold a reference to the domain model assembly? (In an Entity Framework scenario, the domain model assembly is just the DLL created out of the EDMX file.)

Ideally, the design should look like Figure 3, where made-to-measure objects are used to pass data from the presentation layer to the service layer, and back. These ad hoc container objects take the name of Data Transfer Objects (DTOs).

Figure 3 Communication Between Presentation Layer and Service Layer

A DTO is nothing more than a container class that exposes properties but no methods. A DTO is helpful whenever you need to group values in ad hoc structures for passing data around.

From a pure design perspective, DTOs are a solution really close to perfection. DTOs help to further decouple presentation from the service layer and the domain model. When DTOs are used, the presentation layer and the service layer share data contracts rather than classes. A data contract is essentially a neutral representation of the data that interacting components exchange. The data contract describes the data a component receives, but it is not a system-specific class, like an entity. At the end of the day, a data contract is a class, but it is more like a helper class specifically created for a particular service method.

A layer of DTOs isolates the domain model from the presentation, resulting in both loose coupling and optimized data transfer.

Other Benefits of DTOs

The adoption of data contracts adds a good deal of flexibility to the service layer and subsequently to the design of the entire application. For example, if DTOs are used, a change in the requirements that forces a move to a different amount of data doesn't have any impact on the service layer or even the domain. You modify the DTO class involved by adding a new property, but leave the overall interface of the service layer intact.

It should be noted that a change in the presentation likely means a change in one of the use cases and therefore in the application logic. Because the service layer renders the application logic, in this context a change in the service layer interface is still acceptable. However, in my experience, repeated edits to the service layer interface may lead to the wrong conclusion that changes in the domain objects—the entities—may save you further edits in the service layer. This doesn't happen in well-disciplined teams or when developers have a deep understanding of the separation of roles that exists between the domain model, the service layer, and DTOs.

As Figure 4 shows, when DTOs are employed, you also need a DTO adapter layer to adapt one or more entity objects to a different interface as required by the use case. In doing so, you actually implement the "Adapter" pattern—one of the classic and most popular design patterns. The Adapter pattern essentially converts the interface of one class into another interface that a client expects.

Figure 4 DTO Adapters in the BLL

With reference to Figure 4, the adapter layer is responsible for reading an incoming instance of the OperationRequestDTO class and for creating and populating fresh instances of OperationResponseDTO.

When requirements change and force changes in a DTO-based service layer, all you need to do is update the public data contract of the DTO and adjust the corresponding DTO adapter.

The decoupling benefits of DTOs don't end here. In addition, to happily surviving changes in the presentation, you can enter changes to the entities in the domain model without impacting any clients you may have.

Any realistic domain model contains relationships, such as Customer-to-Orders and Order-to-Customer, that form a double link between Customer and Order entities. With DTOs, you also work around the problem of managing circular references during the serialization of entity objects. DTOs can be created to carry a flat stream of values that, if needed, serialize just fine across any boundaries. (I'll return to this point in a moment.)

Drawbacks of DTOs

From a pure design perspective, DTOs are a real benefit, but is this theoretical point confirmed by practice, too? As in many architecture open points, the answer is, it depends.

Having hundreds of entities in the domain model is definitely a good reason for considering alternatives to a pure DTO-based approach. In large projects with so many entities, DTOs add a remarkable level of (extra) complexity and work to do. In short, a pure, 100% DTO solution is often just a 100 percent painful solution.

While normally the complexity added to a solution by DTOs is measured with the cardinality of the domain model, the real number of needed DTOs can be more reliably determined looking at the use cases and the implementation of the service layer. A good formula for estimating how many DTOs you need is to look at the number of methods in the service layer. The real number can be smaller if you are able to reuse some DTOs across multiple service layer calls, or higher if your DTOs group some data using complex types.

In summary, the only argument against using DTOs is the additional work required to write and manage the number of resulting DTO classes. It is not, however, a simple matter of a programmer's laziness. In large projects, decoupling presentation from the service layer costs you hundreds of new classes.

It should also be noted that a DTO is not simply a lightweight copy of every entity you may have. Suppose that two distinct use cases require you to return a collection of orders—say, GetOrdersByCountry and GetOrdersByCustomer. Quite likely, the information to put in the "order" is different. You probably need more (or less) details in GetOrdersByCustomer than in GetOrdersByCountry. This means that distinct DTOs are necessary. For this reason, hundreds of entities are certainly a quick measure of complexity, but the real number of DTOs can be determined only by looking at use cases.

If DTOs are not always optimal, what would be a viable alternate approach?

The only alternative to using DTOs is to reference the domain model assembly from within the presentation layer. In this way though, you establish a tight coupling between layers. And tightly coupled layers may be an even worse problem.

Referencing Entities Directly

A first, not-so-obvious condition to enable the link of entities directly from the presentation layer is that it is acceptable for the presentation layer to receive data in the format of entity objects. Sometimes the presentation needs data formatted in a particular manner. A DTO adapter layer exists to just massage data as required by the client. If you don't use DTOs though, the burden of formatting data properly must be moved onto the presentation layer. In fact, the wrong place in which to format data for user interface purposes is the domain model itself.

Realistically, you can do without DTOs only if the presentation layer and the service layer are co-located in the same process. In this case, you can easily reference the entity assembly from within both layers without dealing with thorny issues such as remoting and data serialization. This consideration leads to another good question: Where should you fit the service layer?

If the client is a Web page, the service layer is preferably local to the Web server that hosts the page. In ASP.NET applications, the presentation layer is all in code-behind classes and lives side by side with the service layer in the same AppDomain. In such a scenario, every communication between the presentation layer and the service layer occurs in-process and objects can be shared with no further worries. ASP.NET applications are a good scenario where you can try a solution that doesn't use the additional layer of DTOs.

Technology-wise, you can implement the service layer via plain .NET objects or via local Windows Communication Foundation (WCF) services. If the application is successful, you can easily increase scalability by relocating the service layer to a separate application server.

If the client is a desktop application, then the service layer is typically deployed to a different tier and accessed remotely from the client. As long as both the client and remote server share the same .NET platform, you can use remoting techniques (or, better, WCF services) to implement communication and still use native entity objects on both ends. The WCF infrastructure will take care of marshaling data across tiers and pump it into copies of native entities. Also, in this case you can arrange an architecture that doesn't use DTOs. Things change significantly if the client and server platforms are incompatible. In this case, you have no chances to link the native objects and invoke them from the client; subsequently, you are in a pure service-oriented scenario and using DTOs is the only possibility.

The Middle Way

DTOs are the subject of an important design choice that affects the implementation of any communication between the presentation and the back end of the system.

If you employ DTOs, you keep the system loosely coupled and open toward a variety of clients. DTOs are the ideal choice, if you can afford it. DTOs add a significant programming overhead to any real-world system. This doesn't mean that DTOs should not be used, but they lead to a proliferation of classes that can really prefigure a maintenance nightmare in projects with a few hundred entity objects and even more use cases.

If you are at the same time a provider and consumer of the service layer, and if you have full control over the presentation, there might be benefits in referencing the entity model assembly from the presentation. In this way, all methods in the service layer are allowed to use entity classes as the data contracts of their signatures. The impact on design and coding is clearly quite softer.

Whether to use DTOs or not is not a point easy to generalize. To be effective, the final decision should always be made looking at the particulars of the project. In the end, a mixed approach is probably what you'll be doing most of the time. Personally, I tend to use entities as much as I can. This happens not because I'm against purity and clean design, but for a simpler matter of pragmatism. With an entity model that accounts for only 10 entities and a few use cases, using DTOs all the way through doesn't pose any significant problem. And you get neat design and low coupling. However, with hundreds of entities and use cases, the real number of classes to write, maintain, and test ominously approaches the order of thousands. Any possible reduction of complexity that fulfills requirements is more than welcome.

As an architect, however, you should always be on the alert to recognize signs indicating that the distance between the entity model and what the presentation expects is significant or impossible to cover. In this case, you should take the safer (and cleaner) route of DTOs.

Mixed Approach

Today's layered applications reserve a section of the BLL to the service layer. The service layer (also referred to as the application layer) contains the application logic; that is, the business rules and procedures that are specific to the application but not to the domain. A system with multiple front ends will expose a single piece of domain logic through entity classes, but then each front end will have an additional business layer specific to the use cases it supports. This is what is referred to as the service (or application) layer.

Triggered from the UI, the application logic scripts the entities and services in the business logic. In the service layer, you implement the use cases and expose each sequence of steps through a coarse-grained method for the presentation to call.

In the design of the service layer, you might want to apply a few best practices, embrace service-orientation, and share data contracts instead of entity classes. While this approach is ideal in theory, it often clashes with the real world, as it ends up adding too much overhead in projects with hundreds of entities and use cases.

It turns out that a mixed approach that uses data contracts only when using classes is not possible, is often the more acceptable solution. But as an architect, you must not make this decision lightly. Violating good design rules is allowed, as long as you know what you're doing.

 

Source :  MSDN Magazine, Aug 2009