Search This Blog

Tuesday 31 July 2012

How to refresh page using javascript freaquently and automatically ?


Refresh web page using javascript with regular intervals
In some scenario, we need to refresh our web page automatically with some interval of time. The better method to do it is using Javascript function. Then we can set a time interval period and for each interval time page will be refresh without any user interaction with web page.
Using setTimeout() with Javascript
The Javascript setTimeout() function allows code to be executed a set of time after some trigger, such as when the page has loaded or a button is pressed.  That means, the setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
Syntax of SetTimeOut() in Javascript
setTimeout(code,millisec,lang)
Examples of setTimeout() with Javascript
A simple example of setTimeout() in javascript, below sample function shows alert message with the time interval 3 seconds after click the button.
<html>
<head>
<script type="text/javascript">
function timedMsg()
{
var t=setTimeout("alert('I am displayed after 3 seconds!')",3000)
}
</script>
</head>
<body>

<form>
<input type="button" value="Display timed alertbox!" onclick="timedMsg()" />
</form>

</body>
</html>
 
Below mentioned example of setTimeout() in Jvascript will start count down after click the button up to the seconds that we enterd into the text box. It is very simple sample for setTimout(0 in javasscript can be easily understood by beginners also.

<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }
}
</script>
</head>
 
How to reload web page frequently and automatically using javascript setTimeout() function? Below mentioned function will help to refresh page frequently with the time of interval that we mentioned.  We can done it by two methods
  1. In meta tage we can set time of interval and have to also mention url that we have to load with the time of interval.
<meta http-equiv="refresh" content="30;url=index.html">
  1. 2.  Next option is create a method in javascript and call it in page load as mentioned below.  
<script type="text/javascript">
    window.onload = setupRefresh;

    function setupRefresh() {
      setTimeout("refreshPage();", 30000); // milliseconds
    }
    function refreshPage() {
       window.location = location.href;
    }
  </script>

Tuesday 24 July 2012

Collapsible panel extender samples in ASP.Net indifferent scenario


How to implement collapsible panel extender in ASP.Net/C#?

Ajax collapsible panel extender is a tool used to collapse and expand each section with content or without content with asynchronous javascript, hence there is no postback happening in the middle of collapse/expand process. Dot Net framework helps to create collapse and expand functionalities within easy steps. Ajax tool kit included a control name Ajax Collapsible Panel Extender allows to implement above mentioned process as very easily.  The CollapsiblePanel is a very flexible extender that allows you to easily add collapsible sections to your web page. This extender targets any ASP.NET Panel control. The page developer specifies which control(s) on the page should be the open/close controller for the panel, or the panel can be set to automatically expand and/or collapse when the mouse cursor moves in or out of it, respectively.

Steps to implement Ajax collapsible panel extender in ASP.Net/C#

Here we are going to demonstrate step by step process to implement ajax collapsible panel extender in ASP.Net/C#. In order to implement collapsible panel extender we need to include ajax control toolkit dll as reference to our visual studio.
  1. Register Ajax control toolkit to your aspx page
  2. Drag and drop a <ScriptManager> from the Toolbox to the page
  3. Now add an UpdatePanel to the page. Inside the <ContentTemplate> drag and drop a CollapsiblePanel from the AJAX toolkit. After applying some Css and add properties of the CollapsiblePanel, the mark up will look similar to the following

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
TagPrefix="cc1" %>

<!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>CollapsiblePanelExtender Tips </title>   
<style type="text/css">
.cpHeader
{
color: white;
background-color: #719DDB;
font: bold 11px auto "Trebuchet MS", Verdana;
font-size: 12px;
cursor: pointer;
width:450px;
height:18px;
padding: 4px;           
}
.cpBody
{
background-color: #DCE4F9;
font: normal 11px auto Verdana, Arial;
border: 1px gray;               
width:450px;
padding: 4px;
padding-top: 7px;
}      
</style>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Panel ID="pHeader" runat="server" CssClass="cpHeader">
<asp:Label ID="lblText" runat="server" />
</asp:Panel>

<asp:Panel ID="pBody" runat="server" CssClass="cpBody">
Here will display our contents or controls
</asp:Panel>

<cc1:CollapsiblePanelExtender ID="CollapsiblePanelExtender1" runat="server"
TargetControlID="pBody" CollapseControlID="pHeader" ExpandControlID="pHeader"
Collapsed="true" TextLabelID="lblText" CollapsedText="Click to Show Content.."
ExpandedText="Click to Hide Content.."
CollapsedSize="0">
</cc1:CollapsiblePanelExtender>

</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

How to Expand/Collapse the ASP.NET AJAX CollapsiblePanel programmatically using JavaScript?

In above example we looked that how we can implement ajax collapsible panel extender within the aspx page. In some scenario we need to call this functionality on some javscript events. In those scenario, we need to study that how we can call collapse and expand functionalities from javascript. Below is the code for calling ajax collapsible panel extender from javascript.
<asp:Button ID="btnClick" OnClientClick="ExpandCollapse()"
runat="server" Text="Expand/Collapse" />
</ContentTemplate>
</asp:UpdatePanel>
Add JavaScript in the <head> tag as shown below:
<script type="text/javascript">

function ExpandCollapse() {           
var collPanel = $find("CollapsiblePanelExtender1");
if (collPanel.get_Collapsed())
collPanel.set_Collapsed(false);
else
collPanel.set_Collapsed(true);
}      

</script>
 
How we can implement ajax collapsible panel extender from code behind in ASP.Net/C#?
We are going to check how we can call expand/collapse ajax collapsible panel extender from code behind in asp.net/c#. In some scenario we need to call expand/collapse functions in Ajax collapsible panel extender dynamically from asp.net/C#. Below mentioned code helps to dynamically call expand/collapse ajax collapsible panel extender from asp.net/c#
protected void btn_Collapse(object sender, EventArgs e)
    {
        // Expand
        this.CollapsiblePanelExtender1.Collapsed = false;
        this.CollapsiblePanelExtender1.ClientState = "false";
        // Collapse
        // Expand
        this.CollapsiblePanelExtender1.Collapsed = true;
        this.CollapsiblePanelExtender1.ClientState = "true";
    }
How to add an Ajax collapsible panel extender dynamically from code behind in ASP.Net/C#
In some scenario we have to create and implement a ajax collapsible panel extender dynamically as per the data from the database in ASP.Net/C#. We can create and implement ajax collapsible panel extender dynamically from code behind in ASP.Net/C# using below mentioned code.

using AjaxControlToolkit;

protected void Page_Load(object sender, EventArgs e)
{        
// Create Header Panel
Panel panelHead = new Panel();
panelHead.ID = "pH";
panelHead.CssClass = "cpHeader";
// Add Label inside header panel to display text
Label lblHead = new Label();
lblHead.ID = "lblHeader";
panelHead.Controls.Add(lblHead);

//Create Body Panel
Panel panelBody = new Panel();
panelBody.ID = "pB";
panelBody.CssClass = "cpBody";
// Add Label inside body Panel to display text
Label lblB = new Label();
lblB.ID = "lblBody";
lblB.Text = "This panel was added dynamically";
panelBody.Controls.Add(lblB);

// Create CollapsiblePanelExtender
CollapsiblePanelExtender cpe =
    new CollapsiblePanelExtender();
cpe.TargetControlID = panelBody.ID;
cpe.ExpandControlID = panelHead.ID;
cpe.CollapseControlID = panelHead.ID;
cpe.ScrollContents = false;
cpe.Collapsed = true;
cpe.ExpandDirection =
CollapsiblePanelExpandDirection.Vertical;
cpe.SuppressPostBack = true;
cpe.TextLabelID = lblHead.ID;
cpe.CollapsedText = "Click to Show Content..";
cpe.ExpandedText = "Click to Hide Content..";

this.UpdatePanel1.ContentTemplateContainer.Controls.Add(panelHead);
this.UpdatePanel1.ContentTemplateContainer.Controls.Add(panelBody);
this.UpdatePanel1.ContentTemplateContainer.Controls.Add(cpe);

}

Saturday 21 July 2012

How to Import CSV File Into SQL Server Using Bulk Insert in SQLServer?



Restore data from csv files into SQL Server
This is very common scenario that we have to import data into sql server database from csv files. In SQL Server there is an option to insert data from a csv file into database. We are going to demonstrate how we can import data from csv files into a sql server database. The constraints are we need to have data in csv files as same structure in the table structure
BULK INSERT
Imports a data file into a database table or view in a user-specified format in SQL Server 2008 R2. Use this statement to efficiently transfer data between SQL Server and heterogeneous data sources.
Arguments :
database_name
Is the database name in which the specified table or view resides. If not specified, this is the current database.
schema_name
Is the name of the table or view schema. schema_name is optional if the default schema for the user performing the bulk-import operation is schema of the specified table or view.
table_name
Is the name of the table or view to bulk import data into. Only views in which all columns refer to the same base table can be used. For more information about the restrictions for loading data into views,
 data_file 
Is the full path of the data file that contains data to import into the specified table or view. BULK INSERT can import data from a disk (including network, floppy disk, hard disk, and so on).
BATCHSIZE =batch_size
Specifies the number of rows in a batch. Each batch is copied to the server as one transaction
CHECK_CONSTRAINTS
Specifies that all constraints on the target table or view must be checked during the bulk-import operation.
Steps to Import CSV to SQL Server / Sample CSV import to SQL Server using BULK Insert
Here we are going to show how to import csv files data into a SQL Server table using bulk Insert method. First of all create a csv file with data as follows :- id, name, age, joindate (Should be same as structure of table).  We have a table with same structure of columns : id, name, age , joindate.
Step 1 : Create a table

CREATE TABLE [dbo].[Employee](
      [id] [int] IDENTITY(1,1) NOT NULL,
      [name] [varchar](50) NULL,
      [age] [int] NULL,
      [joindate] [datetime] NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
      [id] ASC
)
) ON [PRIMARY]
 
Step 2 : Create a csv files and enter the data as same as structure table
 
Step3 : Run following script to insert data from csv to table
BULK
INSERT Employee
FROM 'c:\emp.txt'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)

Saturday 14 July 2012


How to call serverside function from client side javascript in ASP.Net?


Call ASP.Net/C# function using Javscript 
Usually in ASP.net platform, server side functions (all codes written in asp.net,C#) are executing from the server side and all client side funtions (javascript,jquery,ajax) are executing from the client side. Obviously client side functions are too faster than the server side because there is no need to go upto server, will running from the browser itself.
 But we are unable to written all functions in client side to get good performance. But for this technique, there is some tips can be used. What we are going to do is, we are writing a server side code in ASP.Net,C# and call these functions from client side using javascript and ajax.
 Steps to Calling ServerSide method from javscript
  1. Create a aspx page with three textboxes and a button control.
  2. User enter two numbers in first two textboxes and press calculate button.
  3. We are fetching entered values and calling a serverside funtion by passing this values.
  4. In the server side function find the sum and return the result.
  5. In client side’s succes event, getting result from the server and displayed to third textbox.
 Step 1 :
 Create a aspx page with controls, two textboxes for entering the numbers, one button for find the sum of number and a one more text box to display the result.
 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Result.aspx.cs" Inherits="testWebApp.Result" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!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></title>
</head>
<body>
    <form id="form1" runat="server">
      <asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>
    <div>
        <table>
            <tr>
                <td>
                    Number1:
                </td>
                <td>
                    <asp:TextBox ID="txt1" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Number2:
                </td>
                <td>
                    <asp:TextBox ID="txt2" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Sum:
                </td>
                <td>
                    <asp:TextBox ID="txtSum" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnSum" runat="server" Text="Sum" OnClientClick="CallSum();return false;" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>
  Step 2  
In code behind, write a web method to access two parameters and return the result. In the function we added parameters and return the result. 
protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Server side function Sum
        /// </summary>
        /// <param name="arg1">arg1</param>
        /// <param name="arg2">arg2</param>
        /// <returns>result(sum)</returns>
        [System.Web.Services.WebMethod]
        public static int Sum(int arg1, int arg2)
        {

            /* On server side we can do any thing. Like we can access the Session.
             * We can do database access operation. Without postback.
             */
            try
            {
                return arg1 + arg2;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
Step 3
 Create a javscript method in aspx page to get input textboxes values and call serverside function. Here itself we decalre a success and failure event, for getting the event from the server after the current function executed.
 <script language="javascript" type="text/javascript">
    <!--

        // Javascript function
        function CallSum() {
            //Get the controls
            var txt1 = $get("txt1");
            var txt2 = $get("txt2");
            var txtresult = $get("txtSum");

            //Call server side function
            PageMethods.Sum(txt1.value, txt2.value, OnCallSumComplete, OnCallSumError, txtresult);

            /*Server side function get the 2 arguments arg1 and arg2. We are passing txt1.value and txt2.value
            for that. OnCallSumComplete is callback function for complete successfully. OnCallSumError is callback
            function on error. txtresult is usercontext parameter.

            OnCallSumComplete,OnCallSumError,txtresult are optional parameters.

            If server side code executed successfully then OnCallSumComplete will call.
            If server side code do not executed successfully then OnCallSumError will call.

            */
        }

        // Callback function on complete
        // First argument is always "result" if server side code returns void then this value will be null
        // Second argument is usercontext control pass at the time of call
        // Third argument is methodName (server side function name) In this example the methodName will be "Sum"
        function OnCallSumComplete(result, txtresult, methodName) {
            //Show the result in txtresult
            txtresult.value = result;
        }

        // Callback function on error
        // Callback function on complete
        // First argument is always "error" if server side code throws any exception
        // Second argument is usercontext control pass at the time of call
        // Third argument is methodName (server side function name) In this example the methodName will be "Sum"
        function OnCallSumError(error, userContext, methodName) {
            if (error !== null) {
                alert(error.get_message());
            }
        }

    // -->
    </script>
Project is ready for call server sided functions from client side using javascript. Run the application and enter two numbers in first and second textboxes then press calculate button, the we can show that result is displayed in third box without any page postback. If we enterd alphabets instead of numbers, from the server it will happening error and ‘failure’ event occurred in the javascript will alert the details of the error.