ListItemCollection.SyncToList
10 January 08 12:16 AM | danieb | with no comments

Here's a example that uses extension methods, lambda expressions and anonymous methods to synchronize values from a ListItemCollection to a EntityList (Linq to SQL).

/// <summary>
///
This is used to easily bind a CheckBoxList to a EntitySet
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items">
List of items to Sync </param>
/// <param name="list">
EntitySet to Remove from</param>
/// <param name="selected">
Method to Find</param>
/// <param name="create">
Method to Create a New Instance of T from a ListItem</param>
/// <param name="delete">
Method to Delete T</param>
public static void SyncToList<T>(this ListItemCollection items
    , EntitySet<T> list
    , Func<T, ListItem, bool> selected
    , Func<ListItem, T> create
    , Func<T, bool> delete)
   where T : class, new()
{
    foreach (ListItem item in items)
    {
        T litem = list.FirstOrDefault(p => selected.Invoke(p, item));
        if (item.Selected && litem == null)
        {
            litem = create.Invoke(item);
            list.Add(litem);                   
        }
        else if(!item.Selected && litem != null)
        {
            if(delete != null)
                delete.Invoke(litem);
            list.Remove(litem);     
        }
    }
}

Example (Linq to SQL):

this.chkl_Clients.Items.SyncToList<UserClient>(this.User.UsersClients,                                    
delegate(UserClient u, ListItem i)
{//Selected
   
return u.ClientId == int.Parse(i.Value); },           
delegate(ListItem l)
{//Create
   
UserClient u = new UserClient();
    u.UserId = this.User.UserId;
    u.ClientId = int.Parse(l.Value);
    return u;
}
,delegate(UserClient u)
{//Delete
   
Factory.DataContext.UsersClients.DeleteOnSubmit(u);
    return true;
}
);           
DataContext.SubmitChanges();

ListItemCollection.SelectByValue, SelectByText
09 January 08 11:42 PM | danieb | with no comments
I found a very easy way to select items in a ListItemCollection 
using Extension Methods, Anonymous Methods and Lambda Expressions.
 /// <summary>
 /// This will select the items in a ChekboxList, ListBox
 /// </summary>
 /// <typeparam name="T">Type of items</typeparam>
 /// <param name="items">Source</param>
 /// <param name="selectionList">Selected items</param>
 /// <param name="property">Expression to select items</param>
 public static void SelectByValue<T>(this ListItemCollection items
,IEnumerable<T> selectionList
, Func<T, string> property) where T : class, new() { foreach(ListItem i = items)
i.Selected = selectionList.FirstOrDefault(
p => property.Invoke(p) == i.Value) !=
null; } /// <summary> /// This will select the items in a ChekboxList, ListBox /// </summary> /// <typeparam name="T">Type of items</typeparam> /// <param name="items">Source</param> /// <param name="selectionList">Selected items</param> /// <param name="property">Expression to select items</param> public static void SelectByText<T>(this ListItemCollection items
, IEnumerable<T> selectionList
, Func<T, string> property) where T : class, new() {
foreach(ListItem i = items)
i.Selected = selectionList.FirstOrDefault(
p => property.Invoke(p) == i.Text) !=
null; }
Here's an example :
chkl_Roles.Items.SelectByValue<Role>(this.User.Roles,
delegate(Role r) { return r.RoleId.ToString(); });
The Worst Bug Ever
26 November 07 06:24 AM | danieb | 1 comment(s)

I do support on a SharePoint Portal (2003, Framework 1.1). Last week after we deployed some new functionality we started to get very strange errors. The portal would just break at random arbitrary functions. I traced the root cause to the following warning in the System Event Log:

A process serving application pool 'X' suffered a fatal communication error with the World Wide Web Publishing Service. The process id was 'X'. The data field contains the error number.

After investigating the application log for hours, days I found nothing but errors caused by the chain reaction of error in the application log. However we would receive this error quite often.

Common Language Runtime detected an invalid program.

Then eventually it logged an error that basically said that it’s failing to compile a temporary file.

Cannot execute a program. The command being executed was "c:\windows\microsoft.net\framework\v1.1.4322\csc.exe" /noconfig @"C:\WINDOWS\TEMP\lannijk8.cmdline".

Thinking I had found the problem I delete the windows temp and the Asp.net temp directories. However a couple hours later the error was back, but not logging the Compile issue, only the warning in the system event log.  Googling the errors, didn’t return anything that made any sense.

Eventually we figured out (after reading this article) that when I added an extra Web Method to an existing web service, the generated Web Service had too many local variables.  I don’t know what the exact number is for .net 1.1 but for 2.0 its 32767, which is really a lot.

See .net declares a local variable for each method and parameter in your web service and compiles this class.

So we resolved the issue by removing some of the web methods, but if this is not an option there's a hotfix available to raise that limit to 4 million.

Using Generics, Anonymous Methods and Delegates to join.
20 November 07 04:54 PM | danieb | with no comments
/// <summary>
/// Delegate used to in Join
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public delegate object JoinDelegate<T>(T obj);
/// <summary>
/// Anonymous Method Delegate Join
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <param name="join"></param>
/// <param name="delimiter"></param>
/// <returns></returns>
public static string Join<T>(IEnumerable items, JoinDelegate<T> join, string delimiter)
{   
    StringWriter sw = new StringWriter();
    bool firstTime = true;
    foreach (T t in items)   
    {
        if (firstTime)
            firstTime = false;
        else
            sw.Write(delimiter);
         sw.Write(join.Invoke(t));
    }
    return sw.ToString();

}

public struct StructTest
{
    public StructTest(string ID){this.id = ID;}
    public string id;
}[TestMethod]
public void Test_GenericJoin()
{
    StructTest[] items = new StructTest[] { new StructTest("1"),
                                            new StructTest("2") };
    string result = StringHelper.Join<StructTest>(items,
                               delegate (StructTest item)
{ return item.id;});
    Assert.AreEqual("1,2", result);

}

 

Custom Ajax Controls
11 June 07 11:30 AM | danieb | with no comments

I have uploaded a demo of some custom AJAX controls we've pieced together.

  • DropDownList with paging
  • ImageDropdown with paging
  • Holiday support for the Calendar Control

Check out the sample and download the source code.

Publishing Code from Word 2007
06 June 07 06:59 PM | danieb | 2 comment(s)

I found a way to trick word in publishing code with the correct format and spacing.

You can do a find replace on:

  • "^p" (paragraph) with "^l" (newline)
  • " " (4 spaces) with "^t" (tab)

I don't know if there is a better way but this works quite well check the beautiful formatting here and here

To yield, or not to yield
06 June 07 05:43 PM | danieb | with no comments


I must say the yield keyword new in 2.0 is one of my favourites.
How I would best explain it best is that it iterates on demand.
Here is a very cool enumerator I wrote for our Exception Handler class.
Download the sourcecode here
/// <summary>
///
Enumerate the exception and the inner exceptions
/// </summary>
///
<param name="ex"></param>
///
<returns></returns>
public static IEnumerable<Exception> GetEnumerator(Exception ex)
{
    Exception tmp = ex;
    while (tmp != null)
    {
        Exception toYield = tmp;
        tmp = tmp.InnerException;
        yield return toYield;
    }
}


This made searching for specific exception type or formatting our exceptions much more elegant and faster in theory
(I say in theory since I don't think iterating thru exceptions is very CPU intensive!).
This small console app just illustrates the iteration on demand:
class Program
{
    public static IEnumerable<int> GetEnumerator()
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("yield for :" + i);
            yield return i;
        }
    }
    public static List<int> GetItems()
    {
        List<int> ret = new List<int>();
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("for :" + i);
            ret.Add(i);
        }
        return ret;
    }
    static void Main(string[] args)
    {
        foreach (int j in GetEnumerator())
        {
            Console.WriteLine("yield foreach :" + j);
        }
        Console.ReadLine();
        foreach (int j in GetItems())
        {
            Console.WriteLine("foreach :" + j);
        }
        Console.ReadLine();
    }
}
Here is just an example on how to traverse a tree using yield:
public class TreeNode<T> : IComparable where T : IComparable
{
public TreeNode(){ }
public TreeNode(T data) : this(){this.data = data;}
private T data;
public T Data
{
    get { return data; }
    set { data = value; }
}
private TreeNode<T> parent;
public TreeNode<T> Parent
{
    get { return parent; }
    set { parent = value; }
}        
private TreeNodeCollection<T> nodes;
public TreeNodeCollection<T> Nodes
{
    get
    {
        if (nodes == null){nodes = new TreeNodeCollection<T>(this);}
        return nodes;
    }
    set { nodes = value; }
}
public
IEnumerable<TreeNode<T>> GetAncestors()
{
    return GetAncestors(this);
}
public static IEnumerable<TreeNode<T>> GetAncestors(TreeNode<T> node)
{
    if ((node != null) && (node.Parent != null))
    {
        yield return node.Parent;
        foreach (TreeNode<T> n in GetAncestors(node.Parent))
            yield return n;
    }
}
public IEnumerable<TreeNode<T>> GetDescendents()
{
    return GetDescendents(this);
}
public static IEnumerable<TreeNode<T>> GetDescendents(TreeNode<T> node)
{
    foreach (TreeNode<T> child in node.Nodes)
    {
        yield return child;
        foreach (TreeNode<T> de in GetDescendents(child))
        {
            yield return de;
        }                
    }
}

GenericList<T>, Events, Aggregator
06 June 07 05:42 PM | danieb | 1 comment(s)

Download the sourcecode here

I found this custom class I pieced together quite useful. It's essentially just a wrapper for List<T>, but with some added functionality.

So I added the following events that also supports "Cancel" *
BeforeAdd *
ItemAdded
BeforeItemInsert *
ItemInserted
BeforeRemove *
ItemRemoved
BeforeRemoveAt *
ItemRemovedAt
BeforeClear *


DistinctList<T>
The cancel events allowed me to create "DistinctList<T>" which is quite handy.
Notice that T has to implement IComparable since the Contains evaluates the "CompareTo" on T to determine if it's contained in the list. (This is crucial for custom objects)
/// <summary>
///
A Disctinct list of items
/// The list will automatically check that no duplicates are added to the collection
/// </summary>
///
<typeparam name="T"></typeparam>
public class DistinctList<T> : GenericList<T>
where T : IComparable
{
    protected override bool OnBeforeItemInsert(int index, T item)
    {
        if (!this.Contains(item))
        {
            return base.OnBeforeItemInsert(index, item);
        }
        return true;
    }
    protected override bool OnBeforeAdd(T item)
    {
        if (!this.Contains(item))
        {
            return base.OnBeforeAdd(item);
        }
        return true;
    }
    
}

Aggregation
I know Linq will make this obsolete since it supports aggregation but in 2.0 how many times have you written similar code?
List<int> list = new List<int>(new int[] { 70, 20 });
int total = 0;
foreach (int i in list)
    total += i;
Assert.AreEqual(((double)total) / ((double)list.Count), 45.0);

Is this not much easier?
GenericList<int> list = new GenericList<int>(new int[] { 70, 20 });
Assert.AreEqual(list.Average(), 45.0);

Or on Complex types like person:
class Person : IComparable
{
    public Person(string name, int age) { this.Name = name; this.Age = age; }
    public string Name;
    public int Age;

    public int CompareTo(object obj)
    {
        return this.Name.CompareTo(((Person)obj).Name);
    }        
}

We can simply do this:
GenericList<Person> list = new GenericList<Person>(new Person[]{
new Person("Old Guy",70)
,new Person("Young Guy",20)});
Assert.AreEqual(list.Average("Age"), 45.0);

So how does it work? I have pieced together an Aggregation helper that uses the (+) and (-) operators.
public static T Aggregate<T>(Aggregators aggregator, IEnumerable list, string propertyName)
    where T : IComparable
{
T ret = default(T);
    int count = 0;
    foreach (object item in list)
    {
        T value = AggregationHelper.GetValue<T>(item, propertyName);
        switch (aggregator)
        {
            case Aggregators.avg:
            case Aggregators.sum:
                ret = GenericWrapper<T>.Sum(ret, value);
                break;
            case Aggregators.max:
                if (ret.CompareTo(value) > 0)
                    ret = value;
                break;
            case Aggregators.min:
                if (ret.CompareTo(value) < 0)
                    ret = value;
                break;
            default:
                throw new NotImplementedException(
                 string.Format("Aggregator '{0}' not implemented"
                 , aggregator.ToString()));
        }
        count++;
    }
    if (aggregator == Aggregators.avg)
    {
        if (ret is IConvertible)
        {
            double total = (double)System.Convert.ChangeType(ret, typeof(double));
            double avg = total / (double)count;
            ret = (T)System.Convert.ChangeType(avg, typeof(T));
        }
        else
        {
            throw new
NotImplementedException("Type should be IConvertable when using average");
        }
    }
    return ret;
}

The GetValue<T> will either simply return the value or use reflection for complex types to get the value i.e. Person.Age.

For the GenericWrapper<T> I used Lightweight Code Generation (LCG) for operator overloading as shown in this example by Keith Farmer.
Basically what this does it is allows me to call the +,- operators on any type without having to cast.
class GenericWrapper<T> : IComparable, IComparable<T>
    where T : IComparable
{
    public GenericWrapper(T value) { _value = value; }
    private T _value;
    public T Value
    {
        get { return _value; }
        set { _value = value; }
    }

    #region Opperators        
    /// <summary>
    /// cached copy of the Add<T,T> delegate
    /// </summary>
    private static BinaryOperator<T, T, T> addTT;

    /// <summary>
    /// cached copy of the Subtract<T,T> delegate
    /// </summary>
    private static BinaryOperator<T, T, T> subTT;

    /// <summary>
    /// overloaded addition operator
    /// This will use GenericOperatorFactory to create the Add<T,T> delegate
    /// </summary>
    /// <param name="p1"></param>
    /// <param name="p2"></param>
    /// <returns></returns>
    public static GenericWrapper<T> operator +(GenericWrapper<T> p1, GenericWrapper<T> p2)
    {
        // use addTT to cache the delegate locally
        if (addTT == null)
        {
            addTT = GenericOperatorFactory<T, T, T, GenericWrapper<T>>.Add;
        }
        return new GenericWrapper<T>(addTT(p1.Value, p2.Value));
    }

    /// <summary>
    /// overloaded subtraction operator
    /// This will use GenericOperatorFactory to create the Subtract<T,T> delegate
    /// </summary>
    /// <param name="p1"></param>
    /// <param name="p2"></param>
    /// <returns></returns>
    public static GenericWrapper<T> operator -(GenericWrapper<T> p1, GenericWrapper<T> p2)
    {
        // use subTT to cache the delegate locally
        if (subTT == null)
        {
            subTT = GenericOperatorFactory<T, T, T, GenericWrapper<T>>.Subtract;
        }
        return new GenericWrapper<T>(subTT(p1.Value, p2.Value));
    }
    #endregion

    public virtual int CompareTo(object other)
    {
        return this.Value.CompareTo((T)(other));
    }
    
    public virtual int CompareTo(T other)
    {
        return this.Value.CompareTo(other);
    }
    
    #region Sum
    public static T Sum(T x, T y)
    {
        GenericWrapper<T> tmp = (new GenericWrapper<T>(x) + new GenericWrapper<T>(y));

        return tmp.Value;
    }        
    #endregion
}

Divx-Zune
27 March 07 08:04 AM | danieb | with no comments

Transcode DiVX, XViD, and MPEG files with .AVI extensions to zune! See how to?

Date RangeValidator
08 March 07 05:36 PM | danieb | 1 comment(s)

I struggled a bit with a range validator for dates. So hopefully this can help someone.

I tried:

RangeValidator val = new RangeValidator();
val.MinimumValue = DateTime.Today.ToString();
val.MaximumValue = DateTime.MaxValue.ToString();

I but finally got it to work:

RangeValidator val = new RangeValidator();
val.MinimumValue = DateTime.Today.ToString("d");
val.MaximumValue = DateTime.MaxValue.ToString("d");

March 2007 CTP
01 March 07 06:48 AM | danieb | 1 comment(s)

The Orcas March 2007 CTP is available as a Virtual PC image or as a standard self-extracting install.

Vista and Office 2007 Preview Handler Pack released
28 February 07 03:54 PM | danieb | 1 comment(s)

File previewers that come with the 2007 Microsoft Office system allow you to preview the following files in Microsoft Office Outlook 2007:

Microsoft Office Outlook 2007 items.
Microsoft Office Word 2007 documents.
Microsoft Office PowerPoint 2007 presentations.
Microsoft Office Excel 2007 worksheets.
Microsoft Office Visio 2007 drawings.
Images and text files.

Check this cool Preview Handler for *.cs and *.aspx. Then here is another previewer from msdn mag for pdf.

   

  

Inheriting Attributes from an Interface
22 February 07 05:15 PM | danieb | with no comments

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)]

public class SomeAttribute : System.Attribute { }

 

public interface ISomeInterface

{

[SomeAttribute]

string Property { get; set;}

 

[SomeAttribute]

string GetProperty();

}

 

public class SomeClass : ISomeInterface

{

public string Property

{

get { throw new NotImplementedException(); }

set { throw new NotImplementedException(); }

}

public string GetProperty() { throw new NotImplementedException(); }

}

 

[TestMethod()]

public void TestAttributeOn_ISomeInterface_PropertyInfo()

{

Type t = typeof(ISomeInterface);

PropertyInfo propInfo = t.GetProperty("Property");

 

Assert.IsNotNull(System.Attribute.GetCustomAttribute(propInfo, typeof(SomeAttribute)));

}

[TestMethod()]

public void TestAttributeOn_SomeClass_PropertyInfo()

{

Type t = typeof(SomeClass);

PropertyInfo propInfo = t.GetProperty("Property");

Assert.IsNotNull(System.Attribute.GetCustomAttribute(propInfo, typeof(SomeAttribute), true));

}

[TestMethod()]

public void TestAttributeOn_SomeClass_GetProperty()

{

Type t = typeof(SomeClass);

MethodInfo methodInfo = t.GetMethod("GetProperty");

Assert.IsNotNull(System.Attribute.GetCustomAttribute(methodInfo, typeof(SomeAttribute), true));

}

 

So the second and third test (TestAttributeOn_SomeClass_PropertyInfo, TestAttributeOn_SomeClass_GetProperty) fails.

So if I think of WCF we define an interface with attributes.

 

Example:

 

[ServiceContract]

public interface ICustomers

{

[OperationContract]

string GetCustomer();

}

 

So surely if WCF can inherit attributes we should also be able to do so too!

But wait a minute in WCF only the interface is exposed. Damn!

 

So what is the solution? Recursively check for attributes on inherited interfaces?!

 

 

Vista Drivers
20 February 07 04:32 PM | danieb | with no comments

Here is a cool site if you are looking for Vista Drivers (Has most of the drivers of the big vendors). This will save you some time.

New Releases
19 February 07 08:52 PM | danieb | with no comments

 

Microsoft SQL Server 2005 Service Pack 2

Virtual PC 2007 Released

More Posts Next page »