Thursday, December 30, 2010
Lambda expression common syntax-CSharp
// simplest form; no types, no brackets
Func
// optional exlicit argument brackets
Func
// optional type specification when used with brackets
Func
// multiple arguments require brackets (types optional)
Func
// multiple argument with explicit types
Func
The signature of the lambda must match the signature of the delegate used (whether it is explicit, like above, or implied by the context in things like .Select(cust => cust.Name)
You can use lambdas without arguments by using an empty expression list:
// no arguments
Func
Ideally, the expression on the right hand side is exactly that; a single expression. The compiler can convert this to either a delegate or an Expression tree:
// expression tree
Expression
However; you can also use statement blocks, but this is then only usable as a delegate:
// braces for a statement body
Func
int z = x * y;
Console.WriteLine(z);
return z;
};
Note that even though the .NET 4.0 Expression trees support statement bodies, the C# 4.0 compiler doesn't do this for you, so you are still limited to simple Expression trees unless you do it "the hard way"; see my article on InfoQ for more information.
Calculate relative time
const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;
if (delta < 0)
{
return "not yet";
}
if (delta < 1 * MINUTE)
{
return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
}
if (delta < 2 * MINUTE)
{
return "a minute ago";
}
if (delta < 45 * MINUTE)
{
return ts.Minutes + " minutes ago";
}
if (delta < 90 * MINUTE)
{
return "an hour ago";
}
if (delta < 24 * HOUR)
{
return ts.Hours + " hours ago";
}
if (delta < 48 * HOUR)
{
return "yesterday";
}
if (delta < 30 * DAY)
{
return ts.Days + " days ago";
}
if (delta < 12 * MONTH)
{
int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
return months <= 1 ? "one month ago" : months + " months ago";
}
else
{
int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return years <= 1 ? "one year ago" : years + " years ago";
}
* 2 hours ago
* 3 days ago
* a month ago
Monday, November 1, 2010
Default delegate in C#
Action is a good candidate, but ThreadStart was commonly used (fairly confusingly), or MethodInvoker if you were already referencing winforms. A quick test (note, running in .NET 4.0, using just some libraries - so not exhaustive):
var qry = from asm in AppDomain.CurrentDomain.GetAssemblies()
from type in asm.GetTypes()
where type.IsSubclassOf(typeof(Delegate))
let method = type.GetMethod("Invoke")
where method != null && method.ReturnType == typeof(void)
&& method.GetParameters().Length == 0
orderby type.AssemblyQualifiedName
select type.AssemblyQualifiedName;
foreach (var name in qry) Console.WriteLine(name);
shows some more candidates:
System.Action, mscorlib...
System.CrossAppDomainDelegate, mscorlib...
System.IO.Pipes.PipeStreamImpersonationWorker, System.Core...
System.Linq.Expressions.Compiler.LambdaCompiler+WriteBack, System.Core...
System.Net.UnlockConnectionDelegate, System...
System.Runtime.Remoting.Contexts.CrossContextDelegate, mscorlib...
System.Threading.ThreadStart, mscorlib...
System.Windows.Forms.AxHost+AboutBoxDelegate, System.Windows.Forms...
System.Windows.Forms.MethodInvoker, System.Windows.Forms...
Sunday, October 17, 2010
Programmatically create a PDF in my .NET application
ReportDocument rptCust;
string sDate_time;
string sDestination_path;
CrystalDecisions.Shared.ExportOptions myExportOptions;
CrystalDecisions.Shared.DiskFileDestinationOptions File_destination;
CrystalDecisions.Shared.PdfRtfWordFormatOptions Format_options;
myExportOptions = new CrystalDecisions.Shared.ExportOptions();
File_destination = new CrystalDecisions.Shared.DiskFileDestinationOptions();
Format_options = new CrystalDecisions.Shared.PdfRtfWordFormatOptions();
sDate_time = DateTime.Now.ToString("ddMMyyyyHHmmssff");
sDestination_path = sDestination_file + sPolicy_number + sPolicy_number1 + "-" + sDate_time + ".pdf";
File_destination.DiskFileName = sDestination_path;
myExportOptions = rptCust.ExportOptions;
myExportOptions.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile;
myExportOptions.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat;
myExportOptions.DestinationOptions = File_destination;
myExportOptions.FormatOptions = Format_options;
rptCust.Export();
Convert vb to c sharp project to C# 4.0
2. add the 4 class files that you have,
3. run them each through the VB->c# translator you linked to originally,
4. dump the VB logging stuff and add in log4net
5. turn the Windows Scripting stuff from VB into C# (I think your problem with this is that the translator above is flipping out on the types of WindowsScripting Host stuff)
6. Compile and test.
With luck, this will take you a couple of hours. With bad luck, it depends on what the project actually does and that will determine how long.
I wish you good luck.
If you decide to go this route, be liberal about commenting out huge parts of code and compiling and working on eliminating compiling errors first. I'll try to keep an eye out to help you with any other specific questions that I see come across the front page.
Saturday, October 16, 2010
Add delegate to interface c#
public delegate void UpdateStatusEventHandler(string status);
public delegate void StartedEventHandler();
public interface IMyInterface
{
event UpdateStatusEventHandler StatusUpdated;
event StartedEventHandler Started;
}
The implementation won't (and shouldn't) redeclare the delegate type, any more than it would redeclare any other type used in an interface.
Saturday, October 2, 2010
c# DateTime, Trim without converting to string
Example1
var dt = DateTime.Now; // 10/1/2010 10:44:24 AM
var dateOnly = dt.Date; // 10/1/2010 12:00:00 AMExample2DateTime now = DateTime.Now;
DateTime today = now.Date;Example3DateTime now = DateTime.Now;
DateTime today = new DateTime(now.Year, now.Month, now.Day);
Reading Email using Pop3 in C#
Following code taken from POP3 Tutorial page and links would help you:
//
// create client, connect and log in
Pop3 client = new Pop3();
client.Connect("pop3.example.org");
client.Login("username", "password");
// get message list
Pop3MessageCollection list = client.GetMessageList();
if (list.Count == 0)
{
Console.WriteLine("There are no messages in the mailbox.");
}
else
{
// download the first message
MailMessage message = client.GetMailMessage(list[0].SequenceNumber);
...
}
client.Disconnect();
Create Excel (.XLS and .XLSX) file from C#
//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
//Open a DB connection (in this example with OleDB)
OleDbConnection con = new OleDbConnection(dbConnectionString);
con.Open();
//Create a query and fill the data table with the data from the DB
string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();
adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();
//Add the table to the data set
ds.Tables.Add(dt);
//Here's the easy part. Create the Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);
Building JSON object to send to an AJAX WebService
[WebMethod]
public Response ValidateAddress(Request request)
{
return new test_AddressValidation().GenerateResponse(
test_AddressValidation.ResponseType.Ambiguous);
}
...
public class Request
{
public Address Address;
}
public class Address
{
public string Address1;
public string Address2;
public string City;
public string State;
public string Zip;
public AddressClassification AddressClassification;
}
public class AddressClassification
{
public int Code;
public string Description;
}
Simpler way to Serializing objects in C# 4.0
[Serializable]
public class ContentModel
{
public int ContentId { get; set; }
public string HeaderRendered { get; set; }
public ContentModel()
{
ContentId = 0;
HeaderRendered = string.Empty;
}
public ContentModel(SerializationInfo info, StreamingContext ctxt)
{
ContentId = (int)info.GetValue("ContentId", typeof(int));
HeaderRendered = (string)info.GetValue("HeaderRendered", typeof(string));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("ContentId ", ContentId);
info.AddValue("HeaderRendered", HeaderRendered);
}
}
C# Polymorphism
Compile Time Polymorphism
Method overloading is a great example. You can have two methods with the same name but with different signatures. The compiler will choose the correct version to use at compile time.
Run-Time Polymorphism
Overriding a virtual method from a parent class in a child class is a good example. Another is a class implementing methods from an Interface. This allows you to use the more generic type in code while using the implementation specified by the child. Given the following class definitions:
public class Parent
{
public virtual void SayHello() { Console.WriteLine("Hello World!"); }
}
public class Child : Parent
{
public override void SayHello() { Console.WriteLine("Goodbye World!"); }
}
The following code will output "Goodbye World!":
Parent instance = new Child();
instance.SayHello();
Early Binding
Specifying the type at compile time:
SqlConnection conn = new SqlConnection();
Late Binding
The type is determined at runtime:
object conn = Activator.CreateInstance("System.Data.SqlClient.SqlConnection");
Friday, September 24, 2010
Reading Excel files from C#
Dictionaryprops = new Dictionary ();
props["Provider"] = "Microsoft.Jet.OLEDB.4.0";
props["Data Source"] = repFile;
props["Extended Properties"] = "Excel 8.0";
StringBuilder sb = new StringBuilder();
foreach (KeyValuePairprop in props)
{
sb.Append(prop.Key);
sb.Append('=');
sb.Append(prop.Value);
sb.Append(';');
}
string properties = sb.ToString();
using (OleDbConnection conn = new OleDbConnection(properties))
{
conn.Open();
DataSet ds = new DataSet();
string columns = String.Join(",", columnNames.ToArray());
using (OleDbDataAdapter da = new OleDbDataAdapter(
"SELECT " + columns + " FROM [" + worksheet + "$]", conn))
{
DataTable dt = new DataTable(tableName);
da.Fill(dt);
ds.Tables.Add(dt);
}
}
Upload files with HTTPWebrequest (multipart/form-data)
byte[] data; // data goes here.
javascript:void(0)
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = userNetworkCredentials;
request.Method = "PUT";
request.ContentType = "application/octet-stream";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data,0,data.Length);
stream.Close();
response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
temp = reader.ReadToEnd();
reader.Close();
Tuesday, September 21, 2010
Convert Byte Array to Hexadecimal String, and vice versa, in C#?
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
or:
public static string ByteArrayToString(byte[] ba)
{
string hex = BitConverter.ToString(ba);
return hex.Replace("-","");
}
There are even more variants of doing it, for example here.
The reverse conversion would go like this:
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
Dynamic LINQ OrderBy
To do this without the dynamic LINQ library, you just need the code as below. This covers most common scenarios including nested properties.
To get it working with IEnumerable
public static IOrderedQueryableOrderBy (this IQueryable source, string property)
{
return ApplyOrder(source, property, "OrderBy");
}
public static IOrderedQueryableOrderByDescending (this IQueryable source, string property)
{
return ApplyOrder(source, property, "OrderByDescending");
}
public static IOrderedQueryableThenBy (this IOrderedQueryable source, string property)
{
return ApplyOrder(source, property, "ThenBy");
}
public static IOrderedQueryableThenByDescending (this IOrderedQueryable source, string property)
{
return ApplyOrder(source, property, "ThenByDescending");
}
static IOrderedQueryableApplyOrder (IQueryable source, string property, string methodName) {
string[] props = property.Split('.');
Type type = typeof(T);
ParameterExpression arg = Expression.Parameter(type, "x");
Expression expr = arg;
foreach(string prop in props) {
// use reflection (not ComponentModel) to mirror LINQ
PropertyInfo pi = type.GetProperty(prop);
expr = Expression.Property(expr, pi);
type = pi.PropertyType;
}
Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);
object result = typeof(Queryable).GetMethods().Single(
method => method.Name == methodName
&& method.IsGenericMethodDefinition
&& method.GetGenericArguments().Length == 2
&& method.GetParameters().Length == 2)
.MakeGenericMethod(typeof(T), type)
.Invoke(null, new object[] {source, lambda});
return (IOrderedQueryable)result;
}
Monday, September 6, 2010
clipboard to Notepad in c# Example
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
[DllImport("user32.dll", SetLastError = true)]
private static extern bool BringWindowToTop(IntPtr hWnd);
private void OnClicked_PasteToNotepad(object sender, EventArgs e) {
// Let's start Notepad
Process process = new Process();
process.StartInfo.FileName = "C:\\Windows\\Notepad.exe";
process.Start();
// Give the process some time to startup
Thread.Sleep(10000);
// Copy the text in the datafield to Clipboard
Clipboard.SetText(uxData.Text, TextDataFormat.Text);
// Get the Notepad Handle
IntPtr hWnd = process.Handle;
// Activate the Notepad Window
BringWindowToTop(hWnd);
// Use SendKeys to Paste
SendKeys.Send("^V");
}
}
Example HttpWebRequest , WebRequest
public class Httpx
{
public string HttpGET(string uri)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
req.Timeout = 30000;
req.Method = "GET";
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; GTB6.5; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2; .NET4.0C; .NET4.0E)";
HttpWebResponse result = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(result.GetResponseStream());
result.Close();
return sr.ReadToEnd();
}
public Stream HttpGETStream(string uri)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
req.Timeout = 30000;
req.Method = "GET";
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; GTB6.5; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2; .NET4.0C; .NET4.0E)";
HttpWebResponse result = (HttpWebResponse)req.GetResponse();
return result.GetResponseStream();
}
public void HttpUpload(string uri)
{
}
}
Monday, August 30, 2010
Working with untyped datasets
DataTable dataTable = new DataTable();
using (var connection = new SqlConnection
(Settings.Default.SkeetySoftDefectsConnectionString))
{
string sql = "SELECT Summary, Status FROM Defect";
new SqlDataAdapter(sql, connection).Fill(dataTable);
}
var query = from defect in dataTable.AsEnumerable()
where defect.Field("Status") != Status.Closed
select defect.Field("Summary");
foreach (string summary in query)
{
Console.WriteLine (summary);
}
Untyped datasets have two problems as far as LINQ is concerned. First, we don’t have
access to the fields within the tables as typed properties; second, the tables themselves
aren’t enumerable. To some extent both are merely a matter of convenience—we
could use direct casts in all the queries, handle DBNull explicitly and so forth, as well as
enumerate the rows in a table using dataTable.Rows.Cast
workarounds are quite ugly, which is why the DataTableExtensions and DataRow-
Extensions classes exist.
Code using untyped datasets is never going to be pretty, but using LINQ is far nicer
than filtering and sorting using DataTable.Select. No more escaping, worrying
about date and time formatting, and similar nastiness.
Listing 12.10 gives a simple example. It just fills a single defect table and prints the
summaries of all the defects that don’t have a status of “closed.”