Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Net;
- using System.IO;
- using System.Data.OleDb;
- using System.Data;
- using System.Web.SessionState;
- using System.Runtime.Serialization;
- using System.Xml.Serialization;
- using System.Xml;
- using System.Text;
- using System.Windows.Forms;
- // Take asp.net sesssion. Save to db. Force asp to load it. If
- // asp returns a new session id, set a cookie with that new session id
- /*
- '*************************************************************************
- 'Version: 1.0000 Change Date: May 11 2010 Author: Lorne Kates
- 'Desc: Created to transfer entire session from .net to asp
- '*************************************************************************
- 'Version: 1.0001 Change Date: June 20, 2010 Author: Lorne Kates
- 'Desc: Changed constructor interface to accept HTTP context instead of request, session.
- * HTTPContext contains request, response and session. (or default ot HttpContext.Current
- '*************************************************************************
- *************************************************************************
- 'Version: 1.0002 Change Date: July 20, 2010 Author: Lorne Kates
- 'Desc: Added check for objects and arrays in session, and skip them. There are no objects or arrays that
- * need to be passed between the two languages, just primitive types. (This was already implemented in asp->.net
- '*************************************************************************
- * */
- public class SessionTransferUtil
- {
- private string m_response = "";
- private string m_error = "";
- private HttpContext m_context;
- private bool m_debug = false;
- public SessionTransferUtil(bool debug) : this()
- {
- this.m_debug = debug;
- }
- public void debug(string strMsg)
- {
- if (m_debug)
- {
- HttpContext.Current.Response.Write(strMsg);
- }
- }
- public SessionTransferUtil(HttpRequest request, HttpSessionState session) : this(HttpContext.Current)
- {
- }
- public SessionTransferUtil(HttpContext context)
- {
- this.m_context = context;
- }
- public SessionTransferUtil()
- {
- this.m_context = HttpContext.Current;
- }
- public bool SaveSessionToAsp()
- {
- HttpWebRequest hwr;
- WebResponse owrWebResponse;
- StreamReader osrStreamRead;
- string strGuid;
- string url;
- bool succuess = false;
- string strApsSessionCookieName;
- string strAspSessionCookieValue;
- HttpCookie aspSessionIdCookie;
- debug("Adding Session to db: ");
- strGuid = AddSessionToDatabase();
- debug(" saved as " + strGuid + "<br>");
- url = this.Context.Request.Url.GetLeftPart(UriPartial.Authority);
- url += HttpRuntime.AppDomainAppVirtualPath + "/";
- //for (int i = 0; i < this.Context.Request.Url.Segments.Length - 1; i++)
- //{
- // url += this.Context.Request.Url.Segments[i];
- //}
- debug("Will transfer to " + url + "<br>");
- url += String.Format("SessionTransfer.asp?dir=2asp&guid={0}", strGuid);
- debug("Will transfer to " + url + "<br>");
- hwr = (HttpWebRequest)HttpWebRequest.Create(url);
- // Send over all the cookies we have. One of them will be the ASP
- // session ID, which the client will have set and will need to
- // regenerate their sess
- hwr.Headers.Add("Cookie", this.Context.Request.Headers["Cookie"]);
- debug("Cookies: " + this.Context.Request.Headers["Cookie"] + "<br>");
- try
- {
- owrWebResponse = hwr.GetResponse();
- if ((owrWebResponse.ContentLength > 0))
- {
- osrStreamRead = new System.IO.StreamReader(hwr.GetResponse().GetResponseStream());
- this.Response = osrStreamRead.ReadToEnd();
- if (osrStreamRead != null)
- {
- osrStreamRead.Close();
- }
- succuess = true;
- foreach (string key in owrWebResponse.Headers.Keys)
- {
- string[] values = owrWebResponse.Headers.GetValues(key);
- for (int i = 0; i < values.Length; i++)
- {
- if (key == "Set-Cookie")
- {
- debug("Raw cookies: " + key + "<br>");
- string[] splits = values[i].Split('=');
- string[] splits2 = splits[1].Split(';');
- strApsSessionCookieName = splits[0];
- strAspSessionCookieValue = splits2[0];
- aspSessionIdCookie = new HttpCookie(strApsSessionCookieName, strAspSessionCookieValue);
- aspSessionIdCookie.Path = "/";
- SessionManager.Context.Response.Cookies.Add(aspSessionIdCookie);
- debug("Cookie received is: " + aspSessionIdCookie + "<br>");
- }
- }
- }
- }
- // Do it again to be sure?
- ClearSessionFromDatabase(strGuid);
- }
- catch (WebException we)
- {
- this.Error =
- String.Format("An error occured while fetching {0}: <p>{1}",
- url,
- we.Message);
- debug("Error in hwr: " + this.Error + "<br>");
- }
- return succuess;
- }
- //This method adds the session information to the database and returns the GUID
- // used to identify the data.
- private string AddSessionToDatabase()
- {
- /*
- SqlDataAdapter myDataAdapter = new SqlDataAdapter(
- "SELECT au_lname, au_fname FROM Authors WHERE au_id = @au_id",
- connection);
- myCommand.SelectCommand.Parameters.Add("@au_id", SqlDbType.VarChar, 11);
- myCommand.SelectCommand.Parameters["@au_id"].Value = SSN.Text;
- */
- int i = 0;
- string strSql, guidTemp = GetGuid();
- string key;
- object oval;
- string val;
- string strType;
- List<OleDbParameter> olParams = new List<OleDbParameter>();
- OleDbParameter p;
- bool blnDoSave;
- Type tObjectType;
- XmlSerializer oxs;
- MemoryStream om;
- XmlTextWriter ow;
- string xmlstring = null;
- bool blnAttemptSerialize = false; // Turn to true if we ever need to
- // get sync with objects working
- strSql = "INSERT INTO ASPSessionState (GUID, SessionKey, SessionValue, VarType, Saved_Time) VALUES (?,?,?,?, GetDate());";
- // The only session variables we don't save are object types
- // such as objects and collections.
- while (i < this.Context.Session.Contents.Count)
- {
- key = this.Context.Session.Contents.Keys[i];
- oval = this.Context.Session.Contents[i];
- val = "";
- if (oval == null)
- {
- oval = String.Empty;
- }
- strType = oval.GetType().ToString();
- tObjectType = oval.GetType();
- blnDoSave = true;
- if (tObjectType.IsPrimitive || tObjectType.Equals(typeof(string)) || tObjectType.Equals(typeof(String)))
- {
- val = oval.ToString();
- }
- else if (tObjectType.IsSerializable && blnAttemptSerialize)
- {
- try
- {
- oxs = new XmlSerializer(tObjectType);
- om = new MemoryStream();
- ow = new XmlTextWriter(om, Encoding.UTF8);
- xmlstring = null;
- oxs.Serialize(ow, oval);
- om = (MemoryStream)ow.BaseStream;
- xmlstring = UTF8ByteArrayToString(om.ToArray());
- val = xmlstring;
- }
- catch (Exception ex)
- {
- val = oval.ToString();
- }
- }
- else
- {
- if (blnAttemptSerialize)
- {
- try
- {
- }
- catch
- {
- blnDoSave = false;
- }
- }
- else
- {
- blnDoSave = false;
- }
- }
- if (blnDoSave)
- {
- olParams.Clear();
- p = new OleDbParameter("@Guid", OleDbType.Char, 38);
- p.Value = guidTemp;
- olParams.Add(p);
- p = new OleDbParameter("@Key", OleDbType.VarChar, 254);
- p.Value = key;
- olParams.Add(p);
- p = new OleDbParameter("@Val", OleDbType.VarWChar, 1073741823);
- p.Value = val;
- olParams.Add(p);
- p = new OleDbParameter("@Type", OleDbType.VarChar, 254);
- p.Value = strType;
- olParams.Add(p);
- DBUtility.ExecuteNonQuery(strSql, olParams);
- }
- i++;
- }
- return guidTemp;
- }
- //This method retrieves the session information identified by the parameter
- // guidIn from the database.
- public void GetSessionFromDatabase(string guidIn)
- {
- DataSet ds;
- string strSql;
- string guidTemp = GetGuid();
- List<OleDbParameter> olParams = new List<OleDbParameter>();
- olParams.Add(new OleDbParameter("GUID", OleDbType.VarChar, 38));
- olParams[olParams.Count - 1].Value = guidIn;
- //Get a DataReader that contains all the Session information
- strSql = "SELECT * FROM ASPSessionState WHERE GUID = ?";
- ds = DBUtility.Fill(strSql, olParams);
- //Iterate through the results and store them in the session object
- foreach (DataRow dr in ds.Tables[0].Rows)
- {
- this.Context.Session[dr["SessionKey"].ToString()] = dr["SessionValue"].ToString();
- }
- }
- //This method removes all session information from the database identified by the
- // the GUID passed in through the parameter guidIn.
- public void ClearSessionFromDatabase(string guidIn)
- {
- string strSql;
- List<OleDbParameter> olParams = new List<OleDbParameter>();
- olParams.Add(new OleDbParameter("GUID", OleDbType.VarChar, 38));
- olParams[olParams.Count - 1].Value = guidIn;
- //olParmas.Add(new OleDbParameter("Date", OleDbType.Date));
- //olParmas[olParmas.Count - 1].Value = DateTime.Now;
- // Delete this session, and any session older than a day (housekeeping)
- strSql = "DELETE FROM ASPSessionState WHERE GUID = ? OR datediff(day, isnull(saved_time, getdate() - 1), getdate()) >= 1";
- DBUtility.ExecuteNonQuery(strSql, olParams);
- }
- //This method returns a new GUID as a string.
- private string GetGuid()
- {
- return System.Guid.NewGuid().ToString();
- }
- /// <summary>
- /// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
- /// </summary>
- /// <param name="characters">Unicode Byte Array to be converted to String</param>
- /// <returns>String converted from Unicode Byte Array</returns>
- private String UTF8ByteArrayToString(Byte[] characters)
- {
- UTF8Encoding encoding = new UTF8Encoding();
- String constructedString = encoding.GetString(characters);
- return (constructedString);
- }
- /// <summary>
- /// Converts the String to UTF8 Byte array and is used in De serialization
- /// </summary>
- /// <param name="pXmlString"></param>
- /// <returns></returns>
- private Byte[] StringToUTF8ByteArray(String pXmlString)
- {
- UTF8Encoding encoding = new UTF8Encoding();
- Byte[] byteArray = encoding.GetBytes(pXmlString);
- return byteArray;
- }
- #region Public Accessors
- public string Response
- {
- get { return m_response; }
- set { m_response = value; }
- }
- public string Error
- {
- get { return m_error; }
- set { m_error = value; }
- }
- public HttpContext Context
- {
- get
- {
- return this.m_context;
- }
- set
- {
- this.m_context = value;
- }
- }
- #endregion
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement