Silverlight Hack

Silverlight & related .NET technologies

About Me

Welcome to Silverlighthack.com.  This is a site where you can find many articles on Silverlight, Windows Phone 7 and .NET related technologies.  

My name is Bart Czernicki.  I have been working with computers since 1988 and have over 12 professional years in the IT field focusing on architecture, technology strategy and product management.  I currently work as a Sr. Software Architect at a large software development company.

Below is the cover of my new book that shows how Silverlight's unique RIA features can be applied to create next-generation business intelligence (BI 2.0) applications.

Silverlight 4 Business Intelligence Soft 

Contact: [email protected]

View Bart Czernickis profile on LinkedIn

NONE of the comments or opinions expressed here should be considered ofmy past or current employer(s).  The code provided is as-is without anyguarantees or warranties.

WCF 101 - Understanding Transfer Security Visually

Overview 

WCF includes a variety of security settings and design options.  One of the security options the service architect has to worry about is transfer security.  Transfer security deals with ensuring safe and secure communication between a client and service host. 

Transfer security is very important for several reasons.  Even the best authorization and authentication service design means nothing if the messages are not secure.  Unsecure messages can lead to a variety of problems like:

  • exposing the message contents to the outside world including hackers
  • exposing other security mechanisms on how to compromise your service (authentication or authorization)
  • spoofed messages (By mimicking certain message patterns, hackers can create fake messages that can cause your service to end up corrupted.)
  • DOS attacks
WCF Transfer Security Implementation

WCF provides a variety of ways to secure the communication channel between the service and the client.  Using these options properly can lead to highly secure communication with a very low probability of your messages being compromised.  Conversely,  even missing a small setting in the transfer security configuration can lead to messages that can have compromised privacy or integrity.

Generally speaking, WCF supports four different ways to secure your service transfer mechanism:

  • Transport - This secures the messages by using a secure protocol that encrypts the entire channel that the messages are flowing over.
  • Message - This secures the messages by encrypting the messages themselves.
  • Both - This method combines both Transport and Message security.  This secures the messages by encrypting the messages themselves and encrypting the channel.
  • Mixed - This method uses Transport security to protect the message contents.   However, message security is used to protect the credentials of the user.

A developer who is not experienced with WCF might have a hard time comprehending these concepts initially.  Therefore, I decided to show at a very high level how you can understand these transfer security modes visually.

Unsecure (None) Transfer Security

Messages are unencrypted over a channel stack that is unsecure

  • Messages are are unencrypted and the channel is unencrypted as well.
  • Unsecure transfer security is obviously not recommended.
  • Services DO NOT have to have content you want to protect in order to provide message security.   Without properly protecting your messages, your service can be exposed to hackers and it could cause unwanted performance problems as well attacks like relay or DOS attacks can bring the entire service down.
Message Transfer Security

Messages are encyrpted over a channel stack that is unsecure

  • Individual messages are encrypted.
  • Message transfer adds the most overhead and latency to the WCF service (other than the Both/Mixed option)
    • Each message needs to be properly encrypted and encoded as it leaves the client or service.
    • Each message needs to verified that it was not tampered with when it is received.
Transport Transfer Security

Messages are unencyrpted over a channel stack that is secure (If the channel were unsecure, you could see the messages in clear text.)

  • The messages are not encrypted; however, the channel is secure through using a secure protocol.
  • The communication channel is set up intially and transport security can take advantage of hardware acceleration and thus, can be further optomized.
  • Transport security is point to point.  Since the messages themselves are not encrypted, once they go to another point, they can be potentially exposed to integrity/privacy attacks as if they were unsecure.
Message Transfer Security (mulitple hops)

Messages are encyrpted over an unsecure channel between the client and the service endpoint (1st hop).  Notice the messages remain encrypted between the first service and second service (2nd hop).

  • The big advantage of message security is that it provides end to end security.
    • Messages leaving intermediary services retain their security.
  • Message security is not provided by all bindings and it is considered the best practice when designing enterprise services organized in a "matrix".
Transport Transfer Security (multiple hops)

Messages are unencyrpted over an secure channel between the client and the service endpoint (1st hop).  Notice the messages DO NOT remain encrypted between the first service and second service (2nd hop).

  • The big disadvantage of transport security is that it is only guaranteed to be point to point.
  • Message leaving and the intermediate service are not secure (by default).
  • Messages can be secured in the 2nd hop; however, it requires additional work.

Silverlight supports Transport level security natively out of the box with WCF configuration.  Message security is possible inside Silverlight; however, it does require additional advanced programming beyond setting simple binding/behavior settings.  However, message security is not 100% supported with all the different options like securing Messages with credentials.

Summary

In this article, I introduced the basics of WCF transfer security design scenarios.  I decided to show the differences visually so that this concept is easier to understand for those new to WCF.

Posted: Dec 10 2008, 16:27 by Bart Czernicki | Comments (0) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: .net | WCF
Tags:
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us

PDC 2008 - Silverlight 2 Wrap-Up

PDC (Professional Developers Conference) 2008 is over and there was a lot of information released over the course of the 4 days.  You probably have heard some of it if not all of it.  I wanted to write a post to summarize the information pertaining to Silverlight either directly or not directly that was released last week.  Over the course of the week, Silverlight developers were bombarded with information that was coming out and this post's goal is to help developers get a handle on all of the information.  Here is the summary of what has been released during the week of the PDC 2008:

  • Silverlight Tools for Visual Studio 2008 SP1 
  • Silverlight Control Toolkit
  • Expression Encoder SP1
  • PDC Silverlight Videos (directly related)
  • PDC Silverlight Videos (indirectly related)
  • Silverlight 2 for Mobile Devices
  • WCF REST Starter Kit
  • Silverlight and SEO
Silverlight Tools for Visual Studio 2008 SP1

Silverlight Tools for Visual Studio 2008 SP1 were released over 3 weeks ago.  However, for those people who are detailed oriented, this release was labeled as RC1.  I posted a question on this on the forum the day this was released.  Apparently, this was NOT the final release of the tools.  On 10/30/2008 Microsoft released a new build of the Silverlight Tools.  I don't think anything has changed, but regardless, you will want to update your tools to this new build.  The new build of the tools can be downloaded here: http://www.microsoft.com/downloads/details.aspx?FamilyId=c22d6a7b-546f-4407-8ef6-d60c8ee221ed&displaylang=en

Silverlight Control ToolKit

The Silverlight Contol Toolkit was announced at the PDC 2008.  It has a bunch of great controls, themes and charting cababilities.  The big news is that the toolkit is open sourced and it you can extend it or build your own controls.  Not only is it a great way to enhance your current Silverlight applications, but it is also a great way to learn about Silverlight control development and architecture.  Shawn Burke's team has also included a bunch of unit tests using the Silverlight Framework so you can learn how to implement some TDD with Silverlight.  You can download the toolkit here: http://www.codeplex.com/Silverlight

Expression Encoder SP1

Expression Encoder SP1 has been released.  I like the approach Microsoft took by adding service packs to both Blend and Encoder rather than forcing people to upgrade.  Therefore, people who have invested in version 2 are getting their money's worth.  SP1 of Encoder allows you to create custom Silverlight 2 video player skins.  It also includes H.264/AAC support.  The service pack is available here: http://www.microsoft.com/expression/try-it/default.aspx?filter=servicepacks (Note: Expression Encoder also has an Express version which will work after the trial expires allowing you to do some basic things.)

PDC 2008 Silverlight Related Videos Online

If you weren't at the PDC, Microsot published the videos from the 4 days to the web.  You can watch the PDC 2008 Videos online here: https://sessions.microsoftpdc.com/timeline.aspx.  Here are the videos that are either directly or indicrectly related to Silveright development and I have some notes on the ones I watched.

If you are an architect, development manager, etc.,  I highly recommend watching some of these videos and then getting your team together for a lunch or a meeting and watching this together.  I find this spurs developers thinking together about the current and future technology earlier.

PDC Silverlight videos (directly related to Silverlight)

PDC Silverlight Videos (indirectly related)

Silverlight cannot consume data directly from objects or databases located on servers (even if it is the same server Silverlight is hosted on).  Silverlight is all about consuming data from services.  These videos are an absolute MUST to watch if you are a Silverlight developer and consume data from services.

  • WCF: Developing RESTful Services: http://channel9.msdn.com/pdc2008/TL35/ 
    • Great introduction on developing WCF services that are based on REST.  Towards the end of the video there is a great example of consuming these services via a Silverlight client. Unless you are a REST expert, you will gain a lot of information from this video.
  • Developing Applications using Data Services: http://channel9.msdn.com/pdc2008/TL07/
    • Excellent video that deals with ADO.NET Data Services development and the Entity Framework.  This video shows some of the cool interceptors for security and enhancing services that exist in ADO.NET Data Services.  If you are building a simple Silverlight client that needs, call batching, smart data and/or security concurrency management,  ADO.NET Data Services provide a lot of great features here.
Silverlight 2 For Mobile Devices

Microsoft is porting Silverlight to mobile devices.  This is a really welcome feature.  Many users who have an iPhone know that Apple is currently "blocking" the availability of Flash to mobile devices.  This is where Silverlight has a potential advantage and put a dent in the Flash market share by targeting mobile devices.  Most of this information is coming from this video here from the PDC: http://channel9.msdn.com/pdc2008/PC10/

Here are some of the highlights from the PDC:

  • By 2010 statistics show that there will be about 4 billion mobile phones in the planet.  There is a huge opportunity here!  So how do you write applications that are rich to thousands of users?  Silverlight :)
  • Silverlight 2 (That's right; the same Silverlight 2 on desktops) has been announced for the mobile space.
  • Plublic CTP will be available in 2009 (Q1).  My guess is that they will release this at the same time as MIX 2009.
  • The really cool part is that the SL 2 on mobile requires NO CODE changes to work on a mobile device where Silverlight is installed!!  That is really nice and very powerful and one code works on both the desktop and mobile devices. 
    • The Baby Smash demo really drives this point home further.  So not only can you share code between WPF and Silverlight 2, you can share code between WPF, Silverlight 2 and Silverlight 2 Mobile!  That is impressive; three platforms with one codebase.
WCF REST Starter Kit

One of the ways that Silverlight can consume data is through RESTful services.  WCF was part of the .NET 3.0 framework back in 2006.  In 2006 REST services were just starting to get traction as many Web 2.0 companies used this design as a preferred method for their service APIs.  WCF .NET 3.5 has added some features for REST services.   However, there was still a lot of plumbing code in order to write proper RESTful services in .NET 3.5.  The MySpace API is a great example of what can be done with WCF and REST on a very large implementation.

In order to make writing some of the WCF REST services easier, Microsoft released the WCF REST Starter Kit during the PDC. 

The WCF Starter Kit makes building RESTful services a lot easier.  It also shows the impressive architecture of WCF.  It can be enhanced with using attributes and interceptors to build a REST architecture for services.

Silverlight and SEO

Several months ago Google announced that it can now crawl Flash-based applications.  This is pretty important because now Flash-based content is searchable and this is critical to any revenue model that is based on high-page ranks on Google (sales, ads, etc).  Silverlight currently cannot be crawled by Google (maybe in the future).  However, there are couple things you can do right now to make sure your Silverlight application gets crawled by Google:

  • Ensure that the page hosting your Silverlight content has proper meta tags and place the SEO there.
  • You can also place a page for a "deprecated" client.  Therefore, if you receive a hit from a user that doesn't have Silverlight, you can bring them to an HTML page rather than the full Silverlight client.  This way when the Google robot tries to crawl your site, it will crawl it based on the HTML page.

This information is really important for developers that are jumping into RIA.  Most architects are ready to jump right into the technologies and try to solve problems with RIA.  However, things like SEO sometimes might fall through the cracks and might not be acceptable to a client. Check out this post for more information on Silverlight SEO Optimization: http://nerddawg.blogspot.com/2008/10/search-engine-optimization-for.html

 

Posted: Oct 29 2008, 13:09 by Bart Czernicki | Comments (4) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: .net | Blend | Mobile | Silverlight | WCF
Tags:
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us

Software Entrepreneurship Track - Tracking a Microsoft .NET based startup

Outside of my fulltime job, I have a couple of projects I am working on in my spare time.  Both of these projects of course are RIA (Silverlight) ideas that are currently little side projects but hopefully will turn into something more.  I have worked in over 4 environments that I would consider startups.  All 4 have been acquired or sold while being an employee there.  As an employee, I have gained a great deal of experience while dealing with the many benefits and drawbacks while working in startup surroundings.  However, most of it comes from an internal perspective.  As an employee, you don't see a lot of the external events going on and sometimes the big picture.  Until you look at the startup process from an external vantage point do you appreciate what it takes to take an idea and mature it into a successful business.

I wanted to write about a great resource for Microsoft based startups from a high level vantage point.  This article focuses on one company's technical implementations of a new business model.  I am not affiliated with it in any way and all this information is what I have found out from tv, podcasts and web searches.  Why is this on my site? The information below is a great way of looking at a technology from another angle for a startup.  Furthermore, its based on .NET; how can you go wrong?

Several months ago, I watched several entreuprenurial shows on the MOJO channel.  One of the shows was called Start-Up Junkies which followed the start of the company called Earth Class Mail.  The company featured was trying to develop a system to make postal mail available online and easy to manage like e-mail.  The show mainly focused on the business plan and raising capital for the business.  It essentially was a reality show on a startup.  You have all the drama, hardships and the roller coaster ride of a startup well on display in the 8 episodes.  If you have Mojo as part of your cable/satellite, you can catch re-runs of the show.  However, it's just easier to watch all the episodes at your leisure on Hulu.  After watching all the episodes several months ago, some of the insight in the episodes kept repeating in my head.  So I decided to write about some of my thoughts on it.

 

Reality Episodes and .NET stuff
The first few episodes (while still interesting to me) focus more on the finances and raising capital.  I highly recommend you check all of them out regardless of your background.  However, Episode 8 is the episdode developers/software entreupreurs will DEFINITELY want to check out. As a .NET developer, episode 8 has everything you can think of:
  • Description of re-write from LAMP -> Microsoft .NET 
  • ASP.NET Exceptions (I counted at least 4 different ones)
  • Lambda expressions whiteboarded (you gotta love that)
  • Developer & QA bug/defect meeting
  • CEO & VP of Engineering uncomfortable conversations over software deadlines
  • Deadline for a presentation
    • Multiple plans in case of failure
    • Showing less (don't push this button)
  • Recruting employees from Microsoft to the startup
  • Cross referencing of web/advertising campaign with Google Analytics & the content network (that is more in episode 7)

I am not going to go over the episode in detail.  For those who are in the software business, you will definitely want to check it out.  Just from the things I mentioned above, you should love the amount of .NET geek stuff in there for a 30 minute show!  If you are a reality TV junkie and a .net developer, you are going to love the show.

 

Enterprise Development
"We just moved to the .NET platform so that we can scale"
-- CEO of Earth Class Mail

Gotta LOVE that quote!  Even though I am passionate about .NET, I think the quote misrepresents the facts.  Let's put the quote in context.  Earth Class Mail is in the busines of providing your postal mail online by having it scanned and materializing it digitally.  They were originally written in PHP and based on the LAMP architecture.  There are gigantic sites that have millions of hits per day that obviously scale very well (in fact, some would argue better than .NET) that are written on LAMP.  That comment taken literally is completely false.  If you look at the Hulu message boards of Google online, you will see a lot of people referencing that comment and essentially making fun of it.  Ron (the CEO) even repeats the quote on other message boards :) ("...our platform is built on .NET now in order to support millions of simultaneous users").

Literally, that is a ridiculous comment.  However, let's evaluate a couple of things.  First, this is the CEO talking.  I don't know Ron, nor have I ever met him; however, let's assume that his developer skills are average at best.  He is most likely repeating talking points from a meeting with his engineering staff.  How can this be taken out of context?  Let's dig deeper into the technology they are using.  The following I am going to go over is NOT part of any of the shows directly.  Several months ago I came across the interview with Matt Davis with Scott Hanselman who was/is (?) the architect at Earth Class Mail.  This interview was done in October 2007, back in the beta days of .NET 3.5.

If you listen to the interview, you have a little more insight as to why they went with .NET and why you could argue that .NET is the platform that would scale for them.  I am going to look at it from three different perspectives.

Existing System

In the interview, Matt asserts that the original system was done by Russian contractors and completed using the LAMP architecture stack.  It was a 2 tier stack largely focusing a lot of the logic on PHP.  Obviously, there are many applications that can be built on the LAMP stack that scale and run some of the biggest online businesses today.  Matt (in the interview) and Paul Irvine who was the VP of Engineering at Earth Class mail (in the MicrosoftStartUpZOne interview) both obviously agree that the LAMP architecture could scale.  It was the orginal LAMP prototype that was not built to scale and needed to be replaced.  Going back to the original statement about moving to .NET for scaling. The comment is not too far fetched if you are scaling your business with a new system that replaces the old one.  It's technically a valid statement, even though they could have just re-architected the original LAMP system to scale.

The Technology

Earth Class Mail is in the business of providing your postal mail online to you via the web (SaaS).  This involves sorting the mail, scanning it and providing high-res images of the mail contents.  This is the key part of their business.  Obviously, there is a decent UI/graphical portion to the application(s) in the system.  Listening to the interview with Matt, you understand that they went with .NET 3.5 and WPF for some of the presentation enhancements to the system.  .NET is probably the only framework that allows you to create a rich UI experience (while still inside the IDE and using the same language) using WPF or Silverlight.  This is where I agree 120%.  While it is not clearly stated, the future presentation scalability of a system is greatly enhanced if it includes a native stack that will be improved.  WPF and Silverlight are going to be the future mainstream presentation layers for most .NET based systems.  This is exactly where the scalabiliy shines.  You have the ability to leverage a common codebase and deploy fat client applications (local, administraton) via traditional methods or ClickOnce.  If they want to provide a SharePoint web part with Silverlight with the Earth Class Mail technology, they can choose to do so.  While the presentation offerings expand, they are using one native technology under the covers as the engine.  From a UI perspective, the .NET technology allows you to scale a great deal.

The Enterprise

A large part of Earth Class Mail's business is focusing on Enterprise level deployments.  Not only are they targeting the electronic delivery of postal mail for the masses, but for entire countries and Fortune 500 companies.  In fact, during the show one of the challenges that creeps up is them dealing with an enterprise level client codename "Cheetah".  So what does this have to do with .NET scaling?  Obviously, enterprise level deployments are usually synonymous with providing deep scalability.  This is where I think .NET comes in.  Open source and RAD alternatives are great in scaling and delivering rich systems for the masses (your average end user).  This is where Microsoft is getting CLOBBERED by Google (Gmail, Docs, Maps), Adobe (Flash), Apple (iPhone).  However, Microsoft's strengths are in its enterprise level products: collaboration (SharePoint), e-mail (Outlook), Business Intelligence (Analysis Services), Enterprise Reporting (Reporting Services), database storage (SQL Server), SOA (Biztalk & WCF), etc.  A lot of these products have rich integration with each other and the .NET framework.  If your focus is on writing an app that integrates with FaceBook, iGoogle, uses Amazon cloud storage and/or works on Macs/Linux, then obviously Microsoft technologies are probably not your top option.  However, since most Fortune 500 companies are more comfortable with Microsoft based technology from the workstations all the way to the enterprise applications, using .NET is a no brainer.  The amount of scalability that can be achieved with all the Microsoft products together is enormous.

The Power of the Microsoft Partnership

Earth Class Mail has huge potential to be a multi billion dollar company.  Having them utilize the .NET platform is an obvious big win for Microsoft.  Microsoft is trying to market its tools not just for the enterprise, but for startups as well.  Earth Class Mail in return for being a partner receives huge benefits of its own.  Microsoft obviously provides its partners with technical advise, training resources and their own internal roadmap insight.  Furthermore, a Microsoft partnership goes further in opening doors for strategic growth and exposure that are not possible for a small company going at it alone.  A perfect example of this is shown in Episode 8.  Earth Class Mail featured at the Microsoft booth at the Post-Expo.  Furthermore, the CEO is invited to deliver one of the key speeches at the expo.  These are excellent examples where a strategic partnership with Microsoft goes well beyond just the technology and can open up an "enterprise geared" startup valuable avanues.

Here is a good list of all the items offered by Microsoft for startups.  Also check out the Microsoft StartUpZone for more information.

In conclusion,  scaling needs to be looked at from different perspectives other than just a literal comment.  Of course, .NET is not the only platform that can scale.  However, in terms of what the business is and who it is targeting, I think that chosing the .NET technology was an obvious and correct choice for them.

 

I just wanted to write a few notes about the show and anyone who is thinking about doing a .NET based startup or is a developer might find not only interesting but entertaining as well.

 

Posted: Oct 05 2008, 15:07 by Bart Czernicki | Comments (5) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: .net | entrepreneurial
Tags:
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us

Evolution of C# delegate syntax from .NET 1.x to 3.5

Delegates were introduced with C# 1.0 (with .NET 1.0) as a way to represent function pointers.  Delegates like most other aspects of advanced C#/.NET programming were often misunderstood and a lot of times programmers didn't even know they were using them inside their code! One source of this problem was a rather cluggy syntax provided with the original C# 1.0 syntax.  Luckily as .NET evolved, so did the syntax for delegates by becoming more concise and clear.  This is exactly what this article focuses on; this is NOT an intro into delegates, how they relate/work with events or a "best practice" guide.

The best way to show delegate syntax in action is to try to solve a simple coding problem with them.  Suppose I get asked this on an interview: I have a form with 2 text boxes and I can input 2 numbers.  What I would like to do is when I click the "=" button (equals) is have the numbers be added via a delegate binary operation, by adding the two numbers.

So the form looks something like this:

Let's assume that we have an event handler already hooked up to the button and after we click that button we expect the two numbers to be added.

.NET 1.x (1.0 - 1.1) Solution (C# 1.0)

This solution has four parts:

  • Declare the delegate with the desired signature
  • Declare a method that matches the delegate signature
  • Instantiate the delegate (tell the delegate with method to call)
  • Call the delegate and retrieve the result
Delcare the delegate:

delegate int Add(int firstNumber, int secondNumber);

The delegate type is created by using the delegate keyword (much the same way we would declare a string type; i.e., string someString = "test";)  The second word is the return type for our delegate.  Since we are trying to add two numbers we expect to get a integer (int) back.  Next, is the name of the delegate.  In our case, we named the delegate Add (much the same way you would name a method).  Lastly, we need want our code to add two numbers together.  Therefore, we would like to have two interger parameters that are going to be passed from our text box. 

In the code above, what we did was create a template in a sense of how we want our method to look like.  We do not know what this method will do yet, but we do know it will have two integers as parameters and it will return an integer.

Declare a method that matches the delegate signature:

private int AddNumbers(int firstNumber, int secondNumber)

        {

            return firstNumber + secondNumber;

        }

Here we declared a method that matches the desired signature of our delegate type.  Our method is called AddNumbers and it takes two integer parameters and has a integer return.  The method is where our simple business logic of adding two numbers will occur and the method body will execute and give the delegate some kind of functionality (in our case add two numbers).

Instantiate the delegate (tell the delegate with method to call)

Add add = new Add(this.AddNumbers);

This piece of code will instantiate a new Add type and tell it to call the AddNumbers method.  Behind the scenes, the compiler compiles the delegate type we declared (code in "Declare the delegate") into a class.  This class can take a parameter for its constructor a method that matches the signature of the delegate.  It doesn't matter what the method is called or what the underlying business logic does. The only thing that matters is that the signature of the method matches the signature of the delegate.  To reiterate (in our case) this is a method that has 2 integer parameters with an integer return type.

Call the delegate and retrieve the result

int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

Calling the delegate is the simplest part.   Now that we have an instance of the delegate called "add", we simply pass in the two integer parameters.  Above, we have two text boxes and we convert each Text property into an integer and pass them into the instance of our Add delegate "add".  The delegate takes these parameters and simply calls the method it was told to in the step above and passes these paramters. 

For those confused, you can just call the delegate directly.  For example:

int result = add(3, 4);

As you will see below, all of the different types of using delegate code use the same way to call the delegate. This part of calling the delegate does not change, no matter what method you use!

Summary

Using delegates in .NET 1.0 - 1.1 (2002 - 2003) was not the friendliest.  There were a few steps to go through.  Many programmers taking the leap from VB.NET or another language simply by passed delegates because of the additional syntax.  Imagine learning a new language and trying to conceptualize using delegates and their uses.  Delegates in these early days of .NET were usually used/abused by C++ programmers familiar with the delegate C++ counterpart.  Delegates also in those days had some performance issues; design implications (making a public delegate is bad) and some designs could cause memory problems. 

Putting it all together would look something like this:

    1         // 1) Declare a delegate

    2         delegate int Add(int firstNumber, int secondNumber);

    3 

    4         // 2) Declare a method (matches the delegate signature)

    5         private int AddNumbers(int firstNumber, int secondNumber)

    6         {

    7             return firstNumber + secondNumber;

    8         }

    9 

   10         private void btnAdd_Click(object sender, EventArgs e)

   11         {

   12             // 3) Initialize the delegate to a method that matches the signature

   13             Add add = new Add(this.AddNumbers);

   14 

   15             // 4) retrieve the result

   16             int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

Not counting comments/whitespace it was about 7 lines of code to declare/initialize/call a delegate back in the .NET 1.x days. More importantly, you have 4 seperate parts to this solution.

.NET 2.0 - 3.0 Solution (C# 2.0)

.NET 2.0 introduced a concept called anonymous methods.  This allowed us to call inline business logic (i.e., a method) without having to have the method defined.  The business logic simply became part of the delegate.  Let's see how this improved our delegate syntax for our scenario. 

This solution has three parts:

  • Declare the delegate with the desired signature
  • Instantiate the delegate (with the business logic defined inside the delegate "body")
  • Call the delegate and retrieve the result
Delcare the delegate:

delegate int Add(int firstNumber, int secondNumber);

The delegate type declaration is the same as the prior version.

Instantiate the delegate (with the business logic defined inside the delegate "body")

Add add = delegate(int firstNumber, int secondNumber)

        {

            return firstNumber + secondNumber;

        };

We put the business logic now inside the "body" of the instantiation of the delegate. Notice how we skipped the method decleration in this solution, because it's not needed since it's inside the delegate "body". 

So, this is nice and clear and we eliminated a whole part (no more method to declare) and one statement of code.  This is what anonymous methods allow us to do, by putting the method logic directly inside the "body" of the delegate.  The syntax for the anonymous method starts with the word delegate itself after the equal sign.  In this case, it tells the compiler that we are declaring an anonymous method.  The next step is to define the parameters to match the signature of our Add method, which are the two intergers respectively.  Our inline body of our delegate is the same as our AddNumbers method returning an integer.  That's all there is to it.  Anonymous methods can have no parameters and as well can have no (void) returns.

Call the delegate and retrieve the result

int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

Same as before.  Nothing new to see here.

Summary

Using delegates in .NET 2.0 - 3.0 became simpler.  Not just because you eliminated one line of code, but because now it had one less "working part" and programmers not familiar with delegate syntax could easily tell what was going on.  This solution obviously would not work when you wanted to design more complex/re-usable objects.  However, it made the use of anonymous methods in predicates and simple situations much easier and the delegate syntax was finally resembling some brevity that functional languages enjoy. 

In summary, our .NET 2.0 - 3.0 solution looks like this:

    1         // 1) Declare a delegate

    2         delegate int Add(int firstNumber, int secondNumber);

    3 

    4         // 2) Initialize the delegate using an anonymous method(new in .NET 2.0)

    5         Add add = delegate(int firstNumber, int secondNumber)

    6         {

    7             return firstNumber + secondNumber;

    8         };

    9 

   10         private void btnAdd_Click(object sender, EventArgs e)

   11         {

   12             // 3) Retrieve the result

   13             int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

A lot more concise and we elminated 3 lines of code; 1 part (method decleration) and the code is a little clearer to read. 

.NET 3.5 Solution (Type 1) (C# 3.0)

.NET 3.5 (C# 3.0) introduces even more brevity to delegate syntax with lambda expressions.  Lambda expressions are a further evolution of syntax brevity for anonymous methods.  You take the spirit of declaring the business logic inline with delegates even further.  I broke the .NET 3.5 solution into type 1 and type 2.  Type 1 uses just uses the new lambda expression syntax.

This solution has several parts:

  • Declare the delegate with the desired signature
  • Instantiate the delegate (with the business logic defined inside the delegate "body")
  • Call the delegate and retrieve the result
Delcare the delegate:

delegate int Add(int firstNumber, int secondNumber);

The delegate type declaration is the same as the prior version(s).

Instantiate the delegate (with the business logic defined inside the delegate "body")

Add add = (firstNumber, secondNumber) => firstNumber + secondNumber;

Whoa!  That looks different.   Let's take a step back and see how we got to the lambda expression from the anonymous method. 

In the .NET 2.0 version we had something like this:

Add add = delegate(int firstNumber, int secondNumber)

        {

            return firstNumber + secondNumber;

        };

First, let's remove the delegate keyword.  Since the delegate keyword back in the .NET 2.0 (C# 2) version told the compiler we were declaring an anonymous method, it needs to be replaced since we want to use lamdba expressions.  Since we are going to replace the anonymous method syntax with lambda expression syntax, we need to use the keyword that tells the compiler we are working a lambda expression.  This keyword is "=>".  The compiler would like to see this after the parameters are defined but before the inline body of the expression. 

Our first step in our lambda expression will look like this (This is valid syntax and will compile):

Add add = (int firstNumber, int secondNumber) =>

        {

            return firstNumber + secondNumber;

        };

The expression now reads:  The parameters of integer firstNumber and integer secondNumber "goes to" return the sum of firstNumber plus secondNumber. The code above is now a fully functioning Lamdba Expression and not an anonymous method anymore.  Replacing the "delegate" keyword with the appropriate location for the "=>" keyword converted this from an anonymous method to a lambda expression.  This is very important, so the compiler with this simple keyword swap now knows we are dealing with a lambda expression.

We didn't really gain much here.  We essentially replaced one keyword with another.  What we can do next is add additional lambda expression shortcuts. Lambda expressions do not require curly braces or return type. 

If we remove both of these, this expression now becomes:

Add add = (int firstNumber, int secondNumber) => firstNumber + secondNumber;

That's getting much better.  Notice, no curly braces or the return keyword; the C# 3.0 compiler can derive all this information for us!  The expression looks more concise now.  But we can do better.  The compiler is even smarter now since it can detect the type of parameters we want to use.  We don't need to explicitly say that we are passing in two integers; this is detected by the compiler. 

Now the full expression (after removing the two int keywords) remains as just the parameter names:

Add add = (firstNumber, secondNumber) => firstNumber + secondNumber;

Call the delegate and retrieve the result

int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

Same as before.  Nothing new to see here.

Summary

We did a lot here.  Lambda expressions make a big difference in syntax brevity and clarity.  Let's take look what we have now:

    1         // 1) Declare a delegate

    2         delegate int Add(int firstNumber, int secondNumber);

    3 

    4         // 2) Initialize the delegate using a lambda expressions (new in .NET 3.5)

    5         Add add = (firstNumber, secondNumber) => firstNumber + secondNumber;

    6 

    7         private void btnAdd_Click(object sender, EventArgs e)

    8         {

    9             // 3) Retrieve the result

   10             int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

A lot more concise and we elminated 3 more lines of code!  Now we are getting somewhere. 

.NET 3.5 Solution (Type 2) (C# 3.0)

The type 2 solutions still utilizes lamdba expressions.  However, it also uses the new Func delegate.  A Func is a delegate type with several generic parameters defined.  There are 5 different Func delegates pre-defined for you with .NET 3.5.  Why are there 5 different ones?  This should cover you for most of your scenarios when designing methods/delegates, etc.  Usually if you are creating signatures of methods with more than 4 parameters, you probably need to refactor your parameters into an object.  '

For example, the Func that we need has to have 2 input parameters and a return parameter.  This one that is pre-defined in .NET will suit us great:

public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);

This solution has ONLY TWO parts:

  • Declare & instantiate the delegate (with the business logic defined inside the delegate "body")
  • Call the delegate and retrieve the result
Declare & instantiate the delegate (with the business logic defined inside the delegate "body") 

We already have a delegate (Func) with the required signature we need. It is a generic delegate; however, we can determine the types of parameters/result we need.  All we need to do is create a variable of this type and pass in the expression we created above (.NET 3.5 Type 1).  Our entire decleration/instatiation is in ONE line of code now:

Func<int, int, int> add = (firstNumber, secondNumber) => firstNumber + secondNumber;

Now that's nice concise syntax!.  All we did was declare a variable called add of type Func with 2 integer parameters and an integer return parameter (return type).  On the right-hand side of the equation we simply just use the lamdba expression from the example above.   

Call the delegate and retrieve the result

int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

Same as before.  Nothing new to see here.

Summary

This is as simple as you are going to get right now; a single line of code to declare/initialize a delegate with a lambda expression.

    1         Func<int, int, int> add = (firstNumber, secondNumber) => firstNumber + secondNumber;

    2 

    3         private void btnAdd_Click(object sender, EventArgs e)

    4         {

    5             // 2) Retrieve the result

    6             int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

This is as concise as you will get.  One line of code to rule them all :)

If you want to delve deeper, I would suggest picking up a C# 3 book.  I didn't really explain some of the origins of this code and some of the nuances with anonymous methods/lambda expressions or even delegates.  I just wanted to focus on the evolution of the C# syntax.  Attached is a simple VS 2008 solution zip that demonstrates the 4 different major -- there are lot more smaller permutations -- ways to write delegate syntax.  I broke the solution so that each type of code is in its own respective form (this way, every variable is named the same).  I also did not want to introduce any other C# constructs but wanted to strictly focus on the topic which was the syntax.

EvolutionOfDelegates.zip (55.06 kb)

Posted: Jul 14 2008, 17:09 by Bart Czernicki | Comments (0) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: .net
Tags:
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us