DropDownList in GridView Async and find Control in Class File in c#.net


In this article, I have described the ways of keeping DropDownList in the GridView and binding the data by preserving the default SelectedValue. Apart from DropDownList, I have also shown how to keep CheckBox, RadioButtonList, TextBox in the GridView and preserving the default data,how to find control in class file ,how to use async Trigger in Update Panel using GridView in C#.net

Placing the DropDownList in the GridView

To place the DropDownList in the GridView, you will have to use asp:TemplateField that under <Columns>, Generally you will need to use the DropDownList in the GridView in the Edit mode (under EditItemTemplate, However this solution will work for you even if you want to place the DropDownList in the ItemTemplate) where you want your user to select the data from the DropDownList and update the record. A typical example is shown in the picture below

Image

The aspx page code of above GridView is below

<%@ Page Title="" Language="C#" MasterPageFile="~/GridMaster.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="Default" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"
    ClientIDMode="Static">
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" ClientIDMode="Static">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="GridView1" />
        </Triggers>
        <ContentTemplate>
            <asp:Label ID="lblMessage" runat="server" EnableViewState="true" />
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ClientIDMode="Static"
                GridLines="None" AutoGenerateEditButton="True" OnRowCancelingEdit="GridViewCancelEdit"
                OnRowEditing="GridViewEdit" OnRowUpdating="GridViewUpdate" 
                DataKeyNames="PersonID" CellPadding="4" ForeColor="#333333">
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                <Columns>
                    <asp:BoundField DataField="PersonID" HeaderText="Person ID" ReadOnly="True" Visible="false" />
                    <asp:TemplateField HeaderText="First Name">
                        <ItemTemplate>
                            <%# Eval("FName") %>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FName") %>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Last Name">
                        <ItemTemplate>
                            <%# Eval("LName") %>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LName") %>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Department DropDown">
                        <ItemTemplate>
                            <%# Eval("DeptName")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:DropDownList ID="dropDownDept" DataSource="<%# BindDropDownDepartment() %>"
                                DataTextField="DeptName" DataValueField="DeptId" runat="server" SelectedValue='<%# Eval("DeptId").ToString() %>'>
                            </asp:DropDownList>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="CustomCheckBox Field">
                        <ItemTemplate>
                            <%# Eval("IsActive") %>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:CheckBox ID="chkActive" runat="server" Checked='<%# Eval("IsActive") %>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="RadioButtonField">
                        <ItemTemplate>
                            <%# Eval("IsActive") %>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:RadioButtonList ID="radioActive" runat="server" RepeatDirection="Horizontal"
                                RepeatLayout="Flow" SelectedValue='<%# Eval("IsActive") %>'>
                                <asp:ListItem Text="True" Value="True" />
                                <asp:ListItem Text="False" Value="False" />
                            </asp:RadioButtonList>
                        </EditItemTemplate>
                    </asp:TemplateField>
                </Columns>
                <EditRowStyle BackColor="#999999" />
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
            </asp:GridView>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

In your code behind file of Default.aspx.cs code will be such as below given

using System;
using System.Data;
 
public partial class Default : System.Web.UI.Page
{
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            var obj = new BAL();
            obj.LoadPerson(ref  GridView1);
        }
    }
    
    protected DataTable BindDropDownDepartment()
    {
        var obj = new BAL();
        return obj.LoadAll();
    }
    protected void GridViewCancelEdit(object sender, System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
    {
        var obj = new BAL();
        GridView1.EditIndex =-1;
        obj.LoadPerson(ref  GridView1);
 
    }
    protected void GridViewEdit(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
    {
        var obj = new BAL();
        GridView1.EditIndex = e.NewEditIndex;
        obj.LoadPerson(ref  GridView1);
 
    }
    protected void GridViewUpdate(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
    {
        
        GridView1.EditIndex = -1;
        var obj = new BAL();
        obj.UpdateGrid(ref GridView1, e.RowIndex);
    }
}

Now Add a class File in Your Application and write down in that below given code.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls;
 
/// <summary>
/// Summary description for BAL
/// </summary>
public class BAL
{
 
    public BAL()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public void LoadPerson(ref GridView grd)
    {
 
        using (var objCon = new SqlConnection())
        {
            objCon.ConnectionString = ConfigurationManager.ConnectionStrings["cnGrid"].ConnectionString;
            if (objCon.State == ConnectionState.Closed)
                objCon.Open();
            using (var objAdp = new SqlDataAdapter("usp_PersonRecords", objCon))
            {
                objAdp.SelectCommand.CommandType = CommandType.StoredProcedure;
                var ds = new DataSet();
                objAdp.Fill(ds);
                grd.DataSource = ds.Tables[0];
                grd.DataBind();
            }
        }
 
    }
    public DataTable LoadAll()
    {
        dynamic objDt;
        using (var objCon = new SqlConnection())
        {
            objCon.ConnectionString = ConfigurationManager.ConnectionStrings["cnGrid"].ConnectionString;
            if (objCon.State == ConnectionState.Closed)
                objCon.Open();
            using (var objAdp = new SqlDataAdapter("usp_DeptRecords", objCon))
            {
                objAdp.SelectCommand.CommandType = CommandType.StoredProcedure;
                var ds = new DataSet();
                objAdp.Fill(ds);
                objDt = ds.Tables[0];
            }
        }
        return objDt;
    }
    public void UpdateGrid(ref GridView grd, int index)
    {
 
        var row = grd.Rows[index];
        var ddlDept = (DropDownList)row.FindControl("dropDownDept");
        var txtFname = (TextBox)row.FindControl("txtFirstName");
        var txtLname = (TextBox)row.FindControl("txtLastName");
        var isActive = (RadioButtonList)row.FindControl("radioActive");
        var chkAct = (CheckBox)row.FindControl("chkActive");
 
        var id = Convert.ToInt32(grd.DataKeys[row.RowIndex].Value);
        var FNAME = txtFname.Text.ToUpper();
        var lname = txtLname.Text.ToUpper();
        var deptID = Convert.ToInt32(ddlDept.SelectedItem.Value);
        var isactive = isActive.SelectedValue == "True" ? Convert.ToInt32(1) : Convert.ToInt32(0);
        using (var objCon = new SqlConnection())
        {
            objCon.ConnectionString = ConfigurationManager.ConnectionStrings["cnGrid"].ConnectionString;
            if (objCon.State == ConnectionState.Closed)
                objCon.Open();
            using (var cmd = new SqlCommand("usp_PersonUpdate", objCon))
            {
                cmd.CommandType = CommandType.StoredProcedure;
 
                var parm = new[]
                               {
                                   new SqlParameter("@PersonID", SqlDbType.Int, Int32.MaxValue) {Value =id},
                                   new SqlParameter("@FName", SqlDbType.VarChar, 100) {Value =FNAME },
                                   new SqlParameter("@LName", SqlDbType.VarChar, 100) {Value = lname},
                                   new SqlParameter("@DeptID", SqlDbType.Int, Int32.MaxValue) {Value =deptID},
                                   new SqlParameter("@IsActive", SqlDbType.Bit) {  Value = isactive}
                               };
                cmd.Parameters.AddRange(parm);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                LoadPerson(ref grd);
            }
        }
    }
}

Now  Run by pressing F5 remember that before run to this ensure your database and connection string  in web config file and change in that setting of your MSSQLServer

<connectionStrings>
		<add name="cnGrid" connectionString="Data Source=xxxx;Initial Catalog=dbGrid;Persist Security Info=True;User ID=xxx;Password=xxx;Pooling=False" providerName="System.Data.SqlClient"/>
</connectionStrings>

Download Url : https://docs.google.com/file/d/0B-sDsBkcsM1YODBWaVZmLTJ6YlE/edit?usp=sharing

CheckBoxList in ASP.Net MVC3 Razor


CheckBoxList in ASP.Net MVC3 Razor

 

If we want to create many check boxes or check boxes list we can call it inside a loop as follows.

1
2
3
4
@foreach (var item in MyCollection)
{
@Html.CheckBox("checkBoxName", new {value=item.checkBoxValue })@item.CheckBoxText<br />
}

 

Here is a generic extension method for create a check boxes list in an elegant manner.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public static MvcHtmlString CheckBoxList<T>(this HtmlHelper helper,
String name,
IEnumerable<T> items,
String textField,
String valueField,
IEnumerable<T> selectedItems=null)
{
Type itemstype = typeof(T);
PropertyInfo textfieldInfo = itemstype.GetProperty(textField,typeof(String));
PropertyInfo valuefieldInfo = itemstype.GetProperty(valueField);
 
TagBuilder tag;
StringBuilder checklist = new StringBuilder();
foreach(var item in items)
{
tag = new TagBuilder("input");
tag.Attributes["type"] = "checkbox";
tag.Attributes["value"] = valuefieldInfo.GetValue(item,null).ToString();
tag.Attributes["name"] = name;
if (selectedItems != null && selectedItems.Contains(item))
{
tag.Attributes["checked"] = "checked";
}
tag.InnerHtml = textfieldInfo.GetValue(item,null).ToString();
checklist.Append(tag.ToString());
checklist.Append("<br />");
}
return MvcHtmlString.Create(checklist.ToString());
}

In the first three lines we get the type of the data collection then get the property info of text field and value field that will be used to create each check box. We enumerate over the input data collection and use  TagBuilder class to create input tag and set its attributes like type,name, and value. We check the selectedItems collection to set checked attribute of our check box.

Say we have a list of users that we display it as checkboxlist to select some users, we can use our helper method as follows

1
@Html.CheckBoxList("SelectedUsers", AllUsersList, "Name", "ID")

To get the values of checked users we have two scenarios:
Strongly typed model scenario:
The model must have pro

perty with the same name that we provided to our helper method.

1
2
3
4
5
6
class MyModel
{
//Note you can define it as array of strings, dates or any primitive data type
//according to the type of the property of value field.
Public Int32[] SelectedUsers{get; set;}
}

when we post the view, the model binder will bind the values of selected check boxes into the property with the same name.

Not Strongly typed model scenario:
In this case, our action method that will handle our request(decorated by HttpPost attribute) should be defined to accept a FormCollection parameter that will contain key with the same name we provided to our helper method

1
2
3
4
5
6
[HttpPost]
public ActionResult ActionMethodName(FormCollection myForm)
{
String selectedusers = myForm["SelectedUsers"];
//Note this will return the selected users ids as comma separated string.
}

How To Get CheckBox Selected Values in Controller In MVC3


Introduction

In this article i am going to define u you how we can get selected values of checkbox in mvc3 in controller.in this article u will also get to know about multiple form in a single view how to use them.

Step 1: Make a new Empty Project using mvc3 in visual studio 2010.

Step 2: Now Add Collection Class in Model folder by Right click on model whose code would be such as below given.

 public class MyViewModel
    {
        public int Id { get; set; }
        public bool Checkbox { get; set; }
        public string Value { get; set; }
    }
 
 
    // view model for checklistbox
    public class CheckBoxListViewModel
    {
        public List<CheckListBoxItem> Items { get; set; }
 
        // the name of this list should be the same as of the CheckBoxes otherwise you will not get any result after post
        public List<string> SelectedValues { get; set; }
    }
 
    // represents single check box item
    public class CheckListBoxItem
    {
        public string Value { get; set; }
        public string Text { get; set; }
        public bool IsCheck { get; set; }
    }

Step 3: After this add a HomeController in Controller Folder and write in that below given code.

public ActionResult Index()
        { 
 
            var list = new List<MyViewModel>
            {
                new MyViewModel { Id = 1, Checkbox = false ,Value="Coal"},
                new MyViewModel { Id = 2, Checkbox= false ,Value="Cotton"},
                new MyViewModel { Id = 3, Checkbox = false ,Value = "Fabric"},
            };
            var outObj = list.Select(row => new SelectListItem()
                            {
                                Text = row.Value,
                                Value = row.Id.ToString(CultureInfo.InvariantCulture),
                                Selected = row.Checkbox
                            });
            ViewBag.keydata = outObj;
            // pass ViewModel object to View for display
 
            return View();
        }

Step 4 :  Now Add your view index.cshtml in view folder and paste in his below given code.

@{
    ViewBag.Title = "Index";
    var obj = ViewBag.keydata;
}
@using (Html.BeginForm("Index", "Home"))
{
    IEnumerable<SelectListItem> ct = ViewBag.keydata;
    foreach (var item in ct)
    {
    @Html.CheckBox("chk", item.Selected, new { value = item.Value });<label>@item.Text</label>
    }
<div>
       <input type="submit" value="Send" name="action:Send" /></div>
}

Step 5:  Now Make your Index Action with HttpPost Attribute in Controller which is below given.

 [HttpPost]
        [MultipleButton(Name = "action", Argument = "Send")]
        public ActionResult Index(FormCollection obj)
        {
           
            if (obj != null)
            {
                string[] AllStrings = obj["chk"].Split(',');
                foreach (string item in AllStrings)
                {
                    if (item.Contains("false"))
                    {
 
                    }
                    else
                    {
                        var outk = item;
                    }
 
 
 
                    // handle value
                }
            }
           
            return RedirectToAction("Index", "Home");
        }
Now Run by pressing f5 and See by putting Result in Your action you will get your all selected
Check boxes values.

If you Want to Download complete source of this article you can get to download it by click on below given url

https://docs.google.com/file/d/0B-sDsBkcsM1YWV9PWVUwYlVHRjA/edit?usp=sharing

Creating an expandable master-details table using DataTable Plugin of jQuery


Hello Friends today i need to display master details so i decided to do rnd on net after lot of effort i found a good jQuery datatable plugin that’s really awesome and intellgent.

if you want to creating fully functional tables with pagination, sorting, filtering features is an easy task if you use the jQuery DataTables plug-in. This plug-in enables you to add all of these functionalities to a plain HTML table using a single line of code as shown in the following example:

(‘#mygrid’).datatable();

but before this you will have to need some files such as jQuery Datatable and themes file.

Now i will explain u step by step my jQuery Datatable  plugin article.basically in this practical is composed in MVC3 +Razor view Engine and Entity Framework.

in my sample have Three views

1) Index –display to static static data

2) Server Side — display server side data of Action method using ajax request and also have Model help.

3) Ajax Loading — Display using complete ajax request data on view without model class help.

 

Step 1) First of all you will have to make a New Empty MVC3 Project using Visual Studio 2010 as below given in image :

Image

Step 2 : Now Make DataBase dbNestedDataTable and In that add Two Tables and Also add Some Dummy entries those tables.

for help you can use to below given sqlscript.

USE dbNestedDataTable

go

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N’[dbo].[Company]‘) AND type in (N’U’))
BEGIN
CREATE TABLE [dbo].[Company](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL,
    [Address] [varchar](100) NULL,
 CONSTRAINT [PK_Company] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N’[dbo].[Employee]‘) AND type in (N’U’))
BEGIN
CREATE TABLE [dbo].[Employee](
    [EmployeeID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL,
    [Position] [varchar](50) NULL,
    [Phone] [varchar](50) NULL,
    [Email] [varchar](50) NULL,
    [CompanyID] [int] NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
    [EmployeeID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N’[dbo].[FK_Employee_Company]‘) AND parent_object_id = OBJECT_ID(N’[dbo].[Employee]‘))
ALTER TABLE [dbo].[Employee]  WITH CHECK ADD  CONSTRAINT [FK_Employee_Company] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[Company] ([ID])
Step 3: Now Come back in ur web application and now add a controller by right click on controller folder with name of HomeController.

Image

Step 4 : Now go into home controller u will see a index action and by right click on View and Click on AddView u will get a new view in View->Home->index.cshtml as below given image.

 

 

 

 

 

Image

Step 5 : Now Click on Index.cshtml view and go into it’s source  and paste below given code.

@{
    ViewBag.Title = "Index";
}
 
    @section onReady
    {
    var oTable;
$('#companies tbody td img').click(function () {
    var nTr = this.parentNode.parentNode;
    if (this.src.match('Math-minus-icon')) {
        /* This row is already open - close it */
        this.src = "/Content/Math-plus-icon.png";
        oTable.fnClose(nTr);
    }
    else {
        /* Open this row */
        this.src = "/Content/Math-minus-icon.png";
        var companyid = $(this).attr("rel");
        $.get("@Url.Action("CompanyEmployees","Home")?companyID=" + companyid, function (employees) {
            oTable.fnOpen(nTr, employees, 'details');
        });
    }
        });
        /* Initialize table and make first column non-sortable*/
oTable = $('#companies').dataTable({  "bJQueryUI": true,
                                        "aoColumns": [
                                        {   "bSortable": false,
                                            "bSearchable": false },
                                        null,
                                        null,
                                        null
                                ]
    });
}
 
<div id="demo">
    <table id="companies" class="display">
        <thead>
            <tr>
                <th>
                </th>
                <th>
                    Company name
                </th>
                <th>
                    Address
                </th>
                <th>
                    Town
                </th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>
                    <img src="/Content/Math-plus-icon.png" rel="1" style="cursor:pointer;" alt="expand/collapse">
                </td>
                <td>
                    Emkay Entertainments
                </td>
                <td>
                    Nobel House, Regent Centre
                </td>
                <td>
                    Lothian
                </td>
            </tr>
            <tr>
                <td>
                    <img src="/Content/Math-plus-icon.png" rel="2" style="cursor:pointer;" alt="expand/collapse">
                </td>
                <td>
                    The Empire
                </td>
                <td>
                    Milton Keynes Leisure Plaza
                </td>
                <td>
                    Buckinghamshire
                </td>
            </tr>
        </tbody>
    </table>
</div>

Step 6: Now You will have to go in _Layout.chstml page that's in Shared Folder in which you will
add some resources link and url which are below given.
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
    <link href="@Url.Content("~/Content/dataTables/demo_page.css")" rel="stylesheet" type="text/css" />
        <link href="@Url.Content("~/Content/dataTables/demo_table.css")" rel="stylesheet" type="text/css" />
        <link href="@Url.Content("~/Content/dataTables/demo_table_jui.css")" rel="stylesheet" type="text/css" />
        <link href="@Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" media="all" />
        <link href="@Url.Content("~/Content/themes/smoothness/jquery-ui-1.10.3.custom.min.css")"rel="stylesheet" type="text/css" media="all" />
        <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery.dataTables.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery-ui.js")" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            @RenderSection("onReady", required: false)
        });
    </script>
</head>
<body>
    <header class="ui-state-processing">
        <ul>
            <li>
        @Html.ActionLink("Static table", "Index", "Home")        
            </li>
        
        
            <li>@Html.ActionLink("Server-side generated table", "ServerSide", "Home")</li>
 
       <li> @Html.ActionLink("Ajax-loaded table", "Ajax", "Home")</li>
        </ul>
    </header>
    <div class="ui-widget-content">
        @RenderBody()
    </div>
</body>
</html>

Step 7 : Now Add new Entity model by right click on Model Folder and make connection with your database which u have been made in MSSQLSERVER and then
you will see that your application will give u below type image.
Image
Image
Step 8: Now add Two Methods in your home controller.
   public ActionResult CompanyEmployees(int? companyID)
        {
            var employees = GetEmployees();
            var companyEmployees = (from e in employees
                                    where (companyID == null || e.CompanyID == companyID)
                                    select e).ToList();
            return PartialView("CompanyEmployees", companyEmployees);
        }
        public IEnumerable<Employee> GetEmployees()
        {
            using (var db = new dbNestedDataTableEntities())
            {
                return db.Employees.ToList();
            }
        }
and complie then run by pressing F5 on Index page you will see that look as below given.
Image

Upto this you will get data static data display how using datatable plugin in
MVC3
now you will do Second Thing ServerSide Data How Bind to DataTable in MVC From View Action.
Add Two Method in Your homecontroller
  public ActionResult ServerSide()
        {
            var obj = GetCompanies();
            return View(obj);
        }
        public IEnumerable<Company> GetCompanies()
        {
            using (var db = new dbNestedDataTableEntities())
            {
                return db.Companies.ToList();
            }
        }
and Add a new view whose name is ServerSide.cshtml
in which source code will be such as.
@model IEnumerable< mvcwithnesteddatatable.Models.Company>
@{
    ViewBag.Title = "ServerSide";
}
@section onReady
    {
    var oTable;
$('#companies tbody td img').click(function () {
    var nTr = this.parentNode.parentNode;
    if (this.src.match('Math-minus-icon')) {
        /* This row is already open - close it */
        this.src = "/Content/Math-plus-icon.png";
        oTable.fnClose(nTr);
    }
    else {
        /* Open this row */
        this.src = "/Content/Math-minus-icon.png";
        var companyid = $(this).attr("rel");
        $.get("@Url.Action("CompanyEmployees","Home")?companyID=" + companyid, function (employees) {
            oTable.fnOpen(nTr, employees, 'details');
        });
    }
        });
        /* Initialize table and make first column non-sortable*/
oTable = $('#companies').dataTable({  "bJQueryUI": true,
                                        "aoColumns": [
                                        {   "bSortable": false,
                                            "bSearchable": false },
                                        null,
                                        null,
                                        null
                                ]
    });
}
<div id="demo">
    <table id="companies" class="display">
        <thead>
            <tr>
                <th></th>
                <th>ID</th>
                <th>Company Name</th>
                <th>Town</th>
            </tr>
        </thead>
    @foreach (var item in Model) {
        <tr>
            <td><img src="/Content/Math-plus-icon.png" style="cursor:pointer;" alt="expand/collapse" rel="@item.ID"/></td>
            <td>@item.ID</td>
            <td>@item.Name</td>
            <td>@item.Address</td>
        </tr>
    }
    </table>
</div>
In Third phase of this article complete ajax request will do have to add a class in Model folder whose name is
JQueryDataTableParamModel.cs ,it's code will be such as
 /// <summary>
    /// Class that encapsulates most common parameters sent by DataTables plugin
    /// </summary>
    public class JQueryDataTableParamModel
    {
        /// <summary>
        /// Request sequence number sent by DataTable, same value must be returned in response
        /// </summary>       
        public string sEcho{ get; set; }
 
        /// <summary>
        /// Text used for filtering
        /// </summary>
        public string sSearch{ get; set; }
 
        /// <summary>
        /// Number of records that should be shown in table
        /// </summary>
        public int iDisplayLength{ get; set; }
 
        /// <summary>
        /// First record that should be shown(used for paging)
        /// </summary>
        public int iDisplayStart{ get; set; }
 
        /// <summary>
        /// Number of columns in table
        /// </summary>
        public int iColumns{ get; set; }
 
        /// <summary>
        /// Number of columns that are used in sorting
        /// </summary>
        public int iSortingCols{ get; set; }
 
        /// <summary>
        /// Comma separated list of column names
        /// </summary>
        public string sColumns{ get; set; }
 
    }

After add this code in your class file go into homecontroller and add two more methods which are
below given.


public ActionResult Ajax()
        {
            return View();
        }
        /// <summary>
        /// Returns data by the criterion
        /// </summary>
        /// <param name="param">Request sent by DataTables plugin</param>
        /// <returns>JSON text used to display data
        /// <list type="">
        /// <item>sEcho - same value as in the input parameter</item>
        /// <item>iTotalRecords - Total number of unfiltered data. This value is used in the message: 
        /// "Showing *start* to *end* of *iTotalDisplayRecords* entries (filtered from *iTotalDisplayRecords* total entries)
        /// </item>
        /// <item>iTotalDisplayRecords - Total number of filtered data. This value is used in the message: 
        /// "Showing *start* to *end* of *iTotalDisplayRecords* entries (filtered from *iTotalDisplayRecords* total entries)
        /// </item>
        /// <item>aoData - Twodimensional array of values that will be displayed in table. 
        /// Number of columns must match the number of columns in table and number of rows is equal to the number of records that should be displayed in the table</item>
        /// </list>
        /// </returns>
        public ActionResult AjaxHandler(JQueryDataTableParamModel param)
        {
            var allCompanies = GetCompanies();
            IEnumerable<Company> filteredCompanies;
            //Check whether the companies should be filtered by keyword
            if (!string.IsNullOrEmpty(param.sSearch))
            {
                //Used if particulare columns are filtered 
                var nameFilter = Convert.ToString(Request["sSearch_1"]);
                var addressFilter = Convert.ToString(Request["sSearch_2"]);
                var townFilter = Convert.ToString(Request["sSearch_3"]);
 
                //Optionally check whether the columns are searchable at all 
                var isNameSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
                var isAddressSearchable = Convert.ToBoolean(Request["bSearchable_2"]);
                var isTownSearchable = Convert.ToBoolean(Request["bSearchable_3"]);
 
                filteredCompanies = GetCompanies()
                   .Where(c => isNameSearchable && c.Name.ToLower().Contains(param.sSearch.ToLower())
                               ||
                               isAddressSearchable && c.Address.ToLower().Contains(param.sSearch.ToLower())
                               );
            }
            else
            {
                filteredCompanies = allCompanies;
            }
 
            var isNameSortable = Convert.ToBoolean(Request["bSortable_1"]);
            var isAddressSortable = Convert.ToBoolean(Request["bSortable_2"]);
            var isTownSortable = Convert.ToBoolean(Request["bSortable_3"]);
            var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
            Func<Company, string> orderingFunction = (c => sortColumnIndex == 1 && isNameSortable ? c.Name :
                                                           sortColumnIndex == 2 && isAddressSortable ? c.Address :
                                                           "");
 
            var sortDirection = Request["sSortDir_0"]; // asc or desc
            if (sortDirection == "asc")
                filteredCompanies = filteredCompanies.OrderBy(orderingFunction);
            else
                filteredCompanies = filteredCompanies.OrderByDescending(orderingFunction);
 
            var displayedCompanies = filteredCompanies.Skip(param.iDisplayStart).Take(param.iDisplayLength);
            var result = from c in displayedCompanies select new[] { Convert.ToString(c.ID), c.Name, c.Address };
            return Json(new
            {
                sEcho = param.sEcho,
                iTotalRecords = allCompanies.Count(),
                iTotalDisplayRecords = filteredCompanies.Count(),
                aaData = result
            },
                        JsonRequestBehavior.AllowGet);
        }
        
      
    }
After adding these two methods make a new view with Ajax.cshtml name and in that source code will be
@{
    ViewBag.Title = "Ajax";
}
@section onReady
{
 
    var oTable;
    $('#companies tbody td img').live('click', function () {
    var nTr = this.parentNode.parentNode;
    if (this.src.match('details_close')) {
    /* This row is already open - close it */
    this.src = "@Url.Content("/Content/images/details_open.png")";
    oTable.fnClose(nTr);
    }
    else {
    @*/* Open this row */*@
    this.src = "@Url.Content("/Content/images/details_close.png")";
    var companyid = $(this).attr("rel");
    $.get("@Url.Action("CompanyEmployees", "Home")?companyID=" + companyid, function (employees) {
    oTable.fnOpen(nTr, employees, 'details');
    });
    }
    });
 
    
    @*/* Initialize table and make first column non-sortable*/*@
    
    
      oTable = $('#companies').dataTable({
                                    "bProcessing": true,
                                    "bServerSide": true,
                                    "sAjaxSource": 'AjaxHandler',
                                    "bJQueryUI": true,
                                    "aoColumns": [
			                                    { "bSortable": false, "bSearchable": false,
			                                        "fnRender": function (oObj) {
			                                            return '<img src="/Content/images/details_open.png" alt="expand/collapse" rel="' + oObj.aData[0] + '"/>';
			                                        } 
			                                    },
			                                  { "sName": "Name" },
    { "sName": "Address" }
    ],
    
        });
 
}
<div id="demo">
    <table id="companies" class="display">
        <thead>
            <tr>
                <th>ID</th>
                <th>Company Name</th>
                <th>Town</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>



Now Run Your Application and See Result on Click of three links and observer the difference also enjoy
your programming.
If you want to download this practical source complete get to it by below given url.
https://docs.google.com/file/d/0B-sDsBkcsM1Yc0ZRQlM5S1Z4MFE/edit?usp=sharing

Use Of PagedDataSource Class


Hello Friends Today I wil share with you new Experience which i did in my company that’s Use of Paged Data Source Class.
It’s Really a cool class and give us smart of to paging.
With Just A Smart Coding.

for This You will have to no need to take tension of Cursors ,Difficult logic’s
Simply Make a new Web Site
and
Do Following Steps of Coding as Given below.
Step 1:Make Presentation view of your page as below given
make a new web forma and place on page
1)DropDownlist(with soem entries)
2) DataList 1(with a link button in itemtemplate)
3) DataList 2(with some bind records using eval)
4) Two Link Button (previous and next)

<p>

<%@ 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”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<table>
<tr>
<td>
<asp:DropDownList ID=”ddlselect” runat=”server” AutoPostBack=”True”
onselectedindexchanged=”ddlselect_SelectedIndexChanged”>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
</asp:DropDownList>
<asp:LinkButton ID=”LinkButton1″ Text=”Previous” runat=”server”
onclick=”LinkButton1_Click”></asp:LinkButton>
<asp:DataList ID=”DataList2″ runat=”server” RepeatDirection=”Horizontal”
onitemcommand=”DataList2_ItemCommand”
onitemdatabound=”DataList2_ItemDataBound”
onselectedindexchanged=”DataList2_SelectedIndexChanged”>
<ItemTemplate>
<asp:LinkButton ID=”lnkbtnPaging” runat=”server” CommandArgument='<%# Eval(“PageIndex”) %>’
CommandName=”lnkbtnPaging” Text='<%# Eval(“PageText”) %>’></asp:LinkButton>
</ItemTemplate>
</asp:DataList><br />
<asp:LinkButton ID=”lnkNext”  Text=”Next” runat=”server”
onclick=”lnkNext_Click”></asp:LinkButton>
</td>
</tr>
</table>
<asp:DataList ID=”DataList1″ runat=”server”>
<ItemTemplate>
<asp:Label ID=”Label1″ runat=”server” Text='<%# Eval(“BookId”) %>’></asp:Label>
<asp:Label ID=”Label2″ runat=”server” Text='<%# Eval(“BookName”) %>’></asp:Label>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
</p>

Step 2: Now Do coding As Given Below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{

PagedDataSource pds = new PagedDataSource();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
string sql = “Select * from TbBook Order By BookId”;
SqlDataAdapter da = new SqlDataAdapter(sql, ConfigurationManager.ConnectionStrings["Or"].ConnectionString);
DataTable dt = new DataTable();
da.Fill(dt);
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = Convert.ToInt16(ddlselect.SelectedValue);
pds.CurrentPageIndex = CurrentPage;
lnkNext.Enabled = !pds.IsLastPage;
LinkButton1.Enabled = !pds.IsFirstPage;
DataList1.DataSource = pds;
DataList1.DataBind();
doPaging();
}
public int CurrentPage
{

get
{
if (this.ViewState["CurrentPage"] == null)
return 0;
else
return Convert.ToInt32(this.ViewState["CurrentPage"].ToString());
}
set
{
this.ViewState["CurrentPage"] = value;
}

}

private void doPaging()
{
DataTable dt = new DataTable();
dt.Columns.Add(“PageIndex”);
dt.Columns.Add(“PageText”);
for (int i = 0; i < pds.PageCount; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i;
dr[1] = i + 1;
dt.Rows.Add(dr);
}
DataList2.DataSource = dt;
DataList2.DataBind();
}

protected void DataList2_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals(“lnkbtnPaging”))
{
CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
BindGrid();
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
BindGrid();
}
protected void lnkNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
BindGrid();
}
protected void DataList2_SelectedIndexChanged(object sender, EventArgs e)
{

}
protected void ddlselect_SelectedIndexChanged(object sender, EventArgs e)
{
CurrentPage = 0;
BindGrid();
}
protected void DataList2_ItemDataBound(object sender, DataListItemEventArgs e)
{
LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl(“lnkbtnPaging”);
if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
{
lnkbtnPage.Enabled = false;
lnkbtnPage.Font.Bold = true;
}
}
}

Note :Never Forget to make table of tbbook with columns and fill dummy entries int that.
Then Press F5 and Run your web site see the handsome paging of your site.
enjoy and do programming.

NTILE FUNCTIon of MSSQLSERVER


NTILE(): This is one of the most coolest function provided by T-SQL. This is very useful while grouping a dataset into multiple sets i.e. in case if you want to distribute the result set into more than one tables or destination, this function is useful in accomplishing this task.

Let’s consider we have a table with 1 million records, and we want to divide this 1 million records across five tables, then we can achieve this by using NTILE () function.

The functionality of NTILE () function is same as other ranking functions i.e. ROW_NUMBER(), RANK() and DENSE_RANK(), except it takes one parameter named “integer_expression” i.e. NTILE(integer_expression). The integer_expression signifies the number of groups the NTILE function will create to distribute the data. integer_expression can be of type int, or bigint but must be positive integer. If you specify any other value like 2.5 or -3, it will throw the below error:

The function ‘ntile’ takes only a positive int or bigint expression as its input.

Let’s consider the example of Employee table, where we have 7 records, and our purpose is to distribute these records into two separate tables, one containing highest salaries and the other with lower salaries. Then the query goes like this:

For the table with Highest Salaries:

[ Copy to Clipboard ] | [ View Source ]
SELECT * FROM (
SELECT NTILE(2) OVER( ORDER BY salary DESC) AS GroupID,* FROM dbo.employee
) InnQ
WHERE InnQ.GroupID = 1
OUTPUT:


For the table with Lowest Salaries:

SELECT * FROM (
SELECT NTILE(2) OVER( ORDER BY salary DESC) AS GroupID,* FROM dbo.employee
) InnQ
WHERE InnQ.GroupID = 2


You might have noticed here that in the first set we have four records while in the second one we have three records. This is because; we have odd number of records in the employee table from where these sets are derived. When the integer_expression parameter is divisible with the total number of records in the source table, then we can get even number of records in all the sets derived from it or else it will start filling the remaining records starting from first set.

Let’s dissect the query a little:

SELECT NTILE(2) OVER( ORDER BY salary DESC) AS GroupID,* FROM dbo.employee;

GroupID column has two distinct numbers on the basis of which the records are divided into two separate sets as shown below.


As the total number of records in the employee table is not divisible by the integer_expression parameter in NTILE (), we have two groups with different sizes differ by one member. The group with higher number of members comes before the group with small number of members.

Using in NTILE():

clause in NTILE () function increases it functionality a little more. Here, we will see how partition by affects NTILE () in the above example. Let’s consider the below query to group records by department wise.

SELECT NTILE(2) OVER(PARTITION BY DeptNo ORDER BY salary DESC) AS GroupID,* FROM dbo.employee;
OUTPUT:

Let’s dissect the above query and see the process behind it.

The OVER clause in the query will partition the employee table as per DeptNo i.e. into three sub-sets. Then the NTILE(2) will divide each partition into groups of two as show in the below figure.

File Upload Control With Regular Expression Validation Control In asp.net 4.0 With Ajax


Aryan Verma

http://orientprogrammer.wordpress.com
Step 1: Make A New Web Site Using IDE 4.0 (Visual Studio 2010)
and after clicking on new web site you will get interface look as below given.


Step 2: Now place given control in code or can write to these.

.style1
{
color: #FF9900;
}

File Upload Control With Regular Expression Validator And Validations On Image Uploading
Upload Gravatar

Now Run and Enjoy In This .net World

Capital To First letter With Jquery


function toUpper(obj) {
    var mystring = obj.value;

    var sp = mystring.split(‘ ‘);
    var wl = 0;
    var f, r;
    var word = new Array();
    for (i = 0 ; i < sp.length ; i++) {
        f = sp[i].substring(0, 1).toUpperCase();
        r = sp[i].substring(1).toLowerCase();
        word[i] = f + r;
    }
    newstring = word.join(‘ ‘);
    obj.value = newstring;
    return true;
}

Generic Session Helper


 public static class AllSession
    {

        public static string Get(string key)
        {
            object value = HttpContext.Current.Request.QueryString[key];
            return (value == null) ? null : value.ToString();
        }

        public static string Post(string key)
        {
            object value = HttpContext.Current.Request.Form[key];
            return (value == null) ? null : value.ToString();
        }

        public static string Session(string key)
        {
            object value = HttpContext.Current.Session[key];
            return (value == null) ? null : value.ToString().Trim();
        }

        public static void ClearSession(string key)
        {
            HttpContext.Current.Session[key] = null;
        }

        public static void StoreInSession(string key, object value)
        {
            HttpContext.Current.Session[key] = value;
        }

        public static long TownID
        {
            get
            {

                return GetFromSession<long>(“TownID”);
            }
            set
            {
                SetInSession<long>(“TownID”, value);
            }
        }

        public static string TownName
        {
            get
            {

                return GetFromSession<string>(“TownName”);
            }
            set
            {
                SetInSession<string>(“TownName”, value);
            }
        }
        public static string UnitTime
        {
            get
            {

                return GetFromSession<string>(“UnitTime”);
            }
            set
            {
                SetInSession<string>(“UnitTime”, value);
            }
        }
        public static long UserId
        {
            get
            {

                return GetFromSession<long>(“UserId”);
            }
            set
            {
                SetInSession<long>(“UserId”, value);
            }
        }

        public static void Abandon()
        {
            if (HttpContext.Current != null && HttpContext.Current.Session != null)
                HttpContext.Current.Session.Abandon();
        }

        private static T GetFromSession<T>(string key)
        {
            if (HttpContext.Current.Session == null)
            {
                return default(T);
            }
            object obj = HttpContext.Current.Session[key];
            if (obj == null)
            {
                return default(T);
            }
            return (T)obj;
        }

        private static void SetInSession<T>(string key, T value)
        {
            if (value == null)
            {
                HttpContext.Current.Session.Remove(key);
            }
            else
            {
                HttpContext.Current.Session[key] = value;
            }
        }

        private static T GetFromApplication<T>(string key)
        {
            return (T)HttpContext.Current.Application[key];
        }

        private static void SetInApplication<T>(string key, T value)
        {
            if (value == null)
            {
                HttpContext.Current.Application.Remove(key);
            }
            else
            {
                HttpContext.Current.Application[key] = value;
            }
        }
    }

Call Web Serivce Cross Domain


   var surl = ‘http://localhost:5989/WebService1.asmx/GetCSS?aid=realm&callback=?';    
        $.support.cors = true;            
        $.ajaxSetup({ cache: false });
      $.ajax({
            type: “GET”,
            contentType: “application/json; charset=utf-8″,
            url: surl,
            dataType:’jsonp’,
            async: false,                
            crossDomain: ‘true’,              
            success: function (data, textStatus , xhr) {
alert(data);
                    var newCSS = headTag + data;
                     document.getElementsByTagName(‘head’)[0].innerHTML = newCSS;        
            },error: function (error, textStatus , xhr) {
                 alert(‘Error:’ + error.responseText);                   
        }
    });

 

Web Method in Web Service

 [WebMethod(Description = "GetCSS for intellicac")]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void GetCSS(string aid, string callback)
        {
            if (string.IsNullOrEmpty(aid))
                aid = “occfinance”;
            StringBuilder _tempate = new StringBuilder();
            try
            {
                _tempate.Append(“<style>”);
                string content = System.IO.File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath(@”~\Intellicalc\css\intellicalc.css”));
                _tempate.Append(content);
                using (SqlConnection con = new SqlConnection(Convert.ToString(System.Configuration.ConfigurationManager.ConnectionStrings["ConString"])))
                {
                    con.Open();
                    using (SqlCommand com = new SqlCommand(“GetsettingDetails”, con))
                    {
                        com.CommandType = CommandType.StoredProcedure;

                        com.Parameters.AddWithValue(“@AffiliateId”, Regex.Replace(aid, “[^a-zA-Z]+”, “”));
                        using (SqlDataReader dr = com.ExecuteReader())
                        {
                            while (dr.Read())
                            {
                                Settingdetails obj = new Settingdetails();
                                obj.settingid = Convert.ToInt32(dr["settingid"] ?? “1”);
                                obj.name = Convert.ToString(dr["name"] ?? “barcolors”);
                                obj.settingvalue = Convert.ToString(dr["value"] ?? “#555555″);

                                _tempate = _tempate
                                  .Replace(“[" + obj.name.Trim() + "]“, obj.settingvalue);
                            }
                            dr.Close();
                        }
                        con.Close();
                        con.Dispose();
                    }
                }
            }
            catch
            {

            }

            _tempate.Append(“</style>”);
            StringBuilder sb = new StringBuilder();
            JavaScriptSerializer js = new JavaScriptSerializer();
            js.MaxJsonLength = Int32.MaxValue;
            sb.Append(callback + “(“);
            sb.Append(js.Serialize(_tempate.ToString()));
            sb.Append(“);”);
            Context.Response.Clear();
            Context.Response.ContentType = “application/json”;
            Context.Response.Write(sb.ToString());
            Context.Response.End();
        }

———

CSS File

.intellicalc *, .icprice_disabled *, .icprice *, .icstepbox * {
    font-family: Arial, Verdana, Tahoma;
    font-size: 12px;
    color: #000000;
    line-height:normal;
}
.intellicalc ul {
    margin:0px;
}
.icclosebutton { border: 0px; }
.property {
    background-color:white;
    border:1px solid gray;
    width:100%;
}
.icslider_point_ie6{position: absolute;width: 15px;height: 76px;background-image: url(‘http://www.beremote.com/img/blank.gif&#8217;);background-repeat: no-repeat;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=”http://www.beremote.com/img/pointer.png&#8221;,sizingMethod=”scale”)}
.icslider_point{position: absolute;width: 15px;padding-right:30px;padding-bottom:20px;height: 76px;background-image: url(‘http://www.beremote.com/img/pointer.png&#8217;);background-repeat: no-repeat;}
.property #title {
    font-weight:bold;
}
.repossessed {
font-size:10pt;
text-transform:uppercase;
}
.icbanner {
    cursor:pointer;
}
#icpopup .icstepbox {
    margin-left: auto;
    margin-right: auto;
}
#icpopup .icstep1close {
    display:inline!important;
}
#icpopup {
    position:absolute;
    left:0px;
    top:0px;
    width:100%;
    height:600px;
    background-image:url(‘http://www.beremote.com/img/icpopup.png&#8217;);
    display:none;
    text-align:center;
    padding-top:50px;
    z-index: 9999;
}
.iccopy {
    text-align:right;
}
.iccopy a {
    color:silver;
    text-decoration:none;
}
.iclookbelow {
    float: left;
    display: inline;
    font-weight: bold;
    color: [textcolor1] !important;
    padding-left: 4px;
}
#icdiv_side {
    clear: left;
    padding: 7px;
    padding-top: 12px;
    margin-top: 10px;
    border-top: 1px solid #e1e1e1;
}
#icdiv_side, #icdiv_side a {
    font-size: 12px;
}
#icdiv_step1 {
    width: [step1width]px !important;
    text-align:left;    
}
#icdiv_step2 {
    width:950px;
}
#icdiv_step3 {
    border:1px solid gray;
    padding:20px;
    width:[step3width]px !important;
    display:none;
    z-Index:2000;
    text-align:left;
    margin-left: auto;
    margin-right: auto;
}
.inpspan {
    background-color:white;
    border:1px solid gray;
    padding:2px;
}
.inpfield {
    border:0px;
    text-align:right;
    width:105px;
}
#icdiv_step3 .inpfield {
    border:0px;
    text-align:right;
    width:160px;
}
.icbartable {
    width:100%;
    border-top:1px solid silver;
    border-bottom:1px solid silver;
}
.icbartable td {
    border:0px solid red;
}
.icbar_label{
    width:100px;
    font-size:7pt;
    color:[textcolor2] !important;
    padding-top:2px;
}
.icbar {
    margin-left:0px;
    position:relative;
    width:auto;
    height:65px;
}    
    
#icbar_ir {
    height:65px;
    position: relative;
}
#icbar_pp {
    position:relative;
    height:20px;
}
#icbar_mp {
    position:relative;
    height:20px;
}    
#icdiv_ratesld {
    margin-top:-70px;
    margin-left:-7px;
    padding:0px;
    position:relative;
}
.icsel_rategroup {
    font-size:12pt;
    width:780px;
    
}
.icbar_num {
    position:absolute;
    text-align:center;
    width:50px;
    color:[textcolor2] !important;
    border:0px solid red;
}
.icbartext * {
    color:[textcolor2] !important;
}
.icbar_rate {
    position:absolute;
    border:1px solid gray;
    background-color:green;
    padding-right:5px;
    height:33px;
    top:15px;
    text-align:right;
    line-height: 33px!important;
    font-size: 11px;
    font-weight:bold;
}
.icsummary {
    width:100%;
}
.icsummary td {
    padding-left: 0px;
    vertical-align:top;
}
.icsvalues {
    margin:0px;
    padding:0px;
}
.icsvalues li {
    list-style:none;
    float:left;
    padding:5px;
}
.iclabel {    
    font-size:9px;
    color: [textcolor2] !important;
    text-align:left;
}
.icvalue {
    font-size:14px;
    font-weight:bold;
    color:[textcolor4] !important;
    width:90%;
    line-height: 32px!important;
    background-color: [boxcolors] !important;    
}
.iccontainer div {
    float:left;
    display:inline;
}
.icend {
    background-color:  [boxcolors] !important;
    width:5px;
    height:32px;
    filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=”http://www.beremote.com/img/infobox_right.png&#8221;,sizingMethod=”scale”);
}
.icstart {
    background-color:  [boxcolors] !important;
    width:5px;
    height:32px;
    filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=”http://www.beremote.com/img/infobox_left.png&#8221;,sizingMethod=”scale”);
}
.iccontainer {
        background-color:  [boxcolors] !important;
        height:32px;
    line-height: 32px!important;
    text-align:right;
    display:inline;
}
.icvalueactive {
    font-size:14px;
    font-weight:bold;
    color:yellow;
}

.icbutton {
    font-size:12pt;
    color:white;
    background-color:#2262c2;
}
.icinpspan {
    float: left;
    font-weight: bold;
    color: [textcolor1] !important;
    font-size: 14px;
    padding-top: 1px;
    padding-left: 8px;
}
.icstepbox {
    background-color:white;
    border:1px solid silver;
    overflow:hidden;
    width:auto;
    color:gray;
    padding:10px;
}
.icstepbox_padd {
    
}
.iclogo {
    border:0px;
    width:75px;
    float:left;
}
.iclogolarge {
    border: 0;
    width: 170px;
    float: left;
}
.ichead {
    padding-bottom:15px;
}
#icdiv_step3 .ichead {
    padding-bottom: 0px;    
}
.iccontent {
    overflow:hidden;
}
.iccontent table {
    width: 100%;
}
.icfoot {   
    padding:0px;
    text-align:right;
}
#icdiv_step3 .icfoot {
    padding: 10px;
    text-align: left;
    float: none;
}
#icdiv_step3 .icfoot input {
    margin-top: 16px;
}
.ictitle {
    color:[textcolor1] !important;
    font-weight:bold;
    font-size:12pt;
    display: inline;
    margin-top: 2px;
}
.ictitle2 {
    color:[textcolor2] !important;
    font-weight:bold;
    font-size:12pt;
    display: block;
    margin-top: 2px;
    margin-bottom:10px;
}
.ictitle3 {
    color:[textcolor2] !important;
}
.icrepaymentmethods {
    height: 30px;
}
.iclabel1 {
    float: left;
    padding:7px;
    color:[textcolor2] !important;
    margin-right: 10px;
    width: 50px;
}
.iclabel2 {
    float: left;
    color:[textcolor2] !important;
    margin-right: 0px;
    width: 122px;
    padding: 3px 0px;
}
.icvalue1 {
    float: left;
    height: 30px;
    width: 159px;
    background-image: url(‘http://www.beremote.com/img/inputback.gif&#8217;);
    background-repeat: no-repeat;
    background-position: top left;
    margin-right: 10px;
}
.icvalue1_input {
    text-align:right;
    width: 134px;
    float: left;
    margin-top: 6px;
}
.icvalue1_input input {
    font-weight: bold;
}
.icvalue1_help {
    width: 22px !important;
    float: right;
    background-color: [boxcolors] !important;
}
.icvalue1_help img {
    display:block;
}
.icprice_inactive {
    color:gray;
}
.icprice {
    height:20px;
    background-color:[boxcolors] !important;    
    width:180px;
    border:2px outset silver;
}
.icprice table {
    width:100%;
    
}
.icprice td {
    padding:2px;
}
.icenquirebutton {
        background-image:url(‘http://www.beremote.com/img/enquire_default.gif&#8217;);
    background-repeat: no-repeat;
    cursor:pointer;
    width:300px;
    height:67px;
    padding:10px;
    color:[textcolor2] !important;
    text-align:left;
}
.icenquirebutton span {
    color:[textcolor2];
}
.icenquirebutton div {
    width:175px;
    text-align:left;
    font-size:10pt;
}
.icenquirebutton div b {
    color:[boxcolors] !important;
    font-size:10pt;
}
.icprice_td1, .icprice_td3 {
   font-family: Arial, Verdana, Tahoma;
    font-weight: bold;
    color: white;
    font-size: 14px!important;
    width:12px;
    text-align:center;
}
.icprice_td2 {
   font-family: Arial, Verdana, Tahoma;
    background-color:#eeeeee;
    text-align:right;    
}
.icprice_td2 span {
   font-family: Arial, Verdana, Tahoma;
    font-weight:bold;
    color: [textcolor1] !important;
    font-size: 10px;    
}
.icprice_td4 {
    font-family: Arial, Verdana, Tahoma;
        background-image: url(‘http://www.beremote.com/img/apply_left.gif&#8217;);
    background-repeat:no-repeat;
    background-position:left;
    padding-left: 8px;
    padding-top: 4px;
    padding-bottom: 3px;
    padding-right: 10px;
    height:36px;
}
.icprice_td4 span {
   font-family: Arial, Verdana, Tahoma;
    color:[textcolor2] !important;
}
.icprice_td5 {
   font-family: Arial, Verdana, Tahoma;
    background-color: [boxcolors] !important;
    background-repeat:no-repeat;
    background-position:right;
    text-decoration:underline;
    width:100px;
    font-size:8pt;
    padding-left: 8px;
    color:white;
}
.icprice_disabled .icleft_td {
     background-image: url(‘http://www.beremote.com/img/apply_left.gif&#8217;);
    background-repeat:no-repeat;
    background-position:left;
    padding: 7px 8px 8px 8px;
    color: #bbbbbb;
}
.icprice_disabled .icright_td {
    background-color: [boxcolors] !important;
      background-image: url(‘http://www.beremote.com/img/apply_right_disabled.png&#8217;);
    background-repeat:no-repeat;
    background-position:right;
    text-decoration:underline;
    width:70px;
    font-size:10px;
    padding: 8px;
    color:white;
}
.icprice_button {
    background-color: [boxcolors] !important;  
    padding:2px;
    color:white;
    width:130px;
    font-weight:bold;    
    border:1px outset gray;
    cursor:pointer;     
    text-align:right;
}
.icprice_disabled #icbestprice {
    font-weight:bold;
    color: #d3d3d3;
    font-size: 11px;
}
.icprice .icfullprice {
    font-size: 11px; color: [textcolor3] !important;
}
.icprice_disabled .icfullprice {
    font-size: 11px; color: #bbbbbb;
}
.icstep2back {
    display: inline;
    margin-top: 2px;
}
.icstep2back a {
    color: [textcolor1] !important;
    font-weight:bold;
    font-size:12pt;
    text-decoration: none;
}
.icstep1close {
    display: none;
    margin-top: 2px;
}

#icshowmebutton, #iccancelbutton, #iccancelbutton1 {
    height: 30px;
    font-weight: bold;
    width: 125px;
    color: [textcolor1] !important;
}
#icupdatebutton {
    height: 35px;
    font-weight: bold;
    width: 125px;
    color: [textcolor1] !important;
}
#icsubmitbutton {
    height: 30px;
    font-weight: bold;
    width: 125px;
    color: [textcolor1] !important;
}

.icstep3label {
    color:[textcolor3] !important;
}
.icstep3value {
    height: 30px;
    padding-top: 5px;
    text-align: right;
      background-image: url(‘http://www.beremote.com/img/step3_input.gif&#8217;);
    background-repeat: no-repeat;
    background-position: left top;
}
.icstep3value input {
    border: 0px;
    width: 180px;
    margin-right: 7px;
}
.icstep3field {
    padding:10px;
    float: left;
    clear: left;
}
.icstep3field .licstep3abel {
    width:200px;
}
.icstep3field .icstep3value {
    width:200px;
}
#icvloan, #icvdeposit {
    text-align:right;
}
/* END */
.icprice_widget {
  background-image: url(‘http://www.beremote.com/img/icalcbutton-question.png&#8217;);
  background-repeat:no-repeat;
  cursor:pointer;
  padding-left:22px;
  padding-top:2px;
 
  font-size:8pt!important;
  text-decoration:none;
  height:20px;
  width:140px;
  color:black!important;
  overflow:hidden;
  text-align:left;
  font-weight:normal;
    font-family: Arial, Verdana, Tahoma;
}
.icprice_widget_inactive {
    font-family: Arial, Verdana, Tahoma;
  background-image: url(‘http://www.beremote.com/img/icalcbutton-question.png&#8217;);
  background-repeat:no-repeat;
  cursor:pointer;
  padding-left:22px;
  padding-top:2px;
  font-size:8pt!important;
  text-decoration:none;
  height:20px;
  width:120px;
  color:gray!important;
  overflow:hidden;
  text-align:left;
  font-weight:normal;
}
.icbannertext {
    position:absolute;
    color:[textcolor2] !important;
        top:55px;
    padding-top:5px;
    padding-left:5px;
}
.icbannertext b {
    color:[boxcolors] !important;
}
.ictext {
    color:[textcolor2] !important;
    padding-bottom:10px;
    padding-top:10px;
    overflow:hidden;        
}
.icbubble {
    background-color: [boxcolors] !important;
    color:white;
    padding:10px;
}
#icwhatisthis {
    z-index:2001;left:35px;top:35px;width:600px;height:500px;position:absolute;border:1px solid black;color:white;
    padding:20px 20px 20px 20px;
    background-color:#333333;
    display:none;
}
#icwhatisthis p, #icwhatisthis li  {
    font-size:12px;
    color:white;
}

#icwhatisthis ul {
    margin-left:20px;
}
.icalc_bubble { height: 50px; }
.icalc_bubble_bg { font-size: 10px; font-weight: bold; color: #3a3a3a; background-image: url(‘http://www.beremote.com/img/icalc_bubble_bg.gif&#8217;); background-repeat: repeat-x; }
.icstepbox table td { border: 0px; }
.icstepbox ul li {margin:0px; }
.icalc_bubble td { padding: 0px; text-align:center; vertical-align:middle; }
.icbar_label {vertical-align:middle; }

sqlhelper/dbhelper/disposehelper/SafeDataReader/


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Diagnostics;
using Repositories.ManageSQL;

namespace Repositories.ManageSQL
{
///

/// Strongly typed DBHelper for MS SQL Server
///

public partial class SqlHelper : DbHelper
{
public static string BuildTrustedConnectionString(string serverName, string databaseName)
{
var s = new SqlConnectionStringBuilder();
s.DataSource = serverName;
s.InitialCatalog = databaseName;
s.IntegratedSecurity = true;
return s.ToString();
}
public static string BuildConnectionString(string serverName, string databaseName, string userName, string password)
{
var s = new SqlConnectionStringBuilder();
s.DataSource = serverName;
s.InitialCatalog = databaseName;
s.UserID = userName;
s.Password = password;
return s.ToString();
}
public static string GetConnectionString(string connectionStringKey)
{
return System.Configuration.ConfigurationManager.ConnectionStrings[connectionStringKey].ConnectionString;
}

public int DefaultCommandTimeout { get; set; }

public SqlHelper(string connectionString)
: base(connectionString)
{
this.DefaultCommandTimeout = 30;
}

protected override SqlConnection CreateConnection(string connectionString)
{
return new SqlConnection(connectionString);
}

protected override SqlCommand CreateCommand(string cmdText, SqlConnection connection)
{
return new SqlCommand(cmdText, connection) { CommandTimeout = DefaultCommandTimeout };
}

protected override IDbDataAdapter CreateDataAdapter(SqlCommand cmd)
{
return new SqlDataAdapter(cmd);
}

public SafeDataReader ExecuteSafeReader(CommandType cmdType, string cmdText, Action paramAction)
{
var conn = this.SharedConnection ?? CreateConnection(this.ConnectionString);
var cmd = CreateCommand(cmdText, conn);
cmd.CommandType = cmdType;
if (paramAction != null) paramAction(cmd.Parameters);

if (this.SharedConnection != conn) conn.Open();

var dr = cmd.ExecuteReader();

var d = new DisposeHelper(() =>
{
dr.Dispose();
cmd.Dispose();
if (this.SharedConnection != conn)
{
conn.Dispose();
}
});
return new SafeDataReader(dr, d);
}
// Use a SqlDataReader to stream results
protected SqlDataReader ExecuteReader(CommandType cmdType, string cmdText, Action paramAction)
{
var conn = this.SharedConnection ?? CreateConnection(this.ConnectionString);
var cmd = CreateCommand(cmdText, conn);
cmd.CommandType = cmdType;
if (paramAction != null) paramAction(cmd.Parameters);

if (this.SharedConnection != conn) conn.Open();
return cmd.ExecuteReader(); // WARNING: Leaks SqlCommand and SqlConnection IDisposables
}

// Bulk copy implementations
public void BulkCopy(SqlDataReader dr, string destinationTable, int batchSize, ColumnMatchingMode mode)
{
var conn = this.SharedConnection ?? CreateConnection(this.ConnectionString);
try
{
using (var bc = new SqlBulkCopy(conn))
{
bc.DestinationTableName = destinationTable;
bc.BatchSize = batchSize;
bc.NotifyAfter = batchSize;

switch (mode)
{
case ColumnMatchingMode.Ordinal:
for (int i = 0; i < dr.FieldCount; i++)
{
bc.ColumnMappings.Add(i, i);
}
break;
case ColumnMatchingMode.CaseSensitiveName:
for (int i = 0; i
{
Trace.TraceInformation(“{0} rows copied…”, totalRows += batchSize);
};

if (this.SharedConnection != conn) conn.Open();
try
{
bc.WriteToServer(dr);
}
finally
{
if (this.SharedConnection != conn) conn.Close();
}
}
}
finally
{
if (this.SharedConnection != conn) conn.Dispose();
}
}
public void BulkCopy(DataTable dt, string destinationTable)
{
BulkCopy(dt, destinationTable, ColumnMatchingMode.Ordinal);
}
public void BulkCopy(DataTable dt, string destinationTable, ColumnMatchingMode mode)
{
var c = new List(dt.Columns.Count);
switch (mode)
{
case ColumnMatchingMode.Ordinal:
foreach (DataColumn dc in dt.Columns)
{
c.Add(new SqlBulkCopyColumnMapping(dc.Ordinal, dc.Ordinal));
}
break;
case ColumnMatchingMode.CaseSensitiveName:
foreach (DataColumn dc in dt.Columns)
{
c.Add(new SqlBulkCopyColumnMapping(dc.ColumnName, dc.ColumnName));
}
break;
default:
throw new ArgumentOutOfRangeException(“mode”);
}
BulkCopy(dt, destinationTable, c.ToArray());
}
public void BulkCopy(DataTable dt, string destinationTable, params string[] destinationColumnNames)
{
var columnMaps = destinationColumnNames.Select((s, i) => new SqlBulkCopyColumnMapping(i, s));
BulkCopy(dt, destinationTable, columnMaps.ToArray());
}
public void BulkCopy(DataTable dt, string destinationTable, params SqlBulkCopyColumnMapping[] columnMappings)
{
var conn = this.SharedConnection ?? CreateConnection(this.ConnectionString);
try
{
using (var bc = new SqlBulkCopy(conn))
{
bc.DestinationTableName = destinationTable;
foreach (var columnMapping in columnMappings)
{
if (columnMapping != null)
{
bc.ColumnMappings.Add(columnMapping);
}
}

int totalRows = dt.Rows.Count;
bc.NotifyAfter = totalRows / 10;
bc.SqlRowsCopied += (s, e) =>
{
Trace.TraceInformation(“{0}/{1} rows copied…”, e.RowsCopied, totalRows);
};

if (this.SharedConnection != conn) conn.Open();

try
{
bc.WriteToServer(dt);
}
catch (Exception ex)
{
var e = new SqlBulkCopyExceptionHelper(this.ConnectionString, bc, ex, dt);
Exception newEx;
if (e.TryHandle(out newEx))
{
throw newEx;
}
else
{
throw;
}
}
finally
{
if (this.SharedConnection != conn) conn.Close();
}
}
}
finally
{
if (this.SharedConnection != conn) conn.Dispose();
}
}
}
}
————-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Diagnostics;

namespace Repositories.ManageSQL
{
partial class SqlBulkCopyExceptionHelper
{
private SqlBulkCopy SqlBulkCopy { get; set; }
private Exception InnerException { get; set; }
private string ConnectionString { get; set; }
private DataTable SourceTable { get; set; }

public SqlBulkCopyExceptionHelper(string connectionString, SqlBulkCopy bc, Exception ex, DataTable sourceTable)
{
this.ConnectionString = connectionString;
this.SqlBulkCopy = bc;
this.InnerException = ex;
this.SourceTable = sourceTable;
}

public bool TryHandle(out Exception ex)
{
var handlers = new Func[] { HandleInvalidColumnLength, HandleConversionError };
foreach (var h in handlers)
{
ex = h();
if (ex != null) return true;
}
ex = null;
return false;
}

private Exception HandleConversionError()
{
DataTable schemaDt = GetSchema();

foreach (DataRow dr in this.SourceTable.Rows)
{
foreach (DataColumn dc in schemaDt.Columns)
{
object o = dr[GetSourceColumnIndex(dc.Ordinal)];
if (o == null || o == DBNull.Value) continue;

try
{
Convert.ChangeType(o, dc.DataType);
}
catch (FormatException)
{
return new InvalidOperationException(
string.Format(“Cannot convert {0} to {1}. Row {2}, Column {3}:{4}”, o, dc.DataType, dr.Table.Rows.IndexOf(dr), dc.Ordinal, dc.ColumnName),
this.InnerException
);
}
}
}
return null;
}

private Exception HandleInvalidColumnLength()
{
const string INVALID_COL_LENGTH = “Received an invalid column length from the bcp client for colid”;
const int ERROR_CODE = unchecked((int)0x80131904);
var sqlEx = this.InnerException as SqlException;
if (sqlEx == null || sqlEx.ErrorCode != ERROR_CODE || sqlEx.Errors.Count < 1)
{
// Not correct SQL Exception
return null;
}
string msg = sqlEx.Errors[0].Message;
int columnId;
if (msg.Length < INVALID_COL_LENGTH.Length || !int.TryParse(msg.Substring(INVALID_COL_LENGTH.Length).TrimEnd('.'), out columnId))
{
// Incorrect message
return null;
}

// get length of Sql table column
DataTable schemaDt = GetSchema();
var destCol = schemaDt.Columns[columnId - 1]; // columnId is 1-based
var sourceCol = this.SourceTable.Columns[GetSourceColumnIndex(destCol.Ordinal)];
var destColLength = destCol.MaxLength;
if (destColLength destColLength)
{
return new InvalidOperationException(
string.Format(“Row {0}, Column index {1} is {2} chars, but {3}.{4} max length is {5} chars”,
this.SourceTable.Rows.IndexOf(dr), sourceCol.Ordinal, s.Length,
this.SqlBulkCopy.DestinationTableName, schemaDt.Columns[destCol.Ordinal].ColumnName, destColLength
),
this.InnerException
);
}
}

return null;
}

private DataTable GetSchema()
{
DataTable schemaDt = new DataTable();
using (var conn = new SqlConnection(this.ConnectionString))
using (var cmd = new SqlCommand(“SELECT * FROM ” + this.SqlBulkCopy.DestinationTableName, conn))
using (var da = new SqlDataAdapter(cmd))
{
da.FillSchema(schemaDt, SchemaType.Source);
}
return schemaDt;
}

private int GetSourceColumnIndex(int destinationIndex)
{
SqlBulkCopyColumnMapping cm = this.SqlBulkCopy.ColumnMappings.Cast()
.FirstOrDefault(c => c.DestinationOrdinal == destinationIndex);
if (cm == null)
{
cm = this.SqlBulkCopy.ColumnMappings[destinationIndex];
}
return cm.SourceOrdinal < 0 ? this.SourceTable.Columns.IndexOf(cm.SourceColumn) : cm.SourceOrdinal;
}
}
}
—————
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Data;

namespace Repositories.ManageSQL
{
/// This is a DataReader that 'fixes' any null values before
/// they are returned to our business code.
///

public class SafeDataReader : IDataReader
{
private IDataReader _dataReader;
private DisposeHelper _disposer;
///

/// Get a reference to the underlying data reader
/// object that actually contains the data from
/// the data source.
///

protected IDataReader DataReader
{
get { return _dataReader; }
}

///

/// Initializes the SafeDataReader object to use data from
/// the provided DataReader object.
///

/// The source DataReader object containing the data.
public SafeDataReader(IDataReader dataReader, DisposeHelper disposer)
{
_dataReader = dataReader;
_disposer = disposer;
}

///

/// Gets a string value from the datareader.
///

///
/// Returns empty string for null.
///
/// Ordinal column position of the value.
public string GetString(string name)
{
return GetString(_dataReader.GetOrdinal(name));
}

///

/// Gets a string value from the datareader.
///

///
/// Returns empty string for null.
///
/// Name of the column containing the value.
public virtual string GetString(int i)
{
if (_dataReader.IsDBNull(i))
return string.Empty;
else
return _dataReader.GetString(i);
}

///

/// Gets a value of type from the datareader.
///

/// Ordinal column position of the value.
public object GetValue(string name)
{
return GetValue(_dataReader.GetOrdinal(name));
}

///

/// Gets a value of type from the datareader.
///

/// Name of the column containing the value.
public virtual object GetValue(int i)
{
if (_dataReader.IsDBNull(i))
return null;
else
return _dataReader.GetValue(i);
}

///

/// Gets an integer from the datareader.
///

///
/// Returns 0 for null.
///
/// Ordinal column position of the value.
public int GetInt32(string name)
{
return GetInt32(_dataReader.GetOrdinal(name));
}

///

/// Gets an integer from the datareader.
///

///
/// Returns 0 for null.
///
/// Name of the column containing the value.
public virtual int GetInt32(int i)
{
if (_dataReader.IsDBNull(i))
return -1;
else
return _dataReader.GetInt32(i);
}

///

/// Gets a double from the datareader.
///

///
/// Returns 0 for null.
///
/// Ordinal column position of the value.
public double GetDouble(string name)
{
return GetDouble(_dataReader.GetOrdinal(name));
}

///

/// Gets a double from the datareader.
///

///
/// Returns 0 for null.
///
/// Name of the column containing the value.
public virtual double GetDouble(int i)
{
if (_dataReader.IsDBNull(i))
return 0;
else
return _dataReader.GetDouble(i);
}

///

/// Gets a from the datareader.
///

///
/// A null is converted into min possible date
/// See Chapter 5 for more details on the SmartDate class.
///
/// Name of the column containing the value.
//public Csla.SmartDate GetSmartDate(string name)
//{
// return GetSmartDate(_dataReader.GetOrdinal(name), true);
//}

/////

///// Gets a from the datareader.
/////

/////
///// A null is converted into the min possible date
///// See Chapter 5 for more details on the SmartDate class.
/////
///// Ordinal column position of the value.
//public virtual Csla.SmartDate GetSmartDate(int i)
//{
// return GetSmartDate(i, true);
//}

/////

///// Gets a from the datareader.
/////

/////
///// A null is converted into either the min or max possible date
///// depending on the MinIsEmpty parameter. See Chapter 5 for more
///// details on the SmartDate class.
/////
///// Name of the column containing the value.
/////
///// A flag indicating whether the min or max
///// value of a data means an empty date.
//public Csla.SmartDate GetSmartDate(string name, bool minIsEmpty)
//{
// return GetSmartDate(_dataReader.GetOrdinal(name), minIsEmpty);
//}

//public virtual Csla.SmartDate GetSmartDate(
// int i, bool minIsEmpty)
//{
// if (_dataReader.IsDBNull(i))
// return new Csla.SmartDate(minIsEmpty);
// else
// return new Csla.SmartDate(
// _dataReader.GetDateTime(i), minIsEmpty);
//}

///

/// Gets a Guid value from the datareader.
///

///
/// Returns Guid.Empty for null.
///
/// Ordinal column position of the value.
public System.Guid GetGuid(string name)
{
return GetGuid(_dataReader.GetOrdinal(name));
}

///

/// Gets a Guid value from the datareader.
///

///
/// Returns Guid.Empty for null.
///
/// Name of the column containing the value.
public virtual System.Guid GetGuid(int i)
{
if (_dataReader.IsDBNull(i))
return Guid.Empty;
else
return _dataReader.GetGuid(i);
}

///

/// Reads the next row of data from the datareader.
///

public bool Read()
{
return _dataReader.Read();
}

///

/// Moves to the next result set in the datareader.
///

public bool NextResult()
{
return _dataReader.NextResult();
}

///

/// Closes the datareader.
///

public void Close()
{
_dataReader.Close();
}

///

/// Returns the depth property value from the datareader.
///

public int Depth
{
get
{
return _dataReader.Depth;
}
}

///

/// Returns the FieldCount property from the datareader.
///

public int FieldCount
{
get
{
return _dataReader.FieldCount;
}
}

///

/// Gets a boolean value from the datareader.
///

///
/// Returns for null.
///
/// Ordinal column position of the value.
public bool GetBoolean(string name)
{
return GetBoolean(_dataReader.GetOrdinal(name));
}

///

/// Gets a boolean value from the datareader.
///

///
/// Returns for null.
///
/// Name of the column containing the value.
public virtual bool GetBoolean(int i)
{
if (_dataReader.IsDBNull(i))
return false;
else
return _dataReader.GetBoolean(i);
}

///

/// Gets a byte value from the datareader.
///

///
/// Returns 0 for null.
///
/// Ordinal column position of the value.
public byte GetByte(string name)
{
return GetByte(_dataReader.GetOrdinal(name));
}

///

/// Gets a byte value from the datareader.
///

///
/// Returns 0 for null.
///
/// Name of the column containing the value.
public virtual byte GetByte(int i)
{
if (_dataReader.IsDBNull(i))
return 0;
else
return _dataReader.GetByte(i);
}

///

/// Invokes the GetBytes method of the underlying datareader.
///

///
/// Returns 0 for null.
///
/// Name of the column containing the value.
public Int64 GetBytes(string name, Int64 fieldOffset,
byte[] buffer, int bufferoffset, int length)
{
return GetBytes(_dataReader.GetOrdinal(name), fieldOffset, buffer, bufferoffset, length);
}

///

/// Invokes the GetBytes method of the underlying datareader.
///

///
/// Returns 0 for null.
///
/// Ordinal column position of the value.
public virtual Int64 GetBytes(int i, Int64 fieldOffset,
byte[] buffer, int bufferoffset, int length)
{
if (_dataReader.IsDBNull(i))
return 0;
else
return _dataReader.GetBytes(i, fieldOffset, buffer, bufferoffset, length);
}

///

/// Gets a char value from the datareader.
///

///
/// Returns Char.MinValue for null.
///
/// Name of the column containing the value.
public char GetChar(string name)
{
return GetChar(_dataReader.GetOrdinal(name));
}

///

/// Gets a char value from the datareader.
///

///
/// Returns Char.MinValue for null.
///
/// Ordinal column position of the value.
public virtual char GetChar(int i)
{
if (_dataReader.IsDBNull(i))
return char.MinValue;
else
{
char[] myChar = new char[1];
_dataReader.GetChars(i, 0, myChar, 0, 1);
return myChar[0];
}
}

///

/// Invokes the GetChars method of the underlying datareader.
///

///
/// Returns 0 for null.
///
/// Name of the column containing the value.
public Int64 GetChars(string name, Int64 fieldoffset,
char[] buffer, int bufferoffset, int length)
{
return GetChars(_dataReader.GetOrdinal(name), fieldoffset, buffer, bufferoffset, length);
}

///

/// Invokes the GetChars method of the underlying datareader.
///

///
/// Returns 0 for null.
///
/// Ordinal column position of the value.
public virtual Int64 GetChars(int i, Int64 fieldoffset,
char[] buffer, int bufferoffset, int length)
{
if (_dataReader.IsDBNull(i))
return 0;
else
return _dataReader.GetChars(i, fieldoffset, buffer, bufferoffset, length);
}

///

/// Invokes the GetData method of the underlying datareader.
///

/// Name of the column containing the value.
public IDataReader GetData(string name)
{
return GetData(_dataReader.GetOrdinal(name));
}

///

/// Invokes the GetData method of the underlying datareader.
///

/// Ordinal column position of the value.
public virtual IDataReader GetData(int i)
{
return _dataReader.GetData(i);
}

///

/// Invokes the GetDataTypeName method of the underlying datareader.
///

/// Name of the column containing the value.
public string GetDataTypeName(string name)
{
return GetDataTypeName(_dataReader.GetOrdinal(name));
}

///

/// Invokes the GetDataTypeName method of the underlying datareader.
///

/// Ordinal column position of the value.
public virtual string GetDataTypeName(int i)
{
return _dataReader.GetDataTypeName(i);
}

///

/// Gets a date value from the datareader.
///

///
/// Returns DateTime.MinValue for null.
///
/// Name of the column containing the value.
public virtual DateTime GetDateTime(string name)
{
return GetDateTime(_dataReader.GetOrdinal(name));
}

///

/// Gets a date value from the datareader.
///

///
/// Returns DateTime.MinValue for null.
///
/// Ordinal column position of the value.
public virtual DateTime GetDateTime(int i)
{
if (_dataReader.IsDBNull(i))
return DateTime.MinValue;
else
return _dataReader.GetDateTime(i);
}

///

/// Gets a decimal value from the datareader.
///

///
/// Returns 0 for null.
///
/// Name of the column containing the value.
public decimal GetDecimal(string name)
{
return GetDecimal(_dataReader.GetOrdinal(name));
}

///

/// Gets a decimal value from the datareader.
///

///
/// Returns 0 for null.
///
/// Ordinal column position of the value.
public virtual decimal GetDecimal(int i)
{
if (_dataReader.IsDBNull(i))
return 0;
else
return _dataReader.GetDecimal(i);
}

///

/// Invokes the GetFieldType method of the underlying datareader.
///

/// Name of the column containing the value.
public Type GetFieldType(string name)
{
return GetFieldType(_dataReader.GetOrdinal(name));
}

///

/// Invokes the GetFieldType method of the underlying datareader.
///

/// Ordinal column position of the value.
public virtual Type GetFieldType(int i)
{
return _dataReader.GetFieldType(i);
}

///

/// Gets a Single value from the datareader.
///

///
/// Returns 0 for null.
///
/// Name of the column containing the value.
public float GetFloat(string name)
{
return GetFloat(_dataReader.GetOrdinal(name));
}

///

/// Gets a Single value from the datareader.
///

///
/// Returns 0 for null.
///
/// Ordinal column position of the value.
public virtual float GetFloat(int i)
{
if (_dataReader.IsDBNull(i))
return 0;
else
return _dataReader.GetFloat(i);
}

///

/// Gets a Short value from the datareader.
///

///
/// Returns 0 for null.
///
/// Name of the column containing the value.
public short GetInt16(string name)
{
return GetInt16(_dataReader.GetOrdinal(name));
}

///

/// Gets a Short value from the datareader.
///

///
/// Returns 0 for null.
///
/// Ordinal column position of the value.
public virtual short GetInt16(int i)
{
if (_dataReader.IsDBNull(i))
return 0;
else
return _dataReader.GetInt16(i);
}

///

/// Gets a Long value from the datareader.
///

///
/// Returns 0 for null.
///
/// Name of the column containing the value.
public Int64 GetInt64(string name)
{
return GetInt64(_dataReader.GetOrdinal(name));
}

///

/// Gets a Long value from the datareader.
///

///
/// Returns 0 for null.
///
/// Ordinal column position of the value.
public virtual Int64 GetInt64(int i)
{
if (_dataReader.IsDBNull(i))
return 0;
else
return _dataReader.GetInt64(i);
}

///

/// Invokes the GetName method of the underlying datareader.
///

/// Ordinal column position of the value.
public virtual string GetName(int i)
{
return _dataReader.GetName(i);
}

///

/// Gets an ordinal value from the datareader.
///

/// Name of the column containing the value.
public int GetOrdinal(string name)
{
return _dataReader.GetOrdinal(name);
}

///

/// Invokes the GetSchemaTable method of the underlying datareader.
///

public DataTable GetSchemaTable()
{
return _dataReader.GetSchemaTable();
}

///

/// Invokes the GetValues method of the underlying datareader.
///

public int GetValues(object[] values)
{
return _dataReader.GetValues(values);
}

///

/// Returns the IsClosed property value from the datareader.
///

public bool IsClosed
{
get
{
return _dataReader.IsClosed;
}
}

///

/// Invokes the IsDBNull method of the underlying datareader.
///

/// Name of the column containing the value.
public virtual bool IsDBNull(int i)
{
return _dataReader.IsDBNull(i);
}

///

/// Returns a value from the datareader.
///

/// Name of the column containing the value.
public object this[string name]
{
get
{
object val = _dataReader[name];
if (DBNull.Value.Equals(val))
return null;
else
return val;
}
}

///

/// Returns a value from the datareader.
///

/// Ordinal column position of the value.
public virtual object this[int i]
{
get
{
if (_dataReader.IsDBNull(i))
return null;
else
return _dataReader[i];
}
}
///

/// Returns the RecordsAffected property value from the underlying datareader.
///

public int RecordsAffected
{
get
{
return _dataReader.RecordsAffected;
}
}

#region IDisposable Support

private bool _disposedValue; // To detect redundant calls

// IDisposable
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
// free unmanaged resources when explicitly called
_dataReader.Dispose();
}

// free shared unmanaged resources
if (_disposer != null)
{
_disposer.Dispose();
}
}
_disposedValue = true;
}

// This code added by Visual Basic to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
GC.SuppressFinalize(this);
}

#endregion

}
}
————–
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Repositories.ManageSQL
{
///

/// Class to call an Action when disposing.
/// Useful for returning objects for use in using() clauses
///

public class DisposeHelper : IDisposable
{
private Action OnDispose { get; set; }

public DisposeHelper(Action onDispose)
{
this.OnDispose = onDispose;
}

public void Dispose()
{
this.OnDispose();
}
}
}
—————

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;

namespace Repositories.ManageSQL
{
///

/// Base class for DbHelpers, with strongly typed Connection, Command, and ParameterCollection
/// clases.
/// Strong typing allows us to take advantage of convenience methods like SqlParameterCollection.AddWithValue
///

///
///
///
public abstract class DbHelper
where TConnection : class, IDbConnection
where TCommand : class, IDbCommand
where TParameterCollection : class, IDataParameterCollection
{
public string ConnectionString { get; protected set; }
protected TConnection SharedConnection { get; set; }

protected abstract TCommand CreateCommand(string cmdText, TConnection connection);
protected abstract TConnection CreateConnection(string connectionString);
protected abstract IDbDataAdapter CreateDataAdapter(TCommand cmd);

public DbHelper(string connectionString)
{
this.ConnectionString = connectionString;
}

///

/// Open a shared connection for use in transactions
///

///
public virtual IDisposable BeginSharedConnection()
{
if (this.SharedConnection != null)
{
throw new InvalidOperationException(“Shared connection already in progress!”);
}

this.SharedConnection = CreateConnection(this.ConnectionString);
this.SharedConnection.Open();

return new DisposeHelper(() =>
{
this.SharedConnection.Dispose();
this.SharedConnection = null;
});
}

// Execute command with no parameters, and no return
public void ExecuteNonQuery(CommandType cmdType, string cmdText)
{
ExecuteNonQuery(cmdType, cmdText, null);
}
// Execute command with parameters, and no return
public void ExecuteNonQuery(CommandType cmdType, string cmdText, Action paramAction)
{
ExecuteNonQuery(cmdType, cmdText, paramAction, c => true);
}
// Execute command with parameters, and a return value (from an output SqlParameter)
public T ExecuteNonQuery(CommandType cmdType, string cmdText, Action paramAction, Func returnValue)
{
return ExecuteNonQuery(cmdType, cmdText, null, paramAction, returnValue);
}
// Execute command with parameters, and a return value (from an output SqlParameter).
// Also gives full access to the SqlCommand object to set other properties, eg., timeouts
public virtual T ExecuteNonQuery(CommandType cmdType, string cmdText, Action cmdAction, Action paramAction, Func returnValue)
{
if (returnValue == null) throw new ArgumentNullException(“returnValue”);

var conn = this.SharedConnection ?? CreateConnection(this.ConnectionString);
try
{
using (var cmd = CreateCommand(cmdText, conn))
{
cmd.CommandType = cmdType;
if (cmdAction != null) cmdAction(cmd);
if (paramAction != null) paramAction((TParameterCollection)cmd.Parameters);

if (this.SharedConnection != conn) conn.Open();
try
{
cmd.ExecuteNonQuery();
return returnValue(cmd);
}
finally
{
if (this.SharedConnection != conn) conn.Close();
}
}
}
finally
{
if (this.SharedConnection != conn) conn.Dispose();
}
}

// Execute a scalar command, with parameters (or null if no parameters).
// convertValue must handle converting from DBNull.Value
public virtual T ExecuteScalar(CommandType cmdType, string cmdText, Action paramAction, Func convertValue)
{
if (convertValue == null) throw new ArgumentNullException(“convertValue”);

var conn = this.SharedConnection ?? CreateConnection(this.ConnectionString);
try
{
using (var cmd = CreateCommand(cmdText, conn))
{
cmd.CommandType = cmdType;
if (paramAction != null) paramAction((TParameterCollection)cmd.Parameters);

if (this.SharedConnection != conn) conn.Open();
try
{
return convertValue(cmd.ExecuteScalar());
}
finally
{
if (this.SharedConnection != conn) conn.Close();
}
}
}
finally
{
if (this.SharedConnection != conn) conn.Dispose();
}
}

// Execute a command returning a single row in resultset.
// map Func gets access to IDataReader to map values from IDataReader to a strongly typed (or anonymous) object
// If no rows are returned from resultset, returns default(T)
public virtual T ExecuteSingle(CommandType cmdType, string cmdText, Action paramAction, Func map)
{
var conn = this.SharedConnection ?? CreateConnection(this.ConnectionString);
try
{
using (var cmd = CreateCommand(cmdText, conn))
{
cmd.CommandType = cmdType;
if (paramAction != null) paramAction((TParameterCollection)cmd.Parameters);

if (this.SharedConnection != conn) conn.Open();
try
{
using (var dr = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (!dr.Read())
{
return default(T);
}
return map(dr);
}
}
finally
{
if (this.SharedConnection != conn) conn.Close();
}
}
}
finally
{
if (this.SharedConnection != conn) conn.Dispose();
}
}

// Execute a command returning multiple rows in resultset.
// map Func gets access to IDataReader to map values from IDataReader to a strongly typed (or anonymous) object
// If no rows are returned from resultset, returns empty set
public virtual IEnumerable ExecuteSet(CommandType cmdType, string cmdText, Action paramAction, Func map)
{
var conn = this.SharedConnection ?? CreateConnection(this.ConnectionString);
try
{
using (var cmd = CreateCommand(cmdText, conn))
{
cmd.CommandType = cmdType;
if (paramAction != null) paramAction((TParameterCollection)cmd.Parameters);

if (this.SharedConnection != conn) conn.Open();
try
{
using ( var dr = cmd.ExecuteReader(CommandBehavior.SingleResult))
{
while (dr.Read())
{
yield return map(dr);
}
}
}
finally
{
if (this.SharedConnection != conn) conn.Close();
}
}
}
finally
{
if (this.SharedConnection != conn) conn.Dispose();
}
}

public DataTable FillDataTable(CommandType cmdType, string cmdText)
{
return FillDataTable(cmdType, cmdText, null);
}
public DataTable FillDataTable(CommandType cmdType, string cmdText, Action paramAction)
{
return FillDataSet(cmdType, cmdText, paramAction).Tables[0];
}
public DataSet FillDataSet(CommandType cmdType, string cmdText)
{
return FillDataSet(cmdType, cmdText, null);
}
public virtual DataSet FillDataSet(CommandType cmdType, string cmdText, Action paramAction)
{
var conn = this.SharedConnection ?? CreateConnection(this.ConnectionString);
try
{
using (var cmd = CreateCommand(cmdText, conn))
using (var da = (IDisposable)CreateDataAdapter(cmd))
{
cmd.CommandType = cmdType;
if (paramAction != null) paramAction((TParameterCollection)cmd.Parameters);

var ds = new DataSet();
if (this.SharedConnection != conn) conn.Open();
try
{
((IDbDataAdapter)da).Fill(ds);
return ds;
}
finally
{
if (this.SharedConnection != conn) conn.Close();
}
}
}
finally
{
if (this.SharedConnection != conn) conn.Dispose();
}
}
}
}
———–
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Diagnostics;

namespace Repositories.ManageSQL
{
public enum ColumnMatchingMode
{
Ordinal = 0,
CaseSensitiveName = 1
}
}
————–
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.Data.SqlClient;
using Repositories.ManageSQL;

namespace Repositories
{
public abstract class BaseRepository
{
protected SqlHelper sqlH { get; set; }

protected BaseRepository()
: this(SqlHelper.GetConnectionString(“Connection”))
{
}

protected BaseRepository(string connectionString)
: this(new SqlHelper(connectionString))
{
}

protected BaseRepository(SqlHelper sqlHelper)
{
this.sqlH = sqlHelper;
}

}
}

syn


pkverma
p@ssw0rd1111
pkverma@sampatti.com
SynapseIndia-
Uname : Emp0743
Password : p@ssword1111
Data Source = 103.246.249.54,35333
DataBase = KidTrackerRestore
User ID = NewKidTrackerLogin
Password = New!KidTracker32

 http://192.168.1.141/svn/MS/Robert
ProjectName : Kid Tracker
dbname : aspnet-OnlineRegistration-20140303145529

occfinance
conor@occfinance.com
floor62014

How To Merge Content of First Pdf to Second PDF using itext sharp and How to add image logo in pdf


using (Stream inputPdfStream = new FileStream(“input.pdf”, FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream inputImageStream = new FileStream(“some_image.jpg”, FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream outputPdfStream = new FileStream(“result.pdf”, FileMode.Create, FileAccess.Write, FileShare.None))
{
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
var pdfContentByte = stamper.GetOverContent(1);

Image image = Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(100, 100);
pdfContentByte.AddImage(image);
stamper.Close();
}

Allow just numbers jquery for inputbox


 $(‘.onlynumber’).keydown(function (e) {
                if (e.shiftKey || e.ctrlKey || e.altKey) {
                    e.preventDefault();
                } else {
                    var key = e.keyCode;
                    if (!((key == 8) || (key == 46) || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105))) {
                        e.preventDefault();
                    }
                }
            });