Diving in OOP (Part 2) : Polymorphism and Inheritance (Inheritance)


Introduction

In our first part of the article, we learned about different scenarios of method overloading and did lots of interesting hands on too. My article in the second part of the series will focus solely on inheritance concept in OOP. Let’s define Inheritance using some bullet points:

Roadmap

We still stick to our roadmap that we defined before starting the series for learning OOP:

Note: Each and every code snippet written in this article is tried and tested.

Inheritance in Action

OK. Let’s do some hands on. Create a console application and name it InheritanceAndPolymorphism. Add a class named ClassA and a class named ClassB, with the following code:
ClassA:

class ClassA
{

}

ClassB:

class ClassB
{
public int x = 100;
public void Display1()
{
Console.WriteLine(ClassB Display1″);
}
public void Display2()
{
Console.WriteLine(ClassB Display2″);
}
}

We see classClassA is empty and we added two methods in class ClassB, i.e. Display1 and Display2. We also have a variable declared and defined with a value 100.
Now in the main method of Program.cs, write the following code:

Program.cs

class Program
    {
        static void Main(string[] args)
        {

ClassA a = new ClassA();
a.Display1();
}
}

If we run the code, we immediately result in the compile time error.
 
Error'InheritanceAndPolymorphism.ClassA‘ does not contain a definition for ‘Display1‘ and no extension method ‘Display1‘ accepting a first argument of type ‘InheritanceAndPolymorphism.ClassA‘ could be found (are you missing a using directive or an assembly reference?)
i.e. Too obvious, we don’t have definition of Display1 method in ClassA, nor can we access the same method usingClassA instance because it is not derived from any such class like ClassB that contains Display1 method. The class ClassA does not contain any code or variable defined. An empty class does not throw any error as we are able to instantiate an object that looks like a (instance of ClassA). The error comes about because the class ClassA has no method called Display1. However the class ClassB has a method named Display1. Guess how fun it could be if we are allowed to access all the code of classB from ClassA itself.
Just derive the class ClassA from ClassB using : operator as code shown below:
ClassA:

class ClassA:ClassB
{

}

ClassB:

class ClassB
{
public int x = 100;
public void Display1()
{
Console.WriteLine(ClassB Display1″);
}
public void Display2()
{
Console.WriteLine(ClassB Display2″);
}
}

Program.cs

class Program
    {
        static void Main(string[] args)
        {
            ClassA a = new ClassA();
            a.Display1();
            Console.ReadKey();
        }
    }
And now run the code as it was, we get an output now.

Output

ClassB Display1
i.e. now ClassA can access the inherited public methods of ClassB. The error vanishes and the Display1 inClassB gets invoked. If after the name of a class we specify : ClassB i.e., the name of another class, a lot changes at once. ClassA is now said to have been derived from ClassB. What that means is all the code we wrote in ClassBcan now be accessed and used in ClassA. It is if we actually wrote all the code that is contained in ClassB in ClassA. If we had created an instance that looks like that of ClassB, everything that the instance could do, now an instance ofClassA can also do. But we have not written a line of code in ClassA. We are made to believe that ClassA has one variable x and two functions Display1 and Display2 as ClassB contains these two functions. Therefore, we enter
into the concepts of inheritance where ClassB is the base class, ClassA the derived class.
Let’s take another scenario. Suppose we get into a situation where ClassA also has a method of same name as of inClassB. Let’s define a method Derive1 in ClassA too, so our code for classA becomes:
class ClassA:ClassB
    {
        public void Display1()
        {
            System.Console.WriteLine("ClassA Display1");
        }
    }

ClassB:

class ClassB
{
public int x = 100;
public void Display1()
{
Console.WriteLine(ClassB Display1″);
}
public void Display2()
{
Console.WriteLine(ClassB Display2″);
}
}

Now if we run the application using the following code snippet for Program.cs class:
class Program
    {
        static void Main(string[] args)
        {
            ClassA a = new ClassA();
            a.Display1();
            Console.ReadKey();
        }
    }
The question is what will happen now? What will be the output? Will there be any output or any compilation error. Ok, let’s run it.
We get Output:
ClassA Display1
But did you notice one thing, we also got a warning when we run the code:
 
Warning: ‘InheritanceAndPolymorphism.ClassA.Display1()‘ hides inherited member ‘InheritanceAndPolymorphism.ClassB.Display1()‘. Use the new keyword if hiding was intended.
 
Point to remember: No one can stop a derived class to have a method with the same name already declared in its base class.
So, ClassA undoubtedly can contain Display1 method, that is already defined with the same name in ClassB.
When we invoke a.Display1(), C# first checks whether the class ClassA has a method named Display1. If it does not find it, it checks in the base class. Earlier Display1 method was only available in the base class ClassB and hence got executed. Here, since it is there in ClassA, it gets called from ClassA and not ClassB.
 
Point to remember: Derived classes get a first chance at execution, then the base class.
The reason for this is that the base class may have a number of methods and for various reasons, we may not be satisfied with what they do. We should have the full right to have our copy of the method to be called. In other words, the derived classes methods override the ones defined in the base class.
What happens if we call base class Display1 method too with base keyword in derived class, i.e., by usingbase.Display1(), so our ClassA code will be:
ClassA:

class ClassA:ClassB
{
public void Display1()
{
Console.WriteLine(ClassA Display1″);
base.Display1();
}
}

ClassB:

class ClassB
{
public int x = 100;
public void Display1()
{
Console.WriteLine(ClassB Display1″);
}
public void Display2()
{
Console.WriteLine(ClassB Display2″);
}
}

Program.cs

class Program
    {
        static void Main(string[] args)
        {
            ClassA a = new ClassA();
            a.Display1();
            Console.ReadKey();
        }
    }

Output

ClassA Display1 
ClassB Display1
We see here first our ClassA Display1 method is called and then ClassB Display1 method.
Now if you want the best of both the classes , you may want to call the base classes (ClassBDisplay1 first and then yours or vice versa. To achieve this, C# gives you a free keyword, called base. The keyword base can be used in any of the derived class. It means call the method off the base class. Thus base.Display1 will call the methodDisplay1 fromClassB the base class
of ClassA as defined earlier.
 
Point to remember: A reserved keyword named “base” can be used in derived class to call the base class method.
What if we call Display2 method from base class, with an instance of derived class ClassA?
/// <summary>
   /// ClassB: acting as base class 
   /// </summary>
   class ClassB
    {
        public int x = 100;
        public void Display1()
        {
            Console.WriteLine("ClassB Display1");
        }
        public void Display2()
        {
            Console.WriteLine("ClassB Display2");
        }
    }

/// <summary>
/// ClassA: acting as derived class
/// </summary>
class ClassA : ClassB
{
public void Display1()
{
Console.WriteLine(ClassA Display1″);
base.Display2();
}
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
class Program
{
static void Main(string[] args)
{
ClassA a = new ClassA();
a.Display1();
Console.ReadKey();
}
}

Output

In the above code, we only made just a small change, base.Display1 was replaced by base.Display2. In this particular scenario, method Display2 from the class ClassB gets called. Base is usually a very general purpose. It lets us access members of the base class from the derived class as explained earlier. We cannot use base in ClassBas ClassB is not derived from any class as per our code. So it’s done that the base keyword can only be used in derived classes?
Let’s take another case:
/// <summary>
   /// ClassB: acting as base class 
   /// </summary>
   class ClassB
    {
        public int x = 100;
        public void Display1()
        {
            Console.WriteLine("ClassB Display1");
        }
    }

/// <summary>
/// ClassA: acting as derived class
/// </summary>
class ClassA : ClassB
{
public void Display2()
{
Console.WriteLine(ClassA Display2″);
}
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
class Program
{
static void Main(string[] args)
{
ClassB b = new ClassB();
b.Display2();
Console.ReadKey();
}
}

Output

Error: ‘InheritanceAndPolymorphism.ClassB‘ does not contain a definition for ‘Display2‘ and no extension method ‘Display2‘ accepting a first argument of type ‘InheritanceAndPolymorphism.ClassB‘ could be found (are you missing a using directive or an assembly reference?)
 
Point to remember: Inheritance does not work backwards.
So we got an error. Since we see, ClassA is derived from ClassB, i.e., ClassB is base class. Therefore, classClassAcan use all the members of class ClassB. Inheritance does not have backwards compatibility, whatever membersClassA contains do not permeate upwards toClassB. When we tried to access Display2 method of classA from the instance of class ClassB, it cannot give it to class ClassB and thus an error occurs.
 
Point to remember: Except constructors and destructors, a class inherits everything from its base class .
If a class ClassC is derived from class ClassB, which in turn has been derived from class ClassA, then ClassC will inherit all the members declared in ClassB and also of ClassA. This is called transitive concept in inheritance. A derived class may inherit all the members of the base class but it cannot remove members off that base class. A derived class can however hide members of the base class by creating methods by the same name. The original member/method of the base class remains unmodified and unaffected by whatever happens in the derived class. It remains unchanged in the base class, i.e., simply not visible in the derived class.
A class member could be of two types, i.e. either a static member that directly belongs to a class or an instance member that is accessed through instance of that class and belongs to that particular instance only. Instance member is accessible only through the object of the class and not directly by the class. The default member declared in the class are nonstatic, we just have to make them static by using static keyword.
All classes derive from a common base class named object. So Object is the mother of all classes.
If we do not derive any class from any other class, it’s the responsibility of C# to add :object by itself to the class definition. Object is the only class that is not derived from any other class. It is the ultimate base class for all the classes.
Suppose ClassA is derived from ClassB as in our case, but ClassB is not derived from any class,
public class ClassB
    {
    }

public class ClassA : ClassB
{
}

C# automatically adds :object to ClassB, i.e., the code at compile time becomes:
public class ClassB:object
    {
    }

public class ClassA : ClassB
{
}

But as per theory, we say ClassB is the direct base class of ClassA, so the classes of ClassA are ClassB and object.
Let’s go for another case:
public class ClassW : System.ValueType
    {
    }

public class ClassX : System.Enum
{
}

public class ClassY : System.Delegate
{
}

public class ClassZ : System.Array
{
}

Here we have defined four classes, each derive from a built in class in C#, let’s run the code.
We get so many compile time errors.

Errors

'InheritanceAndPolymorphism.ClassW' cannot derive from special class 'System.ValueType'
'InheritanceAndPolymorphism.ClassX' cannot derive from special class 'System.Enum'
'InheritanceAndPolymorphism.ClassY' cannot derive from special class 'System.Delegate'
'InheritanceAndPolymorphism.ClassZ' cannot derive from special class 'System.Array'
Don’t be scared.
Did you notice the word special class. Our classes defined cannot inherit from special built in classes in C#.
Point to remember: In inheritance in C#, custom classes cannot derive from special built in c# classes likeSystem.ValueTypeSystem.EnumSystem.DelegateSystem.Array, etc.
One more case,
public class ClassW
    {
    }

public class ClassX
{
}

public class ClassY : ClassW, ClassX
{
}

In the above mentioned case, we see three classes, ClassWClassX and ClassYClassY is derived from ClassWand ClassX. Now if we run the code, what would we get?
Compile time Error: Class ‘InheritanceAndPolymorphism.ClassY‘ cannot have multiple base classes: ‘InheritanceAndPolymorphism.ClassW‘ and ‘ClassX‘.
So one more Point to remember: A class can only be derived from one class in C#. C# does not support multiple inheritance by means of class*.
*Multiple inheritance in C# can be accomplished by the use of Interfaces, we are not discussing about interfaces in this article.
We are not allowed to derive from more than one class, thus every class can have only one base class.
Another case:
Suppose we try to write code as below:
public class ClassW:ClassY
    {
    }

public class ClassX:ClassW
{
}

public class ClassY : ClassX
{
}

Code is quite readable and simple, ClassW is derived from ClassYClassX is derived from ClassW, and ClassY in turn is derived from ClassX. So no problem of multiple inheritance, our code should build successfully. Let’s compile the code. What do we get? Again a compile time error.
Error: Circular base class dependency involving ‘InheritanceAndPolymorphism.ClassX‘ and ‘InheritanceAndPolymorphism.ClassW‘.
 
Point to remember: Circular dependency is not allowed in inheritance in C#. ClassX is derived from ClassW which was derived from ClassY and ClassY was again derived from ClassX, which caused circular dependency in three classes, that is logically impossible.

Equalizing the Instances/Objects

Let’s directly start with a real case:
ClassB:
public class ClassB
    {
        public int b = 100;
    }

ClassA:

public class ClassA
{
public int a = 100;
}

Program.cs

/// <summary>
    /// Program: used to execute the method.
    /// Contains Main method.
    /// </summary>
    public class Program
    {
        private static void Main(string[] args)
        {
            ClassB classB = new ClassB();
            ClassA classA = new ClassA();
            classA = classB;
            classB = classA;
        }
    }
We are here trying to equate two objects or two instances of two different classes. Let’s compile the code,
We get compile time error:
 
Error
Cannot implicitly convert type 'InheritanceAndPolymorphism.ClassB' to 'InheritanceAndPolymorphism.ClassA'

Cannot implicitly convert type ‘InheritanceAndPolymorphism.ClassA’ to ‘InheritanceAndPolymorphism.ClassB’

 
InheritanceAndPolymorphism is the namespace that I used for my console application, so there is no need to be scared of that word, just ignore it.
C# works on rules, it will never allow you to equate objects of different independent classes to each other. Therefore, we cannot equate an object classA of ClassA to classB of ClassB or vice versa. No matter the classes contain similar structure and their variables are initialized to similar integer value, even if we do.
public class ClassB
    {
        public int a = 100;
    }

public class ClassA
{
public int a = 100;
}

I just changed int b ofClassB to int a. In this case too, to equate an object is not allowed and not possible.
C# is also very particular if it comes with dealing with data types.
There is however one way to do this. By this way which we’ll discuss, one of the errors will disappear. The only time we are allowed to equate dissimilar data types is only when we derive from them? Check out the code mentioned below. Let’s discuss this in detail, when we create an object of ClassB by declaring new, we are creating two objects at one go, one that looks like ClassB and the other that looks like object, i.e., derived from Object class (i.e. ultimate base class). All classes in C# are finally derived from object. Since ClassA is derived from ClassB, when we declare newClassA, we are creating 3 objects, one that looks like ClassB, one that looks like ClassA and finally that looks likeobject class.
public class ClassB
    {
        public int b = 100;
    }

public class ClassA:ClassB
{
public int a = 100;
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassB classB = new ClassB();
ClassA classA = new ClassA();
classA = classB;
classB = classA;
}
}

We just derived ClassA from ClassB, this is something we can do, we learned a lot about this in this article. Now compile the code, we get:
 
Error: Cannot implicitly convert type ‘InheritanceAndPolymorphism.ClassB‘ to ‘InheritanceAndPolymorphism.ClassA‘. An explicit conversion exists (are you missing a cast?)
Like I mentioned, C# is very particular about objects equating.
Thus when we write classA = classBclassA looks like ClassAClassB and object and as a looks like ClassB, there is a match at ClassB.Result? No error Smile | :) . Even though classB and classA have the same values, usingclassB we can only access the members of ClassB, even though had we used classA we could access ClassAalso. We have devalued the potency of classB. The error occurs at classA = classB, because the class ClassB is less/smaller than the class ClassA. The class ClassA has ClassB and more. We cannot have a larger class on the right and a smaller class on the left. classB only represents a ClassB whereas classA expects a ClassA which is aClassA andClassB.
 
Point to remember: We can only and only equate the dissimilar objects if they are derived from each other. We can equate an object of a base class to a derived class but not vice versa.
Another code snippet:
public class ClassB
    {
        public int b = 100;
    }

public class ClassA:ClassB
{
public int a = 100;
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassB classB = new ClassB();
ClassA classA = new ClassA();
classB=classA;
classA = (ClassA)classB;
}
}

Although we violated a C# rule of equating objects, we did not get any compiler error because of the cast we did to the object. A() is called a cast. Within the brackets, the name of the class is put. A cast basically proves to be a great leveller. When we intend to write classA = classB, C# expects the right hand side of the equal to be a classA, i.e., a ClassA instance. But it finds classB, i.e., a ClassB instance. So when we apply the cast, we actually try to convert instance of ClassB to instance of ClassA. This approach satisfies the rules of C# on only equating similar objects type. Remember it is only for the duration of the line that classB becomes a ClassA and not a ClassB.
Now, if we remove ClassB as a base class to class ClassA as in the following code, and try to typecast classA toClassB object.
public class ClassB
    {
        public int b = 100;
    }

public class ClassA // Removed ClassB as base class
{
public int a = 100;
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassB classB = new ClassB();
ClassA classA = new ClassA();
classB = (ClassB)classA;
classA = (ClassA)classB;
}
}

Output

Error
Cannot convert type 'InheritanceAndPolymorphism.ClassA' to 'InheritanceAndPolymorphism.ClassB'
Cannot convert type 'InheritanceAndPolymorphism.ClassB' to 'InheritanceAndPolymorphism.ClassA'
*’InheritanceAndPolymorphism’: Namespace I used in my application, so ignore that.
So we see that casting only works if one of the two classes is derived from one another. We cannot cast any two objects to each other.
One last example:
/// <summary>
    /// Program: used to execute the method.
    /// Contains Main method.
    /// </summary>
    public class Program
    {
        private static void Main(string[] args)
        {
            int integerA = 10;
            char characterB = 'A';
            integerA = characterB;
            characterB = integerA;
        }
    }
We run the code.

Output

Error: Cannot implicitly convert type ‘int‘ to ‘char‘. An explicit conversion exists (are you missing a cast?)
Point to remember: We cannot implicitly convert an int to char, but char can be converted to int.

Conclusion

In this part of our article series, we learned about inheritance. We took various scenarios and practical examples back to back to understand the concept deeply. In my next article, we’ll be discussing about run time polymorphism. Inheritance plays a very important role in run time polymorphism.
Let’s list down all our points to remember:
  1. No one can stop a derived class to have a method with the same name already declared in its base class.
  2. Derived classes get a first chance at execution, then the base class.
  3. A reserved keyword named “base” can be used in derived class to call the base class method.
  4. Inheritance does not work backwards.
  5. Except constructors and destructors, a class inherits everything from its base class.
  6. In inheritance in C#, custom classes cannot derive from special built in C# classes like System.ValueType,System.EnumSystem.DelegateSystem.Array, etc.
  7. A class can only be derived from one class in C#. C# does not support multiple inheritance by means of class.
  8. Circular dependency is not allowed in inheritance in C#. ClassX is derived from ClassW which was derived from ClassY and ClassY was again derived from ClassX, which caused circular dependency in three classes, that is logically impossible.
  9. We can only and only equate the dissimilar objects if they are derived from each other. We can equate an object of a base class to a derived class but not vice versa.
  10. We cannot implicitly convert an int to char, but char can be converted to int.
You can read about compile time polymorphism in my first article of the series. Keep coding and learning. .

Read more:

Other Series

My other series of articles:

For more informative articles visit my Blog.

For more technical articles you can reach out to CodeTeddy.
Advertisements

Diving in OOP (Part 1) : Polymorphism and Inheritance(Early Binding/Compile Time Polymorphism).


Introduction

I have been writing a lot about advanced topics like MVC, Entity Framework, Repository Patterns etc, my priority always remains to cover the topic as a whole, so that a reader does not have to search for missing links anywhere else. This article will cover almost every OOPS concept that a novice/beginner developer may hunt for, and not only beginners, the article’s purpose is to be helpful to experienced professionals who may need to brush-up on their concepts or who prepare for interviews.
I will take the topics in a manner that we cover them in a simple, straightforward way giving code snippets as example wherever needed. We’ll take C# as our programming language throughout our readings.
We’ll play with tricky questions and not go for enough theory. For theory you can refer MSDN.
Pre-requisites
Since this is the first part of the series, my readers should have basic knowledge of C# and should be aware of OOP concepts and terminology.
Note: Each and every code snippet written in this article is tried and tested.

OOPS

1. What is OOPS and what is advantage of OOP?

OOP stands for “Object-Oriented Programming.” Remember, it’s OOP not OOPS,’S’ may stand for system, synopsis, structure etc. It is a programming approach entirely based on objects, instead of just functions and procedures like in procedural languages. It is like a programming language model organized around objects rather than “actions” and data rather than logic. An “object” in an OOP language refers to a specific type, or “instance,” of a class. Each object has a structure exactly similar to other objects in a class, but can have individual properties/values. An object can also invoke methods, specific to that object
OOP makes it easier for developers to structure and organize software programs. Individual objects can be modified without affecting other aspects of the program therefore it is also easier to update and change programs written in object-oriented languages. Since the nature of software programs have grown larger over the years, OOP has made developing these large programs more manageable and readable.

2. What are OOP Concepts?

Following are OOP concepts explained in brief, we’ll take the topics in detail.
  1. Data Abstraction: Data Abstraction is a concept in which the internal and superfluous details of the implementation of a logic is hidden from an end user(who is using the program) .A user can use any of the data and method from the class without knowing about how this is created or what is the complexity behind it. In terms of a real world example, when we drive a bike and change the gears we don’t have to care about how internally its working, like how liver is pulled or how chain is set.
  2. Inheritance: Inheritance is most popular Concept in OOP’s .This provides a developer an advantage called reusability of code. Suppose a class is written having functions with specific logic, then we can derive that class into our newly created class and we don’t have to write the logic again for derived class functions, we can use them as it is.
  3. Data Encapsulation: Wrapping up of member data and member functions of a class in a single unit is called encapsulation. The visibility of the member functions,data members is set via access modifiers used in class.
  4. Polymorphism: Poly means many and morphism means many function The Concepts Introduces in the form of Many behaviours of an object.
  5. Message Communication: Message Communication means when an object passes the call to method of class for execution.
OK, we covered lots of theory, now it’s time for action. I hope that will be interesting. We’ll cover the topics in a series as follows,
  1. Diving in OOP (Day 1): Polymorphism and Inheritance(Early Binding/Compile Time Polymorphism)
  2. Diving in OOP (Day 2): Polymorphism and Inheritance (Inheritance)
  3. Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time Polymorphism)
  4. Diving in OOP (Day 4): Polymorphism and Inheritance (All about Abstarct classes in C#)
  5. Diving in OOP (Day 5): All about access modifiers in C# (Public/Private/Protected/Internal/Sealed/Constants/Readonly Fields)
  6. Diving in OOP (Day 6): Understanding Enum in C# (A Practical Approach)
  7. Diving into OOP (Day 7): Properties in C# (A Practical Approach)
  8. Diving into OOP (Day 8): Indexers in C# (A Practical Approach)
  9. Diving into OOP (Day 9): Understanding Events in C# (An Insight)

3. Polymorphism:

In this article we will cover almost all the scenarios of compile type polymorphism, the use of params keyword in detail, and case study or hands on to different possible combinations of the thoughts coming to our mind while coding.

Method Overloading or Early Binding or Compile Time Polymorphism

  1. Let’s create a simple console application named InheritanceAndPolymorphism, and add a class namedOverload.cs and add three methods named DisplayOverload having varied parameters as follows,

    Overload.cs

    public class Overload
        {
            public void DisplayOverload(int a){
                System.Console.WriteLine("DisplayOverload " + a);
            }
            public void DisplayOverload(string a){
                System.Console.WriteLine("DisplayOverload " + a);
            }
            public void DisplayOverload(string a, int b){
                System.Console.WriteLine("DisplayOverload " + a + b);
            }
        }

    In the main method in Program.cs file, add the following code,

    Program.cs

    class Program
        {
            static void Main(string[] args)
            {
                Overload overload = new Overload();
                overload.DisplayOverload(100);
                overload.DisplayOverload("method overloading");
                overload.DisplayOverload("method overloading", 100);
                Console.ReadKey();
            }
        }
Now when you run the application, the output is,

Output

DisplayOverload 100
DisplayOverload method overloading
DisplayOverload method overloading100
The class Overload contains three methods named DisplayOverload, they only differ in the datatype of the parameters they consist of. In C# we can have methods with the same name, but the datatypes of their parameters should differ. This feature of C# is called method overloading. Therefore, we need not to remember lots of method names if a method differs in behavior, only providing different parameters to the methods can call a method individually.
Point to remember: C# recognizes the method by its parameters and not by its name.
A signature signifies the full name of the method. So the name of a method or its signature is the original method name + the number and data types of its individual parameters.
If we run project using following code,
public void DisplayOverload() { }
     public int DisplayOverload(){ }
We certainly get a compile time error as,
Error: Type ‘InheritanceAndPolymorphism.Overload’ already defines a member called ‘DisplayOverload’ with the same parameter types
Here we had two functions who differ only in the data type of the value that they return, but we got a compile time error, therefore, another point to remember comes,
 
Point to remember: The return value/parameter type of a method is never the part of method signature if the names of the methods are same. So this is not polymorphism.
If we run the project using following code,
static void DisplayOverload(int a)  {   }
public void DisplayOverload(int a) {   }
public void DisplayOverload(string a){  }
We again get a compile time error,
Error: Type ‘InheritanceAndPolymorphism.Overload’ already defines a member called ‘DisplayOverload’ with the same parameter types
Can you differentiate with the modification done in the above code, we now have two DisplayOverload methods, that accept an int (integer). The only difference is that one method is marked static. Here the signature of the methods will be considered same as modifiers such as static are also not considered to be a part of method signature.
 
Point to remember: Modifiers such as static are not considered as part of method signature.
If we run the program as per following code, considering the method signature is different now,
private void DisplayOverload(int a) {   }

private void DisplayOverload(out int a)
{
a = 100;
}

private void DisplayOverload(ref int a) { }

We again get a compile time error,
Error: Cannot define overloaded method ‘DisplayOverload’ because it differs from another method only on ref and out
The signature of a method not only consists of the data type of the parameter but also the type/kind of parameter such as ref or out etc. Method DisplayOverload takes an int with different access modifiers i.e. out/ref etc, the signature on each is different.
 
Point to remember: The signature of a method consists of its name, number and types of its formal parameters. The return type of a function is not part of the signature. Two methods can not have the same signature and also non-members cannot have the same name as members.

4. Role of Params Parameter in Polymorphism

A method can be called by four different types of parameters.
  1. pass by value,
  2. Pass by reference,
  3. As an output parameter,
  4. Using parameter arrays.
As explained earlier the parameter modifier is never the part of method signature. Now let’s focus on Parameter Arrays.
A method declaration means creating a separate declaration space in memory. So anything created will be lost at the end of the method.
Running following code,
public void DisplayOverload(int a, string a)  {   }

public void Display(int a)
{
string a;
}

Results in compile time error,
 
Error1: The parameter name ‘a’ is a duplicate
Error2: A local variable named ‘a’ cannot be declared in this scope because it would give a different meaning to ‘a’, which is already used in a ‘parent or current’ scope to denote something else
 
Point to remember: Parameter names should be unique. And also we can not have a parameter name and a declared variable name in the same function as same.
In the case of pass by value, the value of the variable is passed and in the case of ref and out, the address of the reference is passed.
When we run the following code,

Overload.cs

public class Overload
    {
        private string name = "Akhil";

public void Display()
{
Display2(ref name, ref name);
System.Console.WriteLine(name);
}

private void Display2(ref string x, ref string y)
{
System.Console.WriteLine(name);
x = Akhil 1″;
System.Console.WriteLine(name);
y = Akhil 2″;
System.Console.WriteLine(name);
name = Akhil 3″;
}
}

Program.cs

class Program
    {
        static void Main(string[] args)
        {
            Overload overload = new Overload();
            overload.Display();
            Console.ReadKey();
        }
    }
We get out put as,

Output

Akhil
Akhil 1
Akhil 2
Akhil3

We are allowed to pass the same ref parameter as many times as we want. In the method Display the string name has a value of Akhil. Then by changing the string x to Akhil1, we are actually changing the string name to Akhil1 as name is passed by reference. Variables x and name refer to the same string in memory. Changing one changes the other. Again changing y also changes name variable as they refer to the same string anyways. Thus variables x, y and name refer to the same string in memory.
When we run the following code,

Overload.cs

public class Overload
    {
        public void Display()
        {
            DisplayOverload(100, "Akhil", "Mittal", "OOP");
            DisplayOverload(200, "Akhil");
            DisplayOverload(300);
        }

private void DisplayOverload(int a, params string[] parameterArray)
{
foreach (string str in parameterArray)
Console.WriteLine(str + + a);
}
}

Program.cs

class Program
    {
        static void Main(string[] args)
        {
            Overload overload = new Overload();
            overload.Display();
            Console.ReadKey();
        }
    }
We get output,

Output

Akhil 100
Mittal 100
OOP 100
Akhil 200
We will often get into a scenario where we would like to pass n number of parameters to a method. Since C# is very particular in parameter passing to methods, if we pass an int where a string is expected, it immediately breaks down. But C# provides a mechanism for passing n number of arguments to a method,
we can achieve it with the help ofparams keyword.
 
Point to remember: This params keyword can only be applied to the last argument of the method. So the n number of parameters can only be at the end.
In the case of method DisplayOverload, the first argument has to be an integer, the rest can be from zero to an infinite number of strings.
If we add a method like ,
private void DisplayOverload(int a, params string[] parameterArray, int b) {  }
We get a compile time error as,
 
Error: A parameter array must be the last parameter in a formal parameter list
Thus is is proved that params keyword will be the last parameter in a method, this is already stated in the latest point to remember.

Overload.cs

public class Overload
    {
        public void Display()
        {
            DisplayOverload(100, 200, 300);
            DisplayOverload(200, 100);
            DisplayOverload(200);
        }

private void DisplayOverload(int a, params int[] parameterArray)
{
foreach (var i in parameterArray)
Console.WriteLine(i + + a);
}

}

Program.cs

class Program
    {
        static void Main(string[] args)
        {
            Overload overload = new Overload();
            overload.Display();
            Console.ReadKey();
        }
    }
When we run the code we get,
200 100
300 100
100 200
Therefore,
 
Point to Remember: C# is very smart to recognize if the penultimate argument and the params have the same data type.
The first integer is stored in the variable a, the rest are made part of the array parameterArray.
private void DisplayOverload(int a, params string[][] parameterArray)  {     }

private void DisplayOverload(int a, params string[,] parameterArray) { }

For the above written code, we again get a compile time error and a new point to remember as well,
 
Error:The parameter array must be a single dimensional array
Point to remember: same as error above.
The data type of the params argument must be a single dimensional array. Therefore [ ][ ]
is allowed but not [,]. We also not allowed to combine the params keyword with ref or out.

Overload.cs

public class Overload
    {
        public void Display()
        {
            string[] names = {"Akhil", "Ekta", "Arsh"};
            DisplayOverload(3, names);
        }

private void DisplayOverload(int a, params string[] parameterArray)
{
foreach (var s in parameterArray)
Console.WriteLine(s + + a);
}

}

Program.cs

class Program
    {
        static void Main(string[] args)
        {
            Overload overload = new Overload();
            overload.Display();
            Console.ReadKey();
        }
    }

Output

Akhil 3
Ekta 3
Arsh 3
We are, therefore, allowed to pass a string array instead of individual strings as arguments. Here, names is a string array which has been initialized using the short form. Internally when we call the function DisplayOverload, C# converts the string array into individual strings.

Overload.cs

public class Overload
    {
        public void Display()
        {
           string [] names = {"Akhil","Arsh"};
           DisplayOverload(2, names, "Ekta");
        }

private void DisplayOverload(int a, params string[] parameterArray)
{
foreach (var str in parameterArray)
Console.WriteLine(str + + a);
}

}

Program.cs

class Program
    {
        static void Main(string[] args)
        {
            Overload overload = new Overload();
            overload.Display();
            Console.ReadKey();
        }
    }

Output

Error: The best overloaded method match for ‘InheritanceAndPolymorphism.Overload.DisplayOverload(int, params string[])’ has some invalid arguments
Error:Argument 2: cannot convert from ‘string[]’ to ‘string’
So, we got two errors. 
For the above mentioned code, C# does not permit mix and match. We assumed that the last string “Ekta” would be added to the array of strings names or convert names to individual strings and then add the string “Ekta” to it. Quite logical.
Internally before calling the function DisplayOverload, C# accumulates all the individual parameters and converts them into one big array for the params statement.

Overload.cs

public class Overload
    {
        public void Display()
        {
            int[] numbers = {10, 20, 30};
            DisplayOverload(40, numbers);
            Console.WriteLine(numbers[1]);
        }

private void DisplayOverload(int a, params int[] parameterArray)
{
parameterArray[1] = 1000;
}

}

Program.cs

class Program
    {
        static void Main(string[] args)
        {
            Overload overload = new Overload();
            overload.Display();
            Console.ReadKey();
        }
    }

Output

1000
We see that the output produced is the proof of concept. The member parameterArray[1] of array has an initial value of 20 and in the method DisplayOverload, we changed it to 1000. So the original value changes, this shows that the array is given to the method DisplayOverload, Hence proved.

Overload.cs

public class Overload
    {
        public void Display()
        {
            int number = 102;
            DisplayOverload(200, 1000, number, 200);
            Console.WriteLine(number);
        }

private void DisplayOverload(int a, params int[] parameterArray)
{
parameterArray[1] = 3000;
}

}

Program.cs

class Program
    {
        static void Main(string[] args)
        {
            Overload overload = new Overload();
            overload.Display();
            Console.ReadKey();
        }
    }

Output

102
In the above mentioned scenario C# creates an array containing 1000 102 and 200. We now change the second member of array to 3000 which has nothing to do with the variable number. As DisplayOverload has no knowledge of number, so how can DisplayOverload change the value of the int number? Therefore it remains the same.

Overload.cs

public class Overload
    {
        public void Display()
        {
            DisplayOverload(200);
            DisplayOverload(200, 300);
            DisplayOverload(200, 300, 500, 600);
        }

private void DisplayOverload(int x, int y)
{
Console.WriteLine(The two integers “ + x + + y);
}

private void DisplayOverload(params int[] parameterArray)
{
Console.WriteLine(parameterArray”);
}

}

Program.cs

class Program
    {
        static void Main(string[] args)
        {
            Overload overload = new Overload();
            overload.Display();
            Console.ReadKey();
        }
    }

Output

parameterArray
The two integers 200 300
parameterArray
Now we’ll talk about method overloading. C# is extremely talented though partial. It does not appreciate the paramsstatement and treats it as a stepchild. When we invoke DisplayOverload only with one integer, C# can only call theDisplayOverload that takes a params as a parameter as it matches only one int. An array can contain one member too. The fun is with the DisplayOverload that is called with two ints now. So here we have a dilemma. C# can call theparams DisplayOverload or DisplayOverload with the two ints. As discussed earlier, C# treats the params as a second class member and therefore chooses the DisplayOverload with two ints. When there are more than two ints like in the third method call, C# is void of choice but to grudgingly choose the DisplayOverload with the params. C# opts for the params as a last resort before flagging an error.
Now a bit tricky example, yet important,

Overload.cs

public class Overload
    {
        public static void Display(params object[] objectParamArray)
        {
            foreach (object obj in objectParamArray)
            {
                Console.Write(obj.GetType().FullName + " ");
            }
            Console.WriteLine();

}
}

Program.cs

class Program
    {
        static void Main(string[] args)
        {
            object[] objArray = { 100, "Akhil", 200.300 };
            object obj = objArray;
            Overload.Display(objArray);
            Overload.Display((object)objArray);
            Overload.Display(obj);
            Overload.Display((object[])obj);
            Console.ReadKey();

}
}

Output

System.Int32 System.String System.Double
System.Object[]
System.Object[]
System.Int32 System.String System.Double
In the first instance we are passing the method Display an array of object that looks like object. Since all the classes are derived from a common base class object, we can do that. The method Display gets an array of objectsobjectParamArray. In the foreach object class has a method named GetType that returns an object that looks like Type, which too has a method named FullName that returns the name of the type. Since three different types displayed. In the second method call of Display we are casting objArray to an object. Since there is no conversion available from converting an object to an object array i.e. object [ ], so only a one element object [ ] is created. It’s the same case in the third invocation and the last explicitly casts to an object array.
For proof of concept,

Overload.cs

public class Overload
    {
        public static void Display(params object[] objectParamArray)
        {
            Console.WriteLine(objectParamArray.GetType().FullName);
            Console.WriteLine(objectParamArray.Length);
            Console.WriteLine(objectParamArray[0]);

}
}

Program.cs

class Program
    {
        static void Main(string[] args)
        {
            object[] objArray = { 100, "Akhil", 200.300 };
            Overload.Display((object)objArray);
            Console.ReadKey();
        }
    }

Output

System.Object[]
1
System.Object[]

5. Conclusion

In this article of our Diving in OOP series we learnt about compile time polymorphism, it is also called early binding or method overloading. We catered most of the scenarios specific to polymorphism.We also learned about the use of powerful params keyword and its use in polymorphism.
To sum up lets list down all the point to remembers once more,
  1. C# recognizes the method by its parameters and not by its name.
  2. The return value/parameter type of a method is never the part of method signature if the names of the methods are same. So this is not polymorphism.
  3. Modifiers such as static are not considered as part of method signature.
  4. The signature of a method consists of its name, number and types of its formal parameters. The return type of a function is not part of the signature. Two methods can not have the same signature and also non-members cannot have the same name as members.
  5. Parameter names should be unique. And also we can not have a parameter name and a declared variable name in the same function as same.
  6. In case of pass by value, the value of the variable is passed and in the case of ref and out, the address of the reference is passed.
  7. This params keyword can only be applied to the last argument of the method.So the n number of parameters can only be at the end.
  8. C# is very smart to recognize if the penultimate argument and the params have the same data type.
  9. Parameter array must be a single dimensional array.
In upcoming articles we’ll cover topics in the same fashion.  Happy Coding.

Read more:

Other Series

My other series of articles:

For more informative articles visit my Blog.

For more technical articles you can reach out to CodeTeddy.

 

 

Complete End to End CRUD Operations Using Knockout.JS and EntityFramework 5 in MVC4 Application


I) Introduction

I have been browsing multiple sites to check if I could find a complete end to end tutorial or article upon CRUD operations using Knockout.JS and MVC 4. Unfortunately, all the ones I found were incomplete or had too short an explanation. In my last article we learned CRUD in ASP.NET web forms using MVC and EntityFramework. This article is the continuation to the same series. This article will be a kind of tutorial to explain how we can set up a Knockout.JS environment in an MVC4 application that is also capable of performing CRUD operations.

II) Our Road-Map

We’ll stick to our agenda of Learning Knockout.JS as follows,

III) Part2: Complete end to end CRUD operations using Knockout.JS and Entity Framework in MVC4 application

We’ll continue to discuss KO step by step in this article
  1. Creating an MVC application.
  2. Creating CRUD action methods using Entity Framework 5.
  3. Perform CRUD operations using MVC4 and Entity Framework 5
  4. Adding Knockout.JS to our MVC application.
  5. Perform CRUD operation using KO in our MVC 4 application.
Before we start, not going very deep into theory I would like to give an introduction to MVC,Entity Framework and Knockout.

IV) MVC

Model: The business entity on which the overall application operates. Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be encapsulated by the Model.
View: The user interface that renders the model into a form of interaction.
Controller: Handles a request from a view and updates the model that results a change in Model’s state.
To implement MVC in .NET we need mainly three classes (View, Controller and the Model).

V) Entity Framework

Let’s have a look on standard definition of Entity Framework given by Microsoft:

“The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. The Entity Framework’s ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals.

In a simple language, Entity framework is an Object/Relational Mapping (ORM) framework. It is an enhancement to ADO.NET, an upper layer to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database.
Hope this gives a glimpse of an ORM and EntityFramework.

VI) Knockout.JS

Knockout.JS (KO) is basically a JS library that enables Declarative Bindings using an ‘Observable’ View Model on the client (browser) following observer pattern approach, enabling UI to bind and refresh itself automatically whenever the data bound is modified. Knockout.JS provides its own templating pattern that helps us to bind our view model data easily. KO works on MVVM pattern i.e. Model-View-View Model.
As the architecture is shown, Views interact with View Models in a two way binding manner i.e. when the model is changed it view updates itself and when view is updated, the model updates itself instantaneously.
KO provides 3 most important features like,

 

The whole idea of KO derives from these three major functionalities. KO also helps in developing Single page applications (SPA’s).SPA’s are out of the box new way of developing rich internet applications(RIA’s) in todays era.

VII) Application Architecture

The architecture is very much self explanatory. The application works on client-server model, where our MVC application or Web API application (not covered in this tutorial) will interact with EntityFramework layer on server side. Entity Framework layer will be responsible for data transactions with data base.
On clientside we have HTML templates which will communicate with server through Ajax calls and the templates will be bind to data via JSON objects through knockout observables (already discussed in first part).

VIII) MVC Application

1. Step1: Create a data base named LearningKO and add a table named student to it, script of the table is as follows,
USE [LearningKO]
GO
/****** Object:  Table [dbo].[Student]    Script Date: 12/04/2013 23:58:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Student](
 [StudentId] [nvarchar](10) NOT NULL,
 [FirstName] [nvarchar](50) NULL,
 [LastName] [nvarchar](50) NULL,
 [Age] [int] NULL,
 [Gender] [nvarchar](50) NULL,
 [Batch] [nvarchar](50) NULL,
 [Address] [nvarchar](50) NULL,
 [Class] [nvarchar](50) NULL,
 [School] [nvarchar](50) NULL,
 [Domicile] [nvarchar](50) NULL,
CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED
(
 [StudentId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age], [Gender], [Batch], [Address], [Class], [School], [Domicile]) VALUES (N'1', N'Akhil', N'Mittal', 28, N'Male', N'2006', N'Noida', N'Tenth', N'LFS', N'Delhi')
INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age], [Gender], [Batch], [Address], [Class], [School], [Domicile]) VALUES (N'2', N'Parveen', N'Arora', 25, N'Male', N'2007', N'Noida', N'8th', N'DPS', N'Delhi')
INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age], [Gender], [Batch], [Address], [Class], [School], [Domicile]) VALUES (N'3', N'Neeraj', N'Kumar', 38, N'Male', N'2011', N'Noida', N'10th', N'MIT', N'Outside Delhi')
INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age], [Gender], [Batch], [Address], [Class], [School], [Domicile]) VALUES (N'4', N'Ekta', N'Mittal', 25, N'Female', N'2005', N' Noida', N'12th', N'LFS', N'Delhi')
  • Step2: Open your Visual Studio (Visual Studio Version should be greater than or equal to 12) and add an MVC Internet application,


 
 
I have given it a name “KnockoutWithMVC4”.
  • Step3: You’ll get a full structured MVC application with default Home controller in the Controller folder. By default the entity framework is downloaded as a package inside application folder, but if not you can add entity framework package by right click the project, select manage nugget packages and search and install Entity Framework,




  • 4. Step 4: Right click project file, select add new item and add ADO.NET entity data model. Follow the steps in the wizard as shown below,



    Generate the model from the data base, select your server and LearningKO database name, the connection string will automatically be added to your Web.Config, name that connection string as LearningKOEntities.

    Select tables to be added to the model. In our case it’s Student Table.


  • Step5: Now add a new controller to the Controller folder, right click controller folder and add a controller named Student. Since we have already created our Datamodel, we can choose for an option where CRUD actions are created by chosen Entity Framework Datamodel,


 
 
  • Name your controller as StudentController,
  • from Scaffolding Options, select “MVC controller with read/write actions and views, using Entity Framework”.
  • Select Model class as Student, that lies in our solution.
  • Select Data context class as LearningKOEntities that is added to outr solution when we added EF data model.
  • Select Razor as rendering engine for views.
  • Click Advanced options, Select Layout or master page and select _Layout.cshtml from the shared folder.
  • Step6: We see out student controller prepared with all the CRUD operation actions as shown below,
    7. using System;
    8. using System.Collections.Generic;
    9. using System.Data;
    10. using System.Data.Entity;
    11. using System.Linq;
    12. using System.Web;
    13. using System.Web.Mvc;
    14. 
    15. namespace KnockoutWithMVC4.Controllers
    16. {
    17.     public class StudentController : Controller
    18.     {
    19.         private LearningKOEntities db = new LearningKOEntities();
    20. 
    21.         //
    22.         // GET: /Student/
    23. 
    24.         public ActionResult Index()
    25.         {
    26.             return View(db.Students.ToList());
    27.         }
    28. 
    29.         //
    30.         // GET: /Student/Details/5
    31. 
    32.         public ActionResult Details(string id = null)
    33.         {
    34.             Student student = db.Students.Find(id);
    35.             if (student == null)
    36.             {
    37.                 return HttpNotFound();
    38.             }
    39.             return View(student);
    40.         }
    41. 
    42.         //
    43.         // GET: /Student/Create
    44. 
    45.         public ActionResult Create()
    46.         {
    47.             return View();
    48.         }
    49. 
    50.         //
    51.         // POST: /Student/Create
    52. 
    53.         [HttpPost]
    54.         [ValidateAntiForgeryToken]
    55.         public ActionResult Create(Student student)
    56.         {
    57.             if (ModelState.IsValid)
    58.             {
    59.                 db.Students.Add(student);
    60.                 db.SaveChanges();
    61.                 return RedirectToAction("Index");
    62.             }
    63. 
    64.             return View(student);
    65.         }
    66. 
    67.         //
    68.         // GET: /Student/Edit/5
    69. 
    70.         public ActionResult Edit(string id = null)
    71.         {
    72.             Student student = db.Students.Find(id);
    73.             if (student == null)
    74.             {
    75.                 return HttpNotFound();
    76.             }
    77.             return View(student);
    78.         }
    79. 
    80.         //
    81.         // POST: /Student/Edit/5
    82. 
    83.         [HttpPost]
    84.         [ValidateAntiForgeryToken]
    85.         public ActionResult Edit(Student student)
    86.         {
    87.             if (ModelState.IsValid)
    88.             {
    89.                 db.Entry(student).State = EntityState.Modified;
    90.                 db.SaveChanges();
    91.                 return RedirectToAction("Index");
    92.             }
    93.             return View(student);
    94.         }
    95. 
    96.         //
    97.         // GET: /Student/Delete/5
    98. 
    99.         public ActionResult Delete(string id = null)
    100.         {
    101.             Student student = db.Students.Find(id);
    102.             if (student == null)
    103.             {
    104.                 return HttpNotFound();
    105.             }
    106.             return View(student);
    107.         }
    108. 
    109.         //
    110.         // POST: /Student/Delete/5
    111. 
    112.         [HttpPost, ActionName("Delete")]
    113.         [ValidateAntiForgeryToken]
    114.         public ActionResult DeleteConfirmed(string id)
    115.         {
    116.             Student student = db.Students.Find(id);
    117.             db.Students.Remove(student);
    118.             db.SaveChanges();
    119.             return RedirectToAction("Index");
    120.         }
    121. 
    122.         protected override void Dispose(bool disposing)
    123.         {
    124.             db.Dispose();
    125.             base.Dispose(disposing);
    126.         }
    127.     }
    128. }


  • 7. Step7: Open App_Start folder and, change the name of controller from Home to Student,

 

the code will become as,
public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: Default”,
url: {controller}/{action}/{id}”,
defaults: new { controller = Student”, action = Index”, id = UrlParameter.Optional }
);
}

 

  • Step8: Now press F5 to run the application, and you’ll see the list of all students we added in to table Student while creating it is displayed. Since the CRUD operations are automatically written, we have action results for display list and other Edit, Delete and Create operations. Note that views for all the operations are created in Views Folder under Student Folder name.
  • Now you can perform all the operations on this list.


    Since I have not provided any validation checks on model or creating an existing student id, the code may break, so I am calling Edit Action in create when we find that id already exists,

    Now create new student ,

    We see that the student is created successfully and added to the list,

    In data base,

    Similarly for Edit,

    Change any field and press save.The change will be reflected in the list and data base,

    For Delete,

    Student Deleted.
    And in database,

    So, that’s it, our first job is completed i.e. to create an MVC application, and perform CRUD operations using Entity Framework 5. You can see that until now we have not written a single line of code. Yes that’s the magic of MVC and EF. Cheers!

    IX) Knockout Application

    Our first job is well done,now moving on to our primary target, i.e. KO. Since KO depends largely on MVVM pattern, we’ll take MVVM at client side, and use our controller to be as same just modified little bit for returning JSON logic. You can learn about MVVM pattern and KO theory in first part of this article series.

    1. Step1:JQuery and Knockout.js files are very important to be in the solution’s script folder. Check to them and if you do not find them, then add the packages for jQuery and Knockout, in the same fashion as you added Entity Framework.Right click project, select “Manage nugget packages” and search for jQuery then install it , then search for knockout package and install it,

    2. Step2: Right click Scripts folder and a folder named ViewModel.Add four js files to that folder, and name them as CreateVM.jsEditVM.jsDeleteVM.js and StudentListVM.js respectively. These are View Model files added to communicate to Controller and render our View templates.
    3. Step3: Add some code to CreateVm.js as,
      var urlPath = window.location.pathname;
      $(function () {
          ko.applyBindings(CreateVM);
      });

    var CreateVM = {
    Domiciles: ko.observableArray([Delhi’, Outside Delhi’]),
    Genders: ko.observableArray([Male’, Female’]),
    Students: ko.observableArray([]),
    StudentId: ko.observable(),
    FirstName: ko.observable(),
    LastName: ko.observable(),
    Age: ko.observable(),
    Batch: ko.observable(),
    Address: ko.observable(),
    Class: ko.observable(),
    School: ko.observable(),
    Domicile: ko.observable(),
    Gender: ko.observable(),
    SaveStudent: function () {
    $.ajax({
    url: /Student/Create’,
    type: post’,
    dataType: json’,
    data: ko.toJSON(this),
    contentType: application/json’,
    success: function (result) {
    },
    error: function (err) {
    if (err.responseText == Creation Failed”)
    { window.location.href = /Student/Index/’; }
    else {
    alert(Status:”+err.responseText);
    window.location.href = /Student/Index/’;;
    }
    },
    complete: function () {
    window.location.href = /Student/Index/’;
    }
    });
    }
    };

    On document load we apply bindings for CreateVM, then inside the view model method we initialize the observables to properties of Student, that will be bind to respective view.You can read more about observables in KO in first part of the series. There is a save function, that sends an ajax request to Student Controller’s Create method, and gets string result. data: ko.toJSON(this), means sending the object in JSON format to controller method.

    Student/Create Controller Method

    Modify the code of controller method of Create, to return JSON to the caller. The HTML templates bound with objects are actually bound to json properties, set in the methods of view model using Knockout Observables.
    The work on observer pattern, so that when model is updated the views automatically gets updated and when views get updated the models update itself, this is called two way binding.

    Controller Code

           [HttpPost]
    public string Create(Student student)
            {
    if (ModelState.IsValid)
                {
    if (!StudentExists(student))
                        db.Students.Add(student);
    else
    return Edit(student);
                    db.SaveChanges();
    return "Student Created";
                }
    return "Creation Failed";
            }

    View Code

    Change the code of the already created views to work with KO,
    For create.cshtml,

    <h2>Create</h2>
    <fieldset>
    <legend>Create Student</legend>

    <div class=”editor-label”>
    Student id
    </div>
    <div class=”editor-field”>
    <input data-bind=”value: StudentId” />
    </div>

    <div class=”editor-label”>
    First Name
    </div>
    <div class=”editor-field”>
    <input data-bind=”value: FirstName” />
    </div>

    <div class=”editor-label”>
    Last Name
    </div>
    <div class=”editor-field”>
    <input data-bind=”value: LastName” />
    </div>

    <div class=”editor-label”>
    Age
    </div>
    <div class=”editor-field”>
    <input data-bind=”value: Age” />
    </div>

    <div class=”editor-label”>
    Gender
    </div>
    <div class=”editor-field”>
    <select data-bind=”options: Genders, value: Gender, optionsCaption: ‘Select Gender…'”></select>
    </div>

    <div class=”editor-label”>
    Batch
    </div>
    <div class=”editor-field”>
    <input data-bind=”value: Batch” />
    </div>

    <div class=”editor-label”>
    Address
    </div>
    <div class=”editor-field”>
    <input data-bind=”value: Address” />
    </div>

    <div class=”editor-label”>
    Class
    </div>
    <div class=”editor-field”>
    <input data-bind=”value: Class” />
    </div>

    <div class=”editor-label”>
    School
    </div>
    <div class=”editor-field”>
    <input data-bind=”value: School” />
    </div>

    <div class=”editor-label”>
    Domicile
    </div>
    <div class=”item “>
    <select data-bind=”options: Domiciles, value: Domicile, optionsCaption: ‘Select Domicile…'”></select>
    </div>

    <p>
    <button type=”button” data-bind=”click: SaveStudent”>Save Student To Database</button>
    </p>
    </fieldset>
    <div>
    <a href=”@Url.Action(“Index”, “Student”)” >Back to List</a>
    </div>

    @section Scripts {
    @Scripts.Render(“~/Scripts/ViewModels/CreateVM.js”)
    }

    You can see I have used data-bind attribute of HTML5 to bind the View elements to View Models properties like data-bind="value: StudentId" , the same applies to all the editable elements. Click button is bound to SaveStudent method of view model.
    At the end of the page we have registered the CreateVM.js view model for this particular view by

    @section Scripts {
        @Scripts.Render("~/Scripts/ViewModels/CreateVM.js")
    }

    Tag.

  • Step3: We do the same set of operations for all the views, View models and Controller method, the code is as below,

For Edit

View Model

Code added in StudentListVM for Edit View Model, since it only perform get when it loads.

Controller methods

public ActionResult Edit(string id=null)
        {
            Student student = db.Students.Find(id);
if (student == null)
            {
return null;
            }
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            ViewBag.InitialData = serializer.Serialize(student); 
return View();
        }

/// <summary>
/// Edits particular student details
/// </summary>
/// <param name=”student”></param>
/// <returns></returns>
[HttpPost]
public string Edit(Student student)
{
if (ModelState.IsValid)
{
db.Entry(student).State = EntityState.Modified;
db.SaveChanges();
return Student Edited”;
}
return Edit Failed”;
}

View

<h2>Edit</h2>
<fieldset>
<legend>Edit Student</legend>

<div class=”editor-label”>
Student id
</div>
<div class=”editor-field”>
<input data-bind=”value: StudentId” readonly=”readonly” />
</div>

<div class=”editor-label”>
First Name
</div>
<div class=”editor-field”>
<input data-bind=”value: FirstName” />
</div>

<div class=”editor-label”>
Last Name
</div>
<div class=”editor-field”>
<input data-bind=”value: LastName” />
</div>

<div class=”editor-label”>
Age
</div>
<div class=”editor-field”>
<input data-bind=”value: Age” />
</div>

<div class=”editor-label”>
Gender
</div>
<div class=”editor-field”>
<select data-bind=”options: Genders, value: Gender, optionsCaption: ‘Select Gender…'”></select>
</div>

<div class=”editor-label”>
Batch
</div>
<div class=”editor-field”>
<input data-bind=”value: Batch” />
</div>

<div class=”editor-label”>
Address
</div>
<div class=”editor-field”>
<input data-bind=”value: Address” />
</div>

<div class=”editor-label”>
Class
</div>
<div class=”editor-field”>
<input data-bind=”value: Class” />
</div>

<div class=”editor-label”>
School
</div>
<div class=”editor-field”>
<input data-bind=”value: School” />
</div>

<div class=”editor-label”>
Domicile
</div>
<div class=”editor-field”>
<select data-bind=”options: Domiciles, value: Domicile, optionsCaption: ‘Select Domicile…'”></select>
</div>
<p>
<button type=”button” data-bind=”click: SaveStudent”>Save Student To Database</button>
</p>
</fieldset>
<div>
<a href=”@Url.Action(“Index”, “Student”)”>Back to List</a>
</div>
@section Scripts {
<script>

$(function () {
ko.applyBindings(EditVM);
});

var initialData = @Html.Raw(ViewBag.InitialData)’; //get the raw json
var parsedJSON = $.parseJSON(initialData); //parse the json client side
var EditVM = {
Domiciles: ko.observableArray([Delhi’, ‘Outside Delhi’]),
Genders: ko.observableArray([Male’, ‘Female’]),
Students: ko.observableArray([]),
StudentId: ko.observable(parsedJSON.StudentId),
FirstName: ko.observable(parsedJSON.FirstName),
LastName: ko.observable(parsedJSON.LastName),
Age: ko.observable(parsedJSON.Age),
Batch: ko.observable(parsedJSON.Batch),
Address: ko.observable(parsedJSON.Address),
Class: ko.observable(parsedJSON.Class),
School: ko.observable(parsedJSON.School),
Domicile: ko.observable(parsedJSON.Domicile),
Gender: ko.observable(parsedJSON.Gender),
SaveStudent: function () {
$.ajax({
url: /Student/Edit’,
type: post’,
dataType: json’,
data: ko.toJSON(this),
contentType: application/json’,
success: function (result) {
},
error: function (err) {
if (err.responseText == Creation Failed”)
{ window.location.href = /Student/Index/’; }
else {
alert(Status:” + err.responseText);
window.location.href = /Student/Index/’;;
}
},
complete: function () {
window.location.href = /Student/Index/’;
}
});
}
};

</script>
}

For Delete

View Model

Code added in StudentListVM for Edit View Model, since it only perform get when it loads.

Controller methods

public ActionResult Delete(string id = null)
        {
            Student student = db.Students.Find(id);
if (student == null)
            {
return null;
            }
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            ViewBag.InitialData = serializer.Serialize(student);
return View();
        }

/// <summary>
/// Delete particular student details
/// </summary>
/// <param name=”student”></param>
/// <returns></returns>
[HttpPost]
public string Delete(Student student)
{
Student studentDetail = db.Students.Find(student.StudentId);
db.Students.Remove(studentDetail);
db.SaveChanges();
return Student Deleted”;
}

View

@model KnockoutWithMVC4.Student

@{
ViewBag.Title = Delete”;
}

Delete Student

Are you sure you want to delete this?

Delete
<div class=display-label”>
Student Id

<div class=display-field”>
<input data-bind=value: StudentId” />

<div class=display-label”>
First Name

<div class=display-field”>
<input data-bind=value: FirstName” />

<div class=display-label”>
Last Name

<div class=display-field”>
<input data-bind=value: LastName” />

<div class=display-label”>
Age

<div class=display-field”>
<input data-bind=value: Age” />

<div class=display-label”>
Gender

<div class=display-field”>
<input data-bind=value: Gender” />

<div class=display-label”>
Batch

<div class=display-field”>
<input data-bind=value: Batch” />

<div class=display-label”>
Address

<div class=display-field”>
<input data-bind=value: Address” />

<div class=display-label”>
Class

<div class=display-field”>
<input data-bind=value: Class” />

<div class=display-label”>
School

<div class=display-field”>
<input data-bind=value: School” />

<div class=display-label”>
Domicile

<div class=display-field”>
<input data-bind=value: Domicile” />

<button type=button” data-bind=click: DeleteStudent”>Delete Student |
<a href=@Url.Action(“Index, “Student)”>Back to List

@section Scripts {

$(function () {
ko.applyBindings(DeleteVM);
});

var initialData = @Html.Raw(ViewBag.InitialData)’; //get the raw json
var parsedJSON = $.parseJSON(initialData); //parse the json client side
var DeleteVM = {
Domiciles: ko.observableArray([Delhi’, Outside Delhi’]),
Genders: ko.observableArray([Male’, Female’]),
Students: ko.observableArray([]),
StudentId: ko.observable(parsedJSON.StudentId),
FirstName: ko.observable(parsedJSON.FirstName),
LastName: ko.observable(parsedJSON.LastName),
Age: ko.observable(parsedJSON.Age),
Batch: ko.observable(parsedJSON.Batch),
Address: ko.observable(parsedJSON.Address),
Class: ko.observable(parsedJSON.Class),
School: ko.observable(parsedJSON.School),
Domicile: ko.observable(parsedJSON.Domicile),
Gender: ko.observable(parsedJSON.Gender),
DeleteStudent: function () {
$.ajax({
url: /Student/Delete’,
type: post’,
dataType: json’,
data: ko.toJSON(this),
contentType: application/json’,
success: function (result) {
},
error: function (err) {
if (err.responseText == Creation Failed”)
{ window.location.href = /Student/Index/’; }
else {
alert(Status:” + err.responseText);
window.location.href = /Student/Index/’;;
}
},
complete: function () {
window.location.href = /Student/Index/’;
}
});
}
};

}

For Index(To display list)

View Model

var urlPath = window.location.pathname;
$(function () {
    ko.applyBindings(StudentListVM);
    StudentListVM.getStudents();
});

//View Model
var StudentListVM = {
Students: ko.observableArray([]),
getStudents: function () {
var self = this;
$.ajax({
type: GET”,
url: /Student/FetchStudents’,
contentType: application/json; charset=utf-8″,
dataType: json”,
success: function (data) {
self.Students(data); //Put the response in ObservableArray
},
error: function (err) {
alert(err.status + : “ + err.statusText);
}
});
},
};

self.editStudent = function (student) {
window.location.href = /Student/Edit/’ + student.StudentId;
};
self.deleteStudent = function (student) {
window.location.href = /Student/Delete/’ + student.StudentId;
};

//Model
function Students(data) {
this.StudentId = ko.observable(data.StudentId);
this.FirstName = ko.observable(data.FirstName);
this.LastName = ko.observable(data.LastName);
this.Age = ko.observable(data.Age);
this.Gender = ko.observable(data.Gender);
this.Batch = ko.observable(data.Batch);
this.Address = ko.observable(data.Address);
this.Class = ko.observable(data.Class);
this.School = ko.observable(data.School);
this.Domicile = ko.observable(data.Domicile);
}

Controller methods

public JsonResult FetchStudents()
        {
            return Json(db.Students.ToList(), JsonRequestBehavior.AllowGet);
        }

View

@model IEnumerable

@{
ViewBag.Title = Index”;
}

Students List

<a href=@Url.Action(“Create, “Student)” >Create Student

 

First NameLast NameAgeGenderBatchAddressClassSchoolDomicile   <tbody data-bind=foreach: Students”>

<td data-bind=”text: StudentId”><td data-bind=text: FirstName”><td data-bind=text: LastName”><td data-bind=text: Age”><td data-bind=text: Gender”><td data-bind=text: Batch”><td data-bind=text: Address”><td data-bind=text: Class”><td data-bind=text: School”><td data-bind=text: Domicile”><a data-bind=click: editStudent”>Edit
<a data-bind=click: deleteStudent”>Delete

Student Id

@section Scripts {
@Scripts.Render(~/Scripts/ViewModels/StudentListVM.js”)
}

The return Json(db.Students.ToList(), JsonRequestBehavior.AllowGet); code returns the student object in json format, for binding to the view.
All set now, you can press F5 to run the application and we see, that application runs in the same manner as it executed before,

Now you can perform all the operations on this list.


Do not type anything else other than int for student id and Age, since validation checks are missing, they may cause error.

Now create new student ,


We see that the student is created successfully and added to the list,

In data base,


Similarly for Edit,

Change any field and press save.The change will be reflected in the list and data base,

For Delete,

Student Deleted.


And in database,

X) Knockout Attributes Glossary

. observable: Used to define model/entity properties. If these properties are bound with user interface and when value for these properties gets updated, automatically the UI elements bound with these properties will be updated with the new value instantaneously.
e.g. this.StudentId = ko.observable("1"); – => StudentId is the observable property. KO represent an object for the Knockout.js library.
The value of the observable is read as var id= this. StudentId ();

· observableArrayobservableArray represents a collection of data elements which required notifications. It’s used to bind with the List kind of elements.

e.g this.Students = ko.observableArray([]);
· applyBindings: This is used to activate knockout for the current HTML document or a specific UI element in HTML document. The parameter for this method is the view-model which is defined in JavaScript. This ViewModel contains the observable, observableArray and various methods.
Various other types of binding are used in this article:
. click: Represents a click event handler added to the UI element so that JavaScript function is called.
. value: This represents the value binding with the UI element’s value property to the property defined into the ViewModel.
The value binding should be used with  ,  , 
. visible: This is used to hide or unhide the UI element based upon the value passed to it’s binding.
. Text: This represent the text value of the parameter passed to the UI element.

XI) Conclusion

In this article of series Learning Knockout, we learned a lot of things about MVC, Entity Framework and Knockout.JS. We did practical hands on by creating a CRUD operations application too.

Therefore we can mark it as tasks done.
We’ll be covering more topics in my upcoming articles.
Note: few of the images in this article are taken via Google search.

Read more:

Other Series

My other series of articles:

For more technical articles you can reach out to CodeTeddy.
Happy Coding Smile | :) .

Introduction to Knockout.js and CRUD Operations in ASP.Net Web Forms Using Knockout.JS


Download Source Code

I) Introduction

The development paradigm has been changing rapidly for a last few years. The out of the box technologies have been introduced to develop applications with fast, scalable, extensible structure, easy to maintain and easy to use. Knockout.JS is also one of the examples of such emerging technologies. I take an opportunity to explain the concept and topic my way.
We’ll be discussing the technology from basic to advanced level by just following a road-map.

II) Our Road-map


We’ll learn Knockout.JS in the following three parts:
  1. Part 1: Introduction to Knockout.js and CRUD Operations in ASP.NET Web Forms using Knockout.JS and Entity Framework.
  2. Part 2: Complete end to end CRUD operations using Knockout.JS and Entity Framework in MVC4 application.

III) Part 1: Introduction to Knockout.js and CRUD Operations in ASP.NET Web Forms using Knockout.JS

We’ll discuss this part by starting with an introduction to knockout, MVVM and observer pattern. Then by setting up a basic environment in knockout.js, thereby creating an ASP.NET web forms application and performing CRUD operations.

IV) Knockout

In today’s changing trend of development, data driven apps depend largely on JavaScript and JS based libraries such as jQuery. The client side programming appears to become more and more complex because the user interface becomes richer. In scenarios like this, the data binding and dependency tracking are highly desirable in the applications for further extensibility of the application. Knockout JS fulfills these rich requirements on client side programming and makes a developers’ life easy and joyful. Let’s discuss KO in detail.

Knockout.JS (KO) is basically a JS library that enables Declarative Bindings using an ‘Observable’ ViewModel on the client (browser) following observer pattern approach, enabling UI to bind and refresh itself automatically whenever the data bound is modified. Knockout.JS provides its own templating pattern that helps us to bind our view model data easily. KO works on MVVM pattern i.e. Model-View-ViewModel.
As the architecture is shown, Views interact with View Models in a two way binding manner, i.e., when model is changed, view updates itself and when view is updated, model too updates itself instantaneously.
KO provides 3 most important features like:
  • Automatic Refresh of UI
  • Two way binding
  • Templating
The whole idea of KO derives from these three major functionalities. KO also helps in developing single page applications (SPAs). SPAs are out of the box new way of developing rich internet applications (RIAs) in today’s era.

V) Model-View-View Model (MVVM)

When we develop a rich UI internet based application, we create Views (UI like HTML and aspx pages) using server controls, HTML controls and then extend our application by writing business logic behind those views like event handling, property binding, creating entities. This approach increases complexities when the application is too large. Here, we require separation of concerns and maintainability of the application, especially on client side.
The MVVM pattern includes three key parts:
  1. Model (Business rule, data access, model classes, Data displayed in UI)
  2. View (User interface (html, aspx, cshtml…))
  3. ViewModel (Event handling, binding, business logic)
Model refers to our application data and domain model, i.e., entities. In a traditional ASP.NET web application, the data is basically stored inside database or files and UI fetches the data using client-server request like Ajax or direct bind itself.
View Model contains the User Interface level operations/methods/functions, performed on model data to bind the outcome to view. The operations include business logic validations and checks to be performed before binding data to UI. View models act as interface between model and views and act as a wrapper over model prior binding to Views.
View is the user interface of our application. View talks to View Model to invoke certain methods/operations as explained above. View gets updated automatically whenever data from the View Model changes.
MVVM provides a clear separation of concerns between the user interface (UI) and the business logic.
In the MVC pattern, a view acts as the broker agent between the Model (the data displayed in the View) and the Controller (server-side endpoint that takes data from the View and performs some action on that data and provides a response.

VI) Observables for Two Way Binding

KO provides Observables in the library to be bound to UI elements and simultaneously code is written to view models, so that when view updates the data the model updates itself and vice versa, for example, in the following code:
<tr>
    <td>Batch :</td>
    <td>
        <input data-bind="value: Batch" /></td>
    <td><span data-bind="text: Batch" /></td>
</tr>
<tr>
    <td>Address :</td>
    <td>
        <input data-bind="value: Address" /></td>
    <td><span data-bind="text: Address" /></td>
</tr>
<tr>
    <td>Class :</td>
    <td>
        <input data-bind="value: Class" /></td>
    <td><span data-bind="text: Class" /></td>
</tr>
The above code shows a part of view, you can see the elements are bound to properties like text and value, these properties are provided by KO, and the right side of these properties are property key names which are bind in view-models with the help of observables like shown below:
    var self = this;
    self.Batch = ko.observable();
    self.Address = ko.observable();
    self.Class = ko.observable();
So this would be the code in View model, anyways we’ll be discussing all this in detail.
NOTE: Data-bind is an HTML5 attribute.

VII) Setting up Environment in Visual Studio for KO

We go step by step to set up Knockout js environment in Visual Studio.
The pre-requisite is Visual Studio must be version greater than or equal to 12. I am using Visual Studio 2013 Express.
Step 1: Open Visual Studio and create a simple ASP.NET application, I have given it a name KOSetup.
 
Step 2: Right click on project, and in context menu select manage Nuget packages to install JQuery and KO.
 
Step 3: Type jQuery in search text box to get the latest compatible jQuery library. Click install to install the library.
 
Step 4: In the similar fashion, search ‘knockout’ in search textbox and install knockoutjs library in your application.
 
Step 5: Our solution will look like we have a folder created named Scripts and that contains jQuery and knockout libraries.
 
Step 6: Now right click the project and add an aspx page, I named that page LearnKO.aspx.
 
Step 7: Similarly create a JavaScript file and add that to the project , I named that file as LearnKO.js.
 
Step 8: Open the learnKO.js file and drag the jQuery file and knockout.js library file to the LearKO.js file, we see in the below picture that reference of both the files is created on the js file. We did this because it will prove us intellisense support for jQuery and knockout on our LearnKO.js file.
 
Step 9: Write document.ready function of jquery in our LearnKO.js file. Document.ready function is fired when our HTML document object model is loaded in browser.
This is all we have to do to setup knockout, now we know how to setup initial environment to use knockout.js in our application.
We proceed now to create the application, talk to database and create template and view model.

VIII) Creating Knockout Application

Step 10: For communication to database, add Entity Framework library in the same manner as we added JQuery and KO, installing Entity Framework library will add the EF DLL to the project. We’ll talk to database using Entity Framework of Microsoft. Alternatively, there are a number of ways to talk to database like ADO.NET, LINQ to SQL, etc. But first things first, create a database you have to use in SQL Server. I’ve provided the script for the same.
Step 11: Right click project and add ADO.NET Entity data Model, click Add, and follow these below steps:
Step 12: Following is step two of Entity Data Model. You can choose model contents from database you already created. So select “Generate From database” option. Click Next.
Step 13: Choose the table you want to add, i.e., Student table as shown below in the figure. Name the model asLearningKOModel. Click Finish.
Step 14: We get certain files in our solution like context and tt files. We also get Student.CS file, that will act as our server side domain model. The context class contains the data communication methods of Entity Framework.
Step 15: Write three methods with the help of Entity Framework in our aspx.cs page. One method to fetch all theStudents and another method to save and delete a student to/from database, as shown below. Mark them as web method so that they could be called from client side.
The code is as follows:
#region Public Web Methods.
        /// <summary>
        /// Gets Student Details
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public static Student[] FetchStudents()
        {
            LearningKOEntities dbEntities = new LearningKOEntities();
            var data = (from item in dbEntities.Students
                        orderby item.StudentId
                        select item).Take(5);
            return data.ToArray();
        }

/// <summary>
/// Saves Student Details
/// </summary>
/// <param name=”data”></param>
/// <returns></returns>
[WebMethod]
public static string SaveStudent(Student[] data)
{
try
{
var dbContext = new LearningKOEntities();
var studentList = from dbStududent in dbContext.Students select dbStududent;
foreach (Student userDetails in data)
{
var student = new Student();
if (userDetails != null)
{
student.StudentId = userDetails.StudentId;
student.FirstName = userDetails.FirstName;
student.LastName = userDetails.LastName;
student.Address = userDetails.Address;
student.Age = userDetails.Age;
student.Gender = userDetails.Gender;
student.Batch = userDetails.Batch;
student.Class = userDetails.Class;
student.School = userDetails.School;
student.Domicile = userDetails.Domicile;
}
Student stud=(from st in studentList where
st.StudentId==student.StudentId select st).FirstOrDefault();
if (stud == null)
dbContext.Students.Add(student);
dbContext.SaveChanges();
}
return Data saved to database!”;
}
catch (Exception ex)
{
return Error: “ + ex.Message;
}
}

/// <summary>
/// Deletes Student Details
/// </summary>
/// <param name=”data”></param>
/// <returns></returns>
[WebMethod]
public static string DeleteStudent(Student data)
{
try
{
var dbContext = new LearningKOEntities();
var student = dbContext.Students.FirstOrDefault
(userId => userId.StudentId == data.StudentId);
if (student != null)
{
if (student != null)
{
dbContext.Students.Remove(student);
dbContext.SaveChanges();
}
}
return Data deleted from database!”;

}
catch (Exception ex)
{
return Error: “ + ex.Message;
}
}
#endregion

 
Step 16: Open the aspx page we created and add the following code to it. The code provides templates in HTML bound to model properties, one to add Student and other displaying Student List.
<table style="width:100%;" >
            <tbody>
                <tr>
                    <th style="width:100px;">Property Name</th>
                    <th style="width:100px;">Enter Value</th>
                    <th style="width:100px;">Example of two Way Binding</th>
                </tr>
                </tbody>
            <tr>
                <td>Student ID (int):</td>
                <td>
                    <input data-bind="value: StudentId" />
                    </td> <!--,valueUpdate:'keypress'-->
                <td><span data-bind="text: StudentId" /></td>
            </tr>
            <tr>
                <td>First Name :</td>
                <td>
                    <input data-bind="value: FirstName" /></td>
                <td  ><span data-bind="text: FirstName" /></td>
            </tr>
            <tr>
                <td>Last Name :</td>
                <td>
                    <input data-bind="value: LastName" /></td>
                <td><span data-bind="text: LastName" /></td>
            </tr>

<tr>
<td>Student Age (int) :</td>
<td>
<input data-bind=”value: Age” /></td>
<td><span data-bind=”text: Age” /></td>
</tr>
<tr>
<td>Gender :</td>
<td>
<select data-bind=”options: Genders, value:
Gender, optionsCaption: ‘Select Gender…'”
></select></td>
<td><span data-bind=”text: Gender” /></td>
</tr>
<tr>
<td>Batch :</td>
<td>
<input data-bind=”value: Batch” /></td>
<td><span data-bind=”text: Batch” /></td>
</tr>
<tr>
<td>Address :</td>
<td>
<input data-bind=”value: Address” /></td>
<td><span data-bind=”text: Address” /></td>
</tr>
<tr>
<td>Class :</td>
<td>
<input data-bind=”value: Class” /></td>
<td><span data-bind=”text: Class” /></td>
</tr>
<tr>
<td>School :</td>
<td>
<input data-bind=”value: School” /></td>
<td><span data-bind=”text: School” /></td>
</tr>
<tr>
<td>Domicile :</td>
<td>
<select data-bind=”options: Domiciles, value:
Domicile, optionsCaption: ‘Select Domicile…'”
></select>
</td>
<td><span data-bind=”text: Domicile” /></td>
</tr>
<tr>
<td colspan=”3″>
<button type=”button” data-bind=”click:
AddStudent”
>Add Student</button>
<button type=”button” data-bind=”click:
SaveStudent”
>Save Student To Database</button>
</td>
</tr>

</table>
</div>

<div style=”width:70%;float:left;display:inline-block;”>
<h2>List of Students</h2>
<table style=”width:100%;” data-bind=”visible:
Students().length > 0″
border=”0″>
<tr>
<th>Student Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Gender</th>
<th>Batch</th>
<th>Address</th>
<th>Class</th>
<th>School</th>
<th>Domicile</th>
</tr>
<tbody data-bind=”foreach: Students”>
<tr>
<td><span data-bind=”text: StudentId” /></td>
<td>
<input data-bind=”value: FirstName” /></td>
<td>
<input data-bind=”value: LastName” /></td>
<td>
<input data-bind=”value: Age” /></td>

<td>
<select data-bind=”options: $root.Genders,
value: Gender”
></select></td>
<td>
<input data-bind=”value: Batch” /></td>
<td>
<input data-bind=”value: Address” /></td>
<td>
<input data-bind=”value: Class” /></td>
<td>
<input data-bind=”value: School” /></td>
<td>
<select data-bind=”options: $root.Domiciles,
value: Domicile”
></select></td>

<td><a href=”#” data-bind=”click: $root.
DeleteStudent”
>Delete</a></td>
</tr>
</tbody>
</table>

There are two HTML tables, one for adding student to database and other showing all the students having delete anchor link to delete the student, these template properties will be bound in view model, where we write method to communicate with data base and call Web Methods we created in aspx.cs page. The Viewmodel also contains observables to be bound to these properties.
Step 17: Now it’s time to create ViewModel, Open the learnKO.js file and add codes to fetch, save and delete student, and observables bound to properties binded on controls of HTML page.
/// <reference path="jquery-2.0.3.min.js" />
/// <reference path="knockout-3.0.0.js" />

function Student(data) {
    this.StudentId = ko.observable(data.StudentId);
    this.FirstName = ko.observable(data.FirstName);
    this.LastName = ko.observable(data.LastName);
    this.Age = ko.observable(data.Age);
    this.Gender = ko.observable(data.Gender);
    this.Batch = ko.observable(data.Batch);
    this.Address = ko.observable(data.Address);
    this.Class = ko.observable(data.Class);
    this.School = ko.observable(data.School);
    this.Domicile = ko.observable(data.Domicile);
}

function StudentViewModel() {
var self = this;
self.Domiciles = ko.observableArray([Delhi’, Outside Delhi’]);
self.Genders = ko.observableArray([Male’, Female’]);
self.Students = ko.observableArray([]);
self.StudentId = ko.observable();
self.FirstName = ko.observable();
self.LastName = ko.observable();
self.Age = ko.observable();
self.Batch = ko.observable();
self.Address = ko.observable();
self.Class = ko.observable();
self.School = ko.observable();
self.Domicile = ko.observable();
self.Gender = ko.observable();

self.AddStudent = function () {
self.Students.push(new Student({
StudentId: self.StudentId(),
FirstName: self.FirstName(),
LastName: self.LastName(),
Domicile: self.Domicile(),
Age: self.Age(),
Batch: self.Batch(),
Address: self.Address(),
Class: self.Class(),
School: self.School(),
Gender: self.Gender()
}));
self.StudentId(),
self.FirstName(),
self.LastName(),
self.Domicile(),
self.Age(),
self.Batch(),
self.Address(),
self.Class(),
self.School(),
self.Gender()
};

self.DeleteStudent = function (student) {

$.ajax({
type: POST”,
url: LearnKO.aspx/DeleteStudent’,
data: ko.toJSON({ data: student }),
contentType: application/json; charset=utf-8″,
success: function (result) {
alert(result.d);
self.Students.remove(student)
},
error: function (err) {
alert(err.status + – “ + err.statusText);
}
});
};

self.SaveStudent = function () {
$.ajax({
type: POST”,
url: LearnKO.aspx/SaveStudent’,
data: ko.toJSON({ data: self.Students }),
contentType: application/json; charset=utf-8″,
success: function (result) {
alert(result.d);
},
error: function (err) {
alert(err.status + – “ + err.statusText);
}
});
};

$.ajax({
type: POST”,
url: LearnKO.aspx/FetchStudents’,
contentType: application/json; charset=utf-8″,
dataType: json”,
success: function (results) {
var students = $.map(results.d, function (item) {
return new Student(item)
});
self.Students(students);
},
error: function (err) {
alert(err.status + – “ + err.statusText);
}
})
}

$(document).ready(function () {
ko.applyBindings(new StudentViewModel());
});

We create StudentViewModel() as our primary view model JavaScript function, that contains all the business logic and operations.
We bind this View model on document ready function by the KO method named applyBindings. This initializes our view model, ko.applyBindings(new StudentViewModel());
Function function Student(data) contains observables bound to model properties.
We can create observable arrays of Domiciles and genders to bind to the dropdown list of our HTML. Ko provides these observables and other such properties to bind to model.
  • observable: Used to define model/entity properties. If these properties are bound with user interface and when value for these properties gets updated, automatically the UI elements bound with these properties will be updated with the new value instantaneously.

E.g. this.StudentId = ko.observable(“1”); - => StudentId is the observable property. KO represent an object for the Knockout.js library.

The value of the observable is read as var id= this. StudentId ();

  • observableArrayobservableArray represents a collection of data elements which required notifications. It’s used to bind with the List kind of elements.
    E.g. this.Students = ko.observableArray([]);
  • applyBindings: This is used to activate knockout for the current HTML document or a specific UI element in HTML document. The parameter for this method is the view-model which is defined in JavaScript. ThisViewModel contains the observableobservableArray and various methods.

 

Various other types of binding are used in this article:
  • click: Represents a click event handler added to the UI element so that JavaScript function is called.
  • value: This represents the value binding with the UI element’s value property to the property defined into theViewModel.
The value binding should be used with :
  • visible: This is used to hide or unhide the UI element based upon the value passed to its binding.
  • Text: This represents the text value of the parameter passed to the UI element.
Step 18: Include js files and stylesheet (you can create your own stylesheet file) to head section of aspx page.
 
Step 19: Press F5 to run the application, and we’ll be shown a page having HTML controls as follows:
List of Students shows the list of students from database, bound to viewmodel’s event.
Try to create a new student and add student, then save it to database, it will automatically be added to the right hand side list.
We can see that Domicile and Genders drop down lists are bound to our Viewmodel’s properties.
Note: Do not give string in StudentId and Age as no validation is put on those fields, code may break.
Create Student:
Student added to list and database:
Job done!
Now you can say that you have become a knockout.js developer.

IX) Conclusion

We learnt a lot in this article about how to set up knockout.js in Visual Studio, lots of theory and also created a sample application just to hands-on the concept. There are numerous articles and blogs related to the same concept, you can explore more and more to learn. In the next article, I’ll explain creating a sample application and performing CRUD operations in MVC4 with knockout js and Entity Framework. Now pat your back to have done a great job by learning a new concept.
Note: Few of the images in this article are taken via Google search.

Complete CRUD Operations in MVC 4 using Entity Framework 5 Without Writing a Single Line of Code


Introduction

In this article, I’ll describe how to perform basic CRUD operations in an MVC4 application with the help of Entity Framework 5 without writing a single line of code. EF and MVC had advanced themselves to the level that we don’t have to put effort in doing extra work.

I) MVC

Model: The business entity on which the overall application operates. Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be encapsulated by the Model.
View: The user interface that renders the model into a form of interaction.
Controller: Handles a request from a view and updates the model that results a change in Model’s state.
To implement MVC in .NET, we need mainly three classes (ViewController and the Model).

II) Entity Framework

Let’s have a look at the standard definition of Entity Framework given by Microsoft:

“The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. The Entity Framework’s ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals.”

In a simple language, Entity framework is an Object/Relational Mapping (ORM) framework. It is an enhancement to ADO.NET, an upper layer to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database.
Hope this gives a glimpse of an ORM and EntityFramework.

III) MVC Application

Step 1: Create a database named LearningKO and add a table named student to it, script of the table is as follows:
USE [LearningKO]
GO
/****** Object: Table [dbo].[Student] Script Date: 12/04/2013 23:58:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Student](
[StudentId] [nvarchar](10) NOT NULL,
[FirstName] [nvarchar](50) NULL,
[LastName] [nvarchar](50) NULL,
[Age] [int] NULL,
[Gender] [nvarchar](50) NULL,
[Batch] [nvarchar](50) NULL,
[Address] [nvarchar](50) NULL,
[Class] [nvarchar](50) NULL,
[School] [nvarchar](50) NULL,
[Domicile] [nvarchar](50) NULL,
CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED
(
[StudentId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, _
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age], _
[Gender], [Batch], [Address], [Class], [School], [Domicile]) _
VALUES (N'1', N'Akhil', N'Mittal', 28, N'Male', N'2006', N'Noida', N'Tenth', N'LFS', N'Delhi')
INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age], _
[Gender], [Batch], [Address], [Class], [School], [Domicile]) _
VALUES (N'2', N'Parveen', N'Arora', 25, N'Male', N'2007', N'Noida', N'8th', N'DPS', N'Delhi')
INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age], _
[Gender], [Batch], [Address], [Class], [School], [Domicile]) _
VALUES (N'3', N'Neeraj', N'Kumar', 38, N'Male', _
N'2011', N'Noida', N'10th', N'MIT', N'Outside Delhi')
INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age], _
[Gender], [Batch], [Address], [Class], [School], [Domicile]) _
VALUES (N'4', N'Ekta', N'Mittal', 25, N'Female', N'2005', N' Noida', N'12th', N'LFS', N'Delhi')

Step 2: Open your Visual Studio (Visual Studio Version should be greater than or equal to 12) and add an MVC Internet application.
I have given it a name “KnockoutWithMVC4”.
Step 3: You’ll get a full structured MVC application with default Home controller in the Controller folder. By default, entity framework is downloaded as a package inside application folder but if not, you can add entity framework package by right clicking the project, select manage nugget packages and search and install Entity Framework.
Step 4: Right click project file, select add new item and add ADO.NET entity data model, follow the steps in the wizard as shown below:
Generate model from database, select your server and LearningKO database name, the connection string will automatically be added to your Web.Config, name that connection string as LearningKOEntities.
Select tables to be added to the model. In our case, it’s Student Table.

Step 5: Now add a new controller to the Controller folder, right click controller folder and add a controller namedStudent. Since we have already created our Datamodel, we can choose for an option where CRUD actions are created by chosen Entity Framework Datamodel:
  • Name your controller as StudentController.
  • From Scaffolding Options, select “MVC controller with read/write actions and views, using Entity Framework”.
  • Select Model class as Student, that lies in our solution.
  • Select Data context class as LearningKOEntities that is added to our solution when we added EF data model.
  • Select Razor as rendering engine for views.
  • Click Advanced options, select Layout or master page and select _Layout.cshtml from the shared folder.

Step 6: We see our student controller prepared with all the CRUD operation actions as shown below:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace KnockoutWithMVC4.Controllers
{
public class StudentController : Controller
{
private LearningKOEntities db = new LearningKOEntities();

//
// GET: /Student/

public ActionResult Index()
{
return View(db.Students.ToList());
}

//
// GET: /Student/Details/5

public ActionResult Details(string id = null)
{
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}

//
// GET: /Student/Create

public ActionResult Create()
{
return View();
}

//
// POST: /Student/Create

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Student student)
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}

return View(student);
}

//
// GET: /Student/Edit/5

public ActionResult Edit(string id = null)
{
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}

//
// POST: /Student/Edit/5

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Student student)
{
if (ModelState.IsValid)
{
db.Entry(student).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(student);
}

//
// GET: /Student/Delete/5

public ActionResult Delete(string id = null)
{
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}

//
// POST: /Student/Delete/5

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string id)
{
Student student = db.Students.Find(id);
db.Students.Remove(student);
db.SaveChanges();
return RedirectToAction("Index");
}

protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}

Step 7: Open App_Start folder and, change the name of controller from Home to Student.
The code will become as:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Student",
action = "Index", id = UrlParameter.Optional }
);
}

Step 8: Now press F5 to run the application, and you’ll see the list of all students we added into table Student while creating it is displayed. Since the CRUD operations are automatically written, we have action results for display list and other Edit, Delete and Create operations. Note that views for all the operations are created in Views Folder underStudent Folder name.
Now you can perform all the operations on this list.
Since I have not provided any validation checks on model or creating an existing student id, the code may break, so I am calling Edit Action in create when we find that id already exists.
Now create new student.
We see that the student is created successfully and added to the list.
In database:
Similarly for Edit:
Change any field and press save. The change will be reflected in the list and database:
For Delete:
Student deleted.
And in database:
Not a single line of code is written till now.

Conclusion

In this tutorial, we learnt to setup environment for MVC and Entity Framework 5 and perform CRUD operations on Student model without writing a single line of code. You can expand the application by adding multiple Controllers, Models and Views.
Note: Few of the images in this article are taken via Google search.
You can follow my articles at csharppulse.blogspot.in.
Happy coding!

LINQ Interview Questions (All in One)


I. Introduction

This article explains some of the main and important concepts of LINQ and C#. The article explains LINQ in detail, and covers almost every concept of LINQ and C# 2.0 and 3.0. This is an effort to put together the important concepts in one place to make it easy to follow. I will explain the topics by giving simple examples, rather than explaining too much theory behind the examples.

II. Pre-requisites

  • The reader of this article should be aware of the LINQ term.
  • The reader should have basic knowledge of SQL.
  • The reader should know how to code in C#.

III. Overview

LINQ is so dynamic that it could be described in several ways as:
  • LINQ is a uniform programming model for any kind of data. LINQ enables you to query and manipulate data with a consistent model that is independent from data sources.
  • LINQ is just another tool for embedding SQL queries into code.
  • LINQ is yet another data abstraction layer.

IV. What Is LINQ?

In my terms, LINQ is actually a methodology that simplifies and unifies the implementation of any kind of data access. LINQ does not force you to use a specific architecture; it facilitates the implementation of several existing architectures for accessing data.
LINQ is a programming model that introduces queries as a first-class concept into any Microsoft .NET language. However, complete support for LINQ requires some extensions in the language used.
These extensions boost productivity, thereby providing a shorter, meaningful, and expressive syntax to manipulate data.
Examining a simple LINQ query:
var query = from c in Customers
                     where c.Country == "Italy"
                     select c.CompanyName;
The SQL-like syntax used in LINQ is called a query expression, but remember LINQ is not the same as embedded SQL.

V. How LINQ Works Internally

When we look at the following query expression:
Customer[] Customers = GetCustomers();
var query = from c in Customers where c.Country == "Italy“ select c;
When the compiler compiles the above code, it generates the following code:
Customer[] Customers = GetCustomers();
IEnumerable query =
Customers .Where( c => c.Country == "Italy" );
Look at another query expression:
var query = from c in Customers
where c.Country == "Italy“ orderby c.Name
select new { c.Name, c.City };
and the code when compiled:
var query = Customers.Where( c => c.Country == "Italy" ).OrderBy( c => c.Name ).Select
( c => new { c.Name, c.City } );
Therefore, we see the compiler internally treats this SQL type query as a simple C# lambda expressions query.
One important thing about LINQ to keep in mind is that a LINQ query is not really executed until there is access to the query result, this is also called on demand loading or lazy loading,
Example:
1. var query = from c in Customers ...
      foreach ( string name in query ) ...

2. var query = from c in Customers …
List customers = query.ToList();

In both the above mentioned examples, the LINQ query does not execute in the first line actually, it is executed in the second line when that query variable is actually addressed or used. Write a code and try it yourself.

VI. Relational Model vs. Hierarchical/Graph Model

LINQ works on relational and hierarchical model. Rather than explaining theory, I would explain the concept with these examples:
  • In a relational model:
    var query = from c in Customers join o in Orders on c.CustomerID equals o.CustomerID
    select new {  c.CustomerID, c.CompanyName, o.OrderID };
  • In a hierarchical model:
    var query = from c in Customers from o in c.Orders
    select new {  c.Name, o.Quantity, o.Product. ProductName  };
The above two statements clearly state both the models, if you are aware of SQL queries, you can get the above given examples.
Follow the below mentioned scenarios.

A. Type declarations with simple relationships

class Customer
{
 public string Name;
 public string City;

public Order[] Orders;
}

public class Order
{
public int Quantity;
public Product Product;
}

public class Product
{
public int ProductId;
public decimal Price;
public string ProductName;
}

B. Type declarations with two-way relationships

public class Customer
{
public string Name;
public string City;
public Order[] Orders;
}

public class Order
{
public int Quantity;
public Product Product;
public Customer Customer;
}

public class Product
{
public int ProductId;
public decimal Price;
public string ProductName;
public Order[] Orders;
}

C. Querying the graph of objects

var query = from p in products where p.ProductId == 3 from o in p.Orders
select o;
  • If you have entity relationships in your data model, you can still use explicit relationships in a LINQ:
    var query = from c in Customers join s in Suppliers on c.City equals s.City
    select new { c.City, c.Name, SupplierName = s.Name };

    And something like the following will be returned:

    City=Torino Name=Marco SupplierName=Trucker
    City=Dallas Name=James SupplierName=FastDelivery
    City=Dallas Name=James SupplierName=Horizon
    City=Seattle Name=Frank SupplierName=WayFaster
  • LINQ can return a hierarchy or graph of objects for a SQL query that contains several entities with one or more one-to-many relationships:
    var query = from c in Customers join s in _
    Suppliers on c.City equals s.City into customerSuppliers
    select new { c.City, c.Name, customerSuppliers };

Here is how the hierarchized results might appear:

City=Torino Name=Marco customerSuppliers=...
customerSuppliers: Name=Trucker City=Torino
City=Dallas Name=James customerSuppliers=...
customerSuppliers: Name=FastDelivery City=Dallas
customerSuppliers: Name=Horizon City=Dallas
City=Seattle Name=Frank customerSuppliers=...
customerSuppliers: Name=WayFaster City=Seattle
  • LINQ requires to describe your data in terms of entities that are also types in the language.
  • A LINQ query, it is always a set of operations on instances of some classes.
  • These objects might be the real container of data, or they might be a simple description (in terms of metadata) of the external entity one is going to manipulate.
  • A query can be sent to a database through an SQL command only if it is applied to a set of types that map tables and relationships contained in the database.
  • The conversion of all these operations in SQL commands is the responsibility of the LINQ engine.
  • Class declaration mapped on a database table:
[Table("Products")]
public class Product
{

[Column(IsPrimaryKey=true)]
public int IdProduct;
[Column(Name=UnitPrice”)]
public decimal Price;
[Column()]
public string ProductName;

[Column()]
public bool Taxable;
[Column()]
public decimal Tax;
}

D. Database update calling the SubmitChanges() method

Example:
var taxableProducts = from p in db.Products where p.Taxable == true select p;

foreach( Product product in taxableProducts ) { RecalculateTaxes( product ); }
db.SubmitChanges();

VII. XML Manipulation

LINQ has a different set of classes and extensions to support the manipulation of XML data.
e.g. A fragment of an XML file of orders:
<?xml version="1.0" encoding="utf-8" ?>
<orders xmlns="http://schemas.devleap.com/Orders">
<order idCustomer="ALFKI" idProduct="1" quantity="10" price="20.59"/>
<order idCustomer="ANATR" idProduct="5" quantity="20" price="12.99"/>
<order idCustomer="KOENE" idProduct="7" quantity="15" price="35.50"/>
 </orders>

A. Reading the XML file of orders using an XmlReader

String nsUri = "http://schemas.devleap.com/Orders";
XmlReader xmlOrders = XmlReader.Create( "Orders.xml" );
List orders = new List();

Order order = null;

while (xmlOrders.Read())
{

switch (xmlOrders.NodeType)
{
case XmlNodeType.Element:

if ((xmlOrders.Name == order”) && (xmlOrders.NamespaceURI == nsUri))
{

order = new Order();
order.CustomerID = xmlOrders.GetAttribute( idCustomer” );

order.Product = new Product();
order.Product.IdProduct = Int32.Parse
( xmlOrders.GetAttribute( idProduct” ) );
order.Product.Price = Decimal.Parse
( xmlOrders.GetAttribute( price” ) );
order.Quantity = Int32.Parse
( xmlOrders.GetAttribute( quantity” ) );
orders.Add( order );
}
break;
}
}

B. An XQuery like the following one to select nodes

for $order in document("Orders.xml")/orders/order return $order

C. Reading the XML file using LINQ to XML

XDocument xmlOrders = XDocument.Load( "Orders.xml" );
XNamespace ns = "http://schemas.devleap.com/Orders";
var orders = from o in xmlOrders.Root.Elements( ns + "order" )
select new Order {
CustomerID = (String)o.Attribute( "idCustomer" ),
Product = new Product {
IdProduct = (Int32)o.Attribute("idProduct"), Price = (Decimal)o.Attribute("price")
},
Quantity = (Int32)o.Attribute("quantity")
};

VIII. Language Integration

Language integration is a fundamental aspect of LINQ. It allows you to write code such as the following:
var query =
from c in Customers
where c.Country == "Italy" orderby c.Name
select new { c.Name, c.City };
Instead of writing this code:
var query = Customers
.Where( c => c.Country == "Italy" )
.OrderBy( c => c.Name )
.Select( c => new { c.Name, c.City } );
  • LINQ enables a more declarative style of coding for C# and Visual Basic.
  • In SQL, we describe what you want. In C#, we describe how to obtain the expected result.
  • Declarative programming can take advantage of services offered by compilers and frameworks, and in general, it is easier to read and maintain.
  • This single “feature” can be the most important one because it boosts programmers’ productivity.

IX. Type Checking

Another important aspect of language integration is type checking. Whenever data is manipulated by LINQ, no unsafe cast is necessary. Data is always strongly typed, including both the queried collections and the single entities that are read and returned.
This enables the use of Visual Studio features such as IntelliSense and Refactoring, even with LINQ queries.

X. Transparency Across Different Type Systems

The type system of the Microsoft .NET Framework and the type system of SQL Server are different. Using LINQ, we give precedence to the .NET type system because it is the one supported by any language that hosts a LINQ query. It is necessary to convert many types of data between these two worlds. LINQ handles this conversion for you automatically, making the differences in type systems almost completely transparent to the programmer.

XI. LINQ Flavors

LINQ is a technology that covers many data domains. Some of these domains are included in those “LINQ Flavors” that Microsoft provides as part of the .NET 3.5 Framework, as shown below:

XII. LINQ to Objects

LINQ to Objects has the goal of manipulating collections of objects, which can be related to each other to form a hierarchy or a graph. From a certain point of view, LINQ to Objects is the default implementation used by a LINQ query. LINQ to Objects is enabled including the System.Linq namespace.

XIII. LINQ to ADO.NET

LINQ to ADO.NET includes different LINQ implementations that share the need to manipulate relational data. It includes other technologies that are specific to each particular persistence layer:
  • LINQ to SQLHandles the mapping between custom types in C# and the physical table schema
  • LINQ to EntitiesIs in many ways similar to LINQ to SQL. However, instead of using the physical database as a persistence layer, it uses a conceptual Entity Data Model (EDM). The result is an abstraction layer that is independent from the physical data layer.
  • LINQ to DataSetMakes it possible to query a DataSet using LINQ

XIV. LINQ to XML

LINQ to XML offers a slightly different syntax that operates on XML data, allowing query and data manipulation.This query corresponds to the following C# 3.0 syntax:
var book =
new XElement( "Book",
new XAttribute( "Title", "Introducing LINQ" ), from person in team
where person.Role == "Author“ select new XElement( "Author", person.Name ) );

XV. C#2 and C#3 Important Language Features

1. C# 2.0 Revisited – Generics

You must be aware of this concept very well, but I wanted to cover this in my way taking simple examples.
Let’s take Min() function of C# for example,

Problem

The Min function, following is the issue:
int Min( int a, int b )
{ if (a < b) return a; else return b; }
object Min( object a, object b )
{ if (a < b) return a; else return b; }
IComparable Min( IComparable a, IComparable b )
{ if (a.CompareTo( b ) < 0) return a; else return b; }
int a = 5, b = 10;
int c = (int) Min( a, b );
I hope you got the issue, yes type casting.
C# 2.0 solved this problem with generics. The basic principle of generics is that type resolution is moved from the C# compiler to the jitter. Here is the generic version of the Min function:

Solution

T Min( T a, T b ) where T : IComparable {
                           if (a.CompareTo( b ) < 0) return a;
    else return b;
}

2. C# 2.0 Revisited – Delegates

delegate is a class that encapsulates one or more method. Internally, one delegate stores a list of method pointers, each of which can be paired with a reference to an instance of the class containing an instance method.
delegate can be declared as:
delegate void SimpleDelegate(); delegate int ReturnValueDelegate();
delegate void TwoParamsDelegate( string name, int age );
  • In C# 1.X, Delegates were instantiated as:
    public class DemoDelegate { void MethodA() { … }
    int MethodB() { … }

    void MethodC( string x, int y ) { … }

    void CreateInstance() {

    SimpleDelegate a = new SimpleDelegate( MethodA );
    ReturnValueDelegate b = new ReturnValueDelegate ( MethodB );

    TwoParamsDelegate c = new TwoParamsDelegate(

    MethodC ); // … } }

  • Delegate instantiation in C# 2.0:
    public class DemoDelegate
     {
    void MethodA() { … }

    int MethodB() { … }

    void MethodC( string x, int y ) { … }

    void CreateInstance() {
    SimpleDelegate a = MethodA;
    ReturnValueDelegate b = MethodB;
    TwoParamsDelegate c = MethodC; //
    }

    // … }

3. C# 2.0 Revisited – Anonymous Methods

  • Using an anonymous method:
    public class DemoDelegate {
    void Repeat10Times( SimpleDelegate someWork )
    { for (int i = 0; i < 10; i++) someWork(); }
    void Run2() {
    int counter = 0;
    this.Repeat10Times( delegate { Console.WriteLine("C# chapter" );
    counter++; } );
    Console.WriteLine( counter ); } // … }
  • Parameters for an anonymous method:
    public class DemoDelegate {

    void Repeat10Times( TwoParamsDelegate callback )
    { for (int i = 0; i < 10; i++)

    callback( Linq book”, i ); }

    void Run3() { Repeat10Times(

    delegate( string text, int age )

    { Console.WriteLine( {0} {1}”, text, age ); } );

    }

    // … }

4. C# 2.0 Revisited – Enumerators and Yield

a. IEnumerator and IEnumerable declarations

public interface IEnumerator
    {
bool MoveNext();
object Current { get; }
void Reset();
    }

public interface IEnumerable
{
IEnumerator GetEnumerator();
}

C# 2.0 introduced the yield statement through which the compiler automatically generates a class that implements the IEnumerator interface returned by the GetEnumerator method. The yield statement can be used only immediately before a return or break keyword. Enumeration using a yield statement:
public class CountdownYield : IEnumerable {
public int StartCountdown;

public IEnumerator GetEnumerator() {
for (int i = StartCountdown – 1; i >= 0; i–)
{
yield return i; }
}
}

b. Multiple yield statements

             public class CountdownYieldMultiple : IEnumerable
               {
                     public IEnumerator GetEnumerator() {

yield return 4;
yield return 3;
yield return 2;
yield return 1;
yield return 0;

}
}

c. Enumeration using yield (typed)

public class CountdownYieldTypeSafe : IEnumerable<int> {
public int StartCountdown;

IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); }

public IEnumerator<int> GetEnumerator() {

for (int i = StartCountdown – 1; i >= 0; i–)

{ yield return i; }
}
}

5. C# 3.0 Features – Local Type Inference

C# 3.0 offers type inference that allows us to define a variable by using the var keyword instead of a specific type. This might seem to be equivalent to defining a variable of type object, but it is not.
     var a = 2; //a is declared as int
     object b = 2; // Boxing an int into an object
     int C = a; // No cast, no unboxing
     int D = (int)b // Cast is required, an unboxing is done
  • When var is used, the compiler infers the type from the expression used to initialize the variable. The compiled IL code contains only the inferred type.
  • In other words, consider this code:
      int a = 5;
      var b = a;
  • It is perfectly equivalent to this example:
      int a = 5;
      int b = a;
  • The var keyword can be used only within a local scope.
  • In other words, a local variable can be defined in this way, but not a member or a parameter.
  • The following code shows some examples of valid uses of var:
    public void ValidUse( decimal d )
      {
        var x = 2.3; // double
    
        var y = x; // double
        var r = x / y; // double
    
        var s = "sample"; // string
        var l = s.Length; // int
        var w = d; // decimal
    
        var p = default(string); // string
    }
  • The sample shows some cases in which the var keyword is not allowed:
    class VarDemo {

    // invalid token ‘var’ in class, struct or interface member declaration

    var k =0;

    // type expected in parameter list

    public void InvalidUseParameter( var x ){} // type expected in result type declaration
    public var InvalidUseResult() { return 2; }

    public void InvalidUseLocal() {

    var x; // Syntax error, ‘=’ expected

    var y = null; // Cannot infer local variable type from ‘null’
    }
    // … }

6. C# 3.0 Features – Lambda Expressions

C# 2.0 introduced the capability to “pass a pointer to some code” as a parameter by using anonymous methods. This concept is a powerful one, but what you really pass in this way is a reference to a method, not exactly a piece of code. That reference points to strongly typed code that is generated at compile time. Using generics, we can obtain more flexibility, but it is hard to apply standard operators to a generic type.
C# 3.0 introduces lambda expressions, which allow the definition of anonymous methods using more concise syntax. Lambda expressions can also optionally postpone code generation by creating an expression tree that allows further manipulation before code is actually generated, which happens at execution time.
Lambda expression examples:
• ( int a, int b ) => { return a + b; } // Explicitly typed, statement body
• ( int a, int b ) => a + b; // Explicitly typed, expression body

• ( a, b ) => { return a + b; } // Implicitly typed, statement body
• ( a, b ) => a + b // Implicitly typed, expression body

• ( x ) => sum += x // Single parameter with parentheses
• x => sum += x // Single parameter no parentheses

• () => sum + 1 // No parameters
Some lambda expressions have a particular name based on their purpose. A predicate is a Boolean expression that is intended to indicate membership of an element in a group. For example, it is used to define how to filter items inside a loop:
// Predicate

 age ) => age > 21
A projection is an expression that returns a type different from the type of its single parameter:
// Projection: takes a string and returns an int
 ( s ) => s.Length
  • Lambda expression as a predicate:
    public static void Demo() {
    string[] names = { "Marco", "Paolo", "Tom" }; 
    Display( names, s => s.Length > 4 ); }
    public static void Display( T[] names, Func<T, bool> filter ){
    foreach( T s in names) {
    if (filter( s )) Console.WriteLine( s ); }
    }
  • A lambda expression can also be assigned to a variable of these delegate types:
    public delegate T Func();
    public delegate T Func( A0 arg0 );
    public delegate T Func( A0 arg0, A1 arg1 );
    public delegate T Func( A0 arg0, A1 arg1, A2 arg2 );
    public delegate T Func( A0 arg0, A1 arg1, A2 arg2, A3 arg3 );

7. C# 3.0 Features – Extension Methods

C# 3.0 introduces a syntax that conceptually extends an existing type (either reference or value) by adding new methods without deriving it into a new type. The methods that extend a type can use only the public members of the type itself, just as you can do from any piece of code outside the target type.
An extension method must be static and public, must be declared inside a static class, and must have the keyword this before the first parameter type, which is the type that the method extends.
Extension methods are public because they can be (and normally are) called from outside the class where they are declared.
However, the result type of the extension method might be the extended type itself.
LINQ very frequently uses extension methods in this way.
The following code shows a traditional approach to writing two methods (FormattedUS and FormattedIT) that converts a decimal value into a string formatted with a specific culture:
static class Traditional {
public static void Demo() {
decimal x = 1234.568M;
Console.WriteLine( FormattedUS( x ) );

Console.WriteLine( FormattedIT( x ) );
}

public static string FormattedUS( decimal d ) {
return String.Format( formatIT, {0:#,0.00}”, d );
}
public static string FormattedIT( decimal d ) {
return String.Format( formatUS, {0:#,0.00}”, d );
}

static CultureInfo formatUS = new CultureInfo( en-US” );
static CultureInfo formatIT = new CultureInfo( it-IT” );
}

a. Extension methods declaration

using System;
using System.Globalization;

internal static class ExtensionMethods
{
public static void Demo()
{
decimal x = 1234.568M;
Console.WriteLine(x.FormattedUS());
Console.WriteLine(x.FormattedIT());
Console.WriteLine(FormattedUS(x)); // Traditional call allowed
Console.WriteLine(FormattedIT(x));// Traditional call allowed
}

private static CultureInfo formatUS = new CultureInfo(en-US”);
private static CultureInfo formatIT = new CultureInfo(it-IT”);

public static string FormattedUS(this decimal d)
{
return String.Format(formatIT, {0:#,0.00}”, d);
}

public static string FormattedIT(this decimal d)
{
return String.Format(formatUS, {0:#,0.00}”, d);
}
}

b. Extension methods for native value types

static class ExtensionMethods {
public static decimal Double( this decimal d ) { return d + d; }
public static decimal Triple( this decimal d ) { return d * 3; }
public static decimal Increase( this decimal d ) { return ++d; }
public static decimal Decrease( this decimal d ) { return --d; }
public static decimal Half( this decimal d ) { return d / 2; } //}
Extension methods call order:
decimal x=14M,y= 14M;
x = Half(Triple(Decrease(Decrease(Double(Increase(x) )))) );
y = y.Increase().Double().Decrease().Decrease().Triple().Half( );
  • An extension method is not automatically considered. Its resolution follows some rules.
  • Here is the order of evaluation used to resolve a method for an identifier.
  • Instance method: If an instance method exists, it has priority.
  • Extension method: The search for an extension method is made through all static classes in the “current namespace” and in all namespaces included in active using directives.

c. Extension methods resolution

public class A
{
    public virtual void X() { }
}
public class B : A
{
    public override void X() { }
    public void Y() { }
}
static public class E
{
    static void X(this A a) { }
    static void Y(this A b) { }
    public static void Demo() {
A a = new A();
B b = new B();
A c = new B();
a.X(); // Call A.X
b.X(); // Call B.X
c.X(); // Call B.X
a.Y(); // Call E.Y
b.Y(); // Call B.Y
c.Y(); // Call E.Y }
}

d. Lambda expression as predicate

public static void Display( this T[] names, Func<T, bool> filter ) {…}

public static void Demo() {

string[] names = { Marco”, Paolo”, Tom” };
names.Display( s => s.Length > 4 );// It was: Display( names, s => s.Length > 4 );

}

8. C# 3.0 Features – Object Initialization Expressions

C# 3.0 introduces a shorter form of object initialization syntax that generates functionally equivalent code:
// Implicitly calls default constructor before object initialization
Customer customer = new Customer { Name = "Marco", Country = "Italy" };

a. Explicit constructor call in object initializer

// Explicitly specify constructor to call before object initialization
Customer c1 = new Customer() { Name = "Marco", Country = "Italy" };
// Explicitly specify nondefault constructor
Customer c2 = new Customer( "Paolo", 21 ) { Country = "Italy" };

b. Nested object initializers

public class Point
{
    private int x, y;

public int X
{
get { return x; }
set { x = value; }
}

public int Y
{
get { return y; }
set { y = value; }
}
}

public class Rectangle
{
private Point tl, br;

public Point TL
{
get { return tl; }
set { tl = value; }
}

public Point BR
{
get { return br; }
set { br = value; }
}
}

// Possible code inside a method
Rectangle r = new Rectangle { TL = new Point { X = 0, Y = 1 },BR = new Point { X = 2, Y = 3 } };

c. Initializers for owned objects

public class Rectangle { Point tl = new Point(); Point br = new Point();

public Point TL { get { return tl; } } public Point BR { get { return br; } } }

// Possible code inside a method
Rectangle r = new Rectangle { TL = { X = 0, Y = 1 },BR = { X = 2, Y = 3 } };

d. Collection initializers

//Collection classes that implement ICollection
List<int> integers = new List<int> { 1, 3, 9, 18 };
List list = new List {

new Customer( Jack”, 28 ) { Country = USA”}, new Customer { Name = Paolo” },

new Customer { Name = Marco”, Country = Italy” }
};

//Collection classes that implement IEnumerable
ArrayList integers = new ArrayList() { 1, 3, 9, 18 };
ArrayList list = new ArrayList {

new Customer( Jack”, 28 ) { Country = USA”}, new Customer { Name = Paolo” },

new Customer { Name = Marco”, Country = Italy” }
};

9. C# 3.0 Features – Anonymous Types

An object initializer can also be used without specifying the class that will be created with the new operator.
Doing that, a new class-an anonymous type-is created.
Consider the example shown below:
Customer c1 = new Customer { Name = "Marco" };
 var c2 = new Customer { Name = "Paolo" };

var c3 = new { Name = Tom”, Age = 31 };
var c4 = new { c2.Name, c2.Age };

var c5 = new { c1.Name, c1.Country };
var c6 = new { c1.Country, c1.Name };

When you do GetType() – the following is the output that is generated:
c1 is Customer c2 is Customer c3 is:
f__AnonymousType0`2[System.String,System.Int32] c4 is
f__AnonymousType0`2[System.String,System.Int32] c5 is
 f__AnonymousType5`2[System.String,System.String] c6 is
f__AnonymousTypea`2[System.String,System.String]

10. C# 3.0 Features – Query Expressions

C# 3.0 also introduces query expressions, which have a syntax similar to the SQL language and are used to manipulate data. This syntax is converted into regular C# 3.0 syntax that makes use of specific classes, methods, and interfaces that are part of the LINQ libraries.

XVI. LINQ Syntax Fundamentals

1. LINQ Query Expression

The following code shows a prototype of the full syntax of a LINQ query expression:
query-expression ::=
from-clause query-body query-body
::= join-clause* (from-clause join-clause* | let-clause | where-clause)*
orderby-clause? (select-clause | groupby-clause) query-continuation?
from-clause ::= from itemName in srcExpr _
select-clause ::= select selExpr groupby-clause ::= group selExpr by keyExpr
The first from clause can be followed by zero or more fromlet, or where clauses.
let clause applies a name to the result of an expression, while a where clause defines a filter that will be applied to include specific items in the results. Each from clause is a generator that represents an iteration over a sequence on which query operators (such as the extension methods of System.Linq.Enumerable) are applied.
let-clause ::= let itemName = selExpr where-clause ::= where predExpr
from clause can be followed by any number of join clauses. The final select or group clause can be preceded by an orderby clause that applies an ordering to the results:
join-clause ::= join itemName in srcExpr on keyExpr equals keyExpr (into itemName)?

orderby-clause ::= orderby (keyExpr (ascending | descending)?)* _
query-continuation ::= into itemName query-body.

XVII. Conclusion

Long post, I guess we covered a lot of concepts deeply. You can learn more theory from MSDN or other renowned community sites. We covered very important and deep concepts of LINQ, C#2.0 and C# 3.0.
Happy coding!
To read more informative articles on C#, ASP.NET and MVC, follow A Practical Approach.

Continue reading “LINQ Interview Questions (All in One)”

Web Services and Windows Services Interview Questions


WebServices And Windows Services

Can you give an example of when it would be appropriate to use a web service as opposed to non-serviced .NET component
Web service is one of main component in Service Oriented Architecture. You could use web services when your clients and servers are running on different networks and also different platforms. This provides a loosely coupled system. And also if the client is behind the firewall it would be easy to use web service since it runs on port 80 (by default) instead of having some thing else in Service Oriented Architecture applications.
What is the standard you use to wrap up a call to a Web service
“SOAP.

What is the transport protocol you use to call a Web service SOAP HTTP with SOAP
What does WSDL stand for? “WSDL stands for Web Services Dsescription Langauge. There is WSDL.exe that creates a .wsdl Files which defines how an XML Web service behaves and instructs clients as to how to interact with the service.
eg: wsdl http://LocalHost/WebServiceName.asmx
Where on the Internet would you look for Web Services?http://www.uddi.org

What does WSDL stand for? Web Services Description Language

True or False: To test a Web service you must create a windows application or Web application to consume this service? False.

What are the various ways of accessing a web service ?

1.Asynchronous Call
Application can make a call to the Webservice and then continue todo watever oit  wants to do.When the service is ready it will notify the application.Application  can use BEGIN and END method to make asynchronous call to the webmethod.We can use  either a WaitHandle or a Delegate object when making asynchronous call.
The WaitHandle class share resources between several objects. It provides several  methods which will wait for the resources to become available
The easiest and most powerful way to to implement an asynchronous call is using a  delegate object. A delegate object wraps up a callback function. The idea is to  pass a method in the invocation of the web method. When the webmethod has finished  it will call this callback function to process the result
2.Synchronous Call
Application has to wait until execution has completed.
 Note: Few of the references are taken from other sites/sources
 
What are VSDISCO files?VSDISCO files are DISCO files that support dynamic discovery of Web services. If you place the following VSDISCO file in a directory on your Web server, for example, it returns   references to all ASMX and DISCO files in the host directory and any subdirectories not noted in elements:
                <DYNAMICDISCOVERY
                  xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">
                  <EXCLUDE path="_vti_cnf" />
                  <EXCLUDE path="_vti_pvt" />
                  <EXCLUDE path="_vti_log" />
                  <EXCLUDE path="_vti_script" />
                  <EXCLUDE path="_vti_txt" />
                </DYNAMICDISCOVERY>
 
How does dynamic discovery work?ASP.NET maps the file name extension VSDISCO to an HTTP handler that scans the host  directory and subdirectories for ASMX and DISCO files and returns a dynamically generated DISCO document. A client who requests a VSDISCO file gets back what appears to be a static DISCO document.
Note that VSDISCO files are disabled in the release version of ASP.NET. You can reenable them by uncommenting the line   in the section of Machine.config that maps *.vsdisco to System.Web.Services.Discovery.DiscoveryRequestHandler and granting the ASPNET  user account permission to read the IIS metabase. However, Microsoft is actively discouraging the use of VSDISCO files because they could represent a threat to Web server security.
 
Is it possible to prevent a browser from caching an ASPX page?
Just call SetNoStore on the HttpCachePolicy object exposed through the Response object’s Cache property, as demonstrated here:
        <%@ Page Language="C#" %>

<%
Response.Cache.SetNoStore ();
Response.Write (DateTime.Now.ToLongTimeString ());
%>

SetNoStore works by returning a Cache-Control: private, no-store header in the HTTP response. In this example, it prevents caching of a Web page that shows the current time.
What does AspCompat=”true” mean and when should I use it?
AspCompat is an aid in migrating ASP pages to ASPX pages. It defaults to false but should be set to true in any ASPX file that creates apartment-threaded COM objects–that is, COM objects registered ThreadingModel=Apartment. That includes all COM objects written with  Visual Basic 6.0. AspCompat should also be set to true (regardless of threading  model)  if the page creates COM objects that access intrinsic ASP objects such as Request and Response. The following directive sets AspCompat to true:
 <%@ Page AspCompat="true" %>
Setting AspCompat to true does two things. First, it makes intrinsic ASP objects available      to the COM components by placing unmanaged wrappers around the equivalent ASP.NET objects. Second, it improves the performance of calls that the page places to apartment- threaded COM objects by ensuring that the page (actually, the thread that processes the  request for the page) and the COM objects it creates share an apartment. AspCompat=”true” forces ASP.NET request threads into single-threaded apartments (STAs). If those threads create COM objects marked ThreadingModel=Apartment, then the objects are created in the same STAs as the threads that created them. Without AspCompat=”true,” request threads run in a multithreaded apartment (MTA) and each call to an STA-based COM object incurs a performance hit when it’s  marshaled across apartment boundaries.
Do not set AspCompat to true if your page uses no COM objects or if it uses COM objects that don’t access ASP intrinsic objects and that are registered ThreadingModel=Free or  ThreadingModel=Both.
Can two different programming languages be mixed in a single ASMX file?
No.
 
What namespaces are imported by default in ASMX files?
The following namespaces are imported by default. Other namespaces must be imported manually.· System, System.Collections,System.ComponentModel,System.Data, System.Diagnostics,System.Web,System.Web.Services
How do I provide information to the Web Service when the information is required as a SOAP Header?
The key here is the Web Service proxy you created using wsdl.exe or through Visual Studio .NET’s Add Web Reference menu option. If you happen to download a WSDL file for a Web Service that requires a SOAP header, .NET will create a SoapHeader class in the proxy source file. Using the previous example:
      public class Service1 : System.Web.Services.Protocols.SoapHttpClientProtocol
        {   
            public AuthToken AuthTokenValue;

[System.Xml.Serialization.XmlRootAttribute(Namespace=http://tempuri.org/&#8221;, IsNullable=false)]
public class AuthToken : SoapHeader { public string Token; }}

In this case, when you create an instance of the proxy in your main application file, you’ll also create an instance of the AuthToken class and assign the string:

     Service1 objSvc = new Service1();
     processingobjSvc.AuthTokenValue = new AuthToken();
     objSvc.AuthTokenValue.Token = <ACTUAL token value>;
     Web Servicestring strResult = objSvc.MyBillableWebMethod();
 
What is WSDL?
WSDL is the Web Service Description Language, and it is implemented as a specific XML vocabulary. While it’s very much more complex than what can be described here, there are two important aspects to WSDL with which you should be aware. First, WSDL provides instructions to consumers of Web Services to describe the layout and contents of the SOAP packets  the Web Service intends to issue. It’s an interface description document, of sorts. And second, it isn’t intended that you  read and interpret the WSDL. Rather, WSDL should be processed by machine, typically to generate proxy source code (.NET) or create dynamic proxies on the fly (the SOAP Toolkit or Web Service Behavior).
What is a Windows Service and how does its lifecycle differ from a “standard” EXE?
Windows service is a application that runs in the background. It is equivalent to a NT service.
The executable created is not a Windows application, and hence you can’t just click and run it . it needs to be installed as a service, VB.Net has a facility where we can add an installer to our program and then use a utility to install the service. Where as this is not the case with standard exe

How can a win service developed in .NET be installed or used in Win98?
Windows service cannot be installed on Win9x machines even though the .NET framework runs on machine.

 
Can you debug a Windows Service? How ? 
Yes we can debug a Windows Service.
Attach the WinDbg debugger to a service after the service starts
This method is similar to the method that you can use to attach a debugger to a process and then debug a process.
Use the process ID of the process that hosts the service that you want to debug
  1. To determine the process ID (PID) of the process that hosts the service that you want to debug, use one of the following methods.
    • Method 1: Use the Task Manager
      1. Right-click the taskbar, and then click Task Manager. The Windows Task Manager dialog box appears.
      2. Click the Processes tab of the Windows Task Manager dialog box.
      3. Under Image Name, click the image name of the process that hosts the service that you want to debug. Note the process ID of this process as specified by the value of the corresponding PID field.
    • Method 2: Use the Task List Utility (tlist.exe)
      1. Click Start, and then click Run. The Run dialog box appears.
      2. In the Open box, type cmd, and then click OK.
      3. At the command prompt, change the directory path to reflect the location of the tlist.exe file on your computer.Note The tlist.exe file is typically located in the following directory: C:\Program Files\Debugging Tools for Windows
      4. At the command prompt, type tlist to list the image names and the process IDs of all processes that are currently running on your computer.

    Note Make a note of the process ID of the process that hosts the service that you want to debug.

  2. At a command prompt, change the directory path to reflect the location of the windbg.exe file on your computer.Note If a command prompt is not open, follow steps a and b of Method 1. The windbg.exe file is typically located in the following directory: C:\Program Files\Debugging Tools for Windows.
  3. At the command prompt, type windbg –p ProcessID to attach the WinDbg debugger to the process that hosts the service that you want to debug.
Note ProcessID is a placeholder for the process ID of the process that hosts the service that you want to debug.

Use the image name of the process that hosts the service that you want to debug

You can use this method only if there is exactly one running instance of the process that hosts the service that you want to run. To do this, follow these steps:

  1. Click Start, and then click Run. The Run dialog box appears.
  2. In the Open box, type cmd, and then click OK to open a command prompt.
  3. At the command prompt, change the directory path to reflect the location of the windbg.exe file on your computer.Note The windbg.exe file is typically located in the following directory: C:\Program Files\Debugging Tools for Windows.
  4. At the command prompt, type windbg –pn ImageName to attach the WinDbg debugger to the process that hosts the service that you want to debug.
NoteImageName is a placeholder for the image name of the process that hosts the service that you want to debug. The “-pn” command-line option specifies that the ImageName command-line argument is the image name of a process. back to the top
Start the WinDbg debugger and attach to the process that hosts the service that you want to debug
  1. Start Windows Explorer.
  2. Locate the windbg.exe file on your computer.Note The windbg.exe file is typically located in the following directory: C:\Program Files\Debugging Tools for Windows
  3. Run the windbg.exe file to start the WinDbg debugger.
  4. On the File menu, click Attach to a Process to display the Attach to Process dialog box.
  5. Click to select the node that corresponds to the process that hosts the service that you want to debug, and then click OK.
  6. In the dialog box that appears, click Yes to save base workspace information. Notice that you can now debug the disassembled code of your service.
Configure a service to start with the WinDbg debugger attached
You can use this method to debug services if you want to troubleshoot service-startup-related problems.
1 Configure the “Image File Execution” options. To do this, use one of the following methods:
  • Method 1: Use the Global Flags Editor (gflags.exe)
    1. Start Windows Explorer.
    2. Locate the gflags.exe file on your computer.Note The gflags.exe file is typically located in the following directory: C:\Program Files\Debugging Tools for Windows.
    3. Run the gflags.exe file to start the Global Flags Editor.
    4. In the Image File Name text box, type the image name of the process that hosts the service that you want to debug. For example, if you want to debug a service that is hosted by a process that has MyService.exe as the image name, type MyService.exe.
    5. Under Destination, click to select the Image File Options option.
    6. Under Image Debugger Options, click to select the Debugger check box.
    7. In the Debugger text box, type the full path of the debugger that you want to use. For example, if you want to use the WinDbg debugger to debug a service, you can type a full path that is similar to the following: C:\Program Files\Debugging Tools for Windows\windbg.exe
      h. Click Apply, and then click OK to quit the Global Flags Editor.
  • Method 2: Use Registry Editor
    1. Click Start, and then click Run. The Run dialog box appears.
    2. In the Open box, type regedit, and then click OK to start Registry Editor.
    3. Warning If you use Registry Editor incorrectly, you may cause serious problems that may require you to reinstall your operating system. Microsoft cannot guarantee that you can solve problems that result from using Registry Editor incorrectly. Use Registry Editor at your own risk.In Registry Editor, locate, and then right-click the following registry subkey:
      HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
    4. Point to New, and then click Key. In the left pane of Registry Editor, notice that New Key #1 (the name of a new registry subkey) is selected for editing.
    5. Type ImageName to replace New Key #1, and then press ENTER.Note ImageName is a placeholder for the image name of the process that hosts the service that you want to debug. For example, if you want to debug a service that is hosted by a process that has MyService.exe as the image name, type MyService.exe.
    6. Right-click the registry subkey that you created in step e.
    7. Point to New, and then click String Value. In the right pane of Registry Editor, notice that New Value #1, the name of a new registry entry, is selected for editing.
    8. Replace New Value #1 with Debugger, and then press ENTER.
    9. Right-click the Debugger registry entry that you created in step h, and then click Modify. The Edit String dialog box appears.
    10. In the Value data text box, type DebuggerPath, and then click OK.

    Note DebuggerPath is a placeholder for the full path of the debugger that you want to use. For example, if you want to use the WinDbg debugger to debug a service, you can type a full path that is similar to the following: C:\Program Files\Debugging Tools for Windows\windbg.exe

2 For the debugger window to appear on your desktop, and to interact with the debugger, make your service interactive. If you do not make your service interactive, the debugger will start but you cannot see it and you cannot issue commands. To make your service interactive, use one of the following methods:
  • Method 1: Use the Services console
    1. Click Start, and then point to Programs.
    2. On the Programs menu, point to Administrative Tools, and then click Services. The Services console appears.
    3. In the right pane of the Services console, right-click ServiceName, and then click Properties.Note ServiceName is a placeholder for the name of the service that you want to debug.
    4. On the Log On tab, click to select the Allow service to interact with desktop check box under Local System account, and then click OK.
  • Method 2: Use Registry Editor
    1. In Registry Editor, locate, and then click the following registry subkey:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ServiceName
      Note Replace ServiceName with the name of the service that you want to debug. For example, if you want to debug a service named MyService, locate and then click the following registry key:
      HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyService
    2. Under the Name field in the right pane of Registry Editor, right-click Type, and then click Modify. The Edit DWORD Value dialog box appears.
    3. Change the text in the Value data text box to the result of the binary OR operation with the binary value of the current text and the binary value, 0x00000100, as the two operands. The binary value, 0x00000100, corresponds to the SERVICE_INTERACTIVE_PROCESS constant that is defined in the WinNT.h header file on your computer. This constant specifies that a service is interactive in nature.
3 When a service starts, the service communicates to the Service Control Manager how long the service must have to start (the time-out period for the service). If the Service Control Manager does not receive a “service started” notice from the service within this time-out period, the Service Control Manager terminates the process that hosts the service. This time-out period is typically less than 30 seconds. If you do not adjust this time-out period, the Service Control Manager ends the process and the attached debugger while you are trying to debug. To adjust this time-out period, follow these steps:
  1. In Registry Editor, locate, and then right-click the following registry subkey: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
  2. Point to New, and then click DWORD Value. In the right pane of Registry Editor, notice that New Value #1 (the name of a new registry entry) is selected for editing.
  3. Type ServicesPipeTimeout to replace New Value #1, and then press ENTER.
  4. Right-click the ServicesPipeTimeout registry entry that you created in step c, and then click Modify. The Edit DWORD Value dialog box appears.
  5. In the Value data text box, type TimeoutPeriod, and then click OKNote TimeoutPeriod is a placeholder for the value of the time-out period (in milliseconds) that you want to set for the service. For example, if you want to set the time-out period to 24 hours (86400000 milliseconds), type 86400000.
  6. Restart the computer. You must restart the computer for Service Control Manager to apply this change.
4 Start your Windows service. To do this, follow these steps:
  1. Click Start, and then point to Programs.
  2. On the Programs menu, point to Administrative Tools, and then click Services. The Services console appears.
  3. In the right pane of the Services console, right-click ServiceName, and then click Start.
Note ServiceName is a placeholder for the name of the service that you want to debug.
 Note: Few of the references are taken from other sites/sources
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=3631&lngWId=10