Labels

Monday, November 29, 2010

Date Validation

Mostly found, data validation is slightly tricky. Checking against only Regurlar experession deos not serves the purpose. Here is the right apporach.
It involves two steps.

1.       Check for proper format – Using Regex -
2.       Chech for Date validity against Feburary Month (with and without Leap Year).

Here it is:



Step 1
string REGEXPR = @"^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$";

bool res = Regex.IsMatch(yourDate, REGEXPR);

Step2:
string date = "02/29/2009";
bool res = true;

try
{
    DateTime testDate = Convert.ToDateTime(date);
}
catch
{
   res = false;
}

MessageBox.Show(res.ToString()); // False

These steps certifies the date correctness.

Hope this helps..

Regards,
 Arun Manglick

Monday, November 22, 2010

n-Tier Architecture

Introduction

1.1         Purpose

This document describes the details of four tier implementation of the new architecture.

1.2         Scope

The scope of this document is demonstrating the four tier implementation of the new architecture.

1.3         Intendent Audience

This document is primarily targeted for the developers and architects working on the Veriphy applications. It provides a useful perspective to other stakeholders such as managers, and the customer.

 

Overall Description

1.4         Assumptions and Dependencies

1.5         Conceptual Overview

 

In this scenario, the solution is divided across four separate tiers, or physical machines.

 

·         The client workstation represents first tier that uses a browser application to interact with the Web server.

·         The Web server represents a second tier that contains the presentation layer, which is responsible for handling requests from the user and interacting with the business layer to implement the request.

·         The application server represents the third tier with service, business, and data access layers.

·         The fourth tier in this design is the database server.

 

1.6         Tiered Diagram

 

 

 

·         Browser interaction with the Web Server uses standard HTTP GET and POST requests.

·         The presentation layer uses a request-based / message-based protocol to interact with the service layer.

·         The Service Layer uses a Facade call to interact with the business layer.

·         Stand-alone ASP.NET Web application that supports basic CRUD operations.

·         Presentation and Business logic are distributed across physical boundaries.

·         DAL implementation will be implemented using LINQ.

·         The application uses data from an existing database schema.

·         Tables and views in the database define data structures used by the application

 

1.7         Another View

 

 

 

 

1.8         Detailed Tiered/Layered

 

 


The following is a summary of the patterns used by this scenario:

 

·         User interface processing is handled by a Request-Response pattern.

·         The user interface is composed of multiple controls, with some that can be bound to data elements.

·         An Http-Get request / Proxy is used to communicate between the presentation layer and service layer

·         The Data Transfer Object (DTO) pattern is used to package multiple data structures into one.

·         The Service Layer provides translation between internal and external data structures.

·         The Business Layer uses a façade pattern to support coarse-grained message-based operations.

·         Transactions and Business Logic are managed by objects in the business layer.

·         Business entities are defined using the Table Module pattern (LINQ).

·         The Table or Row Data Gateway pattern is used to provide a data access interface.

·         The Query Object pattern is used to support the generation of SQL queries.

 

1.9         Technical Details

 

Client Workstation

 

 

Target browser is Internet Explorer 6.x and higher

 

Browser will initiate the further flow.

 

 

                Web Server

 

 

ASP.NET Page Control

ASP.NET Page controls are used to define each page of the web application.

Standard ASP.NET page processing is used to handle control events.

 

Composite View

Page, server and user controls represent a Composite View.

Bound Data Control

Control that can be bound to a data structure, which is used to provide data displayed by the control.

Proxy

Provides a local interface used to interact with services on the application tier.

Adding a service reference will generate classes used to interact with the service. From a coding perspective the proxy provides a local interface that hides details related to interaction with the service.

 

Proxy is used when the presentation layer is required to communicate using WCF contracts.

 

 

                Application Server – Service Layer

 

 

Service Interface

The service layer can be Class Library Project or could be defined using WCF service, data, message, and fault contracts.

 

Operations exposed by the service are application scoped. For example, instead of providing multiple operations to return demographic information you would provide one operation that returns all data related to demographic information.

 

Data Transfer Object

Used to combine multiple data structures into a unified view that can be passed across physical and logical boundaries.

 

Entity Translator

Implement an object that transforms message data types to business types for requests and reverses the transformation for responses.

 

Classes that provide operations to translate between business entities and WCF data contracts.

 

Translate DTO to Business Entity Objects.

 

Public LINQ.DataManager.Order TranslateOrderToOrderDTO();

 

               

Application Server – Business Layer

 

 

Façade Interface

The business layer implements a façade with coarse grained operations.

Implement a unified interface to a set of operations to reduce coupling between systems.

An Interface type is used to define the façade interface.

The Façade acts as a boundary that catches all unhandled exceptions that may occur when processing business operations.

 

 

public interface BusinessFacade

    {

        Data.Order GetData();

        int SaveData(LINQ.Data.Order businessEntity);

        bool DeleteData(int businessEntityID);

    }

 

 

Business Process Objects

Business process objects are used to handle requests made to the business layer.

Business process objects allow you to Implement Business Rules And Provide Transaction support if required.

Business operations that need to be included in a transaction are combined in a single operation exposed by a business process object that implements the transaction script pattern.

 

 

public bool SaveData(LINQ.Data.Order businessEntity)

{

    string sError = string.Empty;

    bool success = false;

    int orderId = -1;

 

    try

    {

                BeginTransaction();

 

                if (orderId == -1)

                {

                    orderId = LINQ.DataManager.FindNextOrderID();

                    if (orderId == -1)

                    {

                                sError = "Failed to retrieve new Dealer ID. Rolling Back Transaction";

                                RollbackTransaction();

                                return success;

                    }

 

                    orderId = LINQ.DataManager.InsertOrder(businessEntity);

                    if( orderId == 0)

                    {

                                sError = "Failed to insert Dealer ID. Rolling Back Transaction";

                                RollbackTransaction();

                                return success;

                    }

                }             

 

                CommitTransaction();

                success = true;

 

    }

    catch (Exception ex)

    {

                RollbackTransaction();

    }

 

    return success;

}

 

 

 

Application Server – Data Access Layer

 

 

Table Module / Business Entities

Business entity that represents a table or view within a database and provides operations to interact with the table or view.

Business rules are not implemented within the business entities.

The business entities are just data containers. Business rules are handled by business processing components.

 

LINQ DataManager

Separate classes are used to define LINQ query objects.

It behaves like a gateway object - defined for each business entity in the design.

The gateway encapsulates all logic related to interacting with the associated DB table or view.

 

 

public int InsertOrder(LINQ.Data.Order order)

{

     order.InstitutionID = _institutionId;

    _dataContext.Orders.InsertOnSubmit(order);

    _dataContext.SubmitChanges();

 

    return order.OrderID;

}

 

 

 

 

Database Server

 

 

SQL Server DB

Tables and views are accessible to the Data Access Layer using LINQ ORM.

 

 

 

Reference: Link1, Link2

 

Hope this helps.

 

Thanks & Regards,

Arun Manglick

Repository Pattern - LINQ Implementation

The purpose of this article is to describe the technique I have used to implement the repository pattern in .NET applications. I will provide a brief description of the repository pattern and linq-to-sql, however, if you are unfamiliar with these technologies you should research them elsewhere. The goals of my implementation are:

  • it must be a general purpose design that can be reused for many projects
  • it must facilitate domain driven design
  • it must facilitate unit testing and testing in general
  • it must allow the domain model to avoid dependencies on infrastructure
  • it must provide strongly typed querying

 

Repository Pattern

 

The Repository Pattern, according to Martin Fowler, provides a "layer of abstraction over the mapping layer where query construction code is concentrated", to "minimize duplicate query logic". In practice it is usually a collection of data access services, grouped in a similar way to the domain model classes.

By accessing repositories via interfaces the repository pattern helps to break the dependency between the domain model and data access code. This is invaluable for unit testing because the domain model can be isolated.

I implement the repository pattern by defining one repository class for each domain model entity that requires specialized data access methods (other than the standard create, read, update and delete). If an entity does not require specialized data access methods then I will use a generic repository for that entity. A repository class contains the specialized data access methods required for its corresponding domain model entity.

The following class diagram shows an example implementation with one domain entity classes, Message. Message has a specialized repository (IMessageRepository).

 

Linq-to-sql

 

Linq is a strongly typed way of querying data. Linq-to-sql is a dialect of Linq that allows the querying of a Sql Server database. It also includes object / relational mapping and tools for generating domain model classes from a database schema. Linq is an excellent addition to object / relational mappings tools because it facilitates strongly typed queries, such as:

 

List<LabMessage> msgList = _genericMessageRepository.FindAll(m => m.PassCode1 == passCode1,
                                                                                           m => m.Active == (active == Active.Both ? m.Active : Convert.ToBoolean(active.GetHashCode()))).ToList();

 

 

IRepository<T>

The generic interface IRepository<T> defines the methods that are required on each repository.

public interface IRepository<T> where T : class
{
    /// <summary>
    /// Return all instances of type T.
    /// </summary>
    /// <returns></returns>
    IEnumerable<T> All();
  
    /// <summary>
    /// Return all instances of type T that match the expression exp.
    /// </summary>
    /// <param name="exp"></param>
    /// <returns></returns>
    IEnumerable<T> FindAll(Func<T, bool> exp);
  
    /// <summary>
    /// Return all instances of type T that match the expression exp.
    /// </summary>
    /// <param name="exp"></param>
    /// <returns></returns>
    IEnumerable<T> FindAll(Func<T, bool>[] exp);
  
  
    /// <summary>Returns the single entity matching the expression. Throws an exception if there is not exactly one such entity.</summary>
    /// <param name="exp"></param><returns></returns>
    T Single(Func<T, bool> exp);
  
    /// <summary>Returns the first element satisfying the condition.</summary>
    /// <param name="exp"></param><returns></returns>
    T First(Func<T, bool> exp);
  
    /// <summary>
    /// Mark an entity to be deleted when the context is saved.
    /// </summary>
    /// <param name="entity"></param>
    void MarkForDeletion(T entity);
  
    /// <summary>
    /// Create a new instance of type T.
    /// </summary>
    /// <returns></returns>
    T CreateInstance();
  
    /// <summary>Persist the data context.</summary>
    void SaveAll();
} 

 

Repository<T>

IRepository<T> is implemented by a generic repository base class, Repository<T>. Repository<T> is a base implementation that provides data access functionality for all entities. If an entity (T) does not require a specialized repository then its data access will be done through Repository<T>.

public class Repository<T> : IRepository<T> 
    where T : class
{
    protected IDataContextFactory _dataContextFactory;
  
    /// <summary>
    /// Return all instances of type T.
    /// </summary>
    /// <returns></returns>
    public IEnumerable<T> All()
    {
        return GetTable;
    }
  
    /// <summary>
    /// Return all instances of type T that match the expression exp.
    /// </summary>
    /// <param name="exp"></param>
    /// <returns></returns>
    public IEnumerable<T> FindAll(Func<T, bool> exp)
    {
        return GetTable.Where<T>(exp);
    }
  
    /// <summary>
    /// Return all instances of type T that match the expression exp.
    /// </summary>
    /// <param name="exp"></param>
    /// <returns></returns>
    public IEnumerable<T> FindAll(Func<T, bool>[] exprs)
    {
        IEnumerable<T> res = GetTable.ToList<T>();
        foreach (Func<T, bool> selector in exprs)
         {
                res = res.Where<T>(selector);
         }
  
        return res;
    }
  
    /// <summary>See IRepository.</summary>
    /// <param name="exp"></param><returns></returns>
    public T Single(Func<T, bool> exp)
    {
        return GetTable.Single(exp);
    }
  
    /// <summary>See IRepository.</summary>
    /// <param name="exp"></param><returns></returns>
    public T First(Func<T, bool> exp)
    {
        return GetTable.First(exp);
    }
  
    /// <summary>See IRepository.</summary>
    /// <param name="entity"></param>
    public virtual void MarkForDeletion(T entity)
    {
        _dataContextFactory.Context.GetTable<T>().DeleteOnSubmit(entity);        
    }
  
    /// <summary>
    /// Create a new instance of type T.
    /// </summary>
    /// <returns></returns>
    public virtual T CreateInstance()
    {
        T entity = Activator.CreateInstance<T>();
        GetTable.InsertOnSubmit(entity);
        return entity;
    }
  
    /// <summary>See IRepository.</summary>
    public void SaveAll()
    {
        _dataContextFactory.SaveAll();
    }
  
    public Repository(IDataContextFactory dataContextFactory)
    {
        _dataContextFactory = dataContextFactory;
    }
    
    #region Properties
  
    private string PrimaryKeyName
    {
        get { return TableMetadata.RowType.IdentityMembers[0].Name; }
    }
  
    private System.Data.Linq.Table<T> GetTable
    {
        get { return _dataContextFactory.Context.GetTable<T>(); }
    }
  
    private System.Data.Linq.Mapping.MetaTable TableMetadata
    {
        get { return _dataContextFactory.Context.Mapping.GetTable(typeof(T)); }
    }
  
    private System.Data.Linq.Mapping.MetaType ClassMetadata
    {
        get { return _dataContextFactory.Context.Mapping.GetMetaType(typeof(T)); }
    }