Total Pageviews

Friday 16 November 2012

Check and UnCheck all checkboxes in GridView using jQuery


<asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333"
    GridLines="None">
    <AlternatingRowStyle BackColor="White" />
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:CheckBox runat="server" ID="chkAll" />
            </HeaderTemplate>
            <ItemTemplate>
                <asp:CheckBox runat="server" ID="chkEmployee" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="ID">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblID" Text='<%#Eval("Id") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblName" Text='<%#Eval("Name") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Address">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblAddress" Text='<%#Eval("Address") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Designation">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblDesignation" Text='<%#Eval("Designation") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <EditRowStyle BackColor="#7C6F57" />
    <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#E3EAEB" />
    <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#F8FAFA" />
    <SortedAscendingHeaderStyle BackColor="#246B61" />
    <SortedDescendingCellStyle BackColor="#D4DFE1" />
    <SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView> 


Jquery Script
$("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").click(function () {
    if ($(this).is(':checked'))
        $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', true);
    else
        $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', false);
});


Detail Link
http://www.codeproject.com/Tips/422713/Check-all-checkboxes-in-GridView-using-jQuery

Monday 15 October 2012

Qubee & BanglaLion Free Unlimited Internet Trick (Hack)

Auto refresh code in html using meta tags


Place inside <head> to refresh page after 5 seconds:
<meta http-equiv="refresh" content="5">
Redirect to http://example.com/ after 5 seconds:
<meta http-equiv="refresh" content="5;URL='http://example.com/'">
Redirect to http://example.com/ immediately:
<meta http-equiv="refresh" content="0;URL='http://example.com/'">

Friday 14 September 2012

How to create Aggregate Function of SQL Server using .NET CLR

1. C# coding 


using System;
using System.Text;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.IO;

namespace hrn2k1.SqlServer
{
    [Serializable]
    [SqlUserDefinedAggregate(
        Format.UserDefined, //use clr serialization to serialize the intermediate result
        IsInvariantToNulls = true, //optimizer property
        IsInvariantToDuplicates = false, //optimizer property
        IsInvariantToOrder = false, //optimizer property
        MaxByteSize = 8000) //maximum size in bytes of persisted value
    ]
    public class Concat : IBinarySerialize
    {
        /// <summary>
        /// The variable that holds the intermediate result of the concatenation
        /// </summary>
        private StringBuilder intermediateResult;
        /// <summary>
        /// Initialize the internal data structures
        /// </summary>
        public void Init()
        {
            this.intermediateResult = new StringBuilder();
        }

        /// <summary>
        /// Accumulate the next value, not if the value is null
        /// </summary>
        /// <param name="value"></param>
        public void Accumulate(SqlString value, string Separator)
        {
            if (value.IsNull)
            {
                return;
            }
            if (this.intermediateResult.Length > 0)
                this.intermediateResult.Append(Separator).Append(value.Value);
            else
                this.intermediateResult.Append(value.Value);
        }

        /// <summary>
        /// Merge the partially computed aggregate with this aggregate.
        /// </summary>
        /// <param name="other"></param>
        public void Merge(Concat other)
        {
            this.intermediateResult.Append(other.intermediateResult);
        }

        /// <summary>
        /// Called at the end of aggregation, to return the results of the aggregation.
        /// </summary>
        /// <returns></returns>
        public SqlString Terminate()
        {
            string output = string.Empty;
            //delete the trailing comma, if any
            if (this.intermediateResult != null
                && this.intermediateResult.Length > 0)
            {
                output = this.intermediateResult.ToString();
            }

            return new SqlString(output);
        }

        public void Read(BinaryReader r)
        {
            intermediateResult = new StringBuilder(r.ReadString());
        }

        public void Write(BinaryWriter w)
        {
            w.Write(this.intermediateResult.ToString());
        }
    }
}

 2. Integrate .NET DLL into SQL Server

3. SQL Coding

CREATE AGGREGATE Concat (@input nvarchar(200),@Separator nvarchar(50)) RETURNS nvarchar(max)
EXTERNAL NAME [hrn2k1].[hrn2k1.SqlServer.Concat]

3. Use in Query

SELECT UserID,
       COUNT(InvoiceNumber) AS InvoiceCount,
       dbo.Concat(InvoiceNumber,',') AS InvoiceNumbers 
FROM Invoices
GROUP BY UserID

---------------------------------------------------


 public class SearchData
    {
        public SearchData() { }
        public int GetRowCount(string Where)
        {
            int Count = 0;
            try
            {
                using (SqlConnection con = new SqlConnection("Data Source=192.168.0.1;Initial Catalog=hrm;User ID=sa;Password=sa1234"))
                {
                    using (SqlCommand cmd = new SqlCommand("SP_GET_ROWCOUNT", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("@SelectedColumns", SqlDbType.NVarChar, 500).Value = "*";
                        cmd.Parameters.Add("@FromTables", SqlDbType.NVarChar, 500).Value = "Invoices";
                        cmd.Parameters.Add("@Where", SqlDbType.NVarChar, 500).Value = Where == "" ? "1=1" : Where;
                        cmd.Parameters.Add("@Return_Value", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        Count = Convert.ToInt32(cmd.Parameters["@Return_Value"].Value);

                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return Count;
        }
        public DataTable GetData(string Where, string OrderBy, int StartIndex, int PageSize)
        {
            DataTable dtData = new DataTable();
            try
            {
                int pageIndex = StartIndex / PageSize ;
                //using (SqlConnection con = new SqlConnection("Data Source=192.168.0.1;Initial Catalog=hrm;User ID=sa;Password=sa1234"))
                //{
                //    using (SqlCommand cmd = new SqlCommand("SP_GET_DATA", con))
                //    {
                //        cmd.Parameters.Add("@PageIndex", SqlDbType.Int).Value = pageIndex;
                //        cmd.Parameters.Add("@PageSize", SqlDbType.Int).Value = PageSize;
                //        cmd.Parameters.Add("@SelectedColumns", SqlDbType.NVarChar, 500).Value = "*";
                //        cmd.Parameters.Add("@FromTables", SqlDbType.NVarChar, 500).Value = "Invoices";
                //        cmd.Parameters.Add("@Where", SqlDbType.NVarChar, 500).Value = "1=1";
                //        cmd.Parameters.Add("@OrderBy", SqlDbType.NVarChar, 500).Value = " Id";
                //        con.Open();
                //        cmd.ExecuteNonQuery();
                //        con.Close();


                //    }
                //}

                using (SqlDataAdapter da = new SqlDataAdapter("SP_GET_DATA", "Data Source=192.168.0.1;Initial Catalog=hrm;User ID=sa;Password=sa1234"))
                {
                    da.SelectCommand.CommandType = CommandType.StoredProcedure;
                    da.SelectCommand.Parameters.Add("@PageIndex", SqlDbType.Int).Value = pageIndex;
                    da.SelectCommand.Parameters.Add("@PageSize", SqlDbType.Int).Value = PageSize;
                    da.SelectCommand.Parameters.Add("@SelectedColumns", SqlDbType.NVarChar, 500).Value = "*";
                    da.SelectCommand.Parameters.Add("@FromTables", SqlDbType.NVarChar, 500).Value = "Invoices";
                    da.SelectCommand.Parameters.Add("@Where", SqlDbType.NVarChar, 500).Value = Where == "" ? "1=1" : Where;
                    da.SelectCommand.Parameters.Add("@OrderBy", SqlDbType.NVarChar, 500).Value = OrderBy==""?"Id":OrderBy;
                    da.Fill(dtData);
                    da.Dispose();

                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            return dtData;
        }
    }

    public class Entity
    {
    }
    public interface IDataAccess<T>
    {

        T Map(DataRow datarow);
        T Map(SqlDataReader datareader);

        T Get(string Where);
        DataTable GetRows(string Where, string OrderBy);
        List<T> GetList(string Where, string OrderBy);
        int GetRowCount(string Where);
        DataTable GetDataRows(string Where, string OrderBy, int StartRowIndex, int PageSize);
        List<T> GetDataList(string Where, string OrderBy, int StartRowIndex, int PageSize);

        int Save(T obj);
        int Save(T obj, SqlConnection objCon, SqlTransaction objTrans);
        void Delete(string Where);
        void Delete(string Where, SqlConnection objCon, SqlTransaction objTrans);


    }


    public class DalEntity : IDataAccess<Entity>
    {

        public Entity Map(DataRow datarow)
        {
            Entity obj  = new Entity();
            try
            {
                //obj.

            }
            catch (Exception ex)
            {
                throw ex;
            }
            return obj;
        }

        public Entity Map(SqlDataReader datareader)
        {
            Entity obj = new Entity();
            try
            {
             
                //obj.

            }
            catch (Exception ex)
            {
                throw ex;
            }
            return obj;
        }

        public Entity Get(string Where)
        {
            throw new NotImplementedException();
        }

        public DataTable GetRows(string Where, string OrderBy)
        {
            throw new NotImplementedException();
        }

        public List<Entity> GetList(string Where, string OrderBy)
        {
            throw new NotImplementedException();
        }

        public int GetRowCount(string Where)
        {
            throw new NotImplementedException();
        }

        public DataTable GetDataRows(string Where, string OrderBy, int StartRowIndex, int PageSize)
        {
            throw new NotImplementedException();
        }

        public List<Entity> GetDataList(string Where, string OrderBy, int StartRowIndex, int PageSize)
        {
            throw new NotImplementedException();
        }

        public int Save(Entity obj)
        {
            throw new NotImplementedException();
        }

        public int Save(Entity obj, SqlConnection objCon, SqlTransaction objTrans)
        {
            throw new NotImplementedException();
        }
    }

    public class CodeHelper
    {
        public string PackedIntoTryCatch(string Code)
        {

            return string.Format(@"try
            {0}
            {2}
            {1}
            catch (Exception ex)
            {0}
                throw ex;
            {1}", "{", "}", Code);


        }
    }

Thursday 14 June 2012

Tips about Uploading 4 GB file on Web Server

Normally We can't upload files of  size > 4 MB.
If we have to upload file of size maximum 4 GB then the web.config file must be contained the following codes


<configuration>

  </system.web>
<httpRuntime maxRequestLength="4124672" requestValidationMode="2.0" executionTimeout="36000" />
  </system.web>

  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="4223664128"></requestLimits>
      </requestFiltering>
    </security>
  </system.webServer>

</configuration>


Notes:

maxRequestLength  in httpRuntime is KB (Kilo Bytes)


BUT

maxAllowedContentLength  in  requestLimits is B (Bytes)

Monday 11 June 2012

Developing an ASP.NET page with MasterPage and Localization

Introduction

While seeking on the internet for a solution to implement localization within an ASP.NET application using a MasterPage, I realized that a lot of people have got the same problem to solve. Unfortunately, I could not find a suitable solution thus, I intended to do my own implementation.

Background

The solution presented within this article uses the standard localization mechanism of the .NET framework.

Using the code

The published solution uses the Session object as storage for the currently selected culture. This will be initialized during the Session_Start method that is part of the global.asax file.
If a culture change is requested by the user, the MasterPage changes the stored culture in the Session object.
In a BasePage that inherits from Page, the method InitializeCulture is overridden and sets the appropriate culture information stored in the Session object to the current thread. Therefore, every Web Form needs to derive from this BasePage.
Let's start with the Global.asax file:
void Session_Start(object sender, EventArgs e) 
{
    //set english as default startup language
    Session["MyCulture"] = "en-GB";
}
Alternatively, the culture can be defined in the Web.config file with the key <globalization culture="en-GB" /> and then be processed and stored in the Session object from the Session_Start method.
The next step is the master page:
<%@ Master Language="C#" AutoEventWireup="true" 
           CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!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>[Smart-Soft - Masterpage with Localization Support]</title>
</head>

<body>
    <form id="theForm" runat="server">
    <div>
        <asp:contentplaceholder id="ContentPlaceHolder" runat="server">
        </asp:contentplaceholder>
    </div>
    <div style="margin-top:20px;">
        <asp:LinkButton ID="btnSetGerman" runat="server" Text="Deutsch" 
           CommandArgument="de-CH" OnClick="RequestLanguageChange_Click">
        </asp:LinkButton>  
        <asp:LinkButton ID="btnSetEnglish" runat="server" Text="English" 
           CommandArgument="en-GB" OnClick="RequestLanguageChange_Click">
        </asp:LinkButton>
    </div>
    </form>
</body>
</html>
The buttons to change the culture can be either placed in the MasterPage directly, or in any embeddedUserControl. In order to determine the requested language, the CommandArgument attribute of the LinkButtonis used.
..And the code-behind of the master page:
public partial class MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void RequestLanguageChange_Click(object sender, EventArgs e)
    {
        LinkButton senderLink = sender as LinkButton;

        //store requested language as new culture in the session
        Session["MyCulture"] = senderLink.CommandArgument;

        //reload last requested page with new culture
        Server.Transfer(Request.Path);
    }
}
The requested language, passed within the CommandArgument, is processed and stored in the Session object. Afterwards, the initially requested page will be reloaded on the server side.
Last but not least, the BasePage:
/// <summary>
/// Custom base page used for all web forms.
/// </summary>
public class BasePage : Page
{
    private const string m_DefaultCulture = "en-GB";
    
    protected override void InitializeCulture()
    {
        //retrieve culture information from session
        string culture = Convert.ToString(Session["MyCulture"]);

        //check whether a culture is stored in the session
        if (!string.IsNullOrEmpty(culture)) Culture = culture;
        else Culture = m_DefaultCulture;

        //set culture to current thread
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);

        //call base class
        base.InitializeCulture();
    }
}
As mentioned above, the InitializeCulture method is overridden, and gets the stored culture from the Sessionobject and assigns it to the currently running thread.