DefaultModelBinder class in System.Web.Mvc

While working with validation for an  MVC application I came across option for using  DefaultModelBinder class.

public class DefaultModelBinder : IModelBinder

maps following types in response to a request.
primitive types, model classes and collections

What it does is, it takes the required object from the model, binds its properties to the corresponding HTML fields of the form (View).

If the class it is binding implements IDataErrorInfo interface, which binds the developer to implement following properties

Error:  string Error { get; }

Item :  string this[string columnName] { get; }

If a class implements the interface, it ftches the value for the fields, by invoking IDataErrorInfo.this indexer.

What you can do interesting is you can perform your validation / checks and over an object in focus and  if in case it fails to correspond with the requirements, like a customer has provided wrong value for the name of something, It will return the error value , custom provided  at the time of implementation of the interface. Have a look.

Here are details for DefaultModelBinder

Advertisements

How to Generate an AtomFeed using Argotic Framework. Part 4

Argotic Framework provides several classes which are great for the manipulation of a feed resource. AtomFeed class could helps us retrive all the required bits about particular Atom based feed resource and latest content it holds. On the other hand we can use the same class to generate a feed for our on line resources as well. Below is sample program which demonstrates an AtomFeed Object in action.

// create a new AtomFeed Object
                AtomFeed feed = new AtomFeed();

                // Set the title for the feed
                feed.Title = new AtomTextConstruct("codingphobia.com articles");

                // set the language you Feed is published in
                feed.Language = new System.Globalization.CultureInfo("en-gb");

                // set the description for the Feed / Feed resource
                feed.Subtitle = new AtomTextConstruct("Latest Content from codingphobia.com");

                // Set the categories under the Feed / content is published
                feed.Categories.Add(new AtomCategory("AtomFeed"));
                feed.Categories.Add(new AtomCategory("cSharp"));
                feed.Categories.Add(new AtomCategory("SyndicationFeed"));

                // Set the information about the feed Generator Engine
                feed.Generator = new AtomGenerator("WordPress3.0");

                // Add the List of Post / Articles / content links 
                // and information to the Feed Object

                // Adding  Article 1
                AtomEntry atomEntry = new AtomEntry();
                atomEntry.BaseUri = new Uri("http://codingphobia.com/category/c/page/2/");
                atomEntry.Categories.Add(new AtomCategory("Fameworks"));
                atomEntry.Title = 
                    new AtomTextConstruct("Really simple syndication -RSS with .Net. Intro");
                atomEntry.Content = new AtomContent("Some content", UTF32Encoding.Unicode.BodyName);
                atomEntry.PublishedOn = DateTime.Now;
                feed.AddEntry(atomEntry);

                // Adding  Article 2
                atomEntry.BaseUri = new Uri("http://codingphobia.com/category/c/page/1/");
                atomEntry.Categories.Add(new AtomCategory("FeedTypes"));
                atomEntry.Title = new AtomTextConstruct("RSS with .Net. Part1");
                atomEntry.Content = new AtomContent("Some more content", UTF32Encoding.Unicode.BodyName);
                atomEntry.PublishedOn = DateTime.Now;
                feed.AddEntry(atomEntry);

                // Set the url for the Icon for your Feed
                // Displayed on the side of the feed page
                feed.Icon = new AtomIcon(new Uri("http://codingphobia.com/officialImage"));

                // Set the url for the logo for your Feed
                // Displayed on the side of the feed page
                feed.Logo = new AtomLogo(new Uri("http://codingphobia.com/officialLogo"));

                // Set the right for feed consumption 
                feed.Rights = new AtomTextConstruct("CC");     

How to Generate an Rss Feed using System.ServiceModel.Syndication Framework. Part 3

Syndication-Feed provides all the properties we will need to generate a feed for our web site. This article assumes that you have a Data Access layer, which could provide the objects / content and other information needed to publish a feed. I will be using sample variables and objects, which you can replace with originals content / objects

           // Create a raw SyndicationFeed object
            SyndicationFeed feed = new SyndicationFeed();

            // Set the title for the Feed
            feed.Title = new TextSyndicationContent("codingphobia.com articles");

            // set the language you Feed is published in
            feed.Language = "en-gb";

            // set the description for the Feed / Feed resource
            feed.Description = new TextSyndicationContent("Latest Content from codingphobia.com");

            // set the rights information that apply over 
            // the consumption / distribution of the  
            // Feed / content
            feed.Copyright = new TextSyndicationContent("CC");

            // Set the categories under the Feed / content is published
            feed.Categories.Add(new SyndicationCategory("RssFeed"));
            feed.Categories.Add(new SyndicationCategory("cSharp"));
            feed.Categories.Add(new SyndicationCategory("SyndicationFeed"));

            // Set the information about the feed Generator Engine
            feed.Generator = "WordPress3.0";

            // Add the List of Post / Articles / content links 
            // and information to the Feed Object
            List<SyndicationItem> feedItems = new List<SyndicationItem>();

           
            SyndicationItem feedItem1 =
                new SyndicationItem(
                    "Really simple syndication -RSS with .Net. (Intro)",
                    "Rss Feed Fameworks",
                    new Uri("http://codingphobia.com/category/c/page/2/"));
            feedItems.Add(feedItem1);

            SyndicationItem feedItem2 =
                new SyndicationItem(
                    "How to consume an Rss feed using System."+
                    "ServiceModel.Syndication Framework. (Part 1)",
                    "Consume Rss Feed",
                    new Uri("http://codingphobia.com/2009/07/06/how-to-consume-an"+
                    "-rss-feed-using-system-servicemodel-syndication-framework-part-2/"));
            feedItems.Add(feedItem2);

            SyndicationItem feedItem3 =
                new SyndicationItem(
                    "How to consume an Atom feed using Argotic Framework. (Part 2)",
                    "Consume Atom Feed",
                    new Uri("http://codingphobia.com/2009/07/09/how-to-consume-an-atom"+
                    "-feed-using-argotic-framework-part-2/"));
            feedItems.Add(feedItem3);

            // Set the url forthe image / logo for your Feed
            // Displayed on the side of the feed page
            feed.ImageUrl = new Uri("http://codingphobia.com/imageUrl");

How to consume an Atom feed using Argotic Framework. (Part 2)

Argotic Framework provides several classes which are great for the manipulation of a feed resource. AtomFeed class could helps us retrive all the required bits about particular Atom based feed resource and latest content it holds, once the feed is loaded. Below is sample program which demonstrates a AtomFeed Object in action.

            /// Loads the feed.           
            /// <param name="urlToLoad">The URL to load.</param>
            AtomFeed feed = AtomFeed.Create(new Uri(urlToLoad));

            // get the url for Feed(same as used for load).  
            string feedUrl;
            if (feed.BaseUri != null)
            {
                feedUrl = feed.BaseUri.AbsolutePath;
            }

            // get the Title for the feed
            string feedTitle;
            if (feed.Title != null)
            {
                feedTitle = feed.Title.Content;
            }

            // get the description for the feed
            string feedDescription;
            if (feed.Subtitle != null && !feed.Subtitle.Equals(""))
            {
                feedDescription = feed.Subtitle.Content;
            }

            // get the icon for the source of the feed
            string feedIconUrl;
            if (feed.Icon != null)
            {
                feedIconUrl = feed.Icon.Uri.AbsoluteUri;
            }

            // get the format isn which feed id published
            string feedFormat;
            if (!feed.Format.Equals(""))
            {
                feedFormat = feed.Format.ToString();
            }

            // get the logog used by the publisher
            string feedLogo;
            if (feed.Logo != null)
            {
                feedLogo = feed.Logo.Uri.AbsoluteUri;
            }

            // get the rights as announced by the publisher of the feed
            string feedRights;
            if (feed.Rights != null)
            {
                feedRights = feed.Rights.Content;
            }

            // get the version of the Feed like 1.0 / 2.0 / 3.0 
            string FeedVersion;
            if (feed.Version != null)
            {
                FeedVersion = feed.Version.ToString();
            }

            // get the categories under which feed was published
            Collection<AtomCategory> categoryList;
            if (feed.Categories.Count > 0)
            {
                categoryList = feed.Categories; ;
            }

            // get the list of entries(posts / articles / whatever) from
            // this source
            if (feed.Entries != null)
            {
                List<AtomEntry> entries = feed.Entries.ToList<AtomEntry>();
            }

How to consume an Rss feed using System.ServiceModel.Syndication Framework. (Part 1)

System.ServiceModel.Syndication provides several classes which are great for the manipulation of a feed resource. Using SyndicationFeed class

could helps us retrive all the required bits about particular feed resource and latest content, once the feed is loaded.

Below is sample program which demonstrates a syndicationFeed Object in action.

using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Xml;

namespace SyndicationFeedManager
{
    public class RssFeedManager
    {
        public void ParseRssFeed()
        {
            // Url To load Feed From
            string urlToLoadFeed = "";

            // Load Feed, Load Method requires and object of Xmlreader object
            SyndicationFeed feed = SyndicationFeed.Load(XmlReader.Create(urlToLoadFeed));           

            // get Title of Feed
            string feedTitle;
            if (feed.Title != null)
            {
                feedTitle = feed.Title.Text;
            }

            // get Short description of the feed
            string feedDescription;
            if (feed.Description != null)
            {
                feedDescription = feed.Description.Text;
            }

            // get the Icon url of the feed
            string feedIconUrl;
            if (feed.ImageUrl != null)
            {
                feedIconUrl = feed.ImageUrl.AbsoluteUri;
            }

            // get Image Url of the feed,  A snapshot
            string feedImageUrl;
            if (feed.ImageUrl != null)
            {
                feedImageUrl = feed.ImageUrl.AbsoluteUri;
            }

            // get copy right info of feed
            string feedCopyRights;
            if (feed.Copyright != null &amp; !feed.Copyright.Text.Equals(""))
            {
                feedCopyRights = feed.Copyright.Text;
            }

            // get the categoried under whic feed is filed
            List feedCategories = new List();
            if (feed.Categories != null)
            {
                foreach (SyndicationCategory category in feed.Categories.ToList())
                {
                    if (category.Name != null)
                    {
                        feedCategories.Add(category.Name);
                    }
                }
            }

            // get the language feed has been published in
            string feedLanguage;
            if (feed.Language != null &amp;&amp; feed.Language.Length &gt; 1)
            {
                feedLanguage = feed.Language;
            }
        }
    }
}

Really simple syndication -RSS with .Net. (Intro)

In this series of articles we will go through the process of creating and consuming an RSS Feed using the API built into Microsoft .Net Faramework and another papular framework available in the market known as Argotic.

In the preceeding articles after intro, we will go through in detail about:

We will be using Visual C#.Net as our programming language and the available API’s accordingly

First things first:

what is Rss and what does it stand for  ??  Really simple syndication. a more better way to explain is:

It the list of hyper-links of  an on-line resource, ordered in particular manner with the minimum bits of information required to get to that resource.

Most of the modern browser fully suport this feature and come with pre installed Rss parsers.(Chrome being more focused on its performance is currently not supporting this feature but there are some third party option available like Feed Viwer . Another easy is to use Google Reader )

What exactly is Rss ?

Rss is an xml file, generated in one of the standard formats, designed for the purpose. These formats differ slightly and and can hold information depending upn the content they represent. Following are the Rss Format with most commonly in use.

RSS

  • RSS 0.90 (the original Netscape RSS version)
  • RSS 1.0
  • RSS 1.1
  • RSS 2.0

Atom

OPML

BlogML

Rss and Atom being mostly used, we will be working on how to generate and consume feed in these formats.

Frameworks

Microsoft .Net framework has a built in rich library to work with most of the formats named as  System.ServiceModel.Syndication with its most useful class SyndicationFeed.

There is another third party framework known as Argotic , which also provides several classes shich make it very helpful to work woth RSS content

Another third Party framework known as Rss.Net is also papular and is used in the development of  a lot  of Feed related Web Applications.

No particular framework is more papular than other. The difference noticeable is, System.ServiceModel.Syndication has been tested and proved to be 9 times faster than Argotic Framework and is recommended by many developers for that reason. On the other hand Argotic comes with wide set of  rich classes, which provide not only handling implementation of a feed service in commonly used formats very easy but also for less common but important formats, like BlogML.

So it is the choice between the efficiency of your application vs efficiency in development. In the end choice is always yours.

A Quick review of Serialization and DeSeralization events

A Quick review of Serialization and DeSeralization events

.Net provides the facility to intercept Serialization / DeSeralization by providing following events.

Serialization:
OnSerializing
OnSerialized
DeSeralization
OnDesrializing
IDeserialazationCallback

Courtesy: MCTS 70-536 Self Paced Training Kit by Microsoft

Following is the program with implementation of [OnDesrialized] event which checks if the total of the item(s) of a certain category is less than 20, it applies appropriate discount.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Xml.Serialization;</code>

<code>namespace CustomSerializationSample
{
[Serializable]
public class ShoppingCartItem : ISerializable
{
public int productID;
public decimal price;
public int quantity;
[XmlIgnore]
public decimal total;</code>

<code>public ShoppingCartItem(int _productID, decimal _price, int _quantity)
{
productID = _productID;
price = _price;
quantity = _quantity;
total = price * quantity;
}
public ShoppingCartItem()
{
}
[OnDeserialized]
void CalculateTotal(StreamingContext sc)
{
decimal discount;
if (total &lt; 20)
{
discount = (total / 100) * 12;
total = total - discount;
}
}
public override string ToString()
{
return "ProductID: " + this.productID + " : Price " + this.price.ToString() +
", Quantity: " + quantity + ", Disc: " + total;
}

#region ISerializable Members

public ShoppingCartItem(SerializationInfo info,
StreamingContext context)
{

productID = info.GetInt32("Product ID");
price = info.GetInt32("Price");
quantity = info.GetInt32("Quantity");
total = price * quantity;
}
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{

info.AddValue("Product ID", productID);
info.AddValue("Price", price);
info.AddValue("Quantity", quantity);
}
#endregion
}
}