CohesiveSoftware.com

As I have been getting more and more freelance offers and work, the decision was made to launch a new website and brand

Yesterday I launched CohesiveSoftware.com as a contact point for custom work. Me and some fellow developers have teamed up on a few projects and decided to make it official. If you need any work done, please feel free to drop us a line - happy coding!

ServerInfo - Easily scan a Machine/Server Farm for Information

new open-source project in Asp.Net MVC 2

More than once I have been asked what databases are on what server, if server X is running application Y or what websites server ABC is running. These are are relatively simple things to accomplish, and there are tools available to get this information, but this is an extremely simple and portable solution - all the data is kept in xml, so there is no need to install a backend.

All that it is required to get all this information is to enter ip addresses and the user has the rights to scan the machines requested.

In addition, this can keep track of all of the owners of the machines and has a GUI for running WMI Queries, which is extremely powerful if you know how to use it.

This is written with Asp.Net MVC 2, C# and xml; it requires .Net 4.0 framework. I will be updating this to MVC 3/Razor in the near future.

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
      .GetConverter(typeof(T?)); 
    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);

Error:

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))
    .Cast<T>()
    .Where(GetPrimaryKey<T>()
    .Name + ".Equals(@0)", primaryKey)
    .FirstOrDefault();
}

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;
    break;
  }
  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.

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.

Slick-Ticket v2.0 Released

Many improvements across the board, mostly behind the scenes

I am proud to say that I have released version 2 of my open-source trouble-ticketing/help desk system Slick-Ticket. I wasn't initially planning on making a new release, but the program has become suprisingly popular with over 3,000 downloads and an actual (small) community of users which is great!

You can download Slick-Ticket v2.0 if you have never used it before. If you have already been using a previous version, you will need to replace your existing code with the patching program, run it, then download version 2. It does a few database modifications to cleanup the lack of seperation of markup/db which was done very poorly in a rush of the first version. As with any upgrade, I highly recommend you backup prior to running this upgrade!

improvements

  • Broke the dbi.cs class up into more discreet classes
  • Renamed many methods properly
  • Removed (non-user-added) markup from any of the database fields
  • Moved some markup from the code-behinid to the .aspx pages
  • Globalized and ready for translation
  • Added ability to possibly delete attachments/comments/tickets in the future
  • Introduced some more dependency injection
  • Code is now much more robust!

FormFields for ASP.net - New Open Source Project

transform and simplify your markup by allowing inclusion of form validation, uniform display, Linq-to-SQL integration and databinding with minimal effort

ASP.net forms are already simple, there are many tools such as DetailsView, ListView, etc. that can make our lives easier, but sometimes they just won't do. In those cases, we have to resort to writing repititous code for forms, that is what FormFields was developed for. Writing markup over and over for things such as validation, regular expressions, dropdownlist databinding, etc gets old really fast, so I developed a way to simplify it as much as possible.

Take for example a date entry field. You have your TextBox, then the CompareValidator to make sure it's a valid date, then a Mask to limit the user's input, a RequiredFieldValidator to make sure they enter something, a WaterMarkExtender to guide the user and finally a CalendarExtender to make input easier.

Now this is great stuff for a UI, and not too hard to write, but when you have to do more and more entry fields such as SSN, phone number, a dropdown, then a CheckBoxList; building forms can quickly become cumbersome and hard to understand, become incredibly tedious and turn into a ton of markup.

This is the markup required to do everything mentioned above:

<div class="form-field">
  <h3>
    <asp:RequiredFieldValidator ID="rfvSchoolDate" runat="server" ControlToValidate="txtSchoolDate" ErrorMessage="Required" CssClass="right validate" Display="Dynamic" />
    <asp:CompareValidator ID="cvSchoolDate" runat="server" ControlToValidate="txtSchoolDate" ErrorMessage="Invalid Date" CssClass="right validate" Display="Dynamic" Operator="DataTypeCheck" Type="Date" />
    School Date
  </h3>
  <asp:TextBox runat="server" ID="txtSchoolDate" CssClass="full" />
  <ajax:MaskedEditExtender ID="meeSchoolDate" runat="server" Mask="99/99/9999" MaskType="Date" TargetControlID="txtSchoolDate" />
  <ajax:calendarextender runat="server" id="calSchoolDate" TargetControlID="txtSchoolDate" Format="MM/dd/yyyy" PopupPosition="TopLeft" />
  <ajax:TextBoxWatermarkExtender ID="tweSchoolDate" runat="server" TargetControlID="txtSchoolDate" WatermarkCssClass="light full" WatermarkText="mm/dd/yyyy" />
</div>


All of that can be replaced with just this:

<formField:textBox ID="tb_SchoolDate" runat="server" Type="Date" Required="True" Title="School Date" />


Yes, it is just that easy. The payout and styling is all inherited from a single class and is easy to customize while making for uniform displays. There are multiple different presets for it including SocialSecurityNumber, Date, ZipCode, and a ton more.

This is not only for TextBox fields, it also works for CheckBox, DropDownList, ListBox, CheckBoxList and RadioButtonList. And it not only formats everything the same and takes care of validation (anything that is not automated can be easily added) but it also takes care of databinding as well. Instead of making a datasource, adding an initial entry, binding it to the data and adding a RequiredFieldValidator, you can simply do this:

<formField:dropDownList ID="ddl" runat="server" Title="Category" L2STableName="categories" Required="True" />


No DataSource needed, it is all taken care of within the control itself (this is using Linq-to-SQL and the defaults).

documentation and download

I just wanted to give a quick overview of what it does, I have it fully documented and have more examples here: http://formfields.naspinski.net and it is available for download from CodePlex. I hope some people get some use out of this and I would love if people would want to jump in and add new features.

stuff I still want it to do

It does not render in the designer, and you can't put them into the toolbox - I do not know how to do this just yet, I would love for someone to jump in and help out on this one!

I am taking a much needed 30 day vacation, so no new posts/updates will be happening for a while, but I will be right back to advancing this project when I get back.

Shout it kick it on DotNetKicks.com

IQueryableSearch is now up on CodePlex

another open-source project released into the wild

My IQueryableSearch class has been infinitely useful to me and saved me a ton of time. I have also gotten some good feedback on how useful it is. For those of you that don't know what it does (probably most of you) it is simply a universal search for Linq IQueryable collections; a way to search a bunch of fields/properties on a bunch of objects with one simple interface, like google for your own objects.

With that said, I decided to put it up on CodePlex to better track source code and releases; as just posting them as zips on my blog is a pain when the code is being updated. I am also hoping maybe some of you might want to critique/fix/add to my code to make it better - any interest is appreciated. As always, I hope it helps.

To make it easier it is now available in a dll which you can simply put into your bin, add a:
using Naspinski.IQueryableSearch;

And you are ready to start using it.

On a somewhat related note, I am getting close to releasing another large open-source project I have been working on for quite some time that should prove to save huge amounts of time for ASP.net programmer - stay tuned!

Universal IQueryable Search Version 2 with Reflection

'google-like' search with an IQueryable made even simpler

A little bit ago, I came out with this post: Universal IQueryable Search Usable by Linq-to-SQL and Linq-to-Entities and it worked great, but it got me thinking: if I could implement Reflection, it could be even easier to use and require less code to run as it would get the property names/types automatically. So here I am with the new version and it is working great, it has already saved me lots of time. All of the old overloads work as they did previously, I have just added some more. Here is how a few of them work:

single-level search

Now that reflection is being used, you can pass any sorts of objects to the search and it will only compare like-types, no need to specify. If you are trying to search a collection of 'car' objects in an IQueryable named 'cars' you can just do something like this:

Search(object[] keywords)
var results = cars.Search(new object[] {"chevy", 2007});

That will run through all of the properties of 'car', and if any of them are string variables, they will get compared against "chevy" and if they are Int32 variables, they will get compared against 2007. So this search would pull out all 2007 models made by Chevy.

search for specific properties

The above search will search all the properties of an object, but what if 'car' has 100 properties, and you only want to search 2, that is simple as well with this overload:

Search(string[] properties_to_search, object[] keywords)
var results = cars.Search(
  new string[] {"make", "year"},
  new object[] {"chevy", 2007});

Which will only search the properties 'make' and 'year' for the objects; only comparing like Types.

multi-level search

Now let's say that the object 'car' has a some objects that you want to dig into as properties. The 'car' object has an 'engine' property, but if we run the searches above, it will not drill down into the 'engine' object (though it would compare it if you sent an 'engine' as part of the search array). To get it to drill into the engine object, we need to add another parameter, the Type[] types_to_explore so the Search knows to drill down into objects of that type:

Search(object[] keywords, Type[] types_to_explore)
var results = cars.Search(
  new object[] {"V8"}, new Type[] { typeof(engine) });

Now the Search will search anything in the 'car' object and/or in the 'engine' since it now knows to look inside of it; not to mention it will recursively search down into the objects. This would even find something nested like this:
car
  -engine
    -engine
      -style:"V8"

Since you told it to explore all 'engine' types. This would work even if you wanted to search into string, Int32, bool, etc. Types as they all have lots of properties in the world of Reflection - could be a whole new use for this extension?

multi-level search on limited properties

Basically combine what was covered above:

Search(string[] types_to_explore, object[] keywords, Type[] types_to_explore)
var results = cars.Search(
  new string[] {"engine", "style"}, new object[] {"V8"}, new Type[] { typeof(engine) });

I like this one the least as you have to be most verbose (but not as verbose as the other overloads). If you simply try to search for 'style' here, it will not be found, because you did not tell it to search 'engine' (the property, not the type).

so that's the latest

If you haven't looked at the last post, I highly recommend you do, as it is still the most detailed search overloads are explained there (though a bit tougher to use). This is very hard to explain, so I hope you just take a look at the code yourself or better yet, just try it out, you can see with trial and error how it works better than I can explain in a wordy blog. As always, I am very interested in feedback and improvements!
Shout it kick it on DotNetKicks.com