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");
}
 

Wednesday, 29 August 2012

Automatically redirect user when session timout

You can create a BasePae class which inherits System.Web.UI.Page. Override the OnInit method and write appropriate code in that which will redirect to default page.

public class BasePage : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        if (Session["UserName"] == null)
        {
            Response.Redirect("~/LoginPage.aspx");
        }
    }
}

And inherit all your ASPX pages from BasePage class, instead of System.Web.UI.Page like this:-
public partial class HomePage : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}

And finally in your login page, simply set Session["UserName"] with user's name.

Tuesday, 28 August 2012

SQL SERVER: SQL Query To Find Most used Tables

We have very large database and today we want to search the tables which are used mostly.

Means tables which are used in Procedures, Constraints, Views, Triggers etc.

I know this is very strange requirement, but we need to do this.

So, I tried to make an query which will help me to find out the top most tables used in other objects as I mentioned

Let me share that sp with all of you:

SELECT TableName, COUNT(*) 
FROM ( 
Select Distinct 
o.Name 'TableName', 
op.Name 'DependentObject' 
From SysObjects o 
INNER Join SysDepends d ON d.DepId = o.Id 
INNER Join SysObjects op on op.Id = d.Id 
Where o.XType = 'U' 
Group by o.Name, o.Id, op.Name 
) x 
GROUP BY TableName 
ORDER BY 2 desc