jump to navigation

Welcome Microsoft Delegate! Lambda expressions right this way… July 3, 2010

Posted by codinglifestyle in C#, CodeProject, linq, Uncategorized.
Tags: , , , , ,
add a comment

Delegates are deceptively great.  Without them something as simple as the OnClick event of a button would cease to work.  In a nutshell, they offer a simple way to pass a function as a parameter which in turn can be invoked anywhere, anytime.  Pointers for functions, very useful!

In .NET v2.0 the anonymous delegate was quietly introduced, well at least it slipped my notice.  I read about them at the same time I read about Lambda functions.  I saw them laid bare without the syntactic sugar in all they’re simple glory.  As I was stuck on a .NET v2.0 project I found sugar-free anonymous delegates useful to, say, recursively find all controls of a given Type and execute a function on the matching controls.

More recently, I was working on a robust Windows service responsible for various IO operations.  It was vitally important each file operation (heretofore fileop) had its own comprehensive try/catch block.  As the number of fileops increased the code looked like one huge catch block.

It was clear it would be nice to have just one try/catch block in a static utility class which could catch every IO exception conceivable.  Then I could replace each try/catch block with one-line:

bool isBackedUp = FileUtil.FileOp(_logger, () => File.Copy(latestFilename, backupFilename, true));

Notice the file copy on the other side of the lambda function syntax, () =>, is what is executed in the try block below:

public delegate void FileOperation();

internal static bool FileOp(ILogger logger, FileOperation fileOp)

{

bool success = false;

try

{

fileOp.DynamicInvoke();

success = true;

}

catch (ArgumentException argEx)

{

logger.Error(argEx, “Bad arguement(s) passed”);

}

catch (DirectoryNotFoundException dirEx)

{

logger.Error(dirEx, “The specified path is invalid”);

}

catch (FileNotFoundException fileEx)

{

logger.Error(fileEx, “The specified file was not found”);

}

catch (PathTooLongException pathEx)

{

logger.Error(pathEx, “The specified path, file name, or both exceed the system-defined maximum length”);

}

catch (IOException ioEx)

{

logger.Error(ioEx, “An I/O error has occurred”);

}

catch (NotSupportedException supportEx)

{

logger.Error(supportEx, “The requested operation was not supported”);

}

catch (SecurityException secEx)

{

logger.Error(secEx, “The caller does not have the required permission.”);

}

catch (UnauthorizedAccessException accessEx)

{

logger.Error(accessEx, “The caller does not have the required permission”);

}

catch (Exception ex)

{

logger.Error(ex, “General fileop exception”);

}

return success;

}

Not only was this an elegant way to catch a comprehensive set of exceptions, but the resulting code was much more readable.

Of course we could pass bigger hunks of code and this is fine in moderation.  But the flip-side can mean less readable code when lambda functions (and especially lambda expressions) are used without restraint.  Readability for the whole team is paramount.  After all, too much syntactic sugar will rot your teeth!

The brilliant thing about C# is the mind set of “I’m sure there’s a way to do this” is often rewarded with a little research.

Advertisements

A day with The Gu! MVC 2, VS2010 and ASP.NET v4.0 September 29, 2009

Posted by codinglifestyle in ASP.NET, C#, jQuery, linq, Visual Studio 2010.
Tags: , , ,
2 comments

Yesterday I went to Dublin to attend a talk by Scott Guthrie. I knew from reputation Scott was a good speaker so it was great to see him in action. I think most of the Microsoft development world is familiar with Scott’s blog. I’ve exchanged emails with him in the past and he has always done a great job following up. He is a very down to earth guy, very at ease at the podium, and very comfortable the material.

We started the talk with a beginner’s look at MVC 2 and then looked at .NET v4 and VS 2010. Some of this information was a recap of TechEd (see my earlier post), but there was plenty of new information which I’ll recap here.

MVC 2

Scott’s talk was about some of the improvements of the next version of MVC which will be baked in to VS2010. But thankfully, he covered the whole concept in a very demonstration-oriented way. He built upon each concept in a way that left me with a good grasp of the basics.

First, he reiterated that webforms is not going away. MVC is just an alternative presentation layer built upon the same core .NET libraries we know and love. Because there is no designer, no .NET controls, and no code behind (as such) you are much more in control of the generated HTML.

What MVC offers is that control, URL mapping, js integration, and testability. If you’ve ever worked on a messy web app and wished for more structure MVC may be for you. It offers a clean separation of your data layer (model), your html (view), and your business logic (controller).

Right, enough of this verbose carrying-on, time for bullet points!

· MVC 1 was an extra for VS2008 built on ASP.NET v3.5. MVC2 will be baked in to VS2010 and built on ASP.NET v4.0. It will be backwards compatible with MVC1 apps so upgrades should be a snap.

· Controller

o URL Mapping – this is not just a cool feature but fundamental to MVC

§ http://localhost/galway maps to a controller class called galway

· .index is the default action method

§ http://localhost/galway/hooker maps to an action method inside controller Galway

§ http://localhost/galway/hooker/beer maps to the action method hooker and passes the string parameter “beer”. Note this is an alternative to query string parameters.

· These parameters can be strongly typed to string, int, even classes

§ Routing rules go in to gloal.asax.cs

· Operates like an HTTPHandler but is baked in to ASP.NET

· Order routing rules as you see fit. One falls through to another and ultimately to a default

· Can use regular expressions and constraints in your rules

o We can start playing with a controller without a View or Model and directly return some html from controller (think webservice)

o Controller action methods can return an action result type to return a View, redirect, etc.

o To communicate with View we can

§ store information in a ViewData[“key”] dictionary to pass to View

§ store information in a Model and pass this class to View

o Action Filters decorator attributes can be specified on the controller class or an action method to specify which roles / authorization required to use

o Tip: Use a service layer to keep direct data layer queries out of controller

· View

o Offers separation of UI from business logic and just renders the UI

o Remember, no designer or ASP.NET controls. Just you, html, and <%inline code%>.

o HTML. Helper with many built-in templates to generate common controls like checkboxes and textboxes with validation

§ Create your own View templates to have custom scaffolding like a table for a DB list

o Html.EditorFor gives Linq type intellisense to meaning we aren’t binding to a “string” in our model

§ Smart in that Booleans render as checkboxes, etc.

§ EditorTemplates can be used to custom render anything can be shared across entire site or used for just one View

o Html.DisplayFor gives read-only view of data

· Model

o A data entity with logic.

§ Can be LinetoSQL, ADO.NET, your own entity class, whatever

o Can decorate properties with attributes to specify common validators

§ Required, range, etc.

§ Very powerful, dynamic, should greatly ease pain of validating form data

§ Automatically adds a CSS class you can customize to get a red background, whatever

§ Can have server and client side validation

· Client side requires an extra js plug-in but worked seamlessly in demo

· Unit testing is crucial component of MVC and a test project is automatically created for you with every MVC website

o Use AAA method

§ Arrange

· Create a controller

§ Act

· Get the result of (controller.Index(0) as ViewResult)

§ Assert

· Assert if result.IsNotNull

o Dependency injection

§ In the constructor pass DB service layer or fake data. Use an interface for flexibility.

VS2010 & .NET v4.0

· Beta 2 out shortly

· IDE improvements

o Ctrl-, – quick nav via types

o Highlight all references

o Tip: Download CodeRush Xpress for these features in VS2008)

· Better intellisense support

o camel case (i.e. DB matches DataBind)

o Matching (i.e. bind matches DataBind)

o Consume first mode for TDD (test driven development)

§ Ctrl + Alt + Space to toggle

o Much improved javascript support

§ XML documentation (place under function()) for better intellisense for your own libraries

· Debug History and dumping a crash covered again (see previous post)

· .NET 4 is a new CLR unlike 3.0 and 3.5

o In IIS you will see v4.0 as a selectable framework

· Upgrading to VS2010 hopefully just changes solution file (like VS2005 > VS2008) so painless enough to upgrade

· Multi-target support from .NET v2.0 on up

· Lots of project templates including a new online template gallery (web starter kits?)

· Controls to have ClientIDMode property

o Static – is what it is. Call it “bob” and you are guaranteed to get document.getElementByid(“bob”)

o Predictable – new default… no more ctrl001_ prefixing

o Auto – current

o Inherit

· CSS rendering support

o Big upgrades including alternatives to tables for .NET controls

· ViewState – off by default. Force developers to think when we really need it.

· URL routing like MVC for WebForms (connotical)

· SEO (Search Engine Optimization)

o Page.Description and Page.Keywords to generate <meta> tags

§ Idea: Place in master page, tie-in to DB, allow client to change as required

o New SEO plug-in for II7 will crawl site and indentify issues that reduce search relevancy

§ Can increase search traffic 30-40%

· ScriptManager support CDN allowing you to specify URL for AJAX and jQuery direct from http://ajax.microsoft.com. Will actually phantom redirect to very local source but browser histories across many site will use standard Microsoft url meaning high probability of being cached

· New controls

o QueryExtender search control – search a grid

o Chart control

· Validation like MVC for GridView, FormView, ListView

o Auto reflect on class for validation decorator attributes and dynamically render validators with client and server-side validation

· Output/object cache providers (aka customizable I’m sure)

· Pre-start application

o Keep your application up, cached, and ready vs. IIS default behavior which shuts down when not in use

· Performance monitoring

· <%: Html encoded string %>

· Deployment (see previous post)

 

Well that wraps it up.  Please see my earlier post from Tech-Ed and download my PowerPoint presentation which covers a lot of the upcoming features in VS2010.

Visual Studio 2008 JumpStart December 18, 2007

Posted by codinglifestyle in ASP.NET, C#, Javascript, jQuery, linq.
Tags: , , , , , , , , , , ,
add a comment

Yesterday I attended the Visual Studio 2008 Jumpstart at Microsoft in Dublin.  This was a one-day course, presented by David Ryan, introducing some of the new features in C# 3.0 and VS2008.

 

I approach every release with excitement and trepidation.  There are some fantastic new features like JavaScript debugging, nested MasterPages, improved IDE for both coding and web design, and multi-target runtime support.  With multi-targeting support we can use VS2008 to continue to code or support .NET 2.  If you open a VS2005 project, you will be prompted to upgrade your project even if you continue to use .NET 2.  I asked was there any risk associated with this for those who need to continue to support .NET 2 and was told only the SLN file is changed.  So theoretically, there is no reason to keep VS2005 installed!  Do you believe it??  If only we could get rid of VS2003 as well.

 

Now, the reason I also approach each release with trepidation is because you know there is going to be some big, new, ghastly feature which will be force-feed to us like geese in a pâté factory.  This time that feature in LINQ.  Open wide because there is a big push behind LINQ and you’ll notice a using System.Linq statement in every new class (which is a real pain if you change target framework back to .NET 2).  But first, let’s review some of the changes made to C#:

 

  • Anonymous types
    • var dt = DateTime.Today;
    • Anything can be assigned to a var, but once it’s assigned its strongly typed and that type can’t be changed.  So I can’t reuse local variable dt and assign string “Hello” like I could with object.
  • Automatic Properties
    • This:

      private int m_nID;

         public int ID

         {

             get

             {

                 return m_nID;

             }

             set

             {

                 m_nID = value;

             }

         }

 

  •  
    • becomes this:

public int ID { get; set; }

 

  •  
    • The problem is in practice I prefer to use the private variables in code leaving properties for external access only.  Many times the get/set is doing something interesting, like reading the value from a cache or performing some complex operation.  We don’t necessarily want/need this code to execute every time it is accessed from within the class so I use the private variable.  Automatic Properties has us using the public property directly everywhere in the class.  So, personally, this will cause inconsistency in my coding style.
    • You can also specify the get as public but keep the set to just be accessible from within the class like this:

public int ID { get; private set; }

 

  • Object initalizers
    • Ever have to instantiate your own class and have to initialize it with a dozen properties?  Do you add 13 lines of code or go overload the constructor?  Now you don’t have to, imagine a simple Person class with 3 properties:

Person person = new Person { FirstName=“Chris”, LastName=“Green”, Age=33 };

 

  •  
    • Only initialize what you properties you want:

Person person2 = new Person { FirstName = “Chris”, LastName = “Green” };

 

  • Collection initalizers

List<Person> people = new List<Person>

         {

new Person { FirstName = “Chris”, LastName = “Green”, Age = 33 },

new Person { FirstName = “Bill”, LastName = “Bob”, Age = 46 },

new Person { FirstName = “Foo”, LastName = “Bar”, Age = 26 }

         };

 

  • Extension methods
    • This is a way of adding new inherent functionality to existing classes.  The objective is to add a new method to the DateTime type called LastDay() which will return the last day of the given date’s month.

public static class DateTimeUtils

{

        public static int LastDay (this DateTime dt)

        {

            return DateTime.DaysInMonth(dt.Year, dt.Month);

        }

}

 

  •  
    • Notice the this before the first parameter argument.  This tells the compiler that this is an extension method for the DateTime type.  We can now use this method as if it was built in to the DateTime class:
      • int nLastDay = dt.LastDay();
  • Lambda expressions
    • Too lazy or couldn’t be arsed to write a small 2 line function?  This is for you:

Func<string, bool> CheckName = sName => sName == “Bob”;

bool bBob = CheckName(person.FirstName);

Func<int, int> Square = x => x * x;

int nSquare = Square(5);

 

The fact is there’s an ulterior reason var, Lamda expressions, and many of above additions have been added to C# 3.0.  C# had been bent in order to accommodate LINQ.  LINQ allows you to perform queries on objects, DataSets, XML, and databases.  It’s interesting in that it offers an independent layer of abstraction for performing these types of operations.  This has actually occurred to me before when looking at data layers chock full of embedded SQL not being particularly ideal.  LINQ offers a generic and powerful alternative.  Let’s take a look at a simple example based on the people collection from above:

 

var matches = from person in people

              where person.FirstName == “Bob”

              select person;

 

The first thing that caught my attention was the select was last.  One reason they likely did this was to force us to state what we were querying first (the from clause) so that Intellisense could kick-in for the rest of the expression.  Notice person.FirstName was fully supported by Intellisense so the Person class was automatically inferred from the people collection.

 

You can create objects on-the-go from your expression.  For example:

 

var matches = from employee in people

              where employee.FirstName == “Bob”

              select new Person(employee.FirstName, employee.LastName);

 

 

Notice how var is inherently handy here (but bad practice for nearly everything else) as our LINQ expression returns System.Collections.Generic.IEnumerable.  Lambda expressions as well play a key part in LINQ:

 

var matchesBob = people.Select(CheckName => CheckName.LastName == “Bob”);

 

matchesBob.ToArray()

{bool[3]}

    [0]: false

    [1]: true

    [2]: false

 

var matchesInitials = people.Select(ChopName => ChopName.FirstName.Remove(1) + ChopName.LastName.Remove(1));

 

matchesInitials.ToArray()

{string[3]}

    [0]: “CG”

    [1]: “BB”

    [2]: “FB”

 

There is so much more to LINQ that I won’t attempt to cover any more.  Rest assured you will hear much more about LINQ in the months to come (fatten up those livers).  One thing is obvious, C# took a heavy hit in order to support it.  Let’s hope it’s worth it as every release we lean more and more towards VB.  A colleague recently remarked, “C# is all VB under the covers anyhow”.  He might be right.

 

Some other interesting new additions:

  • XElement – for anyone who has programmatically built XML before you will appreciate this quicker alternative
  • ASP.NET ListView – the singular new control this release.  Its basically a Repeater but with design-time support
  • Script Manager Proxy – typically the Ajax ScriptManager will be placed in the MasterPage.  When the content page needs to access the ScriptManager a ScriptManagerProxy can be used to get around the restriction of only one ScriptManager allowed per page.
  • Javascript enhancements – built-in libraries which extend string, add StringBuilder, and a number of other enhancements to make writing JavaScript more .NET-like
  • CLR Add-In Framework: essentially a pattern for loading modules (only from a specified directory) vs. using reflection, iterating classes for a specified type, and using the activator to instantiate the object
  • Transparent Intellisense: In VS2005 Intellisense went in to hyperdrive and our tab keys have never been the same.  However, I often found myself cursing it as it often got in the way.  So when VS is being too helpful and you can’t see what you’re doing press CTRL rather than ESC to turn Intellisense transparent.
  • Right-click the code and you will see an Organize Using menu below Refactor.  Here is a feature I’ve often dreamed of: Remove Unused Usings.  Pinch me!  Also, if you right-click the interface in a class’s definition (public class MyClass : Interface) there is an Implement interface option.   Last, if you are coding away and using a class before adding a using statement use ALT-Shift-F10 to automatically resolve the class and add the using statement to your file.
  • Improved support for debugging multithreaded applications
  • SQL Database Publishing Wizard is now integrated in the VS
  • Did I mention JavaScript debugging??!

 

You may notice I’ve omitted a few big topics.  I didn’t mention Ajax because that’s old news now.  However, there are new versions of the Ajax Control Toolkit and web deployment projects for VS2008.

 

I also didn’t mention Silverlight although I may find some interesting applications for it in the future.  For example, if you really hate writing JavaScript you could use Silverlight’s built-in mini CLR to write C# code which executes in the browser.  Oh, I hear it does some UI stuff too.

 

References: ScottGu 19-11-2007, ScottGu 13-03-2007, ScottGu 08-03-2007, C# 3.0 In a Nutshell, Pro ASP.NET 3.5 in C# 2008, and CodeProject.