Tuesday, 1 October 2013

use of mongo DB in MVC

using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace MVCMongo.Models
{
    public class Department
    {
        public ObjectId _id { get; set; }
        public int DepartmentId { get; set; }
        public string DepartmentName { get; set; }
    }
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }

    }

    public class MongoDBEntities : DbContext
    {
        public MongoDBEntities() : base("name=MongoConnection") { }
        static MongoServer server = MongoServer.Create(ConfigurationManager.ConnectionStrings["MongoConnection"].ConnectionString.ToString());
        MongoDatabase database = server.GetDatabase("MVCMongo");

        List<Department> department;
        public List<Department> Departments
        {
            get
            {
                var collection = database.GetCollection<Department>("Department");
                return collection.FindAllAs<Department>().ToList();
            }
            set { department = value; }
        }
        public void CreateDepartment(Department colleciton)
        {
            try
            {
                int Id = 0;
                if (Departments.Count() > 0)
                    Id = Departments.Max(x => x.DepartmentId);
                Id += 1;
                MongoCollection<Department> MCollection = database.GetCollection<Department>("Department");
                BsonDocument doc = new BsonDocument {
                    {"DepartmentId",Id},
                    {"DepartmentName",colleciton.DepartmentName}
                };

                IMongoQuery query = Query.EQ("DepartmentName", colleciton.DepartmentName);
                var exists = MCollection.Find(query);
                if (exists.ToList().Count == 0)
                    MCollection.Insert(doc);

            }
            catch { }
        }
        public void EditDepartment(Department collection)
        {
            try
            {
                MongoCollection<Department> MCollection = database.GetCollection<Department>("Department");
                IMongoQuery query = Query.EQ("DepartmentId", collection.DepartmentId);
                IMongoUpdate update = MongoDB.Driver.Builders.Update.Set("DepartmentName", collection.DepartmentName);
                MCollection.Update(query, update);
            }
            catch { }
        }
        public void DeleteDepartment( Department collection)
        {
            try
            {
                MongoCollection<Department> MCollection = database.GetCollection<Department>("Department");
                IMongoQuery query = Query.EQ("_id", collection._id);
                MCollection.Remove(query);
            }
            catch { }
        }

    }
}
Add connection string in web.config file
<configuration>
  <connectionStrings>
       <add name="MongoConnection" connectionString="Server=localhost:27017" />
  </connectionStrings>
</configuration>

What is the difference between IEnumerable and IEnumerator?



Both IEnumerable<T> and IEnumerator<T> are help to loop through collections i.e List<T>, Array List etc.
IEnumerable<T> actually uses IEnumerator<T>. IEnumerable<T> has GetEnumerator () function which returns IEnumerator<T> collection.

IEnumerable<T>
IEnumerator<T>
IEnumerable<T> does not remember currently which row is currently iterating through.
IEnumerator <T> remember its currently cursor state.
If you loop sequentially through collections then best use is IEnumerable<T>.
If we pass collection from one method to another and required to remember current cursor position then best use is IEnumerator <T>.

Q. What is the difference between IEnumerable<T> and IQueryable<T>?
Ans:
IEnumerable<T>
IQueryable<T>
IEnumerable<T> exists in System.Collections Namespace.
IQueryable<T> exists in System.Linq Namespace.
While query data from database, IEnumerable<T>
execute select query on server side, load data in-memory on client side and then filter data.
While query data from database, IQueryable<T> execute select query on server side with all filters.
IEnumerable<T> is suitable for LINQ to Object and LINQ to XML queries.
IQueryable<T> is suitable for LINQ to SQL queries.
When you deal with in memory collections (like List<T>, Array List etc) then best use is IEnumerable<T>.
When you want to deal with Sql server, linq to sql, entity framework and other data sources which implemented iqueryable then best use is IQueryable<T>.

Q. What is IList<T>?
Ans:
  IList<T> is an interface.
  Lists and arrays implement IList<T>.
  When you want to pass array or List<T> to any method then IList<T> can be used to hold those values.  
  When method need to add, remove, clear elements from the collection? Use IList<T>.



json details



JSON
·         JSON stands for JavaScript Object Notation. Shortly, it is a data representation format.
·         It is a lightweight data interchange format for creating objects that is a part of and built into javascript.
·         JSON provides a simple alternative to the Fatty XML format for data representation.

Example:
JSON Objects:
JSON objects are written inside curly brackets. Objects can contain multiple key/values pairs. Each key is a property of the JSON object.

var obj1 = { name : "Amit", age : 20, country : "India" };
var obj2 = { name : "John", age : 23, country : "US" };
var obj3 = { name : "Alex", age : 28, country : "France" };
var obj4 = { u1 : obj1, u2 : obj2, u3 : obj3 };

document.write(obj2.name);             //  result : John
document.write(obj4.u3. country);      //  result : France
document.write(obj4["obj1"]["Name"]);  //  result : Amit
JSON Array:

var meats = ["beef", "pork", "lamb"];
var fruits = ["apple", "orange", "grape", "plumb"];
var jsonobj = { arr1: meats, arr2: fruits };

document.write(jsonobj.arr1[0]);  //  result: beef
document.write(jsonobj.arr2[2]);  //  result: grape

Array of JSON objects:
var obj = [{ Dept: "Software", Employees: ["subrat", "ajit", "rakesh"] },
           { Dept: "Sales", Employees: ["amit", "suresh", "deepak"] },
           { Dept: "Marketing", Employees: ["sujit", "shankar", "aditya"] }];

document.write(obj[2].Dept);         //  result: Marketing
document.write(obj[1].Employees[2]); //  result: deepak

WCF Details



Web Service

  Web Service is an application that is designed to interact directly with other applications over the internet.
  Web Service consumers are able to invoke method calls on remote objects by using SOAP and HTTP over the Web.
  Web Service is language independent.
  Web Services communicate by using standard web protocols and data formats. For e.g.

·         HTTP
·         XML
·         SOAP

Advantages of Web Service

Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.

Examples for Web Service

Weather Reporting: You can use Weather Reporting web service to display weather information in your personal website.
Stock Quote: You can display latest update of Share market with Stock Quote on your web site.
News Headline: You can display latest news update by using News Headline Web Service in your website.

In summary you can use any web service which is available to use. You can make your own web service and let others use it. Example you can make Free SMS Sending Service with footer with your advertisement, so whosoever use this service indirectly advertise your company... You can apply your ideas in N no. of ways to take advantage of it.

Frequently used word with web services

What is SOAP?

SOAP (simple object access protocol) is a remote function calls that invokes method and execute them on Remote machine and translate the object communication into XML format. In short, SOAP are way by which method calls are translate into XML format and sent via HTTP.

What is WSDL? 

WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return.
WSDL contains every detail regarding using web service and Method and Properties provided by web service and URLs from which those methods can be accessed and Data Types used.

What is UDDI?

UDDI allows you to find web services by connecting to a directory.


What is WCF (windows communication foundation) Service?

Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined feature of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.

Advantages of WCF

1.       WCF is interoperable with other services when compared to .Net Remoting where the client and service have to be .Net.
2.       WCF services provide better reliability and security in compared to ASMX web services.
3.       In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
4.       WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.

Difference between WCF and Web service

Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service; following table provides detailed difference between them.

Features
Web Service
WCF
Hosting
It can be hosted in IIS
It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming
[WebService] attribute has to be added to the class
[ServiceContract] attribute has to be added to the class
Model
[WebMethod] attribute represents the method exposed to client
[OperationContract] attribute represents the method exposed to client
Operation
One-way, Request- Response are the different operations supported in web service
One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML
System.Xml.serialization name space is used for serialization
System.Runtime.Serialization namespace is used for serialization
Encoding
XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom
XML 1.0, MTOM, Binary, Custom
Transports
Can be accessed through HTTP, TCP, Custom
Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols
Security
Security, Reliable messaging, Transactions





A WCF Service is composed of three components parts,

1.       Service Class - A WCF service class implements some service as a set of methods.
2.       Host Environment - A Host environment can be a Console application or a Windows Service or a Windows Forms application or IIS as in case of the normal asmx web service in .NET.
3.       Endpoints - WCF Service is a program that exposes a collection of Endpoints. All communications with the WCF service will happen via the endpoints.

The endpoint is composed of 3 parts (collectively called as ABC's of endpoint) as defines below:

"A" stands for Address: Where is the service?
"B" stands for Binding: How can we talk to the service?
"C" stands for Contract: What can the service do for us?

AddressBasically URL, specifies where this WCF service/Endpoint is hosted .Client will use this url to connect to the service.                                                 
                                Ex: http://localhost:8090/MyService/SimpleCalculator.svc

Binding: The endpoints also define a binding that specifies how a client will communicate with the service and the address where the endpoint is hosted.

Different bindings supported by WCF

Binding
Description
BasicHttpBinding
Basic Web service communication. No security by default
WSHttpBinding
Web services with WS-* support. Supports transactions
WSDualHttpBinding
Web services with duplex contract and transaction support
WSFederationHttpBinding
Web services with federated security. Supports transactions
MsmqIntegrationBinding
Communication directly with MSMQ applications. Supports transactions
NetMsmqBinding
Communication between WCF applications by using queuing. Supports transactions
NetNamedPipeBinding
Communication between WCF applications on same computer. Supports duplex contracts and transactions
NetPeerTcpBinding
Communication between computers across peer-to-peer services. Supports duplex contracts
NetTcpBinding
Communication between WCF applications across computers. Supports duplex contracts and transactions

Contract: The endpoints specify a Contract that defines which methods of the Service class will be accessible via the endpoint; each endpoint may expose a different set of methods. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client.


Different contracts in WCF

Service Contract

Service contracts describe the operation that service can provide. For Eg, a Service provide to know the temperature of the city based on the zip code, this service is called as Service contract. It will be created using Service and Operational Contract attribute.

Data Contract

Data contract describes the custom data type which is exposed to the client. This defines the data types, which are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or data types cannot be identified by the client e.g. Employee data type. By using Data Contract we can make client to be aware of Employee data type that are returning or passing parameter to the method.

Message Contract

Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

Fault Contract

Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error occurred in the service to client. This helps us to easy identity, what error has occurred.

Example:

Endpoints will be mentioned in the web.config file on the created service.
<system.serviceModel>
    <services>
      <service name="MathService" behaviorConfiguration="MathServiceBehavior">
        <endpoint address="http://localhost:8090/MyService/MathService.svc"
                  contract="IMathService" binding="wsHttpBinding"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
Service Host

Service Host object is in the process of hosting the WCF service and registering endpoints. It loads the service configuration endpoints, apply the settings and start the listeners to handle the incoming request. System.ServiceModel.ServiceHost namespace hold this object. This object is created while self-hosting the WCF service.

In the below example you can find that WCF service is self hosted using console application.

//Creating uri for the hosting the service
Uri uri = new Uri("http://localhost/CategoryService");
//Creating the host object for MathService
  ServiceHost host = new ServiceHost(typeof(CategoryService), uri);
//Adding endpoint to the Host object
  host.AddServiceEndpoint(typeof(ICategoryService),new WSHttpBinding(), uri);
  host.Open(); //Hosting the Service
  Console.WriteLine("Waiting for client invocations");
  Console.ReadLine();
  host.Close();

Message and Channel

 

Message


WCF Message is the unit of data exchange between client and service. It consists of several parts, including a body and headers.

WCF Runtime


WCF runtime is the set of object responsible for sending and receiving message. For example formatting the message, applying security and transmitting and receiving message using various protocol.

 

Channels:


Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as

 

Transport Channels


Handles sending and receiving message from network. Protocols like HTTP, TCP name pipes and MSMQ.

 

Protocol Channels


Implements SOAP based protocol by processing and possibly modifying message. e.g. WS-Security and WS-Reliability.

 

WCF Client and Metadata

 

WCF Client


WCF client is a client application creates to expose the service operations as method. Any application can host a WCF client, including an application that host a service. Therefore it is possible to create a service that includes WCF clients of other services.

A client application is a managed application that uses a WCF client to communicate with another application. To create a client application for a WCF service requires the following steps:

1.       Get the Proxy class and service end point information
Using SvcUtil.exe we can create proxy class for the service and configuration information for endpoints. Example type the following sentence in the Visual studio command prompt, this will generate the class file and configuration file which contain information about the endpoints.
svcutil /language:vb /out:ClientCode.vb /config:app.config http://localhost:8090/MyService/SimpleCalculator.svc?wsdl
2.       Call operations
Add this class files in the client application. Then create the object for this class and invoke the service operation. Configuration information we got from the above step has to be added to the client application configuration file. When the client application calls the first operation, WCF automatically opens the underlying channel. This underlying channel is closed, when the object is recycled.
//Creating the proxy on client side
MyCalculatorServiceProxy.MyServiceProxy proxy 
= new MyCalculatorServiceProxy.MyServiceProxy();
 Console.WriteLine("Counter: " + proxy.MyMethod());
3.       Close the WCF client object
After using the object created in the above steps, we have to dispose the object. Channel will be closed with the service, when the object is cleared.

Metadata


Characteristics of the service are described by the metadata. This metadata can be exposed to the client to understand the communication with service. Metadata can be set in the service by enabling the ServiceMetadata node inside the servcieBehaviour node of the service configuration file.

 
 
 
 
 
 
 
<system.serviceModel>
    <services>
      <service name="MathService"
        behaviorConfiguration="MathServiceBehavior">
        <endpoint address="" contract="IMathService"
          binding="wsHttpBinding"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
    <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
 
This metadata can be viewed while creating WCF client application using SvcUtil.exe



WCF Architecture

 

The following figure illustrates the major components of WCF.


Figure 1: WCF Architecture

Contracts


Contracts layer are next to that of Application layer. Developer will directly use this contract to develop the service. We are also going to do the same now. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system.

 

Service contracts


Describe about the operation that service can provide. Example, Service provided to know the temperature of the city based on the zip code, this service we call as Service contract. It will be created using Service and Operational Contract attribute.

 

Data contract


It describes the custom data type which is exposed to the client. This defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or datatype cannot be identified by the client e.g. Employee data type. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method.

 

Message Contract


Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

 

Policies and Binding


Specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding.

 

Service Runtime


It contains the behaviors that occur during runtime of service.
  • Throttling Behavior- Controls how many messages are processed.
  • Error Behavior - Specifies what occurs, when internal error occurs on the service.
  • Metadata Behavior - Tells how and whether metadata is available to outside world.
  • Instance Behavior - Specifies how many instance of the service has to be created while running.
  • Transaction Behavior - Enables the rollback of transacted operations if a failure occurs.
  • Dispatch Behavior - Controls how a message is processed by the WCF Infrastructure.

 

 


Messaging


Messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as
  • Transport Channels
Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.
  • Protocol Channels
Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.

 

Activation and Hosting


Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF service can be hosted by following mechanism
  • IIS
Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.
  • Windows Activation Service
(WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.
  • Self-Hosting
WCF service can be self-hosted as console application, Win Forms or WPF application with graphical UI.
  • Windows Service
WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).