private static string GetBlobPath(HttpRequest request)
        {
            string hostName = request.Url.DnsSafeHost;
            if (hostName == "localdev")
            {
                hostName = "www.protonit.net";
            }
            string containerName = hostName.Replace('.', '-');
            string currServingFolder = "";
            try
            {
                // "/2013-03-20_08-27-28";
                CloudBlobClient publicClient = new CloudBlobClient("http://caloom.blob.core.windows.net/");
                string currServingPath = containerName + "/" + RenderWebSupport.CurrentToServeFileName;
                var currBlob = publicClient.GetBlockBlobReference(currServingPath);
                string currServingData = currBlob.DownloadText();
                string[] currServeArr = currServingData.Split(':');
                string currActiveFolder = currServeArr[0];
                var currOwner = VirtualOwner.FigureOwner(currServeArr[1]);
                InformationContext.Current.Owner = currOwner;
                currServingFolder = "/" + currActiveFolder;
            }
            catch
            {

            }
            return containerName + currServingFolder + request.Path;
        }
 public virtual void Uninitialize()
 {
     _features = default(FeatureReferences<FeatureInterfaces>);
     if (_request != null)
     {
         UninitializeHttpRequest(_request);
         _request = null;
     }
     if (_response != null)
     {
         UninitializeHttpResponse(_response);
         _response = null;
     }
     if (_authenticationManager != null)
     {
         UninitializeAuthenticationManager(_authenticationManager);
         _authenticationManager = null;
     }
     if (_connection != null)
     {
         UninitializeConnectionInfo(_connection);
         _connection = null;
     }
     if (_websockets != null)
     {
         UninitializeWebSocketManager(_websockets);
         _websockets = null;
     }
 }
        public void Given_argument_name_and_value_are_defined_And_method_is_GET_When_adding_argument_Then_argument_added()
        {
            // setup
            var mockHost = "www.test.com";
            var mockPath = "/index.html";
            var mockUrl = mockHost + mockPath;
            var mockArgumentName = "ArgumentName";
            var mockArgumentValue = "ArgumentValue";

            var assembledRequest = new StringBuilder();
            assembledRequest.Append("GET " + mockPath + "?" + mockArgumentName + "=" + mockArgumentValue + " HTTP/1.0\n");
            assembledRequest.Append("Host: ");
            assembledRequest.Append(mockHost);
            assembledRequest.Append("\nConnection: Close");
            assembledRequest.Append("\n\n");
            var expectedBytes = Encoding.UTF8.GetBytes(assembledRequest.ToString());

            var target = new HttpRequest(mockUrl);

            // execution
            target.AddArgument(mockArgumentName, mockArgumentValue);

            // assertion
            var result = target.ToByteArray();
            Assert.AreEqual(expectedBytes, result, "Argument not added");
        }
 public CompetitionResultAppelRequestHandler(HttpRequest Request, HttpResponse Response, Uri Prefix, UriTemplate CompetitionResultsTemplate, UriTemplate ResultResourceTemplate, string AcceptHeader)
     : base(Request, Response, Prefix, AcceptHeader)
 {
     this.CompetitionResultsTemplate = CompetitionResultsTemplate;
     this.ResultResourceTemplate = ResultResourceTemplate;
     processRequest();
 }
示例#5
0
        public HttpResponse Get(HttpRequest request)
        {
            if (request == null)
                throw new ArgumentNullException("request", "HttpRequest is required for GET.");

            if (request.Uri == null)
                throw new ArgumentNullException("uri", "GET http request requires uri.");

            try
            {
                HttpResponseMessage response = SendAsync(HttpMethod.Get, request).Result;
                return new HttpResponse(response);
            }
            catch (HttpRequestException ex)
            {
                return new HttpResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
            catch (AggregateException ex)
            {
                return new HttpResponse(HttpStatusCode.InternalServerError, ex.InnerException.Message); 
            }
            catch (Exception ex)
            {
                return new HttpResponse(HttpStatusCode.InternalServerError, ex.Message);
            }            
        }
        public static void Main()
        {
            const SPI.SPI_module spiBus = SPI.SPI_module.SPI3;
            const Cpu.Pin chipSelectPin = Stm32F4Discovery.FreePins.PA15;
            const Cpu.Pin interruptPin = Stm32F4Discovery.FreePins.PD1;
            const string hostname = "stm32f4";
            var mac = new byte[] {0x5c, 0x86, 0x4a, 0x00, 0x00, 0xdd};

            //Static IP
            //Adapter.IPAddress = "10.15.16.50".ToBytes();
            //Adapter.Gateway = "10.15.16.1".ToBytes();
            //Adapter.DomainNameServer = Adapter.Gateway;
            //Adapter.DomainNameServer2 = "8.8.8.8".ToBytes();  // Google DNS Server
            //Adapter.SubnetMask = "255.255.255.0".ToBytes();
            //Adapter.DhcpDisabled = true;

            //Adapter.VerboseDebugging = true;
            Adapter.Start(mac, hostname, spiBus, interruptPin, chipSelectPin);

            const int minVal = 0;
            const int maxVal = 100;

            string apiUrl = @"http://www.random.org/integers/?num=1"
                            + "&min=" + minVal + "&max=" + maxVal
                            + "&col=1&base=10&format=plain&rnd=new";

            var request = new HttpRequest(apiUrl);
            request.Headers.Add("Accept", "*/*");

            HttpResponse response = request.Send();
            if (response != null)
                Debug.Print("Random number: " + response.Message.Trim());
        }
示例#7
0
        public void TestToWebRequest()
        {
            var request = new HttpRequest
                          {
                              Url = "http://www.watchdogapp.com",
                              ContentType = "text/json",
                              Accept = "text/xml",
                              Referer = "referer",
                              Host = "somehost.com",
                              UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0"
                          };

            var webRequest = (HttpWebRequest) request.ToWebRequest();

            Assert.AreEqual("http://www.watchdogapp.com/", webRequest.RequestUri.ToString());

            Assert.AreEqual(5, webRequest.Headers.Count);
            Assert.AreEqual(DecompressionMethods.GZip | DecompressionMethods.Deflate, webRequest.AutomaticDecompression);
            Assert.AreEqual("GET", webRequest.Method);
            Assert.AreEqual(30000, webRequest.Timeout);
            Assert.AreEqual("Mozilla/5.0 (Windows NT 6.3; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0", webRequest.UserAgent);
            Assert.AreEqual("text/json", webRequest.ContentType);
            Assert.AreEqual("referer", webRequest.Referer);
            Assert.AreEqual("somehost.com", webRequest.Host);
            Assert.AreEqual(WebRequest.DefaultWebProxy, webRequest.Proxy);

            Assert.AreEqual("text/xml", webRequest.Accept);

            Assert.AreEqual(request.Cookies, webRequest.CookieContainer);
        }
示例#8
0
        /// <summary>
        ///     Gets the client ip address.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.String.</returns>
        public static string GetClientIpAddress(HttpRequest request) {
            try{
                var userHostAddress = request.UserHostAddress;
                if (userHostAddress == "::1") userHostAddress = "127.0.0.1";

                // 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 (userHostAddress != null){
                    IPAddress.Parse(userHostAddress);

                    var 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";
            }
            return "0.0.0.0";
        }
        public LoginResponder(HttpRequest request)
            : base(request)
        {
            guestMode = false;

            var guidStr = request.QueryString["pairing-guid"];
            if (!string.IsNullOrEmpty(guidStr))
            {
                if (!guidStr.StartsWith("0x"))
                    throw new ArgumentException("Invalid pairing guid requested", "request");

                var guid = (ulong)IPAddress.NetworkToHostOrder(long.Parse(guidStr.Substring(2), NumberStyles.AllowHexSpecifier));

                var pairedDevice = Pairing.PairedDevices.GetDevice(guid);
                if (pairedDevice == null)
                    throw new ArgumentException("Device is not paired with", "request");
            }
            else
            {
                var lStr = request.QueryString["l"];
                var kStr = request.QueryString["k"];
                if (string.IsNullOrEmpty(lStr) || string.IsNullOrEmpty(kStr))
                    throw new ArgumentException("Invalid login request", "request");

                guestMode = true;
            }
        }
示例#10
0
        public static string GetClientIPAddress(HttpRequest req)
        {
            string szRemoteAddr = req.ServerVariables["REMOTE_ADDR"];
            string szXForwardedFor = req.ServerVariables["X_FORWARDED_FOR"];
            string szIP = "";

            if (szXForwardedFor == null)
            {
                szIP = szRemoteAddr;
            }
            else
            {
                szIP = szXForwardedFor;
                if (szIP.IndexOf(",") > 0)
                {
                    string[] arIPs = szIP.Split(',');

                    foreach (string item in arIPs)
                    {
                        if (item != "127.0.0.1")
                        {
                            return item;
                        }
                    }
                }
            }
            return szIP;
        }
示例#11
0
 public UrlCachePathResult GetUrlPathResult(HttpRequest httpRequest, string subDirectory = null)
 {
     string subPath = GetUrlSubPath(httpRequest);
     if (subDirectory != null)
         subPath = zPath.Combine(subDirectory, subPath);
     return new UrlCachePathResult { Path = zPath.Combine(_cacheDirectory, subPath), SubPath = subPath };
 }
示例#12
0
 private string _GetUrlSubDirectory(HttpRequest httpRequest)
 {
     if (_getUrlSubDirectory != null)
         return _getUrlSubDirectory(httpRequest);
     else
         return null;
 }
示例#13
0
        protected virtual HttpWebResponse ProxyRequest(HttpRequest source)
        {          
            HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(Url + "?" + source.QueryString.ToString());
            Req.KeepAlive = false;
            Req.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;
            Req.UseDefaultCredentials = true;

            // *** Set properties
            Req.Timeout = 60000;
            Req.UserAgent = source.UserAgent;
            Req.Method = source.HttpMethod;
            Req.ContentType = source.ContentType;

            Req.Headers.Add("Impersonate", source.LogonUserIdentity.Name);
            foreach (string H in ReqHeaders)
            {
                var V = source.Headers[H];
                if (V != null)
                    Req.Headers.Add(H, V);
            }

            if (Req.Method == "POST")
                using (var ReqStream = Req.GetRequestStream())
                {
                    source.InputStream.CopyTo(ReqStream);
                }
            return Req.GetResponse() as HttpWebResponse;            
        }
        public void AddContent_WithHttpWebRequestAdapterAndHttpRequest()
        {
            // Arrange
            Mock<IHttpWebRequestAdapter> mockHttpWebRequest = mocks.Create<IHttpWebRequestAdapter>();

            HttpRequest request = new HttpRequest()
            {
                Content = "content",
                ContentEncoding = Encoding.UTF8,
                ContentType = "application/xml"
            };

            Stream stream = new MemoryStream();

            mockHttpWebRequest.Setup(wr=>wr.GetRequestStream()).Returns(stream);
            mockHttpWebRequest.SetupSet(wr => wr.ContentLength = request.ContentLength);
            mockHttpWebRequest.SetupSet(wr => wr.ContentType = request.ContentType);

            // Act
            helper.AddContent(mockHttpWebRequest.Object, request);

            // Assert

            // Expectations have been met.
        }
示例#15
0
        public HttpResponse GetResponse(HttpRequest request)
        {
            var url = request.Url;

            if (request.QueryString != null && request.QueryString.Any())
            {
                var encodedQueryString = ToQueryString(request.QueryString);
                url = string.Format("{0}?{1}", url, encodedQueryString);
            }

            var key = GetRequestKey(request.Method, url, request.Headers, request.Body);

            if (stubbedRequests.ContainsKey(key) == false)
            {
                throw new ArgumentException(
                    "\n\n----------\n\n" +
                    "No stub found\n" +
                    "=============\n\n" +
                    key +
                    "\n\n\n" +
                    "Known stubs" +
                    "\n============\n\n" +
                    string.Join("\n\n-----\n\n", stubbedRequests.Keys.ToArray()) +
                    "\n\n"
                );
            }

            var stub = stubbedRequests[key];

            return new HttpResponse {
                Code = stub.ResponseCode,
                Headers = new Dictionary<string, string>(),
                Body = stub.ResponseBody,
            };
        }
示例#16
0
 public HttpResponse(HttpRequest request, HttpHeader headers, Byte[] binaryData, HttpStatusCode statusCode = HttpStatusCode.OK)
 {
     Request = request;
     Headers = headers;
     ResponseData = binaryData;
     StatusCode = statusCode;
 }
示例#17
0
        public async Task<byte[]> GetResponseAsync(HttpRequest request)
        {
            Requires.NotNull(request, "request");

            HttpWebRequest webRequest = await HttpWebRequestFactory.CreateRequestAsync(request);
            
            try
            {
                using (WebResponse response = await webRequest.GetResponseAsync())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        return await responseStream.GetBytesAsync();
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    using (Stream responseStream = ex.Response.GetResponseStream())
                    {
                        return responseStream.GetBytes();
                    }
                }
                return null;
            }
        }
 public BaseAppelRequstHandler(HttpRequest Request, HttpResponse Response, Uri Prefix, string VersionHeader)
 {
     this.Request = Request;
     this.Response = Response;
     this.Prefix = Prefix;
     this.VersionHeader = VersionHeader;
 }
示例#19
0
		public override void SendRequestHeaderAndEntity(HttpRequest request, HttpEntity httpEntity, bool expectContinue)
		{
			RequestInitiated = request.Initiated;
			RequestTimeout = request.Timeout;

			if (!this.IsConnected())
			{
				throw new HttpNetworkException("Tls client is closed or not ready (SendRequestHeaderAndEntity)");
			}
			byte[] header = Encoding.ASCII.GetBytes(GetRequestHeader(request).ToString());

			_tlsClient.Send(header);

			if (expectContinue)
			{
				WaitForDataToArrive(2 * 1000);
				if (_tlsClient.Available > 0)
				{
					// now read the 100-continue response
					HttpResponse response = ReceiveResponseHeaders();
					if (response.ResponseCode != 100)
					{
						throw new HttpNetworkException("response returned before entity was sent, but it is not 100-continue");
					}
				}
			}

			byte[] body = httpEntity.Content;
			_tlsClient.Send(body);
		}
示例#20
0
 public static void SignOut(HttpResponse Response, HttpRequest Request)
 {
     HttpCookie cookie = Request.Cookies["DareSessionID"];
     int id = int.Parse(cookie.Value);
     SessionManager.RemoveSession(id);
     if (Response.Cookies.AllKeys.Contains("DareSessionID")) Response.Cookies.Remove("DareSessionID");
 }
        public StaticFileContext(HttpContext context, StaticFileOptions options, PathString matchUrl)
        {
            _context = context;
            _options = options;
            _matchUrl = matchUrl;
            _request = context.Request;
            _response = context.Response;

            _method = null;
            _isGet = false;
            _isHead = false;
            _subPath = PathString.Empty;
            _contentType = null;
            _fileInfo = null;
            _length = 0;
            _lastModified = new DateTime();
            _etag = null;
            _etagQuoted = null;
            _lastModifiedString = null;
            _ifMatchState = PreconditionState.Unspecified;
            _ifNoneMatchState = PreconditionState.Unspecified;
            _ifModifiedSinceState = PreconditionState.Unspecified;
            _ifUnmodifiedSinceState = PreconditionState.Unspecified;
            _ranges = null;
        }
示例#22
0
    void WriteResponseForPostJson(HttpRequest request, HttpResponse response)
    {
        // read request JSON
        uint requestedCount = ReadCount(request.Body);

        // write response JSON
        var json = new JsonWriter<ResponseFormatter>(response.Body, prettyPrint: false);
        json.WriteObjectStart();
        json.WriteArrayStart();
        for (int i = 0; i < requestedCount; i++) {
            json.WriteString("hello!"); 
        }
        json.WriteArrayEnd();
        json.WriteObjectEnd();

        // write headers
        var headers = response.Headers;
        headers.AppendHttpStatusLine(HttpVersion.V1_1, 200, new Utf8String("OK"));
        headers.Append("Content-Length : ");
        headers.Append(response.Body.CommitedBytes);
        headers.AppendHttpNewLine();
        headers.Append("Content-Type : text/plain; charset=UTF-8");
        headers.AppendHttpNewLine();
        headers.Append("Server : .NET Core Sample Server");
        headers.AppendHttpNewLine();
        headers.Append("Date : ");
        headers.Append(DateTime.UtcNow, 'R');
        headers.AppendHttpNewLine();
        headers.AppendHttpNewLine();
    }
示例#23
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;
        }
示例#24
0
 public void Handle(HttpRequest req, HttpResponse resp, JsonRpcHandler jsonRpcHandler)
 {
     if(req.HttpMethod != "POST")
     {
         resp.Status = "405 Method Not Allowed";
         return;
     }
     if(!req.ContentType.StartsWith("application/json"))
     {
         resp.Status = "415 Unsupported Media Type";
         return;
     }
     JToken json;
     try
     {
         json = JToken.ReadFrom(new JsonTextReader(req.Content));
     }
     catch(Exception e)
     {
         resp.Status = "400 Bad Request";
         resp.ContentType = "text/plain";
         resp.Content.WriteLine(e);
         return;
     }
     resp.Status = "200 OK";
     resp.ContentType = "application/json";
     using(var jsonWriter = new JsonTextWriter(resp.Content))
     {
         new JsonSerializer().Serialize(jsonWriter, jsonRpcHandler.Handle(json));
     }
 }
示例#25
0
        /// <summary>
		/// Initializes a new instance of the <see cref="HttpClientContext"/> class.
        /// </summary>
        /// <param name="secured">true if the connection is secured (SSL/TLS)</param>
        /// <param name="remoteEndPoint">client that connected.</param>
        /// <param name="stream">Stream used for communication</param>
        /// <param name="clientCertificate">Client security certificate</param>
        /// <param name="parserFactory">Used to create a <see cref="IHttpRequestParser"/>.</param>
        /// <param name="bufferSize">Size of buffer to use when reading data. Must be at least 4096 bytes.</param>
        /// <param name="socket">Client socket</param>
        /// <exception cref="SocketException">If <see cref="Socket.BeginReceive(byte[],int,int,SocketFlags,AsyncCallback,object)"/> fails</exception>
        /// <exception cref="ArgumentException">Stream must be writable and readable.</exception>
        public HttpClientContext(bool secured, IPEndPoint remoteEndPoint, Stream stream, 
            ClientCertificate clientCertificate, IRequestParserFactory parserFactory, int bufferSize, Socket socket)
        {
            Check.Require(remoteEndPoint, "remoteEndPoint");
            Check.NotEmpty(remoteEndPoint.Address.ToString(), "remoteEndPoint.Address");
            Check.Require(stream, "stream");
            Check.Require(parserFactory, "parser");
            Check.Min(4096, bufferSize, "bufferSize");
            Check.Require(socket, "socket");

            if (!stream.CanWrite || !stream.CanRead)
                throw new ArgumentException("Stream must be writable and readable.");

            _bufferSize = bufferSize;
			RemoteAddress = remoteEndPoint.Address.ToString();
			RemotePort = remoteEndPoint.Port.ToString();
            _log = NullLogWriter.Instance;
            _parser = parserFactory.CreateParser(_log);
            _parser.RequestCompleted += OnRequestCompleted;
            _parser.RequestLineReceived += OnRequestLine;
            _parser.HeaderReceived += OnHeaderReceived;
            _parser.BodyBytesReceived += OnBodyBytesReceived;
        	_localEndPoint = (IPEndPoint)socket.LocalEndPoint;

            HttpRequest request = new HttpRequest();
            request._remoteEndPoint = remoteEndPoint;
            request.Secure = secured;
            _currentRequest = request;

            IsSecured = secured;
            _stream = stream;
            _clientCertificate = clientCertificate;
            _buffer = new byte[bufferSize];

        }
        /// <param name="request">The request from the GlobalAsax is behaves differently!</param>
        public static void HandlerApplication_Error(HttpRequest request, HttpContext context, bool isWebRequest)
        {
            if (Navigator.Manager == null || !Navigator.Manager.Initialized)
                return;

            Exception ex = CleanException(context.Server.GetLastError());
            context.Server.ClearError();

            context.Response.StatusCode = GetHttpError(ex);
            context.Response.TrySkipIisCustomErrors = true;

            HandleErrorInfo hei = new HandleErrorInfo(ex, "Global.asax", "Application_Error");

            if (LogException != null)
                LogException(hei);

            if (isWebRequest)
            {
                HttpContextBase contextBase = context.Request.RequestContext.HttpContext;

                IController controller = new ErrorController { Result = GetResult(contextBase, hei) }; 

                var rd = new RouteData
                { 
                    Values= 
                    {
                        { "Controller", "Error"},
                        { "Action", "Error"}
                    }
                };

                controller.Execute(new RequestContext(contextBase, rd));  
            }
        }
示例#27
0
        public static HttpContent Info(HttpRequest request)
        {
            string data = "";
            if (request.Data != null)
            {
                data = StringHelper.GetString(request.Data);
            }

            var baseContent = new Dictionary<string, HttpContent>() {};

            // get connections
            lock (request.Server.Connections)
            {
                var totalConnections = request.Server.Connections.Count.ToString();
                var connections = "";

                foreach (var connection in request.Server.Connections)
                {
                    if (!connection.Stopped)
                    {
                        var ip = ((IPEndPoint)connection.Socket.Client.RemoteEndPoint).Address.ToString();
                        var port = ((IPEndPoint)connection.Socket.Client.RemoteEndPoint).Port.ToString();

                        connections += ip + ":" + port + "\n";
                    }
                    else
                    {
                        connections += "timed out\n";
                    }
                }

                baseContent.Add("TotalConnections", new HttpContent(totalConnections));
                baseContent.Add("Connections", new HttpContent(connections));
            }

            // get sessions
            // TODO: finish
            lock (request.Server.Sessions)
            {
                var totalSessions = request.Server.Sessions.Count.ToString();
                var sessions = "";

                foreach (var session in request.Server.Sessions)
                {
                    sessions += session.Key + " - " + session.Value.CreationDate.ToString() + "\n";
                }

                baseContent.Add("TotalSessions", new HttpContent(totalSessions));
                baseContent.Add("Sessions", new HttpContent(sessions));
            }

            var currentSession = "";
            currentSession += "ID: " + request.Session.ID + "\n";
            currentSession += "Created: " + request.Session.CreationDate.ToString() + "\n";
            currentSession += "ExpiryDate: " + request.Session.ExpiryDate.ToString() + "\n";

            baseContent.Add("Session", new HttpContent(currentSession));

            return HttpContent.Read(request.Server, "sar.Http.Views.Debug.Info.html", baseContent);
        }
示例#28
0
 static void Get(string url)
 {
     HttpRequest request = new HttpRequest();
     request.Cookies = new CookieDictionary();
     HttpResponse response = request.Get(url);
     Console.WriteLine(response.ToString());
 }
示例#29
0
        protected override void IntializeRequestInfo(HttpRequest httpRequest)
        {
            // base method
            base.IntializeRequestInfo(httpRequest);

            AjaxRequest.CustomHeaders = ExtractAJAXHeader(_currentContext.Request);
            AJAXInfo _AJAXInfo = GetAJAXInfo(_currentContext.Request.Params);

            // validate url
            if (string.IsNullOrEmpty(RequestInfo.RequestUrl))
            {
                LastErrorMessage = "Invalid AJAX headers.";
                LastStatus = LastStatus.Error;
                return;
            }

            AjaxRequest.Username = _AJAXInfo.UserName;
            AjaxRequest.Password = _AJAXInfo.Password;

            RequestInfo.SetContentType(GetContentTypeInCollection(AjaxRequest.CustomHeaders, _DefaultContentType));
            RequestInfo.RedirectedFrom = GetRequestReferer(
                                            AjaxRequest.CustomHeaders,
                                            _currentContext.Request,
                                            Consts.BackEndConenction.ASProxyProjectUrl);
        }
示例#30
0
        public async Task<bool> LogoutASync()
        {
            foreach (var file in _deleteFilesBeforeExit)
            {
                try
                {
                    if (File.Exists(file))
                        File.Delete(file);
                }
                // ReSharper disable once EmptyGeneralCatchClause
                catch (Exception)
                {
                    // We have done our best
                }
            }

            if (_sessionId == null)
                return true;

            var httpRequest = new HttpRequest();
            httpRequest.Parameters.Add("api", "SYNO.API.Auth");
            httpRequest.Parameters.Add("version", "2");
            httpRequest.Parameters.Add("method", "Logout");
            httpRequest.Parameters.Add("session", "SurveillanceStation");
            httpRequest.Parameters.Add("_sid", _sessionId);


            await httpRequest.GetASync(_url + "auth.cgi", 200); // There is no data coming back, just continue after some time

            return true;
        }
示例#31
0
 public static void Send(HttpRequest request, MessageInitiator initiator, MessageAction action, MessageTarget target, params string[] description)
 {
     SendInitiatorMessage(request, initiator.ToString(), action, target, description);
 }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// LoadActions loads the Actions collections
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// -----------------------------------------------------------------------------
        private void LoadActions(HttpRequest request)
        {
            _actions = new ModuleActionCollection();
            if (PortalSettings.IsLocked)
            {
                return;
            }

            _moduleGenericActions = new ModuleAction(GetNextActionID(), Localization.GetString("ModuleGenericActions.Action", Localization.GlobalResourceFile), string.Empty, string.Empty, string.Empty);
            int maxActionId = Null.NullInteger;

            //check if module Implements Entities.Modules.IActionable interface
            var actionable = _moduleControl as IActionable;
            if (actionable != null)
            {
                _moduleSpecificActions = new ModuleAction(GetNextActionID(), Localization.GetString("ModuleSpecificActions.Action", Localization.GlobalResourceFile), string.Empty, string.Empty, string.Empty);

                ModuleActionCollection moduleActions = actionable.ModuleActions;

                foreach (ModuleAction action in moduleActions)
                {
                    if (ModulePermissionController.HasModuleAccess(action.Secure, "CONTENT", Configuration))
                    {
                        if (String.IsNullOrEmpty(action.Icon))
                        {
                            action.Icon = "edit.gif";
                        }
                        if (action.ID > maxActionId)
                        {
                            maxActionId = action.ID;
                        }
                        _moduleSpecificActions.Actions.Add(action);

                        if (!UIUtilities.IsLegacyUI(ModuleId, action.ControlKey, PortalId) && action.Url.Contains("ctl"))
                        {
                            action.ClientScript = UrlUtils.PopUpUrl(action.Url, _moduleControl as Control, PortalSettings, true, false);
                        }
                    }
                }
                if (_moduleSpecificActions.Actions.Count > 0)
                {
                    _actions.Add(_moduleSpecificActions);
                }
            }

            //Make sure the Next Action Id counter is correct
            int actionCount = GetActionsCount(_actions.Count, _actions);
            if (_nextActionId < maxActionId)
            {
                _nextActionId = maxActionId;
            }
            if (_nextActionId < actionCount)
            {
                _nextActionId = actionCount;
            }

            //Custom injection of Module Settings when shared as ViewOnly
            if (Configuration != null && (Configuration.IsShared && Configuration.IsShareableViewOnly)
                    && TabPermissionController.CanAddContentToPage())
            {
                _moduleGenericActions.Actions.Add(GetNextActionID(),
                             Localization.GetString("ModulePermissions.Action", Localization.GlobalResourceFile),
                             "ModulePermissions",
                             "",
                             "action_settings.gif",
                             NavigateUrl(TabId, "ModulePermissions", false, "ModuleId=" + ModuleId, "ReturnURL=" + FilterUrl(request)),
                             false,
                             SecurityAccessLevel.ViewPermissions,
                             true,
                             false);
            }
            else
            {
                if (!Globals.IsAdminControl() && ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "DELETE,MANAGE", Configuration))
                {
                    if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "MANAGE", Configuration))
                    {
                        _moduleGenericActions.Actions.Add(GetNextActionID(),
                                                          Localization.GetString(ModuleActionType.ModuleSettings, Localization.GlobalResourceFile),
                                                          ModuleActionType.ModuleSettings,
                                                          "",
                                                          "action_settings.gif",
                                                          NavigateUrl(TabId, "Module", false, "ModuleId=" + ModuleId, "ReturnURL=" + FilterUrl(request)),
                                                          false,
                                                          SecurityAccessLevel.Edit,
                                                          true,
                                                          false);
                    }
                }
            }

            if (!string.IsNullOrEmpty(Configuration.DesktopModule.BusinessControllerClass))
            {
                //check if module implements IPortable interface, and user has Admin permissions
                if (Configuration.DesktopModule.IsPortable)
                {
                    if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "EXPORT", Configuration))
                    {
                        _moduleGenericActions.Actions.Add(GetNextActionID(),
                                     Localization.GetString(ModuleActionType.ExportModule, Localization.GlobalResourceFile),
                                     ModuleActionType.ExportModule,
                                     "",
                                     "action_export.gif",
                                     NavigateUrl(PortalSettings.ActiveTab.TabID, "ExportModule", false, "moduleid=" + ModuleId, "ReturnURL=" + FilterUrl(request)),

                                     "",
                                     false,
                                     SecurityAccessLevel.View,
                                     true,
                                     false);
                    }
                    if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "IMPORT", Configuration))
                    {
                        _moduleGenericActions.Actions.Add(GetNextActionID(),
                                     Localization.GetString(ModuleActionType.ImportModule, Localization.GlobalResourceFile),
                                     ModuleActionType.ImportModule,
                                     "",
                                     "action_import.gif",
                                     NavigateUrl(PortalSettings.ActiveTab.TabID, "ImportModule", false, "moduleid=" + ModuleId, "ReturnURL=" + FilterUrl(request)),
                                     "",
                                     false,
                                     SecurityAccessLevel.View,
                                     true,
                                     false);
                    }
                }
                if (Configuration.DesktopModule.IsSearchable && Configuration.DisplaySyndicate)
                {
                    AddSyndicateAction();
                }
            }

            //help module actions available to content editors and administrators
            const string permisisonList = "CONTENT,DELETE,EDIT,EXPORT,IMPORT,MANAGE";
            if (ModulePermissionController.HasModulePermission(Configuration.ModulePermissions, permisisonList) 
                    && request.QueryString["ctl"] != "Help"
                    && !Globals.IsAdminControl())
            {
                AddHelpActions();
            }

            //Add Print Action
            if (Configuration.DisplayPrint)
            {
                //print module action available to everyone
                AddPrintAction();
            }

            if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Host, "MANAGE", Configuration) && !Globals.IsAdminControl())
            {
                _moduleGenericActions.Actions.Add(GetNextActionID(),
                             Localization.GetString(ModuleActionType.ViewSource, Localization.GlobalResourceFile),
                             ModuleActionType.ViewSource,
                             "",
                             "action_source.gif",
                             NavigateUrl(TabId, "ViewSource", false, "ModuleId=" + ModuleId, "ctlid=" + Configuration.ModuleControlId, "ReturnURL=" + FilterUrl(request)),
                             false,
                             SecurityAccessLevel.Host,
                             true,
                             false);
            }



            if (!Globals.IsAdminControl() && ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "DELETE,MANAGE", Configuration))
            {
                if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "DELETE", Configuration))
                {
                    //Check if this is the owner instance of a shared module.
                    string confirmText = "confirm('" + ClientAPI.GetSafeJSString(Localization.GetString("DeleteModule.Confirm")) + "')";
                    if (!Configuration.IsShared)
                    {
                        var portal = PortalController.Instance.GetPortal(PortalSettings.PortalId);
                        if (PortalGroupController.Instance.IsModuleShared(Configuration.ModuleID, portal))
                        {
                            confirmText = "confirm('" + ClientAPI.GetSafeJSString(Localization.GetString("DeleteSharedModule.Confirm")) + "')";
                        }
                    }

                    _moduleGenericActions.Actions.Add(GetNextActionID(),
                                 Localization.GetString(ModuleActionType.DeleteModule, Localization.GlobalResourceFile),
                                 ModuleActionType.DeleteModule,
                                 Configuration.ModuleID.ToString(),
                                 "action_delete.gif",
                                 "",
                                 confirmText,
                                 false,
                                 SecurityAccessLevel.View,
                                 true,
                                 false);
                }
                if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "MANAGE", Configuration))
                {
                    _moduleGenericActions.Actions.Add(GetNextActionID(),
                                 Localization.GetString(ModuleActionType.ClearCache, Localization.GlobalResourceFile),
                                 ModuleActionType.ClearCache,
                                 Configuration.ModuleID.ToString(),
                                 "action_refresh.gif",
                                 "",
                                 false,
                                 SecurityAccessLevel.View,
                                 true,
                                 false);
                }

                if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "MANAGE", Configuration))
                {
                    //module movement
                    AddMenuMoveActions();
                }
            }

            if (_moduleGenericActions.Actions.Count > 0)
            {
                _actions.Add(_moduleGenericActions);
            }

            if (_moduleMoveActions != null && _moduleMoveActions.Actions.Count > 0)
            {
                _actions.Add(_moduleMoveActions);
            }

            foreach (ModuleAction action in _moduleGenericActions.Actions)
            {
                if (!UIUtilities.IsLegacyUI(ModuleId, action.ControlKey, PortalId) && action.Url.Contains("ctl"))
                {
                    action.ClientScript = UrlUtils.PopUpUrl(action.Url, _moduleControl as Control, PortalSettings, true, false);
                }
            }
        }
示例#33
0
 public override void Good(HttpRequest req, HttpResponse resp)
 {
     GoodG2B1(req, resp);
     GoodG2B2(req, resp);
 }
 public static CollectionValueRepresentation Create(IOidStrategy oidStrategy, PropertyContextFacade propertyContext, HttpRequest req, RestControlFlags flags) => new CollectionValueRepresentation(oidStrategy, propertyContext, req, flags);
        private void SetValue(PropertyContextFacade propertyContext, HttpRequest req, RestControlFlags flags)
        {
            var collectionItems = propertyContext.Property.GetValue(propertyContext.Target).ToEnumerable();

            Value = collectionItems.Select(i => LinkRepresentation.Create(OidStrategy, new ValueRelType(propertyContext.Property, new UriMtHelper(OidStrategy, req, i)), flags, new OptionalProperty(JsonPropertyNames.Title, RestUtils.SafeGetTitle(i)))).ToArray();
        }
 protected CollectionValueRepresentation(IOidStrategy oidStrategy, PropertyContextFacade propertyContext, HttpRequest req, RestControlFlags flags)
     : base(oidStrategy, flags)
 {
     SetScalars(propertyContext);
     SetValue(propertyContext, req, flags);
     SelfRelType = new CollectionValueRelType(RelValues.Self, new UriMtHelper(oidStrategy, req, propertyContext));
     SetLinks(req, propertyContext, new ObjectRelType(RelValues.Up, new UriMtHelper(oidStrategy, req, propertyContext.Target)));
     SetExtensions();
     SetHeader(propertyContext.Target);
 }
 /* goodG2B() - use goodsource and badsink */
 public static void GoodG2BSink(string data, HttpRequest req, HttpResponse resp)
 {
     CWE601_Open_Redirect__Web_QueryString_Web_53c.GoodG2BSink(data, req, resp);
 }
 public Task OnRequestError(string requestId, Exception ex, dynamic vm, RouteData routeData, HttpRequest request)
 {
     //NOP
     return(Task.CompletedTask);
 }
示例#39
0
 private void AuthorizeUserViaBearerToken(HttpRequest request)
 {
     this.Identity = this.accessTokenProtector.Unprotect(request.Headers["X-NB-Authorization"]);
 }
 private static string FilterUrl(HttpRequest request)
 {
     return request.RawUrl.Replace("\"", "");
 }
示例#41
0
        public static bool IsTrusted(this HttpRequest request)
        {
            var user = request.HttpContext.User;

            return(user.Identity.IsAuthenticated);
        }
示例#42
0
 private bool IsFromWhitelists(HttpRequest request)
 {
     return(this.IPWhitelists != null && this.IPWhitelists.Contains(request.Host.Host));
 }
 /* goodG2B() - use goodsource and badsink */
 public static void GoodG2BSink(string data, HttpRequest req, HttpResponse resp)
 {
     CWE470_Unsafe_Reflection__Web_QueryString_Web_53c.GoodG2BSink(data, req, resp);
 }
示例#44
0
 private static bool HasAuthorizationHeader(HttpRequest request, string scheme = "Bearer")
 {
     return(request.Headers["X-NB-Authorization"] != StringValues.Empty && request.Headers["X-NB-Authorization"].Contains(scheme));
 }
 public void SetUp()
 {
   _defaultRequest = new HttpRequest(string.Empty, "http://google.com", string.Empty);
 }
示例#46
0
 public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "query/{queryName}")] HttpRequest req, TraceWriter log, string queryName)
 {
     return(await Func.Handle(queryName, req, log));
 }
 /// <summary>
 /// Performs request authentication.
 /// </summary>
 /// <param name="request">Instance of <see cref="HttpRequest"/>.</param>
 /// <returns>Instance of <see cref="ClaimsPrincipal"/>, or <c>null</c> if user was not authenticated.</returns>
 protected abstract ClaimsPrincipal AuthenticateRequest(HttpRequest request);
示例#48
0
 public static SignalRConnectionInfo GetSignalRInfo(
     [HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req,
     [SignalRConnectionInfo(HubName = "simplechat", UserId = "{headers.x-ms-signalr-userid}")] SignalRConnectionInfo connectionInfo)
 {
     return(connectionInfo);
 }
 public AspNetHttpRequestInfo(HttpRequest request)
 {
     this.req = request;
 }
示例#50
0
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            string      errMsg  = "";

            string[]     qryStr   = request.QueryString[0].ToLower().Split('|');
            HttpResponse response = context.Response;

            string _search        = request["_search"];
            string numberOfRows   = request["rows"];
            string pageIndex      = request["page"];
            string sortColumnName = request["sidx"];
            string sortOrderBy    = request["sord"];
            int    totalRecords;
            string output = "";
            var    client = new EyeWebServiceClient();

            switch (qryStr[0].ToLower())
            {
            case "getchildren":

                var patients =
                    client.ListChildrenProfile(int.Parse(HttpContext.Current.Session["userId"].ToString()));
                List <Dictionary <String, Object> > tableRowsChildren = new List <Dictionary <String, Object> >();
                Dictionary <String, Object>         rowChildren;
                foreach (var dr in patients)
                {
                    rowChildren = new Dictionary <String, Object>();
                    rowChildren["patientId"]  = dr.patientId;
                    rowChildren["parentId"]   = dr.parentId;
                    rowChildren["providerId"] = dr.providerId;
                    rowChildren["firstName"]  = dr.firstName;
                    rowChildren["lastName"]   = dr.lastName;
                    rowChildren["dob"]        = dr.dob;
                    rowChildren["gender"]     = dr.gender;
                    var providerProfile = client.GetUserProfile(dr.providerId);
                    rowChildren["providerName"] = providerProfile.firstName + " " + providerProfile.lastName;
                    tableRowsChildren.Add(rowChildren);
                }
                output = new JavaScriptSerializer().Serialize(tableRowsChildren);


                /*
                 * output =JsonConvert.SerializeObject(new GridProperties<Patient>
                 *  {
                 *      rows = patients,
                 *      records = Convert.ToInt32(numberOfRows),
                 *      total = (patients.Count + Convert.ToInt32(numberOfRows) - 1)/Convert.ToInt32(numberOfRows),
                 *      page = Convert.ToInt32(pageIndex)
                 *
                 *  });*/
                break;

            case "editchildren":
                XElement patientEntity = new XElement("patientEntity");
                if (context.Request.RequestType.ToString().ToLower() == "post")
                {
                    string[] keys = context.Request.Form.AllKeys;
                    for (int i = 0; i < keys.Length; i++)
                    {
                        patientEntity.Add(new XElement(keys[i], context.Request.Form[(keys[i])].ToString()));
                    }
                }
                if ((string)patientEntity.Element("oper") == "edit")
                {
                    Patient editPatient = new Patient
                    {
                        patientId  = (int)patientEntity.Element("patientId"),
                        parentId   = (int)patientEntity.Element("parentId"),
                        providerId = (int)patientEntity.Element("providerNameDdl"),
                        firstName  = (string)patientEntity.Element("firstName"),
                        lastName   = (string)patientEntity.Element("lastName"),
                        gender     = (string)patientEntity.Element("genderDdl"),
                        dob        = (string)patientEntity.Element("dob")
                    };
                    client.SetChildProfile(editPatient);
                }
                else
                {
                    Patient newPatient = new Patient
                    {
                        parentId   = int.Parse(HttpContext.Current.Session["userId"].ToString()),
                        providerId = (int)patientEntity.Element("providerNameDdl"),
                        firstName  = (string)patientEntity.Element("firstName"),
                        lastName   = (string)patientEntity.Element("lastName"),
                        gender     = (string)patientEntity.Element("genderDdl"),
                        dob        = (string)patientEntity.Element("dob")
                    };
                    client.SetChildProfile(newPatient);
                }
                break;

            case "getproviders":

                var provList = client.ListAllProviderProfile();
                output = new JavaScriptSerializer().Serialize(provList);
                break;

            case "getgenders":

                var dt = new DataTable();
                dt.Columns.Add(new DataColumn
                {
                    ColumnName = "genderId"
                });
                dt.Columns.Add(new DataColumn
                {
                    ColumnName = "gender"
                });
                DataRow drM = dt.NewRow();
                drM["genderId"] = "M";
                drM["gender"]   = "Male";
                dt.Rows.Add(drM);

                DataRow drF = dt.NewRow();
                drF["genderId"] = "F";
                drF["gender"]   = "Female";
                dt.Rows.Add(drF);

                DataRow drN = dt.NewRow();
                drN["genderId"] = "N";
                drN["gender"]   = "Not specified";
                dt.Rows.Add(drN);

                List <Dictionary <String, Object> > tableRows = new List <Dictionary <String, Object> >();
                Dictionary <String, Object>         row;
                foreach (DataRow dr in dt.Rows)
                {
                    row = new Dictionary <String, Object>();
                    foreach (DataColumn col in dt.Columns)
                    {
                        row.Add(col.ColumnName, dr[col]);
                    }
                    tableRows.Add(row);
                }
                output = new JavaScriptSerializer().Serialize(tableRows);
                break;
            }
            response.Write(output);
        }
示例#51
0
        public async Task <ResponseStructure> TestCheckout(HttpRequest httpRequest, HttpResponse httpResponse, int type = 1)
        {
            try
            {
                var authorize = Barayand.Common.Services.TokenService.AuthorizeUser(httpRequest);
                if (authorize < 1)
                {
                    return(ResponseModel.Error("User not logged in."));
                }
                var basket = await GetBasketItems(httpRequest);

                if (basket.CartItems.Count < 1)
                {
                    return(ResponseModel.Error("Basket is empty."));
                }
                UserModel userModel = await _userrepository.GetById(authorize);

                decimal      wll     = userModel.U_Wallet;
                decimal      Sum     = basket.BasketTotalAmount(_lang.GetLang(), CVRT);
                InvoiceModel invoice = new InvoiceModel();
                invoice.I_TotalAmount        = basket.BasketTotalAmount(_lang.GetLang(), CVRT);
                invoice.I_Id                 = UtilesService.RandomDigit(12);
                invoice.I_UserId             = authorize;
                invoice.I_ShippingCost       = basket.ShippingCost;
                invoice.I_RecipientInfo      = JsonConvert.SerializeObject(basket.RecipientInfo);
                invoice.I_CopponDiscount     = basket.SumDiscount();
                invoice.I_CopponId           = (basket.Coppon.Count > 0) ? basket.Coppon.FirstOrDefault().CP_Id : 0;
                invoice.Created_At           = DateTime.Now;
                invoice.I_PaymentDate        = DateTime.Now;
                invoice.I_TotalProductAmount = basket.BasketTotalProductPrice(_lang.GetLang(), CVRT);
                invoice.I_PaymentInfo        = "Test payment";
                invoice.I_PaymentType        = type;


                if (type == 2)
                {
                    decimal w = (_lang.GetLang() == "fa") ?userModel.U_Wallet : userModel.U_Wallet / CVRT;
                    if (w < basket.BasketTotalAmount(_lang.GetLang(), CVRT))
                    {
                        return(ResponseModel.Error("موجودی کیف پول شما کافی نمیباشد"));
                    }
                    else
                    {
                        w = w - basket.BasketTotalAmount(_lang.GetLang(), CVRT);
                        await _walletrepository.DecreaseWallet(userModel.U_Id, basket.BasketTotalAmount("fa", CVRT));

                        await _smsService.WalletAllert(userModel.U_Phone, 2, basket.BasketTotalAmount(_lang.GetLang(), CVRT).ToString("#,# تومان"));

                        invoice.I_Status = 2;
                    }
                }
                if (type == 3)
                {
                    decimal w = userModel.U_Coupon;
                    if (w < basket.BasketProductBinPriceTotal(BINPERC))
                    {
                        return(ResponseModel.Error("تعداد بن های شما برای پرداخت کافی نمیباشد"));
                    }
                    else
                    {
                        userModel.U_Coupon = userModel.U_Coupon - basket.BasketProductBinPriceTotal(BINPERC);
                        await _userrepository.Update(userModel);

                        invoice.I_Status = 2;
                    }
                }
                if (type == 4)
                {
                    invoice.I_Status = 1;
                }
                if (type == 1)
                {
                    invoice.I_Status = 2;
                }
                ResponseStructure res = await _invoicerepository.Insert(invoice);

                if (!res.Status)
                {
                    return(res);
                }
                int sumGiftBon = basket.BasketProductBinPriceTotal(BINPERC);
                foreach (var item in basket.CartItems)
                {
                    //sumGiftBon += (item.Product.P_GiftBin * item.Quantity);
                    var orderres = await _orderrepository.Insert(new OrderModel()
                    {
                        O_Discount     = (!item.PrintAble) ? basket.BasketProductPrice(item.Product.P_Id, _lang.GetLang(), false, false) : basket.BasketProductPrintablePrice(item.Product.P_Id, _lang.GetLang(), false, false),
                        O_DiscountType = item.Product.P_DiscountType,
                        O_Price        = (!item.PrintAble) ? basket.BasketProductPrice(item.Product.P_Id, _lang.GetLang(), true, false) : basket.BasketProductPrintablePrice(item.Product.P_Id, _lang.GetLang(), true, false),
                        O_Quantity     = item.Quantity,
                        O_ProductId    = item.Product.P_Id,
                        O_ReciptId     = invoice.I_Id,
                        Created_At     = DateTime.Now,
                        Lang           = _lang.GetLang(),
                        O_Version      = item.PrintAble ? 2 : 1
                    });
                }
                userModel.U_Coupon += sumGiftBon;
                await _userrepository.Update(userModel);

                await this.FreeUpCart(httpRequest, httpResponse);

                if (_lang.GetLang() == "fa")
                {
                    await _smsService.OrderAlert(userModel.U_Phone, invoice.I_Id, basket.BasketTotalAmount(_lang.GetLang(), CVRT).ToString("#,# تومان"));
                }

                return(ResponseModel.Success("سفارش شما با موفقیت ثبت گردید", new { invoiceid = invoice.I_Id }));
            }
            catch (Exception ex)
            {
                return(ResponseModel.ServerInternalError(data: ex));
            }
        }
 /// <summary>
 /// Checks whether authorization header is present.
 /// </summary>
 /// <param name="request">Instance of <see cref="HttpRequest"/>.</param>
 /// <returns>'true' if there's authentication header with current authentication provider.</returns>
 protected bool IsAuthorizationPresent(HttpRequest request)
 {
     string authHeader = request.Headers[HeaderNames.Authorization];
     return authHeader != null && authHeader.StartsWith(AuthenicationProvider, StringComparison.OrdinalIgnoreCase);
 }
示例#53
0
 /// <summary>
 /// Creates a SharePointContext instance with the specified HTTP request.
 /// </summary>
 /// <param name="httpRequest">The HTTP request.</param>
 /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
 public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
 {
     return(CreateSharePointContext(new HttpRequestWrapper(httpRequest)));
 }
示例#54
0
        public async Task <ResponseStructure> AddToCart(HttpRequest httpRequest, HttpResponse httpResponse)
        {
            try
            {
                AllProducts = ((List <ProductModel>)(await _productrepo.GetAll()).Data);
                StringValues data;
                StringValues PrintAble;
                if (!httpRequest.Headers.TryGetValue("AddToCart", out data))
                {
                    return(ResponseModel.Error("Invalid access detect."));
                }
                if (!httpRequest.Headers.TryGetValue("PrintAble", out PrintAble))
                {
                    return(ResponseModel.Error("Invalid access detect."));
                }
                var        dec         = Barayand.Common.Services.CryptoJsService.DecryptStringAES(data);
                BasketItem rm          = JsonConvert.DeserializeObject <BasketItem>(dec);
                var        findProduct = AllProducts.FirstOrDefault(x => x.P_Id == rm.ProductId);
                if (findProduct == null)
                {
                    return(ResponseModel.Error("Invalid access detect."));
                }
                var product = new ProductBasketModel()
                {
                    P_BinPrice           = findProduct.P_BinPrice,
                    P_Code               = findProduct.P_Code,
                    P_Discount           = findProduct.P_Discount,
                    P_DiscountPeriodTime = findProduct.P_DiscountPeriodTime,
                    P_DiscountType       = findProduct.P_DiscountType,
                    P_ExternalPrice      = findProduct.P_ExternalPrice,
                    P_GiftBin            = findProduct.P_GiftBin,
                    P_Id                       = findProduct.P_Id,
                    P_Image                    = findProduct.P_Image,
                    P_PageCount                = findProduct.P_PageCount,
                    P_PeriodDiscountPrice      = findProduct.P_PeriodDiscountPrice,
                    P_PeriodDiscountPriceType  = findProduct.P_PeriodDiscountPriceType,
                    P_PeriodPrintableFomrulaId = findProduct.P_PeriodPrintableFomrulaId,
                    P_PeriodPrintablePrice     = findProduct.P_PeriodPrintablePrice,
                    P_PeriodPrintablePriceType = findProduct.P_PeriodPrintablePriceType,
                    P_Price                    = findProduct.P_Price,
                    P_PriceFormulaId           = findProduct.P_PriceFormulaId,
                    P_PriceType                = findProduct.P_PriceType,
                    P_PrintAbleVerFormulaId    = findProduct.P_PrintAbleVerFormulaId,
                    P_PrintAbleVerPrice        = findProduct.P_PrintAbleVerPrice,
                    P_PrintAbleVerPriceType    = findProduct.P_PrintAbleVerPriceType,
                    P_PrintAbleVersion         = findProduct.P_PrintAbleVersion,
                    P_PriodDiscountFormulaId   = findProduct.P_PriodDiscountFormulaId,
                    P_Title                    = findProduct.P_Title,
                    P_Type                     = findProduct.P_Type,
                    P_Weight                   = findProduct.P_Weight,
                    PriceModel                 = await _priceCalculator.CalculateBookPrice(findProduct.P_Id, _lang.GetLang())
                };
                rm.PrintAble = bool.Parse(PrintAble);
                BasketModel basket = new BasketModel();
                string      cookie;
                if (httpRequest.Cookies.TryGetValue("Cart", out cookie))
                {
                    if (cookie != null)
                    {
                        var basketInfo = Barayand.Common.Services.CryptoJsService.DecryptStringAES(cookie);
                        basket = JsonConvert.DeserializeObject <BasketModel>(basketInfo);
                        if (basket.CartItems.Count > 0)
                        {
                            if (basket.CartItems.FirstOrDefault(x => x.Product.P_Type != product.P_Type) != null)
                            {
                                return(ResponseModel.Error("You can only add a type of product (Book or Art or Learning trains) in same time."));
                            }
                        }
                        if (bool.Parse(PrintAble) == false)
                        {
                            var checkDuplicatePdf = basket.CartItems.FirstOrDefault(x => x.Product.P_Id == rm.ProductId && x.PrintAble == false);
                            if (checkDuplicatePdf != null)
                            {
                                return(ResponseModel.Error("از هر کتاب شما تنها میتوانید یک نسخه PDF سفارش دهید"));
                            }
                        }
                        var existsProduct = basket.CartItems.FirstOrDefault(x => x.Product.P_Id == rm.ProductId && x.PrintAble == bool.Parse(PrintAble));
                        if (existsProduct != null)
                        {
                            existsProduct.Quantity += rm.Quantity;
                        }
                        else
                        {
                            rm.Product = product;
                            basket.CartItems.Add(rm);
                        }
                    }
                    else
                    {
                        rm.Product = product;
                        basket.CartItems.Add(rm);
                    }
                }
                else
                {
                    rm.Product = product;
                    basket.CartItems.Add(rm);
                    basket.OrderDate = DateTime.Now;
                }

                string token = Barayand.Common.Services.CryptoJsService.EncryptStringToAES(JsonConvert.SerializeObject(basket));
                httpResponse.Cookies.Delete("Cart");
                httpResponse.Cookies.Append("Cart", token);
                return(ResponseModel.Success("Product added."));
            }
            catch (Exception ex)
            {
                _logger.LogError("Error in adding entity to customer basket", ex);
                return(ResponseModel.ServerInternalError(data: ex));
            }
        }
示例#55
0
 public static void Send(HttpRequest request, MessageAction action, string d1, string d2, string d3, string d4)
 {
     SendRequestMessage(request, null, action, null, d1, d2, d3, d4);
 }
示例#56
0
 /// <summary>
 /// Gets the SharePoint host url from QueryString of the specified HTTP request.
 /// </summary>
 /// <param name="httpRequest">The specified HTTP request.</param>
 /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
 public static Uri GetSPHostUrl(HttpRequest httpRequest)
 {
     return(GetSPHostUrl(new HttpRequestWrapper(httpRequest)));
 }
示例#57
0
 public static void Send(HttpRequest request, string loginName, MessageAction action, MessageTarget target, string d1)
 {
     SendRequestMessage(request, loginName, action, target, d1);
 }
示例#58
0
 public static void Send(HttpRequest request, MessageAction action, IEnumerable <string> d1)
 {
     SendRequestMessage(request, null, action, null, string.Join(", ", d1));
 }
示例#59
0
 public static void Send(HttpRequest request, MessageAction action, MessageTarget target, string d1, string d2, IEnumerable <string> d3)
 {
     SendRequestMessage(request, null, action, target, d1, d2, string.Join(", ", d3));
 }
示例#60
0
 public static void Send(HttpRequest request, MessageAction action, string d1)
 {
     SendRequestMessage(request, null, action, null, d1);
 }