Friday, 31 August 2012

What is a private constructor?

When you declare a Constructor with Private access modifier then it is called Private Constructor. We can use the private constructor in singleton pattern.
If you declare a Constructor as private then it doesn’t allow to create object for its derived class, i.e you loose inherent facility for that class.  

Example:
 Class A
 {
 // some code
Private Void A()
{
 //Private Constructor
 }
 }

 Class B:A
{
//code
 }
 B obj = new B();

// will give Compilation Error
Because Class A constructor declared as private hence its accessibility limit is to that class only, Class B can't access. When we create an object for Class B that constructor will call constructor A but class B have no rights to access the Class A constructor hence we will get compilation error.

ASP.NET MVC Execution Process


Note:
When an ASP.NET MVC Web application runs in IIS 7.0, no file name extension is required for MVC projects. However, in IIS 6.0, the handler requires that you map the .mvc file name extension to the ASP.NET ISAPI DLL.


The following table lists the stages of execution for an MVC Web project.

Stage Details
Receive first request for the application In the Global.asax file, Route objects are added to the RouteTable object.
Perform routing The UrlRoutingModule module uses the first matching Route object in the RouteTable collection to create the RouteData object, which it then uses to create a RequestContext (IHttpContext) object.
Create MVC request handler The MvcRouteHandler object creates an instance of the MvcHandler class and passes it the RequestContext instance.
Create controller The MvcHandler object uses the RequestContext instance to identify the IControllerFactory object (typically an instance of the DefaultControllerFactory class) to create the controller instance with.
Execute controller The MvcHandler instance calls the controller s Execute method.
Invoke action Most controllers inherit from the Controller base class. For controllers that do so, the ControllerActionInvoker object that is associated with the controller determines which action method of the controller class to call, and then calls that method.
Execute result A typical action method might receive user input, prepare the appropriate response data, and then execute the result by returning a result type. The built-in result types that can be executed include the following: ViewResult (which renders a view and is the most-often used result type), RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, and EmptyResult.

Thursday, 30 August 2012

How to Send Mail with Error Message Details

File Upload Control with ASP.NET and AJAX

Problem: How to use your Asp.Net Fileupload control with AJAX.


As everybody knows who uses ajax in his daily programming is, ajax don't postback the whole page, AJAX allows the webpage to update Asynchronously.

Lots of us create our applications in asp.net and use fileuplod control to upload files on server side. In such case if we are using ajax with fileupload control, then we find out that null value in our fileupload control(empty HttpFileCollection), its because of the fileupload control which needs a complete postback to upload file.
The FileUpload control does not work inside an UpdatePanel control for uploading files using Asynchronous Postback. It is due to security imposed by browser which doesnot allow JavaScript to directly access the files in user system. But defenately, Synchronous Postback can be used to upload files. ASP.NET AJAX allows both Synchronous and Asynchronous Postback.
So,  "You cannot use Partial Postback to upload files on server, you have to use full post back".
Below is the Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile=
"Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace=
"AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
  <title>Untitled Page</title>
 </head>
 <body>
  <form id="form1" runat="server">
   <asp:ScriptManager ID="ScriptManager1" runat="server" />
   <div>
    <table width="50%" cellpadding="2" cellspacing="0">
     <tr>
      <td>
       <asp:UpdatePanel ID="UpdatePanel1" runat="server" 
UpdateMode="conditional">
        <ContentTemplate>
         <asp:FileUpload ID="FileUpload1" runat="server" />
         <asp:Button ID="btnUpload" runat="server" Text="Upload"
 OnClick="btnUpload_Click" />
        </ContentTemplate>
        <Triggers>
         <asp:PostBackTrigger ControlID="btnUpload" />  
        </Triggers>
       </asp:UpdatePanel>
      </td>
     </tr>
    </table>
   </div>
  </form>  
 </body>
</html> 
 
using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            FileUpload1.SaveAs(MapPath("~/TEST/" + FileUpload1.FileName));
        }
    }
}
Now, AJAX Asynchronous  File Upload Control is available to upload files with Post back.


Load UserControl using jQuery

ASPX Page

  <div style="float: left; width: 100%;">
        <input type="button" id="btnSubmit" value="Load" /></div>
    <div id="dvProducts">
    </div>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnSubmit").live("click", function () {
                LoadProducts();
                $(this).hide();
              
            });

            function LoadProducts() {
                $.ajax({
                    type: "POST",
                    url: "Product.aspx/LoadUserControl",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        $("#dvProducts").append(r.d);
                    }
                });
            }
        });

    </script>

UserControl (ucProduct.ascx)

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ucProduct.ascx.cs" Inherits="jQueryPOC.UserControls.ucProduct" %>
<script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<div style="float: left; width: 60%;">
<asp:DataList ID="DataList1" runat="server" RepeatColumns="1" RepeatDirection="Horizontal"
    DataSourceID="ObjectDataSource1">
    <ItemTemplate>
        <div>
            <asp:Label ID="lblProductName" runat="server" Text='<%# Eval("ProductName") %>'></asp:Label>
            <div style="display: none;">
                <asp:Label ID="lblProductID" runat="server" Text='<%# Eval("ProductID") %>'></asp:Label>
                <asp:ImageMap ID="imgProduct" runat="server" ImageUrl='<%# Eval("ImageName") %>'>
                </asp:ImageMap>
            </div>
        </div>
    </ItemTemplate>
</asp:DataList>
</div>
<div id="dvDetails" style="float: left; width: 20%;display:none; border:1px;">
</div>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetProducts"
    TypeName="jQueryPOC.UserControls.ucProduct"></asp:ObjectDataSource>

ucProduct.ascx.cs
 public IList<ProductDO> GetProducts()
        {
            IList<ProductDO> products = new List<ProductDO>();
            products.Add(new ProductDO { ProductID = 1, ProductName = "Samsung Galaxy S3", Price = 36000, ImageName = "http://localhost:58445/images/SGS3.jpg" });
            products.Add(new ProductDO { ProductID = 2, ProductName = "Apple iPhone 4", Price = 35000, ImageName = "http://localhost:58445/images/AiP4.jpg" });
            products.Add(new ProductDO { ProductID = 3, ProductName = "Samsung Galaxy Note", Price = 32000, ImageName = "http://localhost:58445/images/SGN.jpg" });
            ProductDO obj = products.Where(o => o.ProductID == 1).SingleOrDefault();
            return products;
        }

Page method to get UserControl
[WebMethod]
        public static string LoadUserControl()
        {
            using (Page page = new Page())
            {
                HtmlForm form = new HtmlForm();
                UserControl userControl = (UserControl)page.LoadControl("UserControls/ucProduct.ascx");
                form.Controls.Add(userControl);
                using (StringWriter writer = new StringWriter())
                {
                    page.Controls.Add(form);
                    HttpContext.Current.Server.Execute(page, writer, false);
                    return writer.ToString();
                }
            }
        }

ASP.NET MVC - Highlight Current Link using extension methods

On _layout view :

<ul id="menu">
        <li>@Html.MenuLink("Contact", "Index", "Home")
            @Html.MenuLink("Edit", "Edit", "Home")
            @Html.MenuLink("Detail", "Detail", "Home")</li>
    </ul>

css :

ul#menu li a {
    background: none;
    color: #999;
    padding: 5px;
    border-radius: 15px;
    text-decoration: none;   
}

ul#menu li a.currentMenuItem {
    background-color: black;  
    color: white;
}

class :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace System.Web.Mvc.Html
{
    public static  class MenuExtenstionClass
    {
        public static MvcHtmlString MenuLink(this HtmlHelper helper, string text, string action, string controller)
        {
            var routeData = helper.ViewContext.RouteData.Values;
            var currentController = routeData["controller"];
            var currentAction = routeData["action"];

            if (String.Equals(action, currentAction as string,StringComparison.OrdinalIgnoreCase)
                        && String.Equals(controller, currentController as string, StringComparison.OrdinalIgnoreCase))
            {
                return helper.ActionLink(text, action, controller, null,new { @class = "currentMenuItem" });
            }
            return helper.ActionLink(text, action, controller);
        }
    }
}

How to dynamically change connection string/appSetting in web.config

// Update AppSetting in web config
public void UpdateAppSetting(string key, string value)
{
    Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
    if (config.AppSettings.Settings[key] == null)
    {
        config.AppSettings.Settings.Add(key, value);
    }
    else
    {
        config.AppSettings.Settings[key].Value = value;
    }
    config.Save();
    ConfigurationManager.RefreshSection("appSettings");
}
 
// Update connection string in web config
public void UpdateConnectionString(string key, string value)
{
    Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
    if (config.ConnectionStrings.ConnectionStrings[key] == null)
    {
        config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(key, value));
    }
    else
    {
        config.ConnectionStrings.ConnectionStrings[key].ConnectionString = value;
    }
    config.Save();
    ConfigurationManager.RefreshSection("connectionStrings");
}
 
 
You can update the contents of web.cofig file by simply calling above functions like this:-
 
protected void Page_Load(object sender, EventArgs e)
{
    UpdateAppSetting("Country", "India");
    UpdateConnectionString("dbName", "dbSchool");
}