Archive for the ‘Javscript’ Category

Access Cookies from JavaScript

January 31, 2013

 

Here is the code to access Cookies from Javascript.

Happy coding Smile

 

   1:  <html xmlns="http://www.w3.org/1999/xhtml&quot;>

   2:  <head id="Head1" runat="server">
   3:   
   4:      <title>Welcome</title>
   5:      <script type="text/javascript">
   6:      
   7:        function getCookies() {
   8:              var cks = new Object();
   9:              var ckList = document.cookie.split("; ");
  10:              for (var i = 0; i < ckList.length; i++) {
  11:                  var ck = ckList[i].split("=");
  12:                  cks[ck[0]] = unescape(ck[1]);
  13:              }
  14:              return cks;
  15:          }
  16:   
  17:         
  18:          function init() {
  19:             var cookies = getCookies();
  20:             var value1 = cookies["opADFS_WTREALM"];
  21:                  alert(value1);
  22:          }
  23:          window.onload = init;
  24:      </script>
  26:  </head>
  27:  </html>

JavaScript Session Timeout Forms Authentication using JQuery Ajax and Webservice

July 9, 2012

If you want to handle your Session timeout through Javascript to Popup a window that says “you have been logged out due to time out”  Then Folllow these 3 Simple steps…

Step1: Regster a javascript function in Page_Init method of your Page.

1: private void RegisterSessionTimeOutScript() 2: {

 3:         StringBuilder csText = new StringBuilder();
 4:         csText.Append("<script type=\"text/javascript\" language=\"javascript\">");
 5:         csText.Append("var timeOut;"); 
 6:         csText.Append("var MinutesToTimeOut;");
 7:         csText.Append("function resetTimer() {");
 8:         csText.Append("clearTimeout(timeOut);");
 9:         csText.Append("if(window.abandonSession)");
 10:         csText.Append("timeOut = setTimeout(abandonSession, MinutesToTimeOut*60*1000);");
 11:         csText.Append("// 1Sec = 1000 Milli Secs");
 12:         csText.Append("}");
 13:         csText.Append(string.Format("window.onload=resetTimer; document.onmousemove = resetTimer; document.onkeypress = resetTimer; MinutesToTimeOut={0};", FormsAuthentication.Timeout.Minutes));
 14:         csText.Append("</script>");
 15:         Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "SessionTimeOutScript", csText.ToString());
 16:     }
Register above javascript inside Page_Init method
 1:   protected void Page_Init(object sender, EventArgs e)
 2:     {
 3:         RegisterSessionTimeOutScript();
 4:      }

Step2: JQuery method to call ajax WebService

 1:  $(document).ready(function () {
 2:  function abandonSession() {
 3:           // alert('coming');
 4:             $.ajax({
 5:                 type: "POST",
 6:                 url: "JQuerySessionTimeOutWebservice.asmx/AbandonSessionOnTimeout",
 7:                 contentType: "application/json; charset=utf-8",
 8:                 dataType: "json",
 9:                 success: function (msg) {
 10:                     // Do something interesting here.
 11:                     if (msg.d.IsUserLoggedIn == false) {
 12:                         alert('You are about to be signed out due to your current session timeout');
 13:                         $(window).attr("location", msg.d.LoginUrl);
 14:                     }
 15:                 }
 16:             });
 17:         }

Step3: Create a web service inside your web application.

 1: WebService(Namespace = "http://tempuri.org/")]
 2: [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
 3: // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
 4: [System.Web.Script.Services.ScriptService]
 5: public class JQuerySessionTimeOutWebservice : System.Web.Services.WebService
 6: {
 7:  
 8:     public JQuerySessionTimeOutWebservice()
 9:     {
 10: 
 11:         //Uncomment the following line if using designed components 
 12:         //InitializeComponent(); 
 13:     }
 14: 
 15:     [WebMethod(EnableSession = true)]
 16:     public JsonLoginValues AbandonSessionOnTimeout()
 17:     {
 18:         if (Session != null)
 19:         {
 20:             Session.Abandon();
 21:             FormsAuthentication.SignOut();
 22:         }
 23:  
 24:         JsonLoginValues values = new JsonLoginValues();
 25:         values.IsUserLoggedIn = false;
 26:         values.LoginUrl = (DistributorPortalAPI.Common.IsClaimsAuthentication) ? System.Configuration.ConfigurationManager.AppSettings["SignOutURL"].ToString() : FormsAuthentication.LoginUrl;
 27:         return values;
 28:     }
 29:  
 30: [Serializable]
 31: public class JsonLoginValues
 32: {
 33:     public string LoginUrl;
 34:     public bool IsUserLoggedIn;
 35: }
 36: 
 37: }

You can place Class JsonLoginValues in a separate class file…

Set your Forms Authentication Timeout to one minute in your web.config and then run your application to test your code….

Happy coding…:-)

Calling Web Service from your Java Script

January 26, 2010

Here we will see how to call a web service from your javascript.

Open Visual Studio 2005/2008 and create “New WebApplication”.

Add an aspx page and name it to WebService.aspx. Inside the page declare a static method called Add.

This “Add” method takes parametes called “Input” which is structure with two member variables and returns a Result object which in turn a structure object with “result”  as a member variable which is an integer

public partial class WebService : System.Web.UI.Page
   {

[WebMethod]
       public static Result Add(Input input)
       {
           Result c = new Result();
           c.result = input.item1 + input.item2;
           return c;
       }

  public struct Input
  {
      public int item1;
      public int item2;
  }

public struct Result
{
     public int result;
}

}

Now add one more page called Default.aspx.

On the top of this page, add script manager, which allows you to call web service using javascript. You can see that i have added two more text boxes and html button.

<form id=”form1″ runat=”server”>
    <asp:ScriptManager ID=”s1″ runat=”server”></asp:ScriptManager>
<div>
   Input value 1 <asp:TextBox ID=”t1″ runat=”server”></asp:TextBox>
    <br />
   Input value 2 <asp:TextBox ID=”t2″ runat=”server”></asp:TextBox>
    <br />
   <input type=”button” id=”b1″ onclick=”javascript:CallWebService();” value=”Click”/>

<br />
    Result : <asp:Label ID=”l1″ runat=”server”></asp:Label>

       </div>
  </form>

Now we will write javascript that calls web service, that adds two integer values and displays the result in a Label

As You can see that i have added three javascript methods CallWebService, OnResultFoundand OnFailed.

CallWebServicehas the code that actually makes a call to web service.

if we look deeper into the syntax, Sys.Net.WebServiceProxy.Invoke takes few parameters.

The first parameter is the path of the web service. “/WebService.aspx”

The second parameter is the name of web method to invoke: “Add”

next parameter is useHttpGet (Optional) false if the Web request HTTP verb is POST; otherwise, true. The default is false.

next Parameter is the Javscript dictionary that contains named properties (fields) that correspond to the parameters of the method to call, as in this example we are passing input values:

{ "input": { "item1":item1 ,"item2":item2 } }

note

The field names in the dictionary must match the names of Web service methods.

(Optional)next Parameter is the name of the Javascript  method that would be called back if web service is executed successfully

If no callback function is provided, no action is taken when the Web service method finishes successfully.

(Optional)next Parameter is the name of the Javascript  method that would be called back if web service is executed successfully

If no callback function is provided, no action is taken if an error occurs during the Web service method call.

(Optional) Any user-specific information. userContext can be any JavaScript primitive type, array, or object.

next parameter is the contents of userContext are passed to the callback functions (if any). If userContext is not provided, null is passed to the callback function.

last parameter is (Optional) the time in milliseconds that the network executor must wait before timing out the Web request. timeout can be an integer or null. By defining a time-out interval, you can control the time that the application must wait for the callback to finish.

<script type=”text/javascript”>

function CallWebService()

  {

      var item1 = document.getElementById(‘t1’).value;

      var item2 = document.getElementById(‘t2’).value;

      var lblResult = document.getElementById(‘l1’);

      Sys.Net.WebServiceProxy.invoke(“/WebService.aspx”, “Add”, false, { “input”: { “item1″:item1 ,”item2”:item2 } },

                                  OnResultFound, OnFailed, lblResult, 5000);

  }

function OnResultFound(retVal, lblResult)

{

     lblResult.innerHTML = retVal.result;

}

function OnFailed(error)

{

     alert(“There was an error “+error.toString());

}

</script>

image

Happy Coding 😉

Populate DropDownList by Calling Web Service from JavaScript

January 26, 2010

 

Now we will see how to call WeBService from your javascript and populate drop down.

Here we will see how to call a web service from your javascript.

Open Visual Studio 2005/2008 and create “New WebApplication”.

Add an aspx page and name it to WebService.aspx. Inside the page declare a static method called PopulateCountries.

This “PopulateCountries” method returns a Countries object which in turn a structure object with “countries”  as a member variable which is an array of countries.

public partial class WebService : System.Web.UI.Page
   {

      [WebMethod]
       public static Countries PopulateCountries()
       {
           Countries countries = new Countries();
           Country[] carray = new Country[5];
           Country c = new Country();
           c.countryName = “USA”;
           c.countryId = 1;
           carray[0] = c;

           c = new Country();

           c.countryName = “UK”;
           c.countryId = 2;
           carray[1] = c;

           c = new Country();

           c.countryName = “India”;
           c.countryId = 3;
           carray[2] = c;

           c = new Country();

           c.countryName = “Argentina”;
           c.countryId = 4;
           carray[3] = c;

           c = new Country();

           c.countryName = “Mexico”;
           c.countryId = 5;
           carray[4] = c;

           countries.countries = carray;

           return countries;
       }

       public struct Countries
       {
           public Country[] countries;
       }

       public struct Country
       {
           public string countryName;
           public int countryId;
       }

}

Now add one more page called Default.aspx.

On the top of this page, add script manager, which allows you to call web service using javascript. You can see that i have added drop down list and html button.

<form id=”form1″ runat=”server”>
    <asp:ScriptManager ID=”s1″ runat=”server”></asp:ScriptManager>
    <div> 
   Countries <asp:DropDownList ID=”ddCountries” runat=”server”/>    <br /> 
    <input type=”button” id=”b1″ onclick=”javascript : PopulateCountries();” value=”Click”/> 
       </div>
  </form>

Now we will write javascript that calls web service, returns a list of countries to populate the drop down list.

As You can see that i have added three javascript methods PopulateCountries, OnCountriesFound and OnFailed.

PopulateCountries has the code that actually makes a call to web service.

if we look deeper into the syntax, Sys.Net.WebServiceProxy.Invoke takes few parameters.

The first parameter is the path of the web service. “/WebService.aspx”

The second parameter is the name of web method to invoke: “Add”

next parameter is useHttpGet (Optional) false if the Web request HTTP verb is POST; otherwise, true. The default is false.

next Parameter is the Javscript dictionary that contains named properties (fields) that correspond to the parameters of the method to call, as in this example we are passing an empty braces:

{ }

note

The field names in the dictionary must match the names of Web service methods.

(Optional)next Parameter is the name of the Javascript  method that would be called back if web service is executed successfully

If no callback function is provided, no action is taken when the Web service method finishes successfully.

(Optional)next Parameter is the name of the Javascript  method that would be called back if web service is executed successfully

If no callback function is provided, no action is taken if an error occurs during the Web service method call. 

(Optional) Any user-specific information. userContext can be any JavaScript primitive type, array, or object.

next parameter is the contents of userContext are passed to the callback functions (if any). If userContext is not provided, null is passed to the callback function.

last parameter is (Optional) the time in milliseconds that the network executor must wait before timing out the Web request. timeout can be an integer or null. By defining a time-out interval, you can control the time that the application must wait for the callback to finish.

<script type=”text/javascript”>

   function PopulateCountries()

   {

       var ddCountries = document.getElementById(‘ddCountries’);

Sys.Net.WebServiceProxy.invoke(“/WebService.aspx”, “PopulateCountries”, false, { },OnCountriesFound, OnFailed,  ddCountries, 5000);

   }
function OnCountriesFound(retVal,ddCountries)

   {

       for(var i=0; i<retVal.countries.length; i++)

       {

           ddCountries.options[i] = new Option(retVal.countries[i].countryName, retVal.countries[i].countryId);

       }

   }

function OnFailed(error)

   {

       alert(“There was an error “+error.toString());

   }

</script>

image

Happy Coding 😉