Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, March 20, 2011

Get files from directory (including all subdirectories)

string[] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.bmp", SearchOption.AllDirectories);

Sunday, December 19, 2010

export DataTable To Excel

static DataTable GetTable()
{
DataTable table = new DataTable(); // New data table.
table.Columns.Add("Dosage", typeof(int)); // Add five columns.
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));

table.Rows.Add(15, "Abilify", "xxx", DateTime.Now); // Add five data rows.
table.Rows.Add(40, "Accupril", "yyy", DateTime.Now);
table.Rows.Add(40, "Accutane", "zzz", DateTime.Now);
table.Rows.Add(20, "Aciphex", "zyy", DateTime.Now);
table.Rows.Add(45, "Actos", "xxxy", DateTime.Now);

return table; // Return reference.
}


private void exportDataTableToExcel(DataTable dt, string filePath)
{
// Excel file Path
string myFile = filePath;

//System.Data.DataRow dr = default(System.Data.DataRow);

int colIndex = 0;
int rowIndex = 0;

// Open the file and write the headers
StreamWriter fs = new StreamWriter(myFile, false);

fs.WriteLine("<? xml version=\"1.0\"?>");
fs.WriteLine("<?mso-application progid=\"Excel.Sheet\"?>");
fs.WriteLine("<ss:Workbook xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">");

// Create the styles for the worksheet
fs.WriteLine(" <ss:Styles>");
// Style for the column headers
fs.WriteLine(" <ss:Style ss:ID=\"1\">");
fs.WriteLine(" <ss:Font ss:Bold=\"1\" ss:Color=\"#FFFFFF\"/>");
fs.WriteLine(" <ss:Alignment ss:Horizontal=\"Center\" ss:Vertical=\"Center\" " + "ss:WrapText=\"1\"/>");
fs.WriteLine(" <ss:Interior ss:Color=\"#254117\" ss:Pattern=\"Solid\"/>");
fs.WriteLine(" </ss:Style>");
// Style for the column information
fs.WriteLine(" <ss:Style ss:ID=\"2\">");
fs.WriteLine(" <ss:Alignment ss:Vertical=\"Center\" ss:WrapText=\"1\"/>");
fs.WriteLine(" </ss:Style>");
// Style for the column headers
fs.WriteLine(" <ss:Style ss:ID=\"3\">");
fs.WriteLine(" <ss:Font ss:Bold=\"1\" ss:Color=\"#FFFFFF\"/>");
fs.WriteLine(" <ss:Alignment ss:Horizontal=\"Center\" ss:Vertical=\"Center\" " + "ss:WrapText=\"1\"/>");
fs.WriteLine(" <ss:Interior ss:Color=\"#736AFF\" ss:Pattern=\"Solid\"/>");
fs.WriteLine(" </ss:Style>");
fs.WriteLine(" </ss:Styles>");

// Write the worksheet contents
fs.WriteLine("<ss:Worksheet ss:Name=\"Sheet1\">");
fs.WriteLine(" <ss:Table>");

fs.WriteLine(" <ss:Row>");
foreach (DataColumn dc in dt.Columns)
{
fs.WriteLine(string.Format(" <ss:Cell ss:StyleID=\"1\">" + "<ss:Data ss:Type=\"String\">{0}</ss:Data></ss:Cell>", dc.ColumnName ));
}

fs.WriteLine(" </ss:Row>");

object cellText = null;

// Write contents for each cell
foreach (DataRow dr in dt.Rows)
{
rowIndex = rowIndex + 1;
colIndex = 0;
fs.WriteLine(" <ss:Row>");
foreach (DataColumn dc in dt.Columns)
{
cellText = dr[dc];
// Check for null cell and change it to empty to avoid error
if (cellText == null ) cellText = "";
fs.WriteLine(string.Format(" <ss:Cell ss:StyleID=\"2\">" +
"<ss:Data ss:Type=\"String\">{0}</ss:Data></ss:Cell>", cellText));
colIndex = colIndex + 1;
}
fs.WriteLine(" </ss:Row>");
}

fs.WriteLine(" <ss:Row>");
fs.WriteLine(" </ss:Row>");

// Close up the document
fs.WriteLine(" </ss:Table>");
fs.WriteLine("</ss:Worksheet>");
fs.WriteLine("</ss:Workbook>");
fs.Close();
}

Example:
exportDataTableToExcel (GetTable(),"C:\\PatientDetails.xls");
will write the content of data table with Formatting Styles.

Thursday, February 18, 2010

Sort a enumerable list

// Create a simple example list
List TestList = new List();

TestList.Add("Venezuela");
TestList.Add("Norway");
TestList.Add("Finland");
TestList.Add("Brazil");
TestList.Add("Germany");
TestList.Add("Australia");
TestList.Add("Fakeland");

// Sort the list by A-Z
TestList.Sort(delegate(string A, string B) { return A.CompareTo(B);});

// Print out the test list
foreach (string Country in TestList)
Console.WriteLine(Country);

/*
Results:

Australia
Brazil
Finland
Germany
Norway
Venezuela
*/

Get URL Parameters using LINQ

Dictionary result = new Dictionary();

String urlString = "http://www.jwize.com?param1=valu1¶m2=value2";

var query = from match in urlString.Split('?').Where(m => m.Contains('='))
.SelectMany(pr => pr.Split('&'))
where match.Contains('=')
select new KeyValuePair(
match.Split('=')[0],
match.Split('=')[1]);
query.ToList().ForEach(kvp => result.Add(kvp.Key, kvp.Value));

ASP.Net Page to Return an Image from an SQL

protected void Page_Load(object sender, EventArgs e)
{
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["ProductCatalogueConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
string blobId = Request.QueryString["ID"];
if (!string.IsNullOrEmpty(blobId))
{
string cmdText = "select A.blob from Core.Attachment A where A.AttachmentID = '" + blobId + "'";
conn.Open();
SqlCommand cmd = new SqlCommand(cmdText, conn);
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.Read())
{
byte[] imgBytes = (byte[])reader["blob"];
Response.ContentType = "image/jpeg";
Response.BinaryWrite(imgBytes);
}
}
}

GridView sorting/Paging

OnSorting="gvName_Sorting"
OnPageIndexChanging="gvName_PageIndexChanging"

protected void gvName_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvName.PageIndex = e.NewPageIndex;
BindEvents();
}


protected void gvName_Sorting(object sender, GridViewSortEventArgs e)
{
GridViewSortExpression = e.SortExpression;
SetSortDirection();
BindEvents();
}

protected void BindEvents()
{
DataView dvName = new DataView();

dvName.Sort = GridViewSortExpression + " " + GridViewSortDirection;
dvName.DataSource = dvEvents;
dvName.DataBind();
}

private string GridViewSortDirection
{
get { return ViewState["SortDirection"] as string ?? "DESC"; }
set { ViewState["SortDirection"] = value; }
}

private string GridViewSortExpression
{
get { return ViewState["SortExpression"] as string ?? "DEFAULT SORT COLUMN"; }
set { ViewState["SortExpression"] = value; }
}

private void SetSortDirection()
{
GridViewSortDirection = (GridViewSortDirection == "DESC") ? "ASC" : "DESC";
}

Datatable/Dataview stuff

DataView dvName = dtName.DefaultView;
dvName.Sort = "Column ASC";

foreach (DataRowView drv in dvName)
{
drv["Column"]
}

DataTable dtTable = new DataTable();
foreach (DataRow dr in dtTable)
{
dr["Column"]
}


DataTable dtName = new DataTable();

DataView dvName = dtName.DefaultView;
dvName.RowFilter = "ID = " + intID
dvName.Sort = "Date DESC";

DataTable dtResults = new DataTable();
dtResults.Columns.Add(new DataColumn("ID", System.Type.GetType("System.String")));
dtResults.Columns.Add(new DataColumn("Title", System.Type.GetType("System.String")));
dtResults.Columns.Add(new DataColumn("Date", System.Type.GetType("System.DateTime")));

DataRow drResults = dtResults.NewRow();

drResults["ID"] = id;
drResults["Title"] = title;
drResults["Date"] = Convert.ToDateTime(date);

dtResults.Rows.Add(drResults);

.Net List Sorting with Lambda Functions

private static void sortArray()
{
List liste = new List();
liste.Add(new TestKlasse() { X = 2, Y = 8 });
liste.Add(new TestKlasse() { X = 0, Y = 10 });
liste.Add(new TestKlasse() { X = 1, Y = 9 });
liste.Add(new TestKlasse() { X = 3, Y = 7 });
// with delegate
liste.Sort(delegate(TestKlasse a, TestKlasse b) { return a.Y.CompareTo(b.Y); });
liste.ForEach(delegate(TestKlasse tk){Console.WriteLine("X {0}, Y {1}",tk.X,tk.Y);});
// with lambda function
liste.Sort((a, b) => a.X.CompareTo(b.X));
liste.ForEach(delegate(TestKlasse tk) { Console.WriteLine("X {0}, Y {1}", tk.X, tk.Y); });
}

Simple Delegate Example

using System;
namespace DelegateTest
{
public delegate void TestDelegate(string message);

class Program
{
public static void Display(string message)
{
Console.WriteLine("");
Console.WriteLine("The string entered is : " + message);
}

static void Main(string[] args)
{
//-- Instantiate the delegate
TestDelegate t = new TestDelegate(Display);

//-- Input some text
Console.WriteLine("Please enter a string:");

string message = Console.ReadLine();

//-- Invoke the delegate
t(message);

Console.ReadLine();
}
}
}

Aspx Load User Control with Params

private UserControl LoadControl(string UserControlPath, params object[] constructorParameters)
{
// add this to aspx page that needs to load a .ascx control
// http://www.effegidev.com/post/WebUserControls-and-Parameters.aspx
List constParamTypes = new List();
foreach (object constParam in constructorParameters)
{
constParamTypes.Add(constParam.GetType());
}
UserControl ctl = Page.LoadControl(UserControlPath) as UserControl;
// Find the relevant constructor
ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(constParamTypes.ToArray());
//And then call the relevant constructor
if (constructor == null)
{
throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType.ToString());
}
else
{
constructor.Invoke(ctl, constructorParameters);
}
// Finally return the fully initialized UC
return ctl;
}

Date Taken EXIF Data for a Picture

///
/// Returns the EXIF Image Data of the Date Taken.
///

/// Image (If based on a file use Image.FromFile(f);)
/// Date Taken or Null if Unavailable
public static DateTime? DateTaken(Image getImage)
{
int DateTakenValue = 0x9003; //36867;

if (!getImage.PropertyIdList.Contains(DateTakenValue))
return null;

string dateTakenTag = System.Text.Encoding.ASCII.GetString(getImage.GetPropertyItem(DateTakenValue).Value);

string[] parts = dateTakenTag.Split(':', ' ');
int year = int.Parse(parts[0]);
int month = int.Parse(parts[1]);
int day = int.Parse(parts[2]);
int hour = int.Parse(parts[3]);
int minute = int.Parse(parts[4]);
int second = int.Parse(parts[5]);

return new DateTime(year, month, day, hour, minute, second);
}

Friday, January 15, 2010

Anonymous methods in C#

static void AddUniqe(Item item, List list)
{
int offs = list.FindIndex(delegate(Item i) { return i.id == item.id; });
if (offs >= 0)
list[offs] = item;
else
list.Add(item);
}

Wednesday, July 08, 2009

draw sine wave on Bitmap

string filename = @"C:\0\test.bmp";
int width = 640;

int height = 480;
Bitmap b = new Bitmap(width, height);

for (int i = 0; i < width; i++)
{
int y = (int)((Math.Sin((double)i*2.0*Math.PI/width )+1.0)*(height-1)/2.0);
b.SetPixel(i, y, Color.Black);
}

b.Save(filename);

Sunday, March 15, 2009

Conditional("DEBUG")

#if defined( DEBUG) in C# - use [Conditional("DEBUG")]


System.Diagnostics.Debug uses [Conditional("DEBUG")].

ILDASM.EXE shows that no code is generated.

Copy this code and paste it in your HTML

[Conditional("DEBUG")]
private static void debugtest()
{
...
}

Tuesday, February 10, 2009

Cache

Cache.Insert("KeyValue", someValue, null, DateTime.Now.AddMinutes(15), System.Web.Caching.Cache.NoSlidingExpiration);

Thursday, May 08, 2008

more SQL

// This example needs the
// System.Data.SqlClient library

#region Building the connection string

string Server = "localhost";
string Username = "my_username";
string Password = "my_password";
string Database = "my_database";

string ConnectionString = "Data Source=" + Server + ";";
ConnectionString += "User ID=" + Username + ";";
ConnectionString += "Password=" + Password + ";";
ConnectionString += "Initial Catalog=" + Database;

#endregion


#region Try to establish a connection to the database

SqlConnection SQLConnection = new SqlConnection();

try
{
SQLConnection.ConnectionString = ConnectionString;
SQLConnection.Open();

// You can get the server version
// SQLConnection.ServerVersion
}
catch (Exception Ex)
{
// Try to close the connection
if (SQLConnection != null)
SQLConnection.Dispose();

// Create a (useful) error message
string ErrorMessage = "A error occurred while trying to connect to the server.";
ErrorMessage += Environment.NewLine;
ErrorMessage += Environment.NewLine;
ErrorMessage += Ex.Message;

// Show error message (this = the parent Form object)
MessageBox.Show(this, ErrorMessage, "Connection error", MessageBoxButtons.OK, MessageBoxIcon.Error);

// Stop here
return;
}

#endregion


#region Execute a SQL query

string SQLStatement = "SELECT * FROM ExampleTable";

// Create a SqlDataAdapter to get the results as DataTable
SqlDataAdapter SQLDataAdapter = new SqlDataAdapter(SQLStatement, SQLConnection);

// Create a new DataTable
DataTable dtResult = new DataTable();

// Fill the DataTable with the result of the SQL statement
SQLDataAdapter.Fill(dtResult);

// Loop through all entries
foreach (DataRow drRow in dtResult.Rows)
{
// Show a message box with the content of
// the "Name" column
MessageBox.Show(drRow["Name"].ToString());
}

// We don't need the data adapter any more
SQLDataAdapter.Dispose();

#endregion


#region Close the database link

SQLConnection.Close();
SQLConnection.Dispose();

#endregion

Friday, April 18, 2008

SQLDataReader

public static SqlDataReader Title()
{
SqlConnection connection = ConnectionManager.GetConnection();

var command = new SqlCommand("StoredProcedure", connection);

command.CommandType = CommandType.StoredProcedure;

SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);

return reader;
}

Saturday, January 19, 2008

Linear interpolation, C#

static double interpolate( double x0, double y0, double x1, double y1, double x )
{
return y0*(x - x1)/(x0 - x1) + y1*(x - x0)/(x1 - x0);
}

Thursday, March 08, 2007

state abbreviations list (Dictionary)

Dictionary stateabbrs = new Dictionary();

stateabbrs.Add("Alabama","AL");
stateabbrs.Add("Alaska","AK");
stateabbrs.Add("Arizona","AZ");
stateabbrs.Add("Arkansas","AR");
stateabbrs.Add("California","CA");
stateabbrs.Add("Colorado","CO");
stateabbrs.Add("Connecticut","CT");
stateabbrs.Add("Delaware","DE");
stateabbrs.Add("Florida","FL");
stateabbrs.Add("Georgia","GA");
stateabbrs.Add("Hawaii","HI");
stateabbrs.Add("Idaho","ID");
stateabbrs.Add("Illinois","IL");
stateabbrs.Add("Indiana","IN");
stateabbrs.Add("Iowa","IA");
stateabbrs.Add("Kansas","KS");
stateabbrs.Add("Kentucky","KY");
stateabbrs.Add("Louisiana","LA");
stateabbrs.Add("Maine","ME");
stateabbrs.Add("Maryland","MD");
stateabbrs.Add("Massachusetts","MA");
stateabbrs.Add("Michigan","MI");
stateabbrs.Add("Minnesota","MN");
stateabbrs.Add("Mississippi","MS");
stateabbrs.Add("Missouri","MO");
stateabbrs.Add("Montana","MT");
stateabbrs.Add("Nebraska","NE");
stateabbrs.Add("Nevada","NV");
stateabbrs.Add("New Hampshire","NH");
stateabbrs.Add("New Jersey","NJ");
stateabbrs.Add("New Mexico","NM");
stateabbrs.Add("New York","NY");
stateabbrs.Add("North Carolina","NC");
stateabbrs.Add("North Dakota","ND");
stateabbrs.Add("Ohio","OH");
stateabbrs.Add("Oklahoma","OK");
stateabbrs.Add("Oregon","OR");
stateabbrs.Add("Pennsylvania","PA");
stateabbrs.Add("Rhode Island","RI");
stateabbrs.Add("South Carolina","SC");
stateabbrs.Add("South Dakota","SD");
stateabbrs.Add("Tennessee","TN");
stateabbrs.Add("Texas","TX");
stateabbrs.Add("Utah","UT");
stateabbrs.Add("Vermont","VT");
stateabbrs.Add("Virginia","VA");
stateabbrs.Add("Washington","WA");
stateabbrs.Add("West Virginia","WV");
stateabbrs.Add("Wisconsin","WI");
stateabbrs.Add("Wyoming","WY");