The objective of this article is to demonstrate how to use duck typed (dynamic) view models with ASP.NET MVC, especially when you work with fluid data stores like XML. As we are using .NET dynamic features, you’ll need VS2010 beta or RC to work with the samples. Full source code is available, but I’ll recommend you to go through the article before you download.

[v] Download Twitter Search AspNetMvcDemoApp

The Application

Alright, to start with, have a look at the application screen shot below. It is a simple Twitter search app in ASP.NET MVC, that can show you the latest tweets about what you search for.

image

The Controller

Have a look at my controller. I just created an ASP.NET MVC 2 application in VS2010 and added references to Microsoft.CSharp.dll and AmazedSaint.Elastic project (included in the download above). AmazedSaint.Elastic namespace contains my ElasticObject implementation, I blogged about previously. Basically, ElasticObject can be used as a fluent dynamic wrapper to work with data formats like XML, and it is expected to evolve as smarter cousin of C# 4.0 ExpandoObject.

So, let us get back to the controller. VS already created the templates for me, and I modified the Index action in HomeController like this.

image

You might have noticed that I added a ‘query’ parameter to the Index action. Also, I’ve left out the event handler, so if your twitter connection is broken, the application will crash in your face :). We are parsing the atom format (it is xml) to an XElement, and then creating an ElasticObject out of that. If you are wondering what the heck is ToElastic() method, you should see this. Otherwise, if you can imagine, read on.

The View

The view is also pretty minimal. Two interesting points here. Firstly, we are inheriting the page from ViewPage<dynamic>, which means the viewData we returned from controller gets passed here as a dynamic object. And everything else is pretty simple, isn’t it? We are just iterating through all elements with the name ‘entry’ in the Model (see the result of twitter api call http://search.twitter.com/search.atom?lang=en&q=aspnetmvc), to print the image, author name, tweet text etc.

image

According to ElasticObject conventions, ‘_All’ after an element name will return all elements with that name as shown above. Also, adding a tilde ‘~’ character before an element will return the content of that element. You don’t need that if the accessed item is an attribute (see how we are accessing the href). Again, have compare the elements we used in our view with the twitter api returned atom data if you still need clarity.

Conclusion

Hey, we are done. Run the app, and you can search tweets and view results. As you’ve noticed, we don’t have a strongly typed view model – We used ElasticObject to wrap the xml and passed it to the View. Yes, you need to read about ElasticObject – The source code of the above app and the source code of ElasticObject with few unit tests are available in the related download (see the link above). Minimal, happy coding with ASP.NET MVC, XML data and Duck typed view models. Finally, it is your choice, don’t kick me for using C# dynamic features :).

Shout it
Read more >>

This is an intro post on the ‘ElasticObject’ class. First of all, let us see what exactly the ElasticObject implementation is capable off. After that we might touch the implementation details. To start with, here are few scenarios you can use ElasticObject

  • An easier, fluid way to work with data formats – like XML and JSON. Presently, we’ve some support for XML.
  • Cleaner code though it is duck typed
  • A hierarchical way to maintain loosely typed data.

Note: A Quick Clarification after reading few tweets - ElasticObject is not a class in .NET BCL, it is something that I’ve implemented, and you can get the code by clicking the above link :)

1 – You can create multi level Dynamic objects automatically, like this

ElasticObject supports creating hierarchical dynamic data structures. For example, consider this code.

image 

2 – Then, you can simply convert that to XML using the ‘>’ Conversion Operator

In ElasticObject implementation, several operators are having special meaning. For example, the ‘>’ operator can be used to convert an ElasticObject instance to another data format. Now, this is what you need to do to generate an XElement representation from the above ‘store’ object.

image

And this is what you’ll see if you check the generated XML.

image

3 – You can convert back and forth between XML and ElasticObject

In the above example, we’ve seen how to convert from a ‘dynamic’ ElasticObject to XML. Infact, you can convert XML directly to a ‘dynamic’ ElasticObject, using the XElement.ToElastic() extension method in DynamicExtensions class. See this unit test for getting a better idea.

image

4 – You can add multiple elements with same name, as child elements.

Assume you want to add multiple products. Consider the following code, especially see how we are adding multiple individual products to the Products collection.

image

And if you have a look at the XML representation, you’ll see

image 

Also, notice that you can assign some text content to a node using the <<= operator.

5 – You can use ‘<<’ or ElementAdder operator to add ‘Named’ elements

An ElasticObject has child elements and attributes. You can use the Left shift operator to add child elements to an object.  The ‘<<’ or Element Addition operation will return the newly added ElasticObject. And you can use the Indexer to get a list of child elements with that name – see how we are calling myobj[“Item”]. To get a list of all child elements, you can pass a null as the index parameter. eg: var allChildren=myobj[null];

image

6 – You can use ‘<’ or AttributeAdder operator to add ‘Named’ attributes

You can use the ‘<’ operator to add attributes to an ElasticObject. The ‘<’ or Attribute addition operation will return the newly added attribute ElasticObject.

Also, the <<= operator can be used to assign some value directly to an attribute variable.

image

7 - And Finally, A Quick Twitter Timeline Viewer

Let us create a quick Twitter console app, that loads my time line (oh, by the way, follow me @amazedsaint in twitter for sure) and prints it. Here we go.

image

What we do here is pretty simple. Grab the XML, convert that to an ElasticObject, and get the status elements under root to print out the user’s screen name and text.

If you are wondering what is that ‘tilde’ character (~) before screen_name and text – screen_name and text are elements in xml, and ‘~’ will fetch you the content of those elements. You don’t need that if screen_name and text were attributes rather than elements. Have a look at the screen_name and text elements in Twitter xml feed.

8 – Don’t forget to see the Unit Tests

Finally, Have a look at DynamicExtensionsTest – you’ll find couple of interesting Unit Tests there to help you understand the concepts further. The entire source code is attached that covers the above scenarios (that contains all the given examples), see the code download link above. In this post, I’m just discussing what ElasticObject can do, and I’m not really going to the actual implementation of ElasticObject. That is for another blog post.

Note: Already posted one, see A 10 Minute Twitter Search App in ASP.NET MVC and ElasticObject Dynamic View Models

9 – Violating C# Norms

ElasticObject violates few so called ‘standard’ statically typed C# norms. For example, These are few special meaning operators for ElasticObject, to note.

  • ‘>’ or Data Converter Operator – To convert a dynamic ElasticObject instance to another format. Presently XML is supported – See step 2 above
  • ‘<<’ Element Adder Operator – To add an ‘element’ or ‘child’ to an existing instance – See step 5 above
  • ‘<’ Attribute Adder Operator – To add an ‘attribute’ or ‘property’ to an existing instance – See step 6 above
  • ‘~’ Content Getter – To get the internal value of an element – See step 7 above.
  • ‘<<=’ Content Assigner – To set the internal value of an element – See step 4 above

Also, a dynamic instance of ElasticObject is not expected to handle any method calls. Any thing of the format obj.Something() will just add a new child named Something to obj – much like what the ‘<<’ operator does. You may or may not like it, bear with me. A better discussion point might be how these features are implemented :).

10 - Tail End

I hope ElasticObject may evolve as a ‘smarter cousin’ of .NET 4.0 ExpandoObject in the long run :). I blogged about ExpandoObject class few months back - and showed how to implement a minimal ExpandoObject like class. Read that if you are interested.

Also here is a list of few interesting blog posts, to understand the ‘dynamic’ keyword, and ExpandoObject if you want to refresh.

As with most other posts on C# 4.0 dynamic features, this post might break out another argument thread about whether we really need (or don’t need) dynamic features in C#. I think those kinds of arguments are pretty out dated, and dynamic features has its own benefits :).

Stay tuned, more is coming regarding the practical uses of this!! Keep in touch, subscribe to my blog. Btw, if you are a .NET guy, have you read my post on Top 5 Mistakes .NET developers must avoid?

Read more >>

Remember the “Three Screens and a Cloud” phrase coined by Ray Ozzie? To understand why it is such a brilliant vision, just take a step back and see what percentage of your time you end up spending with these three screens – your PC, your phone and the Television hanging in front of you. And suddenly, you’ll realize that all recent announcements from Microsoft – be it Azure, Live Services, Bing, Silverlight, Windows 7 or the brand new Windows Phone 7 Series – are just individual pieces of a larger puzzle, already envisioned by Microsoft.

image

In that sense, Windows Phone 7 device is not just an individual piece you are going to carry with you. The “Life in motion” term coined for describing the user experience in Windows Phone 7 says it all. And probably that is exactly why Steve Ballmer is almost sure that the software is what matters in a high volume phone market. From the TechCrunch interview with Steve, he mentioned,

Microsoft still thinks a software play is right for them in such a high volume market -- noting that, "when 1.3 billion phones a year are all smart, the software that's gonna be most popular in those phones is gonna be software that's sold by somebody who doesn't make their own phone."

A Development Platform For The ‘Three Screens’

Always, Microsoft’s strong hold is the development community they’ve built around them. And providing a familiar, unified platform for developing and running applications for these three screens is extremely critical for Microsoft. Silverlight to the rescue. This is easy for Microsoft as well – because Silverlight run time is a ‘mini implementation’ of the actual CLR, and hence it is easy to port the SLR to other devices.

Even in PCs, Silverlight has grown much after the first release. And some time back, I wrote about considering Silverlight as a platform of choice for developing applications across devices. Already, Silverlight is much more than a ‘cross platform implementation of .NET for the web’.  With Silverlight 4.0, the Out Of Browser features are getting better.

And after the Windows Phone 7 release, at this point of time, I don’t have any doubt that Silverlight is going to be ‘THE’ development platform for Windows Phone 7 as well. And just now, I’ve seen this report from Channel Web, confirming my thoughts.

At next month's MIX10 event in Las Vegas, Microsoft will officially name Silverlight as the platform for building native applications in Windows Phone 7 and future generations of Windows Phones, sources familiar with the matter told Channelweb.com late Monday.

I guess now we are talking business – in near future, Silverlight will emerge as the ‘platform of choice’ to develop and run applications, to provide a unified developer experience, across the three screens.

Talking about The Cloud Above

Of course, one key aspect of the entire story is, the state persistence and data sharing across these screens the user interact with. Enter the Azure. We’ve already seen the Azure, Cloud Services and Live Mesh in action - and we know the kind of investment Microsoft made in the same.

And I remember seeing a demo where you can pause a movie in Windows and resume it in a Mac, using a Silverlight player. But now, that experience is going beyond desktops and laptops – We are talking about seamless integration of these screens with the cloud, that will act as a hub to connect multiple devices and users.

Tighter integration between these three screens means more user acceptance, more possibilities for developers and more efficiency for the end users.

So, blind comparisons between the ‘phone’ operating systems - like Droid, IPhone and Windows Phone 7 Series - is just one part of the story. I think the real discussion point is - how much one screen can complement the other, how efficiently it can integrate, and how easily developers can develop and deploy applications that can run on + integrate each other - for these three screens.

Already, Microsoft needs to compete with established competitors in each of these markets, but I think Microsoft will gain a real competitive advantage when all these things click together.

Tail End

An interesting observation from @VinayakKamat – as he mentioned in Google Buzz.

Personally I don't think 3 screens and cloud is visionary - it was there all along. We could say infinite screens and cloud, now that is the future - I like Joe, the Windows Phone SVP who did the demo, you could see passion there, hope he capitalizes on it. He was on Ch9 too. If Silverlight on WP7 becomes a reality, this march, it would be a dream come true for .Net developers

I would really love to see the WP7 OS on variety of screens, iPad form factor, bedroom and living room walls (either via projection or energy efficient wall screens)

Alright, so “Clound and ‘n’ Screens” might be a better title. Please, share your thoughts. Keep in touch, follow me in Twitter @amazedsaint Or Subscribe the Feed

 

Updated – Feb 18, 2010:

Wow, I was not really aware about these leaked documents when I wrote the above post. Today, Mary Jo Foley tweeted about some leaked documents about Windows Phone 7. I had a look, and got pleasantly surprised to see this. Have a look at these Leaked documents in WM Power users forum, here is a screen shot of a relevant section, which talks about exactly the same thing I mentioned above - http://wmpoweruser.com/?p=13486

 

image

 

Also, are you a Silverlight guy? Check out my other posts on Silverlight.

Shout it
Read more >>

Top 5 Common programming mistakes .NET developers must avoid !!

image Some time back, I asked a question in Stackoverflow.com, about common programming mistakes .NET developers must avoid. The response was awesome, to say the least. I’m just listing down the top 5 developer crimes I picked, from the answers I received (regardless the votes).

1. Breaking the stack unnecessarily when you re-throw an exception

This a pretty ‘old thing’ - but surprisingly, still a very common mistake. As TheSoftwareJedi mentioned, you don’t really need to break the stack while throwing exceptions. I’ve done this myself when I was a beginner - and I’ve seen this more often than anything else when I do code reviews these days.

To clarify the point - What is the difference between

try { ..} catch (Exception ex) { throw ex; }

and 

try {..} catch(Exception ex) { throw; }  ?

image

And when you lose the stack trace, you can’t debug your app – and even worse, you can’t log your error details properly to your error log.

The MSDN guidelines on exception handling clearly states

Do not rethrow by throwing the same exception object.  This causes the stack trace for the original exception to be lost--use a lone "throw;" statement (without an object following it) to "rethrow" a catch exception.

2. Not using using to dispose objects

When ever you initialize an IDisposable object, it is a good practice to initiate it in a using statement to ensure the object is getting disposed properly, like this.

image

Most developers won’t do that. Greg Dean pointed the same.

image

Here is a little bit of re-cap from MSDN

As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and it also causes the object itself to go out of scope as soon as Dispose is called. Within the usingblock, the object is read-only and cannot be modified or reassigned.

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

Also, do you know that a using statement is expanded by the compiler to a try{..} finally{..} block at compile time? Read more tips about using statement in MSDN.

3. Not unhooking event handlers appropriately after wiring them.

I think Scott Langham brought up a great point about not unhooking event handlers. People don’t really ‘remember’ to unhook events.

image

In C#, when you register an event handler, you are creating a strong reference from the event source to the listener. So, the listener won’t get garbage collected even if you don’t have any pointers to the listener - unless you unhook the event by yourself, and this might even result in a memory leak.

So, if you are thinking about how to deal with situations where your  Source is having a longer life span than the listener – there are multiple ways to deal with it, and Daniel Grunwald covers them nicely in this excellent Codeproject Post.

4. Forgetting that Strings are immutable

In .NET, we know that strings are immutable – which means, once a string is created, its value can’t be changed. All string operations you perform, actually returns a new string containing the modification.

John Sonmez have a nice point with an example.

image

5. Not Overriding GetHashCode when overriding Equals method in C#

Why this is important? If Hashcode of two items does not match, they’ll be never considered equal, and the Equals method will never be called to execute your custom comparison logic – let us say, in scenarios where your objects are used as a key in a dictionary or so. Hence, in first place, you should override GetHashCode and return the same value for two equal objects based on comparison logic. I’ve seen this a couple of times during code review.

So, though Mark Gravell has several interesting points in his answer, my pick is about not overriding GetHashCode when you override Equals method in C#.

image

 

You may read my other Back To Basics posts here, you may find them interesting.

 

Note: As mentioned, these are my favorite picks of common problems, with some custom commentary. I suggest you to go through the entire thread here in Stack Overflow if you are interested. Happy coding!!

Shout it
Read more >>

What is LINQ to Events a.k.a RX Framework?

image I received a mail some time back, asking me to “clarify in simple words the concept of LINQ to Events”. This is a quick post on LINQ to Events a.k.a the RX Framework, and the objective of this post is to high light some of my previous posts on the same topic.

NET Rx team (this is not an official name) found that any push sequence (events, callbacks) can be viewed as a pull sequence (as we normally do while accessing enumerables) as well – or they are Dual in nature. In short observer/observable pattern is the dual of enumeration pattern.

So what is cool about about this duality?

Anything you do with Pull sequences (read declarative style coding) is applicable to push sequences as well. Here are few aspects. You can create Observables from existing events and then use them as first class citizens in .NET – i.e, you may create an observable from an event, and expose the same as a property.

As IObservable is the mathematical dual of IEnumerable, .NET Rx facilitates LINQ over push sequences like Events, much like LINQ over IEnumerables

It gives greater freedom to compose new events – you can create specific events out of general events.

.NET Rx introduces two interfaces, IObservable and IObserver that "provides an alternative to using input and output adapters as the producer and consumer of event sources and sinks" and this will soon become the de-facto for writing asynchronous code in a declarative manner. Here is a quick example.

image

You may go through my previous posts as well to get the head and tail in detail. Also have a look at the related source code as well.

Shout it
Read more >>

top