Showing posts with label Generics. Show all posts
Showing posts with label Generics. Show all posts

Monday, May 5, 2008

Generics Examples - Generating instances with two methods or how to simplify the DAL

In this delivery two methods to generate instances or collections of our entities, simplifying therefore the code of our DAL (traditionally composed by a great amount of methods and mappings “field to field” from tables to objects). Once collected the data using a DataReader, with these methods is possible to obtain a single entity instance or a strong typed collection of instances.

The Methods


// A single instance
public static void FillEntity<T>(T instance, IDataRecord datarecord)
{
Type instanceType = instance.GetType();
for (int i = 0; i < datarecord.FieldCount; i++)
{
if (datarecord[i] != DBNull.Value)
{
string propName = datarecord.GetName(i);
PropertyInfo propInfo = instanceType.GetProperty(propName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (propInfo != null)
{
propInfo.SetValue(instance, datarecord[propInfo.Name], null);
}
}
}
}

// A instance collection
public static List<T> FillEntities<T>(IDataReader dr)
{
List<T> entities = new List<T>();
while (dr.Read())
{
T instance = Activator.CreateInstance<T>();
Utils.FillEntity<T>(instance, dr);
entities.Add(instance);
}
return entities;
}

Using the methods



// A Single Instance
public static UserInfo UserGetById(string userid)
{
UserInfo userInfo = new UserInfo();
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetStoredProcCommand("usergetbyid");
db.AddInParameter(dbCommand, "userid", DbType.String, userid);
IDataReader idr = db.ExecuteReader(dbCommand);
if (idr.Read())
{
Utils.FillEntity<UserInfo>(userInfo, idr);
}
return userInfo;
}

// A instance collection
public static List<OrderInfo> GetOrders(int customerid)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetStoredProcCommand("getorders");
db.AddInParameter(dbCommand, "customerid", DbType.Int32, customerid);
return Utils.FillEntities<OrderInfo>(db.ExecuteReader(dbCommand));
}

Friday, April 25, 2008

Generics Examples - Passing paramaters to Stored Procedures

In this post begins a series of examples of application of Generics that were useful to me throughout several developments. In this delivery a generic method that receives an instance of some entity of our domain and a DbCommand, and based on the SqlParameterAttributes attributes “reflected” from the entity maps the value of the properties with the parameters of stored procedure of the received DbCommand. Using this only method and “decorating” with the SqlParameterAttribute attributes the suitable properties of our classes it is possible to simplify the stored procedures calls.

The Method


public static void MatchStoreProceduresParams<T>(T entity, DbCommand command)
{
Type type = entity.GetType();
foreach (PropertyInfo entityProperty in type.GetProperties())
{
SqlParameterAttribute[] propSqlAttributeArray = (SqlParameterAttribute[])entityProperty.GetCustomAttributes(typeof(SqlParameterAttribute), false);
if (propSqlAttributeArray.Length > 0)
{
SqlParameterAttribute propSqlAttribute = propSqlAttributeArray[0];
if (propSqlAttribute != null)
{
SqlParameter sqlParam = new SqlParameter();
sqlParam.ParameterName = propSqlAttribute.Name;
sqlParam.SqlDbType = propSqlAttribute.SqlDbType;
sqlParam.Value = entityProperty.GetValue(entity, null);
if (propSqlAttribute.IsDirectionDefined)
{
sqlParam.Direction = propSqlAttribute.Direction;
}
command.Parameters.Add(sqlParam);
}
}

}
}

Using the method

public static int CustomerSave(CustomerInfo customer)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetStoredProcCommand("CustomerUpdate");
Utils.MatchStoreProceduresParams(customer, dbCommand);
return db.ExecuteNonQuery(dbCommand);
}

Decorando la clase

public class CustomerInfo
{
int _id;
string _name;
int _age;
decimal _balance;

public CustomerInfo()
{

}

[SqlParameter("@CustomerId", System.Data.SqlDbType.Int)]
public int Id
{
get { return _id; }
set { _id = value; }
}

[SqlParameter("@FirstName", System.Data.SqlDbType.Char)]
public string Name
{
get { return _name; }
set { _name = value; }
}

[SqlParameter("@Age", System.Data.SqlDbType.Int)]
public int Age
{
get { return _age; }
set { _age = value; }
}

[SqlParameter("@Balance", System.Data.SqlDbType.Decimal)]
public decimal Balance
{
get { return _balance; }
set { _balance = value; }
}
}

Tuesday, August 7, 2007

Reflect the underlying type of nullable property / field

Sometimes it's necessary list the properties with their types of an entity instanciated at run-time. For example when develop a CRUD form at runtime for a selected entity or when build a designer form like a report designer or expression designer that implies entities and her properties. This task is not problematic using Reflection, but if we use Nullable properties (and we would have to use it whenever a value can be null) the underlying type of a nullable property can't be obtained in the traditional way. A nullable property is a "constructed type" of the Nullable<T> generic class, this means that the type of the property is the parameter for the constructor of Nullable<T> (For example a nullable int property is an instance of Nullable<int>). I wrote a method that list the properties with their types iterating over the reflected properties adding his name and type to a dictionary, and when it finds a generic property obtains the underlying type of the property using the argument that was supplied to construct the nullable type.
Below a sample of using the method to list the properties and types of a run-time instantiated entity.


using System;
using System.Web;
using System.Collections.Generic;
using System.Reflection;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

public static SortedDictionary<string, string> GetPropertiesAndDataTypes(string entityName)
{
SortedDictionary<string, string> dict = new SortedDictionary<string, string>();
string propertyType = string.Empty;
if (!String.IsNullOrEmpty(entityName))
{
Type type = Type.GetType(entityName);
if (type != null)
{
PropertyInfo[] properties = type.GetProperties();
if (properties != null && properties.Length > 0)
{
foreach (PropertyInfo propertyInfo in properties)
{
if (propertyInfo.PropertyType.IsGenericType)
{
Type nullableProperty = Type.GetType(propertyInfo.PropertyType.FullName);
// Obtains the Name of the type used as parameter of Nullable<T>
propertyType = nullableProperty.GetGenericArguments()[0].FullName;
}
else
{
propertyType = propertyInfo.PropertyType.FullName;
}
dict.Add(propertyInfo.Name, string.Format("{0} ({1})", propertyInfo.Name, propertyType));
}
}
}
}
return dict;
}

protected void ddlEntities_SelectedIndexChanged(object sender, EventArgs e)
{
lbEntityProperties.Items.Clear();
if (ddlEntities.SelectedIndex > 0)
{
lbEntityProperties.DataSource = GetPropertiesAndDataTypes(ddlEntities.SelectedValue);
lbEntityProperties.DataTextField = "Value";
lbEntityProperties.DataValueField = "Key";
lbEntityProperties.DataBind();
}
}
}

public class Product
{
private int _productId;
private string _name;
private bool? _makeFlag;
private DateTime _selStartDate;
private DateTime? _selEndDate;
private int? _daysToManufacture;

public int ProductId
{
get { return _productId; }
set { _productId = value; }
}

public string Name
{
get { return _name; }
set { _name = value; }
}

public bool? MakeFlag
{
get { return _makeFlag; }
set { _makeFlag = value; }
}

public DateTime SelStartDate
{
get { return _selStartDate; }
set { _selStartDate = value; }
}

public DateTime? SelEndDate
{
get { return _selEndDate; }
set { _selEndDate = value; }
}

public int? DaysToManufacture
{
get { return _daysToManufacture; }
set { _daysToManufacture = value; }
}

public Product()
{

}

}

public class Contact
{
private string _name;
private int? _score;
private bool? _isMember;

public Contact()
{ }

public int? Score
{
get { return _score; }
set { _score = value; }
}

public string Name
{
get { return _name; }
set { _name = value; }
}

public bool? IsMember
{
get { return _isMember; }
set { _isMember = value; }
}

}

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Reflect type of nullable properties</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlEntities" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlEntities_SelectedIndexChanged">
<asp:ListItem>-- Select Entity --</asp:ListItem>
<asp:ListItem>Contact</asp:ListItem>
<asp:ListItem>Product</asp:ListItem>
</asp:DropDownList><br /><br />
<asp:ListBox ID="lbEntityProperties" runat="server" Height="258px" Width="265px"></asp:ListBox>
</div>
</form>
</body>
</html>