Thursday, February 18, 2010
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.
IEnumerable
(
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);
}
}
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();
}
{
//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();
}
}
}
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();
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();
}
{
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;
}
{
// add this to aspx page that needs to load a .ascx control
// http://www.effegidev.com/post/WebUserControls-and-Parameters.aspx
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
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
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
Subscribe to:
Posts (Atom)