Archive for the ‘.NET’ Category

c# finding those blasted predefined IEqualityComparer classes!

Tuesday, April 14th, 2009

Why there isn’t any reference in the IEqualityComparer documentation to pre-implmented classes that override the function I don’t know.

But here’s one for string comparisons:

StringComparer

This static class contains many different predefined IEqualityComparer instances to be used in functions like “Contains”. Enjoy.

c# Getting your machine’s IP addresses.

Tuesday, March 17th, 2009

Here is the simple way to get all of the IP addresses for you machine. This code filters out everything but IPv4 address, but to truly get everything just remove the if statement.

string hostName = Dns.GetHostName();
var addrs = Dns.GetHostAddresses(hostName);
bool hasIP = false;
for (int i = 0; i < addrs.Length; i++)
{
    IPAddress addr = addrs[i];
    if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
    {
        si.DataIP = addr.ToString();
        hasIP = true;
        break;
    }
}

c# setting caret position for a richedit control

Tuesday, January 6th, 2009

Here’s the code to set the position of the caret in a richedit control

int position = 12;
richedit1.Select( position, 0 );
richedit1.ScrollToCaret(); // if you want the position to be shown

It’s that simple.

c# logging linq to sql

Thursday, January 1st, 2009

I’ve often been frustrated by the sql that linq produces.  Usually it’s really good, but occasionally it produced monstrosities.   The hard part is getting at the sql that’s produced by a function.  Hovering over the statement in the idea is a real pain so instead I created the following class that dumps the sql to a file

public class DCLogger : IDisposable
    {
        private StringWriter writer;

        public DCLogger(System.Data.Linq.DataContext dc)
        {
            writer = new StringWriter();
            dc.Log = writer;
        }

        #region IDisposable Members

        public void Dispose()
        {
            writer.Flush();
            System.IO.File.WriteAllText( "c:\\temp\\sql.log", writer.ToString() );
        }

        #endregion
    }

To use it just create it passing it you data context. The results are written to the file when it’s disposed.

  using( DCLogger( dc ) )
  {
    // ... some linq statement that executes
  }

c# linq to sql string comparisons

Monday, October 27th, 2008

There are four different string comparisons for handling string fields with linq to sql.  They are as follows:

The exact macth

DataContext dc = new DataContext(...)
var results =
  from row in dc.table
  where row.string_column == "Exact Match"
  select row;

Begins With:

DataContext dc = new DataContext(...)
var results =
  from row in dc.table
  where row.string_column.StartsWith("Ex")
  select row;

produces an sql match string “Ex%”

Contains

DataContext dc = new DataContext(...)
var results =
  from row in dc.table
  where row.string_column.Contains("Ex")
  select row;

Which is equivalent to “%Ex%”

Ends With

DataContext dc = new DataContext(...)
var results =
  from row in dc.table
  where row.string_column.EndsWith("Ex")
  select row;

Which is equivalent to “%Ex”

c# dynamically picking the search direction with linq

Tuesday, September 30th, 2008

I’ve recently been writing an application that builds a linq to sql query dynamically.  For instance:

MyDataContext dc() = new MyDataContext;
var query = dc.MyTables;
query = query.Where( t=>t.id > 10);

and so I want to order it by a certain column:

query = query.OrderBy( t=>t.id )

but the problem is the order direction isn’t know before hand so at first I was stuck with the following:

if ( descending )
    query = query.OrderByDescending( t=>t.id);
else
    query = query.OrderBy(t=>t.id);

Now if there is only a few possible columns to sort against it isn’t too bad.  But when you have 10 different possible columns it really makes a lot of extra work just to control to sort direction.  So I made a little helper class that allows the following.  It works with linq and linq to sql:

query = query.OrderByAscDec( t=>t.id, descending );

here’s the static class that implments the OrderByAscDec function:

static class VPLinqExtensions
{
	public static IOrderedQueryable<TSource> OrderByAscDes<TSource, TKey>(
		this IQueryable<TSource> source,
		System.Linq.Expressions.Expression<Func<TSource,
		TKey>> keySelector, bool IsDescending)
	{
		if (IsDescending)
			return source.OrderByDescending(keySelector);
		else
			return source.OrderBy(keySelector);
	}
}

c# non-blocking sockets

Monday, September 15th, 2008

There doesn’t seem to be much written on blocking socket with c#.  So I’ll write a very short piece, and I’ll only concentrate on client sockets.

Creating a socket is easy here is how:

using System.Net.Sockets;

//...

// Creating a connection
Socket client;
client = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
client.Connect(hostName, port);
client.Blocking = false; // This needs to be done after Connect or it will error out.

Here’s how to write data to the socket

// Writing information to the socket
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(messageText);
foreach (byte c in buffer)
{
	SocketError err = SocketError.WouldBlock;
	// need to try again if the socket would have blocked
	while ( err == SocketError.WouldBlock )
	{
		// this version of Send must be used or an exception would be thrown, which I feel is a pain
		// to deal with -- this way you can see handle the error appropriately.
		client.Send(buffer, 0, 1, SocketFlags.None, out err );
	}

	if ( err != SocketError.Success )
	{
		// handle error
		break;
	}
}

And now code to read from a non-blocking socket

// Reading from the socket
// this loop keeps going until there is a socket error or a '0' byte is read which
// in this example marks the end of the message
System.Text.StringBuilder message = new System.Text.StringBuilder();
while ( true )
{
	byte c = 0;
	int bytesRead;
	SocketError err;
	// read a character.
	bytesRead = client.Receive(buffer, 0, 1, SocketFlags.None, out err );
	// checking what happened
	if ( SocketError.Success == err )
	{
		// read a byte!  Let's process it
		if ( bytesRead > 0 )
		{
			// found a null character -- in this case it makes the end of a message.
			if (c == 0)
			{
				// null terminated message received
				break;
			}
			else
				message.Append((char)c);
			}
		}
	}
	else if ( SocketError.WouldBlock != err )
	{
		break;
	}
}

c# Reading the contents of a web page

Wednesday, September 10th, 2008

Reading the contents of a web page can be very useful.  Here’s some code I’m developing to read the historical stock prices from http://finance.google.com

string uri = "http://finance.google.com/finance/historical?cid=667226&startdate=Sep+9%2C+2007&enddate=Sep+10%2C+2008&output=csv";
WebRequest request = WebRequest.Create(uri);
WebResponse response = request.GetResponse();
var stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
string page = reader.ReadToEnd();

There you go. Very simple isn’t it? Just got to love .Net

c# timing functions

Thursday, June 12th, 2008

Here are some timing functions that come in the .Net framework.  I’ve used these for moderately accurate timing code — at least down to the millisecond level.  For any timing less than about 30 milliseconds these work much better than timer events piled on each other which tend to get inaccurate.

int begin = System.Environment.TickCount
... do something
int end = System.Environment.TickCount
int elapsed = end - begin;

c# getting a list of files from a directory

Wednesday, June 4th, 2008

Here’s how to get an array of file descriptors (name and other information).

System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Program.DataDirectory);
System.IO.FileInfo[] files = di.GetFiles("*.txt");