string.ToNullable<T>() Extension for Converting a string into a Nullable Object of Type T

save time with a simple conversion that works for all nullable Types

For a while, I have used a ToNullable method (that I found somewhere on the intertubes) that required the input of a TryParse delegate like this:
int? eight = "8".ToNullable<T>(int.TryParse);
int? nInt = "".ToNullable<T>(int.TryParse);//null

Which wasn't bad in any way, but I realized that every time I was using this method, I would have to type in the TryParse of the Type I was trying to get; clearly there is a better way, and I found it using TypeConverter. Now I can use my new ToNullable method in a cleaner, less repetitive way:
int? eight = "8".ToNullable<T>();
int? nInt = "".ToNullable<T>();//null

Here is the code:
public static Nullable<T> 
  ToNullable<T>(this string s) where T : struct
  T? result = null; 
  if (!string.IsNullOrEmpty(s.Trim())) 
    TypeConverter converter = TypeDescriptor
    result = (T?)converter.ConvertFrom(s); 
  return result;

This has been added to my Utilities Library on CodePlex. convert integer to nullable ?Int32 convert int to nullable ?int convert double to nullable ?double convert bool to nullable ?bool convert decimal to nullable ?decimal convert long to nullable ?long

Universal Get<>() accessor for any Linq-to-SQL Table

never write a Linq-to-SQL Get accessor again

I don't even want to know how many times I have written something like this:
var p = db.Products.FirstOrDefault(x => x.Id == someId);

Then 4 lines down, do it again almost exactly the same, over and over, at least once for each table. Well... no more! Now that I am able to get the Primary Key of any Linq-to-SQL talbe, it is trival to be able to write a universal get statement so I can simply do this when I want to grab an object by it's Primary Key:
Product p = db.Get<Product>(someId);

What if I want to get an item that has a Guid as a primary key? Same thing, it doesn't matter:
Guid gId = 
  new Guid("4fcc0b82-b137-4e4b-935e-872ed662ba53");
Gizmo g = db.Get<Gizmo>(gId);

If you you give the wrong Type of Key, it will tell you in a nice ArgumentException:
Gizmo g = db.Get<Gizmo>(5);


Primary Key of Table and primaryKey argument are not of the same Type; Primary Key of Table is of Type: System.Guid, primaryKey argument supplied is of Type: System.Int32

Here is the code without any error handling:
public static T Get<T>(this DataContext dataContext,
  object primaryKey) 
    where T : class, INotifyPropertyChanged
  return dataContext.GetTable(typeof(T))
    .Name + ".Equals(@0)", primaryKey)

The full code is available in my Utilities class on CodePlex. This requires System.Linq.Dynamic.

Get the Primary Key PropertyInfo of any Linq-to-SQL Table

Easily find any table's Primary Key property

In my search for a universal generic Get() accessor for Linq-to-SQL DataContexts, I figured I would have to dynamically find the primary key of a table. Using Reflection and the Attributes applied to L2S tables, it is not difficult at all:
//get the primary key PropertyInfo table 'Product'
PropertyInfo info = GetPrimaryKey<Product>();

It's just that easy, it will throw a NotSupportedException if there is no primary key, or the primary key allows NULL. It uses the Linq-to-SQL ColumnAttribute properties to determine what the primary key is. If there is more than one primary key, it will just use the first one it comes across.

The complete source code can be browsed at my new Utilities Library along with full documentation on CodePlex, just figured it would be easy to keep all of my utilities in one place. Otherwise, here is the meat of the code:
public static PropertyInfo GetPrimaryKey<T>()
  PropertyInfo[] infos = typeof(T).GetProperties();
  PropertyInfo PKProperty = null;
  foreach (PropertyInfo info in infos)
    var column = info.GetCustomAttributes(false)
     .Where(x => x.GetType() == typeof(ColumnAttribute))
     .FirstOrDefault(x => 
      ((ColumnAttribute)x).IsPrimaryKey && 
      ((ColumnAttribute)x).DbType.Contains("NOT NULL"));
  if (column != null)
    PKProperty = info;
  if (PKProperty == null) 
    throw new NotSupportedException(
      typeof(T).ToString() + " has no Primary Key");
  return PKProperty;

And yes, I did come up with a universal generic Get() accessor for Linq-to-SQL DataContexts, that's next post... or the code is already posted in my Utilities Library.

FileStream Save() Extension - Easily Save Your FileStreams with the Option of No-Overwrite

an extension to allow fast simple saving without worrying about overwriting a file

With these extensions, you can save a FileStream as simple as this:

Now if you run it again, it will save another file named file[1].txt, then file[2].txt and so on. If you want to overwrite a file, simply state true for the overwrite flag:
fs.Save(@"C;/file.txt", true);

Here is the code:
public static string Save(this FileStream file, 
  string path)
{ return file.Save(path, false); }
public static string Save(this FileStream file, 
  string path, bool overwrite)
  int count = 1;
  string folder = Path.GetDirectoryName(path);
  if (!Directory.Exists(folder)) 
  int fileSize = Convert.ToInt32(file.Length);
  string fileName = Path.GetFileName(file.Name);
  Byte[] bytes = new Byte[fileSize];
  file.Read(bytes, 0, fileSize);
  string root = Path.GetDirectoryName(path) + 
    "\\" + Path.GetFileNameWithoutExtension(path);
  while (!overwrite && File.Exists(path))
    path = root + "[" + count++.ToString() + 
      "]" + Path.GetExtension(path);
  File.WriteAllBytes(path, bytes);
  return Path.GetFileName(path);

Readable Return Urls in your MVC Urls

Don't surrender your clean, readable url to a nasty returnUrl string; keep your MVC urls readable

Asp.Net MVC projects have a great routing resource available to them; this makes for very clean and human-readable urls:


A lot of these web applications will use a returnUrl somewhere in there, this is where the problem comes in: return urls tend to be ugly and unreadable if passed in the query. Let's say I am not deleting something and want to return to the page I was at before, if I simply use a returnTo, the url looks like this:


The markup I used to get that was this:
<%= Html.ActionLink("Delete", "Delete", 
  new { Id = 15, returnTo = 
    ViewContext.HttpContext.Request.Url.ToString() })
Yes, I know you won't hard-code your Id in there, but it's an example. That works just fine, and the user will probably not care, but I do... To go to all that trouble to get nice readable urls, then spit out something that looks this ugly is sacrilege, there has got to be a better way, and there is, and it is ridiculously simple.

set up your routes

In your global.asax.cs, I just need to add 'catch-all' parameter, and make it nice and readable:
  new { controller = "Search", action = "Delete", 
    returnTo = "" },
  new { Id = @"\d+" }

What that {*returnTo} parameter does, is catch everything after '/ReturnTo/' in the url path (this excludes any querystring) - it is important to note that this also includes all of the slashes and does not convert anything into ugly '%2f' type notation.

update your markup

Now the exact same markup above outputs this nice url instead:


Better, but still a bit more than we need, we can make it look better by changing the markup slightly:
<%= Html.ActionLink("Delete", "Delete", 
  new { Id = 15, 
    returnTo = ViewContext.HttpContext.Request.Url
      .LocalPath.ToString() })

Adding in that '.LocalPath' now gives us this:


A nice, very readable url.

return to the url

The rest is pretty trivial, just return to the url:
public RedirectResult Delete(int Id, string returnTo)
    // do your magic here, then:
    return Redirect("~/" + returnTo);

Parsing Strings to Enums with a Simple Univeral Extension

getting an enum to a string is easy, but switching back can be a pain

If I have an enum:
public enum WhatToShow { All, Courses, Seminars };

and I want to turn a string "Courses" back into that enum Type, there are a few ways I could do it. The most basic way would be to use a switch statement; that is a pain, especially for large enums, plus it has to be re-written for each enum. Here is a simple extension you can use to convert strings back into enums:
public static T ToEnum<T>(this string strOfEnum)
    return (T)Enum.Parse(typeof(T), strOfEnum);

Now if I have a simple string, it is simple to turn it back to an enum:
string str = "Courses";
WhatToShow en = str.ToEnum<WhatToShow>();

Forganizer - unobtrusive network file organizer - new open source project

An unobtrusive intranet ASP.NET MVC application for logically tagging, organizing and searching network files in one centralized location with a fast and simple interface

Me and some friends have a network set up where we share movies and music. This is a Windows domain network and we all simply share our folders as 'shares' across the network. The problem is that there are so many different files and they are all spread out, there was no way to browse them all at once in any sort of convenient way. That is where the idea for forganizer came up, it is simply a tagging and search interface for multiple shared drives (or just your local ones if you want). Since I hadn't really made any MVC projects yet, I decided to do this one in ASP.NET MVC, a great new technology. Also, this was my first attempt at many new programming techniques I hadn't really used in the past such as Unit Testing, Inversion of Control (Dependency Injection) and Mocking, all very useful!

I want to say right up front, this is for a Windows network, and will work best with... err... IE7+, because it works best with your file explorer - some features like folder opening and downloads may not work with other browsers.

You can always check out my source code if you want to see how something was done, here I am just going to explain what the program does from a user point of view.

clean install

Once forganizer is installed (just run Content/setup.sql and publish the rest to a website, making sure you have MVC installed and all that good stuff) you will see this:

Now you need to add some files to the system, here is the directory we are going to add for the demo. Notice that there are some files in the top folder, and also some folders that go down (quite a few nested folders actually).

adding some files

To add new files in, simply click on the 'manage' tab on the upper right. The default page for manage is 'add files' so you simply enter the network path in the 'from folder' field and click 'run it'.
Notice that it only uploaded 8 files, those are the files in the root. If you check the 'recursive' checkbox, if will go ahead and run through all of the files regardless of depth:
The system will never add a file more than once, so feel free to run the same folders over and over, in fact, that is how you enter new files that have been put on the shares - I think later I will implement and auto-updater. Now if we were to will in more of the textboxes the system would be more selective. Say I wanted to exclude all of the .txt files I have, I would just fill '.txt' in the 'exclude extensions' blank. Similarly, if I am only interested in video files, I would just put '.avi .mpg .mpeg' in the 'include only these extensions' field - it's really pretty self-explanatory.

now you are up and running

Click on the 'search' tab or on 'forganizer' and you will see that you now have a tidy list of files. Also, you will notice that on the right side, all of the file extensions that were in your folders are now represented in the extensions cloud, sized by the relation of file count - in my example, there are many more .cs files than anything else:
Each file has download, open folder and delete links next to it. They all do what you think they would, except delete does not actually delete a file, just the reference in forganizer. If you delete a reference, then later restore it, it will still hold all the tags you previously assigned to it.

tag some stuff

As of right now, this doesn't do us much good, they are searchable by file extension (just click on the file extension on the right), but you could do that in Explorer. We want to add some tags, so click on 'manage' again, and then on 'mass tag adding' on the right side menu.
In this example, I am adding the tag 'Testing' to all the files in the directory \\network_drive\share\folder\forganizer\Forganizer.Tests. Now go back to the search, and you can see that many of the files have been tagged:
The 'mass tag delete' and 'mass tag edit' work just the same as above (actually runs the same exact code). Notice that I also manually added the 'wallpaper' tags to a couple .jpg files - that was done simply by typing 'wallpaper' in the small textbox by each file and clicking '+tags' or pressing enter. You will also see that now there is a cloud tag on the right showing the tags that are in the present search.

create categories

Now you can make some categories to make searching easier. Categories are just groups of file extensions, I am going to make a 'programming' category that includes .js and .cs files:

the manual tagging interface

Now going back to the main search, you will see that a 'programming' category is now in the sidebar. In the following picture, you can see that I have clicked on the 'WebUI' tag and the '.js' file extension. Now all I see is the .js files that are tagged with 'WebUI', it's just that simple! Also take note of the intuitive urls achieved with MVC.
I also typed MS in some of the .js file blanks as I am going to tag those as MS javascript files by pressing enter:
Those MS tags are now inserted.

Now if you want to delete a tag, simply hover over it and a [delete] link will show up:
Click it and the tag is removed:
Pretty basic stuff and simple to figure out and use. This same add/delete interface is used for categories as well.

file cleanup

Now what if someone went and deleted some files, since forganizer does not actually constantly monitor the files, it will be out of date. That is why I built a cleanup feature - say I delete these files:

I can just go to manage -> file cleanup and click the big button:
And you are all cleaned up. One great feature on this is if any file is deleted, either manually or by the cleanup tool, its tags will be preserved; if that file is ever re-added, or restored, it will still have all the meta-data that it always had.

some more stuff

I went ahead and added the 'WebUI' tag to all the files in the \\network_drive\share\folder\forganizer\forganizer.WebUI folder, and 'DomainModel' to all files in the \\network_drive\share\folder\forganizer\forganizer.Tests folder, and finally 'forganizer' to all the files in the \\\network_drive\share\folder\forganizer\forganizer folder, so I can easily discern all of those files. I also added a 'visual_studio' category that include .csproj, .sln and .suo extensions, as well as a documents and images category.

So now I want to find all the Visual Studio related files in forganizer; all I need to do is click on 'visual_studio' in the categories, and 'forganizer' in the tags section and I get the files I am interested in:
Think of it now as "showing all the .csproj, .sln and .suo files with the forganizer tag" Notice that in the upper right, 'and' has a box around it, you can also choose 'or' and it will be a broader search. Say I clicked the 'or' link and then clicked the 'wallpaper' tag and 'images' as well, now forganizer would be showing "showing all the .csproj, .sln, .suo, .png, .jpg and .jpeg files with the forganizer tag OR the wallpaper tag"
You will also see that each cloud (tags/extensions/categories) will be broken into 2 parts, the active (green) links and the inactive (grey) links. The active links are files that are showing in the search right now, the inactive ones are things you can add to the search that will broaden it; if you have 'and' picked in the tag section, you will not see and inactive tags, as that wouldn't make sense.

remember, this is all unobtrusive

This never actually does anything with the files, deleting only deleted the reference, the files will still be there! This is just a layer on top to help sort/search.

I hope this is interesting to someone out there, if not, it was great to help learn MVC and some other great technologies.

<i> is for image, sprite image

a slightly modified, very simple approach to css sprites

Css Sprites are nothing new, it is a way to take one image and use it for everything for faster page loads; pretty simple. On my latest project, I came across a simple way to to employ these sprites in a logical manner; this method even makes for intellisense images in Visual Studio.

prepare your sprites

The first thing to do, is to get your sprites together in a zip file. Basically gather up all the pictures and icons you will be using and put them into a single folder, then zip them up. Here is the zip I am using for the demo (14.12 kb). Then simply go to Project Fondue set up your settings and process. For the purposes of this method, set the 'Css Prefix' to 'i' and clear the other 'Class Output option' fields. Now you have your css, and you can download the image that Fondue produced, which is the image directly to the left in this post. The tough work is alreaday done, now you are ready to implement it.

the <i> tag

As stated in the title, I chose to use the <i> tag. This tag was originally used for italics, but that practice is not always followed, and most people use CSS reset anyway, so it is up to us to choose what we want it to mean... and I chose 'image' (the img tag wont work as it rendered the ugly 'image not found' image in most browsers). So for this to work, you are going to have to first reset the <i> tag to nothing in css, then set it's background to the sprite image; I will assume you are using your own css reset, and my sprite to the right is called sprites.png.:
i {background:url(Images/sprites.png) no-repeat; 
   display:inline-block; width:24px; height:24px; }

/* code produced by Fondue */
i.danger { background-position: 0 0; } { background-position: 0 -74px; } 
i.error { background-position: 0 -148px; } 
i.folder { background-position: 0 -222px; } 
i.reload { background-position: 0 -296px; } 
i.success { background-position: 0 -370px; } 
i.trash { background-position: 0 -444px; } 
i.warning { background-position: 0 -518px; } 

I am setting the default height/width to 24px because that is the size of my icons, if all of your are not the same, you can either set a default size here, or size every one indivually; I recommend using the most common size as the default for the smallest css.

*If you do have images of different sizes, be sure to set their height/width in their corresponding css classes.

use it

Now you are all set, the html:

<i class="danger"></i>

Produces and:

<i class="download"></i>

Produces and so on. Plus, if you are using visual studio, you will notice since these are css classes, they pop up in your intellisense, so it is easy to push out images on the fly in code.

Setting up Castle Windsor IoC (Inversion of Control) aka Dependency Injection

it can be a bit confusing getting this thing running

Dependency Injection is the new big thing, and I am late on that bandwagon. But I recently began using Castle Windsor while learning ASP.NET MVC through reading Pro ASP.NET MVC Framework which is a fantastic book.

Anyway, setup can be a little pain to go through, and is no longer exactly as written out by the book, so here is a quick and simple guide:


  • Visit the Project Page and look for the MicroKernel/Windsor project, download the latest stable version (it was 2.0.0 while writing this).
  • Copy the dlls to your bin or register them in your GAC.
  • Reference the following libraries:
    • Castle.Core
    • Castle.DynamicProxy2
    • Castle.MicroKernel
    • Castle.Windsor

alter your web.config

Add in the following inside the <configSections$gt;

<section name="castle" type="Castle.Windsor.Configuration.AppDomain. CastleSectionHandler, Castle.Windsor" />

Add this right before your <system.web>


that's it

That's all it takes, your Castle Windsor should now be running.

Getting the Sheet Name(s) from an Excel Document with OleDb

users name their sheets all sorts of crazy things, but sometimes, I want to be able to get the sheet names regardless of what they are named

Considering that I already have my ConnectionString strC set up to access my Excel file, I can just use the GetOleDbSchemaTable method like this:
DataTable dtS;
using (OleDbConnection c = new OleDbConnection(strC))
  dtS = c.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, 
    new object[] { null, null, null, "TABLE" });

Now dtSchema holds the sheet names (in alphabetical order). To get them out:
foreach(DataRow row in dtS.Rows)