c# dynamically picking the search direction with linq

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

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

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

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

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

c# getting the application directory.

June 4th, 2008

Getting the directory that the application is in at run-time is nice.  Here’s the code.

string appDir = AppDomain.CurrentDomain.BaseDirectory;

c# Mandelbrot fractal unleashed!

May 15th, 2008

I remember the first time I saw the Mandelbrot set.  It was incredible!  After I had successfully programmed at it on my 8088 (a very old DOS computer).  I would wait 10 minutes at a time for a screen to pop up.  The detail was nothing short of amazing.  The swirls, the shapes, the colors.  The neatest thing was the ability to zoom into it to reveal more and more and more detail.

Well it’s been many years and computers have improved a great deal as have the tools to program them.  So I wrote another Mandelbrot explorer.

Mandelbrot Image

What is the Mandelbrot set? Well….  In short it is Xn+1 = Xn2 + C iterated until the magnitude of Xn is greater than 4 or the maximum number of iterations is met then the number of iterations is used as the color of the pixel.  Xn is a complex number, C is another complex number where the x coordinate of the pixel defines the real part and the y coordinate defines the imaginary part of the number. The magnitude is defined as X2 + Absolute Value of (Xi2).  Then this process is repeated for each pixel.  Holy smoke that is a mouthful!

Anyway take a peek at the code if you’d like and surely get the app and have fun exploring the Mandelbrot set.

To zoom in a spot just click on it.  The number is the number of iterations.  The more iterations the deeper the pattern goes (well until you run into percision problems).

Mandelbrot Executable

Mandelbrot source code.

Have fun!

A shift

May 9th, 2008

The last couple of weeks have been a real shift for me. After finishing up a contract I have spend most of my time in a different lanuage, and entirely different programming environment. I’ve switched from Windows and c# to Linux and Ruby. From normal applications to web applications.

One of the things I like most about switches is all the new stuff I learn. Currently I’m working on building sweetcarloan.com this has been very educational. I’ve learned a great deal about SEO (search engine optimization) and though the concepts are fairly easy to understand it’s incredible time consuming and difficult. I have new respect for those that do it for a living.

It’s been fun to dive back into Ruby a language that has some similarities to c# but some huge differences. It’s got good support for lambda statements, reflection, extensions methods, inline funtion definitions (hmm had remember the names off hand.) However there are some huge differences in syntax and Ruby is completely dynamic in typing.

So that’s this week it’s been a total shift.

c# force uppercase lettering in a ComboBox

April 28th, 2008

I recently changed from a TextEdit control to a ComboBox and was somewhat annoyed that there wasn’t a property that forced the input characters to all be uppercase.  So I dug around and came up with the following method using the KeyPress event.

         private void productNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            char c = e.KeyChar;
            // make it uppercase only
            if (c >= 'a' && c <= 'z')
            {
                int digit = (int)c;
                digit = digit - 'a' + 'A';
                e.KeyChar = Convert.ToChar(digit);
            }
        }

When the event handler is called it gives you a chance to edit the hit character. Just by changing e.KeyChar you change the actual input character. This is a nifty trick to have under your belt.

c# getting rid of the jitter!

April 18th, 2008

I recently was getting greatly annoyed with some drawing code in my program.  I was drawing a photo that I could zoom and move around.  When I zoomed with the wheel though it would briefly draw the image in two positions.  The first position after it was zoomed, and the second position after it was re-centered on the screen.  Well this looked awful.  Not exactly professional looking.  So I tried a hundered different things.  I tried setting a bool variable in the control to tell the paint function not to draw.  No good.  The drawing was done with asynchronous messages.  Then I tried  BeginInvoke.  That didn’t work also.  I tried SuspendLayout and ResumeLayout functions of the Control class:  No good.  Finally I just used the Visible property which kind of worked, well I didn’t get the double picture, but my background was light color and the foreground dark, so there was still a bad looking flicker.  After a couple of hours I finally found the solution at: http://weblogs.asp.net/jdanforth/archive/2004/03/12/88458.aspx. I worked on the example a little and boiled it down to two functions: StopDrawing and StartDrawing.

The techinque basically turns of drawing and events to the object on the win32 level underneath .Net.  This is very handy and it worked very very well.  Here is the code.

        using System.Runtime.InteropServices;
        private const int WM_SETREDRAW      = 0x000B;
        private const int WM_USER           = 0x400;
        private const int EM_GETEVENTMASK   = (WM_USER + 59);
        private const int EM_SETEVENTMASK   = (WM_USER + 69);

        [DllImport("user32", CharSet = CharSet.Auto)]
        private extern static IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, IntPtr lParam);

        IntPtr eventMask = IntPtr.Zero;

        public void StopDrawing()
        {
            if (drawStopCount == 0)
            {
                // Stop redrawing:
                SendMessage(this.Handle, WM_SETREDRAW, 0, IntPtr.Zero);
                // Stop sending of events:
                eventMask = SendMessage(this.Handle, EM_GETEVENTMASK, 0, IntPtr.Zero);
            }
            drawStopCount++;
        }

        public void StartDrawing()
        {
            drawStopCount--;
            if (drawStopCount == 0)
            {
                // turn on events
                SendMessage(this.Handle, EM_SETEVENTMASK, 0, eventMask);

                // turn on redrawing
                SendMessage(this.Handle, WM_SETREDRAW, 1, IntPtr.Zero);

                Invalidate();
                Refresh();
            }
        }