Thursday, January 15, 2015

All about DateTime in ASP.Net and SQL

GridView BoundField Format
<asp:BoundField HeaderText="Post Date" DataField="PostDate" DataFormatString="{0:dd/MM/yyyy hh:mm:ss tt}" />
Result : 16/01/2015 01:59:46 PM


SQL Query for DateTime Range (Normally, Date has no issue)
Eg. You want to query Feb 18, 2014 to Feb 23, 2014

SELECT *
FROM [BinterWebSystem].[dbo].[tblLogHistory]
WHERE LoginTime BETWEEN '2014/02/18 00:00:00.000' AND '2014/02/23 23:59:59.999'
or (+1day to last date, if 2014/02/18, System will assume '2014/02/18 00:00:00.000')
SELECT *
FROM [BinterWebSystem].[dbo].[tblLogHistory]
WHERE LoginTime BETWEEN '2014/02/18' AND '2014/02/24'


Binding all of the Months to DropDownList
System.Globalization.DateTimeFormatInfo dtInfo = new System.Globalization.DateTimeFormatInfo();
  for (int i = 1; i < 13; i++)
  {
      ddlStartMonth.Items.Add(new ListItem(dtInfo.GetMonthName(i), i.ToString()));
  }

Monday, January 12, 2015

Create Loading page in between two pages

Assuming that after login success in Login.aspx, it redirects to Data.aspx which takes 1 minute for loading page. In such case, user will see that Login page will be frozen for that 1 minute loading time. So. the idea is that we need to have one page to interactive with user that data is loading.

>>> Login.aspx

After logged in, redirect to Loading.aspx instead of Data.aspx


>>> Loading.aspx

Add id and runat attribute in body tag
<body id="body" runat="server">
Loading Data...
</body>

Add following code snipped in Page_Load event.
string myScript = @"<script language='javascript' type='text/javascript'>
                                function Redirect() {
                                window.location = '";
        myScript += "Data.aspx";
        myScript += "';}</script>";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Wait", myScript);
        body.Attributes.Add("onload", "Redirect();");

That's it. Enjoy programming. !!!

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