Tuesday, August 2, 2011

General Design Recommendations for Applications and Services


When designing an application or service, you should consider the following
recommendations:

- Identify the kinds of components you will need in your application. Some
applications do not require certain components. For example, smaller applications
that don’t need to integrate with other services may not need business
workflows or service agents. Similarly, applications that have only one user
interface with a small number of elements may not require user process
components.

-  Design all components of a particular type to be as consistent as possible, using
one design model or a small set of design models. This helps to preserve the
predictability and maintainability of the design and implementation for all
teams. In some cases, it may be hard to maintain a logical design due to technical
environments (for example, if you are developing both ASP.NET- and Windowsbased
user interfaces); however, you should strive for consistency within each
environment. In some cases, you can use a base class for all components that
follow a similar pattern, such as data access logic components.

- Understand how components communicate with each other before choosing
physical distribution boundaries. Keep coupling low and cohesion high by
choosing coarse-grained, rather than chatty, interfaces for remote communication.


- Keep the format used for data exchange consistent within the application or
service. If you must mix data representation formats, keep the number of formats
low. For example, you may return data in a DataReader from data access logic
components to do fast rendering of data in Microsoft ASP.NET, but use DataSets
for consumption in business processes. However, be aware that mixing XML
strings, DataSets, serialized objects, DataReaders, and other formats in the same
application will make the application more difficult to develop, extend, and
maintain.

- Keep code that enforces policies (such as security, operational management, and
communication restrictions) abstracted as much as possible from the application
business logic. Try to rely on attributes, platform application programming
interfaces (APIs), or utility components that provide “single line of code” access
to functionality related to the policies, such as publishing exceptions, authorizing
users, and so on.


- Determine at the outset what kind of layering you want to enforce. In a strict
layering system, components in layer A cannot call components in layer C; they
always call components in layer B. In a more relaxed layering system, components
in a layer can call components in other layers that are not immediately
below it. In all cases, try to avoid upstream calls and dependencies, in which
layer C invokes layer B. You may choose to implement a relaxed layering to
16 Application Architecture for .NET: Designing Applications and Services
prevent cascading effects throughout all layers whenever a layer close to the
bottom changes, or to prevent having components that do nothing but forward
calls to layers underneath.

Monday, August 1, 2011

Loose coupling


Coupling refers to the degree of direct knowledge that one class has of another. This is not meant to be interpreted as encapsulation vs. non-encapsulation. It is not a reference to one class's knowledge of another class's attributes or implementation, but rather knowledge of that other class itself.
Strong coupling occurs when a dependent class contains a pointer directly to a concrete class which provides the required behavior. The dependency cannot be substituted, or its "signature" changed, without requiring a change to the dependent class. Loose coupling occurs when the dependent class contains a pointer only to an interface, which can then be implemented by one or many concrete classes. The dependent class's dependency is to a "contract" specified by the interface; a defined list of methods and/or properties that implementing classes must provide. Any class that implements the interface can thus satisfy the dependency of a dependent class without having to change the class. This allows for extensibility in software design; a new class implementing an interface can be written to replace a current dependency in some or all situations, without requiring a change to the dependent class; the new and old classes can be interchanged freely. Strong coupling does not allow this.
This is a UML diagram (created in IBM Rhapsody) illustrating an example of loose coupling between a dependent class and a set of concrete classes, which provide the required behavior:
Loose Coupling Example.JPG
For comparison, this diagram illustrates the alternative design with strong coupling between the dependent class and a provider:
Strong Coupling Example.JPG

[edit]Measuring data element coupling

The degree of the loose coupling can be measured by noting the number of changes in data elements that could occur in the sending or receiving systems and determining if the computers would still continue communicating correctly. These changes include items such as:
  1. adding new data elements to messages
  2. changing the order of data elements
  3. changing the names of data elements
  4. changing the structures of data elements
  5. omitting data elements

[edit]Methods for decreasing coupling

Loose coupling of interfaces can be dramatically enhanced when publishers of data transmit messages using a flexible file format such as XML to enable subscribers to publish clear definitions of how they subsequently use this data. For example, a subscriber could publish the collection of statements used to extract information from a publisher's messages by sharing the relevant XPath expressions used for data transformation. This would allow a responsible data publisher to test whether their subscriber's extraction methods would fail when a published format changes.
Loose coupling of services can be enhanced by reducing the information passed into a service to the key data. For example, a service that sends a letter is most reusable when just the customer identifier is passed and the customer address is obtained within the service. This decouples services because services do not need to be called in a specific order (e.g. GetCustomerAddress, SendLetter)
Note that loose coupling is not universally positive. If systems are de-coupled in time using Message-oriented middleware, it is difficult to also provide transactional integrity. Data replication across different systems provides loose coupling (in availability), but creates issues in maintaining synchronisation.

Tuesday, July 19, 2011

SerializerDictionary / DerializeDictionary

public static string SerializerDictionary(Dictionary<stringstring> serializeObject)
        {
            var xmlDoc = new XmlDocument();
            var xmlNode = xmlDoc.CreateNode(XmlNodeType.XmlDeclaration, """");
            xmlDoc.AppendChild(xmlNode);
            var xmlElements = xmlDoc.CreateElement("""Elements""");
            xmlDoc.AppendChild(xmlElements);
 
            foreach (var element in serializeObject)
            {
                var xmlElement = xmlDoc.CreateElement("""Element""");
                xmlElements.AppendChild(xmlElement);
 
                var xmlAttribute = xmlDoc.CreateAttribute(element.Key);
                xmlAttribute.Value = element.Value;
                xmlElement.Attributes.Append(xmlAttribute);
            }
 
            return xmlDoc.InnerXml;
        }
 
        public static Dictionary<stringstring> DerializeDictionary(string deserializeObject)
        {
            var deserializedDictionary = new Dictionary<stringstring>();
            var xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(deserializeObject);
            foreach (XmlElement element in xmlDoc.GetElementsByTagName("Element"))
            {
                deserializedDictionary.Add(element.Attributes[0].Name, element.Attributes[0].Value);
            }
            return null;
        }

Monday, May 2, 2011

Deep Clone in C#

Are you trying to do deep clone of the object in c#? Following one more way to clone object:

public object Clone( object item)
{
  if (item == null)
        return null;
 if (item is System.Runtime.Serialization.ExtensionDataObject)
        return null;
  if (item is Entity)
  {
      Entity source = item as Entity;
      Entity result = new Entity(source.LogicalName);
      object value;
      foreach (KeyValuePair<stringobject> pair in source.Attributes)
      {
  value = Clone( pair.Value);
 result.Attributes.Add(pair.Key, value);
      }
      return result;
   }
   else
   {
      if (item is ICloneable)
      {
         ICloneable toclone = item as ICloneable;
         object result = toclone.Clone();
         return result;
      }
      else if ( item is Guid)
      {
         return new Guid(item.ToString());                
      }
else
      {
        Type type = item.GetType();
         PropertyInfo[] properties = type.GetProperties();
         object result = null;
         try 
         {
             result = Activator.CreateInstance(type);
             object value;
             object clonedValue;
             foreach (PropertyInfo prop in properties)
            {
                 clonedValue = null;
                 if (prop.CanWrite)
                 {
                    value = prop.GetValue(item, null);
                    if (value != null)
                    {
                       if (prop.PropertyType == typeof(string))
                       {
                          string newstring = value.ToString();
                          clonedValue = newstring;
                  }
else if (prop.PropertyType.IsClass) 
                     {
                         clonedValue = Clone(value);
                }
if (clonedValue != null)
                   prop.SetValue(result, clonedValue, null);
                     else
                        prop.SetValue(result, value, null);
              }
      }
        }                                }  
        catch (Exception ex)
        {
        // Nothing to do
        }
        return result;
    }
 }

Thursday, March 31, 2011


Why create connection with ConnectionString that placed in Web.Config?
The answer very simple: because we will possible to change it without compile our application...and its very hopeful in PROD environment, isn't? :-)
Suppose, we have MyDataSet of typed DataSet with one table: 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using Dashboard.DAL;
 
namespace Dashboard.Dal
{    
    public class GetData
    {
        public static string ConnectionString { getset; }
 
        public static MyDataset GetData()
        {
            MyDataSet ds = new MyDataSet();
            ConnectionString = ConfigurationManager.ConnectionStrings["  
                                                      ConnectionString"].ToString();
            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                string storeProc = "DataBase.dbo.ProcedureName";
                SqlCommand command = new SqlCommand(storeProc, conn);
                command.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(command);
                conn.Open();
                da.Fill(ds.TypedDataSet);
            }
            return ds;
        }
    }
}
and file web.config:
<configuration>
  <connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=SQL_SERVER_NAME;Initial 
               Catalog=INIT_CATALOG_OF_DB;Persist Security Info=True;
               User ID=USER_NAME;Password=1234" />    
  </connectionStrings>
</configuration>

Good Connection...