SqlViewState - C# Code

using System;

using System.Configuration;

using System.Data;

using System.Data.SqlClient;

using System.Globalization;

using System.IO;

using System.Web;

using System.Web.UI;

using System.Web.UI.HtmlControls;

 

public class SqlViewStatePage : Page

{

       private const int DefaultViewStateTimeout = 20;

 

       private string _viewStateConnectionString;

       private TimeSpan _viewStateTimeout;

 

       public SqlViewStatePage() : base()

       {

              if (this.IsDesignMode)

                     return;

 

              this._viewStateConnectionString = ConfigurationSettings.AppSettings["ViewStateConnectionString"];

 

              try

              {

                     this._viewStateTimeout = TimeSpan.FromMinutes(Convert.ToDouble(ConfigurationSettings.AppSettings["ViewStateTimeout"]));

              }

              catch

              {

                     this._viewStateTimeout = TimeSpan.FromMinutes(SqlViewStatePage.DefaultViewStateTimeout);

              }

       }

 

       protected bool IsDesignMode

       {

              get { return (this.Context == null); }

       }

 

       protected bool IsSqlViewStateEnabled

       {

              get { return (this._viewStateConnectionString != null && this._viewStateConnectionString.Length > 0); }

       }

 

       public TimeSpan ViewStateTimeout

       {

              get { return this._viewStateTimeout; }

              set { this._viewStateTimeout = value; }

       }

 

       private string GetMacKeyModifier()

       {

              int value = this.TemplateSourceDirectory.GetHashCode() + this.GetType().Name.GetHashCode();

 

              if (this.ViewStateUserKey != null)

                     return string.Concat(value.ToString(NumberFormatInfo.InvariantInfo), this.ViewStateUserKey);

 

              return value.ToString(NumberFormatInfo.InvariantInfo);

       }

 

       private LosFormatter GetLosFormatter()

       {

              if (this.EnableViewStateMac)

                     return new LosFormatter(true, this.GetMacKeyModifier());

 

              return new LosFormatter();

       }

 

       private Guid GetViewStateGuid()

       {

              string viewStateKey;

             

              viewStateKey = this.Request.Form["__VIEWSTATEGUID"];

 

              if (viewStateKey == null || viewStateKey.Length < 1)

              {

                     viewStateKey = this.Request.QueryString["__VIEWSTATEGUID"];

 

                     if (viewStateKey == null || viewStateKey.Length < 1)

                            return Guid.NewGuid();

              }

 

              try

              {

                     return new Guid(viewStateKey);

              }

              catch (FormatException)

              {

                     return Guid.NewGuid();

              }

       }

 

       protected override object LoadPageStateFromPersistenceMedium()

       {

              Guid viewStateGuid;

              byte[] rawData;

             

              if (this.IsDesignMode)

                     return null;

 

              if (!this.IsSqlViewStateEnabled)

                     return base.LoadPageStateFromPersistenceMedium();

 

              viewStateGuid = this.GetViewStateGuid();

              rawData = null;

             

              using (SqlConnection connection = new SqlConnection(this._viewStateConnectionString))

              using (SqlCommand command = new SqlCommand("GetViewState", connection))

              {

                     command.CommandType = CommandType.StoredProcedure;

                     command.Parameters.Add("@returnValue", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;

                     command.Parameters.Add("@viewStateId", SqlDbType.UniqueIdentifier).Value = viewStateGuid;

 

                     connection.Open();

 

                     using(SqlDataReader reader = command.ExecuteReader())

                     {

                           if (reader.Read())

                                  rawData = (byte[])Array.CreateInstance(typeof(byte), reader.GetInt32(0));

 

                           if (reader.NextResult() && reader.Read())

                                  reader.GetBytes(0, 0, rawData, 0, rawData.Length);

                     }

              }

 

              using (MemoryStream stream = new MemoryStream(rawData))

                     return this.GetLosFormatter().Deserialize(stream);

       }

 

       protected override void SavePageStateToPersistenceMedium(object viewState)

       {

              Guid viewStateGuid;

              HtmlInputHidden control;

 

              if (this.IsDesignMode)

                     return;

 

              if (!this.IsSqlViewStateEnabled)

              {

                     base.SavePageStateToPersistenceMedium(viewState);

                     return;

              }

 

              viewStateGuid = this.GetViewStateGuid();

 

              using (MemoryStream stream = new MemoryStream())

              {

                     this.GetLosFormatter().Serialize(stream, viewState);

 

                     using (SqlConnection connection = new SqlConnection(this._viewStateConnectionString))

                     using (SqlCommand command = new SqlCommand("SetViewState", connection))

                     {

                           command.CommandType = CommandType.StoredProcedure;

                           command.Parameters.Add("@returnValue", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;

                           command.Parameters.Add("@viewStateId", SqlDbType.UniqueIdentifier).Value = viewStateGuid;

                           command.Parameters.Add("@value", SqlDbType.Image).Value = stream.ToArray();

                           command.Parameters.Add("@timeout", SqlDbType.Int).Value = this._viewStateTimeout.TotalMinutes;

 

                           connection.Open();

                           command.ExecuteNonQuery();

                     }

              }

 

              control = this.FindControl("__VIEWSTATEGUID") as HtmlInputHidden;

 

              if (control == null)

                     this.RegisterHiddenField("__VIEWSTATEGUID", viewStateGuid.ToString());

              else

                     control.Value = viewStateGuid.ToString();

       }

}

No Comments