Wednesday, 11 December 2013

Exception Handling in ASP.NET MVC 4

    What does the user see when a runtime error occurs in an ASP.NET web application? The answer depends on how the website's <customErrors> configuration. By default, users are shown an unsightly yellow screen proclaiming that a runtime error has occurred. This tutorial shows how to customize settings to handle runtime exceptions.

We will use two attributes to handle error in an MVC application
  • customErrors attribute defined in web.config
  • HandleError attribute comes with default MVC Application
  1. Set custom errors mode to ON in web config.
    • From custom error we can set that where we can redirect a user when some exception occurs in our application.
    • Set defaultRedirect attribute'value & add a sub tag for 404 error. Values for defaultRediret and redirect are the URLs of the pages for default redirection when some error occurs.

      <!-- Custom Error Handling -->
      <customErrors mode="On" defaultRedirect="~/Home/DefaultError">
      <error statusCode="404" redirect="~/Home/Error404" />
      </customErrors>



  2. Use HandleError filter attribute

    • The HandleError filter works only if the <customErrors> section is turned on in web.config.
    • HandleError attribute provided by MVC framework.
    • It handle only status code 500 errors. It does not handle 404 not found or other types of errors.
    • If you use both customError attribute in web.config & HandleError attribute and any internal server error (500) occurs then HandleError will override behaviour of customError attribute & will handle error with it's own way.
    Example of Controller level handling
[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }

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

  1. You can use HandleError attribute at
    • Action Level – by adding this attribute on Action ex. [HandleError]
    • Controller Level - by adding this attribute on Controller ex. [HandleError]
    • Application Level - by registering filter in FilterConfig.cs in App_Start folder
Example of Application level handling
     public class FilterConfig
   {
     public static void RegisterGlobalFilters(GlobalFilterCollection filters)
     {
     filters.Add(new HandleErrorAttribute());
     }
    }
  1. When error occurs, this will redirect to a view which is in shared folder named 'Error'
  2. You can change view name. ex. [HandleError(View = "DatabaseError")]
  3. That's all
  4. Redirection sequence of error handling
    • For ( 500 Internal server error)
      1. Redirect to view of Handle Error Attribute
      2. Redirect to Url defaultRedirect defined in customErrors tag in web.config. ( if Handle Error is not registered at any level)
    • For ( 404 or other types of errors)
      1. Other url according to status code defined in customErrors tag.

Note:
  1. Handle Error is an inbuilt Filter. We can use our own custom filter attribute by making a class which is derived from Filter Attribute & implements Iexception Filter interface.
  2. To handle ajax request's exception. Visit the link given below.
  3. For more detail about exception. Visit this link :

Sunday, 8 December 2013

How to implement Simple Membership in MVC 4

Importanat Note: We can initialize simple Membership in MVC 4 by two ways. 

 1.   By InitializeSimpleMembershipAttribute which is already present on Account Controller.
 2.   FromGlobal.asax.

Here we are implementing it with second way. 

So First of all remove InitializeSimpleMembershipAttribute  from Account Controller and follow these steps.


 1. Copy this function in Global.asax 

  void initializeMembership()
        {
            if (!WebSecurity.Initialized)
                WebSecurity.InitializeDatabaseConnection("ConnectionString""UserProfile""UserId""UserName", autoCreateTables: true);

        }


2. This function checks the database of given ConnectionString. Create Membership Table if they are not present, and initializes Simple Membership.

3.    Call this function in the end of Application_Start event. Like given below.

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            initializeMembership();

        }

      
 
4. Tables for membership have now been created in DataBase of given Connection string.

5.  You can also add more fields in UserProfile Table. (Not mentioning here now)

6.  Now add default login url in system.web node in web config if not present.
      
              <authentication mode="Forms">
                     <forms loginUrl="~/Account/Login" timeout="2880" />
              </authentication>


7.   Also add some other settings in system.web in web config. This setting enables SimpleMembershipProvider  explicitly.
      
    <!--MVC 4 Simple Membership Settings-->
              <roleManager enabled="true" defaultProvider="SimpleRoleProvider">
                     <providers>
                           <clear/>
                           <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
                     </providers>
              </roleManager>
              <membership defaultProvider="SimpleMembershipProvider">
                     <providers>
                           <clear/>
                           <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
                     </providers>
              </membership>
             
    <!--End of MVC 4 Simple Membership Settings-->


             


Friday, 23 August 2013

Difference between Routing and URL Rewriting

Many developers compares routing to URL rewritting that is wrong. Since both the approaches are very much different. Moreover, both the approaches can be used to make SEO friendly URLs. Below is the main difference between these two approaches.
  1. URL rewriting is focused on mapping one URL (new url) to another URL (old url) while routing is focused on mapping a URL to a resource.
  2. Actually, URL rewriting rewrites your old url to new one while routing never rewrite your old url to new one but it map to the original route.

Different Types of SQL Keys

We have following types of keys in SQL which are used to fetch records from tables and to make relationship among tables or views.
  1. Super Key

    Super key is a set of one or more than one keys that can be used to identify a record uniquely in a table.Example : Primary key, Unique key, Alternate key are subset of Super Keys.
  2. Candidate Key

    A Candidate Key is a set of one or more fields/columns that can identify a record uniquely in a table. There can be multiple Candidate Keys in one table. Each Candidate Key can work as Primary Key.

  3. Primary Key

    Primary key is a set of one or more fields/columns of a table that uniquely identify a record in database table. It can not accept null, duplicate values. Only one Candidate Key can be Primary Key.
  4. Alternate key

    A Alternate key is a key that can be work as a primary key. Basically it is a candidate key that currently is not primary key.
    Example: In below diagram RollNo and EnrollNo becomes Alternate Keys when we define ID as Primary Key.
  5. Composite/Compound Key

    Composite Key is a combination of more than one fields/columns of a table. It can be a Candidate key, Primary key.
  6. Unique Key

    Uniquekey is a set of one or more fields/columns of a table that uniquely identify a record in database table. It is like Primary key but it can accept only one null value and it can not have duplicate values. For more help refer the article Difference between primary key and unique key.
  7. Foreign Key

    Foreign Key is a field in database table that is Primary key in another table. It can accept multiple null, duplicate values. For more help refer the article Difference between primary key and foreign key.
    Example : We can have a DeptID column in the Employee table which is pointing to DeptID column in a department table where it a primary key.

Sunday, 5 May 2013

How to use jQuery.noConflict


Using jQuery.noConflict, you can make multiple versions of jQuery coexist on the same page.  For instance

Copy code
<script src="jquery-1.3.2.js"></script>
<script>
var jq132 = jQuery.noConflict();
</script>
<script src="jquery-1.4.2.js"></script>
<script>
var jq142 = jQuery.noConflict();
</script>


ASP.NET Forms Authentication "Remember Me"

Today I needed to set up a "remember me" functionality for website's login pages. If you ever tried to achieve this using .NET's FormsAuthentication, you might have noticed that... it's just not working. Even if you pass the "createPersistentCookie" parameter value as "true" when initializing FormsAuthentication - the cookie still lives for a limited time only - the time specified as the Forms-Authentication timeout in "web.config". Then the cookie dies.

The only solution was to increase that timeout value in web.config. And it's not a very good idea because of the security reasons.

The solution is to set the authentication cookie timeout explicitly. See the code, which is pretty self-explaining:

private void FormsAuthLogin(string userName, bool rememberMe)
{
  if (!rememberMe)
  {
    FormsAuthentication.RedirectFromLoginPage(userName, false);
  }
  else
  {
    FormsAuthentication.Initialize();
    DateTime expires = DateTime.Now.AddDays(20);
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
      userName,
      DateTime.Now,
      expires, // value of time out property
      true, // Value of IsPersistent property
      String.Empty,
      FormsAuthentication.FormsCookiePath);

    string encryptedTicket = FormsAuthentication.Encrypt(ticket);

    HttpCookie authCookie = new HttpCookie(
          FormsAuthentication.FormsCookieName,
          encryptedTicket);
    authCookie.Expires = expires;

    Response.Cookies.Add(authCookie);

    string returnUrl = FormsAuthentication.GetRedirectUrl(userName, true);
    if (string.IsNullOrEmpty(returnUrl)) returnUrl = "Default.aspx";
    Response.Redirect(returnUrl);
  }
}

Tuesday, 16 April 2013

Ajax request to cross domain web service

Here http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=wbp-3BJWsU8&format=json is an example URL

$.ajax({
            url: 'http://query.yahooapis.com/v1/public/yql',
                data: {
                    q: "select * from json where url ='http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=wbp-3BJWsU8&format=json'",
                    format: "json"
                },
                dataType: "jsonp",
            success: function (data) {

                alert(JSON.stringify(data));


            },
            error: function (result) {
                alert("Sorry no data found.");
            }
        });

Sunday, 14 April 2013

Upload files using jquery fineuploader plugin in ASP.NET MVC

File uploading is one of the common tasks in web development.
One of the best scripts for file uploading is valums/file-upoader.


<link href="@Url.Content("~/css/fileuploader.css")" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="@Url.Content("~/js/fileuploader.js")" type="text/javascript"></script>
 
<div id="file-uploader">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
</noscript>
</div>
 
<script type="text/javascript">
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '@Url.Action("upload")' // put here a path to your page to handle uploading
//,allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'] // user this if you want to upload only pictures
sizeLimit: 4000000, // max size, about 4MB
minSizeLimit: 0, // min size
 
 });
</script>

Valums Ajax Upload Plugin Overview

This plugin uses XHR for uploading multiple files with progress-bar in FF3.6+, Safari4+, Chrome and falls back to hidden iframe based upload in other browsers, providing good user experience everywhere.

Features

  • multiple file select, progress-bar in FF, Chrome, Safari
  • drag-and-drop file select in FF, Chrome
  • uploads are cancellable
  • no external dependencies
  • doesn’t use Flash
  • fully working with https
  • keyboard support in FF, Chrome, Safari
  • tested in IE7,8; Firefox 3,3.6,4; Safari4,5; Chrome; Opera10.60;

Setup File Uploader plugin on ASP.NET MVC site

Here is step-by-step instructions how to setup file-uploader script on your page on ASP.NET MVC site.
- Download the script from github.
- Save files to the root of your project (or any folder you want). You need these three files:
/js/fileuploader.js
/css/fileuploader.css
/img/loading.gif

- Put the script on your page (view):

- Create an ASP.NET MVC  controller which will handle the file uploading and save the file to some location on the server:
public class HomeController : Controller
{
..
[HttpPost]
public ActionResult Upload(HttpPostedFileBase qqfile)
{
if (qqfile != null)
{
// this works for IE
var filename = Path.Combine(Server.MapPath("~/app_data"), Path.GetFileName(qqfile.FileName));
qqfile.SaveAs(filename);
return Json(new { success = true }, "text/html");
}
else
{
// this works for Firefox, Chrome
var filename = Request["qqfile"];
if (!string.IsNullOrEmpty(filename))
{
filename = Path.Combine(Server.MapPath("~/app_data"), Path.GetFileName(filename));
using (var output = System.IO.File.Create(filename))
{
Request.InputStream.CopyTo(output);
}
return Json(new { success = true });
}
}
return Json(new { success = false });
}
}


Note that the controller action must return JsonResult.
Also note that there are two different ways to handle uploads from IE and other (Firefox/Chrome) browsers. The issue here that IE uploads uses multipart-mime while other browsers use Octet-Stream. And Valums Ajax plugin sends an application/octet-stream instead of multipart/form-data which is what the default model binder can work with.

Fine more examples on github.

Some discussions on stackoverflow about known issues:

Friday, 12 April 2013

jquery ajax call to asmx webservice in asp.net

jQuery script



$.ajax({
    type: "POST",
    url: "/WebServices/UserInfo.asmx/CheckAvailability",
    data: "{ 'Title': '" + TitleName + "' }",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        alert(response);
    },
    error: function (data) {
        alert(data);
    }
}); 

Also made change in web config


<webservices>
      <protocols>
        <add name="HttpGet">
        <add name="HttpPost">
     </protocols>
</webservices>
  
















jquery ajax call to partial view in MVC3

$.ajax({
    type: "Get",
    url: "/User/ResetPassword/",
    success: function (data) {
        $("#divId").html(data);
    }
});