Advertisement
Guest User

SessionTransferUtil.cs

a guest
Mar 15th, 2013
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 10.48 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Net;
  6. using System.IO;
  7. using System.Data.OleDb;
  8. using System.Data;
  9. using System.Web.SessionState;
  10. using System.Runtime.Serialization;
  11. using System.Xml.Serialization;
  12. using System.Xml;
  13. using System.Text;
  14. using System.Windows.Forms;
  15.  
  16. // Take asp.net sesssion. Save to db. Force asp to load it. If
  17. // asp returns a new session id, set a cookie with that new session id
  18. /*
  19. '*************************************************************************
  20. 'Version: 1.0000 Change Date: May 11 2010       Author: Lorne Kates
  21. 'Desc: Created to transfer entire session from .net to asp
  22. '*************************************************************************
  23. 'Version: 1.0001 Change Date: June 20, 2010     Author: Lorne Kates
  24. 'Desc: Changed constructor interface to accept HTTP context instead of request, session.
  25.  *      HTTPContext contains request, response and session. (or default ot HttpContext.Current
  26. '*************************************************************************
  27.  *************************************************************************
  28. 'Version: 1.0002 Change Date: July 20, 2010     Author: Lorne Kates
  29. 'Desc: Added check for objects and arrays in session, and skip them. There are no objects or arrays that
  30.  * need to be passed between the two languages, just primitive types. (This was already implemented in asp->.net
  31. '*************************************************************************
  32.  
  33.  * */
  34. public class SessionTransferUtil
  35. {
  36.  
  37.     private string m_response = "";
  38.     private string m_error = "";
  39.     private HttpContext m_context;
  40.     private bool m_debug = false;
  41.  
  42.     public SessionTransferUtil(bool debug) : this()
  43.     {
  44.         this.m_debug = debug;
  45.     }
  46.  
  47.     public void debug(string strMsg)
  48.     {
  49.         if (m_debug)
  50.         {
  51.             HttpContext.Current.Response.Write(strMsg);
  52.         }
  53.     }
  54.  
  55.     public SessionTransferUtil(HttpRequest request, HttpSessionState session) : this(HttpContext.Current)
  56.     {
  57.        
  58.     }
  59.  
  60.  
  61.     public SessionTransferUtil(HttpContext context)
  62.     {
  63.         this.m_context = context;
  64.     }
  65.  
  66.     public SessionTransferUtil()
  67.     {
  68.         this.m_context = HttpContext.Current;
  69.     }
  70.  
  71.  
  72.  
  73.     public bool SaveSessionToAsp()
  74.     {
  75.         HttpWebRequest hwr;
  76.         WebResponse owrWebResponse;
  77.         StreamReader osrStreamRead;
  78.         string strGuid;
  79.         string url;
  80.         bool succuess = false;
  81.         string strApsSessionCookieName;
  82.         string strAspSessionCookieValue;
  83.         HttpCookie aspSessionIdCookie;
  84.  
  85.         debug("Adding Session to db: ");
  86.         strGuid = AddSessionToDatabase();
  87.         debug(" saved as " + strGuid + "<br>");
  88.  
  89.         url = this.Context.Request.Url.GetLeftPart(UriPartial.Authority);
  90.         url += HttpRuntime.AppDomainAppVirtualPath + "/";
  91.  
  92.         //for (int i = 0; i < this.Context.Request.Url.Segments.Length - 1; i++)
  93.         //{
  94.         //    url += this.Context.Request.Url.Segments[i];
  95.         //}
  96.  
  97.  
  98.         debug("Will transfer to " + url + "<br>");
  99.         url += String.Format("SessionTransfer.asp?dir=2asp&guid={0}", strGuid);
  100.         debug("Will transfer to " + url + "<br>");
  101.  
  102.        
  103.  
  104.  
  105.         hwr = (HttpWebRequest)HttpWebRequest.Create(url);
  106.  
  107.         // Send over all the cookies we have. One of them will be the ASP
  108.         // session ID, which the client will have set and will need to
  109.         // regenerate their sess
  110.         hwr.Headers.Add("Cookie", this.Context.Request.Headers["Cookie"]);
  111.  
  112.         debug("Cookies: " + this.Context.Request.Headers["Cookie"] + "<br>");
  113.  
  114.         try
  115.         {
  116.             owrWebResponse = hwr.GetResponse();
  117.             if ((owrWebResponse.ContentLength > 0))
  118.             {
  119.                 osrStreamRead = new System.IO.StreamReader(hwr.GetResponse().GetResponseStream());
  120.                 this.Response = osrStreamRead.ReadToEnd();
  121.  
  122.                 if (osrStreamRead != null)
  123.                 {
  124.                     osrStreamRead.Close();
  125.                 }
  126.  
  127.                 succuess = true;
  128.  
  129.                 foreach (string key in owrWebResponse.Headers.Keys)
  130.                 {
  131.                    
  132.                     string[] values = owrWebResponse.Headers.GetValues(key);
  133.                     for (int i = 0; i < values.Length; i++)
  134.                     {
  135.                        
  136.                         if (key == "Set-Cookie")
  137.                         {
  138.                             debug("Raw cookies: " + key + "<br>");
  139.  
  140.                             string[] splits = values[i].Split('=');
  141.                             string[] splits2 = splits[1].Split(';');
  142.  
  143.                             strApsSessionCookieName = splits[0];
  144.                             strAspSessionCookieValue = splits2[0];
  145.  
  146.  
  147.                             aspSessionIdCookie = new HttpCookie(strApsSessionCookieName, strAspSessionCookieValue);
  148.                             aspSessionIdCookie.Path = "/";
  149.                             SessionManager.Context.Response.Cookies.Add(aspSessionIdCookie);
  150.  
  151.                             debug("Cookie received is: " + aspSessionIdCookie + "<br>");
  152.  
  153.                         }
  154.                     }
  155.                 }
  156.  
  157.             }
  158.             // Do it again to be sure?
  159.             ClearSessionFromDatabase(strGuid);
  160.  
  161.         }
  162.         catch (WebException we)
  163.         {
  164.             this.Error =
  165.                 String.Format("An error occured while fetching {0}: <p>{1}",
  166.                 url,
  167.                 we.Message);
  168.  
  169.             debug("Error in hwr: " + this.Error + "<br>");
  170.  
  171.         }
  172.  
  173.  
  174.  
  175.  
  176.         return succuess;
  177.     }
  178.  
  179.  
  180.     //This method adds the session information to the database and returns the GUID
  181.     //  used to identify the data.
  182.     private string AddSessionToDatabase()
  183.     {
  184.         /*
  185.           SqlDataAdapter myDataAdapter = new SqlDataAdapter(
  186.                  "SELECT au_lname, au_fname FROM Authors WHERE au_id = @au_id",
  187.                  connection);                
  188.           myCommand.SelectCommand.Parameters.Add("@au_id", SqlDbType.VarChar, 11);
  189.           myCommand.SelectCommand.Parameters["@au_id"].Value = SSN.Text;
  190.  
  191.          */
  192.         int i = 0;
  193.         string strSql, guidTemp = GetGuid();
  194.         string key;
  195.         object oval;
  196.         string val;
  197.         string strType;
  198.         List<OleDbParameter> olParams = new List<OleDbParameter>();
  199.         OleDbParameter p;
  200.         bool blnDoSave;
  201.         Type tObjectType;
  202.         XmlSerializer oxs;
  203.         MemoryStream om;
  204.         XmlTextWriter ow;
  205.         string xmlstring = null;
  206.         bool blnAttemptSerialize = false; // Turn to true if we ever need to
  207.         // get sync with objects working
  208.  
  209.         strSql = "INSERT INTO ASPSessionState (GUID, SessionKey, SessionValue, VarType, Saved_Time) VALUES (?,?,?,?, GetDate());";
  210.  
  211.  
  212.         // The only session variables we don't save are object types
  213.         // such as objects and collections.
  214.         while (i < this.Context.Session.Contents.Count)
  215.         {
  216.             key = this.Context.Session.Contents.Keys[i];
  217.             oval = this.Context.Session.Contents[i];
  218.             val = "";
  219.  
  220.             if (oval == null)
  221.             {
  222.                 oval = String.Empty;
  223.             }
  224.  
  225.  
  226.             strType = oval.GetType().ToString();
  227.  
  228.             tObjectType = oval.GetType();
  229.             blnDoSave = true;
  230.  
  231.  
  232.  
  233.  
  234.             if (tObjectType.IsPrimitive || tObjectType.Equals(typeof(string)) || tObjectType.Equals(typeof(String)))
  235.             {
  236.                 val = oval.ToString();
  237.             }
  238.             else if (tObjectType.IsSerializable && blnAttemptSerialize)
  239.             {
  240.  
  241.                 try
  242.                 {
  243.                     oxs = new XmlSerializer(tObjectType);
  244.                     om = new MemoryStream();
  245.                     ow = new XmlTextWriter(om, Encoding.UTF8);
  246.                     xmlstring = null;
  247.                     oxs.Serialize(ow, oval);
  248.                     om = (MemoryStream)ow.BaseStream;
  249.  
  250.                     xmlstring = UTF8ByteArrayToString(om.ToArray());
  251.                     val = xmlstring;
  252.                 }
  253.                 catch (Exception ex)
  254.                 {
  255.                     val = oval.ToString();
  256.                 }
  257.             }
  258.             else
  259.             {
  260.                 if (blnAttemptSerialize)
  261.                 {
  262.                     try
  263.                     {
  264.  
  265.                     }
  266.                     catch
  267.                     {
  268.                         blnDoSave = false;
  269.                     }
  270.                 }
  271.                 else
  272.                 {
  273.                     blnDoSave = false;
  274.                 }
  275.             }
  276.  
  277.             if (blnDoSave)
  278.             {
  279.                 olParams.Clear();
  280.  
  281.                 p = new OleDbParameter("@Guid", OleDbType.Char, 38);
  282.                 p.Value = guidTemp;
  283.                 olParams.Add(p);
  284.  
  285.                 p = new OleDbParameter("@Key", OleDbType.VarChar, 254);
  286.                 p.Value = key;
  287.                 olParams.Add(p);
  288.  
  289.                 p = new OleDbParameter("@Val", OleDbType.VarWChar, 1073741823);
  290.                 p.Value = val;
  291.                 olParams.Add(p);
  292.  
  293.                 p = new OleDbParameter("@Type", OleDbType.VarChar, 254);
  294.                 p.Value = strType;
  295.                 olParams.Add(p);
  296.  
  297.                 DBUtility.ExecuteNonQuery(strSql, olParams);
  298.             }
  299.            
  300.             i++;
  301.         }
  302.  
  303.  
  304.         return guidTemp;
  305.     }
  306.  
  307.  
  308.     //This method retrieves the session information identified by the parameter
  309.     //  guidIn from the database.
  310.     public void GetSessionFromDatabase(string guidIn)
  311.     {
  312.         DataSet ds;
  313.         string strSql;
  314.         string guidTemp = GetGuid();
  315.         List<OleDbParameter> olParams = new List<OleDbParameter>();
  316.  
  317.         olParams.Add(new OleDbParameter("GUID", OleDbType.VarChar, 38));
  318.         olParams[olParams.Count - 1].Value = guidIn;
  319.  
  320.         //Get a DataReader that contains all the Session information
  321.         strSql = "SELECT * FROM ASPSessionState WHERE GUID = ?";
  322.  
  323.         ds = DBUtility.Fill(strSql, olParams);
  324.  
  325.  
  326.         //Iterate through the results and store them in the session object
  327.         foreach (DataRow dr in ds.Tables[0].Rows)
  328.         {
  329.             this.Context.Session[dr["SessionKey"].ToString()] = dr["SessionValue"].ToString();
  330.         }
  331.     }
  332.  
  333.  
  334.     //This method removes all session information from the database identified by the
  335.     //  the GUID passed in through the parameter guidIn.
  336.     public void ClearSessionFromDatabase(string guidIn)
  337.     {
  338.         string strSql;
  339.         List<OleDbParameter> olParams = new List<OleDbParameter>();
  340.  
  341.         olParams.Add(new OleDbParameter("GUID", OleDbType.VarChar, 38));
  342.         olParams[olParams.Count - 1].Value = guidIn;
  343.  
  344.         //olParmas.Add(new OleDbParameter("Date", OleDbType.Date));
  345.         //olParmas[olParmas.Count - 1].Value = DateTime.Now;
  346.  
  347.         // Delete this session, and any session older than a day (housekeeping)
  348.         strSql = "DELETE FROM ASPSessionState WHERE GUID = ? OR datediff(day, isnull(saved_time, getdate() - 1), getdate()) >= 1";
  349.  
  350.         DBUtility.ExecuteNonQuery(strSql, olParams);
  351.     }
  352.  
  353.  
  354.     //This method returns a new GUID as a string.
  355.     private string GetGuid()
  356.     {
  357.         return System.Guid.NewGuid().ToString();
  358.     }
  359.  
  360.  
  361.  
  362.     /// <summary>
  363.  
  364.     /// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
  365.  
  366.     /// </summary>
  367.  
  368.     /// <param name="characters">Unicode Byte Array to be converted to String</param>
  369.  
  370.     /// <returns>String converted from Unicode Byte Array</returns>
  371.  
  372.     private String UTF8ByteArrayToString(Byte[] characters)
  373.     {
  374.  
  375.         UTF8Encoding encoding = new UTF8Encoding();
  376.  
  377.         String constructedString = encoding.GetString(characters);
  378.  
  379.         return (constructedString);
  380.  
  381.     }
  382.  
  383.  
  384.  
  385.     /// <summary>
  386.  
  387.     /// Converts the String to UTF8 Byte array and is used in De serialization
  388.  
  389.     /// </summary>
  390.  
  391.     /// <param name="pXmlString"></param>
  392.  
  393.     /// <returns></returns>
  394.  
  395.     private Byte[] StringToUTF8ByteArray(String pXmlString)
  396.     {
  397.  
  398.         UTF8Encoding encoding = new UTF8Encoding();
  399.  
  400.         Byte[] byteArray = encoding.GetBytes(pXmlString);
  401.  
  402.         return byteArray;
  403.  
  404.     }
  405.  
  406.  
  407.     #region Public Accessors
  408.     public string Response
  409.     {
  410.         get { return m_response; }
  411.         set { m_response = value; }
  412.     }
  413.     public string Error
  414.     {
  415.         get { return m_error; }
  416.         set { m_error = value; }
  417.     }
  418.  
  419.  
  420.     public HttpContext Context
  421.     {
  422.         get
  423.         {
  424.             return this.m_context;
  425.         }
  426.         set
  427.         {
  428.             this.m_context = value;
  429.         }
  430.     }
  431.     #endregion
  432. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement