August 2011 | Coding Cluster - using asp.net, c#, mvc 4, iphone, php, ios, javascript, in asp.net mvc 3 & more
 

Cookies handling using javascript

Monday


This simple post explained the cookie handling including create,get and delete cookies by using javascript.In one of my ruby project I'm struggled with retained client side paging (Paging using javascript) on that time I'm using this client side cookies to over come that problem.I thing you may use this concept to client side paging,sorting,keep dropdown sclected index and other client side actions.


Code:

<script src="../cookies.js"></script>
 

Step 1: Check cookies is enabled

Before go to create cookie you have to check if the cookies are allowed.

<script type="text/javascript" language="javascript">

    
function isCookiesEnabled () {
        
if (testSessionCookie())
            
alert ("Session coookies are enabled")
        
else
            alert 
("Session coookies are not enabled");
    
}

</script>


  Click to see if session cookies are allowed:


Step 2: Create cookie:

        The next step you can give a name and value for your cookie.
 
<script type="text/javascript" language="javascript">

    
function setCookie(){

        
if (testSessionCookie()) {

               
var myName = document.getElementById('addCookiName').value;

            var 
myValue = document.getElementById('addCookiValue').value;

            
createCookie (myName, myValue);
            alert 
("Session cookie created");
        
}
        
else
        
{
            
alert ("Sorry - session cookies are currently disabled.");
        
}     

}
</script>

Demo: 

Create cookie:

Cookie name:

Cookie value:


 
Step: 3: Get value from cookies by using its name


<script type="text/javascript" language="javascript">

    
function getCookie () {
        
var myCookieName = document.getElementById('getCookiName').value;
        if 
(getCookieValue (myCookieName))
            
alert ('The value of the Cookie is "' + getCookieValue (myCookieName) + '"')
        
else
            alert 
("Cookie not found");
    
}

</script
 

Demo:

Get value from cookie by using it's name
Cookie name:

Step 4:

And finally you can delete value from cookie by using the following nethod


<script type="text/javascript" language="javascript">

    
function deleteCookies () {
        
var myCookieName = document.getElementById('deleteCookiName').value;
        if
(myCookieName !""){
            
if (!getCookieValue (myCookieName))
                
alert ('Cookie does not exist')
           
else  {
                deleteCookie(myCookieName)
;
                alert 
("Cookie deleted successfully");

            
}
        }        
else

        
{

            
alert ('Cookie does not exist')
        }

    }

</script>

Demo: 

Delete value from cookie by using it's name
Cookie name:


You can download full source code from here...

How to get ip address in asp.net using csharp

Saturday

Get IP Address Of A System using c# :

  The following just two line code to useful for Get IP Address Of A Machine using C#.

Code:

     // Get the hostname 
        string yourHost = System.Net.Dns.GetHostName();

        // Show the hostname 
        lblMyhost.Text = yourHost;

        // Get the IP from the host name
        string yourIP = System.Net.Dns.GetHostEntry(yourHost).AddressList[0].ToString();

        // Show the IP 
         lblIPAddress.Text = yourIP;

How to find special characters using c#

 Find if a String contains Special Characters using c#:

Hai friends,
There are many ways to detect if a String contains Special Characters. In this code snippet, I will show a quick way to detect special characters using Regex.

C# code for find  if a String contains Special Characters.

Code: 

static void Main(string[] args)
{
    string str = "Th!s $tri^g c@n$ist $pecial ch@rs";
    Match match = Regex.Match(str, "[^a-z0-9]",
            RegexOptions.IgnoreCase);
    while (match.Success)
    {
        string key = match.Value;
        Console.Write(key);
        match = match.NextMatch();
    }
    Console.ReadLine();
}

How to create Watermark TextBox in ASP.NET


 Watermark TextBox using JavaScript:

This article, will explain how watermark textbox using JavaScript.
 It is very useful and uses less resourcescompared to AJAX.
Below is the short JavaScriptthat helps doing the watermark. 

Code:
<script type = "text/javascript">
   
var defaultText = "Enter your text here";    
function waterMarkText(txt, evt)     
{      
if(txt.value.length == 0 && evt.type == "blur")       
{           
txt.style.color = "red";           
txt.value = defaultText;       
}       
if(txt.value == defaultText && evt.type == "focus")        
{           
txt.style.color = "green";           
txt.value="";        
}
}
</script>

The script will be called on onblur and onfocus events of the textbox. The
script simply does the following two checks
1. If the textbox is empty and the event type is blur event it sets the watermark and changes
the font color as Gray.
2. If the textbox text matches default text and the event type is the focus it clears
the textbox and sets the font color as Black. 
Now we just call it withthe textbox. 
<asp:TextBox ID="TxtWaterMark" runat="server" Text= "Enter your text here"
 ForeColor = "Gray" onblur = "waterMarkText(this, event);"    
onfocus = "waterMarkText(this, event);"> </asp:TextBox>

Now write the following code in to the code behind. 
C#
TxtWaterMark.Attributes.Add("onblur", "waterMarkText(this,event);");
TxtWaterMark.Attributes.Add("onfocus", "waterMarkText(this,event);");   


Watermark Demo:
Watermark TextBox    




The web services enumeration components are not available. You need to reinstall Visual Studio to add web references to your application(Add Web Service Reference)

 Adding Web Service Reference Fails in Visual Studio
                                             I'm got an error message like "The web services enumeration components are not available. You need to re-install Visual Studio to add web references to your application". while try to add web references Sounds like the installation is somehow corrupted.

And I find the following solution from net. Just click start button, click run and type the following command.

1) Run-> "devenv /resetskippkgs" , (without quotes)

2) when having 2 VS installed (like VS2008 and VS2005) on same machine it is better to parse command with the full path name:
"C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\devenv.exe" /resetskippkg

I'm  resolved my problem by this way...
If this post was help to you. Then Share this to your friends. Thanks!



Get Directory Size - C#



 Get Directory Size In Bytes,KB,and MB using C#

     Calculate the Size of a Folder/Directory using .NET 4.0   
                                 .NET 4.0 introduces 7 New methods to Enumerate Directory and Files in .NET 4.0.
All these methods return Enumerable Collections (IEnumerable<T>), which perform better   than  arrays. We will be using the DirectoryInfo.EnumerateDirectories and DirectoryInfo. EnumerateFiles in this sample which returns an enumerable collection of Directory and File information respectively.    
  
Here's how to calculate the size of a folder or directory using .NET 4.0 and LINQ. The code also   calculates the size of all sub-directories.


    Calculate the Size of a Folder/Directory using C#
   
    using System;
    using System.Linq;
    using System.IO;
   
    namespace DirectoryInfo
    {
      class Program
      {
        static void Main(string[] args)
        {
          DirectoryInfo dInfo = new DirectoryInfo(@"Your folder path here");
          // set bool parameter to false if you
          // do not want to include subdirectories.
          long sizeOfDir = DirectorySize(dInfo, true);
   
          Console.WriteLine("Directory size in Bytes : " +
          "{0:N0} Bytes", sizeOfDir);
          Console.WriteLine("Directory size in KB : " +
          "{0:N2} KB", ((double)sizeOfDir) / 1024);
          Console.WriteLine("Directory size in MB : " +
          "{0:N2} MB", ((double)sizeOfDir) / (1024 * 1024));
   
          Console.ReadLine();
        }
   
        static long DirectorySize(DirectoryInfo dInfo, bool includeSubDir)
        {
           // Enumerate all the files
           long totalSize = dInfo.EnumerateFiles()
                        .Sum(file => file.Length);
   
           // If Subdirectories are to be included
           if (includeSubDir)
           {
              // Enumerate all sub-directories
              totalSize += dInfo.EnumerateDirectories()
                       .Sum(dir => DirectorySize(dir, true));
           }
           return totalSize;
        }
      }
    }

How to Disable the Browser Back Button

Disable Browser Back Button Using Javascript:

Just put this JavaScript on the html section to disable browser's back button.(avoid user going to previous page by clicking on back button of browser).

The scripts work all major browsers like IE,FF.Chrome
Code:

<script language="javascript" type="text/javascript">

        noBack2();

        function noBack2(){window.history.forward();}
        window.onload=noBack2;
        window.onpageshow=function(evt){if(evt.persisted)noBack2();}
        window.onunload=function(){void(0);}

</script>


ASP.NET: Unable to make the session state request to the session state server.

Unable to make the session state request to the session state server

Problem:

Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same. If the server is on a remote machine, please ensure that it accepts remote requests by checking the value of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection. If the server is on the local machine, and if the before mentioned registry value does not exist or is set to 0, then the state server connection string must use either 'localhost' or '127.0.0.1' as the server name.


Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same. If the server is on a remote machine, please ensure that it accepts remote requests by checking the value of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection. If the server is on the local machine, and if the before mentioned registry value does not exist or is set to 0, then the state server connection string must use either 'localhost' or '127.0.0.1' as the server name.

Source Error:


An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[HttpException (0x80072749): Unable to make the session state request to the
session state server. Please ensure that the ASP.NET State service is started and that the 
client and server ports are the same.  If the server is on a remote machine, please ensure
that it accepts remote requests by checking the value of
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection.
If the server is on the local machine, and if the before mentioned registry value does not 
exist or is set to 0, then the state server connection string must use either 'localhost' or '127.0.0.1'
as the server name.]    System.Web.SessionState.OutOfProcSessionStateStore.MakeRequest(StateProtocolVerb 
verb, String id, StateProtocolExclusive exclusiveAccess, Int32 extraFlags, Int32 timeout,
Int32 lockCookie, Byte[] buf, Int32 cb, Int32 networkTimeout, SessionNDMakeRequestResults& results) +1582 
System.Web.SessionState.OutOfProcSessionStateStore.DoGet(HttpContext context, String id, 
StateProtocolExclusive exclusiveAccess, Boolean& locked, TimeSpan& lockAge, Object& lockId,
SessionStateActions& actionFlags) +171    System.Web.SessionState.OutOfProcSessionStateStore.
GetItemExclusive(HttpContext context, String id, Boolean& locked, TimeSpan& lockAge, Object& lockId,
SessionStateActions& actionFlags) +26    System.Web.SessionState.SessionStateModule.GetSessionStateItem() +72
System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData) +472 
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +90 ]
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +161 



Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433


Solution:




One I suffered this problem I got the following solution from some other site. Follow the bellow steps:
1) Start–> Administrative Tools –> Services
2) Write click over the service shown below and click "start"

I hope this help you to solve the problem.


Find Browser Name using JavaScript

 Find the browser name using javascript
Hi folks,
             Browser detection allows you to find out what browser your  using.The following javascript function used to find the browser type.

There are two objects often used for this, the navigator.appName and navigator.appVersion objects. The first one returns the name of the browser, the second returns the version of the browser.

Code: 

function findBrowser()
  {
    var browserName=navigator.appName;
    if (browserName=="Netscape")
    {
      alert("Hi You are a Netscape User!");
    }
    else
    {
      if (browserName=="Microsoft Internet Explorer")
      {
        alert("Hi, Your are an Explorer User!");
      }
      else
      {
        alert("????");
      }
    }

  }

Create drop-down list - Javascript


Create drop-down list using for loop in Javascript


Hai Folks,

The following code is used to create drop down list using for loop in javascript.
The screen shot is the example for time (12 hours formate) drop down.
Using this script you can create Minutes, Seconds,Years,etc... like this
Note: you want to create one menu, you dont want the <select> tags inside of the loop.

  <script language="JavaScript" type="text/javascript">

            // loop to create the list
            TimeHours();
            function TimeHours()
            {
                var TimeHours = 0
                document.write("<select name='TimeHours'>");

                for (var i=1; i <=12; i++)
                {
                    TimeHours++;
                    document.write("<option>" + TimeHours + "</option>");
                }

            }
   </script>


Auto refresh div using Ajax

Refreshing a div without page reload using Ajax:

This Ajax code will used to refresh a div element automatically in every 3 seconds without page reload.
You can changed the refreshing time.



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Auto Refresh</title>
    <script type="text/javascript">
      function AutoRefresh(){
        var xmlHttp;
        try{
          xmlHttp=new XMLHttpRequest();// Firefox, Opera 8.0+, Safari
        }
        catch (e){
          try{
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
          }
          catch (e){
            try{
              xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e){
              alert("No AJAX");
              return false;
            }
          }
        }

        xmlHttp.onreadystatechange=function(){
          if(xmlHttp.readyState==4){
            document.getElementById('AutoUpdte').innerHTML=xmlHttp.responseText;
            setTimeout('AutoRefresh()',3000); // JavaScript function calls AutoRefresh() every 3 seconds
          }
        }
        xmlHttp.open("GET","Your_page_url_that_contains_the_div_content",true);
        xmlHttp.send(null);
      }

      AutoRefresh();
    </script>
  </head>
  <body>
    <div id="AutoUpdte">Your Content</div>
  </body>
</html>

Enjoy!

Check all checkboxes using javascript

Javascript Check and Uncheck All Checkboxes:
This is a simple script to check all check boxes in a form using javascript.
You can check all the check boxes inside the table by clicking another one check box placed in header of that table.
In that same way you can uncheck all checkboxes.If you unchecking a single check box from inside the table then the header(main) check box is automatically go to unchecked state.


Code:
<html>
    
<head>
        
<title>JavaScript - Select All checkbox in form</title>
        
<style type="text/css">
            table
.tblCheckDemo {
                font-family
:arial;
                border-collapse
:collapse;
                border
: solid 3px #7f7f7f;
                font-size
:small;
            
}

            table
.tblCheckDemo td {
                padding
: 5px;
                border-right
: solid 1px #7f7f7f;
            
}

            table
.tblCheckDemo .even {
                background-color
: #EEE8AC;
            
}

            table
.tblCheckDemo .odd {
                background-color
: #F9FAD0;
            
}

            table
.tblCheckDemo th {
                border
: 1px solid #7f7f7f;
                padding
: 5px;
                height
: auto;
                background
: #D0B389;
            
}
        </
style>

        
<script LANGUAGE="JavaScript">

            
function checkMain()
             {               
               if(document.myform.chkMain.checked==true)
                {
                       checkAll()

                }  
             else
                {
                    uncheckAll()

                 }
            }
            
function checkSub()
            {
                fruit 
= document.myform.chkFruit;
                var count 0;
                for (i 0i < fruit.lengthi++)
                    
if(fruit[i].checked) 
                      {
                    count++;
                
}

                
if(fruit.length == count) 
                {                     
                     document.myform.chkMain.checked = true;
                
}
                
else
                
{
                    
document.myform.chkMain.checked = false;
                
}
            }

            
function checkAll()
            {

                fruit = document.myform.chkFruit
                for 
(i 0i < fruit.lengthi++)
                    fruit[i].checked = true ;
            
}

            
function uncheckAll()
            {

                fruit = document.myform.chkFruit;
                for 
(i 0i < fruit.lengthi++)
                fruit[i].checked
= false ;
            
}
        
</script>
   
</head>
   
<body>
       
<form name="myform" method="post">
           
<b>Select Your Favorite Fruits </b><br>
           
<table class="tblCheckDemo">
               
<tr>
                   
<th>S.NO</th>
                   
<th>Fruit</th>
 
<th> <input type="checkbox" name="chkMain" onClick="checkMain()"></th>
               
</tr>
               
<tr class="even">
                   
<td>1</td>
                   
<td>Apple</td>
 
<td> <input type="checkbox" name="chkFruit" value="1" onClick="checkSub()"></td>
               
</tr>
               
<tr class="odd">
                   
<td>2</td>
                   
<td>Orange</td>                    <td> <input type="checkbox" name="chkFruit" value="2" onClick="checkSub()"></td>
               
</tr>
                         .
                         .
                         . 
                         .
   
            
</table>
       
</form>
   
</body>
</html>
Demo:

Select Your Favorite Fruits


S.NO Fruit
1 Apple
2 Orange
3 Asian palmyra palm
4 Goe
5 Garden strawberry
6 Sapote
7 Jackfruit
8 Sour cherry
9 Palmera de coco
10 Night blooming cereus

 
 
 

RECENT POSTS

Boost

 
Blogger Widgets