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" %>

Signature

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

Signature

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: 

Signature

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.

 

Signature

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>
Signature

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

Signature

Recently I came across a situation when I had to encrypt certain piece of data into ASP.NET and then read the same encrypted data for decryption into Classic ASP. Spent several hours and could not understand why the same encryption/decryption method used in both are producing entirely two different characters. After doing some tests, finally concluded that it is an issue of character Encoding.  By default ASP.NET produces data in UTF8 Charset and UTF8Encoding Content Encoding . Whereas Classic ASP defaults to null Charset. After all research and headache following one line of code fixed this issue and both started talking to each other.

In ASP.NET Page, on page Load event add following line

Response.ContentEncoding = Encoding.Default

This default value shows as SBCSCodePageEncoding, not sure if that is showing because of my environment or configuration settings but it fixed my issue.

Signature

REST, or Representational State Transfer, is a type of Web service that is rapidly gaining in popularity. So you might ask yourself what the difference is between RESTful services and custom Web services, and why you might choose one type over the other. The key difference between the two types is that REST services are resource-centric while custom services are operation-centric. With REST, you divide your data into resources, give each resource a URL, and implement standard operations on those resources that allow creation, retrieval, update, and deletion (CRUD). With custom services, you can implement any arbitrary method, which means that the focus is on the operations rather than the resources, and those operations can be tailored to the specific needs of your application.


Some services fit very naturally into the REST model—usually when the resources are obvious and much of the service involves management of those resources. Exchange Server, for instance, has a REST API for organizing e-mail and calendar items. Similarly, there are photo-sharing Web sites on the Internet that expose REST APIs. In other cases, the services less clearly match REST operations, but can still be made to fit. Sending e-mail, for example, can be accomplished by adding a resource to an outbox folder. This is not the way you would most naturally think about sending e-mail, but it is not too much of a stretch.


In other cases, though, REST operations just do not fit well. Creating a resource in order to initiate a workflow that drives monthly payroll check printing, for example, would be much less natural than having a specific method for that purpose.


If you can fit your service into the constraints of REST, doing so will buy you a lot of advantages. ADO.NET Data Services in combination with the Entity Framework makes it easy to create both RESTful services and clients to work with them. The framework can provide more functionality to RESTful services automatically because the services are constrained to follow a specific pattern. In addition, RESTful services have a very broad reach because they are so simple and interoperable. They work especially well when you do not know in advance who the clients might be. Finally, REST can be made to scale to handle very large volumes of operations.


For many applications, the constraints of REST are just too much. Sometimes the domain does not divide clearly into a single pattern of resources or the operations involve multiple resources at once. Sometimes the user actions and business logic around them do not map well to RESTful operations, or more precise control is required than can fit into those operations. In these cases, custom services are the way to go.


You can always build an application that has a mix of REST and custom services. Often the ideal solution for an application is a mixture of both.

Source: MSDN Magazine Jun 2009

Signature

As you know, Web.Config and App.Config files are like plain readable XML files. However, it contains sensitive information such as Connection Strings, Impersonation, App Setting Keys and their values. At some point you may need to secure these sections. .NET Framework allows to make your life simple, by just executing few commands on Command Prompt or few clicks using a Enterprise Library Configuration tool, you can achieve the desired result. There is only one basic requirement you should be able to at least remotely login to the Server where you would like to make these thing. Following are few simple steps to secure web.config or app.config.

File: Web.Config using Command Prompt

1. Go to Command Prompt

2. Change Directory to C:\Windows\Microsoft.NET\Framework\v2.0.50727

3. To Encrypt a Section in Web.Cofig -  type following - 

         aspnet_regiis -pef "<CONFIG_SECTION" "<PHYSICAL_PATH>"

        i.e. aspnet_regiis -pef "connectionStrings" “C:\Inetpub\wwwroot\TestWebSite"

        i.e. aspnet_regiis -pef "system.web/identity" “C:\Inetpub\wwwroot\TestWebSite"

4. Go to your website root directory, and create a File AppUser.Aspx and type the following line save it.                

        a. <%@ Page Language="VB" %>

            <% Response.Write( System.Security.Principal.WindowsIdentity.GetCurrent().Name ) %>

        b. Now, open your browser and call this page, this will show you a DOMAIN/UserName under which you website is running. Take a note of it. Now go back to command prompt.

5. Run the following command on command prompt to allow Permission to Users e.g. "NT Authority\Network Service", and the User Your Web Site is using it. run following command

              aspnet_regiis -pa "NetFrameworkConfigurationKey" "NT Authority\Network Service"       

              aspnet_regiis -pa "NetFrameworkConfigurationKey" "DOMAIN/USERNAME"

6. After successful completion of command, remove the AppUser.Aspx file.

7. If you ever want to decrypt the section you encrypted, use following command

              aspnet_regiis -pdf  "<CONFIG_SECTION" "<PHYSICAL_PATH>"

You do not need to make any code change in your application for encryption or decryption, .NET automatically does it for you. 

For more details you can visit http://msdn.microsoft.com/en-us/library/ms998283.aspx

File: App.Config using Command Prompt

So what would you do to encrypt the same in case of App.Config, above command only work for Web.Config. Here is a trick – Copy the contents of App.Config into Web.Config file, or you can rename as web.config. Follow the same instructions as above, and after encryption, copy the file contents or rename it back to App.Config.

Easy Way To Encrypt/Decrypt - Web.Config/App.Config

If you have downloaded and Installed Microsoft Enterprise Library Configuration Tool, just open Web.Config or App.Config and select the section you want to encrypt, Go into Protection à Protection Provider and choose a provider you want (default is none) and save the file, you are done.  BUT,  you may have to follow #4 - #6, if .NET is not able to read encrypted section.

Signature

If you are using .NET 2.0 or higher Framework and System.Transactions Namespace to handle your transactions, chances are you may come across this error. In my application, I was using ADO.NET transaction, in stored procedure SQL Server transaction and now we decided to use a powerful transaction handler using .NET framework. If you are writing everything fresh, most likely you won’t like to mix different type of transaction handling mechanism. But what if you already have existing code and do not want to change, what to do. I tried to mix all the three kind of transactions, but it resulted in errors. Sometime, they timeout, sometime it just hanged and sometime it produced Microsoft Transaction Coordinator (MSDTC) error. So, how to resolve this problem? After spending several hours I found that one must follow following basic steps.


 

1. Import System.Transactions namespace in the class where you want to use distributed transaction

2. Make sure that this transaction mode is the root or mothers for all other type of transactions

3. Now you can add different type of transactions, it can be ADO.Net transaction, SQL Transaction or another child transaction using System.Transaction Namespace

4. After doing the first 3 steps, make sure you configure your machines with following options, otherwise you will come across the above error.

To fully enable MS DTC:

1. In Control Panel, open Administrative Tools, and then double-click Component Services.

2. In the left pane of Console Root, click Component Services, and then expand Computers.

3. Right-click My Computer, and then click Properties.

4. On the MSDTC tab, click Security Configuration.

5. Under Security Settings, select all of the check boxes.

6. Verify that the DTC Logon Account name is set to NT AUTHORITY\NetworkService.

 

 

 

If MSDTC still does not work then

1. Install MSDTC by going on command prompt and run following command: msdtc –install

2. After that you'll need to actually start the service

3. Make sure to go back in component services and follow the above step to enable MS DTC.

4. Windows Firewall –Make sure C:\Windows\System32\MSDTC.exe is added in Exceptions list of Windows Firewall

 

 

 

       If MSDTC still does not work, reboot the machine.

If you MSDTC still does not work, download the following tool and you can see where it is failing

                  http://www.microsoft.com/downloads/details.aspx?familyid=5E325025-4DCD-4658-A549-1D549AC17644&displaylang=en 

                  You need to make sure that these options are enabled on all participating machines (Web Server, App Server, SQL Server etc)


Example:
 
                 Public Sub MainMethod()
                       Dim tranOptions As New TransactionOptions()
                       tranOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted
                       tranOptions.Timeout = New TimeSpan(0, 2, 0)
                       Using topMostScope As New TransactionScope(TransactionScopeOption.Required, tranOptions)
 
                            Call Method1UsingAdo_Net_Transaction()
                            Call Method2UsingSql_Server_Transaction()
                            Call Method3UsingChildTranScope()
 
                            topMostScope.Complete()
                       End Using
                End Sub
 
 

 

 

Signature

About Me

Me Hello,my name is Vishwa Mohan Kumar.
I am a Software Architect. This blog is result of my experiments.

Flickr Photos

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Recent Comments

Comment RSS

Live Traffic Feed