Archive for January, 2008
c# and Linq
by brian on Jan.28, 2008, under Uncategorized
Today I’ve been working at the usual problems of querying internal data model then flushing the changes out to an sqlite database. This is a real drag. I was going to clean up the class and make it more to my liking, so I went to add a new class when I noticed a ‘linq to sql’ option. Then it struck me that this must be something like automatic mapping of programming objects to database much like is had in ruby and rails. If so this would save me a ton of trouble
Well I started to dig. Wow! I’ve been programming for more than 20 years and had many different paradigm shifts. First of functional programming, object oriented programming, patterns, state machines and finite automota, standard template library, Borlands vcl libraries, and now I’m thinking linq is the next big paradigm shift.
I can remember many years ago wishing I’d had a way to do sql queries on my internal objects instead of a for loop over the list. Well I do know!!! Whoo hoo!! This is where the Linq technology comes in. Take a look at the following example:
public class Person
{
public int id;
public string firstName;
public string lastName;
public decimal cash;
public Person(int ID, string FirstName, string LastName, decimal Cash)
{
id = ID;
firstName = FirstName;
lastName = LastName;
cash = Cash;
}
}
....
List>person< people = new List>person<();
people.Add(new Person(1, "George", "McNommy",50));
people.Add( new Person(2,"Adam","Bobbly",1500));
people.Add( new Person(3,"Billy","Freddy",2212));
people.Add( new Person(4,"Caddice","Anderdotter",-34));
IEnumerable>string< result =
from person in people
orderby person.lastName
where person.cash > 0
select person.lastName+", "+person.firstName+": $"+person.cash.ToString();
foreach (string r in result)
log.Text += r + "\r\n";
And here the results as displayed in a rich edit box.
Bobbly, Adam: $1500 Freddy, Billy: $2212 McNommy, George: $50
I’m just scratching the surface here. This will make my life as a programmer so, so, so, much easier!!!
Thanks to Markus Egger for his article I’ve just begun reading and was so excited that I had to make a blog entry before I could finish the article. I sure there are more wonderful surprises coming.
c# Adjusting brightness,contrast, and gamma of an image.
by brian on Jan.23, 2008, under .NET, GUI, c#, c# coding GUI, coding, graphics
c# and gdi+ have a simple way to control the colors that are drawn. It’s basically a ColorMatrix. It’s a 5×5 matrix that is applied to each color if it is set.
Adjusting brightness is just preforming a translate on the color data, and contrast is preforming a scale on the color. Gamma is a whole different form of transform, but it’s included in ImageAttributes which accepts the ColorMatrix.
So here’s the simple code:
Bitmap origanalImage;
Bitmap adjustedImage;
double brightness = 1.0f; // no change in brightness
double constrast = 2.0f; // twice the contrast
double gamma = 1.0f; // no change in gamma
float adjustedBrightness = brightness - 1.0f;
// create matrix that will brighten and contrast the image
float[][] ptsArray ={
new float[] {contrast, 0, 0, 0, 0}, // scale red
new float[] {0, contrast, 0, 0, 0}, // scale green
new float[] {0, 0, contrast, 0, 0}, // scale blue
new float[] {0, 0, 0, 1.0f, 0}, // don't scale alpha
new float[] {adjustedBrightness, adjustedBrightness, adjustedBrightness, 0, 1}};
imageAttributes = new ImageAttributes();
imageAttributes.ClearColorMatrix();
imageAttributes.SetColorMatrix(new ColorMatrix(ptsArray), ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
imageAttributes.SetGamma(gamma, ColorAdjustType.Bitmap);
Graphics g = Graphics.FromImage(adjustedImage);
g.DrawImage(originalImage, new Rectangle(0,0,adjustedImage.Width,adjustedImage.Height)
,0,0,bitImage.Width,bitImage.Height,
GraphicsUnit.Pixel, imageAttributes);
So there it is. Simple enough isn’t it.
It can’t be done! (Ok maybe it can)
by brian on Jan.16, 2008, under abundance
Came across this poem and thought it inspirational
It Couldn’t Be Done
Somebody said that it couldn’t be done,
But he with a chuckle replied
That maybe ” it couldn’t,” but he would be one
Who wouldn’t say so till he’d tried.
So he buckled right in with the trace of a grin
On his face. If he worried, he hid it.
He started to sing as he tackled the thing
That couldn’t be done, and he did it.
Somebody scoffed: ” Oh, you’ll never do that;
At least no one ever has done it.”
But he took off his coat and he took off his hat,
And the first thing we knew he’d begun it.
With a lift of his chin and a bit of a grin,
Without any doubting or quiddit,
He started to sing as he tackled the thing
That couldn’t be done, and he did it.
There are thousands to tell you it cannot be done;
There are thousands to prophesy failure;
There are thousands to point out to you one by one
The dangers that wait to assail you.
But just buckle in with a bit of a grin;
Just take off your coat and go to it;
Just start in to sing as you tackle the thing
That ” cannot be done,” and you’ll do it.
From Edgar A. Guest
Firing an event from within a thread. (At least one way)
by brian on Jan.16, 2008, under .NET, c#, coding
It took me forever to think of this easy method of firing an event from with a thread to the main thread. In searching the web I found several complicated methods that either didn’t work or won’t worth the hassel. But it turns out to be incredible simple and easy to do. The only caveat is that the event subscriber must be a System.Windows.Forms.Control or derived from one
Basically you just get the control target of the delegate and use it’s BeginInvoke or Invoke method and .Net does the rest.
private void DoCommandFinished(Command cmd)
{
if ( null != CommandFinished )
{
System.Windows.Forms.Control c = CommandFinished.Target as System.Windows.Forms.Control;
if (null != c)
{
c.BeginInvoke(CommandFinished, cmd);
}
}
}
I checked this method in my main window thread with the InvokeRequired function. It worked well.
C# writing and xml file.
by brian on Jan.11, 2008, under Uncategorized
Writing xml files in c# is fairly painless and straight forward. I’ll use XmlTextWriter in the following example.
using System.Xml;
string name = "Joe";
int age = 23;
// create writer
XmlTextWriter writer =
new System.Xml.XmlTextWriter("test.xml", Encoding.UTF8);
writer.Indentation = 1;
writer.IndentChar = '\t';
// start the document
writer.WriteStartDocument(true);
// start an element
writer.WriteStartElement("templates");
writer.WriteAttributeString("version", "1.0.0.0");
// create a sub tag people
writer.WriteStartElement("people");
// create a sub tag person
writer.WriteStartElement("person");
// add the attribute age="23"
writer.WriteAttributeString("age",age.ToString());
// write out the full tag Joe
writer.WriteElementString("name",name);
// close out the person tag
writer.WriteEndElement();
// close out the people tag
writer.WriteEndElement();
// close the template tag
writer.WriteEndElement();
// end the document
writer.WriteEndDocument();
// close and write to file.
writer.Close();
Here is the resulting xml (formatting added)
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<templates version="1.0.0.0">
<people>
<person age="23">
<name>Joe</name>
</person>
</people>
</templates>
As I said writing xml is a piece of cake. Parsing on the other hand… I’ll keep you posted.
Getting the current state of keyboard and mouse.
by brian on Jan.09, 2008, under Uncategorized
Every once and a while I need to know whether the Control key is being pressed when I process a mouse event. And sometimes I need to know the mouse position when a key is hit. Of course the keyboard modifiers aren’t passed in mouse events and the mouse button state isn’t passed in the keyboard events.
No problem. For keyboard modifier state use these properties:
Control.ModifierKeys
For the mouse state use these properties:
Control.MouseButtons Cursor.Position // this one you can set :) Control.MousePosition
c# .Net double buffering — plus a little
by brian on Jan.08, 2008, under .NET, GUI, Uncategorized, c#, c# coding GUI, coding
It seems I left out something that helps the quality of the .Net provided form double buffering when you are doing custom drawing. Just override OnPaintBackground and leaving it blank. This prevents the background from being momentarily drawn when you don’t want it to be.
so again here’s how to enable double buffering on the form:
this.SetStyle(
ControlStyles.AllPaintingInWmPaint |
ControlStyles.UserPaint |
ControlStyles.DoubleBuffer,true);
And then the override
protected override void OnPaintBackground(PaintEventArgs e)
{
}
Free Asynchronous Message Queue
by brian on Jan.07, 2008, under GUI, c#, c# coding GUI, coding
If you’ve ever used a message queue to talk to different parts of your application you know that sometimes you run into a problem with tangled call stacks; especially if one message can causes another message to be sent.
However, in c# .Net there is a simple way to untangle the call stack of the message queue. Just use the BeginInvoke method. This unwinds the stack and uses a delegate to call your message reception handler from the control’s thread.
For instance:
delegate void PostOfficeMessageHandler( POMessage message );
public void SendMessage(Control Sender, POMessage Message)
{
PostOfficeMessageHandler mh = recipients[Sender];
Sender.BeginInvoke(mh, Message);
}
The advantages of this method of deliver are two fold. 1. The stack is unwound. 2. It makes message handler in the control’s threads solving some threading issues.
There are a couple of disadvantages. 1. Extra overhead. 2. If the message causes problems you may not know where it’s coming from!
The promise of prayer.
by brian on Jan.06, 2008, under abundance, life, religion
In the following story Nephi, an ancient prophet, has arrived at the sea shore; being guided there by the hand of God. At this point God has commanded them to build a ship and cross the great waters. I find the following passage holds interesting insights about the power of prayer and following received inspiration.
The Book of Mormon: 1 Nephi 18:1-4 1 And it came to pass that they did worship the Lord, and did go forth with me; and we did work timbers of curious workmanship. And the Lord did show me from time to time after what manner I should work the timbers of the ship.
2 Now I, Nephi, did not work the timbers after the manner which was learned by men, neither did I build the ship after the manner of men; but I did build it after the manner which the Lord had shown unto me; wherefore, it was not after the manner of men.
3 And I, Nephi, did go into the mount oft, and I did pray oft unto the Lord; wherefore the Lord showed unto me great things.
4 And it came to pass that after I had finished the ship, according to the word of the Lord, my brethren beheld that it was good, and that the workmanship thereof was exceedingly fine; wherefore, they did humble themselves again before the Lord.
Oft times when we become connected with God we discover that his directions aren’t necessarily popular or easy. In other words it isn’t according to the learning of men. We discover that perhaps the drunken parties aren’t what he wants for us, perhaps we are directed to be honest when it is inconvenient, perhaps it’s averting our eyes away from pornography, perhaps it means spending a bit more time with your spouse and children instead of in front of the computer.
The promise of prayer is that if we persist in prayer and pray often God will give us direction. When we follow the impressions we receive, the results will be there — “the workmanship thereof [will be] exceedingly fine.” A spirit of peace and satisfaction that feeds true happiness will permeate into our lives. We will live a life that we love, and become great as God intends.
So pray to God and he will answer. I like the scripture found in Matthew 7:8 “For every one that asketh receiveth; and he that seeketh findeth; and to him that knocketh it shall be opened.”
It is true. I have experienced God’s directions and his love in my life.
Peace to you.
Brian
Terrain 0.3 release.
by brian on Jan.05, 2008, under c#, coding, graphics, terrain
Well I finally had a little time today to work on my terrain generation software. It’s written in C++ using the SDL and SDL_gfx graphics libraries along with the Guichan GUI library. I had a bunch of fun adding relief shading. Basically it lightening or darkening the color based on the derivative (change in elevation). The steeper the positive change in elevation the brighter and the steeper the elevation loss the darker.
Anyway the results were really quite good, even a bit better than I expected. Here is an example:

Flat 2d rendering

3d (orthographic) Rendering of terrain
Anyway if you want to download a copy and try just go to http://bee-eee.com/ it’s under the software/terrain section.
