Thursday, September 24, 2009
Reverse Data Table
For Eample,
Input Data Table has the following Records,
NAME TITLE DEV_IN SCOST DCOST SOLD
-------- -------------------- -------- ---------- ---------- ----------
RAMESH HOTEL MANAGEMENT DBASE 12000 35000 4
RAMESH DEAD LEE PASCAL 99.95 4500 73
public static DataTable ReverseDataTable(DataTable dataTable)
{
DataTable table = new DataTable();
DataRow[] rowArray = dataTable.Select();
table = dataTable.Clone();
for (int i = rowArray.Length - 1; i >= 0; i--)
{
table.ImportRow(rowArray[i]);
}
return table;
}
OutPut
NAME TITLE DEV_IN SCOST DCOST SOLD
-------- -------------------- -------- ---------- ---------- ----------
RAMESH DEAD LEE PASCAL 99.95 4500 73
RAMESH HOTEL MANAGEMENT DBASE 12000 35000 4
Wednesday, September 23, 2009
Filter DataTable and Sort
{
DataTable table = new DataTable();
try
{
DataRow[] rowArray = dataTable.Select(filterQuery, sortQuery);
table = dataTable.Clone();
foreach (DataRow row in rowArray)
{
table.ImportRow(row);
}
}
catch
{
table = dataTable.Clone();
}
return table;
}
Create Excel File
{
try
{
string str = "
string str3 = "
string str4 = string.Empty;
StringBuilder builder = new StringBuilder();
foreach (DataColumn column in dataTable.Columns)
{
str3 = str3 + "
}
str3 = str3 + "
foreach (DataRow row in dataTable.Rows)
{
builder.Append("
for (int i = 0; i < dataTable.Columns.Count; i++)
{
str4 = " ";
if (!string.IsNullOrEmpty(row[i].ToString()))
{
str4 = row[i].ToString();
}
builder.Append("
}
builder.Append("
}
string s = str + str3 + builder.ToString() + str2;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.xls";
HttpContext.Current.Response.Write(s);
HttpContext.Current.Response.Flush();
return true;
}
catch
{
return false;
}
}
Tuesday, September 22, 2009
Build DataTable
{
DataTable table = new DataTable();
foreach (KeyValuePair
{
if (!table.Columns.Contains(pair.Key))
{
table.Columns.Add(pair.Key, pair.Value);
}
}
return table;
}
Add Row Number to DataTable
{
dataTable.Columns.Add("RowNumber", typeof(int));
for (int i = 0; i < dataTable.Rows.Count; i++)
{
dataTable.Rows[i]["RowNumber"] = i;
}
dataTable.AcceptChanges();
return dataTable;
}
Set DropDownt Selected Values
{
string selectedValue = string.Empty;
foreach (string selValue in selectedValues.Split(','))
{
ListItem listItem = ddlList.Items.FindByValue(selValue);
if (listItem != null)
{
listItem.Selected = true;
selectedValue += listItem.Value + ",";
}
}
return selectedValue.Trim(',');
}
Set CheckBox Selected Values
{
string selectedValue = string.Empty;
foreach (string selValue in selectedValues.Split(','))
{
ListItem listItem = chkBoxList.Items.FindByValue(selValue);
if (listItem != null)
{
listItem.Selected = true;
selectedValue += listItem.Value + ",";
}
}
return selectedValue.Trim(',');
}
Get Check Box Selected Values
{
string selectedValue = string.Empty;
foreach (ListItem listItem in chkBoxList.Items)
{
if (listItem.Selected)
selectedValue += listItem.Value + ",";
}
return selectedValue.Trim(',');
}
Read CSV File and covert to DataTable
public static DataTable ReadCSV(string filePath, DataTable csvTable)
{
//DataTable csvTable = new DataTable();
// open the file "data.csv" which is a CSV file with headers
using (CsvReader csv = new CsvReader(new StreamReader(filePath), true))
{
// missing fields will not throw an exception,
// but will instead be treated as if there was a null value
csv.MissingFieldAction = MissingFieldAction.ReplaceByNull;
// to replace by "" instead, then use the following action:
//csv.MissingFieldAction = MissingFieldAction.ReplaceByEmpty;
int fieldCount = csvTable.Columns.Count;
// this bit could be modified to fine-tune the columns
while (csv.ReadNextRecord())
{
DataRow newRow = csvTable.NewRow();
for (int i = 0; i < fieldCount; i++)
newRow[i] = csv[i] == null ? "MISSING" : csv[i];
csvTable.Rows.Add(newRow);
}
}
return csvTable;
}
Sunday, September 13, 2009
Convert DataSet to Array List
public static ArrayList DataSetToArrayList(string Columns, DataTable dataTable)
{
ArrayList output = new ArrayList();
string[] columnName = Columns.Split(',');
foreach (DataColumn row in dataTable.Columns)
{
foreach (string column in columnName)
{
if (column == row.ColumnName)
output.Add(column);
}
}
return output;
}
Join Two Data Tables
public static DataTable JoinTable(DataTable firstTable, DataTable secondTable, string firstTableKey, string secondTableKey)
{
DataTable dtResults = secondTable.Clone();
foreach (DataColumn dataColumn in firstTable.Columns)
{
if (!dtResults.Columns.Contains(dataColumn.ColumnName))
dtResults.Columns.Add(dataColumn.ColumnName, typeof(string));
}
foreach (DataRow dataRow in firstTable.Rows)
{
DataRow dtRow = dtResults.NewRow();
foreach (DataColumn dataColumn in firstTable.Columns)
{
dtRow[dataColumn.ColumnName] = dataRow[dataColumn.ColumnName].ToString();
}
foreach (DataRow finalRow in secondTable.Select("[" + secondTableKey + "] = '" + dataRow[firstTableKey].ToString() + "'"))
{
foreach (DataColumn dataColumn in secondTable.Columns)
{
dtRow[dataColumn.ColumnName] = finalRow[dataColumn.ColumnName].ToString();
}
break;
}
dtResults.Rows.Add(dtRow);
}
return dtResults;
}
Wednesday, September 9, 2009
Checking/Validation the Proper Email
private static bool isEmail(string inputEmail)
{
string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex re = new Regex(strRegex);
if (re.IsMatch(inputEmail))
return (true);
else
return (false);
}
Sort the Data Table by Column
public DataTable SortDataTableByColumn(DataTable dataTable, string sortColumnName, string sortOrder)
{
DataRow[] filteredRows;
if (!string.IsNullOrEmpty(sortColumnName))
{
if (string.IsNullOrEmpty(sortOrder))
sortOrder = "ASC";
filteredRows = dataTable.Select(string.Empty, sortColumnName + " " + sortOrder);
DataTable filteredDataTable = dataTable.Clone();
foreach (DataRow dataRow in filteredRows)
{
filteredDataTable.ImportRow(dataRow);
}
return filteredDataTable;
}
else
{
return dataTable;
}
}
Stripping the Text
public static string StripText(object textObj, int maxLength)
{
string text = string.Empty;
if (textObj != null && !string.IsNullOrEmpty(textObj.ToString()))
{
text = textObj.ToString();
if (text.Length > maxLength)
{
text = text.Remove(maxLength);
}
}
return text;
}
Format Date
public static string FormatDate(object date, string format)
{
string formattedDate = string.Empty;
if (date != null && Utility.IsDate(date.ToString()))
{
formattedDate = Convert.ToDateTime(date).ToString(format);
}
return formattedDate;
}
Trim Table
public static DataTable TrimDataTable(DataTable dataTable, int noOfRows)
{
DataRow[] dataRows = dataTable.Select();
DataTable filteredDataTable = dataTable.Clone();
for (int i = 0; i < dataRows.Length; i++)
{
filteredDataTable.ImportRow(dataRows[i]);
if (i >= noOfRows - 1)
break;
}
return filteredDataTable;
}
Read Cookie using Java Script
function ReadCookie(cookieName)
{
var theCookie = "" + document.cookie;
var
if (
return "";
var ind1 = theCookie.indexOf(';',
if (ind1 == -1)
ind1 = theCookie.length;
var val = unescape(theCookie.substring(
val = ReplaceAll(val, cookieName + "=" , "");
val = ReplaceAll(val, ";" , "");
return val;
}
function ReplaceAll(str, pcFrom, pcTo)
{
var i = str.indexOf(pcFrom);
var c = str;
while (i > -1)
{
c = c.replace(pcFrom, pcTo);
i = c.indexOf(pcFrom);
}
return c;
}
Remove Duplicate Rows in Data Table
public static DataTable RemoveDuplicateRows(DataTable dTable, string colName)
{
Hashtable hTable = new Hashtable();
ArrayList duplicateList = new ArrayList();
//Add list of all the unique item value to hashtable, which stores combination of key, value pair.
//And add duplicate item value in arraylist.
foreach (DataRow drow in dTable.Rows)
{
if (hTable.Contains(drow[colName]))
duplicateList.Add(drow);
else
hTable.Add(drow[colName], string.Empty);
}
//Removing a list of duplicate items from datatable.
foreach (DataRow dRow in duplicateList)
dTable.Rows.Remove(dRow);
//Datatable which contains unique records will be return as output.
return dTable;
}
How to Create Event Log Entry Using C#
public static void CreateEventlogEntry(EventLogSource eventLogSource, string message)
{
EventLog eventLog = new EventLog();
try
{
string eventLogName = eventLogSource.ToString();
try
{
if (!EventLog.SourceExists(eventLogName))
{
EventLog.CreateEventSource(eventLogName, "Application");
}
}
catch { }
eventLog.Source = eventLogName;
eventLog.WriteEntry(message, EventLogEntryType.Error);
}
catch { }
}
Send Mail Method
public static int SendMail(string subject, string body, string to, string from)
{
try
{
MailAddress mailto = new MailAddress(to);
MailAddress mailfrom = new MailAddress(from);
MailMessage objmail = new MailMessage(from, to, subject, body);
SmtpClient sclient = new SmtpClient();
if (ConfigurationManager.AppSettings["smtphost"] != null)
sclient.Host = ConfigurationManager.AppSettings["smtphost"].ToString();
sclient.Send(objmail);
return (1);
}
catch
{
return (0);
}
}