ASP.Net MVC 2 RTM Released

ASP.Net MVC 2 RTM has finally released and available on MSDN for download here

Brief on ASP.Net MVC 2 RTM

ASP.NET MVC 2 is a framework for developing highly testable and maintainable Web applications by leveraging the Model-View-Controller (MVC) pattern.

The framework encourages developers to maintain a clear separation of concerns among the responsibilities of the application – the UI logic using the view, user-input handling using the controller, and the domain logic using the model. ASP.NET MVC applications are easily testable using techniques such as test-driven development (TDD).

Comparison of ASP.Net MVC 2 RTM with ASP.Net MVC 1 RTM

ASP.Net MVC 2 RTM as compared to ASP.Net MVC 1 RTM has following additional features:

  • Support for Areas: Area feature in ASP.Net MVC 2 would allow complex application to be divided into modules.
  • Improved Security: JSONResult now supports only POST request by default.
  • Improved functionality:
    • Every property for model objects that use IDataErrorInfo to perform validation is validated, regardless of whether a new value was set
    • The UrlParmater.Optional property can be used to work around problems when binding to a model that contains an ID property when the property is absent in a form post
  • Templated Helpers: Feature from ASP.Net Dynamic Data Website in MVC for views.
  • New Validators
  • Support for binding binary data
  • Support for Asynchronous Controller Calls
  • and many more…….

I would be posting few more elaborate blog post on ASP.Net MVC 2 RTM in near future, keep watching…

Code For Keeps:- WPF/Silverlight Retrieve Images from DB/Url

WPF and Silverlight are all about images and styling and the one thing i end up doing a lot is extracting images from Databases, websites and showing them on a screen…and the code to do this is really hard to remember. So keep this code in your safe!!

1. Get Image from a byte[]: If your image is stored in the DB you will generally get it back as a binary. You can get the byte array by doing a ToArray() on the binay

public BitmapImage ImageFromBuffer(Byte[] bytes)
       {
           MemoryStream stream = new MemoryStream(bytes);
           BitmapImage image = new BitmapImage();
           image.SetSource(stream);
           stream.Close();
           return image;
       }

2. Get Image from a Url

public BitmapImage GetImageFromUrl(string imageUrl )

{

          const int BYTESTOREAD = 100000;

        WebRequest myRequest = WebRequest.Create(new Uri(imageUrl, UriKind.Absolute));
        myRequest.Timeout = -1;
        WebResponse myResponse = myRequest.GetResponse();
        Stream ReceiveStream = myResponse.GetResponseStream();
        BinaryReader br = new BinaryReader(ReceiveStream);
        MemoryStream memstream = new MemoryStream();
        byte[] bytebuffer = new byte[BYTESTOREAD];
        int BytesRead = br.Read(bytebuffer, 0, BYTESTOREAD);

        while (BytesRead > 0)
        {
            memstream.Write(bytebuffer, 0, BytesRead);
            BytesRead = br.Read(bytebuffer, 0, BYTESTOREAD);
        }
        BitmapImage image = new BitmapImage();
        image.BeginInit();
        memstream.Seek(0, SeekOrigin.Begin);

        image.StreamSource = memstream;
        image.EndInit();

        return image

     }

Hope if helps make your UI prettier!!!

Cennest!

Bulb Flash: WCF Size and Time restrictions!

While working on a Silverlight client and WCF service i hit a major roadblock when i realized that WCF has a lot of restrictions when it comes to communication. Restrictions in terms for time and  message size

The restriction is not only for size of a message but depth of message which is pretty relevant for Database entities being passed , number of elements in an array and even max length of the string incase you try DataContractSerialization

Use the following settings in your server side to overcome the time and message size restrictions to the max limit possible..

Use the following settings on your BasicHttpBinding

<basicHttpBinding>

‘For timing
<binding name=”BasicHttpBinding_XBOX” closeTimeout=”05:20:00″ openTimeout=”05:20:00″ receiveTimeout=”05:20:00″ sendTimeout=”05:20:00″

for message size

maxBufferSize=”2147483647″ maxBufferPoolSize=”2147483647″ maxReceivedMessageSize=”2147483647″ messageEncoding=”Text” textEncoding=”utf-8″ transferMode=”Buffered” useDefaultWebProxy=”true”>

<readerQuotas 
maxDepth=”2147483647″ maxStringContentLength=”2147483647″ maxArrayLength=”2147483647″
maxBytesPerRead=”2147483647″ maxNameTableCharCount=”2147483647″>

</readerQuotas>
         <security mode=”None”>
           <transport clientCredentialType=”None” proxyCredentialType=”None”
               realm=”” />
           <message clientCredentialType=”UserName” algorithmSuite=”Default” />
         </security>
       </binding>
     </basicHttpBinding>

Add the following behaviour in the service behaviour

<behavior name=”SampleServiceBehavior”>
<dataContractSerializer maxItemsInObjectGraph=”2147483646″/>

Similar settings are needed at the client app.config also.

Following snapshot shows the settings

image

If you are using Silverlight as your client then reader quotas etc are not available, but it the good news is that it reads the values from the server so it still works..

So all you need to do for Silverlight is(apart from the server side changes) make the following settings in the ServiceReferences.ClientConfig

image

Hope this marks the end of your messaging blues..Hope this bulb flash saved you some hours a grey cells!!

Cennest!!

Silverlight WCF Communication Issues!

Lets get the context straight first…i am a hardcore Microsoft person..infact i work ONLY on microsoft technologies.

But its a fact that the speed at which technology is being churned out its becoming difficult to learn how to make all different pieces work together

Although to be fair i think this article is a little late ,as the future prediction is that everyone will use Silverlight with WCF RIA services here on….but for those who may not do so(or maybe all such issues aren’t even resolved)..the next few bulb flashes will be me empathizing with those grapping with issues of making Silverlight work with WCF in a real production environment  and a few things i did to overcome them..

1. Message Size restriction

2. Debugging

3. Foreign key objects not propagated to client

4. Update Service reference issues

So read on and hope these upcoming flashes save you a couple of hours and grey cells!!

Cennest!!

Code for Keeps!: Deep Copy For Custom Objects

One of the major issues i had working with database entities/custom objects in Silverlight/WPF was that since “class” is a reference type any changes made to the object would stay in all its copies!!.

Lets take an example

I have a custom class called Person and i want to show in a listbox all those who are parents.

so basically i have this piece of code.

       List<Person> personList = new List<Person>();
       private void ShowInitialParentList()
       {
           listboxParent.Datacontext = (from p in parentList
                                        where p.IsParent
                                        select p).ToList();
       }

Now for some reason i have another listbox and i want to see what happens if all of them are parents(i don’t know why…just for this example:-))

so i do this

private void AssignSampleParents()
      {
          List <Person>templist= new List<Person>;
          foreach (Person original in personList)
          {
              templist.Add(original);
          }

          foreach (person p in templist)
          {
              p.IsParent = true;
          }
          listboxSample.Datacontext = (from p in tempList
                                       where p.IsParent
                                       select p).ToList();
      }

Now even though i copied the original list using the much cumbersome ADD method functionality(you can try direct assignment or AddRange or anything else you want!) what i get is that not only does the ListBoxSample show all the persons , even the original listbox gets updated..so basically making the copy was of no use!!

The only way to get out of this is to use the “Clone” method which is NOT available by default in custom/database entity objects.

Making a customized Clone method is a LOT of work for all the custom objects in your class….so the thing to do is…

Use the following Extension method!

using System.ComponentModel;
using System.Runtime.Serialization;
using System.IO;

public static class ExtensionMethods
   {
       public static T DeepCopy<T>(this T oSource)
       {

           T oClone;
           DataContractSerializer dcs = new DataContractSerializer(typeof(T));
           using (MemoryStream ms = new MemoryStream())
           {
               dcs.WriteObject(ms, oSource);
               ms.Position = 0;
               oClone = (T)dcs.ReadObject(ms);
           }
           return oClone;
       }
   }

Now if i did the following

        foreach (Person original in personList)
          {
              templist.Add(original.DeepCopy());
          }

everything would be perfect, because the object in the tempList has NO reference to the object in the original list!!

I found this piece of code a real keep!!..It will resolve a LOT of your “Who set this property issues”!

Do let me know if you “kept” this code for keeps!..

More such snippets coming up!

Cennest!!