Monday 17 November 2014

General things for ASP.NET project

Comma Separated Data With Whitespace:

string[] inputData = Console.ReadLine().Split(',').Select(x=>x.Trim()).ToArray();


How to Add Connection String in C#:
In your project Add Reference "System.Configuration".

Create an App.Config file and add the following code:

<connectionStrings>

   <add name=<YourConnectionString> connectionString="Data Source=<ServerName>; DataBase=<DatabaseName>;Uid=sa;Pwd=Passw0rd;"/>

</connectionStrings>

Create a Database.cs file and add the following code:

using System.Configuration;

namespace DAL
{
    public class Database
    {
        public static string PortalString
        {
            get
            {
                return ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
            }
        }
    }
}

Make private constructor in BLL, underscore-prefixed private fields and CamelCase Properties


To get Active Notices:
N.StartDate < CAST(GETDATE() AS DATE) AND N.ExpirationDate > CAST(GETDATE() AS DATE)

Procedure for Searching a Person:
USE [Portal]
GO

CREATE PROCEDURE [dbo].[SearchPersons]
     (
           @personCode varchar(50),
           @dateOfJoining datetime,
           @firstName varchar(50),
           @lastName varchar(50),
           @departmentID int
     )
AS
BEGIN
     SET NOCOUNT ON
    
     SELECT PersonId, PersonCode, DateOfJoining, FirstName, LastName, DepartmentId
     FROM Persons
     WHERE
      (@personCode IS NULL OR PersonCode LIKE '%' + @personCode + '%')
     AND
     (@dateOfJoining IS NULL OR DateOfJoining = @dateOfJoining)
     AND
     (@firstName IS NULL OR FirstName LIKE '%' + @firstName + '%')
     AND
     (@lastName IS NULL OR LastName LIKE '%' + @lastName + '%')
     AND
     (@departmentID IS NULL OR DepartmentId = @departmentID)
    
     SELECT @@Identity
END
GO



How a GridView in ASP.NET looks like:
    <div>
        <asp:GridView ID="EmpGridView" runat="server" AllowPaging="True" AutoGenerateColumns="False"
            CellPadding="4" EnableModelValidation="True" ForeColor="#333333" GridLines="None"
            OnPageIndexChanging="EmpGridView_PageIndexChanging" PageSize="4" Width="100%">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <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" />
            <Columns>
                <asp:TemplateField HeaderText="Employee Code">
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("EmployeeCode") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# String.Format("{0} {1}", Eval("FirstName"), Eval("LastName")) %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Date of Joining">
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%#Eval("DateOfJoining", "{0:dd-MMM-yyyy}")%>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Department">
                    <ItemTemplate>
                        <asp:Label ID="Label4" runat="server" Text='<%# Bind("DepartmentName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# string.Format("~/Employee/AddEditEmployee.aspx?id={0}&op={1}",
HttpUtility.UrlEncode(Eval("EmployeeId").ToString()), "edit")%>' Text="Edit"></asp:HyperLink>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:HyperLink ID="HyperLink2" runat="server" onclick="javascript:return confirm('Are you sure you want to delete ?');"
                            NavigateUrl='<%# Eval("EmployeeId", "DeleteEmployee.aspx?id={0}") %>' Text="Delete"></asp:HyperLink>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>

Page-Indexing in Gridview:

namespace UI
{
    public partial class ManagePersons : System.Web.UI.Page
    {
        PersonList persons;
        protected void Page_Load(object sender, EventArgs e)
        {
            persons = PersonList.GetAllPersons();
            EmpGridView.PageIndex = 0;
            EmpGridView.DataSource = persons;
            EmpGridView.DataBind();
        }


        protected void AddPersonBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("AddEditPerson.aspx?op=add");
        }

        protected void EmpGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            EmpGridView.PageIndex = e.NewPageIndex;
            EmpGridView.DataSource = persons;
            EmpGridView.DataBind();
        }
    }
}


How to Use Query String for ADD/Edit Common Page in c#:
using System.Globalization;

namespace UI
{
    public partial class AddEditPerson : System.Web.UI.Page
    {
        private int    personId;
        private string operation;

        protected void Page_Load(object sender, EventArgs e)
        {
            operation = Request.QueryString["op"];
            if (operation != GlobalConstants.ADD)
            {
                int.TryParse(Request.QueryString["id"], out this.personId);
            }

            if (!Page.IsPostBack)
            {
                DepartmentList departments = DepartmentList.GetAllDepartments();
                ddDepartment.Items.Add(new ListItem("--Please Select--", "NA"));
               
                foreach (var department in departments)
                {
                    ddDepartment.Items.Add(new ListItem(department.DepartmentName, department.DepartmentId.ToString()));
                }
            }
        }

        protected void CancelBtn_Click(object sender, EventArgs e)
        {
                Response.Redirect("../Default.aspx");
        }

        protected void AddPersonBtn_Click(object sender, EventArgs e)
        {
            int departmentId;
            int.TryParse(ddDepartment.SelectedValue, out departmentId);

            DateTime inputBirthDateTime;
            DateTime.TryParseExact(DateOfBirthBox.Text, GlobalConstants.YMD, CultureInfo.InvariantCulture, DateTimeStyles.None, out inputBirthDateTime);

            BLL.Person person = new BLL.Person
            {
                PersonId      = this.personId,
                FirstName       = FirstNameBox.Text,
                DateOfBirth     = inputBirthDateTime,
                DepartmentId    = departmentId
            };

            person.Save();
        }
    }
}



No comments:

Post a Comment