Friday, February 13, 2015

Sample to use repository pattern to return data object from DAO layer to client




From C-sharp corner and few more online resources:
we will talk more on collections, it's hidden features and how to extend it in next post:


using System;using System.Data;using System.Configuration;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;
/// <summary>
///
 Summary description for Customer/// </summary>[Serializable]public class Customer{
      public Customer()
      {
            //            // TODO: Add constructor logic here            //      }
    public string CustomerID { getset; }
    public string FirstName { getset; }
    public string LastName { getset; }
    public string Address { getset; }
    public string City { getset; }
    public string State { getset; }
    public string Country { getset; }
    public string Mobile { getset; }
    public string Mail { getset; }
}
The customer class is created with all the required attributes and all are defined in the property. C# 3.0 and above allows developers to use auto defined properties which do not need to include any private string to use in the get and set.
The class customer is a single entity which has all the attributes of the customers. When you want to store multiple instances of the same customer then there are several ways to store them such as a List<> collection.
Similarly the customer can have its own custom collection class typically it uses the List to add, remove, etc., The CollectionBase class has to be inherited into the Customers collection class. The System.Collections namespace has the CollectionBase interface.

using System;using System.Data;using System.Configuration;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Collections;using System.Xml.Linq;
/// <summary>
///
 Summary description for Customers/// </summary>[Serializable]public class Customers : CollectionBase{
      public Customers()
      {
            //            // TODO: Add constructor logic here            //      }
    #region Properties
    /// <summary>    /// Gets/Sets value for the item by that index    /// </summary>    public Customer this[int index]
    {
        get        {
            return (Customer)this.List[index];
        }
        set        {
            this.List[index] = value;
        }
    }
    #endregion
    #region Public Methods
    public int IndexOf(Customer customerItem)
    {
        if (customerItem != null)
        {
            return base.List.IndexOf(customerItem);
        }
        return -1;
    }
    public int Add(Customer customerItem)
    {
        if (customerItem != null)
        {
            return this.List.Add(customerItem);
        }
        return -1;
    }
    public void Remove(Customer customerItem)
    {
        this.InnerList.Remove(customerItem);
    } 
    public void AddRange(Customers collection)
    {
        if (collection != null)
        {
            this.InnerList.AddRange(collection);
        }
    }
    public void Insert(int index, Customer customerItem)
    {
        if (index <= List.Count && customerItem != null)
        {
            this.List.Insert(index, customerItem);
        }
    }
 
    public bool Contains(Customer customerItem)
    {
        return this.List.Contains(customerItem);
    }
 
    #endregion}
The Customers collection class has indexers to store the customer object into a customers collection. It acquires all the functionality of the collection class like Insert, Delete, Add, Contains, etc..,
Let us see an example of implementing the customers collection class.
public Customers GetAllCustomers()
    {
        Customers customers = null;
        try        {
            string strRetrievalQuery = "SELECT * FROM customers";
            customers = new Customers();
            Customer customer = null;
            SqlDataReader sqlDataReader = _DBConnector.ExecuteQueryReader(strRetrievalQuery);
            if(sqlDataReader != null)
            {
                // Call Read before accessing data.                while (sqlDataReader.Read())
                {
                    customer = new Customer();
                    customer.CustomerID = sqlDataReader[0].ToString();
                    customer.FirstName = sqlDataReader[1].ToString();
                    customer.LastName = sqlDataReader[2].ToString();
                    customer.Address = sqlDataReader[3].ToString();
                    customer.City = sqlDataReader[4].ToString();
                    customer.State = sqlDataReader[5].ToString();
                    customer.Country = sqlDataReader[6].ToString();
                    customer.Mobile = sqlDataReader[7].ToString();
                    customer.Mail = sqlDataReader[8].ToString();
                    customers.Add(customer);
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return customers;
    }


DAO Object
public class ProgramInterfaceWs_responsePositions
    {

        private string user_idField;

        private ulong position_idField;

        private string position_nameField;

        private string full_nameField;

        private ushort position_levelField;

        private string postn_lvl_nmField;

        /// <remarks/>
        public string user_id
        {
            get
            {
                return this.user_idField;
            }
            set
            {
                this.user_idField = value;
            }
        }

        /// <remarks/>
        public ulong position_id
        {
            get
            {
                return this.position_idField;
            }
            set
            {
                this.position_idField = value;
            }
        }

        /// <remarks/>
        public string position_name
        {
            get
            {
                return this.position_nameField;
            }
            set
            {
                this.position_nameField = value;
            }
        }

        /// <remarks/>
        public string full_name
        {
            get
            {
                return this.full_nameField;
            }
            set
            {
                this.full_nameField = value;
            }
        }

        /// <remarks/>
        public ushort position_level
        {
            get
            {
                return this.position_levelField;
            }
            set
            {
                this.position_levelField = value;
            }
        }

        /// <remarks/>
        public string postn_lvl_nm
        {
            get
            {
                return this.postn_lvl_nmField;
            }
            set
            {
                this.postn_lvl_nmField = value;
            }
        }
    }

DAO layer:
public List<ProgramInterfaceWs_responsePositions> BuyerCursor(string languageCode, string countryCode,
                    int baseDivision)
        {
            if (isDisposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }
            try
            {
                var elementList = _repository.FindAll<MerchandiseBuyer>()
                    .SelectMany(f => f.Localizations, (mb, mbt) => new { mb, mbt })
                    .Where(e => e.mb.BaseDivision == baseDivision &&
                        e.mb.CountryCode == countryCode && e.mbt.LanguageCode == languageCode)
                    .Select(k => new
                    {
                        buyerUserId = k.mb.BuyerUserId,
                        buyerReportPositionId = k.mb.BuyerReportPositionId,
                        buyerReportPosDesc = k.mbt.BuyerReportPositionDescription,
                        buyerFullName = k.mbt.BuyerFullName,
                    })
                    .ToList();

                return elementList.Select(e => new ProgramInterfaceWs_responsePositions
                {
                    user_id = e.buyerUserId,
                    position_id = (ulong)e.buyerReportPositionId,
                    position_name = e.buyerReportPosDesc,
                    full_name = e.buyerFullName == null ? " " : e.buyerFullName,
                    position_level = 0,
                    postn_lvl_nm = "Buyer"
                }).ToList<ProgramInterfaceWs_responsePositions>();
            }
            catch
            {
                throw;
            }
        }

Static Void Main()
{
GetPositionsResponse resp = new GetPositionsResponse();

PositionCollection positions = new PositionCollection(); ( the client to see the structure)

List<ProgramInterfaceWs_responsePositions> returnPostn = null; ( the middle layer returning the data)

if (returnPostn != null)
            {
                foreach (ProgramInterfaceWs_responsePositions postn in returnPostn)
                {
                    positions.Add(new Position((int)postn.position_id, postn.position_name.Trim(), (int)postn.position_level, postn.postn_lvl_nm.Trim(), postn.user_id.Trim(), postn.full_name.Trim(), 0));
                }
            }

resp.GetPositionsResult = positions;
            return resp;




}

Response Object:
  [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ServiceModel.MessageContractAttribute(WrapperName = "GetPositionsResponse", WrapperNamespace = "http://namespace /merchandising/hierarchy/position/messages/", IsWrapped = true)]
    public partial class GetPositionsResponse
    {
        /// <summary>
        /// POsition Collection
        /// </summary>
        [System.ServiceModel.MessageBodyMemberAttribute(Namespace = "http:// namespace merchandising/hierarchy/position/messages/", Order = 0)]
        [System.Xml.Serialization.XmlArrayItemAttribute(Namespace = "http:// namespace /merchandising/hierarchy/position/datatypes/")]
        public PositionCollection GetPositionsResult;

        /// <summary>
        /// Default Constructor
        /// </summary>
        public GetPositionsResponse()
        {
        }
        /// <summary>
        /// Argument Constructor
        /// </summary>
        public GetPositionsResponse(PositionCollection GetPositionsResult)
        {
            this.GetPositionsResult = GetPositionsResult;
        }
    }

public class PositionCollection : System.Collections.ObjectModel.Collection<Position>
    {
    }



No comments:

Post a Comment