//***************************************************************************
        // Public Methods
        //
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;

            string
                reqImg = req["imgNm"];

            try
            {
                object objImg = null;
                try
                {
                    if (!string.IsNullOrEmpty(reqImg))
                    {
                        objImg = global::RainstormStudios.Web.Properties.Resources.ResourceManager.GetObject(reqImg);
                    }

                    if (!string.IsNullOrEmpty(reqImg) && objImg == null)
                    {
                        context.AddError(new Exception("Unable to find requested image name.  Returning generic folder image."));
                    }

                    if (objImg == null)
                    {
                        objImg = global::RainstormStudios.Web.Properties.Resources.ResourceManager.GetObject("folder");
                    }

                    if (objImg == null)
                    {
                        throw new Exception("Unable to find any image resources.");
                    }

                    using (MemoryStream ms = new MemoryStream())
                    {
                        ((Bitmap)objImg).Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                        context.Response.StatusCode  = 200;
                        context.Response.ContentType = "image/gif";
                        byte[] imgBts = ms.ToArray();
                        context.Response.OutputStream.Write(imgBts, 0, imgBts.Length);
                    }
                }
                finally
                {
                    if (objImg != null && objImg is IDisposable)
                    {
                        ((IDisposable)objImg).Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                context.AddError(ex);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Standard HttpHandler Entry point. Coordinate the displaying of the Session View
        /// </summary>
        /// <param name="context">The current HttpContext</param>
        public void ProcessRequest(HttpContext context)
        {
            //Only allow session viewing on requests that have originated locally
            if (Common.RequestIsLocal(context.Request) == false)
            {
                context.AddError(new ApplicationException("SessionView can only be accessed locally i.e. localhost"));
                return;
            }

            _HttpHandlerSettings = (HttpHandlersConfig)context.GetSection("sharedCache/httpHandlers");

            if (_HttpHandlerSettings == null ||
                (_HttpHandlerSettings.SessionView == null) ||
                (_HttpHandlerSettings.SessionView.Enabled == false))
            {
                //Session View is not enabled fire exception
                context.AddError(new ApplicationException(@"SessionView is not enabled. See the sharedCache\httpHandlers\ section in your configuration file", null));
                return;
            }

            _context  = context;
            _request  = context.Request;
            _response = context.Response;

            _writer = new HtmlTextWriter(_response.Output);

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

            //Write out Html head and style tags
            _writer.Write("<head>\r\n");
            _writer.Write(pageStyle);
            _writer.Write("</head>\r\n");

            if (_context.Session.Mode != SessionStateMode.Off)
            {
                if (context.Request.QueryString["Item"] == null)
                {
                    //An item specific requets is NOT being made. Display the lot
                    EnumerateAndDisplaySessionState();
                }
                else
                {
                    //A session item specific request is being made. Try and display it
                    DisplaySessionStateItem();
                }
            }
            else
            {
                //Session state is off
                DisplaySessionStateOff();
            }

            _writer.Write("\r\n</body>\r\n</html>\r\n");
        }
Ejemplo n.º 3
0
        internal static void WriteExceptionJsonString(HttpContext context, Exception ex, JavaScriptSerializer serializer)
        {
            context.Response.ClearHeaders();
            context.Response.ClearContent();
            context.Response.Clear();
            context.Response.StatusCode        = (int)HttpStatusCode.InternalServerError;
            context.Response.StatusDescription = HttpWorkerRequest.GetStatusDescription((int)HttpStatusCode.InternalServerError);
            context.Response.ContentType       = "application/json";
            context.Response.AddHeader("jsonerror", "true");
            using (StreamWriter writer = new StreamWriter(context.Response.OutputStream, new UTF8Encoding(false)))
            {
                if (ex is TargetInvocationException)
                {
                    ex = ex.InnerException;
                }

                context.AddError(ex);

                if (context.IsCustomErrorEnabled)
                {
                    writer.Write(serializer.Serialize(new WebServiceError("Error occured while processing request", String.Empty, String.Empty)));
                }
                else
                {
                    writer.Write(serializer.Serialize(new WebServiceError(ex.Message, ex.StackTrace, ex.GetType().FullName)));
                }
                writer.Flush();
            }
        }
Ejemplo n.º 4
0
        public void ProcessRequest(HttpContext context)
        {
            //ESTA CLASE ADMINISTRARA LA PETICION Y DECIDIRA DONDE NOS RECIRECCIONA (POR EJEMPLO, WIKIPEDIA)
            //String url = context.Request.RawUrl;
            //int barra = url.LastIndexOf("/") + 1;
            //String provincia = url.Substring(barra);

            //DICCIONARIO DE RUTAS
            RouteValueDictionary rutas = this.requestContext.RouteData.Values;

            //DE AQUI, YA PODEMOS RECUPERAR EL CONTROLLER, EL ACTION O LO QUE HAYAMOS ESCRITO EN NUESTRO MAPEO DE URL
            String provincia = rutas["nombreprovincia"].ToString();

            //EL SIGUIENTE PASO ES COMPROBAR QUE LA PROVINCIA NO ESTA EN LAS BLOQUEADAS
            if (this.provincias.Contains(provincia))
            {
                //LA FORMA DE INDICAR ERRORES EN MVC ES UTILIZANDO CONTEXTOS
                context.AddError(new Exception("La provincia " + provincia + " no está permitida"));
            }
            else
            {
                String wiki = "https://es.wikipedia.org/wiki/" + provincia;
                context.Response.Redirect(wiki, true);
            }
        }
Ejemplo n.º 5
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                if (HttpHandlerType != null)
                {
                    // If the configuration data is assosicated with
                    // this http handler
                    if (HttpHandlerType is Nequeo.Web.HttpHandler.Captcha)
                    {
                        // Get the query string from the captcha key
                        NameValueCollection queryString = context.Request.QueryString;
                        string text = queryString[Nequeo.Web.UI.Control.Captcha.KEY];

                        // Responed to the http request by writting to
                        // the stream the captcha image for the source request
                        HttpResponse response = context.Response;
                        Bitmap       bitmap   = WebManager.GenerateImage(text);

                        // Write the new captcha image to the request stream.
                        if (bitmap != null)
                        {
                            bitmap.Save(response.OutputStream, ImageFormat.Jpeg);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                context.AddError(ex);
                LogHandler.WriteTypeMessage(ex.Message, typeof(Captcha).GetMethod("ProcessRequest"));
            }
        }
        public void Methods_Deny_Unrestricted()
        {
            context.AddError(new Exception());
            context.ClearError();
            try
            {
                context.GetConfig(String.Empty);
            }
            catch (NullReferenceException)
            {
            }

            try
            {
                context.RewritePath(String.Empty);
            }
            catch (NullReferenceException)
            {
                // ms
            }
            catch (ArgumentNullException)
            {
                // mono
            }

            try
            {
                context.RewritePath(String.Empty, String.Empty, String.Empty);
            }
            catch (NullReferenceException)
            {
                // ms
            }
            catch (ArgumentNullException)
            {
                // mono
            }
#if NET_2_0
            context.GetSection(String.Empty);

            try
            {
                context.RewritePath(String.Empty, true);
            }
            catch (NullReferenceException)
            {
                // ms
            }
            catch (NotImplementedException)
            {
                // mono
            }
#endif
        }
Ejemplo n.º 7
0
        protected override IAsyncResult BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, object state)
        {
            string pais = ObterCodigoPais(httpContext.Request.UserHostAddress);

            if (this.paises.Contains(pais))
            {
                httpContext.AddError(new Exception("Desculpe! Você não pode acessar esta página a partir do seu país."));
            }

            return(base.BeginProcessRequest(httpContext, callback, state));
        }
Ejemplo n.º 8
0
        protected void SynchronousPostbackErrorButton_Click(object sender, EventArgs e)
        {
            var        f             = new ErrorPageHandlerFactory();
            var        p             = f.GetHandler(Context, "GET", "~/ErrorHandling/ErrorForm.aspx", Server.MapPath("~/ErrorHandling/ErrorForm.aspx"));
            var        stringBuilder = new StringBuilder();
            TextWriter output        = new StringWriter(stringBuilder);
            var        context       = new HttpContext(new SimpleWorkerRequest("~/ErrorHandling/ErrorForm.aspx", "", output));

            context.AddError(new ApplicationException("temp error"));
            p.ProcessRequest(context);
            context.Response.Flush();
            throw new ErrorHandlingException("Synchronous Error" + stringBuilder, new ApplicationException("Inner Exception"));
        }
Ejemplo n.º 9
0
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            try
            {
                Trace.TraceWarning("Controller.OnActionExecuted");
                DataManager.Commit();
            }
            catch (Exception ex)
            {
                HttpContext.AddError(ex);
            }
        }
Ejemplo n.º 10
0
        protected override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);

            try
            {
                Trace.TraceWarning("Controller.OnException");
                DataManager.Rollback();
            }
            catch (Exception ex)
            {
                HttpContext.AddError(ex);
            }
        }
Ejemplo n.º 11
0
        public void ProcessRequest(HttpContext context)
        {
            RouteValueDictionary rutes = this.requestcontext.RouteData.Values;
            String province            = rutes["ProvinceName"].ToString();

            if (this.provinces.Contains(province))
            {
                context.AddError(new Exception("La provincia de" + province + ",está protegida por el Gobierno de los Estados Unidos de América"));
            }
            else
            {
                String wiki = "https://es.wikipedia.org/wiki/" + province;
                context.Response.Redirect(wiki, true);
            }
        }
Ejemplo n.º 12
0
        public static Task RunContext(HttpContext context)
        {
            if (_app == null)
            {
                Initialize(context);
                if (_app == null)
                {
                    throw new InvalidOperationException("No application found.");
                }
            }

            var env = CreateEnvironmentHash(context);
            var tcs = new TaskCompletionSource <object>();

            env.Add(OwinKeys.CallCompleted, tcs.Task);
            var task = _app(env);

            return(task
                   .ContinueWith(t =>
            {
                if (t.Exception != null)
                {
                    context.Response.StatusCode = 500;

                    foreach (Exception ex in t.Exception.InnerExceptions)
                    {
                        context.AddError(ex);
                    }
                }
                else if (!env.ContainsKey(OwinKeys.ResponseStatusCode))
                {
                    context.Response.StatusCode = 404;
                }
                else
                {
                    context.Response.StatusCode = (int)env[OwinKeys.ResponseStatusCode];
                }

                if (env.ContainsKey(OwinKeys.ResponseHeaders))
                {
                    WriteHeaders((IDictionary <string, string[]>)env[OwinKeys.ResponseHeaders], context);
                }
                return TaskHelper.Completed();
            }, TaskContinuationOptions.None)
                   .Unwrap()
                   .ContinueWith(t => SetOwinCallCompleted(t, tcs)));
        }
        public void ProcessRequest(HttpContext context)
        {
            ////String url = context.Request.RawUrl;
            ////int barra = url.LastIndexOf("/") +1;
            ////String provincia = url.Substring(barra);

            //RouteValueDictionary rutas = this.requestContext.RouteData.Values;
            ////de aqui sacamos los valores que nos pasan del mapeo
            //String provincia = rutas["provincia"].ToString();

            //if (this.provincias.Contains(provincia))
            //{
            //    //para indicar contextos en MVC se utiliza contextos
            //    context.AddError(new Exception("La provincia " + provincia + " no esta permitida"));
            //    String wikis = "https://es.wikipedia.org/wiki/" + "madrid";
            //    context.Response.Redirect(wikis, true);
            //    //al añadir una excepcion se anula todo el flujo de datos
            //}


            //String wiki = "https://es.wikipedia.org/wiki/" + provincia;
            //context.Response.Redirect(wiki, true);

            //en vez de obtener la infromacion tratando la url como string podemos usar
            //RouteValueDirectory y sacar los valores pidiendoselos al contexto.
            RouteValueDictionary rutas = this.requestContext.RouteData.Values;
            //de aqui sacamos los valores que nos pasan del mapeo
            String noticias = rutas["noticia"].ToString();

            if (this.bloqueos.Contains(noticias))
            {
                //para añadir una excepcion lo hacemos también desde el contexto
                context.AddError(new Exception("Las noticias sobre  " + noticias + " no estan permitidas"));
                //al añadir una excepcion se anula todo el flujo de datos
            }

            //si no hay errores
            String pais = "https://elpais.com/tag/" + noticias + "/a/";

            context.Response.Redirect(pais, true);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Standard HttpHandler Entry point. Coordinate the displaying of the Cache View
        /// </summary>
        /// <param name="context">The current HttpContext</param>
        public void ProcessRequest(HttpContext context)
        {
            if (RequestIsLocal(context.Request) == false)
            {
                context.AddError(new ApplicationException("CacheView can only be accessed locally i.e. localhost"));
                return;
            }

            if (ConfigurationManager.AppSettings["showOutputCache"] != null &&
                ConfigurationManager.AppSettings["showOutputCache"] == "true")
            {
                this.displayOutputCache = true;
            }

            if (ConfigurationManager.AppSettings["showUserControlCache"] != null &&
                ConfigurationManager.AppSettings["showUserControlCache"] == "true")
            {
                this.displayUserControlCache = true;
            }

            this.context  = context;
            this.request  = context.Request;
            this.response = context.Response;

            this.writer = new HtmlTextWriter(this.response.Output);

            this.writer.Write("<html>\r\n");

            // Write out Html head and style tags
            this.writer.Write("<head>\r\n");
            this.writer.Write(this.pageStyle);
            this.writer.Write("</head>\r\n");


            this.EnumerateAndDisplayInternalCache(this.displayOutputCache, this.displayUserControlCache);

            this.writer.Write("\r\n</body>\r\n</html>\r\n");
        }
Ejemplo n.º 15
0
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            Context = context;

            try
            {
                JsonHandler.JsonResponse(context.Response, new Action <JsonWriter>(WriteResult));
            }
            catch (Exception exception)
            {
                context.AddError(exception);
                OnError(EventArgs.Empty);
                if (context.Error != null)
                {
                    throw new HttpUnhandledException("blah", exception);
                }
            }
        }
Ejemplo n.º 16
0
        public void EncodeError_FromHttpContext()
        {
            // setup
            const string url  = "http://myserver.com/site/page?param=value";
            var          x    = new HttpContext(new HttpRequest("file", url, "param=value"), new HttpResponse(TextWriter.Null));
            var          guid = Guid.NewGuid();

            x.Items.Add("loggingId", guid);
            const string msg = "booboo";
            Exception    exc;

            try
            {
                throw new Exception(msg); // to get a stack trace
            }
            catch (Exception ex)
            {
                exc = ex;
            }
            x.AddError(exc);

            // test
            var res = ServerErrorHttpModule.EncodeError(x);

            // sense
            var dec = Encoding.UTF8.GetString(Convert.FromBase64String(res));

            Assert.False(string.IsNullOrEmpty(dec));
            var parts = dec.Split(ServerErrorHttpModule.ErrorSepChar);

            Assert.Equal(4, parts.Length);
            Assert.True(parts.Contains(guid.ToString()));
            Assert.True(parts.Contains(url));
            Assert.True(parts.Contains(msg));
            Assert.Equal(1, parts.Count(p => p.Contains("EncodeError_FromHttpContext")));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Member of the IHttpHandler interface
        /// Process a dynamic web page request
        /// </summary>
        /// <param name="context">represents the current web page request</param>
        public void ProcessRequest(HttpContext context)
        {
#if DEBUG
            if (context.Request["__admin"] != null)
            {
                if (context.Request["__admin"].ToUpper() == "showXml".ToUpper())
                {
                    System.Xml.XmlDocument dom = new System.Xml.XmlDocument();
                    dom.Load(context.Request.PhysicalPath);
                    dom.Save(context.Response.Output);

                    return;
                }
            }
#endif

            ListDictionary objDict = null;

            try
            {
                //Load the XML document indicated in the request
                XmlDocument dom = new XmlDocument();
                dom.Load(context.Request.PhysicalPath);

                //get a list of all the nodes in the SkinUI Namespace
                XmlNodeList l = dom.GetElementsByTagName("*", SkinUtil.SkinUINamespace);

                //Initalize the XSLT variable
                //Create a new object dictionary to store variable declarations
                TransformInfo xsltInfo = null;
                objDict = new ListDictionary();

                //process each of the SkinUI Nodes. Note, since we delete each WebSkin
                //node as we process it, we just need to keep processing the top element
                //of the list until the list is empty.
                while (l.Count > 0)
                {
                    XmlNode n = l[0];
                    switch (n.LocalName)
                    {
                    case "class":
                        ClassDecl(context, n, objDict);
                        break;

                    case "methodcall":
                        MethodCall(context, n, objDict);
                        break;

                    case "database":
                        DatabaseDecl(n, objDict);
                        break;

                    case "query":
                        Query(context, n, objDict);
                        break;

                    case "requestvar":
                        RequestVar(context.Request, n);
                        break;

                    case "transform":
                        if (xsltInfo != null)
                        {
                            throw new Exception("Multiple SkinUI Transform tags found");
                        }
                        xsltInfo = new TransformInfo(n);
                        n.ParentNode.RemoveChild(n);
                        break;

                    default:
                        throw new Exception("Unrecognized SkinUI tag name: " + n.LocalName);
                    }
                }

                //Delete any namespace declarations off the root node for the SkinUI namespace
                for (int i = dom.DocumentElement.Attributes.Count - 1; i >= 0; i--)
                {
                    XmlAttribute a = dom.DocumentElement.Attributes[i];
                    if (a.Value == SkinUtil.SkinUINamespace && a.Prefix == "xmlns")
                    {
                        a.OwnerElement.Attributes.Remove(a);
                    }
                }

                //Get the XSLT file to use in transforms from the controller class
                string xsltFile = "";

                if (xsltInfo != null)
                {
                    if (xsltInfo.defaultTransform != "")
                    {
                        xsltFile = context.Request.PhysicalApplicationPath + xsltInfo.defaultTransform;
                    }
                    else
                    {
                        Object o = objDict[xsltInfo.variable];
                        xsltFile = GetXSLTemplate(o, xsltInfo.method, context);
                    }
                }

                //Call the helper function to perform the actual XSLT Transform
                SkinUtil.Transform(dom, xsltFile, context);
            }
            catch (Exception ex)
            {
                //Catch any exception and add it to the context as an HTTP exception
                HttpException h = new HttpException(500, ex.Message, ex);
                context.AddError(h);
            }
            finally
            {
                if (objDict != null)
                {
                    //Close and release all entries in the object dictionary
                    foreach (DictionaryEntry entry in objDict)
                    {
                        if (entry.Value is SqlConnection)
                        {
                            ((SqlConnection)entry.Value).Close();
                        }
                    }
                }
            }
        }
Ejemplo n.º 18
0
        public void ProcessRequest(HttpContext context)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                var hashLength                   = int.Parse(context.Request.QueryString["hash"]);
                var filename                     = context.Request.QueryString["filename"];
                var fileUploadLibrary            = HttpUtility.UrlDecode(context.Request.QueryString["fileUploadLibrary"]);
                var position                     = context.Request.QueryString["position"];
                var serverUrl                    = HttpUtility.UrlDecode(context.Request.QueryString["site"]);//string.Format("http://{0}/", context.Request.Url.Authority);
                context.Response.Expires         = -1;
                context.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
                context.Response.AddHeader("cache-control", "private");
                context.Response.CacheControl = "no-cache";

                string tempDirectory = Environment.GetEnvironmentVariable("tmp");

                string filePath = tempDirectory + @"\" + filename;

                FileInfo fileInfo = new FileInfo(filePath);

                int bufferLength    = (int)context.Request.InputStream.Length;
                byte[] receivedData = new byte[bufferLength];

                int bytesRead = context.Request.InputStream.Read(receivedData, 0, bufferLength);

                if (bytesRead != bufferLength)
                {
                    byte[] truncatedChunk = new byte[bytesRead];

                    Array.Copy(receivedData, truncatedChunk, bytesRead);

                    receivedData = truncatedChunk;
                }

                ReceivedPackage receivedPackage = new ReceivedPackage(hashLength, receivedData);

                if (!receivedPackage.IsCorrupted())
                {
                    using (FileStream fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write))
                    {
                        fileStream.Write(receivedPackage.FileDataReceived, 0, receivedPackage.FileDataSize);
                    }
                }
                else
                {
                    throw new CorruptedPackageException();
                }

                if (position == "last")
                {
                    using (var fileStream = fileInfo.OpenRead())
                    {
                        using (var site = new SPSite(serverUrl))
                        {
                            using (SPWeb web = site.OpenWeb())
                            {
                                web.AllowUnsafeUpdates = true;
                                SPList list;
                                try
                                {
                                    list = web.GetList(serverUrl + "/" + fileUploadLibrary);
                                }
                                catch (Exception ex)
                                {
                                    context.AddError(ex);
                                    return;
                                }
                                list.RootFolder.Files.Add(serverUrl + "/" + fileUploadLibrary + "/" + filename, fileStream);
                                web.AllowUnsafeUpdates = false;
                            }
                        }
                    }

                    fileInfo.Delete();
                }
            });
        }
Ejemplo n.º 19
0
 public ActionResult Error403()
 {
     HttpContext.AddError(new HttpException(403, "Access Denied"));
     return(View());
 }
Ejemplo n.º 20
0
        //***************************************************************************
        // Public Methods
        //
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;

            string
                strImgPath = req["imgpth"],
                strExt     = req["ext"];

            try
            {
                if (!string.IsNullOrEmpty(strImgPath))
                {
                    // If the application provided an alternate image file path, look
                    //   there first.
                    string lcPath = System.IO.Path.Combine(context.Server.MapPath(strImgPath), strExt + ".gif");
                    if (System.IO.File.Exists(lcPath))
                    {
                        context.Response.WriteFile(lcPath);
                    }
                    return;
                }

                object objImg = null;
                try
                {
                    // If we didn't find the icon in the alternate image path, then
                    //   check the local resources.
                    objImg = global::RainstormStudios.Web.HttpHandlers.Properties.Resources.ResourceManager.GetObject(strExt);

                    if (objImg == null)
                    {
                        // If we didn't found it with any method above, just pull the
                        //   'generic' file icon from the resource collection.
                        objImg = global::RainstormStudios.Web.HttpHandlers.Properties.Resources.ResourceManager.GetObject("file");
                    }

                    if (objImg == null)
                    {
                        throw new Exception("Unable to determine any images for file type icon.");
                    }

                    using (MemoryStream ms = new MemoryStream())
                    {
                        ((Bitmap)objImg).Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                        context.Response.StatusCode  = 200;
                        context.Response.ContentType = "image/gif";
                        byte[] imgBts = ms.ToArray();
                        context.Response.OutputStream.Write(imgBts, 0, imgBts.Length);
                    }
                }
                finally
                {
                    if (objImg != null && objImg is IDisposable)
                    {
                        ((IDisposable)objImg).Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                context.AddError(ex);
            }
        }
Ejemplo n.º 21
0
 public ActionResult ServerSide404(int id)
 {
     HttpContext.AddError(new HttpException(404, "Invalid Id - " + id));
     //return View();
     return(null);
 }
Ejemplo n.º 22
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                int numberOfFilesSaves = 0;

                // Get the collection of http handler configuration extensions
                HttpHandlerUploadExtensionElement[] httpCollection = HttpHandlerUploadConfigurationManager.HttpHandlerExtensionElements();
                if (httpCollection != null)
                {
                    // If http extensions exist
                    if (httpCollection.Count() > 0)
                    {
                        // For each configuration
                        foreach (HttpHandlerUploadExtensionElement item in httpCollection)
                        {
                            // Get the current http handler type
                            // and create a instance of the type.
                            Type   httpHandlerType         = BuildManager.GetType(item.HttpHandlerTypeName, true, true);
                            object httpHandlerTypeInstance = Activator.CreateInstance(httpHandlerType);

                            if (HttpHandlerType == null)
                            {
                                HttpHandlerType = this;
                            }

                            if (HttpHandlerType != null)
                            {
                                if (HttpHandlerType.GetType().FullName.ToLower() == httpHandlerTypeInstance.GetType().FullName.ToLower())
                                {
                                    // Get the number of files that a being uploaded.
                                    HttpFileCollection files = context.Request.Files;
                                    if (files != null)
                                    {
                                        // For each file found.
                                        for (int i = 0; i < files.Count; i++)
                                        {
                                            try
                                            {
                                                // Get the current file and file name
                                                // attempt to save the file to the upload path.
                                                HttpPostedFile file     = context.Request.Files[i];
                                                string         fileName = System.IO.Path.GetFileName(file.FileName);
                                                file.SaveAs(item.UploadPath + "\\" + fileName);

                                                // Respond with the file being saved.
                                                context.Response.ContentType = "text/plain";
                                                context.Response.Write("File: {" + fileName + "} saved successfully");

                                                // Increment by one.
                                                numberOfFilesSaves++;
                                            }
                                            catch (Exception ex) { context.AddError(ex); }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }

                // If files have been uploaded.
                if (numberOfFilesSaves > 0)
                {
                    try
                    {
                        // Respond with the number of files saved.
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(numberOfFilesSaves.ToString() + " file(s) have been saved !");
                    }
                    catch { }
                }
                else
                {
                    try
                    {
                        // Respond with no files have been saved.
                        context.Response.ContentType = "text/plain";
                        context.Response.Write("No files have been saved !");
                    }
                    catch { }
                }
            }
            catch (Exception ex)
            {
                try
                {
                    // Respond with the error.
                    context.Response.ContentType = "text/plain";
                    context.Response.Write("Error: " + ex.Message);
                }
                catch { }

                context.AddError(ex);
                LogHandler.WriteTypeMessage(ex.Message, typeof(FileUpload).GetMethod("ProcessRequest"));
            }
        }
Ejemplo n.º 23
0
 public override void AddError(Exception errorInfo)
 {
     _context.AddError(errorInfo);
 }
Ejemplo n.º 24
0
        private void OnAuthenticateRequest(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpContext     context     = application.Context;
            HttpRequest     request     = context.Request;
            HttpResponse    response    = context.Response;

            try
            {
                // Create a new member info type.
                MemberInfo memberInfo = new MemberInfo();

                // Has the user been authenticated
                if (request.IsAuthenticated)
                {
                    // Get the user identity name
                    string userIdentityName = context.User.Identity.Name;

                    // Generate the hash code from the user identity name.
                    memberInfo.UniqueHashcode   = Hashcode.GetHashcode(userIdentityName, HashcodeType.SHA512);
                    memberInfo.UserIdentityName = userIdentityName;

                    // Add the member info to the context collection.
                    if (((MemberInfo)context.Items[memberInfo.UniqueHashcode]) == null)
                    {
                        context.Items.Add(memberInfo.UniqueHashcode, memberInfo);
                    }

                    // Add the new item or set the current member info.
                    Nequeo.Caching.RuntimeCache.Set(memberInfo.UniqueHashcode, memberInfo, (double)600.0);
                }
                else
                {
                    // The user has not been authenticated
                    // the connecting user is anonymous.
                    string userIdentityName = request.AnonymousID;

                    // If no anonymous id is found then
                    // generate a random user idnetity name.
                    if (String.IsNullOrEmpty(userIdentityName))
                    {
                        LowerUpperCaseGenerator password = new LowerUpperCaseGenerator();
                        userIdentityName           = password.Random(30, 30);
                        memberInfo.IsAnonymousUser = true;
                        memberInfo.HasAnonymousID  = false;
                    }
                    else
                    {
                        memberInfo.IsAnonymousUser = true;
                    }

                    // Generate the hash code from the user identity name.
                    memberInfo.UniqueHashcode   = Hashcode.GetHashcode(userIdentityName, HashcodeType.SHA512);
                    memberInfo.UserIdentityName = userIdentityName;

                    // Add the member info to the context collection.
                    if (((MemberInfo)context.Items[memberInfo.UniqueHashcode]) == null)
                    {
                        context.Items.Add(memberInfo.UniqueHashcode, memberInfo);
                    }

                    // Add the new item or set the current member info.
                    Nequeo.Caching.RuntimeCache.Set(memberInfo.UniqueHashcode, memberInfo, (double)600.0);
                }
            }
            catch (Exception ex)
            {
                context.AddError(ex);
                LogHandler.WriteTypeMessage(ex.Message, typeof(Membership).GetMethod("OnAuthenticateRequest"));
            }
        }
Ejemplo n.º 25
0
 public void AddError(Exception errorInfo)
 {
     httpContext.AddError(errorInfo);
 }
Ejemplo n.º 26
0
        //***************************************************************************
        // Public Methods
        //
        public void ProcessRequest(HttpContext context)
        {
            Exception exKeep = null;
            string
                strW      = context.Request.Params["w"],
                strH      = context.Request.Params["h"],
                strFgClr  = context.Request.Params["fg"],
                strBgClr  = context.Request.Params["bg"],
                strFont   = context.Request.Params["fnt"],
                strSize   = context.Request.Params["sz"],
                strStyle  = context.Request.Params["st"],
                strFormat = context.Request.Params["fmt"],
                strAlign  = context.Request.Params["aln"];

            int iW = 0,
                iH = 0;
            Color
                fgClr = Color.Empty,
                bgClr = Color.Empty,
                tdClr = Color.Empty;
            float
                fSZ    = 0.9f;
            int iFgClr = 0,
                iBgClr = 0,
                iTdClr = 0;
            FontStyle
                style     = FontStyle.Regular;
            int iFntStyle = 0;

            System.Web.UI.WebControls.HorizontalAlign
                align = System.Web.UI.WebControls.HorizontalAlign.NotSet;

            try
            {
                if (!int.TryParse(strW, out iW))
                {
                    context.AddError(new ArgumentException("Specified 'Width' is not a valid integer value."));
                }
                if (!int.TryParse(strH, out iH))
                {
                    context.AddError(new ArgumentException("Specified 'Height' is not a valid integer value."));
                }

                if (string.IsNullOrEmpty(strFormat))
                {
                    strFormat = "hh:MM:ss tt";
                }

                if (!string.IsNullOrEmpty(strFgClr))
                {
                    if (int.TryParse(strFgClr, out iFgClr))
                    {
                        fgClr = Color.FromArgb(iFgClr);
                    }
                    else
                    {
                        fgClr = Color.FromName(strFgClr);
                    }
                }
                else
                {
                    fgClr = Color.Black;
                }
                if (fgClr == null || fgClr == Color.Empty)
                {
                    context.AddError(new ArgumentException("Specified foreground color could not be parsed."));
                }

                if (!string.IsNullOrEmpty(strBgClr))
                {
                    if (int.TryParse(strBgClr, out iBgClr))
                    {
                        bgClr = Color.FromArgb(iBgClr);
                    }
                    else
                    {
                        bgClr = Color.FromName(strBgClr);
                    }
                }
                else
                {
                    bgClr = Color.White;
                }
                if (bgClr == null || bgClr == Color.Empty)
                {
                    context.AddError(new ArgumentException("Specified background color could not be parsed."));
                }

                if (!float.TryParse(strSize, out fSZ))
                {
                    context.AddError(new ArgumentException("Specified font size is not a valid floating point integer value."));
                }

                // Try and parse the font style value into an integer as a check to
                //   see what kind of value was passed.
                if (int.TryParse(strStyle, out iFntStyle))
                {
                    // If the value is an integer, it's probably a bit array of
                    //   enumeration flags.
                    style = (FontStyle)iFntStyle;
                }
                else
                {
                    // If the value is not an integer, try and parse the enumeration
                    //   value directly.
                    style = (string.IsNullOrEmpty(strStyle))
                        ? FontStyle.Regular
                        : (FontStyle)Enum.Parse(typeof(FontStyle), strStyle, true);
                }

                align = (string.IsNullOrEmpty(strAlign))
                        ? System.Web.UI.WebControls.HorizontalAlign.NotSet
                        : (System.Web.UI.WebControls.HorizontalAlign)Enum.Parse(typeof(System.Web.UI.WebControls.HorizontalAlign), strAlign);
            }
            catch (Exception ex)
            {
                exKeep = ex;
            }

            using (Bitmap bmp = new Bitmap(iW, iH))
            {
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    if (exKeep == null)
                    {
                        g.Clear(bgClr);
                        using (StringFormat format = new StringFormat(StringFormatFlags.NoWrap))
                        {
                            if (align == System.Web.UI.WebControls.HorizontalAlign.Center)
                            {
                                format.Alignment = StringAlignment.Center;
                            }
                            else if (align == System.Web.UI.WebControls.HorizontalAlign.Right)
                            {
                                format.Alignment = StringAlignment.Far;
                            }
                            else
                            {
                                format.Alignment = StringAlignment.Near;
                            }
                            format.LineAlignment = StringAlignment.Center;
                            format.Trimming      = StringTrimming.EllipsisCharacter;

                            RectangleF rect = new RectangleF(new PointF(0, 0), new SizeF((float)iW, (float)iH));

                            using (Font font = new Font(strFont, fSZ, style))
                                using (Brush brush = new SolidBrush(fgClr))
                                    g.DrawString(DateTime.Now.ToString(strFormat), font, brush, rect, format);
                        }
                    }
                    else
                    {
                        GraphicsUnit gu = g.PageUnit;
                        g.Clear(Color.White);
                        using (Font font = new Font("Tahoma", 6.0f, FontStyle.Regular))
                            g.DrawString(exKeep.Message, font, Brushes.Black, bmp.GetBounds(ref gu));
                    }
                }
                using (System.IO.MemoryStream fs = new System.IO.MemoryStream())
                {
                    bmp.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
                    byte[] strmData = fs.ToArray();
                    context.Response.OutputStream.Write(strmData, 0, strmData.Length);
                }
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// The Custom MainHandlingSection, which will be used to handle The PreRequests
        /// </summary>
        /// <param name="sender">The HttpApplication</param>
        /// <param name="e">The Sended Event Arguments</param>
        public void MainHandlingSection(object sender, EventArgs e)
        {
            HttpApplication httpApplication = (HttpApplication)sender;

            HttpContext httpContext = HttpContext.Current;

            HttpResponse response = httpContext.Response;

            HttpRequest request = httpContext.Request;

            int _errorcount = 0;

            #region Show and Log The Post Body

            if (httpContext.Request.RequestType == "POST")
            {
                if (this.viewStateStatus != null && this.viewStateStatus.Active == true)
                {
                    log.Debug("Processing View State Putting It Back");
                    ReflectionUtils.makeTheRequestFormDataEditable();
                    string viewState = httpContext.Request.Form[VIEW_STATE_TEXT];
                    viewState = this.viewStateStatus.ViewStateStorage.Get(viewState);
                    if (viewState != null)
                    {
                        httpContext.Request.Form[VIEW_STATE_TEXT] =
                            this.viewStateStatus.ViewStateStorage.Get(viewState);
                    }
                    log.Debug("End Of View State Process");
                }
                Stream       httpStream = httpContext.Request.InputStream;
                StreamReader reader     = new StreamReader(httpStream);
                String       rawRequest = reader.ReadToEnd();
                log.Debug("The Raw Request To The Application");
                log.Debug("------------------------------------------------------------------------------");
                log.Debug(rawRequest);
                log.Debug("------------------------------------------------------------------------------");
            }

            #endregion

            if (request.Url.ToString().IndexOf(DefenceMainSettings.DEFAULT_PAGE) > 0)
            {
                response.Write(DoLogTable());
                response.End();
            }
            else if (request.Url.ToString().IndexOf(DefenceMainSettings.DEFAULT_REPORT_PAGE) > 0)
            {
                response.Write(HTMLFormatting.getStatusPage());
                response.End();
            }
            else
            {
                if (log.IsDebugEnabled)
                {
                    ReflectionUtils.MakePropertyStringArray(httpApplication.Request);
                    log.Debug(request.ContentEncoding.EncodingName);
                    log.Debug(request.ContentEncoding.WebName);
                    log.Debug(request.ContentEncoding.WindowsCodePage);
                }

                //Checks The Application Encoding For The Non Utf-8 Requests To Fix The Asp.Net Filtering Bug

                bool DoUpperCheck = (request.ContentEncoding.WebName == "utf-8" ? false : true);

                string lasterror = "";

                #region Ip Block Processor

                if (ipblock == null)
                {
                    ipblock = new ArrayList();
                    IEnumerator enumerator = blocklist.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        if (enumerator.Current is IPRule)
                        {
                            ipblock.Add(enumerator.Current);
                        }
                    }
                    enumerator = ipblock.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        blocklist.Remove(enumerator.Current);
                    }
                }
                //Gets The Ip Of The Current Request
                string ClientIP = httpContext.Request.UserHostAddress;

                #endregion

                bool status = false;

                #region The Form Parameter Processor

                if (HandleForms == 1 && (httpContext.Request.RequestType.Equals("POST")))
                {
                    log.Info("Begin With The Form Handling");

                    for (int formx = 0; formx < httpContext.Request.Form.Count; formx++)
                    {
                        log.Info("Checking Form Object " + httpContext.Request.Form.GetKey(formx) + "-->" + httpContext.Request.Form[formx]);
                        string formPart = OutputConvertors.ClearHalfFullWidth(httpContext.Request.Form[formx], DoUpperCheck);
                        Rule   oldRule  = null;
                        if (!CheckValue(formPart, ref lasterror, out oldRule))
                        {
                            if (oldRule.RuleAction() == (int)Rule.ActionTypes.Warn)
                            {
                                log.Warn("Invalid Objects has been found according to rule " + lasterror);
                            }
                            else if (oldRule.RuleAction() == (int)Rule.ActionTypes.Deny)
                            {
                                log.Error("Invalid Objects has been found according to rule " + lasterror);
                                _errorcount++;
                                httpContext.AddError(new ValidationException("Invalid Objects has been found according to rule " + lasterror));
                            }
                            else if (oldRule.RuleAction() == (int)Rule.ActionTypes.Allow)
                            {
                                log.Info("Invalid Objects has been found according to rule " + lasterror);
                                //_errorcount++;
                            }
                        }
                    }
                    log.Info("End Of The Form Handling");
                }

                #endregion

                #region The QueryString Processor

                if (HandleQueries == 1 && !(status))
                {
                    log.Info("Begin With The Querystring Handling");

                    for (int queryx = 0; queryx < httpContext.Request.QueryString.Count; queryx++)
                    {
                        string queryPart = OutputConvertors.ClearHalfFullWidth(httpContext.Request.QueryString[queryx], DoUpperCheck);
                        Rule   oldRule   = null;
                        if (!CheckValue(queryPart, ref lasterror, out oldRule))
                        {
                            if (oldRule.RuleAction() == (int)Rule.ActionTypes.Warn)
                            {
                                log.Warn("Invalid Objects has been found according to rule " + lasterror);
                            }
                            else if (oldRule.RuleAction() == (int)Rule.ActionTypes.Deny)
                            {
                                log.Error("Invalid Objects has been found according to rule " + lasterror);
                                _errorcount++;
                                httpContext.AddError(new ValidationException("Invalid Objects has been found according to rule " + lasterror));
                            }
                            else if (oldRule.RuleAction() == (int)Rule.ActionTypes.Allow)
                            {
                                log.Info("Invalid Objects has been found according to rule " + lasterror);
                            }
                        }
                    }
                    log.Info("End With The Querystring Handling");
                }

                #endregion

                #region The Cookie Processor

                if (HandleCookies == 1 && !(status))
                {
                    log.Info("Begin With The Cookie Handling");
                    IEnumerator enums = httpContext.Request.Cookies.Keys.GetEnumerator();
                    while (enums.MoveNext())
                    {
                        string     key  = (string)enums.Current;
                        HttpCookie cook = httpContext.Request.Cookies[key];
                        log.Info("The Cookie Object To Be Check :" + cook.Name + "--->" + cook.Value);
                        string cookiePart = OutputConvertors.ClearHalfFullWidth(cook.Value, DoUpperCheck);
                        Rule   oldRule    = null;
                        if (!CheckValue(cookiePart, ref lasterror, out oldRule))
                        {
                            if (oldRule.RuleAction() == (int)Rule.ActionTypes.Warn)
                            {
                                log.Warn("Invalid Objects has been found according to rule " + lasterror);
                            }
                            else if (oldRule.RuleAction() == (int)Rule.ActionTypes.Deny)
                            {
                                log.Error("Invalid Objects has been found according to rule " + lasterror);
                                _errorcount++;
                                httpContext.AddError(new ValidationException("Invalid Objects has been found according to rule " + lasterror));
                            }
                            else if (oldRule.RuleAction() == (int)Rule.ActionTypes.Allow)
                            {
                                log.Info("Invalid Objects has been found according to rule " + lasterror);
                            }
                        }
                    }
                    log.Info("End With The Cookie Handling");
                }

                #endregion

                if (_errorcount > 0)
                {
                    httpApplication.Response.AddHeader("X-DefAppInformation", "Invalid Object Has Been Found");
                }
                else
                {
                    httpApplication.Response.AddHeader("X-DefAppInformation", "Clean Request");
                }
            }
        }
Ejemplo n.º 28
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                // Get the collection of http handler configuration extensions
                HttpHandlerDataExtensionElement[] httpCollection = HttpHandlerDataConfigurationManager.HttpHandlerExtensionElements();
                if (httpCollection != null)
                {
                    // If http extensions exist
                    if (httpCollection.Count() > 0)
                    {
                        // For each configuration
                        foreach (HttpHandlerDataExtensionElement item in httpCollection)
                        {
                            // Get the current http handler type
                            // and create a instance of the type.
                            Type   httpHandlerType         = BuildManager.GetType(item.HttpHandlerTypeName, true, true);
                            object httpHandlerTypeInstance = Activator.CreateInstance(httpHandlerType);

                            if (HttpHandlerType == null)
                            {
                                HttpHandlerType = this;
                            }

                            if (HttpHandlerType != null)
                            {
                                if (HttpHandlerType.GetType().FullName.ToLower() == httpHandlerTypeInstance.GetType().FullName.ToLower())
                                {
                                    // Get the query string associated with this http handler
                                    string value = context.Request.QueryString[item.UrlQueryTextName];

                                    // If a query string is assosicated with
                                    // this http handler then return the
                                    // data from the database and place this
                                    // data in the current session object.
                                    if (!String.IsNullOrEmpty(value))
                                    {
                                        Type dataAccessProviderType = BuildManager.GetType(item.DataAccessProvider, true, true);
                                        ConnectionContext.ConnectionType     connectionType     = ConnectionContext.ConnectionTypeConverter.GetConnectionType(item.ConnectionType);
                                        ConnectionContext.ConnectionDataType connectionDataType = ConnectionContext.ConnectionTypeConverter.GetConnectionDataType(item.ConnectionDataType);

                                        // Build the current data object type and
                                        // the  select data model generic type.
                                        Type dataType        = BuildManager.GetType(item.DataObjectTypeName, true, true);
                                        Type listGenericType = typeof(SelectDataGenericBase <>);

                                        // Create the generic type parameters
                                        // and create the genric type.
                                        Type[] typeArgs = { dataType };
                                        Type   listGenericTypeConstructor = listGenericType.MakeGenericType(typeArgs);

                                        // Create an instance of the data access provider
                                        Nequeo.Data.DataType.IDataAccess dataAccess = ((Nequeo.Data.DataType.IDataAccess)Activator.CreateInstance(dataAccessProviderType));

                                        // Add the genric tyoe contructor parameters
                                        // and create the generic type instance.
                                        object[] parameters  = new object[] { item.ConnectionName, connectionType, connectionDataType, dataAccess };
                                        object   listGeneric = Activator.CreateInstance(listGenericTypeConstructor, parameters);

                                        PropertyInfo propertyInfo = dataType.GetProperty(item.DataObjectPropertyName);
                                        object       valueType    = Convert.ChangeType(value, propertyInfo.PropertyType);

                                        // Get the current object.
                                        Object[] args = new Object[] {
                                            (item.DataObjectPropertyName + " == @0"),
                                            item.ReferenceLazyLoading,
                                            new object[] { valueType }
                                        };

                                        // Add the current data row to the
                                        // business object collection.
                                        object ret = listGeneric.GetType().InvokeMember("SelectDataEntitiesPredicate",
                                                                                        BindingFlags.DeclaredOnly | BindingFlags.Public |
                                                                                        BindingFlags.Instance | BindingFlags.InvokeMethod,
                                                                                        null, listGeneric, args);

                                        // Assign the generic collection data
                                        // to the current session sate with
                                        // the unquie configuration name as the key.
                                        Nequeo.Caching.RuntimeCache.Set(item.Name, ret, (double)600.0);
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }

                        if (HttpHandlerType != null)
                        {
                            // Redirect to the current request.
                            context.Server.Execute(httpCollection[0].ChildPageGroupExecution);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                context.AddError(ex);
                LogHandler.WriteTypeMessage(ex.Message, typeof(GenericData).GetMethod("ProcessRequest"));
            }
        }