public AspNetRequest(HttpRequestBase request, IPrincipal user)
 {
     _request = request;
     Cookies = new HttpCookieCollectionWrapper(request.Cookies);
     User = user;
     ResolveFormAndQueryString();
 }
        public IEnumerable<Image> GetUploadedImages(HttpRequestBase request, params string[] imageDefinitionKeys)
        {
            List<Image> images = new List<Image>();

            foreach (string inputTagName in request.Files)
            {
                HttpPostedFileBase file = request.Files[inputTagName];
                if (file.ContentLength > 0)
                {
                    // upload the image to filesystem
                    if (IsNotImage(file))
                    {
                        throw new ValidationException(string.Format("File '{0}' is not an image file (*.jpg)", file.FileName));
                    }

                    Image image = new Image
                    {
                        FileName = Guid.NewGuid(),
                        Description = Path.GetFileName(file.FileName)
                    };

                    file.SaveAs(imageFileService.GetFullPath(image.FileNameAsString));

                    // convert the image to main and thumb sizes
                    imageService.CreateSizedImages(image, imageDefinitionKeys);

                    File.Delete(imageFileService.GetFullPath(image.FileNameAsString));

                    images.Add(image);
                }
            }

            return images;
        }
    public bool RequestWantsToBeMobile( HttpRequestBase request )
    {
      if( IsForcedMobileView( request ) )
      {
        cookieHelper.ForceViewMobileSite();
        return true;
      }

      var requestMode = cookieHelper.GetCurrentMode();

      switch( requestMode )
      {
        case SiteMode.NotSet:
          return IsMobileDevice( request );

        case SiteMode.Mobile:
          return true;

        case SiteMode.Desktop:
          return false;

        default:
          return false;
      }
    }
        protected Saml2Request UnbindInternal(HttpRequestBase request, Saml2Request saml2RequestResponse, X509Certificate2 signatureValidationCertificate)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            if (saml2RequestResponse == null)
                throw new ArgumentNullException("saml2RequestResponse");

            if (signatureValidationCertificate == null)
            {
                throw new ArgumentNullException("signatureValidationCertificate");
            }
            if (signatureValidationCertificate.PublicKey == null)
            {
                throw new ArgumentException("No Public Key present in Signature Validation Certificate.");
            }
            if (!(signatureValidationCertificate.PublicKey.Key is DSA || signatureValidationCertificate.PublicKey.Key is RSACryptoServiceProvider))
            {
                throw new ArgumentException("The Public Key present in Signature Validation Certificate must be either DSA or RSACryptoServiceProvider.");
            }

            saml2RequestResponse.SignatureValidationCertificate = signatureValidationCertificate;

            return saml2RequestResponse;
        }
Beispiel #5
1
        // { 
        //   'format':'basic'
        //   'url':'http://host/repository',
        //   'is_hg':true // optional
        // }
        public override DeployAction TryParseDeploymentInfo(HttpRequestBase request, JObject payload, string targetBranch, out DeploymentInfo deploymentInfo)
        {
            deploymentInfo = null;
            if (!String.Equals(payload.Value<string>("format"), "basic", StringComparison.OrdinalIgnoreCase))
            {
                return DeployAction.UnknownPayload;
            }

            string url = payload.Value<string>("url");
            if (String.IsNullOrEmpty(url))
            {
                return DeployAction.UnknownPayload;
            }

            string scm = payload.Value<string>("scm");
            bool is_hg;
            if (String.IsNullOrEmpty(scm))
            {
                // SSH hg@... vs git@...
                is_hg = url.StartsWith("hg@", StringComparison.OrdinalIgnoreCase);
            }
            else
            {
                is_hg = String.Equals(scm, "hg", StringComparison.OrdinalIgnoreCase);
            }

            deploymentInfo = new DeploymentInfo();
            deploymentInfo.RepositoryUrl = url;
            deploymentInfo.RepositoryType = is_hg ? RepositoryType.Mercurial : RepositoryType.Git;
            deploymentInfo.Deployer = GetDeployerFromUrl(url);
            deploymentInfo.TargetChangeset = DeploymentManager.CreateTemporaryChangeSet(message: "Fetch from " + url);

            return DeployAction.ProcessDeployment;
        }
        /// <summary>
        /// Maps data from the media file edit form to the media file object.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public static void MapFile(HttpRequestBase request, string fieldSuffix, MediaFile file)
        {
            HttpPostedFileBase hpf = request.Files["file" + fieldSuffix];
            string externalfilename = request.Params["externalfile" + fieldSuffix];
            string filename = hpf.ContentLength == 0 ? externalfilename : hpf.FileName;
            file.Title = request.Params["title" + fieldSuffix];
            file.Description = request.Params["description" + fieldSuffix];
            file.SortIndex = ComLib.Extensions.NameValueExtensions.GetOrDefault<int>(request.Params, "SortIndex", file.SortIndex);
            file.IsPublic = true;
            if (file.LastWriteTime == DateTime.MinValue)
                file.LastWriteTime = DateTime.Now;

            // No Content?
            if (hpf.ContentLength == 0 && string.IsNullOrEmpty(externalfilename))
                return;

            // Get the file as a byte[]
            if (hpf.ContentLength > 0)
                file.Contents = ComLib.Web.WebUtils.GetContentOfFileAsBytes(hpf);

            // This will autoset the Name and Extension properties.
            file.FullNameRaw = filename;
            file.Length = hpf.ContentLength;
            
            // Set up the thumbnail.
            if (!file.IsExternalFile && file.IsImage)
                file.ToThumbNail(processLocalFileSystemFile: true);
        }
Beispiel #7
1
		public virtual OutgoingWebResponse VerifyAccess(HttpRequestBase httpRequestInfo, out AccessToken accessToken) {
			Requires.NotNull(httpRequestInfo, "httpRequestInfo");

			AccessProtectedResourceRequest request = null;
			try {
				if (this.Channel.TryReadFromRequest<AccessProtectedResourceRequest>(httpRequestInfo, out request)) {
					accessToken = this.AccessTokenAnalyzer.DeserializeAccessToken(request, request.AccessToken);
					ErrorUtilities.VerifyHost(accessToken != null, "IAccessTokenAnalyzer.DeserializeAccessToken returned a null reslut.");
					if (string.IsNullOrEmpty(accessToken.User) && string.IsNullOrEmpty(accessToken.ClientIdentifier)) {
						Logger.OAuth.Error("Access token rejected because both the username and client id properties were null or empty.");
						ErrorUtilities.ThrowProtocol(OAuth2Strings.InvalidAccessToken);
					}

					return null;
				} else {
					var response = new UnauthorizedResponse(new ProtocolException(OAuth2Strings.MissingAccessToken));

					accessToken = null;
					return this.Channel.PrepareResponse(response);
				}
			} catch (ProtocolException ex) {
				var response = request != null ? new UnauthorizedResponse(request, ex) : new UnauthorizedResponse(ex);

				accessToken = null;
				return this.Channel.PrepareResponse(response);
			}
		}
Beispiel #8
1
        //Adapted from Noah Heldman's work at http://stackoverflow.com/a/10407992/17027
        public static bool GetClientIpAddress(HttpRequestBase request, out string remote)
        {
            try
            {
                var userHostAddress = request.UserHostAddress;

                //Attempt to parse.  If it fails, we catch below and return "0.0.0.0"
                //Could use TryParse instead, but I wanted to catch all exceptions
                IPAddress.Parse(userHostAddress);

                var xForwardedFor = request.ServerVariables.AllKeys.Contains("HTTP_X_FORWARDED_FOR") ? request.ServerVariables["HTTP_X_FORWARDED_FOR"] :
                    request.ServerVariables.AllKeys.Contains("X_FORWARDED_FOR") ? request.ServerVariables["X_FORWARDED_FOR"] : "";

                if (string.IsNullOrWhiteSpace(xForwardedFor))
                {
                    remote = userHostAddress;
                    return true;
                }

                //Get a list of public ip addresses in the X_FORWARDED_FOR variable
                var publicForwardingIps = xForwardedFor.Split(',').Where(ip => !IsPrivateIpAddress(ip)).ToList();

                //If we found any, return the last one, otherwise return the user host address
                remote = publicForwardingIps.Any() ? publicForwardingIps.Last() : userHostAddress;
                return true;
            }
            catch (Exception)
            {
                //Always return all zeroes for any failure
                remote = "0.0.0.0";
                return false;
            }
        }
        public NavigationModel(HttpRequestBase httpRequest)
        {
            if(httpRequest == null)
                throw new ArgumentNullException("httpRequest");

            this._currentFilePath = httpRequest.FilePath;
        }
Beispiel #10
1
        public static string GetClientIp(HttpRequestBase request)
        {
            try
            {
                var userHostAddress = request.UserHostAddress ?? string.Empty;

                // Attempt to parse.  If it fails, we catch below and return "0.0.0.0"
                // Could use TryParse instead, but I wanted to catch all exceptions
                if (!string.IsNullOrEmpty(userHostAddress))
                    IPAddress.Parse(userHostAddress);

                string xForwardedFor = request.ServerVariables["REMOTE_ADDR"];
                if (string.IsNullOrEmpty(xForwardedFor)) xForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];

                if (string.IsNullOrEmpty(xForwardedFor))
                    return userHostAddress;

                // Get a list of public ip addresses in the X_FORWARDED_FOR variable
                var publicForwardingIps = xForwardedFor.Split(',').Where(ip => !IsPrivateIpAddress(ip)).ToList();

                // If we found any, return the last one, otherwise return the user host address
                return publicForwardingIps.Any() ? publicForwardingIps.Last() : userHostAddress;
            }
            catch (Exception)
            {
                // Always return all zeroes for any failure (my calling code expects it)
                return "0.0.0.0";
            }
        }
Beispiel #11
1
        public void WriteLog(string userAgent, HttpRequestBase request, string platform, string browser, string user)
        {
            if (request == null) return;

            if (userAgent.IsNotSet())
            {
                LegacyDb.eventlog_create(null, this, "UserAgent string is empty.", EventLogTypes.Warning);
            }
            else
            {
                if (request.Browser != null && platform.ToLower().Contains("unknown") ||
                    browser.ToLower().Contains("unknown"))
                {
                    LegacyDb.eventlog_create(
                        null,
                        this,
                        "Unhandled UserAgent string:'{0}' /r/nPlatform:'{1}' /r/nBrowser:'{2}' /r/nSupports cookies='{3}' /r/nSupports EcmaScript='{4}' /r/nUserID='{5}'."
                            .FormatWith(
                                userAgent,
                                request.Browser.Platform,
                                request.Browser.Browser,
                                request.Browser.Cookies,
                                request.Browser.EcmaScriptVersion.ToString(),
                                user ?? String.Empty),
                        EventLogTypes.Warning);
                }
            }
        }
        protected override void Context()
        {
            AccountService = MockRepository.GenerateStub<IAccountService>();

            Identity = new FakeIdentity(Username);
            _user = new FakePrincipal(Identity, null);

            HttpRequest = MockRepository.GenerateStub<HttpRequestBase>();
            HttpContext = MockRepository.GenerateStub<HttpContextBase>();
            HttpContext.Stub(x => x.Request).Return(HttpRequest);
            HttpContext.User = _user;

            _httpResponse = MockRepository.GenerateStub<HttpResponseBase>();
            _httpResponse.Stub(x => x.Cookies).Return(new HttpCookieCollection());
            HttpContext.Stub(x => x.Response).Return(_httpResponse);

            Logger = MockRepository.GenerateStub<ILogger>();
            WebAuthenticationService = MockRepository.GenerateStub<IWebAuthenticationService>();

            MappingEngine = MockRepository.GenerateStub<IMappingEngine>();
            AccountCreator = MockRepository.GenerateStub<IAccountCreator>();

            AccountController = new AccountController(AccountService, Logger, WebAuthenticationService, MappingEngine, null, AccountCreator);
            AccountController.ControllerContext = new ControllerContext(HttpContext, new RouteData(), AccountController);
        }
        /// <summary>
        /// Returns a hash of the supplied file.
        /// </summary>
        /// <param name="fname">The name of the file.</param>
        /// <param name="request">The current HttpRequest.</param>
        /// <returns>A Guid representing the hash of the file.</returns>
        public static Guid GetFileHash(string fname, HttpRequestBase request)
        {
            Guid hash;
            var localPath = request.RequestContext.
                HttpContext.Server.MapPath(fname.Replace('/', '\\'));

            using (var ms = new MemoryStream())
            {
                using (var fs = new FileStream(localPath,
                    FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    StreamCopy(fs, ms);
                }

                hash = new Guid(Md5.ComputeHash(ms.ToArray()));
                Guid check;
                if (!FileHash.TryGetValue(localPath, out check))
                {
                    FileHash.Add(localPath, hash);
                }
                else if (check != hash)
                {
                    FileHash[localPath] = hash;
                }
            }

            return hash;
        }
        public bool HandleResult( IResult result, IFormatInfo outputFormat, HttpRequestBase request, HttpResponseBase response )
        {
            response.AddHeader("Accept-Ranges", "bytes");

            Range range;
            if ( !TryGetRequestedRange( request, out range ) )
            {
                return false;
            }

            if (!ValidateIfRangeHeader(request, result))
            {
                return false;
            }

            var offset = range.Start ?? 0;
            var end = range.End.HasValue ? range.End.Value : result.ContentLength - 1;
            var length = end - offset + 1;

            response.AddHeader( "Content-Range", "bytes " + offset + "-" + end + "/" + result.ContentLength );
            response.StatusCode = 206;

            result.Serve( response, offset, length );
            return true;
        }
        private bool TryGetRequestedRange( HttpRequestBase request, out Range range )
        {
            var rangeHeader = request.Headers[ "Range" ];
            if ( string.IsNullOrEmpty( rangeHeader ) )
            {
                range = null;
                return false;
            }

            if ( !rangeHeader.StartsWith( RangeByteHeaderStart ) )
            {
                range = null;
                return false;
            }

            var parts = rangeHeader.Substring( RangeByteHeaderStart.Length ).Split( '-' );

            if ( parts.Length != 2 )
            {
                range = null;
                return false;
            }

            range = new Range
            {
                Start = string.IsNullOrEmpty( parts[ 0 ] ) ? (long?) null : long.Parse( parts[ 0 ] ),
                End = string.IsNullOrEmpty( parts[ 1 ] ) ? (long?) null : long.Parse( parts[ 1 ] )
            };
            return true;
        }
        public static bool PopulatePhoneNumbers(UserViewModel uvm, HttpRequestBase request, out string validationError, out string flashErrorMessage)
        {
            flashErrorMessage = null;
            validationError = null;

            if (uvm == null || request == null)
                return false;

            // Find and (re)populate phone numbers.
            foreach (var phoneKey in request.Params.AllKeys.Where(x => x.StartsWith("phone_number_type"))) {
                var phoneTypeId = request[phoneKey].TryToInteger();
                var index = Regex.Match(phoneKey, @"\d+").Value;
                var phoneNumber = request[string.Format("phone_number[{0}]", index)];
                if (phoneTypeId.HasValue) {
                    // TODO: If the number contains an "x", split it out into number and extension.
                    var parts = phoneNumber.ToLower().Split('x');
                    string extension = "";
                    string number = Regex.Replace(parts[0], @"[^\d]", "");
                    if (parts.Length > 1) {
                        // Toss all the rest into the extension.
                        extension = string.Join("", parts.Skip(1));
                    }
                    // If the phone number is blank, just toss the entry - each form usually gets
                    // a blank spot added to it in case the user wants to add numbers, but he doesn't have to.
                    if (!string.IsNullOrEmpty(phoneNumber)) {
                        uvm.User.PhoneNumbers.Add(new PhoneNumber(request[string.Format("phone_number_id[{0}]", index)].TryToInteger(), phoneTypeId.Value, number, extension));
                    }
                } else {
                    flashErrorMessage = "Invalid phone number type - please select a valid phone type from the dropdown list.";
                    validationError = "Invalid phone type.";
                    return false;
                }
            }
            return true;
        }
Beispiel #17
1
        public static ListenTo.Shared.DO.Image GetImageFromRequest(HttpRequestBase request, string key)
        {
            ListenTo.Shared.DO.Image image = null;
            HttpPostedFileBase file = Helpers.FileHelpers.GetFileFromRequest(request, key);

            if (file != null && file.ContentLength != 0 )
            {
                try
                {
                    Byte[] fileData = GetContentFromHttpPostedFile(file);

                    if (IsFileImage(fileData))
                    {
                        image = ImageHelpers.GetImage(fileData);
                    }
                }
                catch (Exception e)
                {
                    //The file is not an image even though the headers are correct!
                    //Log the exception
                    throw;
                }
            }
            return image;
        }
        ///<returns>Can seek now?</returns>
        private bool TryEnableBuffering(HttpRequest httpRequest, long?contentLength, out Stream bodyStream)
        {
            bodyStream = null;

            if (MaxContentLength >= 0 && !contentLength.HasValue)
            {
                InternalLogger.Debug("AspNetRequestPostedBody: body stream cannot seek with unknown ContentLength");
                return(false);
            }

            int bufferThreshold = MaxContentLength <= 0 ? Size64KiloBytes : MaxContentLength;

            if (MaxContentLength == 0 && contentLength > bufferThreshold)
            {
                InternalLogger.Debug("AspNetRequestPostedBody: body stream cannot seek and stream is too big. ContentLength={0}", contentLength);
                return(false);
            }

            bodyStream = EnableRewind(httpRequest, bufferThreshold);
            if (bodyStream?.CanSeek != true)
            {
                InternalLogger.Debug("AspNetRequestPostedBody: body stream cannot seek");
                return(false);
            }

            return(true);
        }
Beispiel #19
0
        /*public static bool VerifyRecaptcha(string Response)
         * {
         *  IRecaptcha<RecaptchaV2Result> recaptcha = new RecaptchaV2(new RecaptchaV2Data()
         *  {
         *      Secret = RecaptchaSecret,
         *      Response = Response
         *  });
         *  var result = recaptcha.Verify();
         *  return result.Success;
         * }
         *
         * public static bool VerifyRecaptcha()
         * {
         *  IRecaptcha<RecaptchaV2Result> recaptcha = new RecaptchaV2(new RecaptchaV2Data()
         *  {
         *      Secret = RecaptchaSecret
         *  });
         *  var result = recaptcha.Verify();
         *  return result.Success;
         * }*/

        public static string RootUrl(System.Web.HttpRequestBase request)
        {
            var r = ConfigurationManager.AppSettings["WebsiteRootUrl"]?.ToString();

            return(r);
            //return request.Url.Scheme + "://" + request.Url.Authority + request.ApplicationPath.TrimEnd('/');
        }
Beispiel #20
0
        public static string GetString(this System.Web.HttpRequestBase request, string name, string defaultValue, bool autoDecode)
        {
            try
            {
                var s = request[name];

                if (string.IsNullOrWhiteSpace(s))
                {
                    return(defaultValue);
                }
                else
                {
                    if (autoDecode)
                    {
                        return(HttpUtility.UrlDecode(s));
                    }
                    else
                    {
                        return(s);
                    }
                }
            }
            catch (Exception)
            {
                return(defaultValue);
            }
        }
Beispiel #21
0
        public static bool GetBool(this System.Web.HttpRequestBase request, string name, bool defaultValue = false)
        {
            try
            {
                var s = request[name];

                if (string.IsNullOrWhiteSpace(s))
                {
                    return(defaultValue);
                }
                else
                {
                    var s1 = HttpUtility.UrlDecode(s).Trim();

                    if (string.Compare(s1, "true", true) == 0)
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            catch (Exception)
            {
                return(defaultValue);
            }
        }
Beispiel #22
0
        /// <summary>
        /// Checks whether the specified request is a debug mode request (unminified JavaScript) or 
        /// release mode (minified JavaScript)
        /// </summary>
        /// <param name="request">HTTP request</param>
        /// <param name="sendCacheHeaders">Whether to send caching headers</param>
        /// <param name="sendFileNotFound">Whether to send a file not found error</param>
        /// <returns><c>true</c> if the specified request is a debug mode request</returns>
        public static bool CheckDebugMode(HttpRequestBase request, out bool sendCacheHeaders, out bool sendFileNotFound)
        {
            sendFileNotFound = false;
            sendCacheHeaders = false;

            // Check if any path info was provided
            var pathInfo = request.PathInfo.Split('/');
            if (pathInfo.Length < 2)
            {
                // Not enough path info for a full path - User could be hitting routejs.axd directly with no params
                // In this case, just serve debug version of the JavaScript
                return true;
            }

            switch (pathInfo.Last())
            {
                case "router.min.js":
                    sendCacheHeaders = true;
                    return false;

                case "router.js":
                    sendCacheHeaders = true;
                    return true;

                default:
                    // Send a 404, invalid file name
                    sendFileNotFound = true;
                    return true;
            }
        }
        public static string FullApplicationPath(HttpRequestBase request)
        {
            var absolutePath = request.Url.AbsolutePath;
            if (absolutePath == "/")
            {
                return request.Url.AbsoluteUri;
            }

            var path = request.Url.AbsoluteUri.Replace(absolutePath, string.Empty);

            var queryIndex = path.IndexOf("?");
            if (queryIndex > 0)
            {
                path = path.Remove(queryIndex);
            }

            path = path + request.ApplicationPath;

            if (!path.EndsWith("/"))
            {
                path += "/";
            }

            return path;
        }
        protected override string Edit(HttpRequestBase request)
        {
            var res = "";

            try
            {
                StudentPresentation existingStudentPresentation =
                    (from sp in _sessionManager.DbContext.StudentPresentations
                     where sp.UserId == _session.UserId &&
                     sp.ContextId == _session.ContextId
                     select sp).SingleOrDefault();

                existingStudentPresentation.Name = request.Form["name"].ToString();
                existingStudentPresentation.LocationName = request.Form["location"].ToString();
                existingStudentPresentation.LocationLat = Double.Parse(request.Form["latitude"].ToString(), CultureInfo.InvariantCulture);
                existingStudentPresentation.LocationLong = Double.Parse(request.Form["longitude"].ToString(), CultureInfo.InvariantCulture);
                existingStudentPresentation.Presentation = request.Form["presentation"].ToString();

                _sessionManager.DbContext.SaveChanges();
            }
            catch (Exception e)
            {
                _log.Error("Failed to edit existing student presentation: " + e.Message);
                throw new Exception("Failed to edit existing student presentation.", e);
            }

            return res;
        }
        public WorkflowMessageService(
			IMessageTemplateService messageTemplateService,
            IQueuedEmailService queuedEmailService, 
			ILanguageService languageService,
            ITokenizer tokenizer, 
			IEmailAccountService emailAccountService,
            IMessageTokenProvider messageTokenProvider,
			IStoreService storeService,
			IStoreContext storeContext,
            EmailAccountSettings emailAccountSettings,
            IEventPublisher eventPublisher,
            IWorkContext workContext,
            HttpRequestBase httpRequest,
			IDownloadService downloadServioce)
        {
            this._messageTemplateService = messageTemplateService;
            this._queuedEmailService = queuedEmailService;
            this._languageService = languageService;
            this._tokenizer = tokenizer;
            this._emailAccountService = emailAccountService;
            this._messageTokenProvider = messageTokenProvider;
            this._storeService = storeService;
            this._storeContext = storeContext;
            this._emailAccountSettings = emailAccountSettings;
            this._eventPublisher = eventPublisher;
            this._workContext = workContext;
            this._httpRequest = httpRequest;
            this._downloadServioce = downloadServioce;
        }
        // Adds do-not-cache headers to the specified HTTP response (which is expected to result in a file-save
        // operation by the browser) in such a way that the IE browser is still able to save the file.
        // (TODO: if we have more file-save action results than just CsvActionResult, this method can be lifted to
        // a common location and be used by all of them.)
        private static void AddDoNotCacheHeadersToFileSaveResponse(HttpResponseBase response, HttpRequestBase request)
        {
            // Get the browser's internal identifier (from .NET browser definition file).
            var browserId = request.Browser.Id;

            // Detect if the browser is a problem version of IE (= IE 7 and 8; IE 6 and lower aren't supported by this
            // website).
            var problemIEVersion = false;
            if ((browserId.Equals("IE7", StringComparison.OrdinalIgnoreCase)) ||
                (browserId.Equals("IE8", StringComparison.OrdinalIgnoreCase)))
            {
                problemIEVersion = true;
            }

            // Add do-not-cache response headers.
            if (!problemIEVersion)
            {
                // Add the website's standard do-not-cache headers.
                NoCacheAttribute.AddResponseHeaders(response);
            }
            else
            {
                // For problem IE versions...   reference: http://stackoverflow.com/a/5084395
                response.AppendHeader("Last-Modified",
                    DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture)); // RFC 1123 format
                response.AppendHeader("Expires", "-1");
                response.AppendHeader("Cache-Control", "must-revalidate, private");
                response.AppendHeader("Vary", "*");
            }
        }
        void SendAsset(HttpRequestBase request, HttpResponseBase response, Bundle bundle, IAsset asset)
        {
            response.ContentType = bundle.ContentType;

            var actualETag = "\"" + asset.Hash.ToHexString() + "\"";
            if(request.RawUrl.Contains(asset.Hash.ToHexString())) {
                CacheLongTime(response, actualETag);
            }
            else {
                NoCache(response);
            }

            var givenETag = request.Headers["If-None-Match"];
            if (!disableHashCheck && givenETag == actualETag)
            {
                SendNotModified(response);
            }
            else
            {
                using (var stream = asset.OpenStream())
                {
                    stream.CopyTo(response.OutputStream);
                }
            }
        }
Beispiel #28
0
        /// <summary>
        /// Identifies the currently selected path, starting from the selected node.
        /// </summary>
        /// <param name="menuItems">All the menuitems in the navigation menu.</param>
        /// <param name="currentRequest">The currently executed request if any</param>
        /// <param name="currentRouteData">The current route data.</param>
        /// <returns>A stack with the selection path being the last node the currently selected one.</returns>
        public static Stack<MenuItem> SetSelectedPath(IEnumerable<MenuItem> menuItems, HttpRequestBase currentRequest, RouteValueDictionary currentRouteData) {
            // doing route data comparison first and if that fails, fallback to string-based URL lookup
            var path = SetSelectedPath(menuItems, currentRequest, currentRouteData, false) 
                    ?? SetSelectedPath(menuItems, currentRequest, currentRouteData, true);

            return path;
        }
Beispiel #29
0
        //Following me
        public string GetLoggedInUsername(System.Web.HttpRequestBase request)
        {
            HttpCookie myCookie = new HttpCookie("rfs.username");

            myCookie = request.Cookies["rfs.username"];
            if (myCookie != null)
            {
                HttpCookie myCookie2 = new HttpCookie("rfs.logincode");
                myCookie2 = request.Cookies["rfs.logincode"];
                if (myCookie2 != null)
                {
                    string             connectionstring = ConfigurationManager.AppSettings["dbconnectionstring"];
                    IdentityValidation idv       = new IdentityValidation(connectionstring);
                    string             user      = HttpUtility.UrlDecode(myCookie.Value);
                    string             logincode = HttpUtility.UrlDecode(myCookie2.Value);
                    if (idv.CheckLoginCode(user, logincode))
                    {
                        // create session
                        //Session[myCookie.Value] = "loggedIn";
                        return(user);
                    }

                    // redirect to home page

                    //username = Server.HtmlEncode(myCookie.Value);
                    //if (Session[username].ToString() == "loggedIn")
                    //{

                    //}
                }
            }
            return(string.Empty);
        }
Beispiel #30
0
        /// <summary>
        /// 如果不是移动端访问,跳转到PC端页面
        /// </summary>
        /// <param name="filterContext"></param>
        /// <returns></returns>
        private string GetPCUrlString(HttpRequestBase request)
        {
            var originalUrl = request.Url.OriginalString;
            var host = request.Url.Host;
            var port = request.Url.Port;
            var mobileDomain = string.Empty;
            var pcDomain = string.Empty;

            if (port == 80)
            {
                mobileDomain = host + "/mobile";
                pcDomain = host;
            }
            else
            {
                mobileDomain = host + ":" + port + "/mobile";
                pcDomain = host + ":" + port;
            }

            if (port == 80)
            {
                string portInUrl = ":80";
                int portIndex = originalUrl.IndexOf(portInUrl);

                if (portIndex != -1)
                {
                    originalUrl = originalUrl.Remove(portIndex, portInUrl.Length);
                }
            }

            return originalUrl.Replace(mobileDomain, pcDomain);
        }
        public PriceCalculationService(
            IDiscountService discountService,
			ICategoryService categoryService,
            IProductAttributeParser productAttributeParser,
			IProductService productService,
			ShoppingCartSettings shoppingCartSettings, 
            CatalogSettings catalogSettings,
			IProductAttributeService productAttributeService,
			IDownloadService downloadService,
			ICommonServices services,
			HttpRequestBase httpRequestBase,
			ITaxService taxService)
        {
            this._discountService = discountService;
            this._categoryService = categoryService;
            this._productAttributeParser = productAttributeParser;
            this._productService = productService;
            this._shoppingCartSettings = shoppingCartSettings;
            this._catalogSettings = catalogSettings;
            this._productAttributeService = productAttributeService;
            this._downloadService = downloadService;
            this._services = services;
            this._httpRequestBase = httpRequestBase;
            this._taxService = taxService;
        }
 public static string GetUserName(HttpRequestBase request,HttpContextBase context)
 {
     //return "poweradmin";
     //return "Administrator";
     //return "wjl";
     return request.IsAuthenticated ? context.User.Identity.Name.GetDomainName() : string.Empty;
 }
        public TaskTypeResult ProcessFormCollection(int taskID, int userID, FormCollection collection, HttpRequestBase request)
        {
            DidacheDb db = new DidacheDb();

            Task task = db.Tasks.Find(taskID);
            UserTaskData data = db.UserTasks.SingleOrDefault(d => d.TaskID == taskID && d.UserID == userID);

            // CREATE POST
            InteractionThread thread = new InteractionThread();
            thread.UserID = userID;
            thread.TotalReplies = 0;
            thread.Subject = "Assignment: " + task.Name;
            thread.TaskID = taskID;
            thread.ThreadDate = DateTime.Now;
            db.InteractionThreads.Add(thread);
            db.SaveChanges();

            InteractionPost post = new InteractionPost();
            post.IsApproved = true;
            post.PostContent = request["usercomment"];
            post.PostContentFormatted = Interactions.FormatPost(request["usercomment"]);
            post.PostDate = DateTime.Now;
            post.ReplyToPostID = 0;
            post.ThreadID = thread.ThreadID;
            post.UserID = userID;
            post.Subject = "RE: Assignment: " + task.Name;
            post.TaskID = taskID;
            db.InteractionPosts.Add(post);
            db.SaveChanges();

            return new TaskTypeResult() { Success = true, UrlHash = "thread-" + thread.ThreadID };
        }
 public Pager(RequestContext requestContext, PageInfo pageInfo, IEnumerable<string> queryKeysForCut)
 {
     _requestContext = requestContext;
     _request = _requestContext.HttpContext.Request;
     _pageInfo = pageInfo;
     _queryKeysForCut = queryKeysForCut;
 }
        public static async Task<IQueryable<Package>> SearchCore(
            ISearchService searchService,
            HttpRequestBase request,
            IQueryable<Package> packages, 
            string searchTerm, 
            string targetFramework, 
            bool includePrerelease,
            CuratedFeed curatedFeed)
        {
            SearchFilter searchFilter;
            // We can only use Lucene if:
            //  a) We are looking for the latest version of a package OR the Index contains all versions of each package
            //  b) The sort order is something Lucene can handle
            if (TryReadSearchFilter(searchService.ContainsAllVersions, request.RawUrl, out searchFilter))
            {
                searchFilter.SearchTerm = searchTerm;
                searchFilter.IncludePrerelease = includePrerelease;
                searchFilter.CuratedFeed = curatedFeed;
                searchFilter.SupportedFramework = targetFramework;

                var results = await GetResultsFromSearchService(searchService, searchFilter);

                return results;
            }

            if (!includePrerelease)
            {
                packages = packages.Where(p => !p.IsPrerelease);
            }

            return packages.Search(searchTerm);
        }
Beispiel #36
0
 public static string GetReferrerUrlOrCurrent(this System.Web.HttpRequestBase request)
 {
     if (request.UrlReferrer != null)
     {
         return(request.UrlReferrer.AbsoluteUri);
     }
     return((request.HttpMethod == "POST") ? request.Url.AbsoluteUri : "/");
 }
        private static Stream GetBodyStream(HttpRequest httpRequest)
        {
#if !ASP_NET_CORE
            var body = httpRequest.InputStream;
#else
            var body = httpRequest.Body;
#endif
            return(body);
        }
Beispiel #38
0
 /// <summary>
 /// 判断URL是否是本域名(防劫持)
 /// </summary>
 /// <param name="request"></param>
 /// <param name="url"></param>
 /// <returns></returns>
 public static bool IsOtherDomain(System.Web.HttpRequestBase request, Uri url)
 {
     //非本域名
     if (Uri.Compare(url, request.Url, UriComponents.HostAndPort, UriFormat.SafeUnescaped, StringComparison.CurrentCulture) != 0)
     {
         return(true);
     }
     return(false);
 }
Beispiel #39
0
        public static string GetRequestUrl(System.Web.HttpRequestBase request)
        {
            if (request == null)
            {
                return(string.Empty);
            }

            return(UrlDeCode(request.Url.ToString()));
        }
Beispiel #40
0
        public IResourceContext FromHttpRequest(System.Web.HttpRequestBase request)
        {
            ResourceContext context = new ResourceContext();

            context.Form        = request.Form;
            context.QueryString = request.QueryString;
            context.Headers     = request.Headers;
            return(context);
        }
        public static bool CanEnd(this IPaymentProvider provider, System.Web.HttpRequestBase request)
        {
            var data = request.ToDictionary(RequestRead.QueryAndForm);

            data.Add("HttpMethod", request.HttpMethod);
            data.Add("Url", request.Url.AbsoluteUri);

            return(provider.CanEnd(data));
        }
        protected internal override bool CanUnbind(System.Web.HttpRequestBase request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            return(request.HttpMethod == "POST" &&
                   request.Form.AllKeys.Contains("SAMLResponse"));
        }
Beispiel #43
0
 public static string GetCookie(System.Web.HttpRequestBase request, string cookieName)
 {
     if (request.Cookies.AllKeys.Contains(cookieName))
     {
         return(request.Cookies[cookieName].Value);
     }
     else
     {
         return("");
     }
 }
Beispiel #44
0
    /// <summary>
    /// 验证是否是其他域名(ture则非本域名)
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public static bool IsOtherDomain(System.Web.HttpRequestBase request)
    {
        var urlReferrer = request.UrlReferrer;//注意一下可能为空

        //非本域名
        if (urlReferrer != null && Uri.Compare(urlReferrer, request.Url, UriComponents.HostAndPort, UriFormat.SafeUnescaped, StringComparison.CurrentCulture) != 0)
        {
            return(true);
        }
        return(false);
    }
        private bool TryGetBody(HttpRequest httpRequest, long?contentLength, out Stream body)
        {
            body = null;
            if (contentLength <= 0)
            {
                return(false);
            }

            if (MaxContentLength > 0 && contentLength > MaxContentLength)
            {
                InternalLogger.Debug("AspNetRequestPostedBody: body stream is too big. ContentLength={0}", contentLength);
                return(false);
            }

            body = GetBodyStream(httpRequest);

            if (body == null)
            {
                InternalLogger.Debug("AspNetRequestPostedBody: body stream was null");
                return(false);
            }

            if (!body.CanRead)
            {
                InternalLogger.Debug("AspNetRequestPostedBody: body stream has been closed");
                return(false);
            }

            if (!body.CanSeek)
            {
                var oldPosition = body.Position;
                if (oldPosition > 0 && oldPosition >= contentLength)
                {
                    InternalLogger.Debug("AspNetRequestPostedBody: body stream cannot seek and already read. StreamPosition={0}", oldPosition);
                    return(false);
                }

                if (!TryEnableBuffering(httpRequest, contentLength, out body))
                {
                    return(false);
                }
            }
            else
            {
                if (MaxContentLength > 0 && !contentLength.HasValue && body.Length > MaxContentLength)
                {
                    InternalLogger.Debug("AspNetRequestPostedBody: body stream too big. Body.Length={0}", body.Length);
                    body = null;
                    return(false);
                }
            }

            return(true);
        }
Beispiel #46
0
        private HttpRequestBase request;                             // 内部使用的 Request 对象

        public DataTablesRequest(System.Web.HttpRequestBase request) // 用于 MVC 模式下的构造函数
        {
            this.request = request;

            this.echo          = this.ParseStringParameter(sEchoParameter);
            this.displayStart  = this.ParseIntParameter(iDisplayStartParameter);
            this.displayLength = this.ParseIntParameter(iDisplayLengthParameter);
            this.sortingCols   = this.ParseIntParameter(iSortingColsParameter);

            this.search = this.ParseStringParameter(sSearchParameter);
            this.regex  = this.ParseStringParameter(bRegexParameter) == "true";

            // 排序的列
            int count = this.iSortingCols;

            this.sortColumns = new SortColumn[count];
            for (int i = 0; i < count; i++)
            {
                SortColumn col = new SortColumn();
                col.Index = this.ParseIntParameter(string.Format("iSortCol_{0}", i));

                if (this.ParseStringParameter(string.Format("sSortDir_{0}", i)) == "desc")
                {
                    col.Direction = SortDirection.Desc;
                }
                else
                {
                    col.Direction = SortDirection.Asc;
                }
                this.sortColumns[i] = col;
            }

            this.ColumnCount = this.ParseIntParameter(iColumnsParameter);

            count        = this.ColumnCount;
            this.columns = new Column[count];

            if (this.ParseStringParameter(sColumnsParameter) == null || !this.ParseStringParameter(sColumnsParameter).Contains(','))
            {
                return;
            }
            string[] names = this.ParseStringParameter(sColumnsParameter).Split(',');

            for (int i = 0; i < count; i++)
            {
                Column col = new Column();
                col.Name        = names[i];
                col.Sortable    = this.ParseStringParameter(string.Format("bSortable_{0}", i)) == "true";
                col.Searchable  = this.ParseStringParameter(string.Format("bSearchable_{0}", i)) == "true";
                col.Search      = this.ParseStringParameter(string.Format("sSearch_{0}", i));
                col.EscapeRegex = this.ParseStringParameter(string.Format("bRegex_{0}", i)) == "true";
                columns[i]      = col;
            }
        }
        private static Stream EnableRewind(HttpRequest httpRequest, int bufferThreshold)
        {
#if ASP_NET_CORE2
            Microsoft.AspNetCore.Http.HttpRequestRewindExtensions.EnableBuffering(httpRequest, bufferThreshold);
            return(httpRequest.Body);
#elif ASP_NET_CORE1
            Microsoft.AspNetCore.Http.Internal.BufferingHelper.EnableRewind(httpRequest, bufferThreshold);
            return(httpRequest.Body);
#else
            return(null);
#endif
        }
Beispiel #48
0
        public Dictionary <string, object> ExtractPostData(System.Web.HttpRequestBase Request)
        {
            // GET THE POST DATA, PUT INTO JSON/DICTIONARY FORM
            Stream               body     = Request.InputStream;
            Encoding             encoding = Request.ContentEncoding;
            StreamReader         reader   = new StreamReader(body, encoding);
            string               json     = reader.ReadToEnd();
            JavaScriptSerializer ser      = new JavaScriptSerializer();
            var req_data = ser.Deserialize <Dictionary <string, object> >(json);

            return(req_data);
        }
    public override void ExecuteResult(ControllerContext context)
    {
        System.Web.HttpResponseBase response = context.HttpContext.Response;
        System.Web.HttpRequestBase  request  = context.HttpContext.Request;
        string url = request.Url.OriginalString;

        ViewData["RequestedUrl"] = url;
        ViewData["ReferrerUrl"]  = (request.UrlReferrer != null && request.UrlReferrer.OriginalString != url) ? request.UrlReferrer.OriginalString : null;
        response.StatusCode      = 404;

        // Prevent IIS7 from overwriting our error page!
        response.TrySkipIisCustomErrors = true;
        base.ExecuteResult(context);
    }
Beispiel #50
0
        public static decimal?GetDecimalNullable(this System.Web.HttpRequestBase request, string name, decimal?defaultValue = null)
        {
            var s = GetString(request, name);

            decimal i;

            if (decimal.TryParse(s, out i))
            {
                return(i);
            }
            else
            {
                return(defaultValue);
            }
        }
Beispiel #51
0
        public static int GetInt(this System.Web.HttpRequestBase request, string name, int defaultValue = 0)
        {
            var s = GetString(request, name);

            var i = 0;

            if (int.TryParse(s, out i))
            {
                return(i);
            }
            else
            {
                return(defaultValue);
            }
        }
Beispiel #52
0
        private string GetRequestParams(System.Web.HttpRequestBase request)
        {
            var data    = "";
            var ignores = @"ASP.NET_SessionId;Lang;ALL_HTTP;ALL_RAW;APPL_MD_PATH;APPL_PHYSICAL_PATH;AUTH_TYPE;AUTH_USER;AUTH_PASSWORD;LOGON_USER;REMOTE_USER;CERT_COOKIE;CERT_FLAGS;CERT_ISSUER;CERT_KEYSIZE;CERT_SECRETKEYSIZE;CERT_SERIALNUMBER;CERT_SERVER_ISSUER;CERT_SERVER_SUBJECT;CERT_SUBJECT;CONTENT_LENGTH;CONTENT_TYPE;GATEWAY_INTERFACE;HTTPS;HTTPS_KEYSIZE;HTTPS_SECRETKEYSIZE;HTTPS_SERVER_ISSUER;HTTPS_SERVER_SUBJECT;INSTANCE_ID;INSTANCE_META_PATH;LOCAL_ADDR;PATH_INFO;PATH_TRANSLATED;QUERY_STRING;REMOTE_ADDR;REMOTE_HOST;REMOTE_PORT;REQUEST_METHOD;SCRIPT_NAME;SERVER_NAME;SERVER_PORT;SERVER_PORT_SECURE;SERVER_PROTOCOL;SERVER_SOFTWARE;URL;HTTP_CONNECTION;HTTP_CONTENT_LENGTH;HTTP_CONTENT_TYPE;HTTP_ACCEPT;HTTP_ACCEPT_CHARSET;HTTP_ACCEPT_ENCODING;HTTP_ACCEPT_LANGUAGE;HTTP_COOKIE;HTTP_HOST;HTTP_REFERER;HTTP_USER_AGENT;HTTP_ORIGIN;HTTP_X_REQUESTED_WITH;RetechWing_User".Split(';');

            foreach (var key in request.Params.AllKeys)
            {
                if (ignores.Any(p => p == key))
                {
                    continue;
                }
                data += key + "=" + request.Params[key] + "\r\n";
            }
            return(data);
        }
Beispiel #53
0
        public static string QueryStringToParams(int pagina, System.Web.HttpRequestBase request)
        {
            string query = request.Params.ToString();
            Regex  regex = new Regex("pagina.*?&");

            query = regex.Replace(query, "");

            regex = new Regex("ALL_HTTP.*");
            query = regex.Replace(query, "");

            regex = new Regex("&&.*");
            query = regex.Replace(query, "");

            return("?pagina=" + pagina + "&" + query);
        }
Beispiel #54
0
        /// <summary>
        /// 获取当前第三方帐号上的访问授权
        /// </summary>
        /// <param name="Request"></param>
        /// <returns></returns>
        public override string GetAccessToken(System.Web.HttpRequestBase Request)
        {
            string code = Request.QueryString.GetString("code", string.Empty);

            _restClient.BaseUrl       = "https://graph.renren.com";
            _restClient.Authenticator = null;
            var request = new RestRequest(Method.GET);

            request.Resource = "oauth/token?grant_type=authorization_code&client_id={appkey}&client_secret={appsecret}&code={code}&redirect_uri={callbackurl}";
            request.AddParameter("appkey", AccountType.AppKey, ParameterType.UrlSegment);
            request.AddParameter("appsecret", AccountType.AppSecret, ParameterType.UrlSegment);
            request.AddParameter("code", code, ParameterType.UrlSegment);
            request.AddParameter("callbackurl", CallbackUrl, ParameterType.UrlSegment);
            var    response     = Execute(_restClient, request);
            string access_token = GetParmFromContent(response.Content, @"""access_token"":""(?<accessToken>[^""]+)""", "accessToken");

            return(access_token);
        }
Beispiel #55
0
        /// <summary>
        /// 获取请求用户的信息
        /// </summary>
        /// <param name="Request"></param>
        /// <returns></returns>
        public Ho_PartnerUser GetUserInfo(System.Web.HttpRequestBase Request)
        {
            HttpCookie Mycookie = Request.Cookies["WebUserInfo"];

            if (Mycookie != null)
            {
                string str = Mycookie.Value;
                if (!string.IsNullOrEmpty(str))
                {
                    str = DESEncrypt.Decrypt(str);
                    string[]  user     = str.Split('&');
                    IDatabase database = DataFactory.Database();
                    var       model    = database.FindEntity <Ho_PartnerUser>(user[0]);
                    return(model);
                }
            }
            return(null);
        }
Beispiel #56
0
        /// <summary>
        /// 获取当前第三方帐号上的访问授权
        /// </summary>
        /// <param name="Request"></param>
        /// <param name="expires_in">有效期(单位:秒)</param>
        /// <returns></returns>
        public override string GetAccessToken(System.Web.HttpRequestBase Request, out int expires_in)
        {
            string code = Request.QueryString.GetString("code", string.Empty);

            _restClient.BaseUrl       = "https://graph.renren.com";
            _restClient.Authenticator = null;
            var request = new RestRequest(Method.GET);

            request.Resource = "oauth/token?grant_type=authorization_code&client_id={appkey}&client_secret={appsecret}&code={code}&redirect_uri={callbackurl}";
            request.AddParameter("appkey", AccountType.AppKey, ParameterType.UrlSegment);
            request.AddParameter("appsecret", AccountType.AppSecret, ParameterType.UrlSegment);
            request.AddParameter("code", code, ParameterType.UrlSegment);
            request.AddParameter("callbackurl", CallbackUrl, ParameterType.UrlSegment);
            var     response = Execute(_restClient, request);
            dynamic json     = Json.Decode(response.Content);

            expires_in = json.expires_in;
            return(json.access_token);
        }
        public IAuthorizationContext FromHttpRequest(System.Web.HttpRequestBase request)
        {
            NameValueCollection values;

            if (request.HttpMethod.ToUpperInvariant() == "GET")
            {
                values = request.QueryString;
            }
            else if (request.HttpMethod.ToUpperInvariant() == "POST")
            {
                values = request.Form;
            }
            else
            {
                throw new HttpException(405, string.Format(CultureInfo.CurrentUICulture, AuthorizationEndpointResources.InvalidRequestMethod,
                                                           request.HttpMethod));
            }

            return(CreateContext(values));
        }
Beispiel #58
0
        public void Logout(System.Web.HttpRequestBase request, System.Web.HttpResponseBase response, System.Web.HttpSessionStateBase session)
        {
            HttpCookie myCookie = new HttpCookie("rfs.username");

            myCookie = request.Cookies["rfs.username"];
            if (myCookie != null)
            {
                session[myCookie.Value] = "";
            }

            HttpCookie currentUserCookie = request.Cookies["rfs.username"];

            response.Cookies.Remove("rfs.username");
            if (currentUserCookie != null)
            {
                currentUserCookie.Expires = DateTime.Now.AddDays(-10);
                currentUserCookie.Value   = null;
                response.SetCookie(currentUserCookie);
            }
        }
Beispiel #59
0
        public static void send(string Email, string Name, System.Web.HttpRequestBase Request, string activationCode, int?password, string Path)
        {
            using (StreamReader reader = System.IO.File.OpenText(System.Web.HttpContext.Current.Server.MapPath(Path))) // Path to your
            {
                MailMessage mm = new MailMessage();
                mm.To.Add(new MailAddress(Email, "Request for Verification"));
                mm.From    = new MailAddress("*****@*****.**");
                mm.Subject = "Microsoft support team";
                // mm.BodyFormat = System.Web.Mail.MailFormat.Html;
                mm.IsBodyHtml = true;
                if (password == null)
                {
                    if ((Path == "~/email.html") || (Path == "~/Validate.html"))
                    {
                        mm.Body = reader.ReadToEnd().Replace("<%Scheme%>", Request.Url.Scheme)
                                  .Replace("<%Authority%>", Request.Url.Authority)
                                  .Replace("<%email%>", Email)
                                  .Replace("<%Code%>", activationCode)
                                  .Replace("<%name%>", Name);
                    }
                }
                else
                {
                    mm.Body = reader.ReadToEnd().Replace("<%Scheme%>", Request.Url.Scheme)
                              .Replace("<%Authority%>", Request.Url.Authority)
                              .Replace("<%email%>", Email)
                              .Replace("<%Code%>", activationCode)
                              .Replace("<%password%>", password.ToString())
                              .Replace("<%name%>", Name);
                }
                SmtpClient smcl = new SmtpClient();
                smcl.UseDefaultCredentials = false;
                smcl.EnableSsl             = true;
                smcl.Host           = "smtp.gmail.com";
                smcl.Port           = 587;
                smcl.DeliveryMethod = SmtpDeliveryMethod.Network;

                smcl.Credentials = new NetworkCredential("*****@*****.**", "Mohamed55&");
                smcl.Send(mm);
            }
        }
Beispiel #60
0
        public PaymentInfo ProcessReturn(System.Web.HttpRequestBase context)
        {
            //Get方式
            NameValueCollection         coll  = context.QueryString;
            Dictionary <string, string> paras = new Dictionary <string, string>();

            foreach (string key in coll.AllKeys)
            {
                paras.Add(key, coll[key]);
            }
            Notify      notify = new Notify(WorkDirectory);
            bool        isSign = notify.Verify(paras, string.Empty, (string)coll["sign"], _Config);
            PaymentInfo info   = new PaymentInfo();

            if (isSign)
            {
                info.OrderIds = coll["out_trade_no"].Split(',').Select(item => long.Parse(item));
                info.TradNo   = coll["trade_no"];
            }
            return(info);
        }