navigation
 Wednesday, March 03, 2010
A quick example of what will and won't work to cast a generic parameter to a concrete type
posted on March 3, 2010  #    by Adam Anderson  Comments [0]
 Wednesday, February 24, 2010
Does RIA deliver on the promise of simplified LOB development?
 |  |  | 
posted on February 24, 2010  #    by John Waters  Comments [2]
 Monday, February 15, 2010
Telerik’s ComboboxColumn for the Silverlight RadGrid is highly useful for presenting drop-down list options for the user in a grid-editing scenario. But it’s also very easy to template, and you can even template the ‘Display’ look of the cells to match that of your dropdown list items. Using templates, we have the ability to display the dropdown choices using data-driven visual elements, for a much richer user experience.
posted on February 15, 2010  #    by Rachel Hagerman  Comments [0]
 Sunday, January 31, 2010

Ok, it looks good, hey it is black :) fancy touches and demos well in Steve Jobs’ hands.  But do I want one of these?

image

The answer is NO, for so many reasons.  I have to say I am disappointed.  I expected Apple to continue being on a roll and bring something that will change the Tablet market forever after the failure of Microsoft and others before it in the pursuit of consumer happiness :)

  • No camera? What were you thinking?  I was expecting TWO of them in the front and the back.
  • No multitasking? Really? this is not a phone, so that is not ok.
  • Is this the Kindle killer, NO WAY, it is much better and easier on the eye to read on the Kindle.  Remember, FANCY and COLORS does not mean better.
  • AT&T, really??? AGAIN???  you never learned from the IPhone deal that AT&T was your weakest link.
  • “Excellent for surfing the web” Really? with no Flash or Silverlight support?  Which web are you surfing?
  • No USB?  Really??? COMMMMEEEE ONNNN
  • No HDMI or any other video output?  COMMEEEE ONNNN
  • No 16:9 aspect ratio for watching movies?

This device is the “most important device of Steve Jobs’ career” as he said on stage two days ago in San Francisco while announcing the device.  No Steve, it is not, you have done very well, don’t sell yourself cheap with a statement like that.

The impressive part about the IPAD really is that Monotouch within 24 hours released an update to their product that will allow you to target the IPAD while continuing to build applications in C#.  I guess the good thing is that the binary format for apps is the same as IPhone while including some new namespaces for the new UI dimensions and layouts.  Kudos to the Monotouch team!

Is it just me or you agree with my opinion? Let me know here by posting a comment

 |  |  |  |  | 
posted on January 31, 2010  #    by Lino Tadros  Comments [1]
 Friday, January 29, 2010

I came across an interesting technique earlier this week. Did you know that you can return an anonymous type from a method and still have strongly typed access to its members? I got this technique from Tomas Petricek’s blog. Here is a quick example of how it works; for details of why it works please see the original article.

        private static object ReturnAnon()
        {
            return new { FirstName = "Captain", MiddleName = "Jack", LastName = "Sparrow" };
        }

        private static T Cast<T>(object o, T type)
        {
            return (T)o;
        }

        static void Main(string[] args)
        {
            var anon = Cast(ReturnAnon(), new { FirstName = "", MiddleName = "", LastName = "" });
            Console.WriteLine(String.Format("FirstName: {0}", anon.FirstName));
            Console.WriteLine(String.Format("MiddleName: {0}", anon.MiddleName));
            Console.WriteLine(String.Format("LastName: {0}", anon.LastName));
            Console.ReadLine();
        }

Of course, just because you can return an anonymous type doesn’t mean that you should. As a general rule, I would say that if you are using the method’s return value in only one place, then it is OK to use this technique. However, the moment that the method is used from a second place, that anonymous type should be explicitly declared instead.

posted on January 29, 2010  #    by Adam Anderson  Comments [0]
 Monday, January 04, 2010
I've always been a fan of Commands way back when they were called Actions in the old Delphi days. With .NET, WPF, and Silverlight we have so many new tools available to us. One I’ve been having fun with is behaviors.
 |  |  | 
posted on January 4, 2010  #    by Bary Nusz  Comments [0]
 Thursday, December 17, 2009

If you, like me, did not install C++, it is not there… see this article. Installing C++ fixed the problem. The C++ team must be getting desperate!

posted on December 17, 2009  #    by John Waters  Comments [0]
 Tuesday, December 01, 2009
I have been using Telerik’s RadTabControl for Silverlight for a while, and have finally been able to upgrade to the new Q3 2009 release. Happily, I am noticing some new features from my wish-list which will make tab navigation oh so much easier.
posted on December 1, 2009  #    by Rachel Hagerman  Comments [0]
 Tuesday, October 13, 2009
Lino Tadros is stirring up a huge amount of interest at DevReach 09 in Sofia
 |  |  |  |  |  | 
posted on October 13, 2009  #    by John Waters  Comments [0]
 Monday, August 31, 2009

We are proud to announce that Falafel is a platinum sponsor of this year’s Silicon Valley Code Camp, along with Microsoft, LinkedIn, Oracle and Foothill College, and has several speakers registered for the event.

Lino Tadros will cover the following topics:

  • Dependency Properties in WPF & Silverlight
  • Silverlight 3 ins & outs
  • IPhone Development in C# with MonoTouch

John Waters will talk about:

  • Partially Connected Silverlight Applications
  • Parallel Programming with .NET

Steve Trefethen is speaking on:

  • Extending CruiseControl.NET
  • Tour of AutomatedQA's TestComplete 7

And Stephen Dempsey has a talk on:

  • Befriending Lambda Expressions

There is a long list of other renowned speakers, come see us and get up to speed on the latest trends and technology! Also, we are hiring, to stop by us after our talks if you are interested in a Senior ASP.NET or Silverlight Engineer position.

Cheers

The Falafel Team

posted on August 31, 2009  #    by Lino Tadros  Comments [1]
 Saturday, July 04, 2009

When:  Wednesday, 7/15/2009 at 6:30 PM
Where: Microsoft San Francisco Office, 835 Market Street, Suite 700, San Francisco

Lino Tadros, Chairman & CEO of Falafel Software is presenting this session at the Bay.NET User Group at the Microsoft offices in San Francisco on July 15th 2009 starting 6:30 PM.  Feel free to register for the Event here and look forward to seeing you there.  It should be a very exciting and fun session.

 |  |  |  |  | 
posted on July 4, 2009  #    by Lino Tadros  Comments [1]
 Thursday, July 02, 2009

Capitola, CA - July 1st 2009, Microsoft awarded Lino Tadros, Falafel Software’s Chairman & CEO, the prestigious MVP award in the C# language category for the 6th year in a row.  This award is mainly awarded to few individuals worldwide for their contributions in the C# community and helping Microsoft with the short term and long term strategies of the language.

Lino Tadros has been presenting numerous sessions on the language in the USA, Europe and Australia since the year 2000 in many of the industries’ top conferences.

MVP_FullColor_ForScreen

 |  |  |  | 
posted on July 2, 2009  #    by Lino Tadros  Comments [0]
 Tuesday, June 30, 2009
One feature I really like in Telerik’s WinForms RadGrid control is the ability to save and load layout information using the Serialization API. It’s nice to be able to to persist appearance and other settings in XML format, so that they can be restored later and provide a more consistent feel for the user. In this blog, learn how to save a non-typical setting: Summary Row formatting.
 |  | 
posted on June 30, 2009  #    by Rachel Hagerman  Comments [0]
 Tuesday, June 09, 2009
If you are using conditional directives in your C# code, you know that you can't set a breakpoint on any code within the directives using Visual Studio. Thankfully, you can add a breakpoint programmatically:

#if MYSYMBOL
#if DEBUG
System.Diagnostics.Debugger.Break();
#endif
DoSomethingForMySymbol();
#else
#if DEBUG
System.Diagnostics.Debugger.Break();
#endif
DoSomethingForEverythingElse();
#endif

System.Diagnostics.Debugger.Break() can only be called in Debug mode, so make sure you wrap it in a #if DEBUG check first. Good luck!


posted on June 9, 2009  #    by Brad Divine  Comments [0]
 Friday, June 05, 2009
Here's a handy little tip for those of you using DataGrids or something similar, for instance, the Telerik RadGrid control. If you want to allow the user to double-click on a row to do something (edit the row, for example), implement the CellDoubleClick event handler for the grid and put your code in there. If you do this, then double-clicks in the column header will also fire the event; this can happen if a user clicks the header too quickly while trying to sort. To prevent this, add code to check e.RowIndex. If the user double-clicked on a header, e.RowIndex will = -1.
posted on June 5, 2009  #    by Brad Divine  Comments [0]
 Monday, June 01, 2009
When programming for Windows, you'll sometimes want a container object (a form, a panel, etc.) to handle certain events, such as MouseOver, MouseMove, MouseUp, MouseDown, etc. But what happens if you have other controls in the container? You could write event handlers for each of those controls, but that seems like a lot of duplication of effort. One solution to this problem is to send the child control's events that you'd like to capture to the event handlers of the container
 | 
posted on June 1, 2009  #    by Brad Divine  Comments [0]
 Friday, May 29, 2009
If you're like me, you sometimes use AJAX controls in your web page. And, if you're like me, you find that when they fail to behave as expected, you as the user are not notified as to the reason. Instead, the page will just stare back at you blankly: no spinning globe, no twirling fox to indicate that it is processing your request. Of course, what's really happened is that your AJAX request caused an unhandled exception on the server and the request was canceled. If you're like me (and if you've read this far I am forced to conclude we must be twins) you'd like some visibility into that unhandled exception.

There is a quick and easy solution! Simply add the following to your ASPX code-behind and during your debugging session Visual Studio will report the exception being thrown, complete with the exception message and stack trace. If you'd like to report the exception to the user, you would wrap the inner call in a try/catch block and update your UI (or Logging) accordingly.

Good luck!

C#
protected override void RaisePostBackEvent(IPostBackEventHandler source, String eventArgument)
{
    base.RaisePostBackEvent(source, eventArgument);
}

VB.NET
Protected Overrides Sub RaisePostBackEvent(ByVal source As IPostBackEventHandler, ByVal eventArgument As String)
    MyBase.RaisePostBackEvent(source, eventArgument)
End Sub

posted on May 29, 2009  #    by Brad Divine  Comments [0]
 Wednesday, May 27, 2009
Once again I’m sharing some tips and tricks for the Telerik RadGridView control; this time for your combobox editors inside the grid. Learn to allow cell clearing using the combobox and have properly sized dropdowns regardless of cell width.
 |  | 
posted on May 27, 2009  #    by Rachel Hagerman  Comments [2]
 Saturday, May 02, 2009
How to delete TortoiseSVN Username/password cache for specific repositories in three easy steps!
posted on May 2, 2009  #    by Brad Divine  Comments [0]
 Friday, May 01, 2009

It seems like Microsoft has teams cranking out frameworks left right and center.. the Common Application Blocks, the MVC Framework, and today I came across Microsoft's new .NET RIA Service Framework.

What does it do? A lot! It provides a complete framework for an n-tier Silverlight application that fetches data from some back end store, binds it to the UI, manipulates it and writes it back.

It is a crafty combination of metadata, naming conventions, code generation and classes that helps you wire up the plumbing and handle tasks like change detection, validation, authorization in a very straight forward manner.

I recommend that you check out the technology if you are about to embark on a n-tier Silverlight application and don't want to write all the plumbing yourself!

posted on May 1, 2009  #    by John Waters  Comments [0]
 Wednesday, April 08, 2009
Once again I am spending a lot of time working with Telerk’s RadControls for WinForms, and most recently have been looking for all sorts of ways to squeeze every possible bit of speed out of a RadGridView control. Sometimes a really simple change has made a noticeable improvement, and I thought it would be useful to collect those simple-yet-effective tips all in one place.
 |  | 
posted on April 8, 2009  #    by Rachel Hagerman  Comments [1]
 Monday, March 30, 2009

In my previous posts about binding in code behind with WPF, I talked about my helper class that allowed me to quickly create a dependency property within any class and use a number of static functions to quickly bind dependency properties in code behind. So when I took a look at the binding capabilities in Silverlight 2.0 I was disappointed to find out that much of the binding had been stripped out.

posted on March 30, 2009  #    by Bary Nusz  Comments [1]
 Friday, March 27, 2009

This helper will do the trick:

    public static class FileHelper
    {
        public static void MoveWithOverwrite(string sourceFileName, string targetFileName)
        {
            if (File.Exists(targetFileName))
            {
                if ((File.GetAttributes(targetFileName) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                    File.SetAttributes(targetFileName, FileAttributes.Normal);
                File.Delete(targetFileName);
            }
            File.Move(sourceFileName, targetFileName);
        }
    }

 

 | 
posted on March 27, 2009  #    by John Waters  Comments [5]

Today I was trying to figure out the Linq syntax to find the max DateTime out of a list of objects that had a ModifiedOn property. Here is what I came up with:

DateTime maxLastModified = list.PickListItems.Items.Max(p => p.ModifiedOn);

Too easy, huh?

Actually, this is not so much Linq as just extension methods and lambda expressions, although one could argue that is what Linq is...I will leave that to the philosphers.

 |  | 
posted on March 27, 2009  #    by John Waters  Comments [0]
 Sunday, March 22, 2009
Yesterday, I discovered Mars, and that made my life a whole lot easier! Find out how setting MultipleActiveResultSets in your connection string can solve thorny issues with multiple active SqlDataReaders using the same Connection...
posted on March 22, 2009  #    by John Waters  Comments [1]
 Tuesday, March 03, 2009
Today was the second day at the MVP Summit in Redmond and it was a lot of fun.  This is my 5th MVP summit and it is so nice to see all the faces that I don't get to see except at the MVP summit from all over the world.  We spent several hours with Anders Hejlsberg discussing futuristic features to the C# language and the evolving of this powerful powerful language inside of the Visual Studio IDE for the next few years.  Met so many friends that I usually see in Europe and Australia while speaking at conferences like Miguel Castro, Richard Campbell, Steve Forte, Todd Anglin, Neil Ford, Remi Caron and many others... It was so nice for us not to be speaking this time but actually attendees :)
These events are usually for us like taking kids to Disneyland :)
This time is so special though because it is the first time I took my wife with me to Microsoft to see what I do and meet these friends.  She was shocked on how childish we all are when we get together :)
    mvp
posted on March 3, 2009  #    by Lino Tadros  Comments [0]
 Wednesday, February 11, 2009
I recently needed to use the cells of a Telerik RadGridView to display data in an unusual way, and bind the values of those cells to the records of another RadGridView control. Some experimentation revealed that the RadGridView cells can be quite versatile, and I thought the resulting sample project was interesting enough to share.
 |  | 
posted on February 11, 2009  #    by Rachel Hagerman  Comments [2]
 Saturday, January 10, 2009
After installing a new version of VS.NET there are three environment settings I always change from the default settings to make things a little better and save me time using VS.NET 2008.
posted on January 10, 2009  #    by Gary Campbell  Comments [1]
 Tuesday, January 06, 2009
A recent project has had me spending a lot of time working with Telerik controls for WinForms, and sometimes learning some lesser-known tricks in the process. Whether by research on Telerik's support site, contact with the fine people at Telerik themselves, or just plain old experimentation, it's been fun to learn these little tidbits that can help turn a control, like the RadTabStrip from just functionally acceptable into something much more.
posted on January 6, 2009  #    by Rachel Hagerman  Comments [1]
 Wednesday, November 26, 2008

On December 2nd 2008 at 6:30 PM, Lino Tadros, President & CEO of Falafel Software, will present two sessions on AJAX and Silverlight 2.0 from 6:30 to 8:30 PM at the Foothills College campus in Los Altos Hills.

Please visit http://www.baynetug.org to learn more about the UsersGroup and the two sessions.  Hope to see you there!

 |  |  | 
posted on November 26, 2008  #    by Lino Tadros  Comments [1]
 Tuesday, November 04, 2008
Use these simple settings to save time on Windows Forms with Accept and Cancel functionality.
posted on November 4, 2008  #    by Rachel Hagerman  Comments [0]
 Wednesday, October 01, 2008
I recently discovered that I can actually use most of my favorite C# 3.0 language features even in projects that target .NET Framework 2.0. Read more to see which...
 |  | 
posted on October 1, 2008  #    by John Waters  Comments [1]
 Monday, September 15, 2008
My latest challenge is to learn everything there is about Sitefinity. When I first came to Falafel, one of my first assignments was to update some of Falafel's DNN modules, one of which was QuoteMax. This was a simple module that would manage a list of quotes and would pick one for display upon each page load. Of course, you might have a hard time saying any DNN module development was simple. In any case, this simple control would be my first try at custom Sitefinity development.
 |  |  |  | 
posted on September 15, 2008  #    by Bary Nusz  Comments [2]
 Tuesday, August 12, 2008
In my previous blog about dependency properties, I detailed a helper class that you can add to any non-DependencyObject class to give you access to dependency properties in that class. To start off with, we need to add a couple of new static functions to our helper class to handle adding bindings with converters.
 |  | 
posted on August 12, 2008  #    by Bary Nusz  Comments [3]
 Tuesday, July 29, 2008
Windows Presentation Foundation provides a simple way to validate user input on your data-bound controls, and it's completely customizable, too. By writing a custom class deriving from ValidationRule, and adding an error template to our control, we can have consistent UI notification of invalid input according to our specific needs.
 |  | 
posted on July 29, 2008  #    by Rachel Hagerman  Comments [1]
 Wednesday, July 23, 2008
Lino Tadros, President and CEO of Falafel Software, has been invited to speak at the DevReach conference in Sofia, Bulgaria
 |  |  |  |  |  | 
posted on July 23, 2008  #    by John Waters  Comments [1]
 Sunday, July 20, 2008
When your WPF project gets large with a well structured class diagram, you may run into a case where you need to add a dependency property to a class that it is not convenient to inherit from a dependency object. In that case you need a little help from a helper class. I recently ran into this little problem and came up with this class.
 |  |  | 
posted on July 20, 2008  #    by Bary Nusz  Comments [0]
 Saturday, July 12, 2008
So, let's say you've got a UserControl in a project that you would like to reference using interfaces without a direct reference to the UserControl's project. Now say you want to bind to a DependencyProperty in the UserControl. An interface to the UserControl doesn't help with the DependencyProperty. When I tackled this issue, I was unable to find any example of it anywhere on the Internet.
 |  | 
posted on July 12, 2008  #    by Bary Nusz  Comments [0]
 Thursday, July 10, 2008
I was recently working on a WPF form that allowed users to edit data stored in an XML file. In the process, I learned a lot about simplifying my databinding code.
 |  | 
posted on July 10, 2008  #    by Rachel Hagerman  Comments [1]
 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 [1]
 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 [1]
 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 [1]
 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 [1]
 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 [2]
 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 [1]
 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 [1]
 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 [1]
 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 [1]
 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 [1]
 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 [1]
 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 [2]
 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 [1]
 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 [1]
 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 [2]
 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:

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace Falafel.ActiveFocus.Common
{
 public class AFCacheManager
 {
  private static TimeSpan m_defaultTimeSpan = new TimeSpan(0, 20, 0);

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

  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;
  }

  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;
  }

  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];
  }
 }
}
 

 

Now, what is exciting here is that I have a completely generic cache manager that can store and retrieve anything in a typesafe manner, using a delegate to do any fetching needed! Here is how I now use it to fetch that cached list of FeatureGroups:

 

public static List<AFFeatureGroup> CacheAllFeatureGroupsAndFeatures()
{
  return AFCacheManager.GetFromCache<List<AFFeatureGroup>>(
    CACHEKEY_FEATUREGROUPS,
    delegate() { return GetFeatureGroupsFromFeatures(new AFFeatureData().GetFeatures()); });
}

 

This is just amazingly concise to me! All I am supplying is :

 

-          the type of the cached object (a List<AFFeatureGroup>)

-          the Cache key to use (the constant CACHEKEY_FEATUREGROUPS)

-          the code to call when missing the data in the cache

 

Note that the code is now another anonymous delegate, it actually calls the method I explained in step 1 above that parses out the flat data. Here you also see how that method in turn gets the data by calling another method, GetFeatures. That in turn actually uses a whole similar approach of generics, that I wrote, which gives as a typesafe  way to convert result sets to lists of objects, but I won’t go there now!

 

And finally, to get down to that dropdownlist:

 

private void PopulateFeatureGroups()
{
  List<AFFeatureGroup> fglist = AFFeatureGroupData.CacheAllFeatureGroupsAndFeatures();
  ddlFeatureGroups.Items.Add(new ListItem("(All)", AFConsts.EMPTY_ITEM_VALUE.ToString()));
  foreach (AFFeatureGroup fg in fglist)
    ddlFeatureGroups.Items.Add(new ListItem(fg.Name, fg.ID.ToString()));
}

And it’s a wrap!

 

And what did I gain from all this convoluted programming asides from elegance and brevity?

I gained a reusable cache that can be tested and trusted and will save me a bunch of time caching other objects in a consistent and type safe manner. Now wasn’t that a geeky way to fill a drop down list?

posted on April 28, 2007  #    by John Waters  Comments [0]
 Tuesday, April 24, 2007
Yesterday I ran into an exception trying to read a non null DateTime value into a nullable type (DateTime?), using a helper method that was calling Convert.ChangeType. It turns out that this method, although very useful, doesn't support nullable types. However, I soon came across a useful blog that has a wrapper class that takes care of that particular problem, courtesy of Peter Johnsson.
posted on April 24, 2007  #    by John Waters  Comments [3]
 Thursday, April 12, 2007

Ever need to show something in a databound gridview that isn't in your datasource? Don't worry, relax, forget about that datasource. Just create that extra row dynamically.

Lets assume I have a GridView with 2 columns. The first column shows the items on an order,  the second column shows the price of that item and the footer shows the order total.  How would I inject a row that shows the tax?

Something like this in the RowDataBound EventHandler would do the trick:

decimal orderTotal = 0.0m;
decimal tax = 0.0m;
protected void gvOrderDetail_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //TODO: Calculate the orderTotal and the tax when RowType = DataRow
    if (e.Row.RowType == DataControlRowType.Footer)
    {
        //Create the Row
        GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
        //Add the two Columns
        row.Cells.AddRange(CreateCells());
        //get a reference to the table that holds this row
        Table tbl = (e.Row.Parent as Table);
        //Add the row at the end of the list, but before the footer.
        tbl.Rows.AddAt(gvOrderDetail.Rows.Count + 1, row);

        //Don't forget to account for any changes in the footer. Since we added a row to show the tax,
        //that tax must also be accounted for in our footer. Calculating the orderTotal and the tax
        //is an exercise for the reader.
        Label lbl;
        lbl = (Label)e.Row.FindControl("lblTotal");
        lbl.Text = String.Format("{0:C}", (orderTotal + tax));
    }
}

private TableCell[] CreateCells()
{

    TableCell[] cells = new TableCell[2];
    TableCell cell;
    Label lbl;

    //The order item column
    cell = new TableCell();
    lbl = new Label();
    lbl.Text = "Sales Tax";
    cell.Controls.Add(lbl);
    cells[0] = cell;

    //The price column
    cell = new TableCell();
    lbl = new Label();
    lbl.Font.Bold = true;
    lbl.Text = tax.ToString("C");
    cell.HorizontalAlign = HorizontalAlign.Right;
    cell.Controls.Add(lbl);
    cells[1] = cell;

    return cells;
}

posted on April 12, 2007  #    by Mike Dugan  Comments [1]
 Wednesday, April 11, 2007
A nice blog post highlighting some aspects of Haskell and the new functional elements of C# 3.0 http://themechanicalbride.blogspot.com/2007/04/haskell-for-c-3-programmers.html
posted on April 11, 2007  #    by Adam Anderson  Comments [1]
 Monday, April 09, 2007

I love the new features of ADO.Net, the Object Datasources and the table adapters that the XSD designer can generate. But they kind of have a will of their own! They open and close connections as they see fit, and dont really care about transactions. If you have a set of related tables that you make changes to, and then want to write all of the changes to the database in one transaction, you need to do things a certain way to make it work...

What about the TransactionScope class?

My first attempt was to use the new TransactionScope functionality in ADO.Net 2.0. You can do something like this:

using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required))
{
   // do stuff that manipulates data
   ts.Complete();
}

While this is a very elegant solution, it is very tricky to get to work. The mechanism uses a Local Transaction Coordinator, but as soon as you execute your second database update command, it escalates the transaction to a distributed transaction (even if you are just doing sequential operations in the same SqlConnection), and tries to do 2 way communication with the DTC (Distributed Transaction Coordinator) running on the SqlServer. This communication turns out to be a major headache to get working. Asides from opening all kinds of firewall holes and configuring lots of complicated DTC options on both the server machine and your local machine, the server needs to be able to do a reverse DNS lookup to call back to your client machine, which proves to be unfeasable if you are developing from home across a VPN or have a dynamic IP address that the server cant lookup. It really only works when your client and the SQL Server are part of the same AD domain.

Long story short, TransactionScope is too complicated right now to actually use in normal development. So I wanted to stick with the traditional transaction support.

Getting the TableAdapters to use the correct Connection object

First of all, you need to make sure all of your TableAdapters use the same Connection object. TableAdapters are not an actual class in ADO.Net, they are code generated classes, kind of like typed DataSets, but unlike typed DataSets they dont inherit from some common TableAdapter class, they just inherit from Component. However, they do expose a Connection property, so I use that to hook up all my TableAdapters to the same Connection object. Something like this:

void InitTableAdapters( SqlConnection conn )
{
  taReportSetGroupAccountNotAssigned.Connection = conn;
  taReportSetGroupAccount.Connection = conn;
  taReportSetGroup.Connection = conn;
  taReportSet.Connection = conn;
}

Setting up the transaction

Now, you can encapsuluate your database operations in a transaction as follows:

SqlConnection conn = new SqlConnection( connStr );

InitTableAdapters( conn );

conn.Open();
SqlTransaction tran = conn.BeginTransaction();
try
{
  // manipulate data

  tran.Commit();
}
catch()
{
  tran.Rollback();
}
finally
{
  conn.Close();
}

However, there is still a problem with this. The SqlCommands inside the TableAdapter need to use the transaction of the Connection object in the Table Adapter, but the generated code does not do that for you. And you don't want to start messing with the generated code, or your changes will be wiped out next time it is regenerated. What to do?

Making the SqlCommand enlist in your transaction

First I tried subclassing the generated TabeAdapter, as I saw there was a protected CommandCollection property. However, it turned out that this collection only contains the Select Command, and I wanted the Insert, Update and Delete commands to participate in the transaction. These are part of the SqlDataAdapter member of the TableAdapter, which is private. Duh!

Well, partial classes come to the rescue! The TableAdapter class is generated as a partial class, which allows you to extend it by adding in additional methods in your own partial class. One gotcha is that you need to use the same namespace for your partial class as for the generated partial class, and that namespace is actually not the same as that of the typed dataset. It has .XXXTableAdapters added on to the end of it, where XXX is the name of your typed dataset. For instance, if your dataset namespace is Falafel.Data, and its name is FalafelDataset, then your TableAdapter namespace will be Falafel.Data.FalafelDatasetTableAdapters.

Armed with this knowledge, we can extend the partial class of each TableAdapter as follows:

namespace Falafel.Data.FalafelDataSetTableAdapters
{
  public partial class ReportSetGroupAccountTableAdapter
  {
    public void JoinTransaction( SqlTransaction tran )
    {  
      TransactionHelper.JoinTransaction(_adapter, tran);
    }
  }
  public partial class ReportSetGroupTableAdapter
  {
    public void JoinTransaction( SqlTransaction tran )
    { 
      TransactionHelper.JoinTransaction(_adapter, tran);
    }
  }
}

Here I am using my own helper class:

public class TransactionHelper
{
  public static void JoinTransaction( SqlAdapter adapter, SqlTransaction tran)
  {
      CheckTransaction(tran, adapter.InsertCommand);
      CheckTransaction(tran, adapter.DeleteCommand);
      CheckTransaction(tran, adapter.UpdateCommand);
      CheckTransaction(tran, adapter.SelectCommand);
  }
  public static void CheckTransaction( SqlAdapter adapter, SqlCommand cmd)
  {
    if (cmd != null)
      cmd.Transaction = tran;
  }
}

Putting it all together

Now that I have injected a public JoinTransaction method into each TableAdapter, I can get them to enlist in the transaction by surreptitiously calling the trojan horse helper:

void EnlistTableAdaptersInTransaction( SqlTransaction tran )
{
  taReportSetGroupAccountNotAssigned.JoinTransaction( tran );
  taReportSetGroupAccount.JoinTransaction( tran );
  taReportSetGroup.JoinTransaction( tran );
  taReportSet.JoinTransaction( tran );   
}

Adding a call to this in my update logic, this is the final sequence of events:

SqlConnection conn = new SqlConnection( connStr );
InitTableAdapters( conn );
conn.Open();
SqlTransaction tran = conn.BeginTransaction();
try
{
  EnlistTableAdaptersInTransaction( tran );
  // manipulate data
  tran.Commit();
}
catch()
{
  tran.Rollback();
}
finally
{
  conn.Close();
}

It's not the most elegant or compact code, but it gets the job done! I hope this will save you some time and allow you to productively use TableAdapters in transactions until the TransactionScope class becomes more development environment friendly!

posted on April 9, 2007  #    by John Waters  Comments [1]
 Wednesday, March 14, 2007
Today I battled with some interesting problems writing changes to a hierarchical datatable to a SQL Server database. Hopefully by writing about this I can save you some time.
posted on March 14, 2007  #    by John Waters  Comments [1]
 Wednesday, February 21, 2007

Using is one of those dual use keywords in C#. Everybody uses using at the top of your code file so that you don’t have to type all of those long namespaces. The other use is for taking control over the closing and disposing of objects that support the IDisposable interface. Sometimes a little using goes a long way. One IDisposable class that is a good candidate for using is SqlConnection. Without using code to access a database, you would need to use a try-finally block to make sure you free up the resource.

 

SqlConnection conn = new SqlConnection(ConnectionString);

try

{

            ….

}

finally

{

      conn.Close();

}

 

Using using the code becomes much cleaner and logical.

 

using (SqlConnection conn = new SqlConnection(ConnectionString))

{

….

}

 

Next time you consider using resources, consider using using and clean your code up.

posted on February 21, 2007  #    by Bary Nusz  Comments [2]
 Tuesday, January 30, 2007

First of all, that title was a mouthful, so let me describe what I meant. A custom DataSource is something that you can assign (or databind) to the DataSource property of any bindable control. In programming terms, this means that the DataSource must implement IListSource, IDataSource, or IEnumerable. Well, I don't know about you, but I don't really want to spend a lot of time implementing all the methods of any of those interfaces. That's where Iterators come in; C# 2.0 added a new feature called Iterator blocks that makes it extremely easy to implement the IEnumerator interface, which is the only thing that you must implement in order to fully implement IEnumerable. In this article, I'll solve a real-world problem using this technique.

In application development, it's very common to need to fill a list control such as a DropDownList with a list of valid items, plus a blank item which represents a null value in a data store. However, while it is very easy to simply set some properties on a DropDownList to databind its items to the contents of a DataTable, there is no simple way to add that blank value without dropping into the code-behind. This is no big deal, but it just doesn't feel very clean to fill some DropDownLists declaratively, and have to resort to imperative code for other DropDownLists. One way to solve this problem would be to create a custom control descending from each list control with properties that control the extra blank item, but first of all, you'd have to write a custom control for each list control, and secondly, if we did that, then we couldn't talk about Iterators, could we? So instead, I'm going to create a custom DataSource that returns the contents of a DataTable, plus a blank item to represent null.

Let's proceed with writing the custom DataSource. Using Iterators to implement IEnumerable is as easy as declaring a class that implements it and using the yield keyword to build the return value. Let's declare our ListSource class and let Visual Studio create the method stubs to implement the interface:

using System;
using System.Collections.Generic;
using System.Text;

namespace Falafel.ListData
{
  class ListDataSource : IEnumerable<ListData>
  {
    #region IEnumerable<ListData> Members

    IEnumerator<ListData> IEnumerable<ListData>.GetEnumerator()
    {
      throw new Exception( "The method or operation is not implemented." );
    }

    #endregion

    #region IEnumerable Members

    IEnumerator IEnumerable.GetEnumerator()
    {
      throw new Exception( "The method or operation is not implemented." );
    }

    #endregion
  }
}

Assume the ListData class is a simple data class with two string properties: Text and Value. The first thing to notice is that the parameter list for GetEnumerator is empty, so the class itself will need to be initialized with properties that control the output of GetEnumerator. Let's add some private fields and a constructor to initialize them. New code is in italics:

using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace Falafel.ListData
{
  class ListDataSource : IEnumerable<ListData>
  {
    private DataTable _Table;
    private string _TextField;
    private string _ValueField;

    public ListDataSource( DataTable table, string textField, string valueField )
    {
      _Table = table;
      _TextField = textField;
      _ValueField = valueField;
    }


    #region IEnumerable<ListData> Members

    IEnumerator<ListData> IEnumerable<ListData>.GetEnumerator()
    {
      throw new Exception( "The method or operation is not implemented." );
    }

    #endregion

    #region IEnumerable Members

    IEnumerator IEnumerable.GetEnumerator()
    {
      throw new Exception( "The method or operation is not implemented." );
    }

    #endregion
  }
}

Of course, you could add code to expose the private fields as properties, but since that's not the focus of the article, let's just assume everyone knows how to do that so we can get to the interesting part. Now that we can create an instance of the class with a reference to a DataTable and some field names, we can implement GetEnumerator:

using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace Falafel.ListData
{
  class ListDataSource : IEnumerable<ListData>
  {
    private DataTable _Table;
    private string _TextField;
    private string _ValueField;

    public ListDataSource( DataTable table, string textField, string valueField )
    {
      _Table = table;
      _TextField = textField;
      _ValueField = valueField;
    }

    #region IEnumerable<ListData> Members

    IEnumerator<ListData> IEnumerable<ListData>.GetEnumerator()
    {
      yield return new ListData( String.Empty, String.Empty );
      foreach ( DataRow row in _Table.Rows )
        yield return new ListData( (string) row[ _TextField ], (string) row[ _ValueField ] );

    }

    #endregion

    #region IEnumerable Members

    IEnumerator IEnumerable.GetEnumerator()
    {
      return ( (IEnumerable<ListData>) this ).GetEnumerator();
    }

    #endregion
  }
}

Let's pause for a minute and contemplate the power of what those two lines have. The return type of GetEnumerator is IEnumerator<ListData>, but nowhere are we implementing any of the methods of the IEnumerator interface. Instead, we are simply iterating through a collection and returning each value with yield return. The C# 2.0 compiler does the work of implementing the IEnumerable interface for you.

Well, you could add any bells and whistles to the class that you wanted to, of course. Maybe you want to be able to specify the text and value of the null item, or maybe you want access to those private members through properties. Let's fast-forward past all that and demonstrate the final application of this class: the ability to bind to the DataSource declaratively. To do so, open any aspx page in Source View, locate a list control such as a DropDownList, and add the following attributes to the opening tag:

DataSource='<%# new ListDataSource( ds.MyTable, "MyTextField", "MyValueField" ) %>' DataTextField="Text" DataValueField="Value"

Now, when the control is databound, it will bind to our custom DataSource and fill its items using the ListData objects yielded by GetEnumerator.

In this article, I took two concepts: that all it takes to implement a DataSource is to implement IEnumerable, and that all it takes to implement IEnumerable is to write a little code using the yield keyword. I combined these concepts to demonstrate how to quickly and easily create a custom DataSource that could implement any custom logic desired and still integrate declaratively with all existing ASP.NET controls. If you are in need of .NET training or consulting, please contact us here at Falafel Software.

posted on January 30, 2007  #    by Adam Anderson  Comments [0]
 Wednesday, January 24, 2007

Dr. T takes you through a well-explained tour of C# 3.0's new features. http://blogs.msdn.com/madst/archive/2007/01/23/is-c-becoming-a-functional-language.aspx

posted on January 24, 2007  #    by Adam Anderson  Comments [0]
 Tuesday, November 07, 2006

Serializing objects to XML and back again in C# is trivial until you need greater control over the operation.  How do you serialize binary data, Color properties or some object type that hasn't been invented yet?  Implementing IXmlSerializable allows you to read and write object data in whatever format and by any means you choose. 

The example serializes a list of objects with a single Color property. 

<?xml version="1.0" ?>
<Items>
    <Item>Red</Item>
    <Item>White</Item>
    <Item>Blue</Item>
</Items>

The sample below serializes "MyObjects.xml" from disk to populate a MYObjectList object, makes changes to the list and re-writes "MyObjects.xml".  The two important IXmlSerializable methods to override are ReadXml() and WriteXml().  ReadXml() consumes an XmlReader instance.  Here we use a XmlTextReader to pull the xml text off the disk.  Likewise, WriteXml() uses a XmlTextWriter instance to recreate the xml file.
 
class Program
{
  static void Main(string[] args)
  {
    MyObjectList myObjectList = new MyObjectList();

    XmlTextReader reader = new XmlTextReader("MyObjects.xml");
    myObjectList.ReadXml(reader);

    myObjectList.Items.Clear();
    myObjectList.Items.Add(new MyObject(Color.BlanchedAlmond));
    myObjectList.Items.Add(new MyObject(Color.Blue));
    myObjectList.Items.Add(new MyObject(Color.LightSlateGray));

    XmlTextWriter writer = new XmlTextWriter("MyObjects.xml", null);
    writer.Formatting = Formatting.Indented;
    myObjectList.WriteXml(writer);
  }
}
 
<?xml version="1.0" ?>
<Items>
    <Item>BlanchedAlmond</Item>
    <Item>Blue</Item>
    <Item>LightSlateGray</Item>
</Items>
 
The sample is straightforward but you can use the same technique with data of any complexity.  "MyObjectList" contains a List<>, but that fact turns out to be immaterial.  The core idea is that implementing IXMLSerializable ReadXML() and WriteXML() can get the job done no matter what the data is or what format it needs to be saved as.  Here is the full source for the example, followed by an example with a slightly more complex xml structure.

using System;
using System.Collections.Generic;
using System.Text;

using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Drawing;

namespace SerializeGenerics1
{

  public class MyObject
  {
    public MyObject(Color MyColor)
    {
      _myColor = MyColor;
    }

    private Color _myColor;
    public Color MyColor
    {
      get { return _myColor; }
      set { _myColor = value; }
    }
  }

  public class MyObjectList
  {
    List<MyObject> _items = new List<MyObject>();

    public List<MyObject> Items
    {
      get { return _items; }
      set { _items = value; }
    }

#region IXmlSerializable Members

    public System.Xml.Schema.XmlSchema GetSchema()
    {
      return null;
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
      _items.Clear();
      while (!reader.EOF)
      {
        if (reader.ReadToFollowing("Item"))
        _items.Add(new MyObject(Color.FromName(reader.ReadString())));
      }
      reader.Close(); 
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
      writer.WriteStartDocument();

      writer.WriteStartElement("Items");

      foreach (MyObject myObject in _items)
      {
        if (myObject.MyColor.IsKnownColor)
        writer.WriteElementString("Item", myObject.MyColor.Name);
      }

      writer.WriteEndElement(); // close Items tag

      writer.WriteEndDocument();

      writer.Close();
    }

#endregion
}

class Program
{
  static void Main(string[] args)
  {
    MyObjectList myObjectList = new MyObjectList();

    XmlTextReader reader = new XmlTextReader("MyObjects.xml");
    myObjectList.ReadXml(reader);

    myObjectList.Items.Clear();
    myObjectList.Items.Add(new MyObject(Color.BlanchedAlmond));
    myObjectList.Items.Add(new MyObject(Color.Blue));
    myObjectList.Items.Add(new MyObject(Color.LightSlateGray));

    XmlTextWriter writer = new XmlTextWriter("MyObjects.xml", null);
    writer.Formatting = Formatting.Indented;
    myObjectList.WriteXml(writer);
  }
 }
}

This next example serializes settings for a "Wheel of Fortune" style game written in WPF.   The "Color" referenced here is from the Systems.Windows.Media namespace and doesn't have a "Name" property as in the previous example.  The xml file is nested with a Settings/Setting/<properties> structure:

<?xml version="1.0" ?>
<Settings>
  <Setting>
    <Percentage>10</Percentage> 
    <Color>#FFFF0000</Color> 
    <Title>Nice Try</Title> 
    <Description /> 
    <IsWinner>False</IsWinner>
  </Setting>
  <Setting>
    <Percentage>10</Percentage> 
    <Color>#FFB0E0E6</Color> 
    <Title>T Shirt</Title> 
    <Description>T-Shirt</Description> 
    <IsWinner>True</IsWinner> 
  </Setting>
</Settings>

The IXmlSerializable implementation:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.ObjectModel;
using System.Windows.Media;
using System.ComponentModel;
using System.Diagnostics;

namespace Falafel.Training.WPF
{
  public class Settings : IXmlSerializable, IEnumerable
  {
    List<Setting> _items = new List<Setting>();

  public void Add(Setting setting)
  {
    _items.Add(setting);
  }

#region IXmlSerializable Members

  public System.Xml.Schema.XmlSchema GetSchema()
  {
    return null;
  }

  public void ReadXml(System.Xml.XmlReader reader)
  {
    try
    {
      XmlTextReader textReader = reader as XmlTextReader;
      textReader.WhitespaceHandling = WhitespaceHandling.None;

      _items.Clear();

      while (textReader.ReadToFollowing("Setting"))
      {
        Setting setting = new Setting();
        textReader.Read();
        setting.Percentage = Convert.ToInt32(textReader.ReadString());
        textReader.Read();
        setting.Color = (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString(textReader.ReadString());
        textReader.Read();
        setting.Title = textReader.ReadString();
        textReader.Read();
        setting.Description = textReader.ReadString();
        textReader.Read();
        setting.IsWinner = Convert.ToBoolean(textReader.ReadString());
        _items.Add(setting);
      }
    }
  catch (Exception ex)
  {
    throw new ApplicationException("Unable to open Settings file. " + ex.Message);
  }
  finally
  {
    reader.Close();
  }
}

public void WriteXml(System.Xml.XmlWriter writer)
{
  XmlTextWriter textWriter = writer as XmlTextWriter;
  textWriter.Formatting = Formatting.Indented;
  textWriter.WriteStartDocument();
  textWriter.WriteStartElement("Settings");

  foreach (Setting setting in _items)
  {
    string color = TypeDescriptor.GetConverter(typeof(Color)).ConvertToString(setting.Color);

    textWriter.WriteStartElement("Setting");

    textWriter.WriteElementString("Percentage", setting.Percentage.ToString());
    textWriter.WriteElementString("Color", color);
    textWriter.WriteElementString("Title", setting.Title);
    textWriter.WriteElementString("Description", setting.Description);
    textWriter.WriteElementString("IsWinner", setting.IsWinner.ToString());

    textWriter.WriteEndElement(); // close Setting tag
  }

  textWriter.WriteEndElement(); // close Settings tag
  textWriter.WriteEndDocument();
  textWriter.Close();
}

#endregion

#region IEnumerable Members

  public IEnumerator GetEnumerator()
  {
    return _items.GetEnumerator();
  }

#endregion
 }
}

ReadXML() casts XMLReader to a XMLTextReader to consume the WhiteSpaceHandling property.  Likewise, WriteXML casts XMLWriter to XMLTextWriter to use the Formatting property.   The structure used here of Settings/Setting/<some properties> is entirely arbitrary.  You can read and write to and from any xml structure you care to put together.

 | 
posted on November 7, 2006  #    by Noel Rice  Comments [0]
 Tuesday, October 17, 2006

In my previous blog, I wrote about how to create generic utility classes that would cast or convert any object to a given type, returning a default if the value was DBNull. I quickly discovered that this code will work just fine as long as the passed type is not nullable. For example, this will work:

int i = ConvertDBNull.To<int>( value, 0 );

But this won't:

int? i = ConvertDBNull.To<int?>( value, null );

The line that fails within the To<>() method is this:

return (T) Convert.ChangeType( value, t );

The reason the call to ChangeType() fails is that there are no conversions defined for the Nullable<> struct, a fact that I find rather puzzling, since it would have been quite easy to do. All you have to do is get the underlying type and convert to it instead. We will still cast the result to the nullable version of the type, because casting a value type to its nullable counterpart is allowed. Here is how to extract that underlying type:

How To Detect Nullable Types Using Reflection

First of all, we will need to be able to detect when a nullable type is passed to the conversion method. The .NET Framework doesn't provide anything that explicitly tests for nullable types, but we can use reflection to determine whether a type is nullable or not. The first thing you need to know is that nullable types are implemented by the framework by using a generic struct called Nullable<>. For example, the following two declarations are identical:

int? i;
Nullable<int> i;

Therefore, if a given type is nullable, it is a generic type whose type is Nullable<>.

private static bool IsNullable( Type t )
{
  if ( !t.IsGenericType ) return false;
  Type g = t.GetGenericTypeDefinition();
  return ( g.Equals( typeof( Nullable<> ) ) );
}

Solving The Conversion Problem

Now that we can detect a nullable type when it's passed, we will need to extract the underlying type. The underlying type is the first and only generic argument passed to the Nullable<> struct. Therefore, the underlying type can be obtained like this:

private static Type UnderlyingTypeOf( Type t )
{
  return t.GetGenericArguments()[ 0 ];
}

We simply need to substitute the underlying type for the nullable type in our original code to get the desired results:

public static T To<T>( object value, T defaultValue )
{
  if ( value == DBNull.Value ) return defaultValue;
  Type t = typeof( T );
  if ( IsNullable( t ) )
    t = UnderlyingTypeOf( t );

  return (T) Convert.ChangeType( value, t );
}

But wait! If you use this method to attempt to convert a null value to a nullable type, the result will be an invalid conversion, because you will be trying to convert null to a value type. We'll have to return without converting if the passed value is null:

public static T To<T>( object value, T defaultValue )
{
  if ( value == DBNull.Value ) return defaultValue;
  Type t = typeof( T );
  if ( IsNullable( t ) )
  {
    if ( value == null ) return default( T );
    t = UnderlyingTypeOf( t );
  }

  return (T) Convert.ChangeType( value, t );
}

Finally, we have a method that will convert any type, including nullable types, to any other type, including nullable types. I hope that you've enjoyed today's submission. If you need training or consulting, contact us and get the Falafel team working for you!

 | 
posted on October 17, 2006  #    by Adam Anderson  Comments [2]
 Friday, October 13, 2006

Oh, DBNull, how you complicate my code! You throw exceptions when I try to cast or convert you, forcing me to litter my code with conditionals that check for you first. Well, your days of plaguing my code with repetitive conditional expressions and operators are at an end, because I just wrote a new utility class that can cast an object to any type, returning a user-defined default value of that same type if the object is DBNull. And thanks to the power of C# 2.0 generics, it only took 7 lines of code. And 4 of those are curly braces.

On a more serious note, this article is really about the same thing as the last one I wrote: how to reduce or eliminate repetitive code. Today's inspiration came from the annoying stock behavior of the DBNull class, which actually goes to the trouble of implementing the IConvertable interface just so it can throw exceptions if any code tries to convert it. The result is that you end up writing a lot of code like this:

// Assume dr is a DataReader
object o = dr[ "Column1" ];
int i = ( o != DBNull.Value ) ? (int) o : 0; // or whatever default value makes sense

Code like this, while innocuous and relatively harmless, just kind of gets to a man after a while. I started to write a class that would test for DBNull before casting to a given type, and it looked kind of like this:

public static class CastDBNull
{
  public static string ToString( object value, string defaultValue )
  {
    return ( value != DBNull.Value ) ? (string) value : defaultValue;
  }
  public static int ToInt32( object value, int defaultValue )
  {
    return ( value != DBNull.Value ) ? (int) value : defaultValue;
  }
  // And so on
}

It didn't take long to recognize a pattern: I was writing the same code over and over again, varying only the type. This calls for generics! The resulting code after applying generics to the problem becomes much more compact:

public static class CastDBNull
{
  public static T To<T>( object value, T defaultValue )
  {
    return ( value != DBNull.Value ) ? (T) value : defaultValue;
  }
}

The generic version takes a type specifier that determines both the return type and the type of the default value. In case generic syntax is still new and strange-looking to you, perhaps an example of how to use this class will help illustrate its power and flexibility:

// Pass string type to cast to string
string s = CastDBNull.To<string>( dr[ "Column1" ], String.Empty );
// Same class, same method, but passing int type allows casting to int
int i = CastDBNull.To<int>( dr[ "Column2" ], 0 );

Calls to this class take a little less typing than the conditional expressions and operators they encapsulate, but more importantly to my fingers, I find them easier to type. I find that writing lots of little utility classes like this makes programming both faster and more enjoyable. Thanks to a flexible method in the Convert class, the same kind of logic can be applied to convert values generically rather than simply casting them:

public static class ConvertDBNull
{
  public static T To<T>( object value, T defaultValue )
  {
    if ( value == DBNull.Value ) return defaultValue;
    return (T) Convert.ChangeType( value, typeof( T ) );
  }
}

I hope that you've enjoyed today's submission. If you need training or consulting, contact us and get the Falafel team working for you!

 | 
posted on October 13, 2006  #    by Adam Anderson  Comments [2]
 Monday, September 25, 2006

I hate writing the same code over and over again. Whenever I do, ennui begins to set in and even writing the same five lines of code again suddenly becomes unbearable. That’s usually a good time to refactor the duplicate code into a method or utility class. I recently found myself writing some code like this that defied the usual Extract Method refactoring: code that created and opened a connection, created a command, executed a reader, iterated through the reader’s results, and did something on every record. Read on to see how to refactor this code into its own reusable class by applying the Template Method Design Pattern...

First let’s take a look at the shape of the code I was writing to examine why Extract Method wasn’t an appropriate refactoring. The code looked something like this:

using ( SqlConnection connection = new SqlConnection() )
{
  using ( SqlCommand command = new SqlCommand() )
  {
    using ( SqlDataReader reader = command.ExecuteReader() )
    {
      while ( reader.Read() )
      {
        // Do something
      }
    }
  }
}

All I really wanted to do was get at that SqlDataReader and process its results. However, I couldn’t just define a method that returned the SqlDataReader from the innermost using statement, because once the using statements are exited, the objects are disposed, so I would be left with a reference to a SqlDataReader with no open SqlConnection. However, there is a design pattern that will solve this problem: the Template Method pattern.

Strictly defined, the Template Method is a pattern whose intent is “Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.” (Gamma, Erich, Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software.) Let’s take that basic idea of defining the skeleton of an algorithm and deferring some steps, and apply it to this problem.

First of all, when I execute code like this, it’s usually a one-time kind of thing, so I don’t really want to have to define a new subclass every time I want to use my new Template Method implementation. Instead, I’m going to define a class that offers events that can be handled to provide the same kind of functionality.

The heart of my new Template Method implementation is the method that defines the skeleton that I keep finding myself writing, and all other design decisions will flow from it. In order for the method to be flexible, I’ll need to be able to pass a ConnectionString, some CommandText, a CommandType, a flexible number of parameters, and maybe a CommandBehavior. That’s a mouthful, and yet I want to keep the actual method signature as small as possible. Since it’s more common to execute multiple commands against the same connection than it is to execute the same command against multiple connections, I decided to make ConnectionString a property of the class rather than a parameter of the method. I’ve observed that the CommandBehavior parameter of SqlCommand.ExecuteReader() is often either omitted or fairly constant; I almost always use CommandBehavior.SingleResult. At any rate, I think that this is another parameter that is better left as a property of the class rather than part of the method signature. That leaves me with CommandText, CommandType, and SqlParameters as my method parameters.

The whole point of this Template Method was to provide a simple way to inject specific logic into the skeleton of some standard data-access logic. I chose to do this with events so I wouldn’t have to define subclasses every time I wanted different logic. In my experience, the two most common places that I do stuff with a SqlDataReader is on each record (processing data), and after the DataReader is closed (reading output parameters). Since I want this new class to be flexible, I will also provide an event that is raised when the DataReader moves from one result to the next. I’ll define a catch-all event type that provides access to the SqlDataReader (for access to the data) and the SqlCommand (for access to the output parameters), and then define three events all of this type that get raised on Read, on NextResult, and on Close. Let’s take a look at the final result of all these decisions:

public int Execute( string commandText, CommandType commandType, params SqlParameter[] parameters )
{
  using ( SqlConnection connection = new SqlConnection( _ConnectionString ) )
  {
    using ( SqlCommand command = new SqlCommand( commandText, connection ) )
    {
      command.CommandType = commandType;
      AddParameters( command, parameters );
      connection.Open();
      using ( SqlDataReader reader = command.ExecuteReader( _Behavior ) )
      {
        ReaderCommandEventArgs args = new ReaderCommandEventArgs( command, reader );
        do
        {
          RaiseEvent( NextResult, args );
          while ( reader.Read() )
            RaiseEvent( Read, args );
        } while ( reader.NextResult() );
        reader.Close();
        RaiseEvent( Close, args );
        return reader.RecordsAffected;
      }
    }
  }
}

AddParameters() is a helper method that adds the parameters to the command, but doesn’t throw an exception if the array is null. RaiseEvent() is another helper method that raises assigned event handlers while skipping unassigned ones.

My new Template Method class is ready for use! I've decided to call it a ReaderCommand, since it invokes the ExecuteReader method of a SqlCommand. Let’s compare the old code with the equivalent code using my new class. Here’s the old code:

using ( SqlConnection connection = new SqlConnection( connectionString ) )
{
  using ( SqlCommand command = new SqlCommand( commandText, connection ) )
  {
    command.Parameters.AddWithValue( "@Param1", "abc" );
    command.Parameters.AddWithValue( "@Param2", 123 );
    connection.Open();
    using ( SqlDataReader reader = command.ExecuteReader( CommandBehavior.SingleResult ) )
    {
      while ( reader.Read() )
        Console.WriteLine( reader[ 0 ] );
    }
  }
}

It’s not that this code is so bad, but there is a lot of boilerplate code in there, with the important varying bits scattered throughout, and no less than four levels of indentation, with the most important logic at the center of it all. Here’s the new code:

ReaderCommand rc = new ReaderCommand( connectionString, CommandBehavior.SingleResult );
rc.Read += new ReaderCommandEventHandler( rc_Read );
rc.Execute( commandText, CommandType.Text, new SqlParameter( "@Param1", "abc" ), new SqlParameter( "@Param2", 123 ) );

static void rc_Read( object sender, ReaderCommandEventArgs e )
{
  Console.WriteLine( e.Reader[ 0 ] );
}

The old code was 14 lines long, with data access and program logic all jumbled together. The new code is 7 lines long (and 3 of those line were auto-generated by the IDE), with the program logic cleanly separated from the data access. The result is code that is easier to read and easier to write.

Today I’ve demonstrated how the Template Method design pattern can reduce redundant code and result in code that is easier to read and write. I hope that this example will inspire you to refactor your own redundant code into reusable classes. For more information on this topic, I highly recommend Head First Design Patterns by Freeman & Freeman as an excellent way to get started with design patterns, and Design Patterns by Erich Gamma, et al. as the definitive initial catalog.

 | 
posted on September 25, 2006  #    by Adam Anderson  Comments [0]
 Tuesday, September 05, 2006

I recently ran into a problem with a large DataSet when I set the EnforceConstraints to true. It gave me the error “Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.” without any clue as to where to look or what to do. Googling the problem, I came across a blog by Dave Lloyd with a good method to figure out exactly where the error is. The only problem was the example code was Dimmed. Naturally I un-Dimmed the code and put it in a proper C# format. I then encapsulated it into a nice little static function that returns a NameValueCollection loaded with all of the relevant error info. The info returned tells you what table, what row/column, and what the constraint is.

private static NameValueCollection BuildDataSetErrorInfo(DataSet dataSet)     
        {     
            NameValueCollection errorInfo = new NameValueCollection();     
            errorInfo.Add("DataSetName: ", dataSet.DataSetName);     
            foreach (DataTable table in dataSet.Tables)     
            {     
                DataRow[] rows = table.GetErrors();     
                if ((rows != null) && (rows.Length > 0))     
                {     
                    errorInfo.Add("Table: ", table.TableName);     
                    foreach (DataRow row in rows)     
                    {     
                        errorInfo.Add("Row Error: ", row.RowError);     
                        DataColumn[] cols = row.GetColumnsInError();     
                        if ((cols != null) && (cols.Length > 0))     
                        {     
                            foreach (DataColumn col in cols)     
                            {     
                                errorInfo.Add("Column: ", col.ColumnName);     
                                errorInfo.Add("Column Error: ", row.GetColumnError(col));     
                            }     
                        }     
                    }     
                }     
            }     
            return errorInfo;     
        }   
 
posted on September 5, 2006  #    by Bary Nusz  Comments [0]
 Friday, March 31, 2006

In .NET 1.1 we always had a problem using the built in Mail class in the System.Net namespace whenever the mail server was on a different server than the authenticating web server because it lacked the authentication feature to the SMTP that allows for this to be transfered correctly.  So we always ended up using a 3rd party component like ASPNETEMAIL which worked pretty well for us.
With the release of .NET 2.0 obviously Microsoft worked on that feature and added the authentication feature to the Mail class. 
This is simple code to show how easy now it is to make this work in .NET 2.0

1 System.Net.Mail.MailMessage Email = new System.Net.Mail.MailMessage ("spamMe@falafel.com", "SpamThis@falafel.com");
2 Email.Subject = "test subject";
3 Email.Body = "this is a test";
4 System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient();
5 //This object stores the authentication values
6 System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential ("username", "password");
7 mailClient.Host = "mail.falafel.com";
8 mailClient.UseDefaultCredentials = false;
9 mailClient.Credentials = basicAuthenticationInfo;
10 mailClient.Send(Email);
posted on March 31, 2006  #    by Lino Tadros  Comments [0]