/// <summary>
 /// Mock an <see cref="HttpContext"/> object with the base URL, together with appropriate
 /// host headers so that code that doesn't operate under an <see cref="HttpContext"/>
 /// can still use one in replacement.
 /// </summary>
 public static HttpContext FakeHttpContext(this HttpContext realContext)
 {
     var baseUrl = realContext.GetPublicFacingBaseUrl();
     var request = new HttpRequest(string.Empty, baseUrl.ToString(), string.Empty);
     var response = new HttpResponse(null);
     return new HttpContext(request, response);
 }
Example #2
0
        /// <summary>
        /// ����Request��ȡ��ҳ�����ʡ���ĵ�Code
        /// </summary>
        /// <param name="Request"></param>
        /// <returns></returns>
        public static string GetProvinceCode( HttpRequest Request )
        {
            string ProvinceURLTemplate = ConfigurationSettings.AppSettings["ProvinceURLTemplate"];

            string SPRequestURL = Request.Url.AbsoluteUri;
            int Index = ProvinceURLTemplate.IndexOf( "**" );
            if( Index < 0 )
            {
                return  ProvinceCode;
            }
            if( SPRequestURL.Length < ( Index + 2 ) )
            {
                return ProvinceCode;
            }

            string PCode = SPRequestURL.Substring( Index , 2 );
            if( CommonUtility.IsEmpty( PCode ) || PCode.Length != 2 )
            {
                return ProvinceCode;
            }
            else
            {
                return PCode.ToUpper();
            }
        }
 public JObject save(HttpRequest blogForm)
 {
     bool result = false;
     string msg = "";
     if (blogForm != null)
     {
         Blog blog = new Blog();
         base.CopyProperties(blog, blogForm);
         try
         {
             blog.CommitTime = DateTime.Now;
             blog.UpdateTime = DateTime.Now;
             db.Blog.Add(blog);
             db.SaveChanges();
             msg = "保存成功!";
             result = true;
         }
         catch (Exception error)
         {
             msg = "操作失败:" + error.Message + ",请重试!";
         }
     }
     return new JObject(
         new JProperty("success", result),
         new JProperty("msg", msg)
     );
 }
        public JObject update(HttpRequest blogForm)
        {
            bool result = false;
            string msg = "";
            if (blogForm != null)
            {
                string id_str = blogForm["ID"];
                string Username = blogForm["Username"];

                try
                {
                    int id = UtilNumber.Parse(id_str);
                    Blog blog = db.Blog.Single(e => e.ID.Equals(id));
                    base.CopyProperties(blog, blogForm);
                    blog.UpdateTime = DateTime.Now;
                    db.SaveChanges();
                    msg = "保存成功!";
                    result = true;
                }
                catch (Exception error)
                {
                    msg = "操作失败:" + error.Message + ",请重试!";
                }
            }
            return new JObject(
                new JProperty("success", result),
                new JProperty("msg", msg)
            );
        }
Example #5
0
 public string ProcessRequest(HttpRequest request)
 {
     StreamReader reader = new StreamReader(request.InputStream);
     string messageContent = reader.ReadToEnd();//This is the request XML from the USSD Gateway
     //UssdRequestMessage message = GenerateObject(messageContent);//Map the attributes on to the object
     return messageContent;
 }
 private bool CanGZipOrDeflate(HttpRequest request, string encodingHeaderValue)
 {
     string acceptEncoding = request.Headers["Accept-Encoding"];
     if (!string.IsNullOrEmpty(acceptEncoding) && (acceptEncoding.Contains(encodingHeaderValue)))
         return true;
     return false;
 }
		public static FacebookRequest GetFacebookDetailsFromRequest(HttpRequest Request)
        {
            if (Request == null) return null;
            if (Request.RequestType != "POST") return null;
            string rawSignedRequest = Request[SignedRequestParameter];
            return GetFacebookDetailsFromRequest(rawSignedRequest);
        }
        /// <summary>
        /// Parses specified url and returns a RouteData instance. 
        /// Then, for example, you can do: routeData.Values["controller"]
        /// </summary>
        public static RouteData GetRouteData(this RouteCollection routeCollection, string url, string queryString = null)
		{
            var request = new HttpRequest(null, url, queryString);
            var response = new HttpResponse(new StringWriter());
            var httpContext = new HttpContext(request, response);
            return RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
		}
 private void CaptureRouterData(HttpRequest request)
 {
     var mode = (request.QueryString["rptmode"] + "").Trim();
     ReportDataObj.IsLocal = mode == "local" ? true : false;
     ReportDataObj.ReportName = request.QueryString["reportname"] + "";
     string dquerystr = request.QueryString["parameters"] + "";
     if (!String.IsNullOrEmpty(dquerystr.Trim()))
     {
         var param1 = dquerystr.Split(',');
         foreach (string pm in param1)
         {
             var rp = new Parameter();
             var kd = pm.Split('=');
             if (kd[0].Substring(0, 2) == "rp")
             {
                 rp.ParameterName = kd[0].Replace("rp", "");
                 if (kd.Length > 1) rp.Value = kd[1];
                 ReportDataObj.ReportParameters.Add(rp);
             }
             else if (kd[0].Substring(0, 2) == "dp")
             {
                 rp.ParameterName = kd[0].Replace("dp", "");
                 if (kd.Length > 1) rp.Value = kd[1];
                 ReportDataObj.DataParameters.Add(rp);
             }
         }
     }
 }      
Example #10
0
        public CookieHelper()
        {
            HttpContext context = HttpContext.Current;

            _request = context.Request;
            _response = context.Response;
        }
        public RaygunRequestMessage(HttpRequest	request, List<string> ignoredFormNames)
        {
            HostName = request.Url.Host;
              Url = request.Url.AbsolutePath;
              HttpMethod = request.RequestType;
              IPAddress = request.UserHostAddress;
              Data = ToDictionary(request.ServerVariables, Enumerable.Empty<string>());
              QueryString = ToDictionary(request.QueryString, Enumerable.Empty<string>());
              Headers = ToDictionary(request.Headers, ignoredFormNames ?? Enumerable.Empty<string>());
              Form = ToDictionary(request.Form, ignoredFormNames ?? Enumerable.Empty<string>(), true);

              try
              {
            var contentType = request.Headers["Content-Type"];
            if (contentType != "text/html" && contentType != "application/x-www-form-urlencoded" && request.RequestType != "GET")
            {
              int length = 4096;
              string temp = new StreamReader(request.InputStream).ReadToEnd();
              if (length > temp.Length)
              {
            length = temp.Length;
              }

              RawData = temp.Substring(0, length);
            }
              }
              catch (HttpException)
              {
              }
        }
        public static FacebookSignature BuildCanvas(HttpRequest request)
        {
            string[] keys = request.QueryString.Keys
                .OfType<string>()
                .Where(s => s.StartsWith(fbCanvasPrefix))
                .ToArray();
            if (keys.Length > 0)
            {
                var result = new FacebookSignature(keys.ToDictionary(k => k.Substring(fbCanvasPrefix.Length), k => request.QueryString[k])) { Signature = request.QueryString[fbCanvasSignature] };
                result.Secret = Configuration.ConfigurationSection.GetSection().FindByApiKey(request.QueryString[fbCanvasApiKey]).AppSecret;
                return result;
            }

            keys = request.Form.Keys
                .OfType<string>()
                .Where(s => s.StartsWith(fbCanvasPrefix))
                .ToArray();
            if (keys.Length > 0)
            {
                var result = new FacebookSignature(keys.ToDictionary(k => k.Substring(fbCanvasPrefix.Length), k => request.Form[k])) { Signature = request.Form[fbCanvasSignature] };
                result.Secret = Configuration.ConfigurationSection.GetSection().FindByApiKey(request.Form[fbCanvasApiKey]).AppSecret;
                return result;
            }

            return null;
        }
 public ProgressWorkerRequest(HttpWorkerRequest wr, HttpRequest request)
 {
     this._originalWorkerRequest = wr;
     this._request = request;
     this._boundary = this.GetBoundary(this._request);
     this._requestStateStore = new Areas.Lib.UploadProgress.Upload.RequestStateStore(this._request.ContentEncoding);
 }
        public static FacebookSignature BuildConnect(HttpRequest request, string apiKey)
        {
            if (request.Cookies["fbs_" + apiKey] != null)
            {
                var values = request.Cookies["fbs_" + apiKey].Value.Trim('"').Split('&');
                var items = values
                    .Where(v => !v.StartsWith("sig="))
                    .ToDictionary(v => HttpUtility.UrlDecode(v.Split('=')[0]), v => HttpUtility.UrlDecode(v.Split('=')[1]));

                var result = new FacebookSignature(items)
                {
                    Signature = values.First(v => v.StartsWith("sig=")).Substring(4),
                    Secret = Configuration.ConfigurationSection.GetSection().FindByApiKey(apiKey).AppSecret
                };
                return result;
            }

            string[] keys = request.Cookies.Keys
                .OfType<string>()
                .Where(s => s.StartsWith(apiKey + "_"))
                .ToArray();
            if (keys.Length > 0)
            {
                var result = new FacebookSignature(keys.ToDictionary(k => k.Substring(apiKey.Length + 1), k => request.Cookies[k].Value)) {
                    Signature = request.Form[apiKey] ,
                    Secret = Configuration.ConfigurationSection.GetSection().FindByApiKey(apiKey).AppSecret
                };
                return result;
            }

            return null;
        }
        internal bool CustomErrorsEnabled(HttpRequest request)
        {
            try
            {
                if (DeploymentSection.RetailInternal)
                {
                    return true;
                }
            }
            catch
            {
            }
            switch (this.Mode)
            {
                case CustomErrorsMode.RemoteOnly:
                    return !request.IsLocal;

                case CustomErrorsMode.On:
                    return true;

                case CustomErrorsMode.Off:
                    return false;
            }
            return false;
        }
Example #16
0
 public static void DeleteCookie(HttpRequest Request, HttpResponse Response, string name, string value)
 {
     HttpCookie cookie = new HttpCookie(name);
     cookie.Expires = DateTime.Now.AddDays(-1D);
     cookie.Value = value;
     Response.AppendCookie(cookie);
 }
 public JObject save(HttpRequest commentForm)
 {
     bool result = false;
     string msg = "";
     if (commentForm != null)
     {
         Comment comment = new Comment();
         base.CopyProperties(comment, commentForm);
         try
         {
             comment.Comment1 = comment.Content;
             comment.CommitTime = DateTime.Now;
             comment.UpdateTime = DateTime.Now;
             db.Comment.Add(comment);
             db.SaveChanges();
             msg = "保存成功!";
             result = true;
         }
         catch (Exception error)
         {
             msg = "操作失败:" + error.Message + ",请重试!";
         }
     }
     return new JObject(
         new JProperty("success", result),
         new JProperty("msg", msg)
     );
 }
Example #18
0
 public bool ChunkExists(HttpRequest request)
 {
     var identifier = request.QueryString["flowIdentifier"];
     var chunkNumber = int.Parse(request.QueryString["flowChunkNumber"]);
     var chunkFullPathName = GetChunkFilename(chunkNumber, identifier);
     return File.Exists(Path.Combine(filesPath.GetFlowJsTempDirectory(), chunkFullPathName));
 }
        /// <summary>
        /// Creates a new set of capabilities based on the context provided.
        /// </summary>
        /// <param name="request">HttpRequest from the device.</param>
        /// <param name="currentCapabilities">Capabilities already determined by other sources.</param>
        /// <returns>A dictionary of capabilities.</returns>
        internal virtual IDictionary Create(HttpRequest request, IDictionary currentCapabilities)
        {
            // Create the mobile capabilities hashtable.
            IDictionary capabilities = new Hashtable();

            return capabilities;
        }
        private void ReadStream(Stream stream, HttpRequest request, string username, AsyncFileUploadProgress progress, AsyncFileUploadRequestParser parser)
        {
            const int bufferSize = 1024 * 4; // in bytes

            byte[] buffer = new byte[bufferSize];
            while (progress.BytesRemaining > 0)
            {
                int bytesRead = stream.Read(buffer, 0, Math.Min(progress.BytesRemaining, bufferSize));
                progress.TotalBytesRead = bytesRead == 0
                                          ? progress.ContentLength
                                          : (progress.TotalBytesRead + bytesRead);

                if (bytesRead > 0)
                {
                    parser.ParseNext(buffer, bytesRead);
                    progress.FileName = parser.CurrentFileName;
                }

                _cacheService.SetProgress(username, progress);

#if DEBUG
                if (request.IsLocal)
                {
                    // If the request is from local machine, the upload will be too fast to see the progress.
                    // Slow it down a bit.
                    System.Threading.Thread.Sleep(30);
                }
#endif
            }
        }
 private void DoPost(HttpRequest httpRequest, HttpResponse httpResponse)
 {
     Dictionary<string, Stream> files = httpRequest.Files.AllKeys.ToDictionary(n => n, n => httpRequest.Files[n].InputStream);
     DirectRequest[] requests = new DirectRequestsBuilder().Build(new StreamReader(httpRequest.InputStream, httpRequest.ContentEncoding), httpRequest.Form, files);
     var responses = new DirectResponse[requests.Length];
     for(int i = 0; i < requests.Length; i++)
     {
         responses[i] = new DirectHandler(_objectFactory, _metadata).Handle(requests[i]);
     }
     using(var textWriter = new StreamWriter(httpResponse.OutputStream, httpResponse.ContentEncoding))
     {
         if(requests[0].Upload)
         {
             httpResponse.ContentType = "text/html";
             textWriter.Write("<html><body><textarea>");
             SerializeResponse(responses, textWriter);
             textWriter.Write("</textarea></body></html>");
         }
         else
         {
             httpResponse.ContentType = "application/json";
             SerializeResponse(responses, textWriter);
         }
     }
 }
        public static HttpContext FakeHttpContext()
        {
            using (var stringWriter = new StringWriter())
            {
                var httpRequest = new HttpRequest("", "http://abc", "");

                var httpResponse = new HttpResponse(stringWriter);
                var httpContext = new HttpContext(httpRequest, httpResponse);

                var sessionContainer = new HttpSessionStateContainer(
                    "id",
                    new SessionStateItemCollection(), 
                    new HttpStaticObjectsCollection(),
                    10,
                    true,
                    HttpCookieMode.AutoDetect,
                    SessionStateMode.InProc,
                    false);

                httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
                    BindingFlags.NonPublic | BindingFlags.Instance,
                    null,
                    CallingConventions.Standard,
                    new[] {typeof(HttpSessionStateContainer)},
                    null)
                    .Invoke(new object[] {sessionContainer});

                return httpContext;
            }
        }
Example #23
0
        public void Save(string ipAddress, HttpContext context, HttpRequest request, HttpResponse response)
        {
            ELSLog esLog = new ELSLog();
            esLog.ElsIpaddress = ipAddress;
            /*  var x = request.Path;

              x = Getapifunction(x);

              switch (request.HttpMethod)
              {
                  case "GET" :
                      x = "SEE " + x;
                      break;
                  case "POST":
                      x = "SENT " + x;
                      break;
              }*/
            // if (x == "/api/contact")
            // {
            //     x = "sendqueue";}
            esLog.ElsRequest = "[" + DateTime.Now.ToString("dd/MMM/yyyy:HH:mm:ss zz") + "]" + " \"" + request.HttpMethod + " "
                + request.Path + "\" " + response.StatusCode + " " + request.TotalBytes + " \"" + request.UrlReferrer + "\" " + "\"" + request.UserAgent + "\"" + " " + request.Form;

            /*    if (HttpContext.Current.Session != null)
                {
                   // context.Session[Userlog] = esLog;
                    Session[Userlog] = esLog;
                }*/
            context.Items[Userlog] = esLog;
        }
Example #24
0
        /// <summary>
        /// Returns true if the requested resource is one of the typical resources that needn't be processed by the cms engine.
        /// </summary>
        /// <param name="request">HTTP Request</param>
        /// <returns>True if the request targets a static resource file.</returns>
        /// <remarks>
        /// These are the file extensions considered to be static resources:
        /// .css
        ///	.gif
        /// .png 
        /// .jpg
        /// .jpeg
        /// .js
        /// .axd
        /// .ashx
        /// </remarks>
        public static bool IsStaticResource(HttpRequest request)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            string path = request.Path;
            string extension = VirtualPathUtility.GetExtension(path);

            if (extension == null) return false;

            switch (extension.ToLower())
            {
                case ".axd":
                case ".ashx":
                case ".bmp":
                case ".css":
                case ".gif":
                case ".htm":
                case ".html":
                case ".ico":
                case ".jpeg":
                case ".jpg":
                case ".js":
                case ".png":
                case ".rar":
                case ".zip":
                    return true;
            }

            return false;
        }
        // This copy constructor is used by the granular request validation feature. Since these collections are immutable
        // once created, it's ok for us to have two collections containing the same data.
        internal HttpHeaderCollection(HttpHeaderCollection col)
            : base(col) {

            _request = col._request;
            _response = col._response;
            _iis7WorkerRequest = col._iis7WorkerRequest;
        }
        /// <summary>
        /// Converts a standard <see cref="HttpRequest"/> to a <see cref="RequestModel"/>
        /// Copies over: URL, HTTP method, HTTP headers, query string params, POST params, user IP, route params
        /// </summary>
        /// <param name="request"></param>
        /// <param name="session"></param>
        /// <param name="scrubParams"></param>
        /// <returns></returns>
        public static RequestModel CreateFromHttpRequest(HttpRequest request, HttpSessionState session, string[] scrubParams = null)
        {
            var m = new RequestModel();

            m.Url = request.Url.ToString();
            m.Method = request.HttpMethod;
            m.Headers = request.Headers.ToDictionary();
            m.Session = session.ToDictionary();

            m.QueryStringParameters = request.QueryString.ToDictionary();
            m.PostParameters = request.Form.ToDictionary();

            // add posted files to the post collection
            if (request.Files.Count > 0)
                foreach (var file in request.Files.Describe())
                    m.PostParameters.Add(file.Key, "FILE: " + file.Value);

            // if the X-Forwarded-For header exists, use that as the user's IP.
            // that will be the true remote IP of a user behind a proxy server or load balancer
            m.UserIp = IpFromXForwardedFor(request) ?? request.UserHostAddress;

            m.Parameters = request.RequestContext.RouteData.Values.ToDictionary(v => v.Key, v => v.Describe());

            if (scrubParams != null)
            {
                m.Headers = Scrub(m.Headers, scrubParams);
                m.Session = Scrub(m.Session, scrubParams);
                m.QueryStringParameters = Scrub(m.QueryStringParameters, scrubParams);
                m.PostParameters = Scrub(m.PostParameters, scrubParams);
            }

            return m;
        }
Example #27
0
        /// <summary>
        /// 获得浏览器名称(包括版本号)
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GetBrowserName(HttpRequest request)
        {
            HttpBrowserCapabilities browser = request.Browser;

            if (browser == null)
                return "Unknown";

            string text;
            if (browser.Browser == "IE")
            {
                if (browser.Beta)
                    text = string.Concat("Internet Explorer ", browser.Version, "(beta)");
                else
                    text = "Internet Explorer " + browser.Version;
            }
            else
            {
                string userAgent = request.UserAgent;

                if (userAgent != null && userAgent.IndexOf("Chrome") != -1)
                    text = "Chrome";
                else if (userAgent != null && userAgent.IndexOf("Safari") != -1)
                    text = "Safari";
                else if (browser.Beta)
                    text = string.Concat(browser.Browser, " ", browser.Version, "(beta)");
                else
                    text = string.Concat(browser.Browser, " ", browser.Version);
            }

            return text;
        }
Example #28
0
        /// <summary>
        /// Logs the 404 error to a table for later checking 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="settings"></param>
        /// <param name="result"></param>
        public static void Log404(HttpRequest request, FriendlyUrlSettings settings, UrlAction result)
        {
            var controller = new LogController();
            var log = new LogInfo
                {
                    LogTypeKey = EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString(),
                    LogPortalID = (result.PortalAlias != null) ? result.PortalId : -1
                };
            log.LogProperties.Add(new LogDetailInfo("TabId", (result.TabId > 0) ? result.TabId.ToString() : String.Empty));
            log.LogProperties.Add(new LogDetailInfo("PortalAlias",  (result.PortalAlias != null) ? result.PortalAlias.HTTPAlias : String.Empty));
            log.LogProperties.Add(new LogDetailInfo("OriginalUrl",  result.RawUrl));

            if (request != null)
            {
                if (request.UrlReferrer != null)
                {
                    log.LogProperties.Add(new LogDetailInfo("Referer", request.UrlReferrer.AbsoluteUri));
                }
                log.LogProperties.Add(new LogDetailInfo("Url", request.Url.AbsoluteUri));
                log.LogProperties.Add(new LogDetailInfo("UserAgent", request.UserAgent));
                log.LogProperties.Add(new LogDetailInfo("HostAddress", request.UserHostAddress));
                log.LogProperties.Add(new LogDetailInfo("HostName", request.UserHostName));
            }

            controller.AddLog(log);
        }
Example #29
0
 public static PaginationQueryCondition GetCurrentPaginationQueryCondition(HttpRequest request)
 {
     int page = GetCurrentPage(request);
     int size = GetPageSize(request);
     PaginationQueryCondition condition = new PaginationQueryCondition(page, size);
     return condition;
 }
        public void ImageProcessRunner_ReturnsLetterboxedImageWhenSizesAreOfDifferentAspectRatio()
        {
            var request = new HttpRequest("somehandler.ashx", "http://localhost:8080/assets/square.jpg", "sz=60x60;90x90;120x120;180x120");

            this.MockRequest(request, (ms, mockResponse, mockContext) =>
            {
                mockResponse.Setup(m => m.StatusCode).Returns(200);
                mockResponse.Setup(m => m.ContentType).Returns("image/jpeg");

                var context = mockContext.Object;
                new TestImageRunner(context).HandleRequest();

                ms.Seek(0, SeekOrigin.Begin);
                Assert.AreEqual(200, context.Response.StatusCode);
                Assert.AreEqual("image/jpeg", context.Response.ContentType);

                var image = Bitmap.FromStream(context.Response.OutputStream) as Bitmap;
                Assert.AreEqual(180, image.Width);
                Assert.AreEqual(120, image.Height);

                var config = ConfigurationManager.GetSection("SlapCrop") as ImageConfigSection;
                Assert.IsNotNull(config);

                var color = ColorUtil.MakeColorFromHex(config.FillColor);
                Assert.AreNotEqual(0, ResHelper.PixelCount(image, color));
            });
        }
Example #31
0
        private static DataItem DoIt(System.Web.HttpRequest Request, ViewModel vmc, Func <DataItem, DataItem> action)
        {
            DataItem r;

            Request.InputStream.Position = 0;
            using (var sr = new System.IO.StreamReader(Request.InputStream))
            {
                r = action(DataItem.FromJson(sr.ReadToEnd()));
                if (r == null && vmc.ModelState.IsValid)
                {
                    vmc.ModelState.Message = "The request in invalid";
                }
            }

            return(r);
        }
Example #32
0
        public static string apply_groups_(AccessControl.AccessManager mgr, System.Web.HttpRequest req)
        {
            Guid guididx = new System.Guid(req.Params["guididx"]);

            System.Collections.ArrayList ht = new System.Collections.ArrayList();
            for (int i = 0; i < req.Params.Keys.Count; ++i)
            {
                string key = req.Params.Keys[i];
                if (key.IndexOf("gm_", 0) == 0)
                {
                    ht.Add(Int32.Parse(key.Substring(3)));
                }
            }
            mgr.apply_groups(guididx, ht);
            return(build_user_info_(mgr, req));
        }
Example #33
0
    public Article()
    {
        //初始化ASP.NET内置对象
        Response    = System.Web.HttpContext.Current.Response;
        Request     = System.Web.HttpContext.Current.Request;
        Server      = System.Web.HttpContext.Current.Server;
        Session     = System.Web.HttpContext.Current.Session;
        Application = System.Web.HttpContext.Current.Application;

        tools       = ToolsFactory.CreateTools();
        MyBLL       = ArticleFactory.CreateArticle();
        MyArt_Label = Article_LabelFactory.CreateArticle_Label();
        MyLabel     = Product_Article_LabelFactory.CreateProduct_Article_Label();

        articleCate = new ArticleCate();
    }
Example #34
0
 public static string GetCookie(System.Web.HttpRequest request, string cookieName)
 {
     try
     {
         string strValues = "";
         if (request.Cookies[cookieName] != null && request.Cookies[cookieName].Value != null)
         {
             strValues = request.Cookies[cookieName].Value;
         }
         return(strValues);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Example #35
0
        public void ProcessRequest(HttpContext context)
        {
            System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
            string fileName = request.QueryString["fileName"];
            string fileDest = request.QueryString["fileDest"];

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition",
                               "attachment; filename=" + fileName + ";");
            response.TransmitFile(fileDest);
            response.Flush();
            response.End();
        }
Example #36
0
        public static string URLPara(string para, System.Web.HttpRequest req)
        {
            string url = string.Format("http://{0}:8889/Viaje/List", req.ServerVariables["LOCAL_ADDR"]);

            if (para == "carga_link")
            {
                url += "?alone=2";
            }

            if (para == "lista_viaje")
            {
                url += "?alone=1";
            }

            return(url);
        }
Example #37
0
    public Promotion()
    {
        //初始化ASP.NET内置对象
        Response    = System.Web.HttpContext.Current.Response;
        Request     = System.Web.HttpContext.Current.Request;
        Server      = System.Web.HttpContext.Current.Server;
        Session     = System.Web.HttpContext.Current.Session;
        Application = System.Web.HttpContext.Current.Application;


        tools     = ToolsFactory.CreateTools();
        MyBLL     = PromotionFactory.CreatePromotion();
        pub       = new Public_Class();
        myproduct = new Product();
        MyLimits  = PromotionLimitFactory.CreatePromotionLimit();
    }
Example #38
0
 public object[] GetParameters(System.Web.HttpRequest request, ActionDescription action)
 {
     if (request == null)
     {
         throw new ArgumentNullException("request");
     }
     if (action == null)
     {
         throw new ArgumentNullException("action");
     }
     object[] parameters = new object[action.Parameters.Length];
     for (int i = 0; i < request.Files.Count; i++)
     {
         parameters[i] = request.Files[i];
     }
     return(parameters);
 }
Example #39
0
        /// <summary>
        /// Upload the file from the client.
        /// </summary>
        /// <param name="request">The http request object</param>
        /// <param name="filename">The file name to create</param>
        /// <param name="size">The size of the file.</param>
        /// <param name="position">The position in the file to start writing from.</param>
        /// <returns>>True if download was complete; else false</returns>
        private bool UploadFile(System.Web.HttpRequest request, string filename, long size, long position)
        {
            System.IO.Stream localDestination = null;

            try
            {
                // Create the new file and start the transfer process.
                localDestination = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);

                // If an upload position exists.
                if (position > 0)
                {
                    localDestination.Position = position;
                }

                // Transfer the data from the client.
                TransferData(request.InputStream, localDestination, (long)request.ContentLength, _timeout);

                // Close the local file.
                localDestination.Flush();
                localDestination.Close();

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
            finally
            {
                // Clean-up
                if (localDestination != null)
                {
                    localDestination.Close();
                }

                // Clean-up
                if (request != null)
                {
                    if (request.InputStream != null)
                    {
                        request.InputStream.Close();
                    }
                }
            }
        }
Example #40
0
    public ShoppingAsk()
    {
        //初始化ASP.NET内置对象
        Response    = System.Web.HttpContext.Current.Response;
        Request     = System.Web.HttpContext.Current.Request;
        Server      = System.Web.HttpContext.Current.Server;
        Session     = System.Web.HttpContext.Current.Session;
        Application = System.Web.HttpContext.Current.Application;

        tools     = ToolsFactory.CreateTools();
        MyBLL     = ShoppingAskFactory.CreateShoppingAsk();
        MyMem     = MemberFactory.CreateMember();
        MyProduct = ProductFactory.CreateProduct();

        ProApp = new Product();
        MEMApp = new Member();
    }
        public void ProcessRequest(HttpContext context)
        {
            System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
            string fileCode = request.QueryString["fileCode"];

            Dictionary <string, string> FileInfoDict = Find_File_Info(context, fileCode);

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition",
                               "attachment; filename=" + FileInfoDict["fileName"] + ";");
            response.TransmitFile(context.Server.MapPath(FileInfoDict["filePath"]));
            response.Flush();
            response.End();
        }
Example #42
0
    public Shop()
    {
        Response    = System.Web.HttpContext.Current.Response;
        Request     = System.Web.HttpContext.Current.Request;
        Server      = System.Web.HttpContext.Current.Server;
        Session     = System.Web.HttpContext.Current.Session;
        Application = System.Web.HttpContext.Current.Application;

        tools     = ToolsFactory.CreateTools();
        myshop    = SupplierShopFactory.CreateSupplierShop();
        Myproduct = ProductFactory.CreateProduct();

        pub      = new Public_Class();
        addr     = new Addr();
        supplier = new Supplier();
        pageurl  = new PageURL();
    }
Example #43
0
    public static string ClientLanguageGet(
        System.Web.HttpRequest Request
        )
    {
        string res = null;

        //
        if (Request.UserLanguages != null)
        {
            if (0 < Request.UserLanguages.Length)
            {
                res = Request.UserLanguages[0];// the first one, in the favourite-list.
            }// else skip
        }// else skip
        // ready.
        return(res);
    }//
Example #44
0
        private void InvokeAsMene(IHttpRequest request, IHttpResponse response, ScriptExecutor _botClient, string pathd, WriteLineToResponse wrresp)
        {
            {
                {
                    CmdResult res;
                    AddToBody(response, "<xml>");
                    AddToBody(response, "\n<!-- Begin Response !-->");
                    // this is our MeNe handler
                    string username = GetVariable(request, "username", GetVariable(request, "ident", null));
                    string saytext  = GetVariable(request, "saytext", "missed the post");
                    string text     = GetVariable(request, "text", GetVariable(request, "entry", pathd.TrimStart('/')));
                    if (text.Contains("<sapi>"))
                    {
                        // example fragment
                        // <sapi> <silence msec="100" /> <bookmark mark="anim:hello.csv"/> Hi there </sapi>
                        text = text.Replace("<sapi>", " ");
                        text = text.Replace("</sapi>", " ").Trim();
                        while (text.Contains("<"))
                        {
                            int p1 = text.IndexOf("<");
                            int p2 = text.IndexOf(">", p1);
                            if (p2 > p1)
                            {
                                string fragment = text.Substring(p1, (p2 + 1) - p1);
                                text = text.Replace(fragment, " ");
                            }
                        }
                    }

                    if (String.IsNullOrEmpty(username))
                    {
                        //res = _botClient.ExecuteCommand(cmd + " " + text, wrresp.WriteLine);
                        res = _botClient.ExecuteCommand("aiml @withuser " + defaultUser + " - " + text, request,
                                                        wrresp.WriteLine, CMDFLAGS.Foregrounded);
                    }
                    else
                    {
                        res = _botClient.ExecuteCommand("aiml @withuser " + username + " - " + text, request,
                                                        wrresp.WriteLine, CMDFLAGS.Foregrounded);
                    }
                    AddToBody(response, "");
                    AddToBody(response, "\n<!-- End Response !-->");
                    AddToBody(response, "</xml>");
                }
            }
        }
Example #45
0
        /// <summary>
        /// SendMessageToClients
        /// </summary>
        /// <param name="chatState">The current chat state.</param>
        /// <param name="serviceNameSendTo">The service name the unique identifiers are connected to.</param>
        /// <param name="sendTo">Send the data to.</param>
        /// <returns>True if error; else false.</returns>
        private bool SendMessageEx(Chat.ChatHttptState chatState, string serviceNameSendTo, string[] sendTo = null)
        {
            bool isError = true;

            System.Web.HttpRequest  request  = chatState.HttpContext.Request;
            System.Web.HttpResponse response = chatState.HttpContext.Response;

            // If content exists.
            if (request.ContentLength > 0)
            {
                MemoryStream sendBuffer = null;
                try
                {
                    // Read the request stream and write to the send buffer.
                    sendBuffer = new MemoryStream();
                    bool copied = Nequeo.IO.Stream.Operation.CopyStream(request.InputStream, sendBuffer, request.ContentLength, base.RequestTimeout);

                    // If all the data has been copied.
                    if (copied)
                    {
                        // Send the data to client(s) on this machine
                        // and another machine if not on this machine.
                        Common.Helper.SendToReceivers(chatState.Member.UniqueIdentifier, base.ServiceName, serviceNameSendTo, sendTo, sendBuffer.ToArray());
                        isError = false;
                    }
                }
                catch (Exception ex)
                {
                    // Internal error.
                    isError             = true;
                    chatState.ErrorCode = new Exceptions.ErrorCodeException(ex.Message, 500);
                }
                finally
                {
                    // Dispose of the buffer.
                    if (sendBuffer != null)
                    {
                        sendBuffer.Dispose();
                    }
                }
            }

            // True if error else false.
            return(isError);
        }
Example #46
0
        public static string GetViaIP()
        {
            string viaIp = null;

            try
            {
                System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
                if (request.ServerVariables["HTTP_VIA"] != null)
                {
                    viaIp = request.UserHostAddress;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return(viaIp);
        }
        /// <summary>
        /// Gets the string param.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="paramName">Name of the param.</param>
        /// <param name="errorReturn">The error return.</param>
        /// <returns>The param value.</returns>
        public static string GetStringParam(System.Web.HttpRequest request, string paramName, string errorReturn, Boolean IsLostHTML = true)
        {
            string retStr = errorReturn;

            if (request.QueryString[paramName] != null)
            {
                // Html, js in filter parameters ||  filter XSS
                retStr = IsLostHTML ? Common.LostXSS(request.QueryString[paramName]) : request.QueryString[paramName];
            }

            //string retStr = request.QueryString[paramName];
            if (request.Form[paramName] != null)
            {
                retStr = request.Form[paramName];
            }

            return(retStr);
        }
Example #48
0
 internal int ValidateOptionNumericQueryStringParam(System.Web.HttpRequest request, string param)
 {
     try
     {
         if (!request.QueryString[param].Equals(null) && !request.QueryString[param].Equals(""))
         {
             return(Convert.ToInt32(request.QueryString[param]));
         }
         else
         {
             return(0);
         }
     }
     catch
     {
         return(0);
     }
 }
Example #49
0
        /// <summary>
        /// 取得客户的IP数据
        /// </summary>
        /// <param name="Request"></param>
        /// <returns></returns>
        public static string RemoteIP(System.Web.HttpRequest Request)
        {
            string Remote_IP = "";

            try
            {
                if (Request.ServerVariables["HTTP_VIA"] != null)
                {
                    Remote_IP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
                }
                else
                {
                    Remote_IP = Request.ServerVariables["REMOTE_ADDR"].ToString();
                }
            }
            catch { }
            return(Remote_IP);
        }
Example #50
0
        private static void PerformInsertOrUpdate(System.Web.HttpResponse Response, System.Web.HttpRequest Request, ViewModel vmc, bool allowed, string name, Func <DataItem, DataItem> action)
        {
            PerformInsertOrUpdateOrDelete(Response, vmc, allowed, name, () =>
            {
                DataItem r;
                Request.InputStream.Position = 0;
                using (var sr = new System.IO.StreamReader(Request.InputStream))
                {
                    r = action(DataItem.FromJson(sr.ReadToEnd()));
                    if (r == null && vmc.ModelState.IsValid)
                    {
                        vmc.ModelState.Message = "The request in invalid";
                    }
                }

                return(r);
            });
        }
Example #51
0
 /// <summary>
 /// Validate Query String Has Valid Index
 /// </summary>
 /// <param name="RequestObject"></param>
 /// <param name="Index"></param>
 /// <returns></returns>
 public static string QueryStringHasIndex(System.Web.HttpRequest RequestObject, int Index)
 {
     if (RequestObject != null && RequestObject.QueryString.Count != 0 && Index >= 0)
     {
         try
         {
             return(RequestObject.QueryString[Index]);
         }
         catch
         {
             return(null);
         }
     }
     else
     {
         return(null);
     }
 }
        /// <summary>
        /// Gets the string param.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="paramName">Name of the param.</param>
        /// <param name="errorReturn">The error return.</param>
        /// <returns>The param value.</returns>
        public static string GetStringParam(System.Web.HttpRequest request, string paramName, string errorReturn, Boolean IsLostHTML = true)
        {
            string retStr = errorReturn;

            if (request.QueryString[paramName] != null)
            {
                /* 过滤掉传参中的HTML和JS,避免XSS攻击 */
                retStr = IsLostHTML ? Common.LostXSS(request.QueryString[paramName]) : request.QueryString[paramName];
            }

            //string retStr = request.QueryString[paramName];
            if (request.Form[paramName] != null)
            {
                retStr = request.Form[paramName];
            }

            return(retStr);
        }
        public void ProcessRequest(HttpContext context)
        {
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            System.Web.HttpRequest  request  = System.Web.HttpContext.Current.Request;

            string filePath      = request.QueryString["filePath"];
            string fileExtension = Path.GetExtension(filePath);
            string fileName      = Guid.NewGuid().ToString("N");
            string fullName      = fileName + fileExtension;

            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition", "attachment; filename=" + fullName + ";");
            response.TransmitFile(HttpContext.Current.Server.MapPath("/Uploads/" + filePath));
            response.Flush();
            response.End();
        }
Example #54
0
    public SupplierStatistics()
    {
        //初始化ASP.NET内置对象
        Response    = System.Web.HttpContext.Current.Response;
        Request     = System.Web.HttpContext.Current.Request;
        Server      = System.Web.HttpContext.Current.Server;
        Session     = System.Web.HttpContext.Current.Session;
        Application = System.Web.HttpContext.Current.Application;

        tools      = ToolsFactory.CreateTools();
        DBHelper   = SQLHelperFactory.CreateSQLHelper();
        JsonHelper = JsonHelperFactory.CreateJsonHelper();
        product    = new Product();
        pub        = new Public_Class();
        supplier   = new Supplier();
        pageurl    = new PageURL();
        category   = CategoryFactory.CreateCategory();
    }
Example #55
0
        /*
         * private Dictionary<string, string> _contentType = new Dictionary<string, string>()
         * {
         *  { "pdf", "application/pdf"},
         *  {"doc", "application/msword"},
         *  {"exe", "application/x-msdownload"}
         * };
         */

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                if ((System.Web.HttpContext.Current.User != null) &&
                    System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    string path = "~/App_Data";

                    System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
                    string fileType  = request.QueryString["fileType"];
                    string fileName  = request.QueryString["fileName"];
                    string extension = System.IO.Path.GetExtension(fileName);

                    System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                    response.ClearContent();
                    response.Clear();
                    response.ContentType = "application/" + extension;
                    response.AddHeader("Content-Disposition",
                                       "attachment; filename=" + fileName + ";");
                    response.TransmitFile(
                        HttpContext.Current.Server.MapPath(
                            string.Format("{0}/{1}/{2}", path, fileType, fileName)));
                    response.Flush();
                    response.End();
                }
                else
                {
                    context.Response.Redirect("../errors/unauthorized.aspx");
                }
            }
            catch (NullReferenceException)
            {
                context.Response.Redirect("../errors/unauthorized.aspx");
            }
            catch (System.IO.DirectoryNotFoundException)
            {
                context.Response.Redirect("../errors/notfound.aspx");
            }
            catch (System.IO.FileNotFoundException)
            {
                context.Response.Redirect("../errors/notfound.aspx");
            }
        }
Example #56
0
        /// <summary>
        /// Processes the callback.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <param name="request">The request.</param>
        /// <param name="settings">The settings.</param>
        /// <returns></returns>
        public override CallbackInfo ProcessCallback(Api.Models.Order order, System.Web.HttpRequest request, IDictionary <string, string> settings)
        {
            CallbackInfo callbackInfo = null;

            try
            {
                order.MustNotBeNull("order");
                request.MustNotBeNull("request");
                settings.MustNotBeNull("settings");
                settings.MustContainKey("PartnerId", "settings");
                settings.MustContainKey("RoundingMode", "settings");

                // Call the validation URL to check this order
                IdealCheck idealCheck = new IdealCheck(settings["PartnerId"], settings["TestMode"] == "1", request["transaction_id"]);

                decimal orderAmount = order.TotalPrice.Value.WithVat;
                if (idealCheck.Payed)
                {
                    decimal mollieAmount = idealCheck.Amount;

                    // Check if amount that mollie received is equal to the orders amount
                    if (Math.Round(mollieAmount, 0) == Math.Round(orderAmount, Convert.ToInt32(settings["RoundingMode"])))
                    {
                        callbackInfo = new CallbackInfo(orderAmount, request["transaction_id"], PaymentState.Captured);
                        LoggingService.Instance.Info <MollieiDeal>(string.Format("Mollie: Saved and finalized orderId {0}", order.Id));
                    }
                    else
                    {
                        callbackInfo = new CallbackInfo(orderAmount, request["transaction_id"], PaymentState.Error);
                        LoggingService.Instance.Info <MollieiDeal>(string.Format("Mollie: Controle: MollieAmount:{0} OrderAmount: {1} do not match!", mollieAmount, orderAmount));
                    }
                }
                else
                {
                    LoggingService.Instance.Info <MollieiDeal>(string.Format("Mollie: Controle: iDeal status not payed, for cartId {0}!", order.Id));
                }
            }
            catch (Exception exp)
            {
                LoggingService.Instance.Error <MollieiDeal>("ProcessCallback exception", exp);
            }

            return(callbackInfo);
        }
Example #57
0
 internal string ValidateStringQueryStringParameter(System.Web.HttpRequest request, string param)
 {
     try
     {
         if (request.QueryString.Get(param) != null && request.QueryString.Get(param) != "")
         {
             return(request.QueryString.Get(param).ToString());
         }
         else
         {
             System.Web.HttpContext.Current.Response.Redirect(@"../Error.aspx?ErrorDetail=" + "Global_MissingParameter&" + request.QueryString.ToString());
             return(String.Empty);
         }
     }
     catch
     {
         return(String.Empty);
     }
 }
        public NBrightInfo GetCurrentCategoryInfo(int portalId, System.Web.HttpRequest request, int entryId = 0)
        {
            var defcatid = 0;
            var qrycatid = Utils.RequestQueryStringParam(request, "catid");

            if (Utils.IsNumeric(entryId) && entryId > 0)
            {
                defcatid = GetDefaultCatId(entryId);
            }

            if (defcatid == 0 && Utils.IsNumeric(qrycatid))
            {
                defcatid = Convert.ToInt32(qrycatid);
            }

            var objCtrl = new NBrightBuyController();

            return(objCtrl.GetData(defcatid, "CATEGORYLANG"));
        }
Example #59
0
 internal int ValidateNumericQueryStringParameter(System.Web.HttpRequest request, string param)
 {
     try
     {
         if (!request.QueryString[param].Equals(null) && !request.QueryString[param].Equals(""))
         {
             return(Convert.ToInt32(request.QueryString[param]));
         }
         else
         {
             System.Web.HttpContext.Current.Response.Redirect(@"../Error.aspx?ErrorDetail=" + "Global_MissingParameter&" + request.QueryString.ToString());
             return(0);
         }
     }
     catch
     {
         return(0);
     }
 }
Example #60
0
 public void CheckUser(System.Web.HttpRequest Request)
 {
     //判断用户是否登陆
     if (Session["openid"] == null || Session["openid"].ToString() == "")
     {
         if (!string.IsNullOrEmpty(Request.QueryString["code"]))
         {
             string openid = publicclass.getopenidbyOAuth2(Request.QueryString["code"], Request.QueryString["state"]);
             if (openid != "" && !openid.Contains("错误"))
             {
                 Session["openid"] = openid;
             }
         }
         else
         {
             Response.Redirect("~/webpage/lost.aspx", true);
         }
     }
 }