Monday, January 23, 2012

Access Master Page Property and Master Page control in .aspx Form.


First Create a Master Page..

 <form id="form1" runat="server">
    <div>
    <asp:Label ID="lblname" Text="Hello" runat="server" BackColor="#FF6600"
            Font-Bold="True" ForeColor="#0066FF"></asp:Label>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
      
        </asp:ContentPlaceHolder>
    </div>
    </form>

-> Create Property in .master.cs Page
    private string _Name;
    public string Name
    {
        get { return _Name; }
        set { _Name = value; }

    }

Now Create a Default.aspx Page...
Add One Line
<%@ MasterType VirtualPath="~/Site1.Master" %>

Now Add a Code in Default.aspx.cs Page in Load Event of Page

 Master.Name = "This is a Demo Of Accessing Master Page Control";

and Now you can use this Property.....

Now accessing the Control of Master Page..

 Label lbl = (Label)Master.FindControl("lblName");
 lbl.Text = "This is a Demo Of Accessing Master Page Control";


->This all discussion is about how to use master page control or Property of it..

Saturday, January 21, 2012

Get File Extension From File Name that Saved into the Folder in Application.


{
            string s=Server.MapPath("~/Images/");
            DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/Images/"));
            FileInfo[] smFiles = di.GetFiles();

            foreach (FileInfo fi in smFiles)
            {
                if (Path.GetFileNameWithoutExtension(fi.Name) == "DefensiveDrivingLargeVehicles_img01")
                {
                   lblExtension.Text = Path.GetFileNameWithoutExtension(fi.Name) + fi.Extension;
                   break;
                  
                }
           }
}
Here There are some Files in Images Folder.Now If i Want to Get Extension of an Image DefensiveDrivingLargeVehicles_img01 .then above code is useful to get the FileExtension.here I am going to print the FileName+FileExtension in Lable...

ADD-EDIT-DELETE FUNCTIONALITY USING DELETGATE AND LINQ.


Create a database name Office with Four Column

1.OfficeId(Auto Increment-Int)
2.OfficeName(nvarhcar(50))
3.City(nvarchar(50))
4.Country(nvarchar(50))


-> Create a .aspx Page name Office.aspx.
-> Create a UserControl OfficeAddEdit.ascx Page.
-> Create a UserControl OfficeList.ascx Page.
-> Add Images Folder and add Edit.gif Image.

Office.aspx Page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Office.aspx.cs" Inherits="OfficeDelegate.Office" %>
<%@ Register Src="~/OfficeList.ascx" TagName="OfficeList" TagPrefix="uc1" %>
<%@ Register Src="~/OfficeAddEdit.ascx" TagName="OfficeAddEdit" TagPrefix="uc2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">

     <div>
     <table width="100%" border="0" cellspacing="0" cellpadding="0" class="RightTable">
        <tr>
            <td colspan="2" class="TableHeader">
                <asp:Label ID="lblAvatarappearanceMasterHeader" runat="server" Text=""></asp:Label>
            </td>
        </tr>
        <tr>
            <td>
          
                <uc1:OfficeList ID="OfficeList1" runat="server" />
                <uc2:OfficeAddEdit ID="OfficeAddEdit1" runat="server" />
            </td>
        </tr>
    </table>
    </div>

    </form>
</body>
</html>

Office.aspx.cs Page

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

namespace OfficeDelegate
{
    public delegate void OfficeEditHandler(object sender, OfficeDelegate.OfficeList.OfficeMasterInfo args);
    public delegate void OfficeAddHandler();
    public delegate void OfficeHandler();
    public partial class Office : System.Web.UI.Page
    {
        public int TabID
        {
            get
            {
                if (ViewState["TabId"] == null)
                    return 0;
                else
                    return Convert.ToInt32(ViewState["TabId"]);
            }

            set
            {
                ViewState["TabId"] = value;
            }
        }

    
        protected void Page_Load(object sender, EventArgs e)
        {
            OfficeList1.EditEvent += new OfficeEditHandler(List_eventhandler);
            OfficeList1.AddEvent += new OfficeAddHandler(ShowDetails_eventhandler);
            OfficeAddEdit1.eventhandler += new OfficeHandler(Detail_eventhandler);
            if (!IsPostBack)
            {
                TabID = 1;
                ShowHideControl();


            }

        }
        void ShowDetails_eventhandler()
        {

            OfficeAddEdit1.OfficeId = 0;
            TabID = 2;
            ShowHideControl();
        }
        void Detail_eventhandler()
        {
            TabID = 1;
            ShowHideControl();
        }
        void List_eventhandler(object sendar, OfficeDelegate.OfficeList.OfficeMasterInfo asgs)
        {
            OfficeAddEdit1.OfficeId = asgs.iOfficeId;
            TabID = 2;
            ShowHideControl();
        }
        private void ShowHideControl()
        {
            if (TabID == 1)
            {
                OfficeList1.Visible = true;
                OfficeList1.View();
                OfficeAddEdit1.Visible = false;
            }
            else if (TabID == 2)
            {
                OfficeAddEdit1.Visible = true;
                OfficeAddEdit1.View();
                OfficeList1.Visible = false;
            }
        }
    }
}



Now OfficeList.ascx Page

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="OfficeList.ascx.cs" Inherits="OfficeDelegate.OfficeList" %>
<asp:Label ID="lblList" runat="server" Text="List Page"></asp:Label>

  <asp:GridView ID="gvList" runat="server" AutoGenerateColumns="false"
    Width="100%" DataKeyNames="OfficeId" onrowcommand="gvList_RowCommand"
    onrowediting="gvList_RowEditing" >
  <Columns>
      <asp:TemplateField ItemStyle-Width="10px">
      <HeaderTemplate>
         Select
      </HeaderTemplate>
      <ItemTemplate>
          <asp:CheckBox ID="chkSelect" runat="server"/>
      </ItemTemplate>
      <ItemStyle Width="5%" HorizontalAlign="Center" />
      </asp:TemplateField>
      <asp:TemplateField ItemStyle-Width="400px" HeaderText="OfficeName">
      <ItemTemplate>
      <asp:Label ID="lblName" runat="server" Text='<%# Eval("OfficeName") %>'></asp:Label>
      </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField ItemStyle-Width="400px" HeaderText="City">
      <ItemTemplate>
      <asp:Label ID="lblCity" runat="server" Text='<%# Eval("City") %>'></asp:Label>
      </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField ItemStyle-Width="400px" HeaderText="Country">
      <ItemTemplate>
      <asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
      </ItemTemplate>
      </asp:TemplateField>
       <asp:TemplateField HeaderText="Action">
       <ItemTemplate>
       <asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/Images/Edit.gif" CommandName="Edit"
       ToolTip='Edit' CommandArgument='<%# Eval("OfficeId") %>' />
       </ItemTemplate>
       <ItemStyle Width="5%" HorizontalAlign="Center" />
       </asp:TemplateField>
      </Columns>
</asp:GridView>
<br />
<div align="right">
<asp:Button ID="btnAdd" runat="server" Text="Add" onclick="btnAdd_Click" />
<asp:Button ID="btnDelete" runat="server" Text="Delete" onclick="btnDelete_Click" />
</div>


OfficeList.ascx.cs Page

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

namespace OfficeDelegate
{
    public partial class OfficeList : System.Web.UI.UserControl
    {
        #region Public Properties
        public event OfficeEditHandler EditEvent;
        public event OfficeAddHandler AddEvent;
        #endregion
        public int TabID
        {
            get
            {
                if (ViewState["TabId"] == null)
                    return 0;
                else
                    return Convert.ToInt32(ViewState["TabId"]);
            }

            set
            {
                ViewState["TabId"] = value;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {

        }
           #region Methods
        private void Bind()
        {
            try
            {
                OfficeDataContext db = new OfficeDataContext();
                var office = from l in db.Offices select l;
                gvList.DataSource = office;
                gvList.DataBind();
            }
            catch (Exception ex)
            {
              

            }
        }
        #endregion
        public void View()
        {
            Bind();
        }
          
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            AddEvent();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            OfficeDataContext db = new OfficeDataContext();
            for (int i = 0; i < gvList.Rows.Count; i++)
            {
                CheckBox chk = (CheckBox)(gvList.Rows[i].FindControl("chkSelect"));
                if (chk.Checked == true)
                {
                    var delete = from l in db.Offices where l.OfficeId == Convert.ToInt32(gvList.DataKeys[i].Value) select l;
                    db.Offices.DeleteAllOnSubmit(delete);
                    db.SubmitChanges();
                }


            }
            Bind();

        }

        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "Edit")
                {
                    int iID = Convert.ToInt32(e.CommandArgument.ToString());
                    OfficeMasterInfo args = new OfficeMasterInfo();
                    args.iOfficeId = iID;
                    EditEvent(this, args);
                    TabID = 2;
                }
            }
            catch (Exception ex)
            {


            }
        }

        protected void gvList_RowEditing(object sender, GridViewEditEventArgs e)
        {

        }
        public class OfficeMasterInfo
        {
            public int iOfficeId;
        }
    }
}




OfficeAddEdit.ascx Page


<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="OfficeAddEdit.ascx.cs" Inherits="OfficeDelegate.OfficeAddEdit" %>
<table>
<tr>
<td>
<asp:Label ID="lblName" Text="OfficeName" runat="server"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="LblCity" Text="City" runat="server"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblCountry" Text="Country" runat="server"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
</td>
</tr>
</table>
<div align="right">
<asp:Button ID="btnAdd" Text="Add" runat="server" onclick="btnAdd_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel"
    onclick="btnCancel_Click"/>
</div>



OfficeAddEdit.ascx.cs Page

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

namespace OfficeDelegate
{
    public partial class OfficeAddEdit : System.Web.UI.UserControl
    {
        public int TabID
        {
            get
            {
                if (ViewState["TabId"] == null)
                    return 0;
                else
                    return Convert.ToInt32(ViewState["TabId"]);
            }

            set
            {
                ViewState["TabId"] = value;
            }
        }
        public int OfficeId
        {
            get
            {
                if (ViewState["Id"] == null)
                    return 0;
                else
                    return Convert.ToInt32(ViewState["Id"]);
            }

            set
            {
                ViewState["Id"] = value;
            }
        }
        public event OfficeHandler eventhandler;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
        
            if (Page.IsValid)
            {
                Insert();
            }
      
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
    
            TabID = 1;
            eventhandler();

      
        }



        public void View()
        {
            if (OfficeId != 0)
            {
                SetTocotrol();
            }
            else
            {
                txtName.Text = string.Empty;
                txtCity.Text = string.Empty;
                txtCountry.Text = string.Empty;
            }
        }

        private void SetTocotrol()
        {
            OfficeDataContext db = new OfficeDataContext();
            Office office = (from l in db.Offices where l.OfficeId == OfficeId select l).FirstOrDefault();
            txtName.Text = office.OfficeName;
            txtCity.Text = office.City;
            txtCountry.Text = office.Country;
        }

      

      

        public void Insert()
        {
            if (OfficeId == 0)
            {
               OfficeDataContext db = new OfficeDataContext();
                var office = new Office { OfficeName = txtName.Text, City = txtCity.Text, Country = txtCountry.Text };
                db.Offices.InsertOnSubmit(office);
                db.SubmitChanges();
                TabID = 1;
                eventhandler();
            }
            else
            {
                OfficeDataContext db = new OfficeDataContext();
                Office office = (from l in db.Offices where l.OfficeId == OfficeId select l).FirstOrDefault();
                office.OfficeName = txtName.Text;
                office.City = txtCity.Text;
                office.Country = txtCountry.Text;
                //db.Offices.InsertOnSubmit(office);
                db.SubmitChanges();
                TabID = 1;
                eventhandler();
            }
        }
    }
}

Friday, January 13, 2012

Fetch the hierarchical Data with comma Separated......For Ex.How many Sub Department are there in one Department...that values are come with comma separated

Declare @ParentId int
set @ParentId = 171
Declare @OptionList varchar(max);
WITH

  cteReports (DepartmentID, Department, ParentDepartmentID)

  AS

  (

    SELECT DepartmentID, Department, ParentDepartmentID

    FROM HealthWatch..Department

    WHERE ParentDepartmentID = @ParentId

    UNION ALL

    SELECT d.DepartmentID, d.Department,d.ParentDepartmentID

     

    FROM HealthWatch..Department d

      INNER JOIN cteReports r

        ON d.ParentDepartmentID = r.DepartmentID

  )

SELECT @OptionList = coalesce(@OptionList+',' ,cast(@ParentId as varchar(255))+',')+ cast(DepartmentID as varchar(255))

FROM cteReports

print @OptionList

Monday, January 9, 2012

Error While accessing the iis...HTTP Error 404.3 - Not Found


HTTP Error 404.3 - Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

The IIS manager did not have a handler for *.svc. So I added a script handler to handle *.svc with aspnet_isapi.dll and I got a new error.

The requested content appears to be script and will not be served by the static file handler.

 It looks like the script maps for the .svc extension are not registered.
 You will need to run ServiceModelReg.exe -i from the "%windir%\Microsoft.NET\Framework\v3.0\Windows Communication Foundation" directory to register the script maps.

Friday, January 6, 2012

Code for DownLoad any document(word,excel,notepad,pdf etc) using C#..


using System.Net;

WebClient req = new WebClient();
 HttpResponse response = HttpContext.Current.Response;
 response.Clear();
 response.ClearContent();
 response.ClearHeaders();
 response.Buffer = true;
 response.AddHeader("Content-Disposition", "attachment;filename=\"" + Server.MapPath(ConfigurationSettings.AppSettings["ResumePath"].ToString()) + hdnvalue.Value + "\"");
byte[] data = req.DownloadData(Server.MapPath(ConfigurationSettings.AppSettings["ResumePath"].ToString()) + hdnvalue.Value);
response.BinaryWrite(data);
response.End();

Where hdnvalue.Value contains the FileName and it comes from the database...

DownLoad PDF Code.....


In DownLoad Click Event write the Following Code.

 Response.ContentType = "Application/pdf";
 //Get the physical path to the file.
 string FilePath = MapPath("~/pdf/data.pdf");
 //Write the file directly to the HTTP content output stream.
 Response.WriteFile(FilePath);
 Response.End();

This code is useful for download the PDF........

Thursday, January 5, 2012

Bind Gridview using Datatable with Add,Edit and Delete Functionality.


DataTable.aspx Page code

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
 <div>
 <asp:Label ID="lblCategoryName" runat="server" Text="Category Name">    </asp:Label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 <asp:TextBox ID="txtCategoryName" runat="server" oncopy="return false" oncut="return false"
  onpaste="return false"></asp:TextBox>
 <br />
  <asp:Label ID="lblSubCategoryName" runat="server" Text="SubCategory Name"></asp:Label>&nbsp;
  <asp:TextBox ID="txtSubCategoryName" runat="server" oncopy="return false" oncut="return false"
    onpaste="return false"></asp:TextBox>
   <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
        <br />
 <asp:GridView runat="server" ID="gvCategory" AutoGenerateColumns="false" OnRowCommand="gvCategory_RowCommand" DataKeyNames="RowSerialNo">
 <AlternatingRowStyle CssClass="even" />
  <EmptyDataTemplate>
            <asp:Label ID="lblNoDataFound" runat="server" Text="Category Not Found."></asp:Label>
  </EmptyDataTemplate>
  <Columns>
                <asp:TemplateField>
                    <ItemStyle Width="35%" />
                    <HeaderTemplate>
                        <asp:Label ID="lblCategory" runat="server" Text="Category" Font-Bold="true">   </asp:Label>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblAnsCategory" runat="server" Text='<%# Eval("CategoryName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemStyle Width="35%" />
                    <HeaderTemplate>
                        <asp:Label ID="lblSubCategory" runat="server" Text="SubCategory" Font-Bold="true"></asp:Label>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblAnsSubCategory" runat="server" Text='<%# Eval("SubCategoryName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemStyle Width="30%" />
                    <HeaderTemplate>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkCategoryEdit" runat="server" Text="Edit" CommandName="SelectRec"
                            CommandArgument='<%#Eval("RowSerialNo")%>' CausesValidation="false"></asp:LinkButton>&nbsp;&nbsp;<asp:LinkButton
                                ID="lnkCategoryDelete" runat="server" Text="X" CommandArgument='<%#Eval("RowSerialNo")%>'
                                CommandName="DeleteRec" CausesValidation="false" OnClientClick='javascript:return confirm("Are you sure want to delete this entry?");'></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </div>
    </form>
</body>
</html>

DataTable.aspx.cs Page code

namespace Datatable
{
    public partial class Test : System.Web.UI.Page
    {
        Int16 RecSerialNo
        {
            get
            {
                if (ViewState["RecSerialNo"] == null)
                {
                    ViewState["RecSerialNo"] = 1;
                }
                return System.Convert.ToInt16(ViewState["RecSerialNo"].ToString());
            }
            set
            {
                ViewState["RecSerialNo"] = value;
            }
        }
        DataTable pageDatatable;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                CreateDataTable();
        }

        private void CreateDataTable()
        {
            pageDatatable = new DataTable();
            DataColumn[] keys = new DataColumn[1];
            DataColumn col1 = new DataColumn("CategoryName");
            DataColumn col2 = new DataColumn("SubCategoryName");
           
            DataColumn col5 = new DataColumn("RowSerialNo");
            pageDatatable.Columns.Add(col1);
            pageDatatable.Columns.Add(col2);
          
            pageDatatable.Columns.Add(col5);
            keys[0] = col5;
            pageDatatable.PrimaryKey = keys;
            ViewState["PagedataTable"] = pageDatatable;

        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (ViewState["PagedataTable"] != null)
            {
                DataTable table = (DataTable)ViewState["PagedataTable"];
                DataRow row = table.NewRow();
                row["CategoryName"] = txtCategoryName.Text;
                row["SubCategoryName"] = txtSubCategoryName.Text;
                
                row["RowSerialNo"] = RecSerialNo;
                if (ViewState["Id"] != null)
                {
                    table.Rows.Find(System.Convert.ToInt64(ViewState["Id"].ToString())).Delete();
                    ViewState["Id"] = null;
                }

                table.Rows.Add(row);
                table.AcceptChanges();

                ViewState["PagedataTable"] = table;
                gvCategory.DataSource = (DataTable)ViewState["PagedataTable"];
                gvCategory.DataBind();
                txtCategoryName.Text = string.Empty;
                txtSubCategoryName.Text = string.Empty;
                RecSerialNo++;



            }

        }

        protected void gvCategory_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            DataTable dt = (DataTable)ViewState["PagedataTable"];
            if (e.CommandName == "DeleteRec")
            {
                string Id = e.CommandArgument.ToString();
                dt.Rows.Find(System.Convert.ToInt64(Id)).Delete();
                dt.AcceptChanges();
                ViewState["PagedataTable"] = dt;
                gvCategory.DataSource = ViewState["PagedataTable"];
                gvCategory.DataBind();

            }
            if (e.CommandName == "SelectRec")
            {

                DataRow dr = dt.Rows.Find(System.Convert.ToInt64(e.CommandArgument.ToString()));
                txtCategoryName.Text = dr[0].ToString();
                txtSubCategoryName.Text = dr[1].ToString();
                ViewState["Id"] = e.CommandArgument.ToString();

            }
        }
    }
}

Sort Record at Sql Querry Level using Store Procedure.......


CREATE PROCEDURE [dbo].[mp_Users_SelectLockedUsers]

@SiteID int,
@SortExpression nvarchar(50)=Null,
@SortDirection nvarchar(50)=Null


SELECT * FROM mp_Users u WHERE
u.SiteID = 1
ORDER BY CASE WHEN @SortExpression='' AND @SortDirection='' Then
u.UserName END,
CASE WHEN @SortExpression='Name' AND @SortDirection='A' Then
u.Name END DESC,
CASE WHEN @SortExpression='Name' AND @SortDirection='D' Then
u.Name END ASC,
CASE WHEN @SortExpression='FirstName' AND @SortDirection='A' Then
u.FirstName END DESC,
CASE WHEN @SortExpression='FirstName' AND @SortDirection='D' Then
u.FirstName END ASC,
CASE WHEN @SortExpression='LastName' AND @SortDirection='A' Then
u.LastName END DESC,
CASE WHEN @SortExpression='LastName' AND @SortDirection='D' Then
u.LastName END ASC,
CASE WHEN @SortExpression='Email' AND @SortDirection='A' Then
u.Email END DESC,
CASE WHEN @SortExpression='Email' AND @SortDirection='D' Then
u.Email END ASC