c# finding those blasted predefined IEqualityComparer classes!

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.

Gay Marriage — The farce.

April 14th, 2009

Here we go again.  I suppose my beliefs will be mocked and I’ll be called a bigot, but public discussion needs to be open and full.  Not just one side.  So I’ll share my beliefs.

Marriage between a man and a women, fulfill a useful role to our society.  They raise citizens.  Even at 50% divorce rate the marriage relationship is by far the most stable, and best environment to raise children to become productive members of a society.  It has been proved that a child is mostly likely to grow up well adjusted with both a Father and a Mother.  As such it is in the interest of our society to protect and foster marriage between a man and a women.

In the eyes of the society in general the purpose of marriage is NOT sexual fulfillment, and NOT expression of love, but a means of perpetuating a sustainable society with productive citizens.

So what good are homosexual marriages to the state?  There is none.  They cannot procreate.  They also cannot provide both a father and a mother through adoption.  They cannot reliably raise well adjusted individuals.

I hear the cries of we have a right!  It’s not fair!  I ask when did you have the right to do what was wrong?

Jesus would never condone such homosexual actions.  Why?  Because he loves us and wants us to be truly happy.  He has said no unclean thing can enter the kingdom of God.  He has defined homosexuality as an action that will defile an individual and disqualify him/her to enter the kingdom of God.  How can we be happy if we cannot enter God’s kingdom in the end?  You cannot.  Nor can you have peace in this life.

Again I’m sure I’ll be mocked as old fashioned and out of touch.  But true principles do not change regardless of whether you believe them or not.

One unchanging fact is that God lives.  I witness it, and am not ashamed to stand as a witness.   From my own experience I know God lives.

Go on ahead and call me a bigot.  Mock if you wish.   I stand for virtue, I stand for that which is right and good and beautiful.

c# Getting your machine’s IP addresses.

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

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

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
  }

MS SQL Delete all the data from the tables.

November 21st, 2008

Here’s a helpful, and perhaps dangerous, little tidbit of code for SQL Server 2005. It deletes all of the data from all of the tables. To be completely effective, the command may need to be run more than once because of foreign keys. Basically run it until there aren’t any errors. Then the db is clean and empty of all data.

exec sp_MSForeachTable "delete from ?"

the sp_MSForeachTable is a very useful system stored procedure.

c# Property Grid - Getting a combo box

October 31st, 2008

You’d think getting a combox display into the property grid would be really simple to do since it’s used everywhere in Visual Studio 2008.  And although it isn’t horrible it isn’t exactly straight forward.  I found a couple of dead-ends, poorly explained, or difficult to find the pith of examples.  Finally I ran across this one at http://gaaton.blogspot.com/ It’s nice and concise, easy to understand, and easy to adapt.  I’m going to put in my sample which essentially taken from gaaton.

internal class ProtcolConverter : StringConverter
    {
        public override bool
            GetStandardValuesSupported(
            ITypeDescriptorContext context)
        {
            //True - means show a Combobox
            //and False for show a Modal
            return true;
        }

        public override bool
            GetStandardValuesExclusive(
            ITypeDescriptorContext context)
        {
            //False - a option to edit values
            //and True - set values to state readonly
            return true;
        }

        public override StandardValuesCollection
            GetStandardValues(
            ITypeDescriptorContext context)
        {
            return new StandardValuesCollection(
                new string[] { "net.tcp", "http" });
        }
    }

And finally the we need to attach the string converter to the property by the following.

[TypeConverter(typeof(ProtcolConverter))]
public string ServiceProtocol
{
     get { return MediaServiceConfig.WCFProtocol; }
     set { MediaServiceConfig.WCFProtocol = value; }
}

Enjoy.

MS SQL tricks for uniqueidentifers or Guid and date time.

October 29th, 2008

In MS SQL Server 2005 the following code is how to get a new uniqueidentifier, and the current date and time.

SELECT newid(),getdate()

Produces these results.

------------------------------------ -----------------------
125700F3-8FB8-496F-8EA4-35D9CB9E8415 2008-10-29 13:09:54.557
(1 row(s) affected)

c# linq to sql string comparisons

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

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