13 August 2014

ViewResult, FileResult, RedirectResult, PartialViewResult

ViewResult

It renders a view as a web page. It can make use of view engines aspx and Razor. The actions of return type ViewResult always returns a view. MVC supports following view types:
1. ASPX
2. ASCX
3. VBHTML
4. CSHTML

Note: A controller can have more than one view of various types. That is, ASPX, ASCX, CSHTML and VBHTML. The priority is always given to ASPX. However, you can access a view by using following example:

public ViewResult Details()
{
   return View("~/Views/Employee/Details.cshtml");

FileResult

The file result returns binary output to write the content of a file to response. That is, it can return the content of any specific file in the browser. If the MIME type of the file is not supported then, it downloads the file.
Example:

public FileResult ReadDoc()
{
    return File(@"F:\wcf.pdf","application/pdf");
}

RedirectResult

It is similar to response.redirect method that can be used to redirect to specific URL.
Example:
Public RedirectResult Google()
{
   return Redirect("http://www.google.com");
}
RedirectToRouteResult

It is similar to server.transfer method that can be used to redirect to any controller  action within the application.
Example:
Public RedirectToRouteResult EmpDetails()
{
   return RedirectToAction("Details","Employee");
}

Redirect using Hyperlink: MVC provides Html Helper "Html.ActionLink", that renders as "" tag to redirect to any location.
Syntax:
@Html.ActionLink("LinkText","Action","Controller", new {html attributes})

Example:
@Html.ActionLink("Go to Employee","Details","Employee", new {target="_blank"},null)

null at the end is used to avoid unwanted default query string added automatically.


PartialViewResult

Partial view are like user controls in web forms. the intention of partial views is to create a prototype that can be accessed from any view.

Example:
* Create partial views
Public PartialViewResult Register()
{
   return PartialView();
}
Public PartialViewResult Login()
{
   return PartialView();
}
* Add partial view to a view
@Html.Partial("Register")



@Html.Partial("Login")

Note: Views are generated as Login.cshtml and Register.cshtml in case of Razor view engine. But, in case with ASPX view engine, these views are created with extension .ASCX.

Note: You can directly invoke partial views by a URL request. You can restrict them by using the action filter "ChildActionOnly".
Example:

[ChildActionOnly]
public PartialViewResult Register()
{
   return PartialView();
}

Action Results in MVC

1. The controller action are public and can be invoked by an URL request.
2. The controller actions can return a view, file etc. These return types are referred as action results.
3. The action results in MVC are defined under the base class 'ActionResult'.
4. The various types of action results and their helper methods are defined below:

Action Results
Helper Method
ViewResult
View()
PartialViewResult
PartialView()
RedirectResult
Redirect()
RedirectToRouteResult
RedirectToAction()
ContentResult
Content()
JsonResult
Json()
JavascriptResult
Javascript()
FileResult
File()
EmptyResult
None

11 August 2014

Rules to remember while creating MVC - Controller's action method

1. Action methods must be public
2. Action methods can't be static
3. Action methods can be overloaded
4. Action methods can't be overridden
5. All Controllers are inherited from Controller class, which has it's own action methods. New controller's action method can't have same action method name that parent class has.
6. Action method parameters can't be 'ref' or 'out'.
7. Actions can't be extension methods.
7. All actions are invoked by 'Get' request.

15 January 2013

Send DataTable as Stored Procedure Paramater

We come across many situations where we need to insert all the records of a DataTable(dt) in a table having same structure as that of the dt. In my case, I was to read excel file and create in-memory dt. This dt resembles a table (dbo.tbl) present in my DB. Now After my dt is ready I was suppose to dump my all the records in dbo.tbl. Though you can do it using loop followed by insert statement but the is another way which is very fast, reliable and efficient too.

I will create my own type in sql using this query:


CREATE TYPE myTableType AS TABLE
(
-- Here you are suppose to mention all of your column names of dbo.tbl (mentioned above)
 -- Please note that you need not to declare any column which has identity 'yes', If you do so, will throw error
   -- do not include such columns having identity [QuestionColumnTableJoinID] [int] IDENTITY(1,1) NOT NULL 
-- include these columns to create your type
    [QuestionId] [varchar](10) NOT NULL,
    [QuestionDesc] [varchar](2000) NOT NULL,
    [TableName] [varchar](50) NULL,
    [ColumnName] [varchar](50) NULL,
    [ColumnDataType] [varchar](20) NULL,
    [IsRequired] [bit] NULL,
    [IsMandatory] [bit] NULL,
    [CreatedDate] [datetime] NULL,
    [IsDeleted] [bit] NOT NULL

)


After Creating the type you need to write a Stored Procedure which has parameter of type : myTableType which we created above.

CREATE PROCEDURE [dbo].[spInsertQuestionTable]
(
    @varTableQuestion dbo.myTableType READONLY
)


AS
BEGIN
    BEGIN TRAN
        INSERT INTO dbo.QuestionTable

        SELECT * FROM @varTableQuestion     

    COMMIT
END



Now your are done with your DB side.
Lets move on to code page, from where we want to call this SP.

                SqlCommand cmd = new SqlCommand("spInsertQuestionTable",con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@varTableQuestion", SqlDbType.Structured);
                cmd.Parameters["@varTableQuestion"].Value = dtQuestions;
                con.open();
                cmd.ExecuteNonQuery();
                con.close();


Note that you have to define your parameter type as SqlDbType.Structured and you are done. All the data inserted in one short.

20 October 2012

REST services

Sometimes SOAP might actually be overkilled for particular web service scenarios. In many cases the developer may need high range of interoperability. So, in order to increase interoperability, they have to restrict themselfs to basic XML message that they transmit over HTTP and they can take advantage of advance WS* specifications that are part of these protocols.

For security, they simply use HTTPS that provides facility of SSL for all the security needs.This is most common today. Most of the developer are using SOAP without WS* and this is often referred to as simple SOAP. Main benefit of doing this is it increases interoperability. Also, there is large number of tool support for generating clients & services from WSDL definition. We can take WSDL schema definition and automatically generate the code that we need without our framework and that code will hide all the underlying XML & HTTP details. This is why, most of the developer still use SOAP.

Some developer decide that they really don't need SOAP at all & just want to exchange XML messages over HTTP without SOAP framing element. This is often referred as plain-old XML (POX). This is usually used in combination with HTTP. When you take this approach, the interoperability is virtually guaranteed because you can easily find HTTP & XML stack on any platform in demand today. But it does require some direct XML / HTML coding.

In order to use POX, you should be comfortable writing XML based code using various XML APIs to produce & consume messages and you also need to be comfortable with HTTP stack for programming the logic to send & receive messages.

POX applications can also be defined in a REST-ful way. If you design your services around HTTP and if you are adhered to restful design principals and you define all your actions in terms of HTTP method & verbs, then indeed you are going to use what we call as RESTful architecture that happens to use plain-old XML messages over wire. 

02 October 2012

WCF - Handling Exceptions

There may be many different kinds of exceptions that may occur at the client side. But client channels need to be prepared for two main exception types :

1. Communication Exceptions - This is a base class that represent various runtime communication errors. This exception is a generalize exception to catch any type of communication exception that is thrown by your service operation also known as Fault Exception. They typically represent business oriented exceptions.

2. Timeout Exception - It is not delivered from communication exception. This represents the error that occurs when send timeout limit exceeded. So when you are writing your client side communication logic, you need to take it into account these various types of exceptions that can occur. Remember that after certain exceptions, the client side channel may enter into "faulted" state which will require you to call abort on the channel instead of close.


To Catch Communication Exception :

catch(CommunicationException ce)
{
       client.Abort();
}

To Catch Timeout Exception :
catch(TimeoutException te)
{
       client.Abort();
}

Configure Client Channel - through Binding & Behaviors

You can configure client channel through both binding & behaviors applied to client scenario. The binding configures the wire level protocol detail, whereas , the behavior configures local execution environment.

Key things that you might configure on the client side binding :-

1. Send Timeout Value : this influence when the time out exception happens.
2. Transport Protocol specific setting : that usually has to be sync with service setting as well.

There are also some client side behavior that you can apply to your client side endpoints. That's why they are called client side endpoint behavior in WCF.

I. Configure client side binding :-

II. Configure client side behavior :-