Pages

Friday, September 24, 2010

Reading Excel files from C#


Dictionary props = new Dictionary();
props["Provider"] = "Microsoft.Jet.OLEDB.4.0";
props["Data Source"] = repFile;
props["Extended Properties"] = "Excel 8.0";

StringBuilder sb = new StringBuilder();
foreach (KeyValuePair prop 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#?

Either:

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

Just stumbled into this oldie...

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 you could add some wrapper methods that go via AsQueryable - but the code below is the core Expression logic needed.

public static IOrderedQueryable OrderBy(this IQueryable source, string property)
{
return ApplyOrder(source, property, "OrderBy");
}
public static IOrderedQueryable OrderByDescending(this IQueryable source, string property)
{
return ApplyOrder(source, property, "OrderByDescending");
}
public static IOrderedQueryable ThenBy(this IOrderedQueryable source, string property)
{
return ApplyOrder(source, property, "ThenBy");
}
public static IOrderedQueryable ThenByDescending(this IOrderedQueryable source, string property)
{
return ApplyOrder(source, property, "ThenByDescending");
}
static IOrderedQueryable ApplyOrder(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

This can be a bit tricky in some scenarios, but it's actually quite simple and easy to do. Below is an example on how to get some text using a text box, (called uxData in this case), open Notepad from code, and to paste the text from the clipboard to Notepad.

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

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

}
}