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!

Naspinski.Utilities now on NuGet

by naspinski 10/20/2012 5:03:00 PM

Utilities class for .Net including Dynamic property getters/setters, automatic IQueryable searching, LinqToSql shortcuts, FileStream shortcuts, String extensions and more

This is a utility class that was developed with the help of others that I use in almost all of my .Net projects. It is available via NuGet as well as on CodePlex. It includes:

DynamicProperty

Change a property value at run time without knowing the property ahead of time:
someObject.SetPropertyValue("Name", "new value")
// is the same as 
someObject.Name = "new value";
// no need to know which property to code in

More Information

IQueryableSearch

Search all/any properties of an IQueryable with one single search.

The 'quick search' is a great tool. Google has shown us that searching with one single, universal search field is the way that people prefer to search. Anyone who has worked with Linq for any amount of time knows this is possible, but it requires a lot of hard-coding and a long jumble of 'where' statements. This class will allow you to run a universal 'google-like' search on any IQueryable. More Information
var results = cars.Search(new object[] {"chevy", 2007});
// will search cars for the string "chevy" 
// and the int 2007 across all fields


LinqToSql

Universal Get Extensions for your DataContexts, Find the Primary Key of any table, and more
Naspinski.Utilities.GetPrimaryKey<table>();
// will return the PropertyInfo of the Primary Key(s) of 'table'

someDataContext.Get<Car>(someKey); 
// is the same as writing:
someDataContext.Cars.FirstOrDefault(x => x.id == someKey);
// regardless of what Type someKey is or what the 
// PropertyInfo.Name of the Primary Key is; never write 
// a Get accessor again!

FileStreamSave

Simple extension to save a FileStream to disk, option to avoid overwriting will automatically update the filename to avoid overwriting:
someFileStream.Save(@"C:\file.txt")
// will save the file to the given path
// 'file[1].txt' if the file is already there 
// the file name will be returned 

someFileStream.Save(@"C:\file.txt", false);
// will save the file to the given path,
// overwriting if the file already exists

StringConversions

Convert strings to things you often need to convert them to, easily.
string s = s.RemoveCharacters(new[] { 'a', 'b' })
// removes any instances of 'a' or 'b' from s

string s = Strings.Random(10)
// random string, all alphanumeric, length 10
string s = Strings.Random(10, 2)
// random string, min 2 special chars, length 10

double x = "8".To<double>; 
// converts string to any type 
// (double in this case)

EnumType et = "Something".ToEnum<EnumType>; 
// turns string into any enum 
// (EnumType.Something in this case)

int? x = "5".ToNullable<int>;
// turns a string into any Nullable Type you want 
// (int in this case)

Tags: , ,

c# | linq

Quick LINQ Trick

by naspinski 9/18/2012 4:21:00 PM

cool way to shorten and make your code more readable with LINQ

Say I have this function:
public string DoStuff(string s) 
{ 
    //whole bunch of stuff
    return s; 
}

Now say I have the following:
public IEnumerable DoThings(IEnumerable strs) 
{  
    var ret = new list();
    foreach(var s in strs)
        ret.Add(DoStuff(s));
    return ret;
}

Which can be reduced to:
public IEnumerable DoThings(IEnumerable strs) 
{  
    foreach(var s in strs)
        yield return DoStuff(s);
}

Or...
public IEnumerable DoThings(IEnumerable strs) 
{  
    strs.Select(x => DoStuff(x));
}

but even further you can simply take it to:
public IEnumerable DoThings(IEnumerable strs) 
{  
    strs.Select(DoStuff);
}

Since the enumeration is already strings, the Select statement knows just to pass them through the method supplied. With it this small, the method is almost useless to write out:
// Tnstead of:
var x = DoThings(strs);

// you can simply substitute: 
var y = strs.Select(DoStuff);

// giving you the same results without having to write 
// a method

It's nothing revolutionary, but can clean up your code where applicable.

Updating Multiple Fields via LINQ and Reflection Automatically (EF4)

by naspinski 5/23/2011 4:00:00 PM

You can use reflection to avoid manually entering a ton of fields

Recently, the question was asked on Stackoverflow about updating multiple integer fields in an EF4 object without having to type each out manually. I had run into a similar problem like this in the recent past where I had a large number of int fields (38 to be exact) and I didn't really want to write in 38 lines of essentially the same thing into my code. Instead, I cam up with this using Reflection. This simple example shows an object 'o' and a single new value 'newValue', but you can easily use an array or list as well for inserting values - this just gets the point across:
foreach(PropertyInfo prop in o.GetType().GetProperties()) 
{
    if(prop.PropertyType == typeof(int))
        prop.SetValue(o, newValue, null);
}

You can see in this example, I look only for integer fields, but it would be simple to check for any other type of field, or name, or a field that has a name that starts with 'abcd' - the list is endless and simple to adapt to.

A relationship is being added or deleted from an AssociationSet ...

by naspinski 12/19/2009 5:06:00 PM

this error may be cause by a Foreign Key changed that gets missed by Linq-to-Entities

My old Linq-to-Entities project came back to haunt me. I had to make some changes to the DB to allow a couple things, and with that, I changed some INT NOT NULL REFERENCES change to INT REFERENCES - the obvious difference being that they now allowed null values. No big deal really, I went into my .edmx file and did 'Update Model from Database' and everything seemed to be working fine, until I tried a certain operation that kicked out this doozy:

A relationship is being added or deleted from an AssociationSet 'FK__Gizmo__CategoryI__0425A276'. With cardinality constraints, a corresponding 'Gizmo' must also be added or deleted.


Now those arent the actual values, but you get the idea. This is telling me that my Foreign Key relationship is being violated, which confused me. I had changed that FK to be nullable, so this should not be happenening. I then tried the same operation in SQL Server Management Studio, just to be sure it was legal on the SQL side, and it worked fine. So I figured, like so many times before, the problem lies with Linq-to-Entities. I opened my .edmx and saw something like this:
As you can see, it clearly shows a one-to-many relationship from Category->Gizmo. This was no longer the case, but L2E failed to pick up on it.

The bottom line is that 'Update Model from Database' did not catch the Foreign Key change


Once I figured this out, it is a simple to fix. Simply right-click on the relationship (in the box above) and click 'Properties'; that will bring up the Properties dialogue. Once this is open, change the End of the referenced table from '1 (One)' to '0...1 (Zero or One)' and save your .edmx.



This should not be necessary as you would assume 'Update Model from Database' would catch things like this, but like so many other things in L2E, it just doesn't work like you want it to. I can't wait for .Net 4.0, supposedly most of the problems with L2E are getting fixed; we'll just have to wait and see.

Tags: , ,

c# | entities | linq

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.