Thursday, May 31, 2012

Handle Session Timeout with JQUERY

Use below code copy and paste for testing: This code keep your session alive if you click on OK button when message pop show. but if you don't click on this button it by default redirect to again same page. So you didn't get session timeout issue again. I had get junk character when session timeout. I did everything e.g webconfig setting  to increase the session timeout and request timeout etc but didn't get any success but now everything is working fine. In the below code i highlighted the main code.

Step1: Put these script and css in the Title Tag


 <script type="text/javascript" src="JS/jquery-ui-1.8rc1.custom.min.js">script>
 <link rel="stylesheet" type="text/css" href="JS/jquery-ui-1.8rc1.custom.css" />
 <script type="text/javascript" src="JS/jquery.idletimer.js">script>

Step2: This is script. Write this code in script tag

 var idleTime = 3000; //60000; //1800000; // number of miliseconds until the user is considered idle
        var initialSessionTimeoutMessage = 'Your session will expire in  seconds.

Click on OK to continue your session.'
;
        var sessionTimeoutCountdownId = 'sessionTimeoutCountdown';
        var redirectAfter = 20; // number of seconds to wait before redirecting the user
        var redirectTo = window.location; // URL to relocate the user to once they have timed out
        //        here window.location is used because it set the current url

        var keepAliveURL = 'keepAlive.php'; // URL to call to keep the session alive
        var expiredMessage = 'Your session has expired.  You are being logged out for security reasons.'; // message to show user when the countdown reaches 0
        var running = false; // var to check if the countdown is running
        var timer; // reference to the setInterval timer so it can be stopped
        $(document).ready(function () {
            // create the warning window and set autoOpen to false
            var sessionTimeoutWarningDialog = $("#sessionTimeoutWarning");
            $(sessionTimeoutWarningDialog).html(initialSessionTimeoutMessage);
            $(sessionTimeoutWarningDialog).dialog({
                title: 'Session Expiration Warning',
                autoOpen: false, // set this to false so we can manually open it
                closeOnEscape: false,
                draggable: false,
                width: 460,
                minHeight: 50,
                modal: true,
                beforeclose: function () { // bind to beforeclose so if the user clicks on the "X" or escape to close the dialog, it will work too
                    // stop the timer
                    clearInterval(timer);

                    // stop countdown
                    running = false;

                    // ajax call to keep the server-side session alive
                    $.ajax({
                        url: keepAliveURL,
                        async: false
                    });
                },
                buttons: {
                    OK: function () {
                        // close dialog
                        $(this).dialog('close');
                    }
                },
                resizable: false,
                open: function () {
                    // scrollbar fix for IE
                    $('body').css('overflow', 'hidden');
                },
                close: function () {
                    // reset overflow
                    $('body').css('overflow', 'auto');
                }
            }); // end of dialog


            // start the idle timer
            $.idleTimer(idleTime);

            // bind to idleTimer's idle.idleTimer event
            $(document).bind("idle.idleTimer", function () {
                // if the user is idle and a countdown isn't already running
                if ($.data(document, 'idleTimer') === 'idle' && !running) {
                    var counter = redirectAfter;
                    running = true;

                    // intialisze timer
                    $('#' + sessionTimeoutCountdownId).html(redirectAfter);
                    // open dialog
                    $(sessionTimeoutWarningDialog).dialog('open');

                    // create a timer that runs every second
                    timer = setInterval(function () {
                        counter -= 1;

                        // if the counter is 0, redirect the user
                        if (counter === 0) {
                            $(sessionTimeoutWarningDialog).html(expiredMessage);
                            $(sessionTimeoutWarningDialog).dialog('disable');
                            window.location = redirectTo;
                        } else {
                            $('#' + sessionTimeoutCountdownId).html(counter);
                        };
                    }, 1000);
                };
            });

        });

Step3:Put this in before closing the body tag:


    div id="sessionTimeoutWarning" style="display: none">
  

Wednesday, May 2, 2012

Dynamic Tree View in asp.net


I have created a function to bind treeview control with database in asp.net. It is upto three label. To use this code first copy it and paste it on your page and then call this method Bind_Tree() on page load event. Also create a database for this. I have created three table (tbl_MainCategory,tbl_SubCategory,tbl_Accessory ) in the database and bind three view upto three label with these three tables. 


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

SqlConnection con = new SqlConnection();
SqlDataAdapter adp = new SqlDataAdapter();
DataSet ds = new DataSet();
string PageName = "default.aspx?{0}={1}";


void Bind_Tree()
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
if (con.State == ConnectionState.Closed)
{
con.Open(); }
Sdr.Close();
}
Module_Sdr.Close();
Module_Sdr.Close();

level3_Sdr.Close();

}

TreeView1.Nodes.Add(root);
}
TreeView1.CollapseAll();
con.Close();
}


}

TreeView1.Nodes.Add(root);
}
TreeView1.CollapseAll();
con.Close();
}

}
TreeView1.Nodes.Add(root);
}
TreeView1.CollapseAll();
con.Close();
}

TreeView1.Nodes.Add(root);
}
TreeView1.CollapseAll();
con.Close();
}

SqlCommand SqlCmd = new SqlCommand("Select * from tbl_MainCategory", con);
SqlDataReader Sdr = SqlCmd.ExecuteReader();
SqlCmd.Dispose();
string[,] ParentNode = new string[100, 2];
int count = 0;
while (Sdr.Read())
{
ParentNode[count, 0] = Sdr.GetValue(Sdr.GetOrdinal("Id")).ToString();
ParentNode[count++, 1] = Sdr.GetValue(Sdr.GetOrdinal("Category")).ToString();
}
for (int loop = 0; loop < count; loop++)
{
TreeNode root = new TreeNode();

root.Text = ParentNode[loop, 1];
root.Target = "_blank";
root.NavigateUrl = string.Format(PageName, "Main Category", ParentNode[loop, 0]);

SqlCommand Module_SqlCmd = new SqlCommand("Select * from tbl_SubCategory where MainCategory =" + ParentNode[loop, 0], con);
SqlDataReader Module_Sdr = Module_SqlCmd.ExecuteReader();

int count1=0;
string[,] childNode = new string[100, 2];
while (Module_Sdr.Read())
{
childNode[count1, 0] = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("Id")).ToString();
childNode[count1++, 1] = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("Category")).ToString();
for (int i = 0; i < count1; i++)
{
TreeNode child = new TreeNode();

child.Text = childNode[i, 1];
child.Target = "_blank";
child.NavigateUrl = string.Format(PageName, "Category", childNode[i, 0]);

root.ChildNodes.Add(child);
SqlCommand level3_SqlCmd = new SqlCommand("Select * from tbl_Accessory where Category =" + childNode[i, 0], con);
SqlDataReader level3_Sdr = level3_SqlCmd.ExecuteReader();
while (level3_Sdr.Read())
{
TreeNode subChild = new TreeNode();
subChild.Text = level3_Sdr.GetValue(level3_Sdr.GetOrdinal("Accessory")).ToString();

subChild.Target = "_blank";

subChild.NavigateUrl = string.Format(PageName, "SubCategory", level3_Sdr.GetValue(level3_Sdr.GetOrdinal("Id")).ToString());


child.ChildNodes.Add(subChild);

}

Wednesday, April 18, 2012

Asp.Net Interview Questions





1.In which event are the controls fully loaded?

Page load event guarantees that all controls are fully loaded. Controls are also accessed in Page_Init events but you will see that view state is not fully loaded during this event

2.What is the difference between a default skin and a named skin?

The default skin is applied to all the Web server controls in a Web form, which are of similar type, and it does not provide a Skin ID attribute. The named skin provides a Skin ID attribute and users have to set the Skin ID property to apply it.

3.Which two new properties are added in ASP.NET 4.0 Page class?

The two new properties added in the Page class are MetaKeyword and MetaDescription.

4.What is the difference between authentication and authorization?

Authentication verifies the identity of a user and authorization is a process where you can check whether or not the identity has access rights to the system. In other words, you can say that authentication is a procedure of getting some credentials from the users and verify the user's identity against those credentials. Authorization is a procedure of granting access of particular resources to an authenticated user. You should note that authentication always takes place before authorization.

5.Which ASP.NET objects encapsulate the state of the client and the browser?

The Session object encapsulates the state of the client and browser.

6.Differentiate globalization and localization.

The globalization is a technique to identify the specific part of a Web application that is different for different languages and make separate that portion from the core of the Web application. The localization is a procedure of configuring a Web application to be supported for a specific language or locale
.
7.Which method has been introduced in ASP.NET 4.0 to redirect a page permanently?

The RedirectPermanent() method added in ASP.NET 4.0 to redirect a page permanently. The following code snippet is an example of the RedirectPermanent() method:
RedirectPermanent("test.aspx");

8.What is the difference between the Response.Write() and Response.Output.Write() methods?

The Response.Write() method allows you to write the normal output; whereas, the Response.Output.Write() method allows you to write the formatted output.

9.What does the Orientation property do in a Menu control?

Orientation property of the Menu control sets the horizontal or vertical display of a menu on a Web page. By default, the orientation is vertical.

10.What is the default timeout for a Cookie?

The default time duration for a Cookie is 30 minutes.

11.What are HTTP handlers in ASP.NET?

HTTP handlers, as the name suggests, are used to handle user requests for Web application resources. They are the backbone of the request-response model of Web applications. There is a specific event handler to handle the request for each user request type and send back the corresponding response object.

Each user requests to the IIS Web server flows through the HTTP pipeline, which refers to a series of components (HTTP modules and HTTP handlers) to process the request. HTTP modules act as filters to process the request as it passes through the HTTP pipeline. The request, after passing through the HTTP modules, is assigned to an HTTP handler that determines the response of the server to the user request. The response then passes through the HTTP modules once again and is then sent back to the user.

You can define HTTP handlers in the element of a configuration file. The element tag is used to add new handlers and the element tag is used to remove existing handlers. To create an HTTP handler, you need to define a class that implements the IHttpHandler interface.

12.What is the use of PlaceHolder control? Can we see it at runtime?

The PlaceHolder control acts as a container for those controls that are dynamically generated at runtime. We cannot see it at runtime because it does not produce any visible output. It used only as a container.

13.What is the difference between page-level caching and fragment caching?

In the page-level caching, an entire Web page is cached; whereas, in the fragment caching, a part of the Web page, such as a user control added to the Web page, is cached.

14.Describe the complete lifecycle of a Web page.

When we execute a Web page, it passes from the following stages, which are collectively known as Web page lifecycle:
  • Page request - During this stage, ASP.NET makes sure the page either parsed or compiled and a cached version of the page can be sent in response
  • Start - During this stage sets the Request and Response page properties and the page check the page request is either a postback or a new request
  • Page Initialization - During this stage, the page initialize and the control's Unique Id property are set
  • Load - During this stage, if the request is postback, the control properties are loaded without loading the view state and control state otherwise loads the view state
  • Validation - During this stage, the controls are validated
  • Postback event handling - During this stage, if the request is a postback, handles the event
  • Rendering - During this stage, the page invokes the Render method to each control for return the output
  • Unload - During this stage, when the page is completely rendered and sent to the client, the page is unloaded.
15.What is State Management? How many ways are there to maintain a state in .NET?

State management is used to store information requests. The state management is used to trace the information or data that affect the state of the applications.

There are two ways to maintain a state in .NET, Client-Based state management and Server-Based state management.

The following techniques can be used to implement the Client-Based state management:
  • View State
  • Hidden Fields
  • Cookies
  • Query Strings
  • Control State

The following techniques can be used to implement Server-Based state management:
  • Application State
  • Session State
  • Profile Properties
  
16.What is a round trip? 
  
  The trip of a Web page from the client to the server and then back to the client is known as a round trip.

17.What is Role-based security?

In the Role-based security, you can assign a role to every user and grant the privilege according to that role. A role is a group of principal that restricts a user's privileges. Therefore, all the organization and applications use role-based security model to determine whether a user has enough privileges to perform a requested task.

18.Where is the ViewState information stored?

The ViewState information is stored in the HTML hidden fields.

19.Explain the AdRotator Control.

The AdRotator is an ASP.NET control that is used to provide advertisements to Web pages. The AdRotator control associates with one or many advertisements, which randomly displays one by one at a time when the Web page is refreshed. The AdRotator control advertisements are associated with links; therefore, when you click on an advertisement, it redirects you to other pages.

The AdRotator control is associated with a data source, which is normally an xml file or a database table. A data source contains all the information, such as advertisement graphics reference, link, and alternate text. Therefore, when you use the AdRotator control, you should first create a data source and then associate it with the AdRotator control.
Can we validate a DropDownList by RequiredFieldValidator?
Yes, we can validate a DropDownList by RequiredFieldValidator. To perform this validation, we have to set the InitialValue property of RequiredFieldValidator control.
20.What are the modes of storing ASP.NET session?

-InProc
-StateServer
-SQLServer

21.What is partial classess in .net?
When there is a need to keep the business logic separate from the User Interface or when there is some class which is big enough to have multiple number of developers implement the methods in it, the class can be separated and written in different files as partial class. 
The keyword partial must appear in each class.

Tuesday, April 10, 2012

Authorize.net in asp.net



Below is the code to implement authorize.net with asp.net. But for this first please create a account on www.authorize.net. After that they provide you the LoginID and Transaction key which are used in the below code. Also for testing : set your account in test mode.  
Below is the function for Authorize.net payment with credit card.
//if you have to use “https://test.authorize.net/gateway/transact.dll
//” for testing then uncomment the x_test_request and if use "https://secure.authorize.net/gateway/transact.dll" then no need to use x_test_request variable.




private void MakePaymentWithAuthorizeDotNet()
    {

        String post_url = Convert.ToString(“https://secure.authorize.net/gateway/transact.dll”);

        Dictionary<string, string> post_values = new Dictionary<string, string>();

        #region Replace Parameters
        //the API Login ID and Transaction Key must be replaced with valid values
//if we have to use “https://test.authorize.net/gateway/transact.dll
//” then uncomment the x_test_request.
// post_values.Add("x_test_request", "TRUE".ToString());
        post_values.Add("x_login","Auth_loginID");
        post_values.Add("x_tran_key", "Auth_trankey");
        post_values.Add("x_delim_data", "TRUE");
        post_values.Add("x_delim_char", "|");
        post_values.Add("x_relay_response", "TRUE");
      
        post_values.Add("x_type", "AUTH_CAPTURE");
        post_values.Add("x_method", "CC");
        post_values.Add("x_card_num”,”Credit Card Number”);
        post_values.Add("x_exp_date",“MMYY”);
        post_values.Add("x_card_code", “CVVID code”);
        post_values.Add("x_Email", “Email ID”);
         post_values.Add("x_amount", "Price Amount"]));
        post_values.Add("x_description", "Shopping Cart");
        post_values.Add("x_ship_to_first_name", txtName.Text.Trim());

        post_values.Add("x_ship_to_address", txtShippingAddress.Text.Trim());
        if (txtPhoneNumber.Text != string.Empty)
        {
            post_values.Add("x_phone", txtPhoneNumber.Text.Trim());
        }
       
            post_values.Add("x_first_name", ConfigurationManager.AppSettings["firstname"]);
            post_values.Add("x_last_name", ConfigurationManager.AppSettings["lastname"]);
            post_values.Add("x_address", ConfigurationManager.AppSettings["address"]);
            post_values.Add("x_state", ConfigurationManager.AppSettings["state"]);
            post_values.Add("x_city", ConfigurationManager.AppSettings["city"]);
            post_values.Add("x_zip", ConfigurationManager.AppSettings["zipcode"]);
      

        #endregion

        String post_string = "";

        foreach (KeyValuePair<string, string> post_value in post_values)
        {
            post_string += post_value.Key + "=" + HttpUtility.UrlEncode(post_value.Value) + "&";
        }
        post_string = post_string.TrimEnd('&');

        HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(post_url);
        objRequest.Method = "POST";
        objRequest.ContentLength = post_string.Length;
        objRequest.ContentType = "application/x-www-form-urlencoded";

        // post data is sent as a stream
        StreamWriter myWriter = null;
        myWriter = new StreamWriter(objRequest.GetRequestStream());
        myWriter.Write(post_string);
        myWriter.Close();
        String post_response;
        HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
        using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
        {
            post_response = responseStream.ReadToEnd();
            responseStream.Close();
        }
        Array response_array = post_response.Split('|');
        string chk = response_array.GetValue(5).ToString();
        if (chk == null || chk == string.Empty)
        {
            Session["chk"] = null;
        }
        else
        {
            Session["chk"] = chk;
        }
        ViewState["status"] = response_array.GetValue(5).ToString();
        string trid = response_array.GetValue(6).ToString();
        string response_code = Convert.ToString(response_array.GetValue(0));
        if (response_code == "1")
        {
            if (trid != "0")
            {
                ViewState["TransID"] = response_array.GetValue(6).ToString();
            }
        }
        else
        {
            ViewState["TransID"] = null;
        }
        ViewState["CreditType"] = response_array.GetValue(51).ToString();
        ViewState["CreditCrd"] = response_array.GetValue(50).ToString();
    }

Friday, October 14, 2011

Webservice to get distance from Latitude and Longitude

 Sample Application for Web Service


Write this code on WebService Page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]

public class Service : System.Web.Services.WebService
{
    public Service () {

    }
    [WebMethod]
    public double distanceFrom(double lat1, double lng1, double lat2, double lng2)
    {
        double dist;       
        dist= distance(lat1, lng1, lat2, lng2);
        return dist;
    }
    private double distance(double lat1, double lon1, double lat2, double lon2)
    {
        double theta = lon1 - lon2;
        double dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * Math.Cos(deg2rad(theta));
        dist = Math.Acos(dist);
        dist = rad2deg(dist);
        dist = dist * 60 * 1.1515;
        //For Kilometer
       // dist = dist * 1.609344;
       //For S Miles
       //   dist = dist * 0.8684;
        dist = Math.Round(dist, 2);
        return (dist);
    }
    private double deg2rad(double deg)
    {
        return (deg * Math.PI / 180.0);
    }
    private double rad2deg(double rad)
    {
        return (rad / Math.PI * 180.0);
    }
}

After This Add Web Reference in your site and write code on your aspx.cs page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ServiceReference1;

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
       
        ServiceReference1.ServiceSoapClient sp=new ServiceSoapClient();
        double lat1=Convert.ToDouble(TextBox1.Text);
        double lat2 = Convert.ToDouble(TextBox3.Text); ;
        double lon1=Convert.ToDouble(TextBox2.Text);
        double lon2 = Convert.ToDouble(TextBox4.Text); ;
        double str = sp.distanceFrom(lat1,lon1,lat2,lon2);
        TextBox5.Text = str.ToString()+' '+"Miles";
    }
}