Thursday, January 8, 2015

Export to excel/csv file download dialog is not prompted if while using ajax Updatepanel

When you have button to export excel or csv file format, saving file will not working if you are using UpdatePanel. It will show following message when you debug.  

Message: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled. Details: Error parsing near '

Cause:

The action that causes this code to execute MUST be a postback event, and not an AJAX call.

This is due to the nature of the way AJAX requests are processed.

Solution:

1: Put button outside UpdatePanel (or)

2: Add following code in PageLoad of you aspx page

((ScriptManager)Master.FindControl("ToolkitScriptManagerID")).RegisterPostBackControl(btnExport)


Download csv example

protected void btnExport_Click(object sender, EventArgs e)

    {
        if (ListUser != null)
        {             //Build the CSV file data as a Comma separated string.
            string csv = string.Empty;

            csv = "\"Login ID\",\"Nav Customer No.\",\"Login Time\",\"Logout Time\"";


            //Add new line.

            csv += "\r\n";

            string logouttime;

            foreach (LoginHistory user in ListUser)
            {
                logouttime = user.LogOutTime == null ? "" : Convert.ToDateTime(user.LogOutTime).ToString("dd/MM/yyyy hh:mm:ss tt");
                csv += "\"" + user.UsrName + "\",\"" + user.CustomerCode + "\",\"" + user.Logintime.ToString("dd/MM/yyyy hh:mm:ss tt") + "\",\"" + logouttime + "\"";
                //Add new line.
                csv += "\r\n";
            }

            //Download the CSV file.

            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=LoginHistory_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".csv");
            Response.Charset = "";
            Response.ContentType = "application/text";
            Response.Output.Write(csv);
            Response.Flush();
            Response.End();
        }
    }


Monday, July 15, 2013

Disable button and show loading message while user clicked in asp.net c# USING UpdatePanel

After the ScriptManager put follow script on the page
 

<script type="text/javascript">
var pbControl = null;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
pbControl = args.get_postBackElement(); //the control causing the postback
pbControl.disabled = true;
}
function EndRequestHandler(sender, args) {
pbControl.disabled = false;
pbControl = null;
}
</script>

Monday, July 8, 2013

How to switch or add or move listbox item to another listbox items using javascript in asp.net C#

I believe, most of the developers will encounter the situation that in two list boxes, we like move listbox item to another listbox.
There is no issue if we are using C#. But, as we've known, there could be better if we can use javascript and it can reduce roundtrips (server-client) for every single time in clicking move button.
It is lightweight and user friendly. I have added one more good function that user can order the list as their own.
Below is the complete javascript.

<script type="text/javascript" language="javascript">
        function listbox_move(listID, direction) {
 

            var listbox = document.getElementById('<%= d.ClientID %>');
            var selIndex = listbox.selectedIndex;

            if (-1 == selIndex) {
                alert("Please select an option to move.");
                return;
            }

            var increment = -1;
            if (direction == 'up')
                increment = -1;
            else
                increment = 1;

            if ((selIndex + increment) < 0 ||
                (selIndex + increment) > (listbox.options.length - 1)) {
                return;
            }

            var selValue = listbox.options[selIndex].value;
            var selText = listbox.options[selIndex].text;
            listbox.options[selIndex].value = listbox.options[selIndex + increment].value
            listbox.options[selIndex].text = listbox.options[selIndex + increment].text

            listbox.options[selIndex + increment].value = selValue;
            listbox.options[selIndex + increment].text = selText;

            listbox.selectedIndex = selIndex + increment;
        }

        function listbox_moveacross(SwapDirection) {
            if (SwapDirection == 'add') {
                var src = document.getElementById('<%= s.ClientID %>');
                var dest = document.getElementById('<%= d.ClientID %>');
            }
            else {
                var src = document.getElementById('<%= d.ClientID %>');
                var dest = document.getElementById('<%= s.ClientID %>');
            }
            for (var count = 0; count < src.options.length; count++) {

                if (src.options[count].selected == true) {
                    var option = src.options[count];

                    var newOption = document.createElement("option");
                    newOption.value = option.value;
                    newOption.text = option.text;
                    newOption.selected = true;
                    try {
                        dest.add(newOption, null); //Standard
                        src.remove(count, null);
                    } catch (error) {
                        dest.add(newOption); // IE only
                        src.remove(count);
                    }
                    count--;

                }

            }

        }
        function listbox_selectall(listID, isSelect) {

            var listbox = document.getElementById(listID);
            for (var count = 0; count < listbox.options.length; count++) {

                listbox.options[count].selected = isSelect;

            }
        }
        function GetSubscribed() {
       
            var listbox = document.getElementById('<%= lbxCustomer.ClientID %>');
            var selIndex = listbox.selectedIndex;

            if (-1 == selIndex) {
                alert("Please select one of the Customers.");
                return false;
            }

            var listbox = document.getElementById('<%= d.ClientID %>');
            var allvalue = '';
            for (var count = 0; count < listbox.options.length; count++) {

                allvalue += ',' + listbox.options[count].value;

            }

            var hiddenControl = '<%= hfSub.ClientID %>';
            document.getElementById(hiddenControl).value = allvalue;
        }
</script>


 In aspx file




You will see that there is a subscribe button because after user move list items, server side code cannot detect the items moved. So I put hidden fields and populate it in OnClientClick.
Then you need to values from Hidden field.
That's it.
Enjoy programming.

Thursday, July 4, 2013

Disable button and show loading message while user clicked in asp.net c# NOT USING UpdatePanel

 HTML
<form id="form1" runat="server"> 
        <asp:Button ID="Button1" runat="server" Text="Button" />

</form>

Codebehind
protected void Page_Load(object sender, System.EventArgs e) 
{
        Button1.Attributes.Add("onclick", (ClientScript.GetPostBackEventReference(Button1, "") + ";this.value=\'Loading...\';this.disabled = true;"));

}

class Default_ : System.Web.UI.Page 
{

protected void Button1_Click(object sender, System.EventArgs e) 

{
        System.Threading.Thread.Sleep(555);

          //Some additional logic here
          ** Without Masterpage **
        ClientScript.RegisterClientScriptBlock( this.GetType(), "reset", 

          ("document.getElementById(\'" + (Button1.ClientID + "\').disabled=false;")), true);

          ** With Masterpage **
        ScriptManager.RegisterClientScriptBlock(
this,true.GetType(), "reset", 
         ("document.getElementById(\'" + (Button1.ClientID + "\').disabled=false;")), true);
}


}

NOTE : This will not work if you are using UpdatePanel. If you are using UpdatePanel, see here.
Ref

Wednesday, July 3, 2013

Rendering ContentPlaceHolder control inside MasterPage in Windows Server 2012 and IIS 8

Today, I would like to share you all something that I found while I was trying to deploy my website to Windows Server 2012 and IIS 8.

Generally, we've already known that inside master page, the control of contentplaceholder will be generated as ctl00_ContentPlaceHolder1_ButtonID

But in IIS8, it will be generated as ContentPlaceHolder1_ButtonID

NOTE : The safer way to get the client id is <%= ButtonID.ClientID %>

More about Client ID
http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx
http://msdn.microsoft.com/en-us/library/1d04y8ss.aspx
http://www.dotnetcurry.com/ShowArticle.aspx?ID=273

Monday, May 20, 2013

Limit maximum characters in textbox (textarea) and display remaining count using javascript in C# Asp.Net

function Count(text, long) {
          var maxlength = new Number(long); // Change number to your max length.
          if (text.value.length > maxlength) {
              text.value = text.value.substring(0, maxlength);
              //alert(" Only " + long + " chars");
          }
          //Display remaining count
          //ctl00_ContentPlaceHolder1_lblCount.innerHTML = maxlength - text.value.length;
          var lblMsg = $get('<%= lblCount.ClientID %>');
          lblMsg.innerHTML = maxlength - text.value.length;
      }

<asp:TextBox ID="TextBox1" TextMode="MultiLine" runat="server" onKeyUp="javascript:Count(this,10);" onChange="javascript:Count(this,10);" ></asp:TextBox>
    <br />
    <asp:Label ID="lblCount" runat="server" Text="10"></asp:Label>

Writing Data in log file or text file line by line in C# Asp.Net

private void WriteTextFile()
    {
        string FileLoc = "C:\\LOGFOLDER\\TextFile.txt";

//This will  create the new file if the file is not exist.
        if (!File.Exists(FileLoc))
        {
            using (StreamWriter sw = File.CreateText(FileLoc))
            {
                sw.WriteLine("My Content Data");
            }
        }

//This will append to the existing file if the file already exist.
        else
        {
            using (StreamWriter sw = new StreamWriter(FileLoc, true))
            {
                sw.WriteLine("My Content Data");
            }
        }
    }