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; }
}
}

Sunday, April 20, 2008

Telerik Radgrid: showing hierarchical data using a Dataset with multiple tables example

The telerik radgrid is one of the most complete grid control in the market. Have a cool set of features and covers the most commonly scenaries.
A common UI requirement is show Hierarchycal data, this data can be loaded in several ways with or without postbacks changing the property "HierarchyLoadMode". In case that the set of data to show is not great (use your criteria), you can choose load all data in the client obtaining a more responsive UI. To minimize roundtrips to database a good choice is code an stored procedure that returns multiple results and obtain a DataSet with multiple tables.
I make an example based on the AdventureWorks db to show the Departments and their respective employees.

The Stored Procedure:
This SP gets the data from Departments and Employees returning two results that share one column (DepartmentId) to make the parent/child relation.

CREATE PROCEDURE [HumanResources].[Department_Get_DepartmentAndEmployees]
AS

/* Get the departments */
SELECT HRD.DepartmentID, HRD.Name as DepartmentName
FROM HumanResournces.Department HRD
ORDER BY DepartmentName

/* Get the employees */
SELECT PC.FirstName,
PC.LastName,
HRE.Title,
HRDep.DepartmentId
FROM
HumanResources.Employee HRE
INNER JOIN Person.Contact PC ON PC.ContactId = HRE.ContactId
INNER JOIN HumanResources.EmployeeDepartmentHistory HRDep ON HRDep.EmployeeId = HRE.EmployeeId


The .aspx Code:
Note the ParentTableRelation tag uses the DepartmentId field to make the relation from the Employees table to the Department table.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<!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>Telerik Radgrid: showing hierarchical data using a Dataset with multiple tables</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="Scriptmanager1" runat="server">
</asp:ScriptManager>
<telerik:RadGrid ID="gvEmployeesByDepartment" runat="server" Width="95%" AutoGenerateColumns="False"
GridLines="None" ShowHeader="True" Skin="Web20">
<MasterTableView DataMember="Departments" DataKeyNames="DepartmentId" Width="100%"
Name="Customers" HierarchyLoadMode="Client">
<DetailTables>
<telerik:GridTableView DataMember="Employees" DataKeyNames="DepartmentId" Width="100%"
runat="server" ShowHeader="true">
<ParentTableRelation>
<telerik:GridRelationFields DetailKeyField="DepartmentId" MasterKeyField="DepartmentId" />
</ParentTableRelation>
<RowIndicatorColumn CurrentFilterFunction="NoFilter" FilterListOptions="VaryByDataType"
Visible="False">
<HeaderStyle Width="20px"></HeaderStyle>
</RowIndicatorColumn>
<ExpandCollapseColumn CurrentFilterFunction="NoFilter" FilterListOptions="VaryByDataType"
Visible="False" Resizable="False">
<HeaderStyle Width="20px"></HeaderStyle>
</ExpandCollapseColumn>
<Columns>
<telerik:GridBoundColumn DataField="Title" UniqueName="Title" ReadOnly="true" HeaderText="Title">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="FirstName" UniqueName="FirstName" ReadOnly="true"
HeaderText="First Name">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="LastName" UniqueName="LastName" ReadOnly="true"
HeaderText="Last Name">
</telerik:GridBoundColumn>
</Columns>
</telerik:GridTableView>
</DetailTables>
<RowIndicatorColumn CurrentFilterFunction="NoFilter" FilterListOptions="VaryByDataType"
Visible="False">
<HeaderStyle Width="20px"></HeaderStyle>
</RowIndicatorColumn>
<ExpandCollapseColumn CurrentFilterFunction="NoFilter" FilterListOptions="VaryByDataType"
Resizable="False">
<HeaderStyle Width="20px"></HeaderStyle>
</ExpandCollapseColumn>
<Columns>
<telerik:GridBoundColumn DataField="DepartmentName" UniqueName="DepartmentName" HeaderText="Department">
</telerik:GridBoundColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
</form>
</body>
</html>


The .cs Code:

using System;
using System.Data;
using System.Web.UI;
using System.Data.SqlClient;

public partial class _Default :System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
BindDepartmentsAndEmployees();
}

private void BindDepartmentsAndEmployees()
{
SqlConnection conn = new SqlConnection(@"Integrated Security=SSPI;Persist Security Info=False;User ID=marketpoint;Initial Catalog=AdventureWorks;Data Source=(local)\sqlexpress");
SqlCommand cmd = new SqlCommand("[HumanResources].[Department_Get_DepartmentAndEmployees]", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet dsDepartmentAndEmployees = new DataSet();
da.Fill(dsDepartmentAndEmployees);
if(da != null)
{
// Renames Dataset table to get more clear names in grid declarative properties
dsDepartmentAndEmployees.Tables[0].TableName = "Departments";
dsDepartmentAndEmployees.Tables[1].TableName = "Employees";
gvEmployeesByDepartment.DataSource = dsDepartmentAndEmployees;
gvEmployeesByDepartment.DataBind();
}
}
}

The UI Result (Click to Enlarge):

Friday, April 4, 2008

NetTiers: Expose custom stored procedures as componentlayer methods

Sometimes is needed a custom functionality that goes far that the CRUD functionality generated by NetTiers. To acomplish this task we can use a custom stored procedure to get the data and expose it as a method of the componentlayer (services layer).
Follow the next steps to expose a custom stored procedure:

1) Configure Codesmith properties
CustomProceduresStartsWith (example: {1}{0}_)
ProcedurePrefix (example: cust_sp_ )

2) Add a Stored Procedure
Add a SP with a name that follows the convention defined in CustomProceduresStartsWith where {1} is the placeholder for
ProcedurePrefix and {0} is the placeholder for the TableName, for example cust_sp_Contact_GetBySalesOrderCountBetween (using AdventureWorks db)

CREATE PROCEDURE [dbo].[cust_sp_Contact_GetBySalesOrderCountBetween]

@min int,
@max int
AS
BEGIN
SET NOCOUNT ON;

SELECT * FROM Person.Contact C
WHERE
(SELECT COUNT(*) FROM Sales.SalesOrderHeader SOH
WHERE SOH.ContactId = C.ContactId) BETWEEN @min and @max
END

3) Run the template

4) Use the method
Now in the componentlayer for the entity we have our custom stored procedure exposed as a method

ContactService contactService = new ContactService();
gvContacts.DataSource = contactService.GetBySalesOrderCountBetween(25, 30);
gvContacts.DataBind();


Note: the return type of the custom stored procedure method can be a TList or the defined in the CustomNonMatchingReturnType property (DataSet/IDataReader).
To determine what type will be return a method compares every column order and type returned from the Sp with every column order and type of the Entity table.
Debugging a bit the template, I have reviewed the method that compares the stored procedure column type with the table column type. This method returns false if some column type returned has no equivalent (File: \TemplateLib\CommonSqlCode.cs Method: IsMatching)

if (!SqlTypesAreEquivalent(command.CommandResults[0].Columns[i].NativeType, table.Columns[i].NativeType))
return false;


If you have UDT (User-Defined Data Types) fields in your table this method will be return false and CustomNonMatchingReturnType will be setted as Method Return type.

Usually is preferible that have an TList as method return than a Dataset or a IDataReader, because in this way you have all the NetTiers functionality to manipulate the data (deepload the TList returned for example). To force return a TList when have
UDT fields you can edit the file \TemplateLib\CommonSqlCode.cs and change in the method IsMatching the above line for this:


if (!SqlTypesAreEquivalent(command.CommandResults[0].Columns[i].DataType.ToString(), table.Columns[i].DataType.ToString()))

Thursday, March 6, 2008

Export Html to Pdf using iTextSharp

This is an example to export from html to pdf using iTextSharp. In this case I used a html template file with some token fields that are replaced and after exported to pdf.

private static void GeneratePDF()
{
// Set output folder to /pdf
string outputFolder = HttpContext.Current.Server.MapPath("pdf");
// Set output file name to a Guid based name
string pdfFileName = outputFolder + "\\" + Guid.NewGuid().ToString() + ".pdf";

Document iTextSharpDocument = new Document(new Rectangle(880, 700));
FileStream fs = new FileStream(pdfFileName, FileMode.CreateNew);
PdfWriter writer = PdfWriter.GetInstance(iTextSharpDocument, fs);
iTextSharpDocument.Open();

// Read the html template and replace values
string templatePath = HttpContext.Current.Server.MapPath("html/ReportTemplate.html");
TextReader templateReader = new StreamReader(templatePath);
StringBuilder sbTemplate = new StringBuilder(templateReader.ReadToEnd());
sbTemplate.Replace("[@title]", "Sales");
sbTemplate.Replace("
[@name]", "Jhon Smith");
sbTemplate.Replace("
[@date]", DateTime.Now.ToString());

XmlDocument htmlDoc = new XmlDocument();
htmlDoc.LoadXml(sbTemplate.ToString());

HtmlParser.Parse(iTextSharpDocument, htmlDoc);

// Release resources
templateReader.Close();

iTextSharpDocument.Close();
writer.Close();

writer = null;
iTextSharpDocument = null;

fs.Close();
fs.Dispose();
}

Monday, December 3, 2007

NetTiers "SELECT DISTINCT" method

Using Nettiers CRUD methods and custom methods we get a very complete DAL that covers a wide range of the queries needed by a application. A frequently question in forums is about how obtain a "Select Distinct" clause equivalent in Nettiers. I've developed a method to obtain the distinct entities based on the values of one or more properties.

public static TList<T> SelectDistinctFromList<T>(TList<T> originalList, System.Enum[] distinctProperties) where T : IEntity, new()
{
Type instanceType = originalList.GetType().GetGenericArguments()[0].BaseType;

PropertyInfo[] propertyColumns = new PropertyInfo[distinctProperties.Length];
for(int i = 0; i < distinctProperties.Length; i++)
{
propertyColumns[i] = instanceType.GetProperty(distinctProperties[i].ToString());
}

TList<T> resultList = new TList<T>();
System.Collections.Specialized.StringCollection keys = new System.Collections.Specialized.StringCollection();
foreach (T instance in originalList)
{
string key = string.Empty;
foreach (PropertyInfo pi in propertyColumns)
{
key += pi.GetValue(instance, null) + "|";
}
if (!keys.Contains(key))
{
keys.Add(key);
resultList.Add(instance);
}
}
return resultList;
}

As you can see there are two steps to get the "Select Distinct", in the first step is retrieve the base collection (TList) and in the second step apply the SelectDistinctFromList method.
This approach is adequate when the first step data is cached, have not a big collection or want to do many "Select Distinct" over the collection. For example, using a Nettiers project generated from
the AdventureWorks DB first obtains the orders for a SalesPerson and after get a list of orders with the distinct Territories and other list with the distinct Customers and Status.

SalesOrderHeaderService service = new SalesOrderHeaderService();
TList<SalesOrderHeader> orders = service.GetBySalesPersonId(279);

TList<SalesOrderHeader> distinctTerritoriesFromOrders = SelectDistinctFromList<SalesOrderHeader>(orders, new Enum[] { SalesOrderHeaderColumn.TerritoryId });

TList<SalesOrderHeader> distinctCustomerAndStatusFromOrders = SelectDistinctFromList<SalesOrderHeader>(orders, new Enum[] { SalesOrderHeaderColumn.CustomerId, SalesOrderHeaderColumn.Status });

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>

Monday, July 16, 2007

Handle multiple asynchronous calls in Asp.Net Ajax complex scenarios

I have been developing an Ajaxed Asp.net application that has in some pages a heavy load of Ajax components implemented with multiple update panels containing controls that fires heavy load process in the server side. To obtain a responsive UI the challenge was that the user can initiates an Ajax request and while it is processed, can initiate another requests.
Browsing the ASP.NET AJAX Client Life-Cycle Events I found the next explanation of Event Order for Multiple Asynchronous Postbacks:
"The default behavior of asynchronous postbacks is that the most recent asynchronous postback takes precedence. If two asynchronous postbacks occur in sequence, and if the first postback is still being processed in the browser, the first postback is canceled. If the first postback has been sent to the server, the server processes the second request when it arrives and does not return the first request."

This behavour "last request wins" prevents the implementation of a full process of multiple request. Googling I found this article thats use a queue and works fine with few Ajax components but freeze the browser in the heavy Ajax request scenario. With a little tweak in the code (commented below) now it works smoothly and can handle a set of continuous requests.
WARNING: have precaution in scenarios with controls that depend of the result of the execution of another control.


<%@ 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 id="Head1" runat="server">
<title>Untitled Page</title>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

</div>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</ContentTemplate>
</asp:UpdatePanel>

<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Button" />
</ContentTemplate>
</asp:UpdatePanel>

<asp:UpdatePanel ID="UpdatePanel3" runat="server">
<ContentTemplate>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="Button" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1"
DisplayAfter="0">
<ProgressTemplate>
Updating panel1
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdateProgress ID="UpdateProgress3" runat="server" AssociatedUpdatePanelID="UpdatePanel3"
DisplayAfter="0">
<ProgressTemplate>
Updating panel3
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdateProgress ID="UpdateProgress2" runat="server" AssociatedUpdatePanelID="UpdatePanel2"
DisplayAfter="0">
<ProgressTemplate>
Updating panel2
</ProgressTemplate>
</asp:UpdateProgress>
<div id="AlertDiv">
<span id="AlertMessage"></span>
</div>

<script type="text/javascript">
Sys.Application.add_load(ApplicationLoadHandler)

function ApplicationLoadHandler(sender, args)
{
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (!prm.get_isInAsyncPostBack())
{
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(CompleteRequest);
}
}
// initialize a queue
var myQueue = new Array();

function CompleteRequest(sender, args)
{
if(myQueue.length > 0)
{ // Fire correspond event again of the item cached
// Original Code:
// $get(myQueue[0].id).click();
// Changed to:
// var control = $get(myQueue[0]);
// setTimeout('__doPostBack(\'' + control.name + '\',\'\')', 0);
var control = $get(myQueue[0]);
setTimeout('__doPostBack(\'' + control.name + '\',\'\')', 0);
Array.removeAt(myQueue, 0);
}
}
function InitializeRequest(sender, args)
{
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm.get_isInAsyncPostBack())
{ // If it's working on another request, cache the current item that cause the request
args.set_cancel(true);
// Original Code:
// Array.add(myQueue, args.get_postBackElement());
// Changed to:
// Array.add(myQueue, args.get_postBackElement().name);
Array.add(myQueue, args.get_postBackElement().name);
}
}

if(typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

</script>

</form>
</body>
</html>


using System;

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

protected void Button1_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
Label1.Text = DateTime.Now.ToLongTimeString();
}
protected void Button2_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
Label2.Text = DateTime.Now.ToLongTimeString();
}
protected void Button3_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
Label3.Text = DateTime.Now.ToLongTimeString();
}
}