Example #1
0
        /// <include file='doc\TraceHandler.uex' path='docs/doc[@for="TraceHandler.IHttpHandler.ProcessRequest"]/*' />
        /// <internalonly/>
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            if (!context.Request.IsLocal && HttpRuntime.Profile.LocalOnly)
            {
                HttpException e = new HttpException(403, null);
                e.SetFormatter(new TraceHandlerErrorFormatter(true));
                throw e;
            }

            _context  = context;
            _response = _context.Response;
            _request  = _context.Request;
            _writer   = Page.CreateHtmlTextWriterInternal(_response.Output, _request);

            _context.Trace.IsEnabled = false;

            _writer.Write("<html>\r\n");
            _writer.Write("<head>\r\n");
            _writer.Write(StyleSheet);
            _writer.Write("</head>\r\n");

            _writer.Write("<body>\r\n");
            _writer.Write("<span class=\"tracecontent\">\r\n");

            if (!HttpRuntime.Profile.IsConfigEnabled)
            {
                HttpException e = new HttpException();
                e.SetFormatter(new TraceHandlerErrorFormatter(false));
                throw e;
            }

            ArrayList datasets = HttpRuntime.Profile.GetData();

            // first check if we should clear data
            if (_request.QueryString["clear"] != null)
            {
                HttpRuntime.Profile.Reset();
                string url = _request.RawUrl;
                _response.Redirect(url.Substring(0, url.IndexOf("?")));
            }

            // then check if we are drilling down
            string strid = _request.QueryString["id"];

            if (strid != null)
            {
                int index = Int32.Parse(strid, CultureInfo.InvariantCulture);
                if (index >= 0 && index < datasets.Count)
                {
                    ShowDetails((DataSet)datasets[index]);
                    _writer.Write("</span>\r\n</body>\r\n</html>\r\n");
                    return;
                }
            }

            // if we get here, its just generic request
            ShowRequests(datasets);
            _writer.Write("</span>\r\n</body>\r\n</html>\r\n");
        }
 void IHttpHandler.ProcessRequest(HttpContext context)
 {
     if (DeploymentSection.RetailInternal || (!context.Request.IsLocal && HttpRuntime.Profile.LocalOnly))
     {
         HttpException exception = new HttpException(0x193, null);
         exception.SetFormatter(new TraceHandlerErrorFormatter(!DeploymentSection.RetailInternal));
         throw exception;
     }
     this._context  = context;
     this._response = this._context.Response;
     this._request  = this._context.Request;
     this._writer   = Page.CreateHtmlTextWriterInternal(this._response.Output, this._request);
     if (context.WorkerRequest is IIS7WorkerRequest)
     {
         this._response.ContentType = this._request.Browser.PreferredRenderingMime;
     }
     if (this._writer != null)
     {
         this._context.Trace.IsEnabled = false;
         this._request.ValidateInput();
         this._writer.Write("<html>\r\n");
         this._writer.Write("<head>\r\n");
         this._writer.Write(StyleSheet);
         this._writer.Write("</head>\r\n");
         this._writer.Write("<body>\r\n");
         this._writer.Write("<span class=\"tracecontent\">\r\n");
         if (!HttpRuntime.Profile.IsConfigEnabled)
         {
             HttpException exception2 = new HttpException();
             exception2.SetFormatter(new TraceHandlerErrorFormatter(false));
             throw exception2;
         }
         IList data = HttpRuntime.Profile.GetData();
         if (this._request.QueryString["clear"] != null)
         {
             HttpRuntime.Profile.Reset();
             string rawUrl = this._request.RawUrl;
             this._response.Redirect(rawUrl.Substring(0, rawUrl.IndexOf("?", StringComparison.Ordinal)));
         }
         string s = this._request.QueryString["id"];
         if (s != null)
         {
             int num = int.Parse(s, CultureInfo.InvariantCulture);
             if ((num >= 0) && (num < data.Count))
             {
                 this.ShowDetails((DataSet)data[num]);
                 this.ShowVersionDetails();
                 this._writer.Write("</span>\r\n</body>\r\n</html>\r\n");
                 return;
             }
         }
         this.ShowRequests(data);
         this.ShowVersionDetails();
         this._writer.Write("</span>\r\n</body>\r\n</html>\r\n");
     }
 }
        public override void Load() {
            NameValueCollection requestValueCollection = Page.RequestValueCollection;
            if (requestValueCollection == null) {
                return;
            }

            try {
                string combinedSerializedStateString = Page.RequestViewStateString;
                string persistedStateID = null;
                bool controlStateInSession = false;

                // SessionState will persist a Pair of <bool requiresControlStateInSession, string/pair>,
                // where if requiresControlStateInSession is true, second will just be the sessionID, as
                // we will store both control state and view state in session.  Otherwise, we store just the
                // view state in session and the pair will be <id, ControlState>
                if (!String.IsNullOrEmpty(combinedSerializedStateString)) {
                    Pair combinedState = (Pair)Util.DeserializeWithAssert(StateFormatter2, combinedSerializedStateString, Purpose.WebForms_SessionPageStatePersister_ClientState);
                    // Check if we are storing control state in session as well
                    if ((bool)combinedState.First) {
                        // So the second is the persistedID
                        persistedStateID = (string)combinedState.Second;
                        controlStateInSession = true;
                    }
                    else {
                        // Second is <sessionID, ControlState>
                        Pair pair = (Pair)combinedState.Second;
                        persistedStateID = (string)pair.First;
                        ControlState = pair.Second;
                    }
                }

                if (persistedStateID != null) {
                    object sessionData = Page.Session[_viewStateSessionKey + persistedStateID];
                    if (controlStateInSession) {
                        Pair combinedState = sessionData as Pair;
                        if (combinedState != null) {
                            ViewState = combinedState.First;
                            ControlState = combinedState.Second;
                        }
                    }
                    else {
                        ViewState = sessionData;
                    }
                }
            }
            catch (Exception e) {
                // Setup the formatter for this exception, to make sure this message shows up
                // in an error page as opposed to the inner-most exception's message.
                HttpException newException = new HttpException(SR.GetString(SR.Invalid_ControlState), e);
                newException.SetFormatter(new UseLastUnhandledErrorFormatter(newException));

                throw newException;
            }
        }
        private static void ThrowError(Exception inner, string persistedState, string errorPageMessage, bool macValidationError)
        {
            ViewStateException innerException = new ViewStateException(inner, persistedState)
            {
                _macValidationError = macValidationError
            };
            HttpException e = new HttpException(GetCorrectErrorPageMessage(innerException, errorPageMessage), innerException);

            e.SetFormatter(new UseLastUnhandledErrorFormatter(e));
            throw e;
        }
Example #5
0
 public override void Load()
 {
     if (base.Page.RequestValueCollection != null)
     {
         try
         {
             string requestViewStateString = base.Page.RequestViewStateString;
             string second = null;
             bool   flag   = false;
             if (!string.IsNullOrEmpty(requestViewStateString))
             {
                 Pair pair = (Pair)Util.DeserializeWithAssert(base.StateFormatter, requestViewStateString);
                 if ((bool)pair.First)
                 {
                     second = (string)pair.Second;
                     flag   = true;
                 }
                 else
                 {
                     Pair pair2 = (Pair)pair.Second;
                     second            = (string)pair2.First;
                     base.ControlState = pair2.Second;
                 }
             }
             if (second != null)
             {
                 object obj2 = base.Page.Session["__SESSIONVIEWSTATE" + second];
                 if (flag)
                 {
                     Pair pair3 = obj2 as Pair;
                     if (pair3 != null)
                     {
                         base.ViewState    = pair3.First;
                         base.ControlState = pair3.Second;
                     }
                 }
                 else
                 {
                     base.ViewState = obj2;
                 }
             }
         }
         catch (Exception exception)
         {
             HttpException e = new HttpException(System.Web.SR.GetString("Invalid_ControlState"), exception);
             e.SetFormatter(new UseLastUnhandledErrorFormatter(e));
             throw e;
         }
     }
 }
Example #6
0
        private static SqlCacheDependency CreateSql7SqlCacheDependencyForOutputCache(string database, string table, string depString)
        {
            SqlCacheDependency dependency;

            try
            {
                dependency = new SqlCacheDependency(database, table);
            }
            catch (HttpException exception)
            {
                HttpException e = new HttpException(System.Web.SR.GetString("Invalid_sqlDependency_argument2", new object[] { depString, exception.Message }), exception);
                e.SetFormatter(new UseLastUnhandledErrorFormatter(e));
                throw e;
            }
            return(dependency);
        }
Example #7
0
        private static void ThrowError(Exception inner, string persistedState, string errorPageMessage,
                                       bool macValidationError)
        {
            ViewStateException middle;
            HttpException      outer;

            middle = new ViewStateException(inner, persistedState);
            middle._macValidationError = macValidationError;

            // Setup the formatter for this exception, to make sure this message shows up
            // in an error page as opposed to the inner-most exception's message.
            outer = new HttpException(GetCorrectErrorPageMessage(middle, errorPageMessage), middle);
            outer.SetFormatter(new UseLastUnhandledErrorFormatter(outer));

            throw outer;
        }
        internal static void WriteValueToStream(Object value, BinaryWriter writer)
        {
            if (value == null)
            {
                writer.Write((byte)TypeID.Null);
            }
            else
            {
                Type t = value.GetType();

                if (t == s_serializedTypes[(int)TypeID.String])
                {
                    writer.Write((byte)TypeID.String);
                    writer.Write((String)value);
                }
                else if (t == s_serializedTypes[(int)TypeID.Int32])
                {
                    writer.Write((byte)TypeID.Int32);
                    writer.Write((Int32)value);
                }
                else if (t == s_serializedTypes[(int)TypeID.Boolean])
                {
                    writer.Write((byte)TypeID.Boolean);
                    writer.Write((Boolean)value);
                }
                else if (t == s_serializedTypes[(int)TypeID.DateTime])
                {
                    writer.Write((byte)TypeID.DateTime);
                    writer.Write(((DateTime)value).Ticks);
                }
                else if (t == s_serializedTypes[(int)TypeID.Decimal])
                {
                    writer.Write((byte)TypeID.Decimal);
                    int[] bits = Decimal.GetBits((Decimal)value);
                    for (int i = 0; i < 4; i++)
                    {
                        writer.Write((int)bits[i]);
                    }
                }
                else if (t == s_serializedTypes[(int)TypeID.Byte])
                {
                    writer.Write((byte)TypeID.Byte);
                    writer.Write((byte)value);
                }
                else if (t == s_serializedTypes[(int)TypeID.Char])
                {
                    writer.Write((byte)TypeID.Char);
                    writer.Write((char)value);
                }
                else if (t == s_serializedTypes[(int)TypeID.Single])
                {
                    writer.Write((byte)TypeID.Single);
                    writer.Write((float)value);
                }
                else if (t == s_serializedTypes[(int)TypeID.Double])
                {
                    writer.Write((byte)TypeID.Double);
                    writer.Write((double)value);
                }
                else if (t == s_serializedTypes[(int)TypeID.SByte])
                {
                    writer.Write((byte)TypeID.SByte);
                    writer.Write((SByte)value);
                }
                else if (t == s_serializedTypes[(int)TypeID.Int16])
                {
                    writer.Write((byte)TypeID.Int16);
                    writer.Write((short)value);
                }
                else if (t == s_serializedTypes[(int)TypeID.Int64])
                {
                    writer.Write((byte)TypeID.Int64);
                    writer.Write((long)value);
                }
                else if (t == s_serializedTypes[(int)TypeID.UInt16])
                {
                    writer.Write((byte)TypeID.UInt16);
                    writer.Write((UInt16)value);
                }
                else if (t == s_serializedTypes[(int)TypeID.UInt32])
                {
                    writer.Write((byte)TypeID.UInt32);
                    writer.Write((UInt32)value);
                }
                else if (t == s_serializedTypes[(int)TypeID.UInt64])
                {
                    writer.Write((byte)TypeID.UInt64);
                    writer.Write((UInt64)value);
                }
                else if (t == s_serializedTypes[(int)TypeID.TimeSpan])
                {
                    writer.Write((byte)TypeID.TimeSpan);
                    writer.Write(((TimeSpan)value).Ticks);
                }
                else if (t == s_serializedTypes[(int)TypeID.Guid])
                {
                    writer.Write((byte)TypeID.Guid);
                    Guid   guid = (Guid)value;
                    byte[] bits = guid.ToByteArray();
                    writer.Write(bits);
                }
                else if (t == s_serializedTypes[(int)TypeID.IntPtr])
                {
                    writer.Write((byte)TypeID.IntPtr);
                    IntPtr v = (IntPtr)value;
                    if (IntPtr.Size == 4)
                    {
                        writer.Write((Int32)v.ToInt32());
                    }
                    else
                    {
                        Debug.Assert(IntPtr.Size == 8);
                        writer.Write((Int64)v.ToInt64());
                    }
                }
                else if (t == s_serializedTypes[(int)TypeID.UIntPtr])
                {
                    writer.Write((byte)TypeID.UIntPtr);
                    UIntPtr v = (UIntPtr)value;
                    if (UIntPtr.Size == 4)
                    {
                        writer.Write((UInt32)v.ToUInt32());
                    }
                    else
                    {
                        Debug.Assert(UIntPtr.Size == 8);
                        writer.Write((UInt64)v.ToUInt64());
                    }
                }
                else
                {
                    writer.Write((byte)TypeID.Object);
                    BinaryFormatter formatter = new BinaryFormatter();
                    try {
                        formatter.Serialize(writer.BaseStream, value);
                    } catch (Exception innerException) {
                        HttpException outerException = new HttpException(HttpRuntime.FormatResourceString(SR.Cant_serialize_session_state), innerException);
                        outerException.SetFormatter(new UseLastUnhandledErrorFormatter(outerException));
                        throw outerException;
                    }
                }
            }
        }
 internal static void WriteValueToStream(Object value, BinaryWriter writer) {
     if (value == null) {
         writer.Write((byte)TypeID.Null);
     } 
     else if (value is String) {
         writer.Write((byte)TypeID.String);
         writer.Write((String) value);
     }
     else if (value is Int32) {
         writer.Write((byte)TypeID.Int32);
         writer.Write((Int32) value);
     }
     else if (value is Boolean) {
         writer.Write((byte)TypeID.Boolean);
         writer.Write((Boolean) value);
     }
     else if (value is DateTime) {
         writer.Write((byte)TypeID.DateTime);
         writer.Write(((DateTime) value).Ticks);
     }
     else if (value is Decimal) {
         writer.Write((byte)TypeID.Decimal);
         int[] bits = Decimal.GetBits((Decimal)value);
         for (int i = 0; i < 4; i++) {
             writer.Write((int)bits[i]);
         }
     }
     else if (value is Byte) {
         writer.Write((byte)TypeID.Byte);
         writer.Write((byte) value);
     }
     else if (value is Char) {
         writer.Write((byte)TypeID.Char);
         writer.Write((char) value);
     }
     else if (value is Single) {
         writer.Write((byte)TypeID.Single);
         writer.Write((float) value);
     }
     else if (value is Double) {
         writer.Write((byte)TypeID.Double);
         writer.Write((double) value);
     }
     else if (value is SByte) {
         writer.Write((byte)TypeID.SByte);
         writer.Write((SByte) value);
     }
     else if (value is Int16) {
         writer.Write((byte)TypeID.Int16);
         writer.Write((short) value);
     }
     else if (value is Int64) {
         writer.Write((byte)TypeID.Int64);
         writer.Write((long) value);
     }
     else if (value is UInt16) {
         writer.Write((byte)TypeID.UInt16);
         writer.Write((UInt16) value);
     }
     else if (value is UInt32) {
         writer.Write((byte)TypeID.UInt32);
         writer.Write((UInt32) value);
     }
     else if (value is UInt64) {
         writer.Write((byte)TypeID.UInt64);
         writer.Write((UInt64) value);
     }
     else if (value is TimeSpan) {
         writer.Write((byte)TypeID.TimeSpan);
         writer.Write(((TimeSpan) value).Ticks);
     }
     else if (value is Guid) {
         writer.Write((byte)TypeID.Guid);
         Guid guid = (Guid) value;
         byte[] bits = guid.ToByteArray();
         writer.Write(bits);
     }
     else if (value is IntPtr) {
         writer.Write((byte)TypeID.IntPtr);
         IntPtr  v = (IntPtr) value;
         if (IntPtr.Size == 4) {
             writer.Write((Int32)v.ToInt32());
         }
         else {
             Debug.Assert(IntPtr.Size == 8);
             writer.Write((Int64)v.ToInt64());
         }
     }
     else if (value is UIntPtr) {
         writer.Write((byte)TypeID.UIntPtr);
         UIntPtr  v = (UIntPtr) value;
         if (UIntPtr.Size == 4) {
             writer.Write((UInt32)v.ToUInt32());
         }
         else {
             Debug.Assert(UIntPtr.Size == 8);
             writer.Write((UInt64)v.ToUInt64());
         }
     }
     else {
         writer.Write((byte)TypeID.Object);
         BinaryFormatter formatter = new BinaryFormatter();
         if (SessionStateUtility.SerializationSurrogateSelector != null) {
             formatter.SurrogateSelector = SessionStateUtility.SerializationSurrogateSelector;
         }
         try {
             formatter.Serialize(writer.BaseStream, value);
         } catch (Exception innerException) {
             HttpException outerException = new HttpException(SR.GetString(SR.Cant_serialize_session_state), innerException);
             outerException.SetFormatter(new UseLastUnhandledErrorFormatter(outerException));
             throw outerException;
         }
     }
 }
Example #10
0
 internal static void WriteValueToStream(Object value, BinaryWriter writer)
 {
     if (value == null)
     {
         writer.Write((byte)TypeID.Null);
     }
     else if (value is String)
     {
         writer.Write((byte)TypeID.String);
         writer.Write((String)value);
     }
     else if (value is Int32)
     {
         writer.Write((byte)TypeID.Int32);
         writer.Write((Int32)value);
     }
     else if (value is Boolean)
     {
         writer.Write((byte)TypeID.Boolean);
         writer.Write((Boolean)value);
     }
     else if (value is DateTime)
     {
         writer.Write((byte)TypeID.DateTime);
         writer.Write(((DateTime)value).Ticks);
     }
     else if (value is Decimal)
     {
         writer.Write((byte)TypeID.Decimal);
         int[] bits = Decimal.GetBits((Decimal)value);
         for (int i = 0; i < 4; i++)
         {
             writer.Write((int)bits[i]);
         }
     }
     else if (value is Byte)
     {
         writer.Write((byte)TypeID.Byte);
         writer.Write((byte)value);
     }
     else if (value is Char)
     {
         writer.Write((byte)TypeID.Char);
         writer.Write((char)value);
     }
     else if (value is Single)
     {
         writer.Write((byte)TypeID.Single);
         writer.Write((float)value);
     }
     else if (value is Double)
     {
         writer.Write((byte)TypeID.Double);
         writer.Write((double)value);
     }
     else if (value is SByte)
     {
         writer.Write((byte)TypeID.SByte);
         writer.Write((SByte)value);
     }
     else if (value is Int16)
     {
         writer.Write((byte)TypeID.Int16);
         writer.Write((short)value);
     }
     else if (value is Int64)
     {
         writer.Write((byte)TypeID.Int64);
         writer.Write((long)value);
     }
     else if (value is UInt16)
     {
         writer.Write((byte)TypeID.UInt16);
         writer.Write((UInt16)value);
     }
     else if (value is UInt32)
     {
         writer.Write((byte)TypeID.UInt32);
         writer.Write((UInt32)value);
     }
     else if (value is UInt64)
     {
         writer.Write((byte)TypeID.UInt64);
         writer.Write((UInt64)value);
     }
     else if (value is TimeSpan)
     {
         writer.Write((byte)TypeID.TimeSpan);
         writer.Write(((TimeSpan)value).Ticks);
     }
     else if (value is Guid)
     {
         writer.Write((byte)TypeID.Guid);
         Guid   guid = (Guid)value;
         byte[] bits = guid.ToByteArray();
         writer.Write(bits);
     }
     else if (value is IntPtr)
     {
         writer.Write((byte)TypeID.IntPtr);
         IntPtr v = (IntPtr)value;
         if (IntPtr.Size == 4)
         {
             writer.Write((Int32)v.ToInt32());
         }
         else
         {
             Debug.Assert(IntPtr.Size == 8);
             writer.Write((Int64)v.ToInt64());
         }
     }
     else if (value is UIntPtr)
     {
         writer.Write((byte)TypeID.UIntPtr);
         UIntPtr v = (UIntPtr)value;
         if (UIntPtr.Size == 4)
         {
             writer.Write((UInt32)v.ToUInt32());
         }
         else
         {
             Debug.Assert(UIntPtr.Size == 8);
             writer.Write((UInt64)v.ToUInt64());
         }
     }
     else
     {
         writer.Write((byte)TypeID.Object);
         BinaryFormatter formatter = new BinaryFormatter();
         if (SessionStateUtility.SerializationSurrogateSelector != null)
         {
             formatter.SurrogateSelector = SessionStateUtility.SerializationSurrogateSelector;
         }
         try {
             formatter.Serialize(writer.BaseStream, value);
         } catch (Exception innerException) {
             HttpException outerException = new HttpException(SR.GetString(SR.Cant_serialize_session_state), innerException);
             outerException.SetFormatter(new UseLastUnhandledErrorFormatter(outerException));
             throw outerException;
         }
     }
 }
Example #11
0
        private static void CreateMdfFile(string fullFileName, string dataDir, string connectionString)
        {
            bool        creatingDir  = false;
            string      databaseName = null;
            HttpContext context      = HttpContext.Current;
            string      tempFileName = null;

            try {
                if (!Directory.Exists(dataDir))
                {
                    creatingDir = true;
                    Directory.CreateDirectory(dataDir);
                    creatingDir = false;
                    try {
                        if (context != null)
                        {
                            HttpRuntime.RestrictIISFolders(context);
                        }
                    }
                    catch { }
                }

                fullFileName = fullFileName.ToUpper(CultureInfo.InvariantCulture);
                char[] strippedFileNameChars = Path.GetFileNameWithoutExtension(fullFileName).ToCharArray();
                for (int iter = 0; iter < strippedFileNameChars.Length; iter++)
                {
                    if (!char.IsLetterOrDigit(strippedFileNameChars[iter]))
                    {
                        strippedFileNameChars[iter] = '_';
                    }
                }
                string strippedFileName = new string(strippedFileNameChars);
                if (strippedFileName.Length > 30)
                {
                    databaseName = strippedFileName.Substring(0, 30) + "_" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
                }
                else
                {
                    databaseName = strippedFileName + "_" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
                }

                tempFileName = Path.Combine(Path.GetDirectoryName(fullFileName), strippedFileName + "_TMP" + s_strSqlExprFileExt);

                // Auto create the temporary database
                SqlServices.Install(databaseName, tempFileName, connectionString);
                DetachDB(databaseName, connectionString);
                try {
                    File.Move(tempFileName, fullFileName);
                }
                catch {
                    if (!File.Exists(fullFileName))
                    {
                        File.Copy(tempFileName, fullFileName);
                        try {
                            File.Delete(tempFileName);
                        }
                        catch { }
                    }
                }
                try {
                    File.Delete(tempFileName.Replace("_TMP.MDF", "_TMP_log.LDF"));
                }
                catch { }
            }
            catch (Exception e) {
                if (context == null || context.IsCustomErrorEnabled)
                {
                    throw;
                }
                HttpException httpExec = new HttpException(e.Message, e);
                if (e is UnauthorizedAccessException)
                {
                    httpExec.SetFormatter(new SqlExpressConnectionErrorFormatter(creatingDir ? DataConnectionErrorEnum.CanNotCreateDataDir : DataConnectionErrorEnum.CanNotWriteToDataDir));
                }
                else
                {
                    httpExec.SetFormatter(new SqlExpressDBFileAutoCreationErrorFormatter(e));
                }
                throw httpExec;
            }
        }
        public override void Load()
        {
            NameValueCollection requestValueCollection = Page.RequestValueCollection;

            if (requestValueCollection == null)
            {
                return;
            }

            try {
                string combinedSerializedStateString = Page.RequestViewStateString;
                string persistedStateID      = null;
                bool   controlStateInSession = false;

                // SessionState will persist a Pair of <bool requiresControlStateInSession, string/pair>,
                // where if requiresControlStateInSession is true, second will just be the sessionID, as
                // we will store both control state and view state in session.  Otherwise, we store just the
                // view state in session and the pair will be <id, ControlState>
                if (!String.IsNullOrEmpty(combinedSerializedStateString))
                {
                    Pair combinedState = (Pair)Util.DeserializeWithAssert(StateFormatter2, combinedSerializedStateString, Purpose.WebForms_SessionPageStatePersister_ClientState);
                    // Check if we are storing control state in session as well
                    if ((bool)combinedState.First)
                    {
                        // So the second is the persistedID
                        persistedStateID      = (string)combinedState.Second;
                        controlStateInSession = true;
                    }
                    else
                    {
                        // Second is <sessionID, ControlState>
                        Pair pair = (Pair)combinedState.Second;
                        persistedStateID = (string)pair.First;
                        ControlState     = pair.Second;
                    }
                }

                if (persistedStateID != null)
                {
                    object sessionData = Page.Session[_viewStateSessionKey + persistedStateID];
                    if (controlStateInSession)
                    {
                        Pair combinedState = sessionData as Pair;
                        if (combinedState != null)
                        {
                            ViewState    = combinedState.First;
                            ControlState = combinedState.Second;
                        }
                    }
                    else
                    {
                        ViewState = sessionData;
                    }
                }
            }
            catch (Exception e) {
                // Setup the formatter for this exception, to make sure this message shows up
                // in an error page as opposed to the inner-most exception's message.
                HttpException newException = new HttpException(SR.GetString(SR.Invalid_ControlState), e);
                newException.SetFormatter(new UseLastUnhandledErrorFormatter(newException));

                throw newException;
            }
        }
        // Called by SqlCacheDependency.GetDependKey
        static internal void EnsureTableIsRegisteredAndPolled(string database, string table) {
            bool    doubleChecked = false;
            
            // First check.  If the cache key exists, that means the first poll request
            // for this table has successfully completed
            Debug.Trace("SqlCacheDependencyManagerCheck", 
                                "Check is called.  Database=" + database+ "; table=" + table);
            
            if (HttpRuntime.CacheInternal[GetMoniterKey(database, table)] != null) {
                return;
            }

            // Initilize polling for this database, if needed.
            InitPolling(database);

            // Wait until this database is initialized by PollCallback for the first time
            DatabaseNotifState  dbState = (DatabaseNotifState)s_DatabaseNotifStates[database];

            if (!dbState._init) {
                int         timeout;
                HttpContext context = HttpContext.Current;

                if (context == null) {
                    timeout = 30;
                }
                else {
                    timeout = Math.Max(context.Timeout.Seconds / 3, 30);
                }
                DateTime waitLimit = DateTime.UtcNow.Add(new TimeSpan(0, 0, timeout));
                
                Debug.Trace("SqlCacheDependencyManagerCheck", "Waiting for intialization: timeout=" + timeout + "s");
                
                for (;;) {
                    if (dbState._init)
                        break;
                        
                    Thread.Sleep(250);

                    // only apply timeout if a managed debugger is not attached
                    if (!System.Diagnostics.Debugger.IsAttached && DateTime.UtcNow > waitLimit) {
                        // We've waited and retried for waitLimit amount of time.
                        // Still PollCallback haven't finished its first call for this database
                        // Assume we cannot connect to SQL.
                        throw new HttpException(
                            SR.GetString(SR.Cant_connect_sql_cache_dep_database_polling, database));
                    }
                }
            }

            while(true) {
                DateTime    utcTablesLastUpdated;
                bool        dbRegistered;
                Exception   pollException;
                int         pollSqlError = 0;

                lock(dbState) {
                     Debug.Trace("SqlCacheDependencyManagerCheck", "dbState:_pollExpt="+ dbState._pollExpt + 
                                "; _pollSqlError=" + dbState._pollSqlError + "; _notifEnabled=" + dbState._notifEnabled );
                     
                    pollException = dbState._pollExpt;
                    if (pollException != null) {
                        pollSqlError = dbState._pollSqlError;
                    }
                    
                    utcTablesLastUpdated = dbState._utcTablesUpdated;
                    dbRegistered = dbState._notifEnabled;
                }

                if (pollException == null &&    // No exception from polling
                    dbRegistered &&             // The database is registered
                    dbState._tables.ContainsKey(table)) {   // The table is also registered
                    Debug.Trace("SqlCacheDependencyManagerCheck", "The table is registered too.  Exit now!");
                    return;
                }

                // Either we hit an error in the last polling, or the database or the table 
                // isn't registered.  
                //
                // See if we can double check.  Double checking is needed because the 
                // results we just looked at might be collected only at last poll time, 
                // which could be quite old, depending on the pollTime setting.
                //
                // The scenario we try to solve is:
                // 1. Let's say polling is configured to happen every 1 minute, and we just poll.
                // 2. A page then registers a table for notification.
                // 3. The page then try to use SqlCacheDependency on that table.
                // 4. If we don't call UpdateDatabaseNotifStat to query the database now,
                //    we'll have to wait for a whole minute before we can use that table.
                //

                // To prevent the SQL server from being bombarded by this kind of per-client-request
                // adhoc check, we only allow a max of one double check per second per database
                if (!doubleChecked && 
                    DateTime.UtcNow - utcTablesLastUpdated >= OneSec) {
                    
                    Debug.Trace("SqlCacheDependencyManagerCheck", "Double check...");
                    UpdateDatabaseNotifState(database);
                    doubleChecked = true;
                    continue;
                }

                if (pollSqlError == SQL_EXCEPTION_SP_NOT_FOUND) {
                    // This error happens if the database isn't enabled for notification.
                    // This doesn't count as a real Sql error
                    Debug.Assert(dbRegistered == false, "When this error happened, we shouldn't be able to poll the database");
                    pollException = null;
                }
                
                // Report any error if we failed in the last PollCallback
                if (pollException != null) {
                    string  error;
                    
                    if (pollSqlError == SQL_EXCEPTION_PERMISSION_DENIED_ON_OBJECT ||
                        pollSqlError == SQL_EXCEPTION_PERMISSION_DENIED_ON_DATABASE) {
                        error = SR.Permission_denied_database_polling;
                    }
                    else {
                        error = SR.Cant_connect_sql_cache_dep_database_polling;
                    }

                    HttpException outerException = new HttpException(
                           SR.GetString(error, database), pollException);

                    outerException.SetFormatter(new UseLastUnhandledErrorFormatter(outerException));
                    
                    throw outerException;
                }

                // If we don't get any error, then either the database or the table isn't registered.
                if (dbRegistered == false) {
                    throw new DatabaseNotEnabledForNotificationException(
                            SR.GetString(SR.Database_not_enabled_for_notification, database));
                }
                else {
                    throw new TableNotEnabledForNotificationException(
                            SR.GetString(SR.Table_not_enabled_for_notification, table, database));
                }
            }
        }
 static SqlCacheDependency CreateSql7SqlCacheDependencyForOutputCache(string database, string table, string depString) {
     try {
         return new SqlCacheDependency(database, table);
     }
     catch (HttpException e) {
         HttpException outerException = new HttpException(
                SR.GetString(SR.Invalid_sqlDependency_argument2, depString, e.Message), e);
         
         outerException.SetFormatter(new UseLastUnhandledErrorFormatter(outerException));
         
         throw outerException;
     }
 }
 internal static void WriteValueToStream(object value, BinaryWriter writer)
 {
     if (value == null)
     {
         writer.Write((byte)0x15);
     }
     else if (value is string)
     {
         writer.Write((byte)1);
         writer.Write((string)value);
     }
     else if (value is int)
     {
         writer.Write((byte)2);
         writer.Write((int)value);
     }
     else if (value is bool)
     {
         writer.Write((byte)3);
         writer.Write((bool)value);
     }
     else if (value is DateTime)
     {
         writer.Write((byte)4);
         DateTime time = (DateTime)value;
         writer.Write(time.Ticks);
     }
     else if (value is decimal)
     {
         writer.Write((byte)5);
         int[] bits = decimal.GetBits((decimal)value);
         for (int i = 0; i < 4; i++)
         {
             writer.Write(bits[i]);
         }
     }
     else if (value is byte)
     {
         writer.Write((byte)6);
         writer.Write((byte)value);
     }
     else if (value is char)
     {
         writer.Write((byte)7);
         writer.Write((char)value);
     }
     else if (value is float)
     {
         writer.Write((byte)8);
         writer.Write((float)value);
     }
     else if (value is double)
     {
         writer.Write((byte)9);
         writer.Write((double)value);
     }
     else if (value is sbyte)
     {
         writer.Write((byte)10);
         writer.Write((sbyte)value);
     }
     else if (value is short)
     {
         writer.Write((byte)11);
         writer.Write((short)value);
     }
     else if (value is long)
     {
         writer.Write((byte)12);
         writer.Write((long)value);
     }
     else if (value is ushort)
     {
         writer.Write((byte)13);
         writer.Write((ushort)value);
     }
     else if (value is uint)
     {
         writer.Write((byte)14);
         writer.Write((uint)value);
     }
     else if (value is ulong)
     {
         writer.Write((byte)15);
         writer.Write((ulong)value);
     }
     else if (value is TimeSpan)
     {
         writer.Write((byte)0x10);
         TimeSpan span = (TimeSpan)value;
         writer.Write(span.Ticks);
     }
     else if (value is Guid)
     {
         writer.Write((byte)0x11);
         byte[] buffer = ((Guid)value).ToByteArray();
         writer.Write(buffer);
     }
     else if (value is IntPtr)
     {
         writer.Write((byte)0x12);
         IntPtr ptr = (IntPtr)value;
         if (IntPtr.Size == 4)
         {
             writer.Write(ptr.ToInt32());
         }
         else
         {
             writer.Write(ptr.ToInt64());
         }
     }
     else if (value is UIntPtr)
     {
         writer.Write((byte)0x13);
         UIntPtr ptr2 = (UIntPtr)value;
         if (UIntPtr.Size == 4)
         {
             writer.Write(ptr2.ToUInt32());
         }
         else
         {
             writer.Write(ptr2.ToUInt64());
         }
     }
     else
     {
         writer.Write((byte)20);
         BinaryFormatter formatter = new BinaryFormatter();
         try
         {
             formatter.Serialize(writer.BaseStream, value);
         }
         catch (Exception exception)
         {
             HttpException e = new HttpException(System.Web.SR.GetString("Cant_serialize_session_state"), exception);
             e.SetFormatter(new UseLastUnhandledErrorFormatter(e));
             throw e;
         }
     }
 }
Example #16
0
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            // VSWhidbey 448844: Disable handler if retail is set to true
            if (DeploymentSection.RetailInternal ||
                (!context.Request.IsLocal && HttpRuntime.Profile.LocalOnly))
            {
                HttpException e = new HttpException(403, null);
                e.SetFormatter(new TraceHandlerErrorFormatter(!DeploymentSection.RetailInternal));
                throw e;
            }

            _context  = context;
            _response = _context.Response;
            _request  = _context.Request;
            _writer   = Page.CreateHtmlTextWriterInternal(_response.Output, _request);

            // if we're in integrated mode, we need to set the content type explicitly
            if (context.WorkerRequest is IIS7WorkerRequest)
            {
                _response.ContentType = _request.Browser.PreferredRenderingMime;
            }

            if (_writer == null)
            {
                // Can't create a writer, horked at this point, just return
                return;
            }

            _context.Trace.IsEnabled = false;

            // Validate the input to prevent XSS attacks.
            _request.ValidateInput();

            _writer.Write("<html>\r\n");
            _writer.Write("<head>\r\n");
            _writer.Write(StyleSheet);
            _writer.Write("</head>\r\n");

            _writer.Write("<body>\r\n");
            _writer.Write("<span class=\"tracecontent\">\r\n");

            if (!HttpRuntime.Profile.IsConfigEnabled)
            {
                HttpException e = new HttpException();
                e.SetFormatter(new TraceHandlerErrorFormatter(false));
                throw e;
            }

            IList datasets = HttpRuntime.Profile.GetData();

            // first check if we should clear data
            if (_request.QueryString["clear"] != null)
            {
                HttpRuntime.Profile.Reset();
                string url = _request.RawUrl;
                _response.Redirect(url.Substring(0, url.IndexOf("?", StringComparison.Ordinal)));
            }

            // then check if we are drilling down
            string strid = _request.QueryString["id"];

            if (strid != null)
            {
                int index = Int32.Parse(strid, CultureInfo.InvariantCulture);
                if (index >= 0 && index < datasets.Count)
                {
                    ShowDetails((DataSet)datasets[index]);
                    ShowVersionDetails();
                    _writer.Write("</span>\r\n</body>\r\n</html>\r\n");
                    return;
                }
            }

            // if we get here, its just generic request
            ShowRequests(datasets);
            ShowVersionDetails();
            _writer.Write("</span>\r\n</body>\r\n</html>\r\n");
        }
        private static void CreateMdfFile(string fullFileName, string dataDir, string connectionString) {
            bool creatingDir = false;
            string databaseName = null;
            HttpContext context = HttpContext.Current;
            string tempFileName = null;

            try {
                if (!Directory.Exists(dataDir)) {
                    creatingDir = true;
                    Directory.CreateDirectory(dataDir);
                    creatingDir = false;
                    try {
                        if (context != null)
                            HttpRuntime.RestrictIISFolders(context);
                    }
                    catch { }
                }

                fullFileName = fullFileName.ToUpper(CultureInfo.InvariantCulture);
                char[] strippedFileNameChars = Path.GetFileNameWithoutExtension(fullFileName).ToCharArray();
                for (int iter = 0; iter < strippedFileNameChars.Length; iter++)
                    if (!char.IsLetterOrDigit(strippedFileNameChars[iter]))
                        strippedFileNameChars[iter] = '_';
                string strippedFileName = new string(strippedFileNameChars);
                if (strippedFileName.Length > 30)
                    databaseName = strippedFileName.Substring(0, 30) + "_" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
                else
                    databaseName = strippedFileName + "_" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);

                tempFileName = Path.Combine(Path.GetDirectoryName(fullFileName), strippedFileName + "_TMP" + s_strSqlExprFileExt);

                // Auto create the temporary database
                SqlServices.Install(databaseName, tempFileName, connectionString);
                DetachDB(databaseName, connectionString);
                try {
                    File.Move(tempFileName, fullFileName);
                }
                catch {
                    if (!File.Exists(fullFileName)) {
                        File.Copy(tempFileName, fullFileName);
                        try {
                            File.Delete(tempFileName);
                        }
                        catch { }
                    }
                }
                try {
                    File.Delete(tempFileName.Replace("_TMP.MDF", "_TMP_log.LDF"));
                }
                catch { }
            }
            catch (Exception e) {
                if (context == null || context.IsCustomErrorEnabled)
                    throw;
                HttpException httpExec = new HttpException(e.Message, e);
                if (e is UnauthorizedAccessException)
                    httpExec.SetFormatter(new SqlExpressConnectionErrorFormatter(creatingDir ? DataConnectionErrorEnum.CanNotCreateDataDir : DataConnectionErrorEnum.CanNotWriteToDataDir));
                else
                    httpExec.SetFormatter(new SqlExpressDBFileAutoCreationErrorFormatter(e));
                throw httpExec;
            }
        }
Example #18
0
        private static void CreateMdfFile(string fullFileName, string dataDir, string connectionString)
        {
            bool        flag       = false;
            string      database   = null;
            HttpContext current    = HttpContext.Current;
            string      dbFileName = null;

            try
            {
                if (!Directory.Exists(dataDir))
                {
                    flag = true;
                    Directory.CreateDirectory(dataDir);
                    flag = false;
                    try
                    {
                        if (current != null)
                        {
                            HttpRuntime.RestrictIISFolders(current);
                        }
                    }
                    catch
                    {
                    }
                }
                fullFileName = fullFileName.ToUpper(CultureInfo.InvariantCulture);
                char[] chArray = Path.GetFileNameWithoutExtension(fullFileName).ToCharArray();
                for (int i = 0; i < chArray.Length; i++)
                {
                    if (!char.IsLetterOrDigit(chArray[i]))
                    {
                        chArray[i] = '_';
                    }
                }
                string str3 = new string(chArray);
                if (str3.Length > 30)
                {
                    database = str3.Substring(0, 30) + "_" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
                }
                else
                {
                    database = str3 + "_" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
                }
                dbFileName = Path.Combine(Path.GetDirectoryName(fullFileName), str3 + "_TMP.MDF");
                SqlServices.Install(database, dbFileName, connectionString);
                DetachDB(database, connectionString);
                try
                {
                    File.Move(dbFileName, fullFileName);
                }
                catch
                {
                    if (!File.Exists(fullFileName))
                    {
                        File.Copy(dbFileName, fullFileName);
                        try
                        {
                            File.Delete(dbFileName);
                        }
                        catch
                        {
                        }
                    }
                }
                try
                {
                    File.Delete(dbFileName.Replace("_TMP.MDF", "_TMP_log.LDF"));
                }
                catch
                {
                }
            }
            catch (Exception exception)
            {
                if ((current == null) || current.IsCustomErrorEnabled)
                {
                    throw;
                }
                HttpException exception2 = new HttpException(exception.Message, exception);
                if (exception is UnauthorizedAccessException)
                {
                    exception2.SetFormatter(new SqlExpressConnectionErrorFormatter(flag ? DataConnectionErrorEnum.CanNotCreateDataDir : DataConnectionErrorEnum.CanNotWriteToDataDir));
                }
                else
                {
                    exception2.SetFormatter(new SqlExpressDBFileAutoCreationErrorFormatter(exception));
                }
                throw exception2;
            }
        }
        internal static void EnsureTableIsRegisteredAndPolled(string database, string table)
        {
            DateTime  time2;
            bool      flag2;
            Exception exception;
            int       num2;
            bool      flag = false;

            if (HttpRuntime.CacheInternal[GetMoniterKey(database, table)] != null)
            {
                return;
            }
            InitPolling(database);
            DatabaseNotifState state = (DatabaseNotifState)s_DatabaseNotifStates[database];

            if (!state._init)
            {
                int         num;
                HttpContext current = HttpContext.Current;
                if (current == null)
                {
                    num = 30;
                }
                else
                {
                    num = Math.Max(current.Timeout.Seconds / 3, 30);
                }
                DateTime time = DateTime.UtcNow.Add(new TimeSpan(0, 0, num));
                do
                {
                    if (state._init)
                    {
                        goto Label_00BD;
                    }
                    Thread.Sleep(250);
                }while (Debugger.IsAttached || (DateTime.UtcNow <= time));
                throw new HttpException(System.Web.SR.GetString("Cant_connect_sql_cache_dep_database_polling", new object[] { database }));
            }
Label_00BD:
            num2 = 0;
            lock (state)
            {
                exception = state._pollExpt;
                if (exception != null)
                {
                    num2 = state._pollSqlError;
                }
                time2 = state._utcTablesUpdated;
                flag2 = state._notifEnabled;
            }
            if (((exception == null) && flag2) && state._tables.ContainsKey(table))
            {
                return;
            }
            if (flag || ((DateTime.UtcNow - time2) < OneSec))
            {
                string str;
                if (num2 == 0xafc)
                {
                    exception = null;
                }
                if (exception == null)
                {
                    if (!flag2)
                    {
                        throw new DatabaseNotEnabledForNotificationException(System.Web.SR.GetString("Database_not_enabled_for_notification", new object[] { database }));
                    }
                    throw new TableNotEnabledForNotificationException(System.Web.SR.GetString("Table_not_enabled_for_notification", new object[] { table, database }));
                }
                switch (num2)
                {
                case 0xe5:
                case 0x106:
                    str = "Permission_denied_database_polling";
                    break;

                default:
                    str = "Cant_connect_sql_cache_dep_database_polling";
                    break;
                }
                HttpException e = new HttpException(System.Web.SR.GetString(str, new object[] { database }), exception);
                e.SetFormatter(new UseLastUnhandledErrorFormatter(e));
                throw e;
            }
            UpdateDatabaseNotifState(database);
            flag = true;
            goto Label_00BD;
        }