navigation
 Friday, June 27, 2008
Read all about the tool that is the talk of the industry, what it does and how Falafel created it...
 |  |  |  | 
posted on June 27, 2008  #    by John Waters  Comments [0]
 Thursday, June 26, 2008

More information is to follow, for now see Telerik's announcement at http://blogs.telerik.com/Blogs.aspx

posted on June 26, 2008  #    by John Waters  Comments [0]
 Sunday, June 08, 2008

I had the pleasure to be invited to participate on the "LINQ in the UI" panel at TechED 2008 this week with some of the brightest minds at Microsoft in regards to that topic.  I shared the stage with Amanda Silver, VB Program Manager, Erick Thompson, MS Program Manager and Charlie Calvert, C# community Program Manager.

LINQ_Panel_1

At Falafel, John Waters and Bary Nusz have been working very hard on releasing the new Telerik Trainer product for Telerik Corp. when they have used LINQ to XML and LINQ to Objects to simplify the UI code and make it readable and maintainable to build a XAML based WPF application.  The main point that we wanted to push on the panel is that LINQ is not just for queries and databases, but you can use it's power to build elegant User Interfaces as it is capable to work with any IEnumerable to accomplish the job.

 | 
posted on June 8, 2008  #    by Lino Tadros  Comments [0]
 Monday, June 02, 2008
Anybody familiar with WPF's storyboard knows that animating with the various UI elements is not a problem at all, but what happens when you want the storyboard to call some code behind? The most important thing to remember about the storyboard is that it can only affect dependency properties. So how do we use this to help us call some code behind?
 |  | 
posted on June 2, 2008  #    by Bary Nusz  Comments [0]
 Monday, May 26, 2008
Read about a cool hack in Visual Studio 2008 SP1 that allows the designer to fall back on a hardcoded master page if it doesn't manage to locate the correct one.
posted on May 26, 2008  #    by John Waters  Comments [0]
 Thursday, May 15, 2008
Read this article for some simple tips about how to check if you are on the right thread, and if not, now to get to the right thread, when updating a visual component in WPF.
 | 
posted on May 15, 2008  #    by John Waters  Comments [0]
 Tuesday, May 06, 2008
Consider how many times we’ve run into the following scenario: We’ve got a GUI design, say, a simple WinForm. Upon interaction with the form, we need to launch a CPU-intensive operation, one which might take a while. At some point the operation will complete and we want the result to show on the form. That’s where the problem starts...
posted on May 6, 2008  #    by Angelo Martinez  Comments [0]
 Tuesday, April 29, 2008
I was working on some code today, that was trying to find a string in a list of strings. I came up with a neat way to express it using a lambda expression.
posted on April 29, 2008  #    by John Waters  Comments [0]
 Tuesday, April 15, 2008
Today I refactored some code that has been bugging me for a while, and wanted to share the results. The change resulted in a substantial code reduction and what I felt was a more elegant solution.
 | 
posted on April 15, 2008  #    by John Waters  Comments [0]
 Friday, April 11, 2008
Passing Microsoft Exam 70-315 Web Applications with Visual C# and Visual Studio.NET - A recent exam-taker's experience and tips for success.
 |  | 
posted on April 11, 2008  #    by Rachel Hagerman  Comments [0]
 Saturday, January 26, 2008
Read how to implement the Singleton Design Pattern in C# using Generics
 | 
posted on January 26, 2008  #    by John Waters  Comments [0]
 Saturday, January 19, 2008
One of the things I have come to love about Linq is how you can focus more on declarative programming: focusing on what you want to accomplish rather than how...
posted on January 19, 2008  #    by John Waters  Comments [0]
 Sunday, December 16, 2007
Here is a new language feature that saves a lot of time and eliminates some mindless typing...
posted on December 16, 2007  #    by John Waters  Comments [0]
 Friday, December 14, 2007

I just learnt something new and cool from one of Scott Guthries blogs: the ?? null coalescing operator in C# 2.0. I never noticed it until now, and actually thought it was part of 3.0, until a kind reader corrected me... it's been around ever since the advent of nullable types in C#.

Basically, this operator works like the T-SQL ISNULL or COALESCE function. Read all about it in Scott's blog!

 

posted on December 14, 2007  #    by John Waters  Comments [0]
 Tuesday, November 20, 2007

Falafel is partnering with Microsoft to offer this free half day seminar at the beautiful Saint Claire hotel in downtown San Jose, CA to celebrate the release of Visual Studio 2008, LINQ, WPF, WCF, WF and other exciting technologies.

ActiveFocus Hosting

Please join us on December 10th from 9:00 AM to 1:00 PM
Register on the Microsoft event site ASAP as space is limited.

Charlie Calvert, the C# Community Project Manager will be there to talk about LINQ and Lino Tadros will present the usefulness of the new technologies.
Hope to see you there!
 |  |  |  |  |  |  |  |  |  | 
posted on November 20, 2007  #    by Lino Tadros  Comments [0]
 Tuesday, October 02, 2007
I am currently attending the DevReach conference in Sofia, Bulgaria.
 |  |  | 
posted on October 2, 2007  #    by John Waters  Comments [0]
 Wednesday, September 26, 2007

Wow!  I was told so many times that Visual Studio 2008 will ship in 2007, well it does not sound like that is a possibility anymore.

Microsoft released a new date, February 27th 20008 to release Windows Server 2008, Visual Studio 2008 and SQL Server 2008

2008 Global Launch Wave
963
Days
Windows Server 2008 • Microsoft Visual Studio 2008 • Microsoft SQL Server 2008
posted on September 26, 2007  #    by Lino Tadros  Comments [0]
 Monday, September 17, 2007
Here is an interesting thing I noted the other day. I have an ASP.Net 2.0 application, and in one of the forms, I store the search criteria that you enter on that page in an instance of my ScheduleSearchCriteria class:
posted on September 17, 2007  #    by John Waters  Comments [0]
 Thursday, August 30, 2007
I was debugging some ASP.Net 2.0 code that renders a PDF to the response buffer of a page request, using code like this (byte[] bytes is the PDF file, which was rendered using Microsoft Reporting Services Web Service interface) :
posted on August 30, 2007  #    by John Waters  Comments [0]
 Monday, July 30, 2007
 | 
posted on July 30, 2007  #    by Adam Anderson  Comments [0]
 Tuesday, July 24, 2007

While having some fun with the Visual Studio SDK I ran across a great example of a Navigation window by Gaston Milano.  It's a great sample to start with if you would like to dive into Visual Studio Package development.  One item of note that I found while using the navigation window on a very large project is that Visual Studio 2005 kept crashing everytime the window would be brought up.  I noticed that before VS crashed it had a difficult time drawing things. I immediately thought of a GDI leak.  I opened up Task Manager and checked the GDI objects and sure enough every time I openned the window the GDI object count would skyrocket upwards, never to return to a sane GDI count again.  VS crashed after reaching a count of about 10,000 GDI objects and I don't blame it for doing that either :) 

The offending routine, the getter for the HierarchyItem::Icon property in HierarchyItem.cs, calls a method NativeMethods.ImageList_GetIcon() which merely vectors off into the win32 version of ImageList_GetIcon().  Looking at the MSDN documentation for this routine you'll notice that the remarks at the end state

"It is the responsibility of the calling application to destroy the icon returned from this function using the DestroyIcon function"

Looking at the code you'll notice that DestroyIcon is never called on the temporary HICON returned from this call so every time this routine is called I noted 2 HICONs being leaked.  And on my large project, this really started adding up.

The fix?

Change the following code in HierarchyItem.cs:

      int handleIcon = NativeMethods.ImageList_GetIcon((int)imageList, (int)index, hbmMask);
      try {
          this.icon = (Icon)Icon.FromHandle((IntPtr)handleIcon).Clone();
      }
      catch (ArgumentException) {
      }
To:
int handleIcon = NativeMethods.ImageList_GetIcon((int)imageList, (int)index, hbmMask);
try {
     this.icon = (Icon)Icon.FromHandle((IntPtr)handleIcon).Clone();
     NativeMethods.DestroyIcon(handleIcon); // <== added to destroy the temp HICON
    } catch (ArgumentException) {
    }

And add a reference to DestroyIcon in the NativeMethods class like so:

        [DllImport("USER32")]
        public static extern int DestroyIcon(int HICON);
Hope that helps any of you running into similar problems.
posted on July 24, 2007  #    by Adam Markowitz  Comments [0]
 Monday, July 23, 2007

I am working on a web application, and some of the client side logic uses JavaScript to get an integer value from a text box. A user logged a bug claiming that when he entered a value that had a leading 0, for instance 0556, the result was in his words "a random number".

I looked up the parseInt global function here, and lo and behold! parseInt interprets a leading 0 as denoting that an octal number follows! It also has special processing for 0x (hexadecimal). To prevent this interpretation, you can specify the radix yourself in an overload of parseInt, for instance:

parseInt( tb.value, 10 );

For base (radix) 10. 

That's all I have to say about that!

posted on July 23, 2007  #    by John Waters  Comments [0]
 Wednesday, June 27, 2007

I stumbled upon this great series of articles that go into much more detail about functional programming in C#, the culmination of which is to write implementations of the "big three" higher-order functions: Map, Filter, and Reduce.

http://diditwith.net/PermaLink,guid,a1a76478-03d2-428f-9db6-9cf4e300ea0f.aspx

posted on June 27, 2007  #    by Adam Anderson  Comments [0]
 Thursday, May 31, 2007

A higher-order function is defined as a function that returns a function as a result. Higher-order functions are common in the world of functional programming, but have only recently started to become more mainstream. As of C# 2.0, they are starting to become part of the language. A perfect example of their use would be with the generic List<T>.FindAll() method, which takes a Predicate<T> as an argument. A Predicate<T> is a delegate, which is a strongly typed method reference. One way to search for all the items in a list is to use anonymous delegates. For example, given a list of Falafel employees:

List<Falafel> falafels = new List<Falafel>();
falafels.Add( new Falafel( "Lino", "Tadros" ) );
falafels.Add( new Falafel( "John", "Waters" ) );
falafels.Add( new Falafel( "Noel", "Rice" ) );
falafels.Add( new Falafel( "Adam", "Anderson" ) );
falafels.Add( new Falafel( "Xavier", "Pacheco" ) );
falafels.Add( new Falafel( "Adam", "Markowitz" ) );
falafels.Add( new Falafel( "Mike", "Dugan" ) );
falafels.Add( new Falafel( "Bary", "Nusz" ) );
falafels.Add( new Falafel( "Rick", "Miller" ) );
falafels.Add( new Falafel( "Mike", "Saad" ) );
falafels.Add( new Falafel( "Eric", "Titolo" ) );

You could search for all employees whose name starts with "A" like this:

falafels.FindAll( delegate( Falafel item ) { return item.FirstName.StartsWith( "A" ); } )

Output:
Adam Anderson
Adam Markowitz

However, if you wanted to perform another search for all employees whose name starts with "M", you'd have to write an entirely different anonymous delegate. That's where higher-order functions can help. Let's create a higher-order function that will return a delegate that searches for Falafels whose first name starts with a string we pass as a parameter:

public static class Predicates
{
  public static Predicate<Falafel> FirstNameStartsWith( string s )
  {
    return delegate( Falafel item ) { return item.FirstName.StartsWith( s ); };
  }
}

Now we can search for employees whose name starts with any letter we want:

falafels.FindAll( Predicates.FirstNameStartsWith( "A" ) );
falafels.FindAll( Predicates.FirstNameStartsWith( "M" ) );

Output:
Adam Anderson
Adam Markowitz

Mike Dugan
Mike Saad

But the fun doesn't stop there! If you define a set of primitive Predicates, you can define more complex Predicates as a combination of the simpler ones. Here is how to define higher-order functions that take a list of Predicates and returns a Predicate that returns the result of evaluating each of them and combining the result with the logical AND or OR operator:

public static Predicate<Falafel> And( params Predicate<Falafel>[] predicates )
{
  return delegate( Falafel item )
  {
    foreach ( Predicate<Falafel> predicate in predicates )
      if ( !predicate( item ) )
        return false;
    return true;
  };
}

public static Predicate<Falafel> Or( params Predicate<Falafel>[] predicates )
{
  return delegate( Falafel item )
  {
    foreach ( Predicate<Falafel> predicate in predicates )
      if ( predicate( item ) )
        return true;
    return false;
  };
}

Using these, we can create a single Predicate that searches for all Falafels whose first name starts with "A" or "R" and whose last name starts with "M":

Predicate<Falafel> predicate = Predicates.Or( Predicates.FirstNameStartsWith( "A" ), Predicates.FirstNameStartsWith( "R" ) );
predicate = Predicates.And( predicate, Predicates.LastNameStartsWith( "M" ) );
falafels.FindAll( predicate );

Output:
Adam Markowitz
Rick Miller

Higher-order functions are a powerful abstraction, and they're only going to become more common and easier to write with C# 3.0 lambda expressions, so give them a try and see how they can help make your code more concise and expressive.

posted on May 31, 2007  #    by Adam Anderson  Comments [0]
 Wednesday, May 02, 2007

If you need to monitor your transactional replication with a custom monitoring service, Microsoft has provided some useful tools to help. Recently I was having trouble reliably monitoring my replication, and then I discovered this page.

 

http://msdn2.microsoft.com/en-us/library/ms146951.aspx

 

If you’re using transactional replication there is no better way to monitor its health than using your own tracer token. This is just like inserting a tracer token using the replication monitor utility in SQL Server Management Studio.

 

First you need to create a connection to the server.

 

   server = new ServerConnection(sci); 

 

then create a TransPublication object.

 

    TransPublication transPublication = new TransPublication(publicationName, publicationDBName, server);

 

Call LoadProperties of the new object to make sure that all publications and subscriptions are loaded.

 

   transPublication.LoadProperties(); 

 

Then post the tracer token and call refresh to send it on its way. You need to save the ID of the token so that you can clean it up later.

 

   id = transPublication.PostTracerToken();
   transPublication.Refresh();
 

 

Now that the tracer token is on its way we need to create a publication monitor to look for its return. You have to go through a couple of layers to get to it.

 

   Microsoft.SqlServer.Replication.ReplicationMonitor monitor =

      new Microsoft.SqlServer.Replication.ReplicationMonitor(server);
   PublisherMonitor pub = monitor.PublisherMonitors[publisherMonitor];
   PublicationMonitor publicationMonitor = pub.PublicationMonitors[publicationDBName, publicationName];

Now we need to enumerate all of the tokens in the publication. You must call LoadProperties to refresh this list.

 

   publicationMonitor.LoadProperties();
   ArrayList tokens = publicationMonitor.EnumTracerTokens();
 

 

You can cast the items in the array list to a TracerToken type to find the token we sent with the ID we saved earlier.

 

   TracerToken token = null;
   foreach (TracerToken t in tokens)
   {
      if (t.TracerTokenId == tokenID)
      {
         token = t;
         break;
      }
   }
 

 

Now that we have our token we need to enumerate the tracer token history with this call.

 

   DataSet tth = publicationMonitor.EnumTracerTokenHistory(token.TracerTokenId); 

 

This returns a dataset that you need to parse through to get the data we are interested in. These include distributor latency, subscriber latency, and overall latency. If these values are blank, then the token has not returned yet. You need to then enumerate the tokens and check again. When the token has returned you then need to cleanup. A simple call will do this for us.

 

   publicationMonitor.CleanUpTracerTokenHistory(tokenID);

 

If any part of the replication fails for any reason, the token will fail to return and you know you have a problem.

posted on May 2, 2007  #    by Bary Nusz  Comments [0]
 Saturday, April 28, 2007

Behind this dropdownlist is some of the coolest code I have written for ages!

 

 

How can that be? Well, I learnt a lot about generics and anonymous delegates in the process… if you want to see some totally geeky code, read on,

Of course, there is a chance that for most of you this is all old hat, in which case you can go back to sleep…it was new to me for sure.

 

Still awake?

 

So, first of all, I had a lot of fun retrieving the data that populates this list.

The data that drives this DropDownList is a list of what I call FeatureGroups (the list has 2 elements, Defects and  Manage Projects), which has a Master Detail relationship to Features (a FeatureGroup contains 0 or more Features). It is in fact a List<AFFeatureGroup>, where each FeatureGroup contains a List<Feature>. Feature references back to its containing FeatureGroup through a FeatureGroupID member.

 

When I go to populate this list of FeatureGroups, I want to do it in one database call, so what I fetch is a flattened out Result Set that contains { FeatureGroup.ID, FeatureGroup.Name, Feature.ID, Feature.Name }.

I then need to iterate through that result set and for each FeatureGroup.ID I find, see if I already have created a FeatureGroup for that ID, if not, create it, then add the Feature to that new or existing feature group.

 

This is a standard pattern, you would have a list of your FeatureGroups in one hand, and be adding to it and searching in it as you go while looping through the flattened result set. Well here is how to spice it up!

 

It turns out that the generic List<T> type has a Find<T>( Predicate<T> match ). The predicate method is a method that takes a Predicate<T> and returns a bool. This method passed in as this parameter is called once on each item in the list, and the first time it returns true, that will be the item returned by Find. And, when invoking Find, you can pass in an anonymous delegate. In other words, you don’t have to pass in a new Predicate<T>( myCompareMethod ), you can just pass in the implementation of myCompareMethod…

This is how it looks:

 

private static List<AFFeatureGroup> GetFeatureGroupsFromFeatures( List<AFFeature> features )
{
  List<AFFeatureGroup> result = new List<AFFeatureGroup>();
  foreach (AFFeature f in features)
  {
    AFFeatureGroup fg = result.Find(
      delegate(AFFeatureGroup featureGroup) { return featureGroup.ID == f.FeatureGroupID; });
    if (fg == null)
    {
      fg = new AFFeatureGroup(f.FeatureGroupID, f.FeatureGroupName);
      result.Add(fg);
    }
    fg.Features.Add(f);
  }
  return result;
}

 

Let me break this down:

 

-          The method receives a List of AFFeatures, this is the flattened out result set containing one Feature in each row with its FeatureGroup as well.

-          The first line, result = new List<…> just creates an empty list of AFFeatureGroups that I will be returning once populated

-          Then,  I loop through all the features that I have fetched

-          In the loop, I call the Find method of List<AFFeatureGroup>, passing  my find implementation. Note two things:

o   a) I declare that the anonymous delegate accepts a AFFeatureGroup, which is mandated by the signature of Predicate<T>, as this code will be called once for each AFFeatureGroup in the list until a match is found

o   b) Inside the implementation curly braces, I can compare the featureGroup.ID of this passed in AFFeatureGroup to the value of f.FeatureGroupID. Think about that some! This is the powerful part! It’s kind of like in Delphi when you could pass in the address of a local nested method and that method would have access to any local variables or parameters in the enclosing method scope. The variable f is in the loop that encloses the call to Find, so in effect, what the compiler does is it captures the current value of f when creating the anonymous method, and makes it available inside the method body! Basically you have a dynamically created nested local method inside of the for loop. This is awesome compiler magic!

-          OK, so if a match is not found, I create a new AFFeatureGroup, and I then add it to the result list

-          If a match was found, or if I just created one, I can now add the feature itself to the feature group

 

And that is it: with this simple set of code I am doing a pretty complex construction of objects! This is what the language features of C# 3.0 will be taking one step further, where I will be able to use type inference to get rid of even more code above, for instance the declaration delegate(AFFeatureGroup featureGroup) can go away and I will just have a lambda expression there instead.

 

So, now for geek part 2…. I now have a method that will take a flattened list and build my two dimensional structure, but now I want to cache that list. Well, first I started with the classic approach, I look in the Cache object for a certain key, and if I don’t find it, I go fetch the data from the database (using the method in part 1), and store it in the cache. But this gets so repetitive, and I also wanted to centralize some of the aspects of the caching, like for how long the cached data is kept.

 

I started off along the lines that my colleague Adam Markowitz pioneered in the Velocity project, where you basically can create a CacheManager class that uses generics to do a type safe cache search. But then I figured if List<T> can accept a Predicate<T> in its Find method, why can’t I write a Cache.Get<T> that also accepts a T Fetcher<T> that will be invoked if there is no cache hit? Of course, Fetcher<T> might need some parameters, so I decided I would need two types of delegate, one that takes no parameters, and one that takes an instance of some arbitrary type D as a parameter (I could have been lazy and used an object instead of D, but what I love about Generics is the type safety it gives you without the performance drawbacks) :

 

public delegate T Fetcher<T, D> ( D data );
public delegate T ParameterlessFetcher<T>();
 

 

Now, my CacheManager can accept one of these 2 delegate types as a parameter in its GetFromCache method, and invoke it if the Cache doesn’t have the sought after data. For instance using the parameterless delegate:

 

public static T GetFromCache<T>(string key, ParameterlessFetcher<T> fetcher)
{
  T res = GetFromCache<T>(key);
  if (res == null)
  {
    res = fetcher();
    AddToCache(key, res);
  }
  return res;
}

 

The GetFromCache and AddToCache are the actual Cachce accessors:

 

public static void AddToCache(string key, object dataToCache)
{
  HttpContext.Current.Cache.Insert(key, dataToCache, null, DateTime.MaxValue, m_defaultTimeSpan);
}

public static T GetFromCache<T>(string key)
{
  return (T) HttpContext.Current.Cache[key];
 

 

Note that I centralize the timespan handling so that this is consistent:

 

private static TimeSpan m_defaultTimeSpan = new TimeSpan(0, 20, 0);

 

Here is how the parameter version looks:

 

public static T GetFromCache<T,D>(string key, Fetcher<T,D> fetcher, D data )
{
  T res = GetFromCache<T>(key);
  if (res == null)
  {
    res = fetcher(data);
    AddToCache(key, res);
  }
  return res;
}

 

And, putting it all together: