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

C# Collections that Every Developer Must Know

C# Collections that Every C# Developer Must Know
  1. List
  2. Dictionary
  3. HashSet
  4. Stack
  5. Queue
List<T>
Represents a list of objects that can be accessed by an index. <T> here means this is a generic list. 

Unlike arrays that are fixed in size, lists can grow in size dynamically. That’s why they’re also called dynamic arrays or vectors. Internally, a list uses an array for storage. If it becomes full, it’ll create a new larger array, and will copy items from the existing array into the new one.

These days, it’s common to use lists instead of arrays, even if you’re working with a fixed set of items.

To create a list:
var list = new List<int>();

If you plan to store large number of objects in a list, you can reduce the cost of reallocations of the internal array by setting an initial size:

// Creating a list with an initial size
var list = new List<int>(10000);

Here are some useful operations with lists:

// Add an item at the end of the list
list.Add(4);
 
// Add an item at index 0
list.Insert(40);
 
// Remove an item from list
list.Remove(1);
 
// Remove the item at index 0
list.RemoveAt(0);
 
// Return the item at index 0
var first = list[0];
 
// Return the index of an item
var index = list.IndexOf(4);
 
// Check to see if the list contains an item
var contains = list.Contains(4);
 
// Return the number of items in the list 
var count = list.Count;
 
// Iterate over all objects in a list
foreach (var item in list)
    Console.WriteLine(item);


Now, let’s see where a list performs well and where it doesn’t.

Adding/Removing Items at the Beginning or Middle
If you add/remove an item at the beginning or middle of a list, it needs to shift one or more items in its internal array. In the worst case scenario, if you add/remove an item at the very beginning of a list, it needs to shift all existing items. The larger the list, the more costly this operation is going to be. We specify the cost of this operation using Big O notation: O(n), which simply means the cost increases linearly in direct proportion to the size of the input. So, as n grows, the execution time of the algorithm increases in direct proportion to n.

Adding/Removing Items at the End
Adding/removing an item at the end of a list is a relatively fast operation and does not depend on the size of the list. The existing items do not have to be shifted. This is why the cost of this operation is relatively constant and is not dependent on the number of items in the list. We represent the execution cost of this operation with Big O notation: O(1). So, 1 here means constant.

Searching for an Item
When using methods that involve searching for an item(e.g. IndexOf, Contains and Find), List performs a linear search. This means, it iterates over all items in its internal array and if it finds a match, it returns it. In the worst case scenario, if this item is at the end of the list, all items in the list need to be scanned before finding the match. Again, this is another example of O(n), where the cost of finding a match is linear and in direct proportion with the number of elements in the list.

Accessing an Item by an Index
This is what lists are good at. You can use an index to get an item in a list and no matter how big the list is, the cost of accessing an item by index remains relatively constant, hence O(1).

Dictionary<TKey, TValue>
Dictionary is a collection type that is useful when you need fast lookups by keys. For example, imagine you have a list of customers and as part of a task, you need to quickly look up a customer by their ID (or some other unique identifier, which we call key).

When storing or retrieving an object in a dictionary, you need to supply a key. The key is a value that uniquely identifies an object and cannot be null. For example, to store a Customer in a Dictionary, you can use CustomerID as the key.

To create a dictionary, first you need to specify the type of keys and values:
var dictionary = new Dictionary<intCustomer>();

Here, our dictionary uses int keys and Customer values. So, you can store a Customer object in this dictionary as follows:

dictionary.Add(customer.Idcustomer);

Later, you can look up customers by their IDs very quickly:
// Return the customer with ID 1234 
var customer = dictionary[1234];

So, why are dictionary look ups so fast? A dictionary internally stores objects in an array, but unlike a list, where objects are added at the end of the array (or at the provided index), the index is calculated using a hash function. So, when we store an object in a dictionary, it’ll call the GetHashCode method on the key of the object to calculate the hash. The hash is then adjusted to the size of the array to calculate the index into the array to store the object. Later, when we lookup an object by its key, GetHashCode method is used again to calculate the hash and the index. As you learned earlier, looking up an object by index in an array is a fast operation with O(1). So, unlike lists, looking up an object in a dictionary does not require  scanning every object and no matter how large the dictionary is, it’ll remain extremely fast.

So, in the following figure, when we store this object in a dictionary, the GetHashCode method on the key is called. Let’s assume it returns 1234. This hash value is then adjusted based on the size of the internal array. In this figure, length of the internal array is 6. So, the remainder of the division of 1234 by 6 is used to calculate the index (in this case 4). Later, when we need to look up this object, its key used again to calculate the index.

HashSet<T>
HashSet represents a set of unique items, just like a mathematical set (e.g. { 1, 2, 3 }). A set cannot contain duplicates and the order of items is not relevant. So, both { 1, 2, 3 } and { 3, 2, 1 } are equal.

Use a HashSet when you need super fast lookups against a unique list of items.
A HashSet, similar to a Dictionary, is a hash-based collection, so look ups are very fast with O(1). But unlike a dictionary, it doesn’t store key/value pairs; it only stores values. 

To create a HashSet:
var hashSet = new HashSet<int>();

Stack<T>
Stack is a collection type with Last-In-First-Out (LIFO) behaviour. We often use stacks in scenarios where we need to provide the user with a way to go back.
Think of your browser. As you navigate to different web sites, these addresses that you visit are pushed on a stack. Then, when you click the back button, the item on the stack (which represents the current address in the browser) is popped and now we can get the last address you visited from the item on the stack. The undo feature in applications is implemented using a stack as well.

Here is how you can use a Stack in C#:
var stack = new Stack<string>();
             
// Push items in a stack
stack.Push("http://www.google.com");
 
// Check to see if the stack contains a given item 
var contains = stack.Contains("http://www.google.com");
 
// Remove and return the item on the top of the stack
var top = stack.Pop();
 
// Return the item on the top of the stack without removing it 
var top = stack.Peek();
 
// Get the number of items in stack 
var count = stack.Count;
 
// Remove all items from stack 
stack.Clear();

Queue<T>
Queue represents a collection with First-In-First-Out (FIFO) behaviour. We use queues in situations where we need to process items as they arrive.

Three main operations on queue include:
  1. Enqueue: adding an element to the end of a queue
  2. Dequeue: removing the element at the front of the queue
  3. Peek: inspecting the element at the front without removing it.
Here is how you can use a queue:
var queue = new Queue<string>();
 
// Add an item to the queue
queue.Enqueue("transaction1");
 
// Check to see if the queue contains a given item 
var contains = queue.Contains("transaction1");
 
// Remove and return the item on the front of the queue
var front = queue.Dequeue();
 
// Return the item on the front without removing it 
var top = queue.Peek();
             
// Remove all items from queue 
queue.Clear();
 
// Get the number of items in the queue
var count = queue.Count;

Difference Between Hash Table and Dictionary 

Hash table 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 retrieving.


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<intstringdt = new Dictionary<intstring>();
            dt.Add(1"One");
            dt.Add(2"Two");
            dt.Add(3"Three");
            foreach (KeyValuePair<intStringkv 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.

Summary
  • Lists are fast when you need to access an element by index, but searching for an item in a list is slow since it requires a linear search.
  • Dictionaries provide fast lookups by key. Keys should be unique and cannot be null.
  • HashSets are useful when you need fast lookups to see if an element exists in a set or not.
  • Stacks provide LIFO (Last-In-First-Out) behaviour and are useful when you need to provide the user with a way to go back.
  • Queues provide FIFO (First-In-First-Out) behaviour and are useful to process items in the order arrived.

Continue Reading →

Wednesday, 15 April 2015

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

bind() method: This method only attaches events to elements which exist beforehand i.e. state of initialized document before the events are attached. If the selector condition is satisfied for an event afterward, bind() will not work on that function. It also won’t work in the case if selector condition is removed from the element.

<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>

on() method: This method attaches events not only to existing elements but also for the ones appended in the future as well. The difference here between on() and live() function is that on() method is still supported and uses a different syntax pattern, unlike the above two methods.


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

//Cancel a link's default action using the .preventDefault() method.
  $"body" ).on"click""a"functionevent ) {
    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:

$"table" ).delegate"td""click"function() {
    $this ).toggleClass"chosen" );
  });

is equivalent to the following code written using .on():

$"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.";
        }
    }
}

Is it required to override all abstract function in derived class?
Yes
Continue Reading →

Thursday, 2 April 2015

Console Program

1: Program to find remainder without using modulo or % operator
class Program
{
    // This function returns remainder of
    // num/divisor without using %
    // (modulo) operator
    static int getRemainder(int num, int divisor)
    {
        return (num - divisor * (num / divisor));
    }

    //initialize an array with 20 numbers and print count of it's all prime number
    static void Main(string[] args)
    {
        Console.Write(getRemainder(10, 3));
        Console.ReadLine();
    }
}
Output : 1

2: I have a string "nbaguarirot". you have to Check if it contains all the characters of nagarro word in sequence.
namespace nagarro
{
    public class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            p.checkString("nbaguarirot");
            Console.ReadLine();
        }

        public void checkString(string name)
        {
            StringBuilder builder = new StringBuilder();
            char[] myarray = { 'n', 'a', 'g', 'a', 'r', 'r', 'o' };

            int i = 0;
            foreach (char item in myarray)
            {
                for (int a= i; a <= name.Length; a++)
                {
                    char val = Convert.ToChar(name.Substring(i, 1));
                    if (item == val)
                    {
                        builder.Append(val);
                        i++; break;
                    }
                    else
                    {
                        i++;
                        continue;
                    }
                }
            }
            StringBuilder b = new StringBuilder();
            b.Append("nagarro");

            if (b.Equals(builder))
            {
                Console.Write("true");
            }
            else
            {
                Console.Write("false");
            }
        }
    }
}

3: Reverse a string without any function?
  string str = "", reverse = "";
  int len = 0;
  Console.WriteLine("Enter a String");
  str = Console.ReadLine();
 
  len = str.Length - 1;
  while (len >= 0)
  {
      reverse = reverse + str[len];
      len--;
  }
 
  Console.WriteLine("Reverse String is {0}", reverse);


Continue Reading →

Use of c# “Yield” keyword ?

Yield is one of the most useful but under-used keywords in C#. The reason is that most of us don't even know about this keyword and the purpose it can serve for us.

The functionality provided by Yield keyword is that when iterating a list, we can read an element of the loop, return to the calling code and go back to the loop again at the same point, from where it left the loop and continue processing the records in the loop. So this will be the basic idea behind the example that we will be using. 

Scenario where “yield” keyword is useful:-
Customized iteration through a collection without creating a temporary collection.

    Let’s try to understand what customized iteration means with an example.  
Consider the below code.
Let say we have a simple list called as “MyList” which has collection of 5 continuous numeric values 1,2,3,4 and 5. This list is browsed/iterated from console application from within static void main method.

static List<intMyList = new List<int>();
static void FillValues()
{
            MyList.Add(1);
            MyList.Add(2);
            MyList.Add(3);
            MyList.Add(4);
            MyList.Add(5);
}
static void Main(string[] args// Caller
{
            FillValues(); // Fills the list with 5 values
            foreach (int i in MyList// Browses through the list
            {
                Console.WriteLine(i);
            }
            Console.ReadLine();
}

Now let me complicate this situation let’s say the caller only wants values greater than “3” from the collection. So the obvious thing as a c# developer we will do is create a function as shown below. This function will have temporary collection. In this temporary collection we will first add values which are greater than “3” and return the same to the caller. The caller can then iterate through this collection.

static IEnumerable<intFilterWithoutYield()
{
            List<inttemp = new List<int>();
            foreach (int i in MyList)
            {
                if (i > 3)
                {
                    temp.Add(i);
                }
            }
            return temp;
}

Now the above approach is fine but it would be great if we would get rid of the collection, so that our code becomes simple. This where “yield” keyword comes to help. Below is a simple code how we have used yield.
Yield” keyword will return back the control to the caller, the caller will do his work and re-enter the function from where he had left and continue iteration from that point onwards. In other words “yield” keyword moves control of the program to and fro between caller and the collection.

static IEnumerable<intFilterWithYield()
{
            foreach (int i in MyList)
            {
                if (i > 3yield return i;
            }
}

So for the above code following are details steps how the control will flow between caller and collection. 
  • Caller calls the function to iterate for number’s greater than 3.
  • Inside the function the for loop runs from 1 to 2 , from 2 to 3 until it encounters value greater than “3” i.e. “4”. As soon as the condition of value greater than 3 is met the “yield” keyword sends this data back to the caller.
  • Caller displays the value on the console and re-enters the function for more data. This time when it reenters, it does not start from first. It remembers the state and starts from “5”. The iteration continues further as usual.
Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives