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.

Wednesday, December 08, 2010

AJAX Database Example

JavaScript:
function showCustomer(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getcustomer.asp?q="+str,true);
xmlhttp.send();
}


======================
ASP:
<%
response.expires=-1
sql="SELECT * FROM CUSTOMERS WHERE CUSTOMERID="
sql=sql & "'" & request.querystring("q") & "'"

set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
set rs=Server.CreateObject("ADODB.recordset")
rs.Open sql,conn

response.write("<table>")
do until rs.EOF
  for each x in rs.Fields
    response.write("<tr><td><b>" & x.name & "</b></td>")
    response.write("<td>" & x.value & "</td></tr>")
  next
  rs.MoveNext
loop
response.write("</table>")
%>

http://stackoverflow.com

http://stackoverflow.com

Hosted jQuery

head
script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
/script
/head

or

head
script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
/script
/head

SQL (Structured Query Language) in one page

 
Contents:
    Review: FAQ;
    Table of contents:
Database Manipulation (CREATE, DROP DATABASE),
Table Manipulation (CREATE, ALTER, DROP TABLE, Data Types),
Index Manipulation (CREATE, DROP INDEX),
Data Manipulation (INSERT, UPDATE, DELETE, TRUNCATE TABLE),
Select (SELECT, FROM, WHERE, ORDER BY, GROUP BY, HAVING, Operators,
Aggregate functions)
, AliasJoinUNIONSELECT INTO/INCREATE VIEW;
    Similar Sites:
MANUALCheat sheetsHTMLCSSXMLDTDJavaScriptW3C DOMSQL,
SSITell a friendFree IconsItlibitum, Corp..

 

All Javascript in one page


Contents:
    Review: 
ReviewAllocationSimple Examples;
    JavaScript Language: 
Values, Data type conversion, Variables, Literals, Expressions, Operators, Statements, Functions, Built-in Functions, Objects, Built-in Objects, Event;

    Built-in JavaScript Objects:
Root (Root Properties, Root Methods),
Array (Array Description, Array Properties, Array Methods),
Boolean (Boolean Description),
Data (Data Description,Data Methods),
Function (Function Description),
Image (Image Description,Image Properties),
Math (Math Description, Math Properties, Math Methods),
Number (Number Description,Number Properties),
String (String Description,String Properties,String Methods);
    Other: Other;
    Similar Sites: 
MANUAL, Cheat sheets, HTML, CSS, XML, DTD, JavaScript, W3C DOM, SQL, SSI, Tell a friend, Free Icons, Itlibitum, Corp..

Friday, April 16, 2010

disable OGA or KB949810 notifications

RUN or from a CMD prompt

MsiExec.exe /X{B2544A03-10D0-4E5E-BA69-0362FFC20D18}

this will force it to uninstall it self (KB949810)

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
*/

Simple XmlSerializer

// This is the test class we want to
// serialize:
[Serializable()]
public class TestClass
{
private string someString;
public string SomeString
{
get { return someString; }
set { someString = value; }
}

private List settings = new List();
public List Settings
{
get { return settings; }
set { settings = value; }
}

// These will be ignored
[NonSerialized()]
private int willBeIgnored1 = 1;
private int willBeIgnored2 = 1;

}

// Example code

// This example requires:
// using System.Xml.Serialization;
// using System.IO;

// Create a new instance of the test class
TestClass TestObj = new TestClass();

// Set some dummy values
TestObj.SomeString = "foo";

TestObj.Settings.Add("A");
TestObj.Settings.Add("B");
TestObj.Settings.Add("C");


#region Save the object

// Create a new XmlSerializer instance with the type of the test class
XmlSerializer SerializerObj = new XmlSerializer(typeof(TestClass));

// Create a new file stream to write the serialized object to a file
TextWriter WriteFileStream = new StreamWriter(@"C:\test.xml");
SerializerObj.Serialize(WriteFileStream, TestObj);

// Cleanup
WriteFileStream.Close();

#endregion


/*
The test.xml file will look like this:



foo

A
B
C


*/

#region Load the object

// Create a new file stream for reading the XML file
FileStream ReadFileStream = new FileStream(@"C:\test.xml", FileMode.Open, FileAccess.Read, FileShare.Read);

// Load the object saved above by using the Deserialize function
TestClass LoadedObj = (TestClass)SerializerObj.Deserialize(ReadFileStream);

// Cleanup
ReadFileStream.Close();

#endregion


// Test the new loaded object:
MessageBox.Show(LoadedObj.SomeString);

foreach (string Setting in LoadedObj.Settings)
MessageBox.Show(Setting);

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

Classic DB Call returns DataSet

public String DKConnectionString = "Data Source=LDI-SQL;Initial Catalog=test_db;User Id=sa;Password=admin;";
public DataSet DKDataSet = new DataSet();

private DataSet RunQuery(string queryString)
{
SqlConnection DKConnection = new SqlConnection(this.DKConnectionString);
SqlDataAdapter DKAdapter = new SqlDataAdapter();
DKDataSet = new DataSet();
DKAdapter.SelectCommand = new SqlCommand(queryString, DKConnection);
DKAdapter.Fill(DKDataSet);
DKConnection.Close();

return DKDataSet;
}

private DataSet GetEmployeeByID(int EmployeeID)
{
String SQL = string.Format(
@"SELECT EmployeeID,
FirstName,
LastName,
DoB,
Address,
City,
State,
ZipCode,
PhoneNumber,
EmailAddress,
Salary,
e.DepartmentID,
DepartmentName
FROM Employees e, Departments d
WHERE e.DepartmentID = d.DepartmentID
AND e.EmployeeID = {0};", EmployeeID);

DKDataSet = RunQuery(SQL);
return DKDataSet;
}

public DataSet InitEmployee(int EmployeeID)
{
DataSet InitMasterDS = new DataSet();
String SQL = string.Format(@"SELECT CustomerID,
CustomerName,
Address,
City,
State,
ZipCode,
Phone,
AccountManagerID
FROM Customers
WHERE AccountManagerID = {0}", EmployeeID);

InitMasterDS.Tables.Add(this.GetEmployeeByID(EmployeeID).Tables[0].Copy());
InitMasterDS.Tables[0].TableName = "Employee";
DKDataSet = RunQuery(SQL);
InitMasterDS.Tables.Add(DKDataSet.Tables[0].Copy());
InitMasterDS.Tables[1].TableName = "Customers";

return InitMasterDS;
}

ASP.NET 2.0 RSS Feed Generator

Generates an RSS XML feed from a SQL stored procedure.

Save below as feedname.aspx, modify stored procedure information to match and run. No seperate markup or cs file necessary, self contained.

This was created from a combination of articles found online. RSS Code originally from: http://www.geekpedia.com/tutorial157_Create-an-RSS-feed-using-ASP.NET-2.0.html

C# Left code from: http://www.csharphelp.com/archives4/archive616.html

<%@ Page Language="C#" %>
<%@ OutputCache Duration="120" VaryByParam="Group" %>


public static string Left(string param, int length)
{
//we start at 0 since we want to get the characters starting from the
//left and with the specified lenght and assign it to a variable
string result = param.Substring(0, length);
//return the result of the operation
return result;
}

protected void Page_Load(object sender, EventArgs e)
{
// Clear any previous output from the buffer
Response.Clear();
Response.ContentType = "text/xml";
System.Xml.XmlTextWriter xtwFeed = new System.Xml.XmlTextWriter(Response.OutputStream, Encoding.UTF8);
xtwFeed.WriteStartDocument();

// The mandatory rss tag
xtwFeed.WriteStartElement("rss");
xtwFeed.WriteAttributeString("version", "2.0");

// The channel tag contains RSS feed details
xtwFeed.WriteStartElement("channel");
xtwFeed.WriteElementString("title", "The Messenger - TransamericaReinsurance.com RSS Feed");
xtwFeed.WriteElementString("link", "http://www.transamericareinsurance.com");
xtwFeed.WriteElementString("description", "Knowledge. Experience. Performance. The Power of Insight.");
xtwFeed.WriteElementString("copyright", "Copyright 2007 Transamerica Occidental Life Insurance Company");

// Objects needed for connecting to the SQL database
System.Data.SqlClient.SqlConnection SqlCon;
System.Data.SqlClient.SqlCommand SqlCom;
System.Data.SqlClient.SqlDataReader SqlDR;

// Edit to match your connection string
SqlCon = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["TARe_DBConn"].ToString());

// Edit to match your stored procedure or SQL command
SqlCom = new System.Data.SqlClient.SqlCommand("sproc_RSSFeeds", SqlCon);
SqlCom.Parameters.Add(new System.Data.SqlClient.SqlParameter("@feedName", "messenger"));
SqlCom.CommandType = System.Data.CommandType.StoredProcedure;

SqlCon.Open();

SqlDR = SqlCom.ExecuteReader();

// Loop through the content of the database and add them to the RSS feed
while (SqlDR.Read())
{
xtwFeed.WriteStartElement("item");
xtwFeed.WriteElementString("title", SqlDR["Title"].ToString());
xtwFeed.WriteElementString("description", Left(SqlDR["Description"].ToString(), 250)+"...");
xtwFeed.WriteElementString("link", "http://cnchnw9321/Media/media_associateArticle.aspx?id=" + SqlDR["ID"]);
xtwFeed.WriteElementString("pubDate", SqlDR["Date"].ToString());
xtwFeed.WriteEndElement();
}

SqlDR.Close();
SqlCon.Close();

// Close all tags
xtwFeed.WriteEndElement();
xtwFeed.WriteEndElement();
xtwFeed.WriteEndDocument();
xtwFeed.Flush();
xtwFeed.Close();
Response.End();
}

SendMail

public static string SendMail(string from, string to, string subject, string body, string smtp)
{
// Create new MailMessage Object
MailMessage message = new MailMessage(from, to, subject, body);

//message.Bcc.Add("someone@tobcc.com");
message.IsBodyHtml = true;

// Create new SmtpClient Object
SmtpClient mailClient = new SmtpClient(smtp, 25);

try
{
// Send eMail and return 1 if successful
// otherwise return error message
mailClient.Send(message);
return "1";
}
catch (System.Net.Mail.SmtpException e)
{
// create or append errors to a log file
CreateLogFiles.CreateLogFiles Err = new CreateLogFiles.CreateLogFiles();
Err.ErrorLog(System.Web.HttpContext.Current.Server.MapPath("/logs/ErrorLog.log"), e.InnerException.Message);
return e.InnerException.Message;
}
}

Email from your GMAIL account using ASP.Net

using System.Web.Mail;
using System;
public class MailSender
{
public static bool SendEmail(
string pGmailEmail,
string pGmailPassword,
string pTo,
string pSubject,
string pBody,
System.Web.Mail.MailFormat pFormat,
string pAttachmentPath)
{
try
{
System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver","smtp.gmail.com");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport","465");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing","2");
//send using: cdoSendUsingPort, value 2, for sending the message using the network.
//smtp authenticate: Specifies the mechanism used when authenticating to an SMTP
//service over the network. Possible values are:
//- cdoAnonymous, value 0. Do not authenticate.
//- cdoBasic, value 1. Use basic clear-text authentication.
//When using this option you have to provide the user name and password
//through the sendusername and sendpassword fields.
//- cdoNTLM, value 2. The current process security context is used to
// authenticate with the service.
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate","1");
//Use 0 for anonymous
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername",pGmailEmail);
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword",pGmailPassword);
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl","true");
myMail.From = pGmailEmail;
myMail.To = pTo;
myMail.Subject = pSubject;
myMail.BodyFormat = pFormat;
myMail.Body = pBody;
if (pAttachmentPath.Trim() != "")
{
MailAttachment MyAttachment = new MailAttachment(pAttachmentPath);
myMail.Attachments.Add(MyAttachment);
myMail.Priority = System.Web.Mail.MailPriority.High;
}

System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
System.Web.Mail.SmtpMail.Send(myMail);
return true;
}
catch (Exception ex)
{
throw;
}
}
}

//Example usage of this class
EmailLib.SendEmail.SendEmail("your_gmail_id",
"your_gmail_password",
"to_email@anydomain.com",
"This is email subject" ,
"This is email body",
Web.Mail.MailFormat.Text,
"Physical path to your Attachment")

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

Output Date as SQL / ISO String YYYY-MM-DD

Console.WriteLine(DateTime.Now.GetDateTimeFormats()[5]);

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

?? operator

string foo = null;
return foo ?? "bar"; // returns bar

string foo = "dummy";
return foo ?? "bar"; // returns dummy

LINQ Conditional Count

MyList.Count(x => x.Product == "Apple")

LINQ Conditional Sum

MyList.Where(x => x.Product == "Apple").Sum(x => x.TotalSales)

evaluation of LINQ expression using .ToArray()

IEnumerable windowsFiles = System.IO.Directory.GetFiles(Environment.GetEnvironmentVariable("SystemRoot"), "*.INF", System.IO.SearchOption.AllDirectories);

IEnumerable files =
(
from f in windowsFiles
where System.IO.File.ReadAllText(f).Contains(searchText)
select System.IO.Path.GetFileNameWithoutExtension(f)
).ToArray(); // ToArray forces immediate evaluation.

Formatting DateTime

using System;
using System.Collections.Generic;
using System.Text;

namespace DateTimeParse
{
class DateConv
{
static void Main(string[] args)
{
// Current Date/Time
Console.WriteLine("Using Now Property --> " + DateTime.Now);
Console.WriteLine("Using Today Property --> " + DateTime.Today);

// DateTime in a text format
string datetimeString = "6/2/2006 12:00:00 PM";
Console.WriteLine("Text Formatted Date and Time --> " + datetimeString);

// Convert the text DateTime to a DateTime format
// This is just to show the syntax involved in a text to DateTime conversion
DateTime convertedDateTime = DateTime.Parse(datetimeString);
Console.WriteLine("Converted to DateTime --> " + convertedDateTime);

// Extract just the date portion of the DateTime variable
string justDate = convertedDateTime.Date.ToShortDateString();
Console.WriteLine("Extract Date Only: --> " + justDate);

// Once the variable is in DateTime format - several different variations
Console.WriteLine("d: {0:d}", convertedDateTime);
Console.WriteLine("D: {0:D}", convertedDateTime);
Console.WriteLine("f: {0:f}", convertedDateTime);
Console.WriteLine("F: {0:F}", convertedDateTime);
Console.WriteLine("g: {0:g}", convertedDateTime);
Console.WriteLine("G: {0:G}", convertedDateTime);
Console.WriteLine("m: {0:m}", convertedDateTime);
Console.WriteLine("M: {0:M}", convertedDateTime);
Console.WriteLine("r: {0:r}", convertedDateTime);
Console.WriteLine("R: {0:R}", convertedDateTime);
Console.WriteLine("s: {0:s}", convertedDateTime);
Console.WriteLine("t: {0:t}", convertedDateTime);
Console.WriteLine("T: {0:T}", convertedDateTime);
Console.WriteLine("u: {0:u}", convertedDateTime);
Console.WriteLine("U: {0:U}", convertedDateTime);
Console.WriteLine("y: {0:y}", convertedDateTime);
Console.WriteLine("Y: {0:Y}", convertedDateTime);
}
}

Update SQL from a DropDownList dynamically created in a GridView

protected void DropDownSelectedIndexChanged(object sender, EventArgs e)
{
//http://programming.top54u.com/post/GridView-DropDownList-Update-SelectedValue-All-At-Once.aspx
//http://www.codeproject.com/KB/webservices/db_values_dropdownlist.aspx

DropDownList d = sender as DropDownList;
if (d == null) return;

//grab row that contains the drop down list
GridViewRow row = (GridViewRow)d.NamingContainer;

//pull data needed from the row (in this case we want the ID for the row)
object ID = gridEntries.DataKeys[row.RowIndex].Values["tableID"];

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString);
conn.Open();

SqlCommand c = new SqlCommand("UPDATE table SET value = @v WHERE tableID = @id", conn);

SqlParameter p = c.Parameters.Add("@id", SqlDbType.Int);
p.Value = Convert.ToInt32(ID);
p = c.Parameters.Add("@v", SqlDbType.Int);
p.Value = Convert.ToInt32(d.SelectedValue);

c.ExecuteNonQuery();

//databind the gridview to reflect new data.
gridEntries.DataBind();
}

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

DataBinding an Arbitrary XML String to an ASP.Net GridViev

DataSet ds = new DataSet();
string xml = GetSomeXMLFromWherever();

ds.ReadXml(new StringReader(xml), XmlReadMode.InferSchema);
GridView1.DataSource = ds;
GridView1.DataBind();

Linq2Sql - Group By Count

public List GetTotalRegisteredUserCount()
{
var qry = from aspnet_Profile profile in aspnet_Profiles
group profile by profile.Country into grp
select new {Country = grp.Key,
Count = grp.Select(x => x.Country).Distinct().Count()
};

return qry.ToList();
}

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

ASP.NET FAQs

http://www.syncfusion.com/support/kb/tag/ASP.NET

WindowsForms FAQs:
http://www.syncfusion.com/FAQ/WindowsForms/FAQ_c58c.aspx#q1010q

NET DB Connection class for MySQL

http://snipplr.com/view/24418/net-db-connection-class-for-mysql/


using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Odbc;
using System.Configuration;

public class DB_Connect
{
// GLOBAL ACCESS TO COMMAND OBJECT
public static OdbcCommand cmd = new OdbcCommand();
private OdbcDataAdapter _Adapter = new OdbcDataAdapter();
private DataSet _ds = new DataSet();
private DataTable _table = new DataTable();
private OdbcConnection _Conn = new OdbcConnection();
private OdbcDataReader _Reader;


public static object runQuery(string db, bool isProc, bool wantLastID)
{
DataTable DT = new DataTable();
string connStr = null;

//SETS THE CONNECTION STRING
if (db.ToLower() == "MPH_DEV".ToLower())
connStr = "Driver={SQL Server Native Client 10.0};Server=myserver;Database=mydb;Uid=mydb;Pwd=mydb;";
else if (db.ToLower() == "keeneye".ToLower())
connStr = "Driver={MySQL ODBC 5.1 Driver};Server=myserver;Port=3306;Database=mydb;User=myuser;Password=mypass; Option=3;";
else
return null;

//SETTING .NET CONNECTION OBJECTS
OdbcConnection conn = new OdbcConnection(connStr);
OdbcDataAdapter adapter = new OdbcDataAdapter();
DataSet ds = new DataSet();

adapter.SelectCommand = new OdbcCommand();
adapter.SelectCommand = cmd;
adapter.SelectCommand.Connection = conn;

//SPECIFYING IF THIS IS A STORED PROCEDURE
if (isProc)
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
else
adapter.SelectCommand.CommandType = CommandType.Text;

// IF THE USER WANTS THE LAST ID OF THE LAST PREVIOUS INSERT
// OR THEY WANT A DATATABLE OBJECT
if (wantLastID)
{
object rt;
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "select LAST_INSERT_ID()";
rt = Convert.ToString(cmd.ExecuteScalar());
return rt;
}
else
{
conn.Open();
adapter.Fill(ds, "getData");
DT = ds.Tables["getData"];
conn.Close();
return DT;
}



}

public DB_Connect(string DB_String)
{
_Conn.ConnectionString = ConnString(DB_String);
_Adapter.SelectCommand = new OdbcCommand();
_Adapter.SelectCommand.Connection = _Conn;

}// End Contructor DB_Connect

public DataTable Execute(String table_Name)
{
_Conn.Open();
_Adapter.Fill(_ds, table_Name);
_table = _ds.Tables[table_Name];
_Conn.Close();
return _table;

}// End execute Function

private String ConnString(string DB_Name)
{
// setup your own connection strings via if statements

if (DB_Name == null)
{

return "Nothing";
}

}// Ends the Connection String Method



#region Properties
public OdbcDataAdapter Adapter
{
get { return _Adapter; }
set { _Adapter = value; }
}
public DataSet DS
{

get { return _ds; }
set { _ds = value; }
}
public DataTable DT_Table
{

get { return _table; }
set { _table = value; }
}
public OdbcConnection Connection
{

get { return _Conn; }
set { _Conn = value; }
}
public OdbcDataReader Reader
{

get { return _Reader; }
set { _Reader = value; }
}

#endregion

//EXAMPLE ON HOW TO USE THIS CLASS

//DB_Connect.cmd = new System.Data.Odbc.OdbcCommand();
//DB_Connect.cmd.CommandText = "Insert into tbl_patient_surgical_history(patient_id,procedure_id) values(?,?)";
//DB_Connect.cmd.Parameters.AddWithValue("?patient_id", pt_id);
//DB_Connect.cmd.Parameters.AddWithValue("?procedure_id", item.Value.ToString());
//DB_Connect.runQuery("keeneye", false, false);



}// End Class DB_Connect

XML config files in WinForms

http://snipplr.com/view/24482/persisting-data-using-xml-config-files-in-winforms-saving-and-restoring-user-and-application-data/

Simple XML parsing using LINQ




The Reddest

Creating an XP Style WPF Button with Silverlight

2/20/2008


The Fattest

Flex And Yahoo Maps

2/12/2007


The Tallest

WPF Tutorial - Creating A Custom Panel Control

2/18/2008



XDocument xmlDoc = XDocument.Load("TestFile.xml");

var tutorials = from tutorial in xmlDoc.Descendants("Tutorial")
select new {
Author = tutorial.Element("Author").Value,
Title = tutorial.Element("Ttle").Value,
Date = tutorial.Element("Date").Value };

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

The difference between <%= and <%# in ASP.NET

The <%= expressions are evaluated at render time

The <%# expressions are evaluated at DataBind() time and are not evaluated at all if DataBind() is not called.

The <%# expressions can be used as properties in server-side controls. <%= expressions cannot.















Equals: <%= this.TestValue %>




Pound: <%# this.TestValue %>




Equals label:




Pound label:











//And the code behind is:

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

protected void Page_PreRenderComplete(object sender, EventArgs e)
{
// DataBind();
_testValue = "3";
}

public string TestValue
{
get { return _testValue; }
}

private string _testValue = "1";
}

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