January 2008 - Posts

LINQ to SQL generates business objects that work similar to datasets.  There are some upsides and downsides to that, but overall, I like the approach.  LINQ to SQL creates these classes all in the same namespace, so if you have the same object in multiple LINQ-to-SQL class designers in the same namespace, you will get an error in this respect.  The best approach may be to create one massive data model for your entire database.  Though this may seem like a problem, LINQ can solve this by using a deferred loading approach.

This means that table data loads when you access it.  However, all the data loads into that table (but not into respective child tables unless you set it up to load immediately) because LINQ needs the entire data set to query against it.  This often puts people on edge about the usefulness of it from the get-go.

However, it's nice because LINQ manages its state for you, and manages all the relationships between objects.  It also can have individual properties be lazy loaded (such as loading raw data).  And, the designer manages all the relationships between entities, and each relationship is setup as a parent/child collection approach, so the parent object can have immediate (yet lazy loaded) access to its children.

 All in all, it is a good idea, though for those who love to have control over their data model, it may not be the most ideal.  Something like LINQ to Entities, which should be released this month or the beginning of February, may be a better approach.

Posted by bmains | with no comments
Filed under:

Sometimes there needs to be logic that someone on the outside using your object can do.  For instance, there is a piece of calculation that only the subscriber of the class can use.  Instead of using inheritance and the template method approach, it's also possible to perform some of this through a delegate.  Simply creating a delegate as such:

public delegate float CalculateValueHandler(Account account, MortgateRate rate);

Allows the code to do this:

public void Calculate(MortgageRate rate, CalculateValueHandler handler)
{
  Accounts accounts = AccountService.LoadAccounts();
  foreach (Account account in accounts)
    account.Estimate = handler(account, rate);

  this.SaveChanges();
}

This may not be the most practical example, but delegates can be more useful than inheritance in certain situations.

Posted by bmains | with no comments
Filed under:

I learned an interesting technique whenever I was looking at the Validation Application Block the other day.  Each validator has an attribute associated with it, so you can define validation at the attribute level of a business object.  So the following property of a business object can look like this:

[NotNullValidator]
public string Text { get; set; }

This essentially says that the text property is required.  To validate this, reflection is used to extract the validator declarations for a property, and to call those validators with the designated business object property appropriately.  All of this happens on the fly, and you don't have to worry about a thing this way.  When creating custom validators, you do have a little more concern over how things are established.  Like I said, each validator has an attribute, and you should do the same when creating custom ones yourself.

When creating a custom validator attribute, a base class of the ValidatorAttribute, or other specific ones like the ValueValidatorAttribute, provide some functionality for you, and require you to override the method:

Validator DoCreateValidator(Type targetType);

However, there is another method that does the same thing:

Validator DoCreateValidator(System.Type targetType, System.Type ownerType, Microsoft.Practices.EnterpriseLibrary.Validation.MemberValueAccessBuilder memberValueAccessBuilder)

The second overload gives you more of an ability to work with validators that validate other properties (like the PropertyComparisonValidator).  In the base class, this method simply calls DoCreateValidator(targetType), and the first method has to be overridden.  However, I realized something; the framework uses the second method first, and if you don't need to access other properties, then you can simply allow the call up the hierarchy.

But I thought that was interesting; the reason is you can override the second one, and that can be used for your specific needs and ignore the base class call to the first method.  I thought that was interesting because essentially this develops a hierarchy of methods; sometimes you need the more detailed options, but if you don't the call propogates up the hierarchy to the less specific implementation.  An interesting design pattern.

Posted by bmains | with no comments

Extension methods are really cool.  The following is an example of one, and I'll discuss it in detail:

public static class StringExtensions
{
   public static string GetFormattedValue(this string data)
   {
      //Do some formatting
   }
}

In the above example, you notice similarities to a normal static class; however, this can be applied to an instance of a string, as shown below:

string value = "   this is my sentence.   ";
string formattedText = value.GetFormattedValue();

The method defined in the static method above can be used in the string instance below.  Let's go into detail.  An extension class in this situation must be a static class; that is a requirement.  Secondly, the "this" declaration as the first parameter notes the type to extend (a string in this instance).  It, in reality, can be any instance class in the .NET framework or any custom library (no limitations except for non-static classes only).  Next, the first parameter of this static extension method is the type to extend, but the rest of the parameters are the parameters for the method.  So if the method was:

public static string GetFormattedValue(this string data, bool trim, bool punctuate, bool camelCase)
{
   //Do some formatting
}

It would be invoked as such:

string formattedText = value.GetFormattedValue(true, false, false);

Very handy to have.  And very easy to create.  You will see this a lot in the .NET framework 3.5; the lambda expression methods (Where, Contains, First, etc.) are often static extensions defined on the list, and there are many other places throughout.

Posted by bmains | 1 comment(s)

When querying for a single item, bringing back a collection from a query brings back an enumerable list when all you wanted was a single item.  You can use the First() method to return the first item in the list, thus getting the item from the query as such:

var data = (from o in Orders
               where o.OrderID = id
               select o.Name).First();

However, it may cause problems if no records exist in the query, so it may be more beneficial to do:

var data = (from o in Orders
               where o.OrderID = id
               select o.Name);

if (data.Count() == 0)
    return string.Empty;
else
    return data.First();

Posted by bmains | 4 comment(s)
Filed under:

Oftentimes, when working with an API, it is helpful to utilize the best of generics; after all, generics automatically strong-type a class, and avoid boxing/unboxing issues.  There can be some downfalls to this approach, however.  For instance, if you have an classes called Menu, Document, Window, all of which inherit from the same base class (say UIObject, for instance).  The generic strongly-typed collection looks like this:

public class UIObjectCollection<T> : List<T> where T:UIObject { }

However, one of the benefits of polymorphism is that you can work with the base class interface without having to worry about the specifies.  For instance, usually Menu, Document, and Window have derived collection classes as such:

public class MenuCollection : UIObjectCollection<Menu> { }
public class DocumentCollection : UIObjectCollection<Document> { }
public class WindowCollection : UIObjectCollection<Window> { }

This approach is very handy, because generics strong-type the collection class, without having to write any additional code.  However, sometimes, it helps to work in generalities, and work with the base class of UIObjectCollection.  However, with generics, it's not UIObjectCollection, it's UIObjectCollection<Menu> and UIObjectCollection<Document>.  This can be problematic.

The solution can be to use an interface.  Define an interface as such:

public interface IObjectCollection
{
  void Add(UIObject item);
  void Remove(UIObject item);
}

Then, in the root collection, define this:

public class UIObjectCollection<T> : List<T>, IObjectCollection where T:UIObject
{
   public void Add(T item) { .. }
   public void Remove(T item) { .. }

   void IObjectCollection Add(UIObject item) { this.Add((T)item); }
   void IObjectCollection.Remove(UIObject item) { this.Remove((T)item); }
}

The interface simply reuses the existing methods, simply by casting the parameter.  T is a UIObject class anyway, and can be downcast.  This situation solves some of the dynamic typing feature that's lacking in .NET.  The interface lets you cast MenuCollection and DocumentCollection to IObjectCollection, so you don't have to know the generic type off-hand.

Posted by bmains | 4 comment(s)
Filed under:

I wanted to touch upon some of the capabilities with LINQ.  I'm getting into a project that will be using LINQ, and so I've been looking at its capabilities and trying to discover all that it can do.  Here are some of the basic LINQ queries that you can perform.  If you don't know what LINQ is, you can find out about it by googling LINQ.  Basically, LINQ takes some of the capabilities of SQL for databases, and .NET-ified it by allowing you to query collections, XML files, and databases through code, in a very simple approach.

LINQ is handy because you can parse through a collection easier.  Before LINQ, if you had a collection of business objects, which the object has a category property, to get a distinct list of categories meant iterating through the list and adding the category name to another temporary collection.  With LINQ, this is a snap.  Below is an example; the collection being queried is a ResourceItemCollection that has ResourceItem objects.  This object type has a category property that is a struct, with the underlying string value being categoryname.

The following is the LINQ query to get a distinct list of category names:

var categories = (from resx in resources
                       
select resx.Category).Distinct();

That's it.  That's all it takes to get a distinct list of categories.  Let me break down the query.  LINQ moves the select list to the bottom of the syntax, though the from and join statements are in the same order, as well as the ordering.  Resx is like a table alias, naming the resources collection (which is an enumerable list) as resx for future use in the query.  The select clause specifies retrieving the Category property only.  In addition, I could have specified "select resx" without the property, and this would return the entire ResourceItem object.

The Distinct() method, one of many specialty methods, is the method used to get a distinct list of items, which is returned to a variable of type variant.  What is "var", you may ask?  Var allows you to not know what the underlying result will be; however, the framework determines what the underlying return type is, so it is still strongly-typed in VS 2008, along with full intellisense.  In a sense, an anonymous type with a property of the Category struct is created and returned as a list, which is how it can be strongly typed.  Below is how the categories are used:

foreach (var category in categories)
{
    Expander expander = new Expander();
    expander.Header = category.CategoryName;
}

Using var in the iterator allows me to dynamically get the category name, because the framework knows the resulting type was a collection of category structs.

You can also use a where clause, as shown below, which in this case the list of items matching a particular category are returned:

var items = from resx in resources
                
where resx.Category = category
                
select resx;

Notice the where clause; it uses the resx designator to reference the ResourceItem object being compared in the where clause, to the string category listed above.  Also notice the resx designation in the select statement, which selects the object as a whole.  Also note, that if you want to select multiple properties, you can do so in this notation:

select new {resx.Author, resx.PubDate};

As I mentioned before, this creates an anonymous type with an Author and PubDate property; in addition, you may see an issue because it wants them to be named as such:

select new { AUTH = resx.Author, PUBLISHED = resx.PubDate};

Now, the anonymous type has our new property names.

Posted by bmains | 9 comment(s)
Filed under:

Recently, when adding WPF features to a windows class library I created, I ran into an issue where there was an error with the InitializeComponent method of the WPF user control in Visual Studio 2008.  I couldn't figure out why this was an error, as the use of that method hasn't changed with WPF.  After looking around, I found this solution: http://blogs.msdn.com/mhendersblog/archive/2005/10/03/476536.aspx.  Essentially, an import statement needs added to the <Project> element, as described in detail in that blog entry.

Posted by bmains | with no comments
Filed under: ,
The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.