Wednesday, October 31, 2012

Operation is not valid due to the current state of the object.


Error : Operation is not valid due to the current state of the object.

Stack Trace:



[InvalidOperationException: Operation is not valid due to the current state of the object.]
   System.Web.HttpValueCollection.ThrowIfMaxHttpCollectionKeysExceeded() +2692482
   System.Web.HttpValueCollection.FillFromEncodedBytes(Byte[] bytes, Encoding encoding) +61
   System.Web.HttpRequest.FillInFormCollection() +148

[HttpException (0x80004005): The URL-encoded form data is not valid.]
   System.Web.HttpRequest.FillInFormCollection() +206
   System.Web.HttpRequest.get_Form() +68
   System.Web.HttpRequest.get_HasForm() +8743911
   System.Web.UI.Page.GetCollectionBasedOnMethod(Boolean dontReturnNull) +97
   System.Web.UI.Page.DeterminePostBackMode() +63
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +133

This error occurs when form fields are very large in numbers.By default, the maximum value of MaxHttpCollection is 1000.

Solution:

To solve this error, increase MaxHttpCollection value. Try adding the following setting in your web.config's <appsettings> block. 

<appSettings>
        <add key="aspnet:MaxHttpCollectionKeys" value="3000" />

 </appSettings> 

you can change the value accordingly as per your need. 

Thursday, October 18, 2012

Count No of Table,View,Indexes,Stored Procedure

Sometime we need to count the no of table/view/indexes/stored procedure in Database.
 --Returns Total No of User Defined Table
select count(*) cntTables from sysobjects where type = 'U'

--Returns Total No of User Defined View
select count(*) cntView from sysobjects where type = 'V'

 --Returns Total No of Index.You may need to further filter,
 -- depending on which types of indexes you want.
select count(*) cntIndex from sysindexes

--Returns No of Stored Procredure
select Count(*) cntProc from sys.procedures


--Return numbers of non clustered indexes on any table in entire database.
SELECT COUNT(i.TYPE) NoOfIndex,
[schema_name] = s.name, table_name = o.name
FROM sys.indexes i
INNER JOIN sys.objects o ON i.[object_id] = o.[object_id]
INNER JOIN sys.schemas s ON o.[schema_id] = s.[schema_id]
WHERE o.TYPE IN ('U')
AND i.TYPE = 2
GROUP BY s.name, o.name
ORDER BY schema_name, table_name

Tuesday, October 9, 2012

Delete Duplicate Rows from Multiple Tables

There are various ways for removing duplicate rows from  table. In my scenario there are three table which from where I have to delete duplicate rows. All these tables have relation. These tables are-:

Purchase_Rcv -: Keeps information about each purchase receive.
Purchase_RcvDet -: Keeps information about purchased product  for each purchase receive
BarcodeDet -: Keeps Barcode Detail for each received product
There is one more table that is -:
POS_STOCK-: As its name exhibits, keeps stock information

So I have to also update stock in this table.

So, to implement this I wrote a select statement which fetches all the rows of table without duplicacy and the query is :
SELECT min(PoRcvDet_Id) as id   FROM [Purchase].[vw_PurchaseRcvDet] group by [Product_code]

Here Product_Code is the column on which I want to remove duplicacy. So, I used group by on Product_Code which returns distinct rows based on Product_Code.

I used min() to keep first entry.One can use max() also.

 Then I wrote the Delete Command which deletes all rows which are not in the selected rows.


Delete FROM [Purchase].[BarcodeDet]
      WHERE fkPoRcvDetId not in
      (SELECT min(PoRcvDet_Id) as id   FROM [Purchase].[vw_PurchaseRcvDet] group by [Product_code] )
           
Delete FROM Purchase.Purchase_RcvDet
WHERE PoRcvDet_Id not in
      (SELECT min(PoRcvDet_Id) as id  FROM [Purchase].[vw_PurchaseRcvDet] group by [Product_code] )
           
Delete FROM Purchase.Purchase_Rcv
WHERE PoRcv_Id not in
      (SELECT min(fkPoRcv_Id) as id  FROM [Purchase].[vw_PurchaseRcvDet] group by [Product_code] )



Update Stock--:


UPDATE [dbo].[POS_STOCK]
   SET [Stock] = b.[Qty]
  from [Purchase].[Purchase_RcvDet] as b
  left outer join  [dbo].[POS_STOCK] on b.[fkProductId]=[dbo].[POS_STOCK].[fkProductId]



In my scenario POS_STOCK has same no of rows as in Purchase_RcvDet. Thats why I have used  left outer join.


Friday, July 20, 2012

“Server.Transfer()” vs “Response.Redirect()”

Both “Server.Transfer()” and “Response.Redirect()” are used to transfer a user from one page to another page. Logically both methods are used for the same purpose but still there are some technical differences between both which we need to understand.

The basic difference between them is the way they communicate. Response.Redirect() first sends request for new page to the browser, then browser sends that request to the web-server, and after that your page changes. But Server.Transfer() directly communicate with the server to change the page hence it saves an extra  round-trip (to the browser) in the whole process.

Now the question arises which to use and when to use?

Response.Redirect() should be used when:
  •  we want to redirect the request to some plain HTML pages on our server or to some other web server
  •  we don't care about causing additional roundtrips to the server on each request
  • we do not need to preserve Query String and Form Variables from the original request
  • we want our users to be able to see the new redirected URL where he is redirected in his browser (and be able to bookmark it if it’s necessary)

Server.Transfer() should be used when:
  • we want to transfer current page request to another .aspx page on the same server
  • we want to preserve server resources and avoid the unnecessary roundtrips to the server
  • we want to preserve Query String and Form Variables (optionally)
  • we don't need to show the real URL where we redirected the request in the users Web Browser

Monday, July 16, 2012

Upload And Remove Files From Table Dynamically

This example shows how to add / remove rows in a grid
simoltaneously. To implement this I have used Repeater Control and DataTable where DataTable is used to store the values entered runtime also remove data if remove command will be passed and Repeater is used to show the data .Final output will be like this one -:

For this add a repeater control on your aspx and  fire properties "onitemcommand " &" onitemdatabound".
 <asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand"
        onitemdatabound="Repeater1_ItemDataBound">
<HeaderTemplate>
<table style="border: thin dotted #0000FF; width: 950px">
<tr>
<th>File Category</th>
<th>File Access</th>
<th>File</th>
<th>Description</th>
<th>&nbsp;</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:DropDownList ID="ddlFileCat" runat="server" ></asp:DropDownList>
</td>
<td>
<asp:RadioButtonList ID="rblFileAccsess" runat="server" RepeatDirection="Horizontal">
<asp:ListItem>Public</asp:ListItem>
<asp:ListItem>Private</asp:ListItem>
</asp:RadioButtonList>
</td> 
<td>
<asp:Label ID="lblFileNm"  runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"FileNm") %>'></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" />
</td>
<td>
<asp:TextBox ID="txtFileDesc" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"FileDesc") %>'></asp:TextBox>
</td>
<td>
<asp:Button ID="btnAddAnother" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Button") %>'  CommandName='<%#DataBinder.Eval(Container.DataItem,"Button") %>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>

Repeater's ItemDataBound property is used to bind dropdownlist form database and to show the value as selected runtime.
 protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {

        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DropDownList ddl = (DropDownList)e.Item.FindControl("ddlFileCat");
            RadioButtonList rbl = (RadioButtonList)e.Item.FindControl("rblFileAccsess");

            SqlDataAdapter adp = new SqlDataAdapter("SELECT [CategoryID],[CatName] FROM [dbo].[MST_FileCategory]", con);
            DataSet ds = new DataSet();
            adp.Fill(ds);

            ddl.DataSource = ds;
            ddl.DataTextField = "CatName";
            ddl.DataValueField = "CategoryID";
            ddl.DataBind();
            ddl.SelectedValue = dtTemp.Rows[i]["FileCat"].ToString();
            rbl.SelectedValue = dtTemp.Rows[i]["FileAccess"].ToString();
            i++;

        }
        //   ddl.SelectedValue = Eval("FileCat").ToString();
    }

To Add or Remove rows from Datatable we will use ItemCommand from where we will pass the Command ADD or REMOVE.

  protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        //int cnt = Repeater1.Items.Count; //get total row count in repeater
        if (e.CommandName == "Add")
        {
            //  cnt++;
            AddColumns();

            foreach (RepeaterItem item in Repeater1.Items)
            {
                //Getting the value of fields
                FileUpload fu = (FileUpload)item.FindControl("FileUpload1");
                Label fileName = (Label)item.FindControl("lblFileNm");
                Button btnAdd = (Button)item.FindControl("btnAddAnother");

                if (btnAdd == e.CommandSource)
                {
                    if (fu.HasFile)
                    {
                        string path = Server.MapPath("~/Docs/");
                        fileName.Text = fu.FileName;
                        fu.SaveAs(path + fileName.Text);
                    }
                }

                string fileCat = ((DropDownList)item.FindControl("ddlFileCat")).SelectedValue;
                string fileAccess = ((RadioButtonList)item.FindControl("rblFileAccsess")).SelectedValue;
                string fileNm = ((Label)item.FindControl("lblFileNm")).Text;
                string fileDesc = ((TextBox)item.FindControl("txtFileDesc")).Text;

                //now chnage button text to remove & save values in table
                dtTemp.Rows.Add(fileCat, fileAccess, fileNm, fileDesc, "Remove");
            }
            //Add dummy rows bcoz we neeed to increase
            dtTemp.Rows.Add("", "", "", "", "Add");
            BindWithRepeater();
        }
        else if (e.CommandName == "Remove")
        {
            // cnt--;
            AddColumns();
            foreach (RepeaterItem item in Repeater1.Items)
            {
                Button btnAdd = (Button)item.FindControl("btnAddAnother");
                if (btnAdd != e.CommandSource)
                {
                    string fileCat = ((DropDownList)item.FindControl("ddlFileCat")).SelectedValue;
                    string fileAccess = ((RadioButtonList)item.FindControl("rblFileAccsess")).SelectedValue;
                    string fileNm = ((Label)item.FindControl("lblFileNm")).Text;
                    string fileDesc = ((TextBox)item.FindControl("txtFileDesc")).Text;

                    if (btnAdd.Text == "Remove")
                    {
                        dtTemp.Rows.Add(fileCat, fileAccess, fileNm, fileDesc, "Remove");
                    }
                    else
                    {
                        dtTemp.Rows.Add(fileCat, fileAccess, fileNm, fileDesc, "Add");
                    }
                }

            }
            BindWithRepeater();
        }

    }

AddColumns() and BindWithRepeater() are user defined functions.Define this functions also and call them in pageload.

  public void AddColumns()
    {
        dtTemp.Columns.Add("FileCat");
        dtTemp.Columns.Add("FileAccess");
        dtTemp.Columns.Add("FileNm");
        dtTemp.Columns.Add("FileDesc");
        dtTemp.Columns.Add("Button");
    }
    public void BindWithRepeater()
    {
        //Bind this Dataset to repeater
        Repeater1.DataSource = dtTemp;
        Repeater1.DataBind();
    }

  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            AddColumns();
            dtTemp.Rows.Add("", "", "", "", "Add");
            BindWithRepeater();
        }
    }

Now here is the whole code -:

Friday, May 11, 2012

Cool Progress Bar in C#,Asp.net


 This example shows you how to display a interactive progress bar while work is in progress.For doing this you need a gif image file which gives a good look for progress.
Like this one :
Then You must have an update panel in web form.Now implement the code given below.You can change image and text as per your need.

<asp:UpdateProgress ID="UPdtProgress" runat="server"
                   AssociatedUpdatePanelID="upTakeAttendance">
        <ProgressTemplate>
                <img ID="imgProgress" runat="server" alt="Work is in Progress" 
                           src="~/PayRoll/images/progressbar.gif" height="17" width="100" /><br />
                 <span style="color: #FF0000;  font-size: small;">  Please Wait</span>
          </ProgressTemplate>
 </asp:UpdateProgress>

Output will look like this -:


Tuesday, May 8, 2012

Open doc,txt or pdf files in C#

This example shows you how to open any doc,txt or pdf file which is saved in any specified location.In this example I m using a GridView which contains a template field which holds FileName.

<asp:TemplateField HeaderText="Application Name" SortExpression="ApplicationName">
       <ItemTemplate>
                       <asp:LinkButton ID="lbOpenApplication" runat="server" Text='<%# Bind("ApplicationName") %>'  CommandArgument='<%# Bind("ApplicationName") %>' CommandName="ViewApplication"></asp:LinkButton>
       </ItemTemplate>
</asp:TemplateField>

In Gridview's RowCommand event we have to write code snippet given below.

protected void gvViewLeave_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "ViewApplication")
        {
            string filename = e.CommandArgument.ToString();
            string path = Server.MapPath("~/PayRoll/Applications/");
            System.Diagnostics.Process.Start(path + filename);
        }
    }