I recently revisited the Simulated Annealing heuristic algorithm using C#. This algorithm is traditionally the choice for solving the Traveling Salesman problem, but I wanted to tackle another large combinatorial problem, Poker Solitaire.
For a description of the problem, visit Dr. Dobbs original article at:
http://www.ddj.com/184408203?pgno=16
How do you calculate a result with a solution set of 25 factorial (15,511,210,043,330,983,907,819,520)?
The Visual Studio 2008 solution (see below) provides a console application that repeatable executes a single annealing process, each time trying to optimize a 5x5 matrix of playing cards. The algorithm attempts to lay the cards out to optimize 12 poker hands (5 rows, 5 columns, 2 diagonals).
You can execute the console application using the syntax below, passing it the name of a text file that represents 25 cards for the 5x5 matrix.
C:> SimulatedSolitaire.Console.exe TestData\BestCards.txt
Download the Visual Studio 2008 solution by clicking here.
Just some random development ramblings mostly related to the Microsoft .NET platform.
Showing posts with label Linq. Show all posts
Showing posts with label Linq. Show all posts
Monday, September 14, 2009
Saturday, January 31, 2009
Obtaining computer SID and Processor ID using C#
Sometimes you have to track a unique identifier for an application (e.g. license key registration). Here are two small C# methods to get the Windows SID (Security ID) and the motherboard processor ID (may be more than one).
using System;
using System.Linq;
using System.Management;
using System.Security.Principal;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
new Program().Run(args);
}
private void Run(string[] args)
{
string sid = UserSecurityId();
Console.WriteLine("The SID is: {0}", sid);
string[] processorIds = ComputerProcessorId();
foreach (string id in processorIds)
{
Console.WriteLine("Processor ID: {0}", id);
}
}
public string UserSecurityId()
{
return WindowsIdentity.GetCurrent().User.AccountDomainSid.ToString();
}
public string[] ComputerProcessorId()
{
return new ManagementObjectSearcher("Select * from Win32_Processor")
.Get()
.OfType<ManagementObject>()
.Select(o => o["ProcessorID"].ToString())
.ToArray();
}
}
}
Tuesday, November 25, 2008
Making custom changes in LINQ-to-SQL designer
This post describes a scenario I encountered recently that would require making custom changes in the LINQ-to-SQL designer.
Even given that the Microsoft rumor-mill has tagged LINQ-to-SQL as terminal given the rise of LINQ-to-Entity, I still find LINQ-to-SQL useful for those non-enterprise solutions. As many developers know, the LINQ-to-SQL class designer doesn’t provide much automated support for keeping your database schema up-to-date with the class designer objects (tables, relationships, etc.)
I haven’t found this to be a huge issue since I work around this limitation by deleting and re-adding tables (which automatically updates the dbml code). I’ve steered clear of making any custom changes through the designer so I can perform this simple work around.
Recently I ran into an issue that makes me want to make manual changes in the designer. It has to do to the way the relationship property names are generated. Let’s look at an example.
Consider you have a table named Grades that represents school grades like 1, 2, 3, and so forth. Now assume you have another table named Worksheets that represents individual worksheets for each school grade. This is a typical one-to-many relationship. Two of the Worksheets columns are StoreGrade (where a PDF worksheet is stored on disk) and DisplayGrade (which grade to display this worksheet for). This allows a worksheet to be reused for 4th grade even though it is stored in the 3rd grade folder. The StoreGrade and DisplayGrade are foreign keys of the Grades table.
When using the LINQ-to-SQL designer, the above scenario will create a Grade object will two properties called Worksheets and Worksheets1. When using intellisense, it really isn’t possible to know which of these properties is for StoreGrade and which is for DisplayGrade. It is possible to change the property names created by using the designer properties for each relationship, but that would mean I lose the ability to delete/re-add a table with ease.
I’m continuing to hold off making custom designer changes, but this is one scenario I’ve run across that gives a reason to make custom changes via the LINQ-to-SQL designer.
Even given that the Microsoft rumor-mill has tagged LINQ-to-SQL as terminal given the rise of LINQ-to-Entity, I still find LINQ-to-SQL useful for those non-enterprise solutions. As many developers know, the LINQ-to-SQL class designer doesn’t provide much automated support for keeping your database schema up-to-date with the class designer objects (tables, relationships, etc.)
I haven’t found this to be a huge issue since I work around this limitation by deleting and re-adding tables (which automatically updates the dbml code). I’ve steered clear of making any custom changes through the designer so I can perform this simple work around.
Recently I ran into an issue that makes me want to make manual changes in the designer. It has to do to the way the relationship property names are generated. Let’s look at an example.
Consider you have a table named Grades that represents school grades like 1, 2, 3, and so forth. Now assume you have another table named Worksheets that represents individual worksheets for each school grade. This is a typical one-to-many relationship. Two of the Worksheets columns are StoreGrade (where a PDF worksheet is stored on disk) and DisplayGrade (which grade to display this worksheet for). This allows a worksheet to be reused for 4th grade even though it is stored in the 3rd grade folder. The StoreGrade and DisplayGrade are foreign keys of the Grades table.
When using the LINQ-to-SQL designer, the above scenario will create a Grade object will two properties called Worksheets and Worksheets1. When using intellisense, it really isn’t possible to know which of these properties is for StoreGrade and which is for DisplayGrade. It is possible to change the property names created by using the designer properties for each relationship, but that would mean I lose the ability to delete/re-add a table with ease.
I’m continuing to hold off making custom designer changes, but this is one scenario I’ve run across that gives a reason to make custom changes via the LINQ-to-SQL designer.
Friday, November 7, 2008
Using LINQ's ToLookup
Often times you have a set of data and want to process the data in sets based on some property of the data. For example, you may want to process all employee records based on what state the employee lives in (presumably for tax purposes).
To organize the employees, we need something like a .NET dictionary class, but be able to store multiple employees per key (i.e. state). A dictionary only stores a single object per key so we're out of luck using that class.
This is where the LINQ ToLookup and GroupBy operators come to the rescue. ToLookup is a non-deferred operator and GroupBy is a deferred operator. The example below illustrates how ToLookup can be used to process employee objects, together, based on what state the employee lives in. The GroupBy is basically the same thing, but the data is grouped during enumeration because of its deferred nature.
To organize the employees, we need something like a .NET dictionary class, but be able to store multiple employees per key (i.e. state). A dictionary only stores a single object per key so we're out of luck using that class.
This is where the LINQ ToLookup and GroupBy operators come to the rescue. ToLookup is a non-deferred operator and GroupBy is a deferred operator. The example below illustrates how ToLookup can be used to process employee objects, together, based on what state the employee lives in. The GroupBy is basically the same thing, but the data is grouped during enumeration because of its deferred nature.
private class Employee
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string StateAbbr { get; set; }
}
static void Main(string[] args)
{
new Program().Run(args);
}
private void Run(string[] args)
{
List<Employee> employees = new List<Employee>
{
new Employee { ID = 1, LastName = "Scott", FirstName = "Michael", StateAbbr = "CO" },
new Employee { ID = 1, LastName = "Smoe", FirstName = "Joe", StateAbbr = "CA" },
new Employee { ID = 1, LastName = "Lampton", FirstName = "Todd", StateAbbr = "CO" },
new Employee { ID = 1, LastName = "Morgan", FirstName = "Jared", StateAbbr = "WA" },
new Employee { ID = 1, LastName = "Smart", FirstName = "Laura", StateAbbr = "ID" },
new Employee { ID = 1, LastName = "Seashell", FirstName = "Sally", StateAbbr = "CO" },
};
ILookup<string, Employee> folksByState = employees
.ToLookup(e => e.StateAbbr);
foreach (IGrouping<string, Employee> stateGroup in folksByState)
{
Console.WriteLine("\nState: {0}", stateGroup.Key);
foreach (Employee e in stateGroup)
{
Console.WriteLine("{0}, {1}, {2}", e.LastName, e.FirstName, e.ID);
}
}
}
Monday, September 8, 2008
Zip XML in memory for Web Service transport (SharpZipLib)
Here is a full test program that demonstrates how to use SharpZipLib to zip an XElement into a byte array. This allows you to transfer large XML items over web services, and then unzip then on the web service side. I included two methods to unzip, both back to an XElement and to an XML file. IIS 6 does allow compression as well, but the reason I had to have the functionality below was that a PC client application was required to send a host web service a large set of XML (rather than the host sending the client XML).
using System;
using System.IO;
using System.Xml.Linq;
using ICSharpCode.SharpZipLib.Zip;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
new Program().Run(args);
}
private void Run(string[] args)
{
// create some xml
XElement xml = XElement.Parse("<xml><element>whatever</element></xml>");
// zip xml
string startXml = xml.ToString();
byte[] bytes = ZipContent(xml, "TestXML");
// unzip xml
xml = UnzipContent(bytes);
string endXml = xml.ToString();
// sanity check
System.Diagnostics.Debug.Assert(startXml == endXml);
}
/// <summary>
/// Convert XML to zipped byte array.
/// </summary>
/// <param name="xml">XML to zip.</param>
/// <param name="entryName">The zip entry name.</param>
/// <returns>A byte array that contains the xml zipped.</returns>
private byte[] ZipContent(XElement xml, string entryName)
{
// remove whitespace from xml and convert to byte array
byte[] normalBytes;
using (StringWriter writer = new StringWriter())
{
xml.Save(writer, SaveOptions.DisableFormatting);
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
normalBytes = encoding.GetBytes(writer.ToString());
}
// zip into new, zipped, byte array
using (Stream memOutput = new MemoryStream())
using (ZipOutputStream zipOutput = new ZipOutputStream(memOutput))
{
zipOutput.SetLevel(9);
ZipEntry entry = new ZipEntry(entryName);
entry.DateTime = DateTime.Now;
zipOutput.PutNextEntry(entry);
zipOutput.Write(normalBytes, 0, normalBytes.Length);
zipOutput.Finish();
byte[] newBytes = new byte[memOutput.Length];
memOutput.Seek(0, SeekOrigin.Begin);
memOutput.Read(newBytes, 0, newBytes.Length);
zipOutput.Close();
return newBytes;
}
}
/// <summary>
/// Return zipped bytes as unzipped XML.
/// </summary>
/// <param name="bytes">Zipped content.</param>
/// <returns>Unzipped XML.</returns>
private XElement UnzipContent(byte[] bytes)
{
// unzip bytes into unzipped byte array
using (Stream memInput = new MemoryStream(bytes))
using (ZipInputStream input = new ZipInputStream(memInput))
{
ZipEntry entry = input.GetNextEntry();
byte[] newBytes = new byte[entry.Size];
int count = input.Read(newBytes, 0, newBytes.Length);
if (count != entry.Size)
{
throw new Exception("Invalid read: " + count);
}
// convert bytes to string, then to xml
string xmlString = System.Text.ASCIIEncoding.ASCII.GetString(newBytes);
return XElement.Parse(xmlString);
}
}
/// <summary>
/// Save zipped bytes as unzipped file.
/// </summary>
/// <param name="bytes">Zipped content.</param>
/// <param name="path">File path to save unzipped XML.</param>
private void UnzipContent(byte[] bytes, string path)
{
// unzip bytes into unzipped byte array
using (Stream memInput = new MemoryStream(bytes))
using (ZipInputStream zipInput = new ZipInputStream(memInput))
using (BinaryWriter writer = new BinaryWriter(File.Create(path)))
{
ZipEntry entry = zipInput.GetNextEntry();
int count;
byte[] input = new byte[1024 * 10];
while ((count = zipInput.Read(input, 0, input.Length)) > 0)
{
writer.Write(input, 0, count);
}
}
}
}
}
Monday, August 18, 2008
Plug-in architecture (dynamically loading DLLs) using LINQ
For implementing a plug-in architecture using the strategy pattern, this is my preferred way of loading some interfaces (DLLs) at runtime. Make sure you look at the second code example showing how to do the same thing in LINQ.
Now using LINQ...
If you want to load an assembly and all the dependent DLLs, you can use the same LINQ query, but use LoadFrom rather than LoadFile.
This can then be called using:
public List<T> LoadDLL<T>(string path, string pattern)
{
List<T> plugins = new List<T>();
foreach (string s in Directory.GetFiles(Path.GetFullPath(path), pattern))
{
foreach (Type t in Assembly.LoadFile(s).GetTypes())
{
if (!t.IsAbstract && typeof(T).IsAssignableFrom(t))
{
plugins.Add((T)Activator.CreateInstance(t));
}
}
}
return plugins;
}
Now using LINQ...
public List<T> LoadDLL<T>(string path, string pattern)
{
return Directory.GetFiles(Path.GetFullPath(path), pattern)
.SelectMany(f => Assembly.LoadFile(f).GetTypes()
.Where(t => !t.IsAbstract && typeof(T).IsAssignableFrom(t))
.Select(t => (T)Activator.CreateInstance(t)))
.ToList();
}
If you want to load an assembly and all the dependent DLLs, you can use the same LINQ query, but use LoadFrom rather than LoadFile.
public List<T> LoadDLL<T>(string path, string pattern)
{
return Directory.GetFiles(Path.GetFullPath(path), pattern)
.SelectMany(f => Assembly.LoadFrom(f).GetTypes()
.Where(t => !t.IsAbstract && typeof(T).IsAssignableFrom(t))
.Select(t => (T)Activator.CreateInstance(t)))
.ToList();
}
This can then be called using:
List<Foo> foos = LoadDLL<Foo>(@".\", "*.dll");
Thursday, August 7, 2008
Format C# code for Blogger posts
This is the tool I like for formatting C# source code in my blog.
http://formatmysourcecode.blogspot.com/
http://formatmysourcecode.blogspot.com/
Wednesday, May 14, 2008
LINQ cheat sheets for deferred and non-deferred
Here are cheat sheets for the LINQ deferred and non-deferred extension methods. Included are the page number references of where these are found in Joseph Rattz's book, Pro LINQ by Apress.
Format is legal, 14" x 8.5"
Click here
Format is legal, 14" x 8.5"
Click here
Sunday, May 4, 2008
CheckBoxList, Linq, and XML
I’ve been playing around with the new Linq stuff in .NET 3. I’m finding it’s possible to do things much easier with Linq, as well as with significantly less code. Recently I had to take all the selected items in an asp.net checkbox list (cblOpinion) and write them to an XML file (filePath). The code turned out to be a single statement:
new XElement("Opinions",
cblOpinion.Items.OfType()
.Where(o => o.Selected)
.Select(o => new XElement("Opinion", o.Text)))
.Save(filePath);
This created a nice XML file that looked like:
opinion a...
opinion b...
opinion c...
opinion d...
Pretty nifty!
new XElement("Opinions",
cblOpinion.Items.OfType
.Where(o => o.Selected)
.Select(o => new XElement("Opinion", o.Text)))
.Save(filePath);
This created a nice XML file that looked like:
Pretty nifty!
Monday, April 21, 2008
Can't compile Linq after VS 2008 migration
I migrated a VS 2005 asp.net website (not using Linq) to VS 2008. Initially, the website compiled fine, but once I tried to add Linq statements, it would not compile.
I had already done the following to prepare for Linq use:
1) Added in the web.config so System.Core (where Linq lives) would be a reference (copied several of these from a virgin VS 2008 asp.net site)
2) Modified the site Build properties and targeted .NET 3.5
3) Added "using System.Linq"
But it still would not compile...all Linq statements were not recognized (even Intellisense worked). It was like I was still using the .NET 2.0 compiler.
When I looked back at the web.config from a virgin VS 2008 asp.net site, I realized I needed to also have the section. I copied this entire section into my web.config and it now compiles fine (with the .3.5 compiler).
It would have been nice if the conversion tool from VS 2005 to 2008 would have done this for me. I have the first official release of VS 2008.
I had already done the following to prepare for Linq use:
1) Added
2) Modified the site Build properties and targeted .NET 3.5
3) Added "using System.Linq"
But it still would not compile...all Linq statements were not recognized (even Intellisense worked). It was like I was still using the .NET 2.0 compiler.
When I looked back at the web.config from a virgin VS 2008 asp.net site, I realized I needed to also have the
It would have been nice if the conversion tool from VS 2005 to 2008 would have done this for me. I have the first official release of VS 2008.
Subscribe to:
Posts (Atom)
Can't RDP? How to enable / disable virtual machine firewall for Azure VM
Oh no! I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore. I did ...
-
Don't want Office 2007 installed on your web server to access Excel 2007 content? Here is a Visual Studio C# solution that demonstrates ...
-
I finally found a good algorithm to validate a file path (had to fix two bugs in it though). I use this static method in Windows Forms when...