Wednesday, November 21, 2007

Reader Helper Class in C#

This class will help with reading data from any DataReader. It has helper methods to parse out almost any datatype from the database into a C# data type.

using System;

using System.Data.Common;

using System.Collections.Generic;

using System.Text;

using System.Xml;

using System.Data.SqlClient;


public class ReaderHelper

{

/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <param name="defaultGuid"></param>

/// <returns></returns>

public static Guid GetGuid(DbDataReader rdr, string column, Guid defaultGuid)

{

int ordinal = rdr.GetOrdinal(column);

if (rdr.IsDBNull(ordinal))

{

return defaultGuid;

}

else

{

return rdr.GetGuid(ordinal);

}

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <param name="defaultGuid"></param>

/// <returns></returns>

public static Guid GetGuid(DbDataReader rdr, string column)

{

int ordinal = rdr.GetOrdinal(column);

return rdr.GetGuid(ordinal);

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <returns></returns>

public static decimal GetDecimal(DbDataReader rdr, string column)

{

return GetDecimal(rdr, column, 0);

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <param name="defaultValue"></param>

/// <returns></returns>

public static decimal GetDecimal(DbDataReader rdr, string column, decimal defaultValue)

{

int ordinal = rdr.GetOrdinal(column);

if (rdr.IsDBNull(ordinal))

{

return defaultValue;

}

else

{

return rdr.GetDecimal(ordinal);

}

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <returns></returns>

public static double GetDouble(DbDataReader rdr, string column)

{

return GetDouble(rdr, column, 0);

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <param name="defaultValue"></param>

/// <returns></returns>

public static double GetDouble(DbDataReader rdr, string column, double defaultValue)

{

int ordinal = rdr.GetOrdinal(column);

if (rdr.IsDBNull(ordinal))

{

return defaultValue;

}

else

{

return rdr.GetDouble(ordinal);

}

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <returns></returns>

public static DateTime GetDateTime(DbDataReader rdr, string column)

{

return GetDateTime(rdr, column, new DateTime());

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <param name="defaultValue"></param>

/// <returns></returns>

public static DateTime GetDateTime(DbDataReader rdr, string column, DateTime defaultValue)

{

int ordinal = rdr.GetOrdinal(column);

if (rdr.IsDBNull(ordinal))

{

return defaultValue;

}

else

{

return rdr.GetDateTime(ordinal);

}

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <returns></returns>

public static string GetString(DbDataReader rdr, string column)

{

return GetString(rdr, column, null);

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <param name="defaultValue"></param>

/// <returns></returns>

public static string GetString(DbDataReader rdr, string column, string defaultValue)

{

int ordinal = rdr.GetOrdinal(column);

if (rdr.IsDBNull(ordinal))

{

return defaultValue;

}

else

{

return rdr.GetString(ordinal);

}

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <returns></returns>

public static string GetStringNotNull(DbDataReader rdr, string column)

{

int ordinal = rdr.GetOrdinal(column);

if (rdr.IsDBNull(ordinal))

{

return "";

}

else

{

string value = rdr.GetString(ordinal);

if (value == null) value = "";

return value;

}

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <returns></returns>

public static int GetInt(DbDataReader rdr, string column)

{

return GetInt(rdr, column, 0);

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <param name="defaultValue"></param>

/// <returns></returns>

public static int GetInt(DbDataReader rdr, string column, int defaultValue)

{

int ordinal = rdr.GetOrdinal(column);

if (rdr.IsDBNull(ordinal))

{

return defaultValue;

}

else

{

return rdr.GetInt32(ordinal);

}

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <returns></returns>

public static int GetInt16(DbDataReader rdr, string column)

{

return GetInt16(rdr, column, 0);

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <param name="defaultValue"></param>

/// <returns></returns>

public static int GetInt16(DbDataReader rdr, string column, int defaultValue)

{

int ordinal = rdr.GetOrdinal(column);

if (rdr.IsDBNull(ordinal))

{

return defaultValue;

}

else

{

return rdr.GetInt16(ordinal);

}

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <param name="defaultValue"></param>

/// <returns></returns>



public static double GetMoney(DbDataReader rdr, string column)

{

int ordinal = rdr.GetOrdinal(column);

SqlDataReader sqlReader = (SqlDataReader)rdr;

if (sqlReader.IsDBNull(ordinal))

{

return new double();

}

else

{

return double.Parse(sqlReader.GetSqlMoney(ordinal).ToString());

}

}

/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <returns></returns>

public static byte GetByte(DbDataReader rdr, string column)

{

int ordinal = rdr.GetOrdinal(column);


if (rdr.IsDBNull(ordinal))

{

return new byte();

}

else

{

return rdr.GetByte(ordinal);

}

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <param name="defaultValue"></param>

/// <returns></returns>

public static char GetChar(DbDataReader rdr, string column, char defaultValue)

{

int ordinal = rdr.GetOrdinal(column);

if (rdr.IsDBNull(ordinal))

{

return defaultValue;

}

else

{

char[] c = new char[1];

rdr.GetChars(0, 0, c, 0, 1);

return c[0];

}

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <returns></returns>

public static bool GetBool(DbDataReader rdr, string column)

{

return GetBool(rdr, column, false);

}


/// <summary>

///

/// </summary>

/// <param name="rdr"></param>

/// <param name="column"></param>

/// <param name="defaultValue"></param>

/// <returns></returns>

public static bool GetBool(DbDataReader rdr, string column, bool defaultValue)

{

int ordinal = rdr.GetOrdinal(column);

if (rdr.IsDBNull(ordinal))

{

return defaultValue;

}

else

{

string value = "";


value = rdr.GetValue(ordinal).ToString();


if (value.Equals("yes", StringComparison.OrdinalIgnoreCase)

|| value.Equals("y", StringComparison.OrdinalIgnoreCase)

|| value.Equals("on", StringComparison.OrdinalIgnoreCase)

|| value.Equals("true", StringComparison.OrdinalIgnoreCase)

|| value.Equals("1", StringComparison.OrdinalIgnoreCase))

{

return true;

}


return false;

}

}


}


Sorting and Grouping with the Asp.Net GridView control

Here is an example of how you can sort and group a GridView.




private bool _sorted = false;

private int _sortColumnIndex = -1;

private string _sortColumnHeader = string.Empty;

private string _SortExpr;


public string SortExpr

{

get { return _SortExpr; }

set { _SortExpr = value; }

}



protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)

{

ResolveGroupingData(e.SortExpression);

}


private void ResolveGroupingData(string sortExpression)

{

foreach (DataControlField field in GridView1.Columns)

{

if (field.SortExpression == sortExpression)

{

_sorted = true;

SortExpr = sortExpression;

_sortColumnIndex = GridView1.Columns.IndexOf(field);

_sortColumnHeader = field.HeaderText;

}

}

}

protected override void Render(HtmlTextWriter writer)

{

if (_sorted)

{

Table table = (Table)GridView1.Controls[0];

Hashtable htLookUp = new Hashtable();

foreach (GridViewRow row in GridView1.Rows)

{

int realIndex = table.Rows.GetRowIndex(row);

string text = row.Cells[_sortColumnIndex].Text;

if (string.IsNullOrEmpty(text))

{

SortExpr = SortExpr.Replace('.', '_');

text = ((Label)row.FindControl("lbl" + SortExpr)).Text;

}

if (!htLookUp.ContainsKey(text))

{

htLookUp.Add(text, null);

GridViewRow newHeaderRow = new GridViewRow(realIndex, realIndex, DataControlRowType.DataRow, DataControlRowState.Normal);

TableCell newCell = new TableCell();

newHeaderRow.Cells.Add(newCell);

newCell.ColumnSpan = GridView1.Columns.Count;

newCell.BackColor = System.Drawing.Color.Gray;

newCell.ForeColor = System.Drawing.Color.White;

newCell.Font.Bold = true;

newCell.Text = string.Format(_sortColumnHeader, "&nbsp;:&nbsp;{0}", text);


table.Controls.AddAt(realIndex, newHeaderRow);

}

}

}

base.Render(writer);

}

Here is an example of how you can sort and group a GridView.




private bool _sorted = false;

private int _sortColumnIndex = -1;

private string _sortColumnHeader = string.Empty;

private string _SortExpr;


public string SortExpr

{

get { return _SortExpr; }

set { _SortExpr = value; }

}



protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)

{

ResolveGroupingData(e.SortExpression);

}


private void ResolveGroupingData(string sortExpression)

{

foreach (DataControlField field in GridView1.Columns)

{

if (field.SortExpression == sortExpression)

{

_sorted = true;

SortExpr = sortExpression;

_sortColumnIndex = GridView1.Columns.IndexOf(field);

_sortColumnHeader = field.HeaderText;

}

}

}

protected override void Render(HtmlTextWriter writer)

{

if (_sorted)

{

Table table = (Table)GridView1.Controls[0];

Hashtable htLookUp = new Hashtable();

foreach (GridViewRow row in GridView1.Rows)

{

int realIndex = table.Rows.GetRowIndex(row);

string text = row.Cells[_sortColumnIndex].Text;

if (string.IsNullOrEmpty(text))

{

SortExpr = SortExpr.Replace('.', '_');

text = ((Label)row.FindControl("lbl" + SortExpr)).Text;

}

if (!htLookUp.ContainsKey(text))

{

htLookUp.Add(text, null);

GridViewRow newHeaderRow = new GridViewRow(realIndex, realIndex, DataControlRowType.DataRow, DataControlRowState.Normal);

TableCell newCell = new TableCell();

newHeaderRow.Cells.Add(newCell);

newCell.ColumnSpan = GridView1.Columns.Count;

newCell.BackColor = System.Drawing.Color.Gray;

newCell.ForeColor = System.Drawing.Color.White;

newCell.Font.Bold = true;

newCell.Text = string.Format(_sortColumnHeader, "&nbsp;:&nbsp;{0}", text);


table.Controls.AddAt(realIndex, newHeaderRow);

}

}

}

base.Render(writer);

}

Example of how to compare two objects for sorting.

The example below demonstrates how you can compare two objects to allow for sorting. This is also a good example of how you can use reflection.

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Collections.Generic;

using System.Reflection;

/// <summary>

/// Summary description for ObjectComparer

/// </summary>

public class ObjectComparer<T> : IComparer<T>

{



#region Properties


private string _direction = "ASC";


public string Direction

{

get { return _direction; }

set { _direction = value; }

}


private string _compareField;


public string CompareField

{

get { return _compareField; }

set { _compareField = value; }

}


#endregion


#region Constructors


public ObjectComparer(string compareField, string direction)

{

_compareField = compareField;

_direction = direction;

}


#endregion


#region IComparer<T> Members


public int Compare(T x, T y)

{

//Split the fields into an array. The field is divided by dots,

//like Employee.Person.FirstName

string[] fieldParts = _compareField.Split('.');


object compareValX = x;

object compareValY = y;


//get the value of each field in the list.

foreach (string field in fieldParts)

{

compareValX = GetPropertyValue(compareValX, field);

compareValY = GetPropertyValue(compareValY, field);

}


//compare the values of the last fields in the list. Assumes the field's

//type implements IComparable.

int compareValue = ((IComparable)compareValX).CompareTo(compareValY);


//negate the result if dircection is descending

if (_direction.ToUpper() == "DESC")

compareValue = -1 * compareValue;


return compareValue;

}


private object GetPropertyValue(object o, string property)

{

//using reflection, load the type and return the value of

//the given property. This will throw an exception if the

//property cannot be found.

PropertyInfo pi = o.GetType().GetProperty(property);

object val = pi.GetValue(o, null);

return val;

}


#endregion


#region IComparer<T> Members


int IComparer<T>.Compare(T x, T y)

{

//throw new Exception("The method or operation is not implemented.");


//Split the fields into an array. The field is divided by dots,

//like Employee.Person.FirstName

string[] fieldParts = _compareField.Split('.');


object compareValX = x;

object compareValY = y;


//get the value of each field in the list.

foreach (string field in fieldParts)

{

compareValX = GetPropertyValue(compareValX, field);

compareValY = GetPropertyValue(compareValY, field);

}


//compare the values of the last fields in the list. Assumes the field's

//type implements IComparable.

int compareValue = ((IComparable)compareValX).CompareTo(compareValY);


//negate the result if dircection is descending

if (_direction.ToUpper() == "DESC")

compareValue = -1 * compareValue;


return compareValue;

}


#endregion

}

How to collect post data and then send it to a remote url as a post using Asp.NET.

Collect post data and send to remote URL as post. I know there is a postbackurl property that can be used, but this method allows you to modify, add, and remove from what you send to the new URL as a post. I've used this technique when integrating with PayPal and I needed to dynamically create a product that is being purchased (by including their user information), but this has many purposed.

void PostMe1(Object sender,EventArgs e){

RemotePost myremotepost = new RemotePost();

myremotepost.Url = "http://www.jigar.net/demo/HttpRequestDemoServer.aspx";

myremotepost.Add("field1","Tom");

myremotepost.Add("field2","Sawyer");

myremotepost.Post();

}

void PostMe2(Object sender,EventArgs e){

RemotePost myremotepost = new RemotePost();

myremotepost.Url = "http://www.jigar.net/demo/HttpRequestDemoServer.aspx";

myremotepost.Add("field1","Huckleberry");

myremotepost.Add("field2","Finn");

myremotepost.Post();

}


public class RemotePost{

private System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();


public string Url = "";

public string Method = "post";

public string FormName = "form1";



public void Add(string name,string value){

Inputs.Add(name,value);

}



public void Post(){

System.Web.HttpContext.Current.Response.Clear();


System.Web.HttpContext.Current.Response.Write("<html><head>");



System.Web.HttpContext.Current.Response.Write(string.Format("</head><body onload="\">",FormName));

System.Web.HttpContext.Current.Response.Write(string.Format("<form name="\" method="\" action="\">",FormName,Method,Url));

for(int i=0;i< Inputs.Keys.Count;i++){

System.Web.HttpContext.Current.Response.Write(string.Format("<input name="\" type="\" value="\">",Inputs.Keys[i],Inputs[Inputs.Keys[i]]));

}

System.Web.HttpContext.Current.Response.Write("</form>");

System.Web.HttpContext.Current.Response.Write("</body></html>");


System.Web.HttpContext.Current.Response.End();

}

}


How to show line breaks in an asp.net label.

When data is collected via a TextBox and line breaks are provided in the input, this is a way to show those breaks in a label. This was surprisingly difficult to figure out for me, so hopefully this will save someone some time.

public string WrappableText(string source)
{
string nwln = Environment.NewLine;
return "

" +
source.Replace(nwln + nwln, "

")
.Replace(nwln, "
") + "

";
}

How to retrieve a page content with Asp.NET

I use the method below to retrieve a page's content. I often use this technique to send invoices or receipts. You can create any page, then call this function to pull it into a string and send it as the email body.

public string GetUrl(string path)
{


using (StringWriter writer = new StringWriter())
{

Server.Execute(path, writer);


string html = writer.ToString();
path = "http://" + Request.ServerVariables["SERVER_NAME"] + ResolveUrl(path);
path = path.Substring(0, path.LastIndexOf("/") + 1);
//this is here so the css references from the theme are absolute paths
html.Replace("\"../", "\"" + path + "../");






return html;
}

}

Friday, November 16, 2007

Searching with the WSSListProvider for Sharepoint

The WSSListProvider is a provider build on the Asp.NET provider framework that eases accessibility and simplifies the programming required to access list data in SharePoint. This is the basis for the SharePoint membership, profile, sitemap and role providers based on SharePoint list data. If you interested in any of these providers, please contact me.

This post explain in brief how to search using the WSSListProvider Sharepoint list provider.
It takes a hashtable of string pairs of search terms. Right now it only does exact "Text" based searching. Adding multiple items to the hashtable results in an "and" statement, all search items must be found.
The result is an xml root node containing no, one, or multiple rows of data. In each row, the data is stored in the attributes.


//This will search for "chris" in the "Username" column of the "+Abstract" list.
Hashtable search = new Hashtable();
search.Add("Username", "chris");
XmlNode result = WSSListManager.SearchListItems("+Abstract", search);
//Next, we can check to see how many items are in the list
//by using the Attribute "ItemCount" of the root node.
int count = int.Parse(result.Attributes["ItemCount"].Value);
//Now, based on how many rows there are, we can do various things.
if (count == 1)
{
//If there's only one row, we will select the first (and only) row
XmlNode node = result["z:row"];
//We now have access to the various Attributes of the row
//You can either access them individually...
string title = node.Attributes["Title"].Value;
//Or loop through all the attributes and use a switch statement
string temp;
bool approved;
foreach (XmlAttribute attrib in node.Attributes)
{
switch (attrib.Name)
{
case "Title":
temp = attrib.Value;
break;
case "Approved":
approved = bool.Parse(attrib.Value);
break;
default:
break;
}
}
}
else if (count > 1)
{
//Alternatively, if there is more than one row, we can
//access the data in all the rows by looping through them
foreach (XmlNode node in result)
{
//We need to check to make sure it's the right kind of node
//It injects "Whitespace" nodes at the beginning and ending of the rows returned
//Alternatively, it may be necessary to use (node.NodeType == XmlNodeType.Element)
if (node.NodeType != XmlNodeType.Whitespace)
{
//Using the same loop-through attributes code as above...
string temp;
bool approved;
foreach (XmlAttribute attrib in node.Attributes)
{
switch (attrib.Name)
{
case "Title":
temp = attrib.Value;
break;
case "Approved":
approved = bool.Parse(attrib.Value);
break;
default:
break;
}
}
}
}
}

Thursday, November 15, 2007

How to show an asp.net User Control on a Sharepoint page

  1. Create a directory to hold the user controls on the sharepoint server under C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\CONTROLTEMPLATES
  2. Move the user control into this directory, this can be uncompiled source code.
  3. Using Sharepoint designer, create a page to display the user control.
  4. Add the user control to the page you created with Sharepoint Designer the same way you would add any user control to a asp.net page.

That's it. Then you should be able to load this page in a browser and display the user control.