ObservableDeveloper - Leonid Sorokin's Blog

.NET, Silverlight, ASP.NET, Web Services, SQL Server, Cloud Computing, and much more...

About the author

I am a .NET Software Developer, Consultant, and Trainer from Toronto, Canada specializing in web development with Rich Internet Applications on the Microsoft development tool chain.

My Photo

Microsoft Certified Professional Developer

Persisting state during asynchronous calls

When using Silverlight you are pretty much forced to use asynchronous requests to web services. In most cases, this is not a problem, but sometimes you may need to be aware of the "context" of the response. In other words, in your callback event handler, you process the response from the server but you need that extra bit of information so you know what do to with the response.

Suppose you have a tree-view control. Every time a user selects a tree-view item you make an asynchronous web request, and when the response arrives you would like to pop-up a balloon over that selected tree-view item with the response (perhaps a detailed explanation of that tree-view item). Sounds simple right? Well, it is. Except that by the time the response has been received, the user may have already selected another tree-view item. Clearly, when the response is received, it is necessary to know who the response is for. In our case, the response event handler needs to receive the tree-view item reference, or better yet, the appropriate data-bound object if you are using data binding.

In Silverlight you can use the WebClient class or the more advanced HttpWebRequest class for making HTTP calls. Either way, when you make the call, you need to pass in an object reference, and when the response is received, that same object can be accessed.

For instance, WebClient has a method named DownloadStringAsync that is used to download non-stream data with two overloads. The difference between them is that one of them takes a userToken object. Here is the method signature:

public void DownloadStringAsync(Uri address, Object userToken)


You can access the user token in the response via the UserState property of the response object. The same mechanism exists for the HttpWebRequest class.

Now you should be able to successfully work with asynchronous requests in Silverlight and the .NET Framework.


Permalink | Comments (0) | Post RSSRSS comment feed

ASP.NET MVC 1.0 Highlights

I decided to write this post after reading the first chapter of an upcoming book on ASP.NET MVC entitled "Professional ASP.NET MVC 1.0" published by Wrox.

You can find an introductory post on ASP.NET MVC by Scott Guthrie @ http://weblogs.asp.net/scottgu/archive/2009/03/10/free-asp-net-mvc-ebook-tutorial.aspx. You will be pleased to realize that the first chapter is absolutely free and it is written by Scott Guthrie himself. It is quite a lengthy read (approximately 190 pages), but the content is excellent.

ASP.NET MVC is not only plumbing code - it is basically a guidance package that enables developers to build/test/maintain ASP.NET web applications in an architecturally sound way. MVC is an acronym for Model-View-Controller, which is a very famous design pattern. You can find more information about it @ http://en.wikipedia.org/wiki/Model-view-controller

Do not confuse the MVC design pattern with the M-V-VM (Model-View-ViewModel) design pattern which is a little different, and is mainly utilized in WPF client-side applications such as Silverlight.

ASP.NET MVC 1.0 is very RESTful and extremely "clean". Everything is done with good design/architecture in mind and separation of concerns is strictly enforced. Yes, you can customize it, but by default, even folder names and class names should follow the designated conventions in order to be used effectively.

While reading the chapter, I noticed a few new concepts that I did not know before. I have decided to list them here. I hope you find them useful. The quotes are from Scott Guthrie, and the explanations are mine.

  • "LINQ to SQL will automatically handle escaping SQL values for you when using strings - so you don't
    need to worry about SQL injection attacks when using it." Of course, all of us lose sleep over SQL injection attacks. What, you don't? Surprised
  • "Partial classes can be used to add methods/properties/events to classes maintained by a VS designer (like the Dinner class generated by the LINQ to SQL designer) and help avoid the tool from messing with our code." I am sure you already know about partial classes, but the next one is new to me...
  • "The OnValidate() partial method is a hook that LINQ to SQL provides that allows us to be notified
    anytime the Dinner object is about to be persisted within the database." Partial methods are especially useful as a way to customize generated code. You can read about partial classes and methods @ http://msdn.microsoft.com/en-us/library/wa80x488.aspx
  • "Why differentiate via HTTP verbs?" The two most used verbs with the HTTP protocol are HTTP GET and HTTP POST. When a crawler crawls your website (for indexing purposes) it follows links which are HTTP GET, and it should not make any HTTP POST requests to the site. First, you should make sure that no HTTP GET requests actually change server state - we have HTTP POST for that. As well, bookmarking a page and sending it to others to use will also use HTTP GET. Suppose you are editing your profile on a website. You have requested to edit your profile with the following URL (HTTP GET): http://site.com/UserProfile/Edit/[id]. After you are finished editing it, you will need to submit the form to the server. You can either submit the form using HTTP POST to the same URL, such as http://site.com/UserProfile/Edit/[id] or use a different URL such as http://site.com/UserProfile/Save/[id]. Which one is better? In either case you are performing an HTTP POST. However, if you use the http://site.com/UserProfile/Save/[id] URL for saving and a form validation error occurred with one of the form fields, the browser will re-display the form. Now, if the user decided at this point to bookmark the URL and send it to his friend, his friend will not be able to access that page, since he/she will be performing an HTTP GET on a URL that does not support HTTP GET requests. On the other hand if we used the same URL such as http://site.com/UserProfile/Edit/[id] for both HTTP GET and HTTP POST, upon a validation error the form will be redisplayed with same URL. The user can go ahead and bookmark it and even send to his friend. His friend should have no problem accessing the URL. The bottom line is: The user can bookmark a URL at any time, so make sure the URLs you use are always valid HTTP GET URLs. On a side note, Silverlight 3 promises to have excellent support for SEO (Search Engine Optimization), and the user should have no problem navigating Silverlight 3 content using the browser's back/forward buttons.
  • "The IQueryable<Dinner> object returned by our FindUpcomingDinners() method encapsulates a query
    to retrieve Dinner objects from our database using LINQ to SQL." Basically, IQueryable<T> encapsulates a LINQ query. This query is not executed until you call ToList() on it, or iterate on it using a foreach statement. Therefore, if a method returns an IQueryable<T> you can actually chain additional queries on top of it, and thus modify the query. With LINQ you can query relational data, XML data, and even POCOs (Plain Old CLR Object), with a unified query syntax. I recommend you get familiar with LINQ since it is very useful and may save you hours or even days on querying functionality you had to write yourself before.

As you can see ASP.NET MVC 1.0 is much more down-to-the-metal than the traditional ASP.NET framework. You are actually forced to think about raw HTTP GET/POST requests and how you handle them. This offers a lot of flexibility, but you must be careful not to abuse this added responsibility. The only thing Scott Guthrie fails to address in his first chapter is how we can use the myriad of existing ASP.NET server controls with ASP.NET MVC. However, I am sure this will be covered in subsequent chapters.

Enjoy the read!


Categories: ASP.NET
Permalink | Comments (0) | Post RSSRSS comment feed

How to pass arbitrary data in a Message object using WCF

I was searching all over the Internet, and yet I could not find any information about this seemingly simple task. Suppose you have an arbitrary string that you would like to return from a WCF (Windows Communication Foundation) service.

You can do one of the following on the service contract:

  1. Create a method/operation with a string return type
  2. Create a method/operation with a Stream return type in order to have full control over how serialization is performed. You can find a good explanation @ http://blogs.msdn.com/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-web.aspx 

However, you may find yourself in a situation where you cannot return a Stream type because you are sending the response somewhere deep inside the WCF stack and you only have the System.ServiceModel.Message type to work with. Here is the documentation of the Message class I am talking about - http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.message.aspx

Aside: If you have ever worked with RIA (Rich Internet Applications) such as Flash or Silverlight you will most likely be familiar with cross-domain policy files, such as crossdomain.xml (Flash) or clientaccesspolicy.xml (Silverlight). I am not going to go into why they are needed, but needless to say, I had to return one of these files depending on the request made from the client. Both of these files contain perfectly valid XML.

If you look carefully at the Message.CreateMessage method you will see it has many overloads. At first, I tried this:

Message reply = Message.CreateMessage(MessageVersion.None, "", XmlReader.Create(new MemoryStream(Encoding.UTF8.GetBytes("[XML goes here]"))));

This works fine as long as the XML you are passing to XmlReader does not contain DTD definitions. For some security reason having a DTD in the XML causes an exception on the XmlReader.Create call. I was able to avoid an exception by setting the ProhibitDtd property on XmlReaderSettings to false, but WCF decided I was performing evil deeds, and independently decided to emit my XML without the DTD definition.

If you look at the overloads of Message.CreateMessage you will quickly realize that you must serialize as XML. In my case, the DTD in the crossdomain.xml caused the headache, but what if you want to pass an arbitrary string such as "Hello World" back from the service as-is, what do you do then? Anything you may try will cause the default DataContractSerializer to kick in and serialize your object. The catch is, you do not actually want serialization.

Here is the code that you need in order to return arbitrary text using WCF's Message class.

/// <summary>
/// Necessary to write out the contents as text (used with the Raw return type)
/// </summary>
public class TextBodyWriter : BodyWriter
{
        byte[] messageBytes;

        public TextBodyWriter(string message)
            : base(true)
        {
            this.messageBytes = Encoding.UTF8.GetBytes(message);
        }

        protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
        {
            writer.WriteStartElement("Binary");
            writer.WriteBase64(this.messageBytes, 0, this.messageBytes.Length);
            writer.WriteEndElement();
        }
}

// ....

// Here is sample code that does the magic of returning raw text to the client...
string response = "Hello World!";
Message reply = Message.CreateMessage(MessageVersion.None, null, new TextBodyWriter(response));
reply.Properties[WebBodyFormatMessageProperty.Name] = new WebBodyFormatMessageProperty(WebContentFormat.Raw); // very important - forces WCF to serialize the message body contents as "Raw" which effectively means no serialization
WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain"; // can also be "application/xml" or anything you prefer


Permalink | Comments (0) | Post RSSRSS comment feed

Expression Blend 2 SP1 does not support async HTTP web requests

Expression Blend is very useful. However, it would be even more useful if a designer was able to see data in the controls which he/she is using. That way, changing the font of a grid will show the changes right away. The key is to have dummy data in the grid so that the designers' changes are reflected in real-time. This would result in a much better experience for the UI/UX designer working in Blend.

However, by default, there is no data in controls used in Blend, and the designer has to live with that.

In order to achieve this "dummy data" behavior, I am currently including Mock data as part of the XAP file that users will eventually receive. This is not so good since users will have to wait for a larger Silverlight XAP file to be downloaded. You can find an application I wrote that uses this technique @ http://www.leonidsorokin.com/blog/post/Architecting-Designing-Silverlight-2-Applications.aspx

In order to avoid having to include potentially large dummy data in the XAP file I wanted to download it dynamically during runtime. In the browser, there is no problem, but the same code in Blend results in the error: WebException: BrowserHttpWebRequest_WebException_RemoteServer.

Here is a thread I posted on this issue in the Expression Blend Forum: http://social.expression.microsoft.com/Forums/en-US/blend/thread/fe5b251f-e54e-4d6a-b442-5cf45fa00e86

By the way, you can debug a Silverlight application running under Expression Blend by simply attaching to the Blend.exe process while your application solution is open in Visual Studio 2008, and setting breakpoints.


Permalink | Comments (0) | Post RSSRSS comment feed

To throw or not to throw Exceptions - that is the question

Today I had to make a decision whether I should be throwing an exception or not.

In my data access layer I had to have a SaveUser method that saves a user object by calling a corresponding SaveUser method on a REST web service.  The question arose regarding the return value of the method in my data access layer. Logically the return value should be a boolean, either the SaveUser operation succeeded or not.

Here is one possible method signature:

bool SaveUser(User user); // not such a good approach

However, this is not a good solution. Why? The return value should always be true, and false only in exceptional circumstances. 

In general, when saving data, it is much better to return nothing, and let exceptional situations be handled by the best candidate - exceptions.

Therefore, the SaveUser method should have the following signature:

void SaveUser(User user); // much better approach

If the web service returns an error, the data access layer should raise an exception and set the InnerException propety to the exception text returned by the web service. 

This is a much cleaner solution than returning true/false from the SaveUser method.


Categories: C# | .NET
Permalink | Comments (0) | Post RSSRSS comment feed

Architecting & Designing Silverlight 2 Applications

Many people write code that is not re-usable, testable, and basically, totally unmaintainable.

Let's face reality - writing "good code" is not trivial, and software developers often find themselves in a position where time is limited and they have to deliver a piece of software.

The question is not only "will they deliver the software on time", but perhaps "what will they end-up delivering"?

Over the past month of research and development, I have read numerous blog posts, MSDN articles, white papers, and conducted my own development to try to answer one question: what are the best patterns & practices known today in order to build maintainable line-of-business Silverlight 2 applications?

I have written a sample Silverlight application called "SilverList" that uses most of the results of my extensive research.

Here are the key Silverlight design concepts:

  • M-V-VM (Model-View-ViewModel) design pattern + Silverlight Commanding in order to allow a more seamless developer/designer relationship. You can read Shawn Wildermuth's article on the subject @ http://msdn.microsoft.com/en-us/magazine/dd458800.aspx
  • Unit Testing (because if you don't write unit tests - you should start, trust me, it provides many benefits). You can find it @ http://code.msdn.microsoft.com/silverlightut
  • Dependency Injection (forget about hardwiring dependencies and start injecting them using Ninject - the ninja of dependency injection!) Ninject can be found @ http://ninject.org/
  • Isolated Storage (think "Google Gears"  - cache, cache, cache!) Why make a round-trip to the server if you don't really need to?
  • Blendability (your UI/UX designer is complaining that when he/she is working in Expression Blend, all the ListBoxes appear empty with no data, same with all the DataGrids and TextBoxes. Well, with M-V-VM and IoC (Inversion of Control), you can inject dummy data so that when your beloved designer wants to change the font, color, or the style of a control, the dummy data is there to reflect the change in real-time! There isn't a need to run the application in the browser just so see the effect of a simple change - very useful for RAD (Rapid Application Development) scenarios.
  • LINQ (Language Integrated Query). Why implement IComparable/IComparer on your custom objects when you can simply write a couple of lines of LINQ code to search/sort a list of data by a given property?

Here is what the the application actually does:

  • Add name-value pairs to the list in the format: name=value (e.g. Hello = World). The name can be comprised of any alpha-numeric characters, following by an equal sign, followed by another set of alpha-numeric characters
  • Delete a name-value pair from the list
  • Sort the list in ascending order either by name or by value
  • Filter the list by either Name or Value. For filtering, the name portion has to be "Name" or "Value". For example, to display all entries in the list with the name Hello, type in "Name = Hello" (no quotes). To filter by value, type in "Value = World" (no quotes).
  • Clear the filter to return to the main list
  • When adding/sorting/deleting name-value pairs, SilverList automatically saves the current data into IsolatedStorage. So if you close the browser and visit the page again, you will see your latest data in the ListBox right away. Filtering, however, is a temporary operation, and does not cause the list data to be saved into IsolatedStorage

As you can see, the application is simple, yet is mainly used to show good design patterns and practices.

Here is a link to the SilverList Unit Testing page: SilverList Unit Tests . Be patient while the XAP is downloaded and the Unit Testing Framework is initialized. You will be able to see how the Silverlight Unit Testing framework executes my unit tests for SilverList live in your brower. Let's hope all the tests pass! Embarassed

This was an introductory post and I will write about this application and plan on dissecting it in more detail in future posts. For now, however, you can grab all the code, and play with it live below.

Here is a link to all the code:

Here is the application live (you need to have the Silverlight plugin installed to use it):

[silverlight:source=/blog/ClientBin/SilverList.xap;width=500;height=600]


Permalink | Comments (0) | Post RSSRSS comment feed