loads of useful information, examples and tutorials pertaining to web development utilizing asp.net, c#, vb, css, xhtml, javascript, sql, xml, ajax and everything else...

 



Advertise Here
C-Sharpener.com - Programming is Easy!  Learn Asp.Net & C# in just days, Guaranteed!

ServerInfo - Easily scan a Machine/Server Farm for Information

by naspinski 7/31/2010 12:23:00 PM

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.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

c# | mvc | my projects | xml

Edit an Object Property Value Dynamically at Run Time

by naspinski 6/1/2010 12:13:00 PM

no need to write a huge switch statement to make a run time decision

Imagine you have an Object with 50 properties, and at runtime, you only need to change the value of one of them. You could write a switch statement to run through all of them, but there is a better way. This is how it would be done with a switch:
switch(propertyName)
{
    case "Name": obj.Name = newVal; break;
    case "Phone": obj.Phone = newVal; break;
    ///and so on...

That sounds like a terrible idea. With Reflection, it was easy to build an extension to update any object with a new value at runtime (provided it can be written to) with the following code:
public static void SetPropertyValue(this object o, 
    string propertyName, object newValue)
{
    PropertyInfo pi;
    pi = o.GetType().GetProperty(propertyName);
    if (pi == null)
        throw new Exception("No Property [" + 
            propertyName + "] in Object [" + 
            o.GetType().ToString() + "]");
    if (!pi.CanWrite)
        throw new Exception("Property [" + 
            propertyName + "] in Object [" + 
            o.GetType().ToString() + 
            "] does not allow writes");
    pi.SetValue(o, newValue, null);
}

Now, instead of that 50+ line mess above, all you need to do to change the "Phone" property to 'newVal' is:
obj.SetPropertyValue("Phone", newVal);

I added this to my Naspinski.Utilities Set on CodePlex as well.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

c# | my projects | steal some code

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

by naspinski 12/14/2009 1:15:00 PM

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

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

c# | my projects

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

by naspinski 12/10/2009 1:18:00 PM

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.

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

c# | linq | linq-to-sql | my projects

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

by naspinski 12/7/2009 7:29:00 AM

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.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

c# | linq | linq-to-sql | my projects