Tuesday, 28 April 2015

DataContractSerializer vs XmlSerializer in WCF

DataContractSerializer
  • Is meant to be used for serialization/deserialization of class in WCF service to and from either JSON or XML.
  • serializes properties and fields.
  • Is faster than XmlSerializer
  • Doesn't control how xml is generated. Should not be used when full control on generated XML structure is required
XMLSerializer
  • XmlSerializer is only for XML serialization
  • Supports full control over the XML structure
  • Serializes only public properties
Continue Reading →

Custom HTML Helpers in ASP.NET MVC

How many times did you wonder how to avoid writing the same chunk of HTML / JavaScript code many times in an MVC Razor view? What if this repetitive task includes some logic?
The solution to avoid this is to build a custom HTML helper to encapsulate everything and make the repetitive task less cumbersome.
Let's say we want to avoid doing this many times inside your views:

  <img src="@myModel.MyObject.ImageSource", alt ="@myModel.MyObject.Imagename",
title ="@myModel.MyObject.ImageDescription" />

And instead, you want something Razor like that may take care of some logic or validations to avoid error because in the previous snippet, the ImageSource or Imagename or again the description may be null:

@Html.Image(@myModel.MyObject.ImageSource, @myModel.MyObject.Imagename,                  @myModel.MyObject.ImageDescription) 

namespace MyNamespace
 { 
    public static class MyHeleprs
    {
        public static MvcHtmlString Image(this HtmlHelper htmlHelper,
              string source, string alternativeText)
        {
            //declare the html helper
            var builder = new TagBuilder("image");
            //hook the properties and add any required logic
            builder.MergeAttribute("src", source);
            builder.MergeAttribute("alt", alternativeText);
            //create the helper with a self closing capability
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        }
    }
}

To make this helper available in your view, add its namespace as follows:

@namespace MyNamespace 

But if you want it available in all your views, you have to add the namespace not to a specific view but to the collection of namespaces in views' web.config:

<add namespace="MyNamespace" />

Now, the Image helper is available everywhere in your views.

Continue Reading →

WCF Service – KnownType DataContract

Data Contract describes the type of data that will be sent or received between a service and a client. But in certain scenarios, sent or received data is not known between the the communicating parties. For example, a service sending data back to client is not the actual data contract but a derived type of it. In such cases, there will be a De-serialization problem. De-serialization engine will not recognize the derived Data Contract type and will generate an error.
In order to handle such scenarios, Data Contract Known types are available in Windows Communication Foundation. So by definition, “Known Type in WCF is an acceptable derived type for a Data Contract“.In one of the article WCF Service articles, blogger explained WCF KnowTypeAttribute with the help of a simple example. But here in this WCF Tutorial, I’ll try to discuss all possible ways to use Data Contract Known Types, so that the reader can get a detailed understanding about Known Types and be able to use it in various practical scenarios.

Consider the following Data Contract classes having inheritance relationship as follows:


    [DataContract]
    public class UserAccount { }

    [DataContract]
    public class Admin : UserAccount { }

    [DataContract]

    public class Guest : UserAccount { }

Now, look into following code:

    [DataContract]
    [ServiceKnownType(typeof(Admin))]
    [ServiceKnownType(typeof(Guest))]
    public class SecurityInfo
    {
        [DataMember]
        private UserAccount user;
    }

Above code will work fine, either we set SecurityInfo data member to Admin or Guest.
But if KnownTypeAttribute for Admin and Guest are not provided, deserialization engine will not recognize Admin and Guest types and will cry.
For more detailed understanding with example of all possible ways of associating Known Types in WCF, Click Here.
Continue Reading →

Monday, 20 April 2015

Hashtable and Dictionary

Hashtable and Dictionary are collection of data structures to hold data as key-value pairs.The Hashtable is a weakly typed data structure, so you can add keys and values of any Object Type to the Hashtable. The Dictionary class is a strongly types <T Key, T Value > and you must specify the data types for both the key and value.

Coming to difference between HashTable & Dictionary,Dictionary is generic whereas Hastable is not Generic.We can add any type of object to HashTable ,but while reteriving we need to Cast it to the required Type.So it is not type safe.But to dictionary,while declaring itself we can specify the type of Key & Value ,so no need to cast while retreiving.

Let me explain it with an Example. 

HashTable Program: 
    public class HashTableProgram
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();
            ht.Add(1, "One");
            ht.Add(2, "Two");
            ht.Add(3, "Three");
            foreach (DictionaryEntry de in ht)
            {
                int Key = (int)de.Key; //Casting
                string value = de.Value.ToString(); //Casting
                Console.WriteLine(Key + " " + value);
            }
        }

    }


Dictionary Example :
    class DictionaryProgram
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> dt = new Dictionary<int, string>();
            dt.Add(1, "One");
            dt.Add(2, "Two");
            dt.Add(3, "Three");
            foreach (KeyValuePair<int, String> kv in dt)
            {
                Console.WriteLine(kv.Key + " " + kv.Value);
            }
        }
    }



Dictionary
Trying to access an in existent key gives runtime error in Dictionary.
Dictionary is a generic type
Generic collections are a lot faster as there's no boxing/unboxing
Dictionary public static members are thread safe, but any instance members are not guaranteed to be thread safe.
Dictionary is preferred than Hash table

Hash table
Trying to access an in existent key gives null instead of error.
Hash table is a non-generic type
Hash table also have to box/unbox, which may have memory consumption as well as performance penalties.
Hash table is thread safe for use by multiple reader threads and a single writing thread
This is an older collection that is obsoleted by the Dictionary collection. Knowing how to use it is critical when maintaining older programs.

Continue Reading →

Wednesday, 15 April 2015

Difference between bind(), live(), on(), delegate() in Jquery

.bind()

Syntax: .bind( eventType [, eventData ], handler )
Attach a handler to an event for the elements.
The .bind() method registers the type of event and an event handler directly to the DOM element. The .bind() doesn't work for elements added dynamically that matches the same selector. 

<script>
    $("#foo").bind("mouseenter mouseleave", function () {
        $(this).toggleClass("entered");
    });

    $("#foo2").bind({
        click: function () {
            // Do something on click
        },
        mouseenter: function () {
            // Do something on mouseenter
        }
    });
    $("#foo").bind("click", function () {
        alert($(this).text());
    });

</script>

.live()

Attach an event handler for all elements which match the current selector, now and in the future.
Syntax: .live( events, handler )

Examples:

Example: Cancel a default action and prevent it from bubbling up by returning false.

1
2
3
$( "a" ).live( "click", function() {
  return false;
});

Example: Cancel only the default action by using the preventDefault method.

1
2
3
$( "a" ).live( "click", function( event ) {
  event.preventDefault();
});

Example: Use an object to bind multiple live event handlers. Note that .live() calls the click, mouseover, and mouseout event handlers for all paragraphs--even new ones.

1
2
3
4
$( "p" ).live({
  click: function() {
    $( this ).after( "<p>Another paragraph!</p>" );
  },
  mouseover: function() {
    $( this ).addClass( "over" );
  },
  mouseout: function() {
    $( this ).removeClass( "over" );
  }
});
In short: .bind() will only apply to the items you currently have selected in your jQuery object. .live() will apply to all current matching elements, as well as any you might add in the future.

.on()

Attach an event handler function for one or more events to the selected elements.
Syntax: .on( events [, selector ] [, data ], handler )

Example: Display each paragraph's text in an alert box whenever it is clicked:

1
2
3
$( "body" ).on( "click", "p", function() {
  alert( $( this ).text() );
});

Example: Cancel a link's default action using the .preventDefault() method.

1
2
3
$( "body" ).on( "click", "a", function( event ) {
  event.preventDefault();
});

.delegate()
Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
Syntax: .delegate( selector, eventType, handler )


For example, the following
 .delegate() code:
1
2
3
$( "table" ).delegate( "td", "click", function() {
  $( this ).toggleClass( "chosen" );
});
is equivalent to the following code written using .on():
1
2
3
$( "table" ).on( "click", "td", function() {
  $( this ).toggleClass( "chosen" );
});


The .delegate() method is very powerful, The difference between .live() and .delegate() is, live function can't be used in chaining. live function needs to be used directly on a selector/element. Also .delegate() works on dynamically added elements to the DOM where the selectors match. Chaining is supported correctly in .delegate().
Continue Reading →

Tuesday, 14 April 2015

Abstract Vs. Static

Can you create abstract function as Static?
A static member cannot be marked as override, virtual, or abstract.

Can you create static function in Abstract class?
Yes.

Example: 
namespace ConsoleApplication2
{
    public abstract class ps
    {
        public ps()
        {
        }
        public ps(string a)
        {

        }
        public abstract string getMessage();
        public static void Helloworld() { Console.WriteLine("hello"); }

         //A static member cannot be marked as override, virtual, or abstract
        //public static abstract void Helloworld() { Console.WriteLine("hello"); }
        //public static abstract string GetName();

    }

    public class Program :ps
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine(p.getMessage());
            Helloworld();
            Console.Read();
        }

        public override string getMessage()
        {
            return "message hello.";
        }
    }

}


Continue Reading →

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)