Monday 31 March 2014

Insert and Show Data in GridView using WCF in ASP.NET

Ans:-
Here insert data into DB and Get Data from DB using WCF web services. In below UI of the application..



For this create one Website as->File->New Website->Give Website Name as WcfTesting->ok
                                              ->select Wcf Services from new template
                                              ->automatically 4 files will create in Solution Explorer
                                             ->as I) Service.cs and IService.cs in App_Code folder
                                                     II)App_Data folder
                                                     III)Service and Web.config file.

Then write code in

IService.cs:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: If you change the interface name "IService" here, you must also update the reference to "IService" in Web.config.
[ServiceContract]
public interface IService
{

[OperationContract]
    List<TestDetails> GetTestData();

[OperationContract]
    string InsertGetTestData(TestDetails testInfo);

// TODO: Add your service operations here
}

// Use a data contract as illustrated in the sample below to add composite types to service operations.
public class TestDetails
{
    int id;
    string name = string.Empty;
    string descrptn = string.Empty;
 
    [DataMember]
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    [DataMember]
    public int Id
    {
        get { return id; }
        set { id = value; }
    }
    [DataMember]
    public string Descrptn
    {
        get { return descrptn; }
        set { descrptn = value; }
    }
}

Web.Config:-

<connectionStrings>
<add name="conStr" connectionString="server=.;database=subsdb;user id=sa;pwd=123"/></connectionStrings>

Service.cs:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

// NOTE: If you change the class name "Service" here, you must also update the reference to "Service" in Web.config and in the associated .svc file.
public class Service : IService
{
    private string strConnection = ConfigurationManager.ConnectionStrings["conStr"].ToString();
    public List<TestDetails> GetTestData()
    {
        List<TestDetails> testdetails = new List<TestDetails>();
        using (SqlConnection con = new SqlConnection(strConnection))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from test", con);
         
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TestDetails testInfo = new TestDetails();
                    testInfo.Id = Convert.ToInt32(dt.Rows[i]["id"].ToString());
                    testInfo.Name = dt.Rows[i]["name"].ToString();
                    testInfo.Descrptn = dt.Rows[i]["descrptn"].ToString();

                    testdetails.Add(testInfo);
                }
            }
            con.Close();
        }
        return testdetails;
    }
    public string InsertGetTestData(TestDetails testInfo)
    {
        string strMessage = string.Empty;
        using (SqlConnection con = new SqlConnection(strConnection))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into test(id,name,descrptn) values(@id,@name,@descrptn)", con);
            cmd.Parameters.AddWithValue("@id", testInfo.Id);
            cmd.Parameters.AddWithValue("@name", testInfo.Name);
            cmd.Parameters.AddWithValue("@descrptn", testInfo.Descrptn);

            int result = cmd.ExecuteNonQuery();
            if (result == 1)
            {
                strMessage = testInfo.Id + " Details inserted successfully";
            }
            else
            {
                strMessage = testInfo.Name + " Details not inserted successfully";
            }
            con.Close();
        }
        return strMessage;
    }

}

After Completion upto this Build this Website and then run and copy that url For consuming this services to another Web application/Console application...

So i am creating another Website here to consume above WCF services.

For this create one Website as->File->New Website->Give Website Name as Website1->ok
                                              ->add new Item->In here add New Web Page from new template
                                                as(Default.aspx)

For consuming above services into this website,Right click and select Add Service References and then Paste above copied link and then clicked go.....and then give service name as....ServiceReference1.And then add this ServiceReference1 to Namespace.

Then write code in

Default.aspx:-

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call Wcf Service to the Website Page</title>
</head>
<body>
    <form id="form1" runat="server">
   <div>
<table align="center">
<tr>
<td colspan="2" align="center">
<b>User Registration</b>
</td>
</tr>
<tr>
<td>
ID:
</td>
<td>
<asp:TextBox ID="txtId" runat="server"/>
</td>
</tr>
<tr>
<td>
Name:
</td>
<td>
<asp:TextBox ID="txtName" runat="server"/>
</td>
</tr>
<tr>
<td>
Desc:
</td>
<td>
<asp:TextBox ID="txtDesc" runat="server"/>
</td>
</tr>

<tr>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblResult" runat="server"/>
</td>
</tr>
<tr>
<td colspan="2">
<asp:GridView runat="server" ID="gvDetails" AutoGenerateColumns="false">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField HeaderText="ID" DataField="id" />
<asp:BoundField HeaderText="Name" DataField="name" />
<asp:BoundField HeaderText="Description" DataField="descrptn" />

</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
 
Default.aspx.cs:-

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using ServiceReference1;

public partial class _Default : System.Web.UI.Page
{

    ServiceReference1.ServiceClient proxy = new ServiceClient();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindTestDetails();
        }
    }
    void BindTestDetails()
    {
        List<TestDetails> testdetails = new List<TestDetails>();

        gvDetails.DataSource = proxy.GetTestData();
        gvDetails.DataBind();
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        TestDetails testInfo = new TestDetails();
        testInfo.Id = Convert.ToInt32(txtId.Text);
        testInfo.Name = txtName.Text;
        testInfo.Descrptn = txtDesc.Text;

        string result = proxy.InsertGetTestData(testInfo);
        lblResult.Text = result;
        BindTestDetails();
        txtId.Text = string.Empty;
        txtName.Text = string.Empty;
        txtDesc.Text = string.Empty;
        }
}



Create Table:-

create table test(id int,name varchar(30),descrptn varchar(30))




Tuesday 25 March 2014

Get/Download Data from DB to Xls file

Ans:-

First create a website using your .net framework and then add a class file in this solution,automatically that class file will add in your App_code folder.Give that class file name as ExcelSheetFunctions.cs.

ExcelSheetFunctions.cs:-

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

namespace ExcelUtility
{
    /// <summary>
    /// Summary description for functions
    /// </summary>
    public class DataSetToExcel
    {
        public DataSetToExcel()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public static void Convert(DataSet ds, string filename)
        {
            HttpResponse response = HttpContext.Current.Response;

            // first let's clean up the response.object
            response.Clear();
            response.Charset = "";

            // set the response mime type for excel
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + ".xls\"");

            // create a string writer
            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    // instantiate a datagrid
                    DataGrid dg = new DataGrid();
                    dg.DataSource = ds.Tables[0];
                    dg.DataBind();
                    dg.RenderControl(htw);
                    response.Write(sw.ToString());
                    response.End();
                }
            }

        }

    }
}

getExcel.aspx:-

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="getExcel.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Get/Download Data from DB to Xls file</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <center>
           <asp:Button ID="btnEnter" runat="server" Text="Get/Download Data from DB to Xls file"
            onclick="btnEnter_Click" />
            </center>
    </div>
    </form>
</body>
</html>

getExcel.aspx.cs:-

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using ExcelUtility;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }

   protected void btnEnter_Click(object sender, EventArgs e)
   {
       SqlConnection cn = new SqlConnection("server=192.168.0.200;database=subsdb;user id=sa;pwd=amtpl@123");
       SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM emp", cn);
       DataSet ds = new DataSet();
       ad.Fill(ds);
       DataSetToExcel.Convert(ds, "Student List");
   }
}


Monday 17 March 2014

Interview Q & A on Server Side Controls(Ajax,User/Custom Controls,Validations) in Asp.Net

1. What is ASP.NET AJAX?
 answer:
ASP.NET AJAX, mostly called AJAX, is a set of extensions of ASP.NET. It is developed by Microsoft to implement AJAX functionalities in Web applications. ASP.NET AJAX provides a set of components that enable the developers to develop applications that can update only a specified portion of data without refreshing the entire page. The ASP.NET AJAX works with the AJAX Library that uses object-oriented programming (OOP) to develop rich Web applications that communicate with the server using asynchronous postback.

2. What is the difference between synchronous postback and asynchronous postback?
 answer:
The difference between synchronous and asynchronous postback is as follows:

Asynchronous postback renders only the required part of the page; whereas, synchronous postback renders the entire page for any postback.

Asynchronous postback executes only one postback at a time, that is, if you have two buttons doing asynchronous postback, the actions will be performed one by one; whereas, synchronous postback executes all the actions at once.

Asynchronous postback only modifies the update panel that raises the postback; whereas, synchronous postback modifies the entire page.

3. What technologies are being used in AJAX?
 answer:
AJAX uses four technologies, which are as follows:
JavaScript
XMLHttpRequest
Document Object Model (DOM)
Extensible HTML (XHTML) and Cascading Style Sheets (CSS)

4. Why do we use the XMLHttpRequest object in AJAX?
 answer:
The XMLHttpRequest object is used by JavaScript to transfer XML and other text data between client and server. The XMLHttpRequest object allows a client-side script to perform an HTTP request. AJAX applications use the XMLHttpRequest object so that the browser can communicate to the server without requiring a postback of the entire page. In earlier versions of Internet Explorer, MSXML ActiveX component is liable to provide this functionality; whereas, Internet Explorer 7 and other browsers, such as Mozilla Firefox, XMLHttpRequest is not liable to.

5. How can we get the state of the requested process?
 answer:
XMLHttpRequest get the current state of the request operation by using the readyState property. This property checks the state of the object to determine if any action should be taken. The readyState property uses numeric values to represent the state.

6. What are the different controls of ASP.NET AJAX?
 answer:
ASP.NET AJAX includes the following controls:
ScriptManager
ScriptManagerProxy
UpdatePanel
UpdateProgress
Timer

7)How do you validate Input data on web page?
answer:
Before submitting a web page to server, Input validation on web page is one of the important task.ASP.Net provides below validation controls to validate data in web controls and shows user friendly Messages to the user.

ASP.Net validation Controls:

8)Define Validation Control in ASP.NET?
 answer:
The validation control is used to implement page level validity of data entered in the server controls. This check is done before the page is posted back to the server thus avoid round trip to the server. If data does not pass validation, it will display an error message to the user.

9)What are the differences between custom Web control and user control?
answer:

Custom Control:

1)         To be used across different applications.
2)         Good for dynamic layout.
3)         Doesn't have a visual interface.
4)         It's a .DLL (Dynamic Linked Libraries) file.
5)         It can be added to the toolbox and can be used in different applications without re-compiling.

User Control:

1)         Can be used for a particular website.
2)         Good for Static layout.
3)         Have a visual interface.
4)         It's an .ascx file.
5)         It can't be added to the toolbox and it will not have design support and loaded at runtime.

10) Differentiate between:
 answer:
Client-side and server-side validations in Web pages.

- Client-side validations happends at the client's side with the help of JavaScript and VBScript. This happens before the Web page is sent to the server.
- Server-side validations occurs place at the server side.

11)What data type does the RangeValidator control support?
 answer:
Integer, String and Date

12)Which two properties are on every validation control?
answer:
We have two common properties for every validation controls
1. Control to Validate,
2. Error Message.

14)What is validationsummary server control?where it is used?.
answer:
The ValidationSummary control allows you to summarize the error messages from all validation controls on a Web page in a single location. The summary can be displayed as a list, a bulleted list, or a single paragraph, based on the value of the DisplayMode property.

15)What are all the navigation controls available with asp.net?
 answer:
Menus
Site Maps
Tree View

16)Can you set which type of comparison you want to perform by the CompareValidator control?
answer:
Yes, by setting the Operator property of the CompareValidator control.

17)What is webpart controls?
answer:
Web Parts is an integrated set of controls for creating Web sites that enable end users to modify the content, appearance, and behavior of Web pages directly from a browser.

18.what are the facilities of webparts?
answer:
1)personalize page content
2)personalize page layout
3)Export and import controls
4)create connections
5)Manage and personalize site-level settings

19.what are the steps involved in webparts page life cycle?
answer:
1)Initialistion
2)Initialisation Complete
3)Load Complete
4)Save State Complete

20)How to Register Webuser control in webpage?
 answer:
<%@ Register TagPrefix="uc" TagName=""
    Src="Spinner.ascx" %>

21)Types of Custom controls?
answer:
Custom controls are compiled controls that act, from the client's perspective,
much like web (ASP) controls. Custom controls can be created in one of three ways:

By deriving a new custom control from an existing control (e.g., deriving your own specialized text box from asp:textbox).
 This is known as a derived custom control.
By composing a new custom control out of two or more existing controls. This is known as a composite custom control.
By deriving from the base control class, thus creating a new custom control from scratch. This is known as a full custom control.

22)How to Consume Custom control in webpage?
answer:
<%@ Register Assembly="CustomControls" 
                Namespace="CustomControls"
                TagPrefix="ccs" %>

23)Which directive we need to use to work with webusercontrol?
answer:
<% Control Language="C#"
    AutoEventWireUP="true"
    CodeFile="abc.ascx.cs"
    Inherits="MyWebUserControl"%>

24)Advantages of WebUser controls?
answer:
Reusability
Performance
EasyModifications

25)Explain any 3rd party tool for asp.net Controls?
answer:
Teleric controls
KendoUI
ComponentGallery

26)Advantages of 3rd Party tools?
answer:
ExceptionalPerformance
Developer Friendly
CrossBrowserSupport


Interview Q & A on MVC in ASP.NET(Part 2)

?  Can we share a view across multiple controllers?
üYes, it is possible to share a view across multiple controllers by putting a view into the shared folder.

?   What is the use of a controller in an MVC application?
üA controller will decide what to do and what to display in the view. It works as follows:
-                      i) A request will be received by the controller
-                      ii) Basing on the request parameters, it will decide the requested activities
-                      iii) Basing on the request parameters, it will delegates the tasks to be performed
-                       iv) Then it will delegate the next view to be shown

?   What are the Core features of ASP.NET MVC?
üCore features of ASP.NET MVC framework are:
-                      Clear separation of application concerns (Presentation and Business Logic)
-                      An extensible and pluggable framework
-                      Extensive support for ASP.NET Routing
-                      Support for existing ASP.NET features

?   Explain about 'page lifecycle' of ASP.NET MVC ?
üThe page lifecycle of an ASP.NET MVC page is explained as follows:

i) App Initialisation:  In this stage, the aplication starts up by running Global.asax’s Application_Start() method.   In this method, you can add Route objects to the static RouteTable.Routes collection.
 If you’re implementing a custom IControllerFactory, you can set this as the active controller factory by assigning it to the System.Web.Mvc.ControllerFactory.Instance property.

ii) Routing:  Routing is a stand-alone component that matches incoming requests to IHttpHandlers by URL pattern.   MvcHandler is, itself, an IHttpHandler, which acts as a kind of proxy to other IHttpHandlers configured in the Routes table.

iii) Instantiate and Execute Controller:   At this stage, the active IControllerFactory supplies an IController instance.

iv) Locate and invoke controller action:  At this stage, the controller invokes its relevant action method, which after further processing, calls RenderView().

v) Instantiate and render view:  At this stage, the IViewFactory supplies an IView, which pushes response data to the IHttpResponse object.

?   Explain about the formation of Router Table in ASP.NET MVC ?
üIn the begining stage, when the ASP.NET application starts, the method known as Application_Start() method is called.
     The Application_Start() will then calls RegisterRoutes() method.
    This RegisterRoutes() method will create the Router table.

?   In an MVC application, what are the segments of the default route ?
üThere are 3 segments of the default route in an MVC application.They are:
1)Controller Name:  Example: Home
1)Action Method Name:  Example: Index
2)Parameter passed to the Action method:  Example: Parameter Id - MVC

?   Is the route {controller}{action}/{id} a valid route definition or not and why ?
ü{controller}{action}/{id} is not a valid route definition.   The reason is that, it has no literal value or delimiter between the placeholders. 
 If there is no literal, the routing cannot determine where to separate the value for the controller placeholder from the value for the action placeholder.
{controller}-{action}/{id}         //valid  ex.:  account-login/1
{controller}/{action}/{id}         //valid  ex.:  account/login/1

?   Is there any way to handle variable number of segments in a route definition?
üYou can handle variable number of segments in a route definition by using a route with a catch-all parameter.
 Example:        controller/{action}/{*parametervalues}
Here * reffers to catch-all parameter.

?   In an MVC application, which filter executes first and which is the last?
üAs there are different types of filters in an MVC application, the ‘Authorization filter’ is the one which executes first and ‘Exception filters’ executes in the end.

?   What are HTML Helpers?
üHTML helpers are methods we can invoke on the HTML property of a view. 

?   Difference between Viewbag and Viewdata in ASP.NET MVC ?
üView Data: In this, objects are accessible using strings as keys.
Example: 
Controller:
public ActionResult Index()
{
var companies = new List<string> { "NIT",  "Nacre" };
ViewData["companies"] = companies;
return View();
}

View:
<ul>
@foreach (var company in (List<string>)ViewData["companies"])
{ <li>  @company </li>
}
</ul>

View Bag: It will allow the object to dynamically have the properties add to it.

Example:
Controller:
public ActionResult Index()
{
var companies = new List<string> { "NIT",  "Nacre" };
ViewBag.companies = companies;
return View();
}

View:
<ul>
@foreach (var company in ViewBag.companies)
{
<li>  @company </li>
}
</ul>

An important point to note is that there is no need to cast our object when using the ViewBag. This is because the dynamic we used lets us know the type.

?   What are Validation Annotations?
üData annotations are attributes you can find in System.ComponentModel.DataAnnotations namespace. These attributes provide server-side validation, and the framework also supports client-side validation when you use one of the attributes on a model property. You can use four attributes in the DataAnnotations namespace to cover common validation scenarios:
-                      Required
-                      StringLength
-                      Compare
-                      RegularExpression
-                      Range

?   What are the file extensions for razor views?
üThere are two types of file extensions for razor views.   They are:
i) .cshtml (C#)   ii) .vbhtml (VB.Net).

?   What is partial view in Asp.Net Mvc?
üA partial view is like as user control in Asp.Net web form. Partial views are reusable views like as Header and Footer. It has .csHtml extension.   Partial() and RenderPartial() Html method renders partial view in Mvc razor.

<div>@Html.Partial("_Comments")</div>
<div>Full path:  @Html.RenderPartial("~/Views/Shared/_Product.cshtml");</div>

?   What is strongly typed view in MVC?
üStrongly type view is used for rendering specific type of model object. By specifying the type of data we get intellisense for that model class.

Exmaple:  return View(employee);

?   How to call an action Method on the click of a link?
ü@Html.ActionLink("LinkName", "ActionMethod", "Controller")

Example:  @Html.ActionLink("Edit", "Edit", "Employee")

?   What is the use of ViewStart in ASP.NET MVC?
üIn the default template of ASP.NET MVC, we get _ViewStart.cshtml page that is used to almost similar to MasterPage in ASP.NET Web Form or like a layout template.

?   In case we are returning anonymous type from Controller to the views, what should be the @model in the View?

ü@model IEnumerable<dynamic variable>

?   What are different ways of returning a View?
üThere are different ways for returning/rendering a view in MVC Razor. E.g. return View(), return RedirectToAction(), return Redirect() and return RedirectToRoute().

**       ***           **



Interview Q & A on MVC in ASP.NET(Part 1)

1.What does MVC represent in ASP.NET?
- MVC stands for Model-View-Controller pattern that represents an architectural pattern for software.

- This separates the components of a Web application and helps in decoupling the business logic.

- It gives more flexibility to overall architecture that allows the changes to be made to a
layer, without affecting the other.

-M represents the Model view that specifies a specific domain data.

-V represents the view of the user interface components used to display the Model data.

-C represents the Controller that handles the user interactions and events. It manipulates the updates that model reflect at every change of the state of an application.

2.Which are the advantages of ASP.NET MVC framework?
-MVC framework is divided in model, view and controller which help to manage complex application. This way it divides the application in input logic, business logic and UI logic.

-MVC framework does not use view state or server-based forms which eliminate the problem of load time delays of HTML pages.

- MVC support ASP.NET routing which provide better URL mapping. In ASP.NET routing URL can be very useful for Search Engine Optimization (SEO) and Representation State Transfer (REST).

-MVC Framework support better development of test-driven development (TDD) application.

-In MVC Framework Testing becomes very easier. Individual UI test is also possible.

3.What do Model, View and Controller represent in an MVC application?
-MVC framework is a development method in which application is divided in three components: Model, View and Controller

-Model: In model we have to write our business logic and all the methods for data manipulations (CRUD)

-View: This component is responsible for user interface of the application.

-Controller: Controller handles the request and sends the response. It sends the request to View as a response or to Model. It acts as a mediator between Model and View.

4.How is the ASP.NET MVC architecture different from others?
-ASP.NET MVC uses a complete Model-View-Controller architecture that combines the Controller and the View in a way that both meet the dependency of each other.

-The testing of the architecture can be done by instantiating a View and carrying out the unit tests without running the controllers through the complete cycle.

-The control of MVC on the output is complete and it renders the HTML in a very clean way.

-The architecture provides an orientation towards the standard compliant pages and control over the behavior of the applications.

-The knowledge of many programming language gets reduced and the model can become more abstract from lots of details that is provided for the ease of use.

5.Why it is useful to use MVC instead of WebForms?
-MVC allows the user to write less amount of code to build the web applications as lots of components are integrated to provide the flexibility in the program.

-Lot of data control options is being provided that can be used in ViewState.

-The application tasks are separated into components to make it easier for the programmers to write the applications but at the same time the amount of the code also increases.

-Main focus remains on the testability and maintainability of the projects that is being carried out in large projects.

-It is being used for the projects that require rapid application development.

6.What is the page lifecycle of an ASP.NET MVC? 
The page lifecycle of ASP.NET MVC is having the following process and it is as follows:

-App initialization: in this the initiation of the application takes place that allow the application to interact the server and start to run the components.

-Routing: in this the messages are routed to the server for making the delivery of the request easier.

-Instantiate and execute controller: in this way the controller handles the request and passes it on to display the output or replies to the request.

-Locate and invoke controller action: The actions allow the controller to be located correctly and it invokes the correct action that has to be taken on the applications.

-Instantiate and render view: this helps in view the result of the application that is being built.

7.Can you describe ASP.NET MVC Request Life Cycle?
Following are the steps that are executed in ASP.NET MVC Request Life Cycle.

1. Application first receives the request and looks up Route object in RouteTable collection. Then the RouteData object is created.

2. Then RequestContext instance is created.

3. MvcHandler and pass RequestContext to handler is created.

4. Then IControllerFactory from RequestContext is identified.

5. Then the object of class that implements ControllerBase is created.

6. MyController.Execute method is called.

7. Then ControllerActionInvoker finds the action to invoke on the controller and executes that action on the controller and by calling the model associated view returns.

8.What are the 3 main components of an ASP.NET MVC application?
1. M - Model
2. V - View
3. C - Controller

9.In which assembly is the MVC framework defined?
System.Web.Mvc

10.Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web application?
Yes, it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web application.

11.What does Model, View and Controller represent in an MVC application?
Model: Model represents the application data domain. In short the applications business logic is contained with in the model.

View: Views represent the user interface, with which the end users interact. In short the all the user interface logic is contained with in the UI.

Controller: Controller is the component that responds to user actions. Based on the user actions, the respective controller, work with the model, and selects a view to render that displays the user interface. The user input logic is contained with in the controller.

12.What is the greatest advantage of using asp.net mvc over asp.net webforms?
It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested.

13.Which approach provides better support for test driven development - ASP.NET MVC or ASP.NET Webforms?
ASP.NET MVC

14.What are the advantages of ASP.NET MVC?
1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
2. Complex applications can be easily managed
3. Seperation of concerns. Different aspects of the application can be divided into Model, View and Controller.
4. ASP.NET MVC views are light weight, as they donot use viewstate.

15.Is it possible to unit test an MVC application without running the controllers in an ASP.NET process?
Yes, all the features in an asp.net MVC application are interface based and hence mocking is much easier. So, we don't have to run the controllers in an ASP.NET process for unit testing.

16.Is it possible to share a view across multiple controllers?
Yes, put the view into the shared folder. This will automatically make the view available across multiple controllers.

17.What is the role of a controller in an MVC application?
The controller responds to user interactions, with the application, by selecting the action method to execute and alse selecting the view to render.

18.Where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax

19.Name a few different return types of a controller action method?
The following are just a few return types of a controller action method. In general an action method can return an instance of a any class that derives from ActionResult class.
1. ViewResult
2. JavaScriptResult
3. RedirectResult
4. ContentResult
5. JsonResult

20.What is the significance of NonActionAttribute?
In general, all public methods of a controller class are treated as action methods. If you want prevent this default behaviour, just decorate the public method with NonActionAttribute.

21.What is the significance of ASP.NET routing?
ASP.NET MVC uses ASP.NET routing, to map incoming browser requests to controller action methods. ASP.NET Routing makes use of route table. Route table is created when your web application first starts. The route table is present in the Global.asax file.

22.What are the 3 segments of the default route, that is present in an ASP.NET MVC application?
1st Segment - Controller Name
2nd Segment - Action Method Name
3rd Segment - Parameter that is passed to the action method

Example: http://pragimtech.com/Customer/Details/5
Controller Name = Customer
Action Method Name = Details
Parameter Id = 5

23.ASP.NET MVC application, makes use of settings at 2 places for routing to work correctly. What are these 2 places?
1. Web.Config File : ASP.NET routing has to be enabled here.
2. Global.asax File : The Route table is created in the application Start event handler, of the Global.asax file.

24.What is the adavantage of using ASP.NET routing?
In an ASP.NET web application that does not make use of routing, an incoming browser request should map to a physical file. If the file does not exist, we get page not found error.

An ASP.NET web application that does make use of routing, makes use of URLs that do not have to map to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are descriptive of the user's action and therefore are more easily understood by users.

25.What are the 3 things that are needed to specify a route?
1. URL Pattern - You can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string.
2. Handler - The handler can be a physical file such as an .aspx file or a controller class.
3. Name for the Route - Name is optional.

26.Is the following route definition a valid route definition?
{controller}{action}/{id}
No, the above definition is not a valid route definition, because there is no literal value or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the controller placeholder from the value for the action placeholder.

27.What is the use of the following default route?
{resource}.axd/{*pathInfo}
This route definition, prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.

28.What is the difference between adding routes, to a webforms application and to an mvc application?
To add routes to a webforms application, we use MapPageRoute() method of the RouteCollection class, where as to add routes to an MVC application we use MapRoute() method.

29.How do you handle variable number of segments in a route definition?
Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all parameter.
controller/{action}/{*parametervalues}

30.What are the 2 ways of adding constraints to a route?
1. Use regular expressions
2. Use an object that implements IRouteConstraint interface

31.Give 2 examples for scenarios when routing is not applied?
1. A Physical File is Found that Matches the URL Pattern - This default behaviour can be overriden by setting the RouteExistingFiles property of the RouteCollection object to true.
2. Routing Is Explicitly Disabled for a URL Pattern - Use the RouteCollection.Ignore() method to prevent routing from handling certain requests.

32.What is the use of action filters in an MVC application?
Action Filters allow us to add pre-action and post-action behavior to controller action methods.

If I have multiple filters impleted, what is the order in which these filters get executed?
1. Authorization filters
2. Action filters
3. Response filters
4. Exception filters

33.What are the different types of filters, in an asp.net mvc application?
1. Authorization filters
2. Action filters
3. Result filters
4. Exception filters

34.Give an example for Authorization filters in an asp.net mvc application?
1. RequireHttpsAttribute
2. AuthorizeAttribute

35.Which filter executes first in an asp.net mvc application?
Authorization filter

36.What are the levels at which filters can be applied in an asp.net mvc application?
1. Action Method
2. Controller
3. Application
[b]Is it possible to create a custom filter?[/b]
Yes

37.What filters are executed in the end?
Exception Filters

Is it possible to cancel filter execution?
Yes

38.What type of filter does OutputCacheAttribute class represents?
Result Filter

39.What are the 2 popular asp.net mvc view engines?
1. Razor
2. .aspx

40.What symbol would you use to denote, the start of a code block in razor views?
@

41.What symbol would you use to denote, the start of a code block in aspx views?
<%= %>

42.In razor syntax, what is the escape sequence character for @ symbol?
The escape sequence character for @ symbol, is another @ symbol

43.When using razor views, do you have to take any special steps to proctect your asp.net mvc application from cross site scripting (XSS) attacks?
No, by default content emitted using a @ block is automatically HTML encoded to protect from cross site scripting (XSS) attacks.

44.When using aspx view engine, to have a consistent look and feel, across all pages of the application, we can make use of asp.net master pages. What is asp.net master pages equivalent, when using razor views?
To have a consistent look and feel when using razor views, we can make use of layout pages. Layout pages, reside in the shared folder, and are named as _Layout.cshtml

45.What are sections?
Layout pages, can define sections, which can then be overriden by specific views making use of the layout. Defining and overriding sections is optional.

46.What are the file extensions for razor views?
1. .cshtml - If the programming lanugaue is C#
2. .vbhtml - If the programming lanugaue is VB

47.How do you specify comments using razor syntax?
Razor syntax makes use of @* to indicate the begining of a comment and *@ to indicate the end. An example is shown below.
@* This is a Comment *@

49.What is MVC?
MVC is a framework methodology that divides an application’s implementation into three component roles: models, views, and controllers.
“Models” in a MVC based application are the components of the application that are responsible for maintaining state. Often this state is persisted inside a database (for example: we might have a Product class that is used to represent order data from the Products table inside SQL).

“Views” in a MVC based application are the components responsible for displaying the application’s user interface. Typically this UI is created off of the model data (for example: we might create an Product “Edit” view that surfaces textboxes, dropdowns and checkboxes based on the current state of a Product object).

“Controllers” in a MVC based application are the components responsible for handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI. In a MVC application the view is only about displaying information – it is the controller that handles and responds to user input and interaction. 

50. What is Razor View Engine?
Razor view engine is a new view engine created with ASP.Net MVC model using specially designed Razor parser to render the HTML out of dynamic server side code. It allows us to write Compact, Expressive, Clean and Fluid code with new syntaxes to include server side code in to HTML.

51. What is namespace of asp.net mvc?
ASP.NET MVC namespaces and classes are located in the System.Web.Mvc assembly.
System.Web.Mvc namespace
Contains classes and interfaces that support the MVC pattern for ASP.NET Web applications. This namespace includes classes that represent controllers, controller factories, action results, views, partial views, and model binders.
System.Web.Mvc.Ajax namespace
Contains classes that support Ajax scripts in an ASP.NET MVC application. The namespace includes support for Ajax scripts and Ajax option settings.
System.Web.Mvc.Async namespace
Contains classes and interfaces that support asynchronous actions in an ASP.NET MVC application
System.Web.Mvc.Html namespace
Contains classes that help render HTML controls in an MVC application. The namespace includes classes that support forms, input controls, links, partial views, and validation.

51. What is the ‘page lifecycle’ of an ASP.NET MVC?
Following process are performed by ASP.Net MVC page:
1) App initialization
2) Routing
3) Instantiate and execute controller
4) Locate and invoke controller action
5) Instantiate and render view

52. How route table is created in ASP.NET MVC?
When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table.

53.How do you avoid XSS Vulnerabilities in ASP.NET MVC?
Use thesyntax in ASP.NET MVC instead of usingin .net framework 4.0.

54. If I have multiple filters implemented, what is the order in which these filters get executed?
1. Authorization filters
2. Action filters
3. Response filters
4. Exception filters

55. What is difference between Viewbag and Viewdata in ASP.NET MVC?
The basic difference between ViewData and ViewBag is that in ViewData instead creating dynamic properties we use properties of Model to transport the Model data in View and in ViewBag we can create dynamic properties without using Model data.
character for @ symbol, is another @ symbol

56. What is Routing?

A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an .aspx file in a Web Forms application. Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.

Interview Q & A on WCF Services in Asp.Net(part 2)

1.What is an Endpoint? How to configure an end point in WCF Application? Is it possible to create an end point dynamically?
An Endpoint is the interface through which the Business Services are exposed to external world. Each Endpoint in a WCF application consists of following things:

(a)    Address – An address is the URL through which the client applications interact with the services. The Address can be configured in the Configuration file of the Service application.
(b)   Binding – A Binding is the one that decides how client applications can interact with the Services. This is used to specify transport, encoding and protocol details required for client applications and services to communicate each other.
(c)    Contract – A Contract is the service which is supposed to be exposed to the external world that client applications consume.

Configuring Endpoint in the Configuration File:
     <endpoint address="http://localhost/SampleServices/Service"
                  binding="basicHttpBinding"
                  contract="SampleService.IService" />
Creating an Endpoint Programmatically:
Sometimes we might have to create the Endpoints through the program based on business requirements. An equivalent C# code which would create the end point from the code looks like below:
      string serviceAddress = "http://localhost/SampleServices/Service";
         BasicHttpBinding basicHBinding = new BasicHttpBinding();
         using (ServiceHost hostService = new ServiceHost(typeof(Service1)))
         {
            hostService.AddServiceEndpoint(typeof(IService1), basicHBinding, serviceAddress);
         }
Note that the above code snippet needs to be placed in the Host Application which hosts the WCF services.

2.What are bindings in a Service? How many types of bindings are available?
A Binding is the one that decides how client applications can interact with the Services. This is used to specify transport, encoding and protocol details required for client applications and services to communicate each other.
All the binding configurations should be set in a separate section with the name “bindings” in the configuration file. This section is under the main section:
     <system.serviceModel>

<bindings>

</bindings>

 </system.serviceModel>

You can define more than one binding configuration inside the “bindings” section.

There are many types of bindings available by default in WCF framework. Out of these, primarily four bindings are very commonly used. They are:
(a)    BasicHTTPBinding – This binding is used for basic web service communication. This is mainly used for interoperability. No security is available with this binding. The medium of communication is through web (HTTP protocol). The typical configuration settings for this binding looks like below:

    <bindings>
      <basicHttpBinding>
        <binding name="sampleBasicHttpBinding">         
        </binding>
      </basicHttpBinding>   
    </bindings>

The above section gives the flexibility to give name to your configuration settings. You could reuse this configuration setting in one or more endpoint (use the name of the binding on the “binding” attribute in your end point).

(b)   WsHTTPBinding – This binding is used for secure, reliable, interoperable binding. This binding is used for a web service with WS-* support like WS-Reliable Messaging for reliability, and WS-Security for message security and authentication. To simplify, this web service is used whenever you need some kind of security to you basic web service. The medium of communication is through web (HTTP protocol). The configuration for this type of binding starts like this:

    <bindings>     
      <wsHttpBinding>
        <binding name="sampleWsHBinding">
         
        </binding>
      </wsHttpBinding>
    </bindings>

(c)    MsmqIntegrationBinding – This binding is used when the WCF Service needs to interact with the MSMQ. The service with this binding can listen to the MSMQ and read or insert messages into the queue. The client applications insert the messages into a queue and the service can read the message from the queue. The medium of communication is through MSMQ in this case. The configuration for this type of binding starts like this:

    <bindings>     
      <msmqIntegrationBinding>
        <binding name="sampleMsmqBinding">
       </binding>
      </msmqIntegrationBinding>
    </bindings>

(d)   NetTcpBinding – This binding is used when the communication between two applications on two computers which are directly connected. This binding uses TCP protocol for communication. The configuration for this type of binding starts like this:

    <bindings>     
      <netTcpBinding>
        <binding name="sampleNetTcpBinding">         
        </binding>
      </netTcpBinding>
    </bindings>

Along with the already built-in bindings, the WCF framework also allows the developers to create custom bindings.

4.What is the difference between BasicHttpBinding and WsHttpBinding? When do you use what?
Following are the differences between BasicHttpBinding and WsHttpBinding. They are:
(a)    BasicHttpBinding supports wide variety of clients (like clients built on .NET, PHP, RUBY etc) whereas WsHttpBinding has limited compatibility to client applications that were built on various technologies
(b)    BasicHttpBinding sends the messages in plain text by default over the network where as WsHttpBinding sends them in an encrypted format by default over the network
(c)    BasicHttpBinding cannot send reliable messaging whereas WsHttpBiding does it.
(d)    BasicHttpBiding cannot support PerSession Instance Context mode where WsHttpBinding does.

5.Why an interface is required to define the Service Contract and Operation Contract?
It is always a best practice to program to an interface rather than programming to an implementation. As WCF service is invoked by wide variety of clients, it is always better to expose the Interface rather than the implementation. This give you the flexibility to change the implementation as per your business node without any impact on the client applications since the client applications are aware of the interface only and does not the implementation class (neither its name or namespace).

6.What is Service Behavior? What role does it play? How to configure the behavior of a Service?
Service Behavior is the configuration setting that decides the execution behavior of the Service. For example, if you would like the Service to use the single instance of its implementation all the time, this can be achieved by configuring the service behavior accordingly.

The behavior of the service can be controlled by placing a ServiceBehavior attribute on top of the Service implementation. For example, below code shows how the ServiveBehavior attribute can be placed on top of a Service implementation.

[ServiceBehavior()]
public class Service1 : IService1
{

   [OperationContract]       


   public string GetData(int value)
   {
            return string.Format("You entered: {0}", value);
   }
}

If you notice the ServiceBehavior attribute in the above code snippet, it is a blank attribute. There are many properties that can be defined within this ServiceBehavior attribute. Few of the important properties are:

(a)    ConcurrencyMode
(b)   IncludeExceptionDetailInFaults
(c)    InstanceContextMode
(d)   Name
(e)   Namespace

Service Behavior can also be configured from the Configuration file. The below sample configuration gives an idea of how it can be done:

  <behaviors>
      <serviceBehaviors>       
        <behavior name="sampleBehavior">
         
        </behavior>
      </serviceBehaviors>
  </behaviors>

The configured behavior can be attached to the end point in the below fashion:

     <endpoint address="http://localhost/SampleServices/Service"
                        binding="basicHttpBinding"
                       contract="SampleService.IService"
         behaviorConfiguration=" sampleBehavior"/>

7.What are different Instance Context Modes available in WCF and when do you use what? How to configure them in the code?

Instance Context Mode settings control the services instances created for the client requests. There are three Instance Context modes that can be set. They are:

(a)    PerCall
(b)   PerSession
(c)    Single

When the service is configured to run on PerCall instance context mode, the below program returns the output as “1” always.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class Service1 : IService1
    {
        int counter = 0;
        [OperationContract]       
        public string GetData(int value)
        {
            counter ;
            return counter.ToString();
        }
    }

8.When the service is configured to run on PerSession instance context mode, the below program holds the value of “counter” variable as long as the client proxy object is live and increments it in each call. For example, if you call GetData method 10 times using the same Client Object, the value returned will be 10 on tenth call.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    public class Service1 : IService1
    {
        int counter = 0;
        [OperationContract]
        public string GetData(int value)
        {
            counter ;
            return string.Format("You entered: {0}", counter.ToString());
        }
    }

When the service is configured to run on Single Instance Context mode, the below program holds the value of “counter” variable forever irrespective of the client application that is calling it. For example, Client A calls the below program 10 times and Client B calls the below service 10 times. The value that is returned to Client B on its 10th call will be 20 and not 10 or 1.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class Service1 : IService1
    {
        int counter = 0;
        [OperationContract]
        public string GetData(int value)
        {
            counter ;
            return string.Format("You entered: {0}", counter.ToString());
        }
    }

9.What is Concurrency Mode and how does that impact the Service behavior?
Concurrency Mode settings control whether an instance of a Service Application processes messages sequentially or concurrently.

There are three modes available. They are:

(a)    Single – each service processes one message at a time
(b)   Multiple – each service processes multiple messages concurrently
(c)    Reentrant – each service instance processes one message at a time, but accepts the calls concurrently when the current message call is calling out.

The Concurrency Mode can be set using the ServiceBehavior attribute. The below code snippet shows an example.

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single)]
    public class Service1 : IService1
    {
        int counter = 0;
        [OperationContract]
        public string GetData(int value)
        {
            counter ;
            return string.Format("You entered: {0}", counter.ToString());
        }
    }

10.What is WCF Throttling? How do you configure the code to throttle based on the need?
Throttling provides an ability to control the number of calls that the WCF service can handle. Throttling Settings limits the number of concurrent calls that can be made to the service and concurrent instances created at the service end and this provides an ability to configure the service to make use of resource effectively.

The below configuration settings control the number of calls, instances and sessions that can be made to the Service.

      <serviceBehaviors>       
        <behavior name="sampleBehavior">
          <serviceThrottling maxConcurrentCalls="10"

                   maxConcurrentInstances="10"

                   maxConcurrentSessions="10"/>

       </behavior>
      </serviceBehaviors>

To look in more detail into this setting, “maxConcurrentCalls = 10” setting allows only maximum of 10 concurrent calls to be made to the Service method. Any other call that is coming to the service needs to wait until, at least one of the call in the above 10 calls is complete.

11.How does tracing and logging of WCF service can be configured?
All you need to do is make some configuration settings to enable tracing and logging in WCF. The service logging and tracing can be easily configured using the inbuilt tool – (svcConfigEditor.exe). Open the WCF Application configuration file from this tool and configure the settings.
How to make WCF Services operate on multiple threaded?
This can be achieved by using WCF Throttling. Refer to Question #8.
How to define the behavior of a WCF service based on the load?
This can be achieved by using WCF Throttling. Refer to Question #8.
How to increase the response message size in a WCF Service?
When you have a large amount of data that needs to be returned from the Service application to the client application, at times the service throws an exception stating that the message not former properly. This is because of the message size settings configured in the configuration file. Below configuration setting provides an idea on where to change the configuration settings:

<bindings>
      <netTcpBinding>
        <binding name="sampleNetTcpBinding" maxReceivedMessageSize="" >

        </binding>
      </netTcpBinding>
</bindings>

Under the binding node, the “maxReceivedMessageSize” attribute needs to be configured properly.

12.How to increase the request time out in WCF Service?
If the service application takes long time to respond a request, the request might timeout on the client side before the service application returns the response. This can be handled by configuring the receiveTimeout attribute properly. Below configuration settings show how:

<bindings>
      <netTcpBinding>
        <binding name="sampleNetTcpBinding" receiveTimeout="">

        </binding>
      </netTcpBinding>
</bindings>

12.How to hide a property defined inside a DataContract class?
 DataContract is the attribute placed on top of the customer data objects (composite data types) to make them serializeable. As you know, the response from the service is always serialized and sent back to the client. Below code snippet shows how to do this:

[DataContract]
    public class CompositeType
    {
    }

When this attribute is placed on top of the object CompositeType, the object can be recognized at the client application end.

Now come to the properties inside the CompositeType, every property inside this class needs to be decorated with the attribute “DataMember”, to have the property recognized at the client end. If no “DataMember” attribute is placed, the propertly is not visible at client application end. Following code snippet shows how to do this.

 [DataContract]
    public class CompositeType
    {   
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }

13.How to enable Sessions usage in WCF Service?
Session based call can be achieved using PerSession Instance Context mode. But please note that PerSession Instance Context mode is not supported by the BasicHttpBinding. If there is a specific need for running the service on BasicHttpBinding for better interoperability, then there is an alternative to enable sessions at the level of BasicHttpBinding by enabling ASP.NET Sessions at Service level. The ASP.NET Compatibility can be set by placing the attribute “AspNetCompatibilityRequirements” on top of the Service Implementation. Below code snippet explains how to do this:

[AspNetCompatibilityRequirements(RequirementsMode =
                       AspNetCompatibilityRequirementsMode.Required)]

    public class Service1 : IService1
    {
        int counter = 0;
        [OperationContract]
        public string GetData(int value)
        {
            counter ;
            return string.Format("You entered: {0}", counter.ToString());
        }
    }


14.What is the difference between Service endpoint and Client endpoint?
Endpoint in WCF service is the combination of three things address, binding and contract. Service endpoint is for the server, server where your WCF service is hosted. Service endpoint defines where the service is hosted, what are the bindings and the contract i.e. methods and interfaces.

While client endpoint is for the client. Client endpoint specifies which service to connect, where it's located etc.

15.What is WCF?
 Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types.

WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it.

16.What is service and client in perspective of data communication?
 A service is a unit of functionality exposed to the world.

The client of a service is merely the party consuming the service.

17.What is address in WCF and how many types of transport schemas are there in WCF?
 Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas.

WCF supports following transport schemas

HTTP
TCP
Peer network
IPC (Inter-Process Communication over named pipes)
MSMQ

The sample address for above transport schema may look like

http://localhost:81
http://localhost:81/MyService
net.tcp://localhost:82/MyService
net.pipe://localhost/MyPipeService
net.msmq://localhost/private/MyMsMqService
net.msmq://localhost/MyMsMqService

18.What are contracts in WCF?
 In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.

WCF defines four types of contracts.

Service contracts
 Describe which operations the client can perform on the service.

There are two types of Service Contracts.

ServiceContract - This attribute is used to define the Interface.
OperationContract - This attribute is used to define the method inside Interface.

[ServiceContract]

interface IMyContract

{

   [OperationContract]

   string MyMethod( );

}

class MyService : IMyContract

{

   public string MyMethod( )

   {

      return "Hello World";

   }

}

Data contracts
 Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.

There are two types of Data Contracts.

DataContract - attribute used to define the class
DataMember - attribute used to define the properties.

[DataContract]

class Contact

{

   [DataMember]

   public string FirstName;

   [DataMember]

   public string LastName;

}

If DataMember attributes are not specified for a properties in the class, that property can't be passed to-from web service.

Fault contracts
 Define which errors are raised by the service, and how the service handles and propagates errors to its clients.

Message contracts
 Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.

19.Where we can host WCF services?
 Every WCF services must be hosted somewhere. There are three ways of hosting WCF services.

They are

1. IIS
2. Self Hosting
3. WAS (Windows Activation Service)

20.What is binding and how many types of bindings are there in WCF?
 A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.

WCF supports nine types of bindings.

Basic binding
 Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.

TCP binding
 Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.

Peer network binding
 Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.

IPC binding 
Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.

Web Service (WS) binding
Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.

Federated WS binding
Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.

Duplex WS binding
Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.

MSMQ binding
Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.

MSMQ integration binding
 Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.

21.What is endpoint in WCF?
 Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint.

The Endpoint is the fusion of Address, Contract and Binding.

 22.How to define a service as REST based service in WCF?
 WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding.

The below code shows how to expose a RESTful service

[ServiceContract]

interface IStock

{

[OperationContract]

[WebGet]

int GetStock(string StockId);

}


By adding the WebGetAttribute, we can define a service as REST based service that can be accessible using HTTP GET operation.

23.What is the address formats of the WCF transport schemas?
 Address format of WCF transport schema always follow

[transport]://[machine or domain][:optional port] format.

for example:

HTTP Address Format
 http://localhost:8888

the way to read the above url is

"Using HTTP, go to the machine called localhost, where on port 8888 someone is waiting"
When the port number is not specified, the default port is 80.

TCP Address Format
 net.tcp://localhost:8888/MyService

When a port number is not specified, the default port is 808:

net.tcp://localhost/MyService

NOTE: Two HTTP and TCP addresses from the same host can share a port, even on the same machine.

IPC Address Format
net.pipe://localhost/MyPipe

We can only open a named pipe once per machine, and therefore it is not possible for two named pipe addresses to share a pipe name on the same machine.

MSMQ Address Format
net.msmq://localhost/private/MyService
net.msmq://localhost/MyService

24.What is Proxy and how to generate proxy for WCF Services?
The proxy is a CLR class that exposes a single CLR interface representing the service contract. The proxy provides the same operations as service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service. The proxy completely encapsulates every aspect of the service: its location, its implementation technology and runtime platform, and the communication transport.

The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference. This brings up the Add Service Reference dialog box, where you need to supply the base address of the service (or a base address and a MEX URI) and the namespace to contain the proxy.

Proxy can also be generated by using SvcUtil.exe command-line utility. We need to provide SvcUtil with the HTTP-GET address or the metadata exchange endpoint address and, optionally, with a proxy filename. The default proxy filename is output.cs but you can also use the /out switch to indicate a different name.

SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs

When we are hosting in IIS and selecting a port other than port 80 (such as port 88), we must provide that port number as part of the base address:

SvcUtil http://localhost:88/MyService/MyService.svc /out:Proxy.cs

25.What are different elements of WCF Srevices Client configuration file?
 WCF Services client configuration file contains endpoint, address, binding and contract. A sample client config file looks like

<system.serviceModel>

   <client>

      <endpoint name = "MyEndpoint"

         address  = "http://localhost:8000/MyService/"

         binding  = "wsHttpBinding"

         contract = "IMyContract"

      />

   </client>

</system.serviceModel>

26.What is Transport and Message Reliability?
 Transport reliability (such as the one offered by TCP) offers point-to-point guaranteed delivery at the network packet level, as well as guarantees the order of the packets. Transport reliability is not resilient to dropping network connections and a variety of other communication problems.

Message reliability deals with reliability at the message level independent of how many packets are required to deliver the message. Message reliability provides for end-to-end guaranteed delivery and order of messages, regardless of how many intermediaries are involved, and how many network hops are required to deliver the message from the client to the service.

27.How to configure Reliability while communicating with WCF Services?
 Reliability can be configured in the client config file by adding reliableSession under binding tag.

<system.serviceModel>

   <services>

      <service name = "MyService">

         <endpoint

            address  = "net.tcp://localhost:8888/MyService"

            binding  = "netTcpBinding"

            bindingConfiguration = "ReliableCommunication"

            contract = "IMyContract"

         />

      </service>

   </services>

   <bindings>

      <netTcpBinding>

         <binding name = "ReliableCommunication">

            <reliableSession enabled = "true"/>

         </binding>

      </netTcpBinding>

   </bindings>

</system.serviceModel>

Reliability is supported by following bindings only

NetTcpBinding
WSHttpBinding
WSFederationHttpBinding
WSDualHttpBinding

28.How to set the timeout property for the WCF Service client call?
 The timeout property can be set for the WCF Service client call using binding tag.

<client>

   <endpoint

      ...

      binding = "wsHttpBinding"

      bindingConfiguration = "LongTimeout"

      ...

   />

</client>

<bindings>

   <wsHttpBinding>

      <binding name = "LongTimeout" sendTimeout = "00:04:00"/>

   </wsHttpBinding>

</bindings>


If no timeout has been specified, the default is considered as 1 minute.

29.How to deal with operation overloading while exposing the WCF services?
 By default overload operations (methods) are not supported in WSDL based operation. However by using Name property of OperationContract attribute, we can deal with operation overloading scenario.

[ServiceContract]

interface ICalculator

{

   [OperationContract(Name = "AddInt")]

   int Add(int arg1,int arg2);



   [OperationContract(Name = "AddDouble")]

   double Add(double arg1,double arg2);

}

Notice that both method name in the above interface is same (Add), however the Name property of the OperationContract is different. In this case client proxy will have two methods with different name AddInt and AddDouble.

30. What is WCF?
WCF stands for Windows Communication Foundation. It is a Software development kit for developing services on Windows. WCF is introduced in .NET 3.0. in the System.ServiceModel namespace. WCF is based on basic concepts of Service oriented architecture (SOA)

Q32. What is endpoint in WCF service?
The endpoint is an Interface which defines how a client will communicate with the service. It consists of three main points: Address,Binding and Contract.

Q33. Explain Address,Binding and contract for a WCF Service?
Address:Address defines where the service resides.
Binding:Binding defines how to communicate with the service.
Contract:Contract defines what is done by the service.

Q34. What are the various address format in WCF?
a)HTTP Address Format:--> http://localhost:
b)TCP Address Format:--> net.tcp://localhost:
c)MSMQ Address Format:--> net.msmq://localhost:

Q35. What are the types of binding available in WCF?
A binding is identified by the transport it supports and the encoding it uses. Transport may be HTTP,TCP etc and encoding may be text,binary etc. The popular types of binding may be as below:
a)BasicHttpBinding
b)NetTcpBinding
c)WSHttpBinding
d)NetMsmqBinding

Q36. What are the types of contract available in WCF?
The main contracts are:
a)Service Contract:Describes what operations the client can perform.
b)Operation Contract : defines the method inside Interface of Service.
c)Data Contract:Defines what data types are passed
d)Message Contract:Defines wheather a service can interact directly with messages

Q37. What are the various ways of hosting a WCF Service?
a)IIS 
b)Self Hosting 
c)WAS (Windows Activation Service)

Q38. What is the proxy for WCF Service?
A proxy is a class by which a service client can Interact with the service.
By the use of proxy in the client application we are able to call the different methods exposed by the service

Q39. How can we create Proxy for the WCF Service?
We can create proxy using the tool svcutil.exe after creating the service.
We can use the following command at command line.
svcutil.exe *.wsdl *.xsd /language:C# /out:SampleProxy.cs /config:app.config

Q40.What is the difference between WCF Service and Web Service?
a)WCF Service supports both http and tcp protocol while webservice supports only http protocol.
b)WCF Service is more flexible than web service.

Q41.What is DataContract and ServiceContract?Explain?
Data represented by creating DataContract which expose the
data which will be transefered /consumend from the serive
to its clients.

**Operations which is the functions provided by this
service.

To write an operation on WCF,you have to write it as an
interface,This interface contains the "Signature" of the
methods tagged by ServiceContract attribute,and all methods
signature will be impelemtned on this interface tagged with
OperationContract attribute.

and to implement these serivce contract you have to create
a class which implement the interface and the actual
implementation will be on that class.


Code Below show How to create a Service Contract:

Code:
[ServiceContract]
Public Interface IEmpOperations
{
[OperationContract]
Decimal Get EmpSal(int EmpId);

}

Class MyEmp: IEmpOperations
{
Decimal Get EmpSal()
{
// Implementation of this method.
}
}

42.What is the difference WCF and Web services?
Web services can only be invoked by HTTP. While Service or a WCF component can be invoked
by any protocol and any transport type. Second web services are not flexible. However, Services
are flexible. If you make a new version of the service then you need to just expose a new end.
Therefore, services are agile and which is a very practical approach looking at the current
business trends.

43.What are the main components of WCF?
The main components of WCF are
1. Service class
2. Hosting environment
3. End point

44.Where we can host WCF services?
Every WCF services must be hosted somewhere. There are three ways of hosting WCF services.
They are
1. IIS
2. Self Hosting
3. WAS (Windows Activation Service)

45.What is endpoint in WCF?
Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint.

46.What is binding and how many types of bindings are there in WCF?
A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.  WCF supports nine types of bindings.( Basic binding, TCP binding, Peer network binding, IPC binding, Web Service (WS) binding, Federated WS binding, Duplex WS binding, MSMQ binding, MSMQ integration binding).

47.what are the various ways of hosting a WCF service?
There are three major ways to host a WCF service:-
• Self-hosting the service in his own application domain. This we have already covered in
the first section. The service comes in to existence when you create the object of Service
Host class and the service closes when you call the Close of the Service Host class.
• Host in application domain or process provided by IIS Server.
• Host in Application domain and process provided by WAS (Windows Activation
Service) Server.

48.What are the types of contract available in WCF?
The main contracts are:
a)Service Contract:Describes what operations the client can perform.
b)Operation Contract : defines the method inside Interface of Service.
c)Data Contract:Defines what data types are passed
d)Message Contract:Defines wheather a service can interact directly with messages

49.What is the proxy for WCF Service?
A proxy is a class by which a service client can Interact with the service.
By the use of proxy in the client application we are able to call the different methods exposed by the service

50.How can we create Proxy for the WCF Service?
We can create proxy using the tool svcutil.exe after creating the service.
We can use the following command at command line.
svcutil.exe *.wsdl *.xsd /language:C# /out:SampleProxy.cs /config:app.config

51.How to test the WCF Service?
We can use the WCF Test client to test the WCF Service. Tool enables users to input test parameters, submit that input to the service, and view the response.
We can use the following command at command line. wcfTestClient.exe URI1 URI2 …

52.What are SOAP Faults in WCF?
Common language runtime (CLR) exceptions do not flow across service boundaries. At the maximum, a CLR exceptions may propagate up to the service tier from business components. Unhandled CLR exceptions reach the service channel and are serialized as SOAP faults before reporting to clients. An unhandled CLR exception will fault the service channel, taking any existing sessions with it. That is why it is very importatnt to convert the CLR exceptions into SOAP faults. Where possible, throw fault exceptions

53.What happens if there is an unhandled exception in WCF?
If there is an unhandled exception in WCF, the the service model returns a general SOAP fault, that does not include any exception specific details by default. However, you can include exception details in SOAP faults, using IncludeExceptionDetailsInFaults attribute. If IncludeExceptionDetailsInFaults is enabled, exception details including stack trace are included in the generated SOAP fault. IncludeExceptionDetailsInFaults should be enabled for debugging purposes only. Sending stack trace details is risky.