navigation
 Monday, March 15, 2010
Falafel is in full force at MIX 2010 in Las Vegas this year exhibiting in the Commons area at the Mandalay Bay Hotel & Casino.  We are all very excited to be here this year to witness the latest and greatest on Silverlight 4, Mobile 7, Mobile 7 with Silverlight, ASP.NET, MVC 2, Sketchflow, IE9, Blend 4, and so many other surprises and fun week at the sin city!
Stop by the booth and ask for your cool Falafel shirt!  they will go fast :)  We would love to chat with you as well!
image  image
  Mix10_SeeYou_blk_240
image
 |  |  |  |  |  |  | 
posted on March 15, 2010  #    by Lino Tadros  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]
 Thursday, February 04, 2010

Lino Tadros, CEO of Falafel Software, recently participated in an SD Times interview, see the full text here. The interview focuses on the ever increasing pace of software and component evolution, and how component vendors like Telerik and software consultants like Falafel can harness that to bring value to their customers.

posted on February 4, 2010  #    by John Waters  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]
 Friday, December 18, 2009
Getting files from an outside source can cause Windows to Block project files. .NET 4 has changed the security settings so some examples downloaded from the internet, for example, might not work without unblocking these files.
posted on December 18, 2009  #    by Scott Frolich  Comments [0]
 Tuesday, November 17, 2009

So the show is on the road again. Falafel has a booth (come visit us), as do all the usual suspects, we met our friends at Telerik, Developer Express etc. The FU T-shirts and Sumo wrestlers are going like hot cake, thanks Matt for making us look good!

The Keynote this morning was a big aha moment from me. Its all about the cloud, which for Microsoft is Windows Azure. Very exciting, they have been busy and come along way since last year. The new SQL Azure service behave just like SQL Server, and you can even use SQL Server Management Studio to work with it using your familiar Transact SQL commands. Also, the development tools, management and monitoring tools, deployment etc are shaping up nicely.

The PDC drop of RIA Services for VS 2010 and .NET Fwk 4/ Entity Fwk 4 is looking very capable, will find out more about that on Thursday.

Now attending a talk on ADO.Net Data Services and .NET Entity Framework. They have done tons of work here since version 2.0. There is model first development (generate the DB from the model), support for POCO classes and change tracking, much better SQL generation and support for executing customized SQL and stored procedures.

Day 2: Wow! Microsoft just released Silverlight 4.0, and it has ALL the features that were missing! I don’t even know where to start! Here is a quick list: supports rich printing, access to external devices, access to webcam and microphone, can run in trusted mode and access file system and cross domain network access, does HTML in OOB mode, full OOB window management support (custom windows chrome), drag and drop files into the SL app, play flash inside the SL app, expanded WCF support (net tcp), right click, improved theming, improved data binding, runs full .net fwk assemblies, twice as fast…. what do you think? Seems like a go? It is beta now and RTM first half of 2010.

Oh – and today Microsoft scored big points by giving all the paying attendees a laptop! That drew some standing ovations at the keynote.

Day 3: Attended “Building Amazing Business Applications with Silverlight 4 and RIA Services” with Brad Abrams, Program Unit Manager. Very slick tooling and designer support! Nice implementation of server and client side filtering, and composing client side operations (filtering, sorting, paging) with server side execution.

I will update this blog as I find out more.

posted on November 17, 2009  #    by John Waters  Comments [0]
 Tuesday, October 13, 2009
Falafel will be exhibiting, come visit our booth to discuss Silverlight for your business, Silverlight Training, or to join our Silverlight team!
posted on October 13, 2009  #    by John Waters  Comments [0]
 Wednesday, September 16, 2009
Find out how to save time and space (not like Dr Who) by using Differencing Disks to configure variations of your core install in Virtual Machines under Hyper V.
posted on September 16, 2009  #    by John Waters  Comments [1]
 Monday, September 14, 2009

In case you wonder, as I did a few days ago, what Hyper V is, here is a simplified answer (the Wikipedia will tell you more):

Hyper V is kind of like Virtual PC for Servers on Steroids: it allows you to efficiently run and manage a whole bunch of different VMs on one machine. Hyper V is a role that is added to Windows 2008 Server (or Windows 2008 Server R2). Once you add the role, some strange things actually happen to your Windows Server installation: it actually becomes it’s own ‘parent partition’ on the server, so that it is also virtualized along with the VMs that you create.

There are many differences between Hyper V and Microsoft Virtual PC. First of all, the VMs have access to way more virtual hardware: multiple processors (Virtual PC only gives you one processor, even on a many core machine), and much more memory. It also requires Hardware Virtualization Assistance, which is present on most modern manycore processors, but if often turned off in the BIOS (I had to turn it on on my Alienware M17X, see this helpful tip). Hyper V also comes with all kinds of nifty management tools, and is trying to get into the datacenter-level virtualized server market.

To confuse things further, there are lots of different SKUs for Hyper V. You can purchase Microsoft Windows Server 2008 (and R2), and enable the Hyper V role, or you can get the free Microsoft Windows Hyper V Server 2008… it’s almost like SKU palindromes! The latter is a stripped down version of the full server SKU that is just specialized in the Hyper V role, and preconfigured for it.

Why would a developer care about all of this? Well, VMs are a great way to test new software, for instance I will be talking about Visual Studio 2010 and the .NET Parallel Computing initiative, and the current beta happens to not be uninstallable (sorry about the double negations). So if I install it on my machine I have to reinstall everything for the next beta refresh. Having better things to do with my time (like blogging about Hyper V on Sunday evening), I would rather put it in a VM. If you have been paying attention you will recall that MS Virtual PC only supports one processor, so that isn’t going to do me much good testing and demoing Parallel Processing…. hence the Hyper V approach. In a later blog I will detail my whole setup and post more on my findings preparing for the Parallel Processing talk at Silicon Valley Code Camp 09.

posted on September 14, 2009  #    by John Waters  Comments [0]
Today I had an interesting battle getting some Virtual Machines connected to the Internet from within their host operating system, Windows 2008 R2 with Hyper V. Read the article and save yourself some pain...
posted on September 14, 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]
The voting for the 2009 Windows IT PRO Community Choice Awards started and is now open till September 16th 2009.
Take the next 15 seconds to vote for your favorite tools and services.
Falafel Software is in category #30 for Training and Certification Services.  Also don’t forget to vote for our favorite tools from Telerik in categories #5,10,27,32 & 33
 |  |  |  |  |  | 
posted on August 31, 2009  #    by Lino Tadros  Comments [2]
 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]
 Wednesday, April 01, 2009

Our dear friend at Falafel Software Gary Campbell, this week, achieved MCP Certification status (Microsoft Certified Professional) on ASP.NET.  Congratulations Gary! 

Gary has been a solid member of the team working on the latest and greatest of technologies for our customers with great success.

posted on April 1, 2009  #    by Lino Tadros  Comments [2]
 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]
 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]
There are times when you may want to create your own custom build configuration for a project in Visual Studio, such as to define compiler symbols or to set build options for different projects within your solution. Fortunately, Visual studio makes it very simple.
posted on November 26, 2008  #    by Rachel Hagerman  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]
 Thursday, October 23, 2008

Hi Fellow .NET geeks worldwide! Are you going to be at PDC 2008 in Los Angeles ?  If Yes, then look for our CTO, John Waters in this flashy shirt seen below around the Telerik booth # 401

We are looking for a few GOOD .NET developers and trainers, John will be conducting interviews right at the PDC, who knows you might go home with an offer letter in hand to start working for a fun and successful company.

Best of luck to all and have a great conference!

dotnet

 |  |  | 
posted on October 23, 2008  #    by Lino Tadros  Comments [1]
 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]
 Tuesday, September 23, 2008
Enabling spellchecking on TextBox and RichTextBox controls is so simple in WPF, and it works just like in Microsoft office!
 | 
posted on September 23, 2008  #    by Rachel Hagerman  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]
 Wednesday, August 27, 2008
I just learned some very interesting things about WPF, Splash screens and Visual Studio 2008 SP1...
posted on August 27, 2008  #    by John Waters  Comments [1]
 Tuesday, August 26, 2008
With Expression Blend it's quite easy to style your own custom ScrollBar to get the look you want.
 | 
posted on August 26, 2008  #    by Bary Nusz  Comments [0]
 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]
 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]
 Thursday, July 17, 2008
For those of use whose first language is something other than XAML, the default control template styles generated in Expression Blend are pretty intimidating. There has got to be a simpler place to start. Well, there is! It's a handy little download you can get straight from your Visual Studio help called ControlTemplateExamples.
posted on July 17, 2008  #    by Rachel Hagerman  Comments [2]
 Wednesday, July 16, 2008
By the time I found the handy JavaScriptSerializer class, it had been introduced, deprecated and brought back from the hellish purgatory where Microsoft keeps objects that have outlived their usefulness.
 |  | 
posted on July 16, 2008  #    by Noel Rice  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]
 Friday, July 11, 2008
Most of my development is web apps, so when I was working on a windows app for a customer today, I noticed that there was an extra file or two being generated with the name of the app followed by ".vshost.exe".
posted on July 11, 2008  #    by Rick Miller  Comments [2]
 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]
 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]
 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]
 Saturday, April 19, 2008
I am attending the ALT.NET open spaces conferences this weekend. The opening was last night and was my introduction to the whole open spaces concept (see the video of the opening at Jeffery Palermo's web site). So many of the bloggers that I follow are attending. It was great to meet them.
posted on April 19, 2008  #    by Falafel Author  Comments [1]
 Tuesday, April 15, 2008
After a Vista upgrade none of my .NET 3.5 web applications would run! Visual Studio gives a "Child nodes not allowed" error for the web.config file, but there is a simple solution - once you find it.
posted on April 15, 2008  #    by Rachel Hagerman  Comments [3]
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]
 Thursday, February 28, 2008
The dotNet object in TestComplete (requires the .NET Classes Support plug-in) allows you to access .Net objects in your TestComplete script code. For example
posted on February 28, 2008  #    by Falafel Author  Comments [1]
 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]
 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]
 Thursday, June 21, 2007

You can write your own cmdlet ("command-let") to extend PowerShell in the .NET language of your choice.  You need to write both the cmdlet and a PowerShell snap-in to help install and register the command.  Here's an example snap-in for a "get-food" command  that lists tasty Mediterranean foods (like Falafels):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using System.Collections.ObjectModel; // supports Collection
using System.Management.Automation; // supports PSSnapIn
using System.Management.Automation.Runspaces; // supports *ConfigurationEntry
using System.ComponentModel; // supports RunInstaller
using Falafel;

// Project also references System.Configuration.Install

public class FalafelSnapIn : CustomPSSnapIn
{
public FalafelSnapIn()
: base()
{
}

public override string Name
{
get
{
return "FalafelSnapIn";
}
}

public override string Vendor
{
get
{
return "Falafel Software ";
}
}

public override string Description
{
get
{
return "Runs custom Falafel commands.";
}
}

/// <summary>
/// Specify the cmdlets that belong to this custom PowerShell snap-in.
/// </summary>
private Collection<CmdletConfigurationEntry> _cmdlets;
public override Collection<CmdletConfigurationEntry> Cmdlets
{
get
{
if (_cmdlets == null)
{
_cmdlets = new Collection<CmdletConfigurationEntry>();
_cmdlets.Add(
new CmdletConfigurationEntry("get-food", typeof(FalafelCmdlet), null));
}

return _cmdlets;
}
}
}

CustomPSSnapIn knows how to be installed via installutil.exe, contains information about name, vendor, description etc., and has collections of types that can be registered with PowerShell such as cmdlets, Types, Formats and Providers.  FalafelSnapIn descends from CustomPSSnapIn, overrides the Cmdlets collection and adds the "get-food" cmdlet to the collection. Notice that much of the PowerShell specific functionality is supported in the System.Management.Automation namespace.

 Next we'll look at FalafelCmdlet, the implementing class for the "get-food" cmdlet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;
using System.Management.Automation; // supports PSSnapIn, CmdLet, Parameter

namespace Falafel
{
[Cmdlet(VerbsCommon.Get, "Food")]
public class FalafelCmdlet : Cmdlet
{
private string _contains;

[Parameter(Mandatory = false, Position = 0, HelpMessage =
"List item descriptions containing this string")]
public string Contains
{
get { return _contains; }
set { _contains = value; }
}

protected override void ProcessRecord()
{
MediterraneanFoods foods = new MediterraneanFoods();
foreach (MediterraneanFood food in foods.FindFoods(_contains))
{
WriteObject(food);
}
}
}
}

First the Cmdlet attribute marks this class as a cmdlet and helps formalize the naming convention for cmdlets as being verb-noun combinations.  VerbsCommon lists the verbs that may be used:

FalafelCmdlet descends from Cmdlet but you can also use PSCmdlet.  Cmdlet is lighter-weight but PSCmdlet has more access to the PowerShell runtime. For this example the functionality would be the same so I will go with the lighter-weight Cmdlet.  The Contains property in this example holds a string used in searching food descriptions.  The Parameter attribute marks the Contains property as a parameter for the cmdlet, provides a help string and identifies Contains as not being mandatory.

Finally the ProcessRecord() method of Cmdlet is overridden to perform the actually work of the command.  In ProcessRecord() a class called MediterraneanFoods returns a generic list of MediterraneanFood objects based on description.  We won't get into the workings of MediterraneanFoods here because its purpose is to simply provide sample functionality for the command.  Note: Watch this space for a tasty blog by Lino on Anonymous Delegates that gets into how the generic list is searched.

The really cool part of ProcessRecord() is the WriteObject() method of Cmdlet.  Instead of Console.Writeline() text-only output, WriteObject() actually ouputs MediteraneanFood objects into the PowerShell pipeline.  This means that your objects are automatically usable by other commands.  You'll see this in a minute when we register and run the command. 

Here are the PowerShell commands I use to install and register the cmdlet:

cd C:\Clients\Falafel\Projects\FalafelCmdletLibrary\bin\Debug
set-alias iu $Env:windir\Microsoft.NET\Framework\v2.0.50727\installutil.exe
iu FalafelCmdletLibrary.dll
Add-PSSnapin FalafelSnapIn

The first line changes the directory to where the assembly for the FalafelCmdlet is stored.  Then, as a convenience you can use set-alias to make access to InstallUtil.exe easier.  The "IU" alias for InstallUtil installs the assembly.  This step produces a certain amount of logging I won't include here.  Finally the Add-PSSnapin makes the snap-in available to the current PowerShell console session.  You can call Get-PSSnapin to see the description and verify it's there:

Now we can run the "get-food" command, passing the "contains" parameter.  Notice the output by default is in table format.

Remember the call to WriteObject() that makes all our output actual objects instead of text?  Here's an example of piping the output of the one command that will easily work with an existing command without any adapting or parsing necessary to make it all work.  The "|" character is used to pipe the output from get-food to a format-list:

...and we have the output in list, not table, format.  Or we could pipe the output to the get-member command that performs reflection on objects passed to it.  You can see the MediterraneanFood object has Description and Name properties:

This all opens up possibilities for you to wrap existing .NET functionality in command-line form and to use the output in other existing commands.

posted on June 21, 2007  #    by Noel Rice  Comments [1]
 Tuesday, June 12, 2007

At Tech Ed in Orlando last week John Waters picked up "Windows PowerShell Unleashed by Tyson Kopczynski" and as John has a eye for cool technology I did likewise and got hooked on PowerShell.  I'm not usually a live-on-the-command-line-love-batch-files kind of guy but PowerShell covers enough ground in a powerful and consistent way that I'm considering adding this to my technology toolbox.  Although PowerShell is intended for system administrator use, there may be a place for PowerShell in development to do limited testing against .NET objects, task automatation and general exploration.  In any case it's a great toy and a hoot to play with.

PowerShell has several important differences from cmd.exe. 

  • PowerShell lets you use NET FCL objects, COM objects and even your own .NET classes.
  • PowerShell scripts can be code signed (see Windows PowerShell Unleashed by Tyson Kopczynski for detailed steps).  Previous scripting environments like Windows Scripting Host (WSH) opened large security holes.  This feature allows scripts from trusted sources to be run.
  • PowerShell is object based, not text based.  This eliminates parsing and reformatting to use the output from a command.
  • PowerShell provides a consistent interface. 
    • You can navigate through files, the certificate store, environmental variables and the registry, all using commands you already know. 
    • Commands confirm to the pattern verb-name, i.e. "get-service" to cut down on memorization.  There are aliases for historic DOS and UNIX commands so you can list a directory with the PowerShell native "get-childitem", UNIX style "ls" or DOS "dir". 
    • PowerShell lets you locate and interrogate available commands and objects.
  • PowerShell is extensible.  You can create your own commands in a .NET assembly and register them for use in PowerShell.  There are several other points of extensibility including providers for navigation, types and formatting.

Here's a sample session of PowerShell to give you a very brief notion of how it works.  Be aware that this is only scratching the surface of the possibilities for PowerShell.  Let's say we want to work with Windows services, so we need to know what commands are available:

 
PS C:\Clients\Falafel\Projects\FalafelCmdletLibrary\bin\Debug> get-command *service
CommandType     Name                                                Definition
-----------     ----                                                ----------
Cmdlet          Get-Service                                         Get-Service [[-Name] <String[]>] [-Include <Stri...
Cmdlet          New-Service                                         New-Service [-Name] <String> [-BinaryPathName] <...
Cmdlet          Restart-Service                                     Restart-Service [-Name] <String[]> [-Force] [-Pa...
Cmdlet          Resume-Service                                      Resume-Service [-Name] <String[]> [-PassThru] [-...
Cmdlet          Set-Service                                         Set-Service [-Name] <String> [-DisplayName <Stri...
Cmdlet          Start-Service                                       Start-Service [-Name] <String[]> [-PassThru] [-I...
Cmdlet          Stop-Service                                        Stop-Service [-Name] <String[]> [-Force] [-PassT...
Cmdlet          Suspend-Service                                     Suspend-Service [-Name] <String[]> [-PassThru] [...

From here we can see what services are available for SQL Server:

PS C:\Clients\Falafel\Projects\FalafelCmdletLibrary\bin\Debug> get-service MSSQL*
Status   Name               DisplayName
------   ----               -----------
Running  MSSQL$NRLAPTOP2    MSSQL$NRLAPTOP2
Running  MSSQL$SQLEXPRESS   SQL Server (SQLEXPRESS)
Running  MSSQL$TELERIK      MSSQL$TELERIK
Running  MSSQLSERVER        SQL Server (MSSQLSERVER)
Stopped  MSSQLServerADHe... SQL Server Active Directory Helper
Running  MSSQLServerOLAP... SQL Server Analysis Services (MSSQL...

Now we want to stop the MSSQLSERVER service and any dependant services:

PS C:\Clients\Falafel\Projects\FalafelCmdletLibrary\bin\Debug> stop-service "MSSQLSERVER" -force

If we re-run get-service we can see that the service is stopped:

PS C:\Clients\Falafel\Projects\FalafelCmdletLibrary\bin\Debug> get-service mssql*
Status   Name               DisplayName
------   ----               -----------
Running  MSSQL$NRLAPTOP2    MSSQL$NRLAPTOP2
Running  MSSQL$SQLEXPRESS   SQL Server (SQLEXPRESS)
Running  MSSQL$TELERIK      MSSQL$TELERIK
Stopped  MSSQLSERVER        SQL Server (MSSQLSERVER)
Stopped  MSSQLServerADHe... SQL Server Active Directory Helper
Running  MSSQLServerOLAP... SQL Server Analysis Services (MSSQL...

You can also interrogate the service objects using the get-member command. For example you could take the service objects returned by get-service and direct them to the get-member command using the "|" pipe symbol. The following is only a partial listing.

PS C:\Clients\Falafel\Projects\FalafelCmdletLibrary\bin\Debug> get-service | get-member
   TypeName: System.ServiceProcess.ServiceController
Name                      MemberType    Definition
----                      ----------    ----------
Name                      AliasProperty Name = ServiceName
Close                     Method        System.Void Close()
Continue                  Method        System.Void Continue()
CreateObjRef              Method        System.Runtime.Remoting.ObjRef CreateObjRef(Type requestedType)
Dispose                   Method        System.Void Dispose()
Equals                    Method        System.Boolean Equals(Object obj)
ExecuteCommand            Method        System.Void ExecuteCommand(Int32 command)
get_DependentServices     Method        System.ServiceProcess.ServiceController[] get_DependentServices()
get_DisplayName           Method        System.String get_DisplayName()
get_MachineName           Method        System.String get_MachineName()
get_ServiceHandle         Method        System.Runtime.InteropServices.SafeHandle get_ServiceHandle()

What about navigation?  If I want to change locations in the file system of course there's "CD" or the PS native "set-location". What's unique here is that you can navigate the registry, environmental variables, certificate stores or any other system that PS has a provider for (yes, you can write your own providers).  For example the following is perfectly legal:

PS C:\Clients\Falafel\Projects\FalafelCmdletLibrary\bin\Debug> cd env:
PS Env:\> dir
Name                           Value
----                           -----
Path                           C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\ATI Technolo...
TEMP                           C:\DOCUME~1\NOELRI~1\LOCALS~1\Temp
SESSIONNAME                    RDP-Tcp#1
PATHEXT                        .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.PSC1
USERDOMAIN                     NRLAPTOP
PROCESSOR_ARCHITECTURE         x86

You could image using CD to navigate hiearchical database information in this way (to what practical end I do not know, but it is amusing). Find out what PowerShell drives are available on your machine by using get-psdrive:

PS C:\Clients\Falafel\Projects\FalafelCmdletLibrary\bin\Debug> get-psdrive
Name       Provider      Root                                                                           CurrentLocation
----       --------      ----                                                                           ---------------
Alias      Alias
C          FileSystem    C:\                                    Clients\Falafel\Projects\FalafelCmdletLibrary\bin\Debug
cert       Certificate   \
D          FileSystem    D:\
Env        Environment
Function   Function
HKCU       Registry      HKEY_CURRENT_USER
HKLM       Registry      HKEY_LOCAL_MACHINE
Variable   Variable

Use get-psprovider to find the providers on your system.  See the MSDN for examples of writing your own provider. 

PS C:\Clients\Falafel\Projects\FalafelCmdletLibrary\bin\Debug> Get-PSProvider
Name                 Capabilities                                      Drives
----                 ------------                                      ------
Alias                ShouldProcess                                     {Alias}
Environment          ShouldProcess                                     {Env}
FileSystem           Filter, ShouldProcess                             {C, D}
Function             ShouldProcess                                     {Function}
Registry             ShouldProcess                                     {HKLM, HKCU}
Variable             ShouldProcess                                     {Variable}
Certificate          ShouldProcess                                     {cert}

You can download PowerShell at http://www.microsoft.com/technet/scriptcenter/topics/msh/download.mspx.  It comes with the install and docs for "Getting Started", "Quick Reference" and "Users Guide".

posted on June 12, 2007  #    by Noel Rice  Comments [1]
 Tuesday, May 15, 2007

There's a fascinating little article "Create Advanced Web Applications With Object-Oriented Techniques" by Ray Djajadinata that delves into how JavaScript implements objects, inheritance, anonymous methods, and even a bit about simulating private properties and namespaces.  This may be relevant if you want greater depth in AJAX, particularly the Microsoft flavor ASP.NET AJAX.  There's a sidebar (by Bertrand Le Roy) about the ASP.NET AJAX OOPS implementation and use of JavaScript to add reflection and other .NET familar constructs including properties, events, enumerations and interfaces.

posted on May 15, 2007  #    by Noel Rice  Comments [0]
 Wednesday, May 02, 2007

We recently completed a self-paced tutorial for Telerik RadControls.

You can download the self paced tutorial from the Telerik site at:

http://www.telerik.com/support/self-paced-tutorial.aspx

The tutorial addresses the entire suite of RadControls, AJAX, client-side scripting, and custom data-binding techniques.

posted on May 2, 2007  #    by Noel Rice  Comments [0]
 Tuesday, May 01, 2007

You can support docking in your web applications using Telerik's new control suite "Prometheus".  Prometheus is completely redesigned to use Microsoft's ASP.NET Ajax.  The Prometheus docking controls make it easy to define objects that may be dragged and areas where objects may be dragged to.  With docking support you can create web portal sites, "PageFlake" style web pages (where the user can dynamically add controls and drag them around on the page), or even "post-it notes" can be added to the page.  The current state-of-play is that the controls are in beta and have a few quirks, but the performance is very responsive and the look and feel is also quite good.

To use Prometheus "RadDock" controls first download and install the Microsoft ASP.NET Ajax extensions at http://ajax.asp.net/, then get the free Prometheus beta download at: http://www.telerik.com/products/aspnet-prometheus/download.aspx.  Once installed, create a new project type "ASP.NET AJAX-Enabled Web Application".  BTW, if you try to use the standard ASP.NET web application you will get really interesting results.

Your toolbox will have the new AJAX extension controls, including "ScriptManager".  ScriptManager is the workhorse of Microsoft's ASP.NET Ajax that registers client side scripts that enable AJAX functionality. The ScriptManager is automatically placed on the default web page so you don't need to do anything further there.

Also in the toolbox are the new Prometheus controls.  The three you need for drag and drop support are:

  • RadDock is the container for text or other controls that need to be dragged on the web page.
  • RadDockZone defines an area on the screen where a RadDock can dropped onto.
  • RadDockLayout can contain a number of RadDockZone controls so you can set the skin for everything at once.  RadDockLayout also has a property StoreLayoutInViewState that can be used to persist the RadDock locations across multiple postbacks.

To test these controls drop a RadDockLayout, two RadDockZones within the RadDockLayout and RadDock controls in each of the RadDockZones. 

How about adding content to the RadDock? 

  • Use the Radock Text property for simple text only that doesn't involve any other controls.
  • Create your own ITemplate implementation class and set the RadDock ContentTemplate property to that class in the code behind.
  • Add to the ContentTemplate property markup.  At this stage of development I don't see a smart tag or other UI assistance so instead add a ContentTemplate tag and add controls within the tag.

For example we could add another new Prometheus control "RadColorPicker":

<ContentTemplate>
  <telerik:RadColorPicker ID="RadColorPicker1" runat="server" Preset="Standard">
  </telerik:RadColorPicker>
</ContentTemplate>

To finish up we set the Skin property of RadDockLayout to "Longhorn".  If you've used the current version of RadDock you're used to adding various skin files to the project.  Not with the Prometheus version where the skins are built-in and you can choose the Skin property value from a drop down list.  Finally you can set the title bar text for each RadDock using the Title property.

When you run the Prometheus version of the docking controls you should experience snappy responsiveness and a very respectiable UI.  Try downloading Prometheus and retrofit some part of your current web application to support docking.  Enjoy!

Note: if you want to learn Telerik RadControls from the ground up, check out the Falafel-authored, self-paced tutorial at http://www.telerik.com/support/self-paced-tutorial.aspx and download the sample projects from our community download site at http://www.falafel.com/community/files/Default.aspx.

posted on May 1, 2007  #    by Noel Rice  Comments [1]
 Tuesday, April 17, 2007

You might overlook the JavaScript debugging utility that's already built in to Visual Studio 2005: the Script Explorer window.  The Script Explorer can take care of the usual debugging tasks like stepping through code, adding watches and evaluating variables. 

To use the debugger in Internet Explorer navigate to the browser Tools | Internet Options | Advanced tab and make sure that "Disable script debugging" is turned off. 

Run your web application in Visual Studio 2005.  Then select the menu option for Debug | Windows | Script Explorer.  Notice in the background the tags for telerik RadEditor controls...

The first thing you notice in the Script Explorer window is a series of JavaScript and resource files that are currently loaded.  Double click on the aspx file you're currently working with and you will see the evaluated HTML returned from the server.  The RadEditor control now shows as its computed HTML, CSS and JavaScript that will actually be functioning in the browser. 

You can also navigate up to the script for the page and set breakpoints and watches.  When the JavaScript executes and hits your breakpoint you get all the usual Visual Studio debugging capabilities for free.

Next blog I'll show the excellent "Firebug" debugging utility for Firefox.  Firebug doesn't stop at just JavaScript but works with the entire stack of AJAX related technologies (and has a high cool-factor).

posted on April 17, 2007  #    by Noel Rice  Comments [0]

The Firebug debugger add-in for Firefox handles the entire stack of AJAX related technologies.  Ever wanted to tweak the margins in your style sheet while you watch the changes?  Profile a web page and see a visual representation of when scripts are loading and how big they are?  Watch the XmlHttpRequest (i.e. AJAX) requests move over the wire in real time?  You can do all this in Firebug, and of course you can step through your JavaScript code.  At Falafel we use this tool in our consulting work and telerik recommends Firebug for use in web applications using their RadControl suite.

Firebug is an innovative tool that handles usual tasks you would expect from a combined DOM explorer, AJAX/JavaScript profiler, and JavaScript debugger.  But it combines technologies in a new way that is definitely cool and a lot of fun to use.  This will take a few blogs to talk about in depth, but this should get you started.

Firebug only installs and runs in Firefox.  Get Firefox at http://www.mozilla.com/en-US/firefox if you don't already have it installed.  In Firefox download and install Firebug from http://www.getfirebug.com/Now run any page in Firefox and notice the green checkbox in the lower right hand corner.  Click it to start up Firebug for the page you're on. 

The Console tab is used for logging output.  The logging statements can be embedded in your script or run interactively on the Firebug interactive JavaScript command line.  The image below shows the special "dir" command line API dumping the contents of the "<body>" tag to the console.  A series of "console" commands output with visually helpful icons.  There's more on this tab that will wait for another blog (or jump ahead by checking out the API documentation at http://www.getfirebug.com/docs.html).

If you couldn't wait and are running Firebug right now, try clicking the Inspect button, then move your mouse on a web page.  The HTML and Style tabs will display the corresponding markup in real time as you move.  Click once on the page to stop inspecting.  Notice the crossed out items in the Style window?  The window is showing how styles are cascading and what styles are not in effect.  Try double clicking a style value -- you can edit the value and see the results immediately!  Also notice when your mouse cursor passes over a color or image tag that a thumbnail pops up.  Very smooth...

Try clicking on the Edit button (next to the Inspect button).  You can edit the HTML and see the results.  Feel free to add a completely different tag like the image below reading "Modify HTML on-the-fly!!".

By the way, when you click the refresh button, all changes go away.  The author of this tool, Joe Hewitt, mentions in his talk about the advanced features of Firebug (http://yuiblog.com/blog/2007/01/26/video-hewitt-firebug/) that this version of Firebug is not intended to be an editor, but more of an exploring and auditioning tool. 

Speaking of auditioning new settings, what about style layout settings?  The Layout tab shows the offset, margin, border and padding for each element you select.  In the browser you will see rules and other visual metric devices overlaying the web page.  Now try clicking one of the settings, say top padding for an image as shown below.  You don't have to enter a number off the keyboard.  Instead try the arrow keys to raise and lower values.  That way you can keep your eye on the layout until it's just right.

Firebugs profiling features show you the JavaScript and XHR requests going over the wire.  The example below is a demo using a set of telerik date controls using a RadAjaxManager to AJAX enable the whole process (thanks to John Waters for letting me steal the example).  In the Net tab we can select to see all or only certain traffic.  The image below shows all the JavaScript traffic; when it loads and how big each piece is.  For the web resources that contain images you can pass the mouse over to see thumbnails.  Click the plus sign to get the details like HTTP headers, requests and responses.

If we click the XHR tab we see only traffic initiated by the XMLHttpRequest object.  XMLHttpRequest is a major component of AJAX, so this feature is very important for evaluating web site performance with and without AJAX, tweaking AJAX performance, and even checking XHR traffic for security vulnerabilities. 

Firebug is after all a debugger.  All the capabilities you expect like step over, step into, run to line, step out, conditional breakpoints, watches, and automatic local variable display are there.  The conditional breakpoint window is a nice piece of UI programming in itself (see below).

Note: Thanks to Ramesh Theivendran for letting me steal the code for this XMLHttpRequest demo (I see a pattern forming here). 

This has been the briefest look at a tool that is sure to set the bar for all web debuggers.  In coming blogs I'll show Firebug in more depth, but until then I hope you try it yourself.

 |  |  | 
posted on April 17, 2007  #    by Noel Rice  Comments [1]
 Tuesday, March 13, 2007

You may need the public key token for purposes such as registering an HTTP module.  Use the strong naming tool with the -T option to extract the public key.  Be sure to call sn from the command line that comes with the .NET framework SDK:

C:\Program Files\telerik\r.a.d.controlsQ4 2006\NET2\bin>sn -T radupload.net2.dll

Microsoft (R) .NET Framework Strong Name Utility  Version 2.0.50727.42
Copyright (c) Microsoft Corporation.  All rights reserved.

Public key token is b4e93c26a31a21f0

posted on March 13, 2007  #    by Noel Rice  Comments [0]
 Wednesday, January 24, 2007

.NET 3.0 has a number of command line utilities like the service utility (svcutil.exe) that can be awkward to run if you're already in Explorer, deep in a folder structure.  Phillip's svn blog reminded me of a trick with the registry to get the command prompt window populated with the current path.

30netprompt.gif

You can use this technique for any command line or batch file you want to attach to the Explorer context menu. 

  1. Add a key (any name and content appears to work) to HKEY_CLASSES_ROOT\Folder\shell.
  2. Below that add a key "command" and set the text to be whatever command you want executed.  I copied the command line from the .NET 3.0 SDK "CMD Shell" (see registry export listing below), but you could use any command line entry.  The nice thing about the .NET 3.0 cmd shell is that it sets the environment so you can access svcutil.exe and other 3.0 specific utilities.

Registry export listing:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Folder\shell\Command Prompt]
@=".NET 3.0 Command Prompt"

[HKEY_CLASSES_ROOT\Folder\shell\Command Prompt\command]
@="C:\\WINDOWS\\system32\\cmd.exe /E:ON /V:ON /T:0E /K \"C:\\Program Files\\Microsoft SDKs\\Windows\\v6.0\\Bin\\SetEnv.Cmd\""

Built in to Windows Vista

If you're running Vista then you're in luck, it's built-in!  Check out this article showing how to shift-right-click a folder to get the "Command Prompt Here" context menu item:

http://blogs.msdn.com/tims/archive/2006/09/18/windows-vista-secret-1-open-command-prompt-here.aspx

posted on January 24, 2007  #    by Noel Rice  Comments [1]
 Tuesday, January 23, 2007

While it's true that the .NET 3.0 doesn't directly add any ASP.NET functionality, it's also true that the .NET 3.0 install makes changes in your \Framework\v2.x directory.  Although the install introduction warned that a reboot might be necessary, it didn't turn out to be necessary and the install was relatively painless.  ...Untill we tried to install on a server running a 2.x webservice and received an error indicating that assembly ServiceModel.DLL couldn't be found. 

The primary assembly for Windows Communication Foundation (WCF) services is ServiceModel.DLL. Another seemingly unrelated fact is that hosting a WCF service in IIS requires a service file with a ".svc" extension in a virtual directory.  How is the svc file processed?  An Http handler for the "*.svc" extension is associated with ServiceModel.DLL.  And how does the .NET 2.0 based ASP.NET know to suddenly start looking for this service file?  The 3.0 install adds a new http handler to the web.config file in the \WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG directory.

<configuration>
  <system.web>
  ...
    <httpHandlers>
    ...
 <add
           path="*.svc"
           verb="*"
           type="System.ServiceModel.Activation.HttpHandler,
           System.ServiceModel, Version=3.0.0.0, ...

An IIS restart allowed the web service to resume without error.

posted on January 23, 2007  #    by Noel Rice  Comments [1]
 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]
 Wednesday, March 29, 2006

Given an array of bytes containing the file data, a MIME type, and a file name:

public void DownloadBytes( byte[] bytes, string mimeType, string fileName )
{
  Response.ContentType = mimeType;
  Response.AppendHeader( "Content-Disposition", "attachment;filename=" + fileName );
  Response.BinaryWrite( bytes );
  Response.Flush();
  Response.End();
}

posted on March 29, 2006  #    by Adam Anderson  Comments [1]
 Thursday, March 23, 2006

The .NET Framework offers two methods for rounding: Decimal.Round() and Math.Round(). However, both methods implement a type of rounding known as "banker's rounding," which rounds .5 to the nearest even number. This is a different implementation from the "standard" arithmetic rounding most people are familiar with, where .5 rounds "up." Even the definition of "up" can vary, depending on whether the rounding is symmetric or asymmetric. Symmetric rounding rounds in the same direction relative to 0 (either towards or away). Asymmetric rounding always rounds in the same absolute direction (towards positive infinity or negative infinity).

Banker's rounding has its benefits, but it can cause incompatibility with other systems that implement different rounding schemes. For example, Math.Round( 8.5m ) will round to 8 in .NET, but round( 8.5, 2 ) will round to 9 in T-SQL. Inside is source code that implements arithmetic symmetric rounding in .NET, the type of rounding that T-SQL uses.

See How To Implement Custom Rounding Procedures for additional information

/// <summary>
/// Implements alternate rounding methods, in contrast to Decimal.Round()
/// and Math.Round(), which implement banker's rounding (5 rounds to even).
/// See http://support.microsoft.com/?kbid=196652 for other methods.
/// </summary>
public static class Round
{
  #region Methods

  #region ArithSym
  /// <summary>
  /// Rounds using arithmetic (5 rounds up) symmetrical (up is away from zero) rounding
  /// </summary>
  /// <param name="d">A Decimal number to be rounded.</param>
  /// <param name="decimals">The number of significant fractional digits (precision) in the return value.</param>
  /// <returns>The number nearest d with precision equal to decimals. If d is halfway between two numbers, then the nearest whole number away from zero is returned.</returns>
  public static decimal ArithSym( decimal d, int decimals )
  {
    decimal factor = Convert.ToDecimal( Math.Pow( 10, decimals ) );
    int sign = Math.Sign( d );
    return Decimal.Truncate( d * factor + 0.5m * sign ) / factor;
  }
  #endregion ArithSym

  #endregion Methods
}

posted on March 23, 2006  #    by Adam Anderson  Comments [0]
 Thursday, March 16, 2006

Here's a little code snippet that will search a collection of Controls for the first control of a specified type.

private object FindControlByType( Control root, Type t )
{
  if ( root != null && root.GetType().Equals( t ) )
    return root;
  foreach( Control c in root.Controls )
  {
    object node = FindControlByType( c, t );
    if ( node != null && node.GetType().Equals( t ) )
      return node;
  }
  return null;
}

Example: the following example returns the first instance of an HtmlForm in a Page's Control collection:

HtmlForm form = (HtmlForm) FindControlByType( Page, typeof( HtmlForm ) );
posted on March 16, 2006  #    by Adam Anderson  Comments [0]
 Friday, November 12, 2004

Delphi's DataModules were a useful programming tool because they provided a centralized place to define data schema and business logic which could then be referenced from multiple locations. Visual Studio .NET, however, encourages the programmer to place DataSets and Adapters on each individual page, resulting in decentralized and possibly redundant business logic. However, it is possible to roll your own DataModule-like components in .NET. Here's how:

  1. Decide whether you want to have your custom DataSet component in the same project or in a class library. Keeping it in the same project is a little simpler, while putting it in a separate class library will result in a separate assembly that contains only data logic, making it more suitable to deploy as a business tier.
  2. Add a new Component to the target project 
  3. Add a Connection and DataAdapters to the Component, and generate a DataSet. The visibility of the Connection and DataAdapters will default to private, so make sure to change them as appropriate for your design.
  4. Once the DataSet has been generated, create a new class that descends from the DataSet subclass. The DataSet subclass name is the same as the name of the .xsd schema file.
  5. Add the following attributes to your DataSet subclass:
    1. [ Serializable() ]
    2. [ System.ComponentModel.ToolboxItem( true ) ]
  6. Add a property to the DataSet subclass that references the Component containing all the DataAdapters. Include logic either in the DataSet subclass constructor or in the property accessor to create a new instance of the DataAdapter container if needed.
  7. Optionally, to hide the base DataSet class, open the base .cs file with the same name as the schema .xsd file and change the ToolboxItem attribute from true to false. Changes made to this file will disappear every time the .xsd it is based on changes, so make the decision whether or not this step is worthwhile accordingly.
  8. Build the project
  9. You can now add the custom DataSet class to the Toolbar. When dragged into another project, the Visual Studio IDE will treat the DataSet subclass as if it is a DataSet; it will appear as a top-level item in the DataBinding dialog box and have the DataSet property editor. Additionally, all the custom business logic methods you added to the class will also be available in code. The DataSet schema will only be editable in the project containing the DataSet subclass, which is a natural result of centralizing your schema and logic. Be forewarned that adding such a custom DataSet to the Toolbar while it is still in development might cause more frustration than it's worth, since Visual Studio will not be easily persuaded to detect changes to the DataSet schema, particularly in the designer.

Sample Code

using System;

namespace MyNamespace.MyDataModules
{

  [ Serializable() ]
  [ System.ComponentModel.ToolboxItem( true ) ]
  // MyStronglyTypedDataSet is the name of the DataSet class
  // automatically generated by Visual Studio .NET
  public class CustomDataSet : MyStronglyTypedDataSet
  {

    // CustomDataSetAdapters is the name of the Component class

    // containing all the DataAdapters used to generate, fill,

    // and update the DataSet.

    private CustomDataSetAdapters _Adapters;
    private System.ComponentModel.Container components = null;

    public CustomDataSet( System.ComponentModel.IContainer container )
    {
      container.Add( this );
      InitializeComponent();
      // Initialize DataSet properties here

_Adapters = new CustomDataSetAdapters( container );
    }

    public CustomDataSet()
    {
      // Initialize DataSet properties here

­_Adapters = new CustomDataSetAdapters();
    }
   
    protected override void Dispose( bool disposing )
    {
      if ( disposing )
      {
        if ( components != null )
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }

 

    // This property exposes the component class containing

    // all the DataAdapters used to generate, fill, and update

    // the DataSet

    public CustomDataSetAdapters Adapters

    {

get

{

  return _Adapters;

}

    }

    public void BusinessLogicMethod1()
    {
      // Custom business logic here
    }
  }
}

posted on November 12, 2004  #    by Adam Anderson  Comments [1]

Expression columns are a useful feature of ADO.NET that allows developers to define calculated columns that are maintained on the client side using local data. This is a significant improvement over performing calculations within a SQL query, because expression columns can recalculate based on changes to local data without requiring a round trip to the database server, and less data needs to be transferred from server to client. Besides being able to perform simple arithmetic on values within the same row, expressions can also retrieve values from parent and child rows in a relational dataset, thus providing lookup and aggregation functionality as well. For detailed information on expression column syntax, see the DataColumn.Expression property help topic.

As useful as expression columns can potentially be, however, they come with a substantial limitation: they cannot be used in conjunction with an insert or update query that automatically refreshes row values from the database server. This is because of the way that the .NET framework applies the retrieved values during an update operation, which is to iterate through all columns in the table, expression columns included, and update their values, temporarily setting the ReadOnly property to false. When this operation is attempted on an expression column, the following exception message will result: “Cannot change ReadOnly property of the expression column.” This has been a known bug since 2002, and Microsoft has supposedly promised a fix for the next version of .NET, although it is unclear whether they mean the next version of the framework or of Visual Studio. Since the bug still exists in Visual Studio 2003 and .NET framework 1.1, one can only hope that this bug will be fixed in Visual Studio 2005 and .NET framework 2.0. Until then, there are several workarounds possible, which will be explained in the following paragraphs.

          Since this bug occurs when expression columns are mixed with insert or update queries that refresh the dataset, the only solution is to remove one of the two factors. The first and simplest solution is to remove the select query from the end of the insert or update query. However, this solution has a drawback in that the row will not be refreshed, which can be especially vexing if the database is generating the primary key field.

          The next solution takes the previous one a step further by writing custom code in the RowUpdated event. The RowUpdated event fires after changes have been applied to the database. Custom code could be added to this event to more selectively and intelligently update only the fields in the dataset that correspond to fields in the database. For example:

 

private void sqlDataAdapter1_RowUpdated(object sender,

  System.Data.SqlClient.SqlRowUpdatedEventArgs e)

{

  DataColumn dc = e.Row.Table.Columns[ "RowID" ];

  bool readOnly = dc.ReadOnly;

  dc.ReadOnly = false;

  try

  {

    SqlCommand cmd = new SqlCommand( "select @@IDENTITY", conn );

    e.Row[ "RowID" ] = cmd.ExecuteScalar();

    e.Row.AcceptChanges();

  }

  finally

  {

    dc.ReadOnly = readOnly;

  }

}

 

          Another possibility is to remove the expression columns from the bug-causing equation, rather than removing the automatically supported dataset refresh. In this approach, each call to DataAdapter.Update() would be bracketed by deletion and recreation of all expression fields in the DataSet. For example:

 

ArrayList al = new ArrayList();

 

// Save expression columns

foreach ( DataColumn dc in ds.Table1.Columns )

  if ( dc.Expression != "" )

    al.Add( dc );

 

// Delete saved columns from collection

foreach ( object o in al )

  ds.Table1.Columns.Remove( (DataColumn) o );

 

try

{

  da.Update( ds.Table1 );

}

finally

{

  // Restore saved columns

  foreach ( object o in al )

    ds.Table1.Columns.Add( (DataColumn) o );

}

 

          Lastly, some expression column functionality can be duplicated through custom data binding expressions. To do this, it is first necessary to explain the syntax data bindings created at design time. When creating a simple data binding through the Data Bindings dialog, Visual Studio creates a DataBinder.Eval() method call. The role of the DataBinder class is to simplify writing data binding expressions by eliminating two tasks required by data binding expressions that do not use DataBinder. These two tasks are: casting the object containing the data, and converting the data to the correct data type, which is typically a string. To see these advantages at work, consider the following line of code, which is a typical example of the kind of expression required to bind non-string data in a repeating control such as a DataList:

 

lblDisplay.Text =

  ((DataRowView) container.DataItem)[ "IntField" ].ToString();

 

If special formatting was needed, then the code would expand to the following:

 

lblDisplay.Text =

  String.Format("{0:d10}",

    ((DataRowView) container.DataItem)[ "IntField" ] );

 

This same task can be accomplished by using DataBinder.Eval(), as shown in the following example:

 

lblDisplay.Text =

  DataBinder.Eval( container.DataItem, "IntField", "{0:d10}" );

 

The benefit is that explicit casting isn’t necessary and the format string may be accessed as an extra parameter of the Eval() method rather than requiring a call to the static String.Format() method. However, the savings in typing have a cost in runtime speed. When writing your own custom data binding expressions, consider using the longer form as a way to improve application performance.

          What is important to understand when writing custom data binding expressions is that there isn’t anything magic about using DataBinder.Eval(). Any expression written in the page language that returns a value can be used as a custom data binding expression. Thus, to perform a simple lookup in a data binding expression, enter the following expression as a custom data binding expression. Assume the dataset ds contains two tables named Table and Lookup, with a relationship defined between them with the default name LookupTable. The example code returns the value of the field LookupValue in the table Lookup.

 

// Typed dataset syntax

ds.Table[0].GetLookupRow.LookupValue

 

// Untyped dataset syntax

ds.Tables["Table"].Rows[0].GetParentRow("LookupTable")["LookupValue"]

 

Likewise, aggregate expression columns can be replaced with equivalent DataTable.Compute() method calls. To extend the above example, assume that the table called Table has a child table called Child containing a field called Amount and related by the field TableID. The relationship in the typed dataset is called TableChild. The following expression column (defined in Table) and DataTable.Compute() calls will yield the same results:

 

// Expression column expression

Sum( Child( TableChild ).Amount )

 

// Equivalent DataTable.Compute() for the current TableRow

Child.Compute( "Sum( Amount )", "TableID=" + TableRow.TableID );

 

Armed with this knowledge, it may be possible to entirely avoid the need for creating any persistent expression columns in the dataset.

          Expression columns provide useful and powerful tools to create columns that can recalculate themselves in response to data changes without making a round trip to the database server while keeping the size of the data transmitted as compact as possible. However, in the current version of .NET, they come with significant limitations that will require extra effort on the developer’s part. If you need both the functionality of expression columns and to refresh row values from the database on insert or update, the approaches described above will provide you with several options with which to work around this bug. Here’s hoping it really gets fixed in the next version!

posted on November 12, 2004  #    by Adam Anderson  Comments [1]