Tag Archive for session

Store/retrieve object in session

//On Login page
User currentUser = <get the User entity here, including relations to UserRights>;
Session.Add("CurrentUser", currentUser);

//On another page
User restoredUser = Session["CurrentUser"] as User;
if (restoredUser != null)
{
	//use the User entity here to check user's rights
}

source

Php Feedback Form w/ Session and Browser Info

<? include("browser_class.php"); ?> //include class from here <a href="http://snipplr.com/view/35627/php-browser-detection-class/" >http://snipplr.com/view/35627/php-browser-detection-class/</a>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">" >http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"></a>
<html xmlns="<a href="http://www.w3.org/1999/xhtml">" >http://www.w3.org/1999/xhtml"></a>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" href="attSearch.css" type="text/css" />
<style>
body {width:400px;margin:0px auto;text-align:left!important}
h2 {color:green;}
</style>
</head>

<body style="background:none!important;">
<?php
// declare values
$loc = $_COOKIE['location'];
$contact_email = $_POST['EmailAddress'];
$contact_subject = $_POST['Subject'];
$contact_name = $_POST['FullName'];
$contact_message = $_POST['Message'];
$contact_custname = $_SESSION['businessName'];
$contact_accno = $_SESSION['accountNo'];
$mydate = date ( 'l, F d Y g:i A',time()+240 );
// where to send e-mail to
$to = '<a href="mailto:youremail@yourprovider.com">youremail@yourprovider.com</a>';

// e-mail subject
$subject = "Feedback from $contact_custname";

// e-mail message
$message = "You have received feedback:
"."----------------------------------------------
"
."Contact Name: $contact_name
"
."Business Name: $contact_accno, $contact_custname
"
."Subject: $contact_subject
"
."Submitted: $mydate
"
."From IP: {$_SERVER['REMOTE_ADDR']}
"
."URL: $loc
"
."Browser: $Browser->Name $Browser->Version
"
."Message: $contact_message";

$headers = "From: $contact_name <$contact_email>
"
."Reply-To: $contact_email
"
."X-Mailer: PHP/".phpversion();

// check for validation, then send the e-mail
if(empty($contact_name) || empty($contact_email) || empty($contact_subject) || empty($contact_message)) {
echo '<h2>Have feedback?</h2>
<form method="post" action="">
<table id="Form-Details">
<tbody>
<tr><td width="20%">Your Name:</td><td><input type="text" name="FullName" size="40" /></td></tr>
<tr><td width="20%">Subject:</td><td><select name="Subject">
		<option value="Feedback">Feedback</option>
		<option value="Suggestion">Suggestion</option>
		<option value="Bug Report">Bug Report</option>
		<option value="Question">Question</option>
		</select>
</td></tr>
<tr><td width="20%">Email:</td><td colspan="3"><input type="text" name="EmailAddress" size="40" /></td></tr>
<tr><td colspan="4">Message:</td></tr>
<tr><td colspan="4"><textarea rows="6" name="Message" cols="47" class="input"></textarea></td></tr>
<tr><td colspan="4" align="right"><input type="submit" value="Submit Feedback" /></td></tr>
</tbody>
</table>
</form>';
} elseif(!ereg("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $contact_email)) {
echo "<h2 style='font-weight:bold;color:red;'>ERROR: Please enter a valid e-mail address.</h2>";
} else {
mail( $to, $subject, $message, $headers );
echo "<h2>Message Sent!</h2><br /><p>$contact_name,<br /><br />Thank you for your feedback, we will get back to you as soon as possible using $contact_email.";
}
?>
</body>
</html>

source

Authentication class using cookies or sessions

<?php
/*
#
#        Copyright Iulian Ciobanu (CIGraphics) 2009
#        Email: <a href="mailto:cigraphics@gmail.com">cigraphics@gmail.com</a>
#        Please leave the copyright and email intact.
#

# DATABASE TABLE:

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user` varchar(200) NOT NULL,
  `password` varchar(40) NOT NULL,
  `email` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

# LETS INSERT SOME DATA FOR TESTING PURPOSES:
INSERT INTO `users` (`id`, `user`, `password`, `email`) VALUES (1, 'user', '20ccbe71c69cb25e4e0095483cb63bd394a12b23', '<a href="mailto:user@email.com">user@email.com</a>');

# FOR TESTING PURPOSES:
The user is: user
The password is: 123456

# USAGE:

$auth = new Auth('database', 'user', 'password', 'host'); // This must be placed at the top of your document you don't need to start the session this script will do it.
$auth->type = session or cookie; // If you want to use sessions you don't need to write it else write cookie.
$auth->emailAuth = false or true; // If you want users to login with email instead of username set it to true or don't write this because is set to false by default
$auth->minval = integer; // The minimum chars for username. Write this only if you want to change the value because it's set by default 6.
$auth->maxval = integer; // The maximum chars for username. Write this only if you want to change the value because it's set by default 22.
$auth->minpass = integer; // The minimum chars for password. Write this only if you want to change the value because it's set by default 6.
$auth->salt = 'LOTS OF CHARS OF ANY TYPE'; // Change this. This is for security hashing. I strongly recommed to change this in the script or write this with other random chars.

$auth->login($user, $password); // Place this in the part where you get the post vars from your login forms

$auth->logout(); // Place this after $auth = new Auth(..) or if you setup type and emailAuth place it below them. Like in example. If you add it without that then you will never be able to login

$auth->error(); // Place this in your document. This function will display the errors from validation and other like mysql errors.



*/
class Auth {
    
    var $type = 'cookie';
    private $connection;
    private $errors = array();
    var $minval = 6;
    var $maxval = 22;
    var $minpass = 6;
    var $salt = '#@()DIJK#)(F#&*()DS#@JKS)@(I()#@DU)*(&@#)(#U)J';
    var $emailAuth = false;
    
    function __construct($db, $user, $pass, $host) {
        if ( $this->type == 'session' ) {
            session_start();
        }
        $this->mysqlconnect($user, $pass, $host);
        $this->mysqldb($db);
        $this->check();
    }
    
    private function mysqlconnect($user, $pass, $host) {
        $conn = @mysql_connect($host, $user, $pass);
        if ( !$conn ) {
            die('There is a problem with your mysql connection');
        } else {
            $this->connection = $conn;
        }
    }
    
    private function mysqldb($db) {
        if ( !@mysql_select_db($db, $this->connection) ) {
             die('The database doesn't exist');
        }
        
    }
    
    private function query($sql) {
        $result = @mysql_query($sql, $this->connection);
        if ( !$result ) {
            $this->errors[] = 'SQL Error';
        } else {
            return $result;
        }
    }
    
    private function fobj($result) {
        return mysql_fetch_object($result);
    }
    
    private function fnum($result) {
        return mysql_num_rows($result);
    }
    
    private function fescape($value) {
        return mysql_real_escape_string($value);
    }
    
    public function login($user, $pass) {
        $email = $this->emailAuth;
        $err = false;
        $user = strtolower($user);
        $password = $this->encrypt($pass);
        if ( $email == true ) {
            if ( !$this->email($user) ) {
                $this->errors[] = 'Email invalid.';
                $err = true;
            } else {
                $col = 'email';
            }
        } else {
            if ( !$this->name($user) ) {
                $this->errors[] = 'Name invalid. Min chars: '.$this->minval.'. Max chars: '.$this->maxval;
                $err = true;
            } else {
                $col = 'user';
            }
        }
        if ( strlen($pass) < $this->minpass ) {
            $this->errors[] = 'Password min value is 6 chars.';
            $err = true;
        }
        
        if ( $err == false ) {
            
            $sql = sprintf("SELECT * FROM users WHERE %s = '%s'", $col, $this->fescape($user));
            $result = $this->query($sql);
            if ( $this->fnum($result) == 0 ) {
                $this->errors[] = ucfirst($col).' doesn't exist.';
            } else {
                $row = $this->fobj($result);
                if ( $row->password == $password ) {
                    if ( $this->type == 'session' ) {
                        $this->set_session($col, $user);
                        $this->set_session('password', $password);
                    } elseif ( $this->type == 'cookie' ) {
                        $this->set_cookie($col, $user);
                        $this->set_cookie('password', $password);
                    }
                    header('Location: ./auth.php');
                } else {
                    $this->errors[] = 'Incorrect password';
                }
            }
                        
        }
    }
    
    private function encrypt($value) {
        $enc = md5($this->salt.md5($value));
        return sha1($enc);
    }
    
    // Email validation
    private function email($email) {
        $reg = "#^(((([a-zd][.-+_]?)*)[a-z0-9])+)@(((([a-zd][.-_]?){0,62})[a-zd])+).([a-zd]{2,6})$#i";
        if ( !preg_match($reg, $email) ) {
            return false;
        } else {
            return true;
        }
    }
    
    // Name validation
    private function name($name) {
        $min = $this->minval - 2;
        if ( !preg_match("#^[a-z][da-z_]{".$min.",".$this->maxval."}[a-zd]$#i", $name) ) {
            return false;
        } else {
            return true;
        }
    }
    
    private function set_session($name, $value) {
        $_SESSION[$name] = $value;
    }
    
    private function destroy_session() {
        session_unset();
        session_destroy();
    }
    
    private function set_cookie($name, $value, $time = 3600 ) {
        setcookie($name, $value, time()+$time, '/');
    }
    
    private function destroy_cookie($name) {
        setcookie($name, '', time()-1, '/');
    }
    
    public function logout() {
        if ( $this->emailAuth == false ) {
            $col = 'user';
        } else {
            $col = 'email';
        }
        if ( $this->type == 'session' ) {
            $this->destroy_session();
        } elseif ( $this->type == 'cookie' ) {
            $this->destroy_cookie('password');
            $this->destroy_cookie($col);
        }
        header ( 'Location: ./auth.php' );
    }
    
    private function check() {
        if ( $this->emailAuth == false ) {
            $col = 'user';
        } else {
            $col = 'email';
        }
        if ( $this->type == 'cookie' ) {
            if ( isset($_COOKIE['password']) ) {
                $sql = sprintf("SELECT * FROM users WHERE %s = '%s'", $col, $this->fescape($_COOKIE[$col]) );
                $result = $this->query($sql);
                $row = $this->fobj($result);
                if ( $row->{$col} !== $_COOKIE[$col] || $row->password !== $_COOKIE['password'] ) {
                    $this->logout();
                }
            } 
        } elseif ( $this->type == 'session' ) {
            if ( isset($_SESSION['password']) ) {
                $sql = sprintf("SELECT * FROM users WHERE %s = '%s'", $col, $this->fescape($_SESSION[$col]) );
                $result = $this->query($sql);
                $row = $this->fobj($result);
                if ( $row->{$col} !== $_SESSION[$col] || $row->password !== $_SESSION['password'] ) {
                    $this->logout();
                }
            }
        }
    }
    
    public function error() {
        if ( is_array($this->errors) && !empty($this->errors) ) {
            echo '<div style="border:1px solid #CCC; background-color:#FAFAFA; color:#FF0000">';
            foreach ( $this->errors as $value ) {
                echo $value."<br />";
            }
            echo '</div>';
        }
    }
    
    public function isLoggedIn() {
        $ret = false;
        if ( $this->emailAuth == false ) {
            $col = 'user';
        } else {
            $col = 'email';
        }
        if ( $this->type == 'cookie' ) {
            if ( isset($_COOKIE['password']) ) {
                $ret = true;
            }
        } elseif ( $this->type == 'session' ) {
            if ( isset($_SESSION['password']) ) {
                $ret = true;
            }
        }
        return $ret;
    }
    
}
?>





Example:
login.php
<?php
include 'class_auth.php';
$auth = new Auth('database', 'user', 'password', 'host'); // This order: Database User Password Host

if ( isset($_GET['logout']) ) {
    $auth->logout();
}

if ( isset($_POST['login']) ) {
    $auth->login($_POST['user'], $_POST['pass']); // This order: User/Email Password True/False (if you want to use email as auth
}
?>

HERE HTML STUFF

<?php if ( $auth->isLoggedIn() ) : ?>
<h1>Welcome</h1>
<a href="<?=$_SERVER['PHP_SELF'];?>?logout=true">Logout</a>
<?php else : ?>
<h1>Please login</h1>
<form action="<?=$_SERVER['PHP_SELF'];?>?auth" method="post">
    <input type="text" name="user" /> User/Email<br />
  <input type="password" name="pass" /> Password<br />
  <input type="submit" name="login" value="Login" />
</form>
<?php $auth->error(); endif; ?>

source

Use cookie to save session data

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShoppingCartViewerCookie extends HttpServlet {

  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    String sessionid = null;
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
      for (int i = 0; i < cookies.length; i++) {
        if (cookies[i].getName().equals("sessionid")) {
          sessionid = cookies[i].getValue();
          break;
        }
      }
    }

    // If the session ID wasn't sent, generate one.
    // Then be sure to send it to the client with the response.
    if (sessionid == null) {
      sessionid = generateSessionId();
      Cookie c = new Cookie("sessionid", sessionid);
      res.addCookie(c);
    }

    out.println("<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>");
    out.println("<BODY>");

    // Cart items are associated with the session ID
    String[] items = getItemsFromCart(sessionid);

    // Print the current cart items.
    out.println("You currently have the following items in your cart:<BR>");
    if (items == null) {
      out.println("<B>None</B>");
    } else {
      out.println("<UL>");
      for (int i = 0; i < items.length; i++) {
        out.println("<LI>" + items[i]);
      }
      out.println("</UL>");
    }

    // Ask if they want to add more items or check out.
    out.println("<FORM ACTION="/servlet/ShoppingCart" METHOD=POST>");
    out.println("Would you like to<BR>");
    out.println("<INPUT TYPE=SUBMIT VALUE=" Add More Items ">");
    out.println("<INPUT TYPE=SUBMIT VALUE=" Check Out ">");
    out.println("</FORM>");

    // Offer a help page.
    out.println("For help, click <A HREF="/servlet/Help"
        + "?topic=ShoppingCartViewerCookie">here</A>");

    out.println("</BODY></HTML>");
  }

  private static String generateSessionId() throws UnsupportedEncodingException {
    String uid = new java.rmi.server.UID().toString(); // guaranteed unique
    return URLEncoder.encode(uid,"UTF-8"); // encode any special chars
  }

  private static String[] getItemsFromCart(String sessionid) {
    return new String[]{"a","b"};  
  }
}

source

Lista de variables de sesion y aplicación

<%@ Language=VBScript %>
<% Option Explicit %>
<%
   'How many session variables are there?
   Response.Write "There are " & Session.Contents.Count & _
             " Session variables<P>"

   Dim strName, iLoop
   'Use a For Each ... Next to loop through the entire collection
   For Each strName in Session.Contents
     'Is this session variable an array?
     If IsArray(Session(strName)) then
       'If it is an array, loop through each element one at a time
       For iLoop = LBound(Session(strName)) to UBound(Session(strName))
          Response.Write strName & "(" & iLoop & ") - " & _
               Session(strName)(iLoop) & "<BR>"
       Next
     Else
       'We aren't dealing with an array, so just display the variable
       Response.Write strName & " - " & Session.Contents(strName) & "<BR>"
     End If
   Next

%>

source

Asynchronous ASP.Net Pages, AJAX Helper, WebRequest Passthrough

Main Class (AsyncCall.cs), place in App_Code directory or compile as a dll and place in the bin dirctory of the site:
-------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Net;
using System.Threading;
using System.IO;
using System.Collections.Specialized;

namespace AsyncStuff
{
	public static class AsyncCall
	{
		public sealed class AsyncState
		{
			internal const string QVARNAME = "ASYNCSession";

			public readonly Page CallingPage;
			internal readonly Uri Url;
			private HttpWebRequest _request;
			private HttpWebResponse _response;
			internal readonly SpecificFunction SpecificFunction;
			public readonly object[] Parameters;
			private string _text;
			internal byte[] FormContent;

			//cascaded constructor only (private)
			private AsyncState(Page page)
			{
				this.CallingPage = page;
				this.Url = GetAsyncUrl(page.Request.Url);
			}

			//off-page url
			internal AsyncState(Uri url, Page page, SpecificFunction specificFunction)
			{
				this.CallingPage = page;
				this.Url = GetAsyncUrl(url);
				this.SpecificFunction = specificFunction;
			}

			internal AsyncState(Page page, SpecificFunction specificFunction)
				: this(page)
			{
				this.SpecificFunction = specificFunction;
			}

			internal AsyncState(Page page, SpecificFunction specificFunction, params object[] parameters)
				: this(page, specificFunction)
			{
				this.Parameters = parameters;
			}

			private Uri GetAsyncUrl(Uri uri)
			{
				string url = uri.OriginalString;
				int start = url.IndexOf("?");
				if (start < 0)
				{
					start = url.Length;
					url = url.Insert(start++, "?");
				}
				else
				{
					start++;
					url = url.Insert(start, "&");
				}

				//timestamped query variable inserted to indicate that a page is running asychronously
				url = url.Insert(start, QVARNAME + "=" + DateTime.Now.ToString("MMddyyyyHHmmssffff"));
				return new Uri(url);
			}

			public HttpWebRequest Request
			{
				get { return this._request; }
				internal set { this._request = value; }
			}

			public HttpWebResponse Response
			{
				get { return this._response; }
				internal set { this._response = value; }
			}

			public string GetResponseText()
			{
				if (this._text == null)
				{
					this._text = "";
					if (this._response != null)
						this._text = (new StreamReader(this._response.GetResponseStream())).ReadToEnd();
				}
				if (this._text == "")
					return null;

				return this._text;
			}
		}

		/// <summary>
		/// A delegate function used to create a callback for the RunPageAsynchronously() function
		/// </summary>
		/// <param name="state">The state object that will be returned from the results of the asychronous call</param>
		public delegate void SpecificFunction(AsyncState state);

		/// <summary>
		/// Run an off-page url request as an asychronous request. (Note: this is a seperate session, so don't expect session variables to persist)
		/// </summary>
		/// <param name="url">Off-page URL which contents will be retreived asychronously</param>
		/// <param name="callingPage">The current System.Web.UI.Page object which is making the asychronous call (must implement IHttpAsyncHandler or use the [%@ Page Async="true"] directive)</param>
		/// <returns>true, if the page was able to run asynchronously (a value of false may indicate the %@ Page directive is not using Async="true"</returns>
		public static bool RunAsynchronously(string url, Page callingPage)
		{
			if (callingPage is IHttpAsyncHandler)
			{
				Uri absUrl = new Uri(url, UriKind.RelativeOrAbsolute);
				if (!absUrl.IsAbsoluteUri || absUrl.OriginalString.StartsWith("file"))
				{
					string resolve = callingPage.ResolveUrl(url);
					Uri pageUrl = callingPage.Request.Url;
					string newPath = pageUrl.OriginalString.Replace(pageUrl.PathAndQuery, resolve);
					absUrl = new Uri(newPath, UriKind.Absolute);

					string filePath = callingPage.MapPath(absUrl.AbsolutePath);
					FileInfo fi = new FileInfo(filePath);
					if (!fi.Exists)
						throw new Exception("File Not Found, requestsed relative path does not exist. Check the filename for spelling errors.");
				}
				AsyncState state = new AsyncState(absUrl, callingPage, new SpecificFunction(AfterOffPage));
				callingPage.AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginAsyncOperation), new EndEventHandler(EndAsyncOperation), state);
				return true;
			}
			return false;
		}

		private static void AfterOffPage(AsyncState state)
		{
			if (state==null || state.Response == null || state.CallingPage==null || state.CallingPage.Response==null)
				return;

			//content rewrite (make calling page same as the page called)
			//requires IIS content rewrite pipline mode, so if exception then ignore
			try
			{
				state.CallingPage.Response.Headers.Clear();
				state.CallingPage.Response.Headers.Add(state.Response.Headers);
			}
			catch { }
			state.CallingPage.Response.ContentType = state.Response.ContentType;
			BinaryReader br = new BinaryReader(state.Response.GetResponseStream());
			int len = (int)state.Response.ContentLength;
			byte[] data = br.ReadBytes(len);
			state.CallingPage.Response.OutputStream.Write(data, 0, len);			
		
			state.CallingPage.Response.End();
		}

		/// <summary>
		/// Run the current page request as an asychronous request. (Note: this is a seperate session, so don't expect session variables to persist)
		/// </summary>
		/// <param name="callingPage">The current System.Web.UI.Page object to be processed (must implement IHttpAsyncHandler or use the [%@ Page Async="true"] directive)</param>
		/// <param name="specificFunction">A parameterless function to call on the async request page</param>
		/// <returns>true, if the page was able to run asynchronously (a value of false may indicate the %@ Page directive is not using Async="true"</returns>
		public static bool RunAsynchronously(Page callingPage, SpecificFunction specificFunction)
		{
			if ((callingPage is IHttpAsyncHandler) && !IsRunningAsync(callingPage))
			{
				AsyncState state = new AsyncState(callingPage, specificFunction);
				callingPage.AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginAsyncOperation), new EndEventHandler(EndAsyncOperation), state);
				return true;
			}
			return false;
		}

		/// <summary>
		/// Run the current page request as an asychronous request. (Note: this is a seperate session, so don't expect session variables to persist)
		/// </summary>
		/// <param name="callingPage">The current System.Web.UI.Page object to be processed (must implement IHttpAsyncHandler or use the [%@ Page Async="true"] directive)</param>
		/// <param name="specificFunction">A function to call on the async request page</param>
		/// <param name="parameters">The parameters to pass to the specific function</param>
		/// <returns>true, if the page was able to run asynchronously (a value of false may indicate the %@ Page directive is not using Async="true"</returns>
		public static bool RunAsynchronously(Page callingPage, SpecificFunction specificFunction, params object[] parameters)
		{
			if ((callingPage is IHttpAsyncHandler) && !IsRunningAsync(callingPage))
			{
				AsyncState state = new AsyncState(callingPage, specificFunction, parameters);
				callingPage.AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginAsyncOperation), new EndEventHandler(EndAsyncOperation), state);
				return true;
			}
			return false;
		}

		/// <summary>
		/// Tests to see if the page is in is asynchronous cycle of an asynchronous request made from the RunPageAsynchronously function
		/// </summary>
		/// <param name="page">The page to check for sychronicity</param>
		/// <returns>true if in the asychronous cycle</returns>
		public static bool IsRunningAsync(Page page)
		{
			return (page.Request.QueryString[AsyncState.QVARNAME] != null);
		}

		private static IAsyncResult BeginAsyncOperation(object sender, EventArgs e, AsyncCallback cb, object stateObj)
		{
			if (stateObj is AsyncState)
			{
				AsyncState state = (AsyncState)stateObj;
				state.Request = (HttpWebRequest)HttpWebRequest.Create(state.Url);
				
				//copy relevant header information
				state.Request.Accept = GetTextList<string>(state.CallingPage.Request.AcceptTypes, ", ", true);
				state.Request.AllowAutoRedirect = true;
				state.Request.AllowWriteStreamBuffering = true;
				state.Request.ContentType = state.CallingPage.Request.ContentType + "; " + state.CallingPage.Request.ContentEncoding.WebName;
				state.Request.Method = state.CallingPage.Request.RequestType;
				state.Request.Referer = state.CallingPage.Request.UrlReferrer.OriginalString;
				
				//copy cookies
				if (state.CallingPage.Request.Cookies.Count > 0)
				{
					state.Request.CookieContainer = new CookieContainer();
					List<string> excludedCookies = new List<string> { "ASP.NET_SessionId" };
					foreach (string key in state.CallingPage.Request.Cookies.Keys)
					{
						if (!excludedCookies.Contains(key, StringComparer.CurrentCultureIgnoreCase))
						{
							HttpCookie cookie = state.CallingPage.Request.Cookies[key];
							Cookie copy = new Cookie(cookie.Name, cookie.Value, state.Url.AbsolutePath, state.Url.Host);
							state.Request.CookieContainer.Add(copy);
						}
					}
				}
				
				//copy form variables
				if (state.CallingPage.Request.Form.Count > 0 && state.Request.Method.Equals("POST", StringComparison.CurrentCultureIgnoreCase))
				{
					string pairs = GetTextDictionary(state.CallingPage.Request.Form, "=", "&", true);					
					state.FormContent = state.CallingPage.Request.ContentEncoding.GetBytes(pairs);
					state.Request.ContentLength = state.FormContent.Length;
					state.Request.BeginGetRequestStream(EndRequestStreamCallback, state);
				}

				return state.Request.BeginGetResponse(cb, stateObj);
			}
			return null;
		}

		private static void EndRequestStreamCallback(IAsyncResult ar)
		{
			if (ar.AsyncState is AsyncState)
			{
				AsyncState state = (AsyncState)ar.AsyncState;				
				BinaryWriter sw = new BinaryWriter(state.Request.EndGetRequestStream(ar));
				sw.Write(state.FormContent, 0, state.FormContent.Length);
				sw.Close();
			}
		}

		private static void EndAsyncOperation(IAsyncResult ar)
		{
			if (ar.AsyncState is AsyncState)
			{
				AsyncState state = (AsyncState)ar.AsyncState;
				if (state.Request != null)
				{
					try { state.Response = (HttpWebResponse)state.Request.EndGetResponse(ar); }
					catch (Exception ex) { throw new Exception("WebRequest Error. Remember that asynchronous calls are made from the server and not the client, so any routing done on the client (say...to a testing server) will not be in effect with this request.", ex); };

					if (state.SpecificFunction != null)
					{
						object target = state.SpecificFunction.Target;
						if (target == null)
							target = state.CallingPage;
						try { state.SpecificFunction.Method.Invoke(target, new object[] { state }); }
						catch (Exception ex) { throw new Exception("An error occured in the SpecificFunction supplied, the debug thread is not attached to the function invoked, therefore further debug information is unavailable.", ex); }
					}
				}
			}
		}

		private static string GetTextList<I>(IEnumerable<I> list, string separator, bool urlEncode)
		{			
			System.Text.StringBuilder sb = new System.Text.StringBuilder();
			int index = 0;
			foreach (I item in list)
			{
				if (index > 0)
					sb.Append(separator);				
				if (urlEncode)				
					sb.Append(HttpUtility.UrlPathEncode(item.ToString()));
				else
					sb.Append(item.ToString());
				index++;
			}
			string ret = sb.ToString();
			sb.Length = 0; //destroy memory
			return ret;
		}

		private static string GetTextDictionary<K, V>(IDictionary<K, V> dictionary, string equality, string separator, bool urlEncode)
		{
			System.Text.StringBuilder sb = new System.Text.StringBuilder();
			int index = 0;
			foreach (K key in dictionary.Keys)
			{
				V value = dictionary[key];
				if (index > 0)
					sb.Append(separator);
				if (urlEncode)
					sb.Append(HttpUtility.UrlPathEncode(key.ToString()));
				else
					sb.Append(key.ToString());
				sb.Append(equality);
				if (urlEncode)
					sb.Append(HttpUtility.UrlPathEncode(value.ToString()));
				else
					sb.Append(value.ToString());

				index++;
			}
			string ret = sb.ToString();
			sb.Length = 0; //destroy memory
			return ret;
		}

		private static string GetTextDictionary(NameValueCollection dictionary, string equality, string separator, bool urlEncode)
		{
			System.Text.StringBuilder sb = new System.Text.StringBuilder();
			int index = 0;
			foreach (string key in dictionary.Keys)
			{
				string value = dictionary[key];
				if (index > 0)
					sb.Append(separator);
				if (urlEncode)
					sb.Append(HttpUtility.UrlPathEncode(key.ToString()));
				else
					sb.Append(key.ToString());
				sb.Append(equality);
				if (urlEncode)
					sb.Append(HttpUtility.UrlPathEncode(value.ToString()));
				else
					sb.Append(value.ToString());
				index++;
			}
			string ret = sb.ToString();
			sb.Length = 0; //destroy memory
			return ret;
		}



	}
}

Page Example (AsyncPage.aspx):
-------------------------------------------------------------------------------
<%@ Page Async="true" Language="C#" AutoEventWireup="true" CodeFile="AsyncPage.aspx.cs" Inherits="AsyncPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">" >http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"></a>

<html xmlns="<a href="http://www.w3.org/1999/xhtml">" >http://www.w3.org/1999/xhtml"></a>
<head runat="server">
    <title></title>
    <script type="text/javascript">
    	function AJAXCall(url, callBack, postData) {
    		//setup the callback
    		var out = callBack;
    		if (!out) {
    			out = function(text) { return; }
    		}

    		//setup the request
    		var request = null;
    		if (window.XMLHttpRequest)
    			request = new XMLHttpRequest();
    		else if (window.ActiveXObject)
    			request = new ActiveXObject("Microsoft.XMLHTTP");
    		else
    			return false;

    		//true for async..
    		request.open("POST", url, true);

    		//setup the handle of the request when the status changes
    		request.onreadystatechange = function() {
    			if (request && request.readyState == 4) {
    				//if (request.status == 200)
    				out(request.responseText);

    			}
    		}
    		//setup the request headers
    		request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    		//send the request
    		if (postData)
    			request.send(postData);
    		else
    			request.send("");
    	}

    	function callback(data) {
    		alert('got here: ' + data);
    	}

    	function button1() {
    		AJAXCall("AsyncPage.aspx?LongFunction=1", callback, "testing=1");
    	}   	

    	function button2() {
    		AJAXCall("AsyncPage.aspx?ShortFunction=1", callback, "testing=1");
    	}

    	function button3() {
    		AJAXCall("AsyncPage.aspx?UrlFunction=1", callback, "testing=1");
    	}

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
		<asp:Label ID="lbl1" runat="server" />
		<input type="button" id="testbutton1" value="TestLong" onclick="javascript:button1();" style="width:100px;Height:25px;" />
		<input type="button" id="testbutton2" value="TestShort" onclick="javascript:button2();" style="width:100px;Height:25px;" />
		<input type="button" id="testbutton3" value="TestUrl" onclick="javascript:button3();" style="width:100px;Height:25px;" />
    </div>
    </form>
</body>
</html>

Code Behind (AsyncPage.aspx.cs):
-------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Threading;
using AsyncStuff;

public partial class AsyncPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {		
		if (AsyncCall.IsRunningAsync(Page))			
			CalledAsync(); //function is run when a page calls itself asychronously

		//a query variable triggers this page to run a different async function (use AJAX Call to this same url with this query variable)
		//these are single-run checked already, so you don't have to worry about running them more than once
		if (Request.QueryString["LongFunction"] != null)		
			AsyncCall.RunAsynchronously(Page, AfterLong, "Long call");

		if (Request.QueryString["ShortFunction"] != null)
			AsyncCall.RunAsynchronously(Page, AfterShort);

		if (Request.QueryString["UrlFunction"] != null)
			AsyncCall.RunAsynchronously("/AsyncTest.aspx?test=1", Page);
				
		//Normal Page load		
		lbl1.Text = "Just sitting here";
    }

	//this stuff called on the async thread
	protected void CalledAsync()
	{
		//stuff done during async
		
		if (Request.QueryString["LongFunction"]!=null)
		{
			//crunch some numbers to waste some time
			for(int i = 1; i<565535; i++)
			{
				decimal num = (decimal)DateTime.Now.Millisecond * (decimal)(new Random(DateTime.Now.Millisecond)).NextDouble();
				num += num;
			}
			Response.Write("Success");
		}
		else if (Request.QueryString["ShortFunction"] != null)
		{
			Response.Write("Short Call Was Run");
		}

		Response.End(); //do not show regular page contents
	}

	//this stuff called on the page thread after the async call returns
	protected void AfterLong(AsyncCall.AsyncState state)
	{
		//this is an example of using the response stream directly, you can use state.GetResponseText() to accomplish this same thing
		StreamReader sr = new StreamReader(state.Response.GetResponseStream());
		string pageContent = sr.ReadToEnd();
		if (pageContent.Contains("Success"))		
			Response.Write(state.Parameters[0].ToString());
		else		
			Response.Write("Failure");

		Response.End();
	}

	//this stuff called on the page thread after the async call returns
	protected void AfterShort(AsyncCall.AsyncState state)	
	{		
		string text = state.GetResponseText();
		if (text!=null)
			Response.Write(text);
		Response.End();
	}
}

source

Kill locked session

SELECT 'ALTER SYSTEM KILL SESSION ''' || SID || ',' || SERIAL# || ''';' KILL_SQL
, MACHINE
, ORACLE_USERNAME
, OS_USER_NAME
, LOCKED_MODE
, OBJECT_NAME
, OBJECT_TYPE
FROM V$LOCKED_OBJECT A
, DBA_OBJECTS B
, V$SESSION C
WHERE A.OBJECT_ID = B.OBJECT_ID
AND A.SESSION_ID = C.SID

source

Session timeout prevention (keep alive).

private void AddKeepAlive()
{
int int_MilliSecondsTimeOut = 2 * 60 * 1000; /*2 minutes*/ //Math.Max((this.Session.Timeout * 60000) - 30000, 5000);
string path = VirtualPathUtility.ToAbsolute("~/KeepAlive.aspx");

string str_Script = @"<script>(function(){var r=0,w=window;if (w.setInterval)w.setInterval(function() {r++;var img=new Image(1,1);img.src='" + path + @"?count='+r;}," + int_MilliSecondsTimeOut.ToString() + @");})();</script>";
Page.ClientScript.RegisterStartupScript(typeof(Page), UniqueID + "Reconnect", str_Script);
}

//[KeepAlive.aspx:]
<%@ OutputCache Location="None" VaryByParam="None" %>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<%=now %>
</html>

source

PHP Token

<?php

// create the token md5'd and uniqid
$token = md5(uniqid(rand(), TRUE));

// store it in a session
$_SESSION['token'] = $token;

echo $_SESSION['token'];

?>

source

Save session value – then header redirect

<?
session_start();
$_SESSION['forward'] = "This session data will not be lost!";

session_write_close();
header('Location: nextpage.php');
?>

source