Thursday, February 18, 2010

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