public void SetsContentNullIfBodyValueIsNull()
 {
     var requestInfo = new RequestInfo(HttpMethod.Get, "foo");
     requestInfo.SetBodyParameterInfo<object>(BodySerializationMethod.Serialized, null);
     var content = this.requester.ConstructContent(requestInfo);
     Assert.Null(content);
 }
 public void ConstructsUriWithEscapedGivenParams()
 {
     var requestInfo = new RequestInfo(HttpMethod.Get, null);
     requestInfo.AddQueryParameter(QuerySerializationMethod.ToString, "b ar", "b az");
     var uri = this.requester.ConstructUri("/foo", requestInfo);
     Assert.Equal(new Uri("http://api.example.com/base/foo?b+ar=b+az"), uri);
 }
Exemple #3
0
        public override void Request(RequestLocalOptions opt, Message req, Action<Message> on_rpy)
        {
            string id;
            string is_closed;
            lock (state_lock) {
                id = (nextid++).ToString ();
                is_closed = closed_err;
                if (is_closed == null) {
                    pending [id] = new RequestInfo {
                        cb = on_rpy,
                        timeout = new Timer ((s) => {
                            RequestTimedOut (id);
                        }, null, (opt.Timeout + 5) * 1000, Timeout.Infinite),
                    };
                }
            }

            if (is_closed != null) {
                req.Discard ();
                Message.StreamToCallback (on_rpy, new RPCException ("transport", "Connection is closed", RPCException.DispatchFailure ()).AsHeader ());
            } else {
                req.Header ["request_id"] = id;
                req.Header ["type"] = "request";
                p.SendMessage (req);
            }
        }
 public void SubstitutesMultiplePathParametersOfTheSameType()
 {
     var requestInfo = new RequestInfo(HttpMethod.Get, "/foo/{bar}/{bar}");
     requestInfo.AddPathParameter("bar", "yay");
     var uri = this.requester.SubstitutePathParameters(requestInfo);
     Assert.Equal("/foo/yay/yay", uri);
 }
 public void EncodesPathParams()
 {
     var requestInfo = new RequestInfo(HttpMethod.Get, "/foo/{bar}/baz");
     requestInfo.AddPathParameter<string>("bar", "a/b/c");
     var uri = this.requester.SubstitutePathParameters(requestInfo);
     Assert.Equal("/foo/a%2fb%2fc/baz", uri);
 }
 public void TreatsNullPathParamsAsEmpty()
 {
     var requestInfo = new RequestInfo(HttpMethod.Get, "/foo/{bar}/baz");
     requestInfo.AddPathParameter<int?>("bar", null);
     var uri = this.requester.SubstitutePathParameters(requestInfo);
     Assert.Equal("/foo//baz", uri);
 }
 public void IgnoresNullQueryParamArrayValuesWhenUsingToString()
 {
     var requestInfo = new RequestInfo(HttpMethod.Get, null);
     requestInfo.AddQueryCollectionParameter<object>(QuerySerializationMethod.ToString, "foo", new[] { "bar", null, "baz" });
     var uri = this.requester.ConstructUri("/foo", requestInfo);
     Assert.Equal(new Uri("http://api.example.com/base/foo?foo=bar&foo=baz"), uri);
 }
        /// <summary>
        /// Adds the request info to the event.
        /// </summary>
        public static void AddRequestInfo(this Event ev, RequestInfo request)
        {
            if (request == null)
                return;

            ev.Data[Event.KnownDataKeys.RequestInfo] = request;
        }
        internal ArgumentBindingContext(RequestInfo request, RequestMapping requestMapping, ParameterInfo parameter, int index, IDictionary<RequestInfo, RequestInfo[]> multipartBodies)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (requestMapping == null)
            {
                throw new ArgumentNullException("requestMapping");
            }

            if (parameter == null)
            {
                throw new ArgumentNullException("parameter");
            }

            if (multipartBodies == null)
            {
                throw new ArgumentNullException("multipartBodies");
            }

            Request = request;
            RequestMapping = requestMapping;
            Parameter = parameter;
            Index = index;
            MultipartBodies = multipartBodies;
        }
 public HttpResponse Execute(RequestInfo req)
 {
     var o = Activator.CreateInstance(_mi.DeclaringType);
     var prms = new object[_binders.Length];
     for(var i = 0 ; i<_binders.Length ; ++i)
     {
         prms[i] = _binders[i](req);
     }
     try
     {
         return _mi.Invoke(o, prms) as HttpResponse;
     }
     catch (TargetInvocationException e)
     {
         throw e.InnerException;
     }
     catch(ArgumentException e)
     {
         return new HttpResponse(HttpStatusCode.BadRequest, new TextContent(e.Message));
     }
     catch(InvalidOperationException e)
     {
         return new HttpResponse(HttpStatusCode.InternalServerError, new TextContent(e.Message));
     }
 }
        internal ChannelHandler(MessageVersion messageVersion, IChannelBinder binder, ServiceChannel channel)
        {
            ClientRuntime clientRuntime = channel.ClientRuntime;

            _messageVersion = messageVersion;
            _isManualAddressing = clientRuntime.ManualAddressing;
            _binder = binder;
            _channel = channel;

            _isConcurrent = true;
            _duplexBinder = binder as DuplexChannelBinder;
            _hasSession = binder.HasSession;
            _isCallback = true;

            DispatchRuntime dispatchRuntime = clientRuntime.DispatchRuntime;
            if (dispatchRuntime == null)
            {
                _receiver = new ErrorHandlingReceiver(binder, null);
            }
            else
            {
                _receiver = new ErrorHandlingReceiver(binder, dispatchRuntime.ChannelDispatcher);
            }
            _requestInfo = new RequestInfo(this);
        }
        public void Cache(RequestInfo requestInfo, string answer)
        {
            HashAnswer hashAnswer = new HashAnswer();
            hashAnswer.Answer = answer;
            hashAnswer.QuestionText = requestInfo.Data;

            var firstOrDefault = work.HandlerTypes.GetAll().FirstOrDefault(
                x => x.Name == requestInfo.HandlerName);

            if (firstOrDefault != null)
            {
                hashAnswer.HandlerTypeId = firstOrDefault.Id;
            }
            else
            {
                // Create handler type if note exists
                HandlerType handler = new HandlerType()
                {
                    Name = requestInfo.HandlerName
                };
                work.HandlerTypes.Create(handler);
                work.Save();
                hashAnswer.HandlerTypeId =
                    work.HandlerTypes.GetAll().First(x => x.Name == requestInfo.HandlerName).Id;
            }

            work.HashAnswers.Create(hashAnswer);
            work.Save();
        }
Exemple #13
0
 public HttpResponseMessage Get()
 {
     string dsName = (string)Request.Properties[Constants.ODataDataSource];
     var ds = DataSourceProvider.GetDataSource(dsName);
     var options = BuildQueryOptions();
     EdmEntityObjectCollection rtv = null;
     if (DynamicOData.BeforeExcute != null)
     {
         var ri = new RequestInfo(dsName)
         {
             Method = MethodType.Get,
             QueryOptions = options,
             Target = options.Context.Path.Segments[0].ToString()
         };
         DynamicOData.BeforeExcute(ri);
         if (!ri.Result)
             return Request.CreateResponse(ri.StatusCode, ri.Message);
     }
     try
     {
         rtv = ds.Get(options);
         if (options.SelectExpand != null)
             Request.ODataProperties().SelectExpandClause = options.SelectExpand.SelectExpandClause;
         return Request.CreateResponse(HttpStatusCode.OK, rtv);
     }
     catch (UnauthorizedAccessException ex)
     {
         return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex);
     }
     catch (Exception err)
     {
         return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, err);
     }
 }
Exemple #14
0
 public HttpResponseMessage Delete(string key)
 {
     var path = Request.ODataProperties().Path;
     var edmType = path.Segments[0].GetEdmType(path.EdmType);
     string dsName = (string)Request.Properties[Constants.ODataDataSource];
     var ds = DataSourceProvider.GetDataSource(dsName);
     if (DynamicOData.BeforeExcute != null)
     {
         var ri = new RequestInfo(dsName)
         {
             Method = MethodType.Delete,
             Target = (edmType as EdmEntityType).Name
         };
         DynamicOData.BeforeExcute(ri);
         if (!ri.Result)
             return Request.CreateResponse(ri.StatusCode, ri.Message);
     }
     try
     {
         var count = ds.Delete(key, edmType);
         return Request.CreateResponse(HttpStatusCode.OK, count);
     }
     catch (UnauthorizedAccessException ex)
     {
         return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex);
     }
     catch (Exception err)
     {
         return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, err);
     }
 }
Exemple #15
0
        public void HeadersFromPropertiesCombineWithHeadersFromClass()
        {
            var requestInfo = new RequestInfo(HttpMethod.Get, "foo");
            requestInfo.ClassHeaders = new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("This-Will-Stay", "YesIWill"),
                new KeyValuePair<string, string>("Something", "SomethingElse"),
                new KeyValuePair<string, string>("User-Agent", "RestEase"),
                new KeyValuePair<string, string>("X-API-Key", "Foo"),
            };

            requestInfo.AddPropertyHeader<string>("Something", null, null);
            requestInfo.AddPropertyHeader("User-Agent", String.Empty, null);
            requestInfo.AddPropertyHeader("X-API-Key", "Bar", null);
            requestInfo.AddPropertyHeader("This-Is-New", "YesIAm", null);

            var message = new HttpRequestMessage();
            this.requester.ApplyHeaders(requestInfo, message);

            Assert.Equal(new[] { "YesIWill" }, message.Headers.GetValues("This-Will-Stay"));
            Assert.Equal(new[] { "SomethingElse" }, message.Headers.GetValues("Something"));
            Assert.Equal(new[] { "RestEase", "" }, message.Headers.GetValues("User-Agent"));
            Assert.Equal(new[] { "Foo", "Bar" }, message.Headers.GetValues("X-API-Key"));
            Assert.Equal(new[] { "YesIAm" }, message.Headers.GetValues("This-Is-New"));
        }
        public void RequestAsyncSendsRequest()
        {
            var requester = new RequesterWithStubbedSendRequestAsync(null);
            var responseMessage = new HttpResponseMessage()
            {
                Content = new StringContent("content"),
            };
            requester.ResponseMessage = Task.FromResult(responseMessage);
            var responseDeserializer = new Mock<IResponseDeserializer>();
            requester.ResponseDeserializer = responseDeserializer.Object;
            var cancellationToken = new CancellationToken();

            responseDeserializer.Setup(x => x.Deserialize<string>("content", responseMessage))
                .Returns("hello")
                .Verifiable();

            var requestInfo = new RequestInfo(HttpMethod.Get, "foo");
            requestInfo.CancellationToken = cancellationToken;
            var result = requester.RequestAsync<string>(requestInfo).Result;

            responseDeserializer.Verify();

            Assert.Equal(requestInfo, requester.RequestInfo);
            Assert.Equal("hello", result);
        }
Exemple #17
0
 public void GNTPParserTest()
 {
     var pw = new PasswordManager();
     var info = new RequestInfo();
     var parser = new GNTPParser(pw, false, true, true, true, info);
     var items = new List<IGNTPRequest>();
     parser.MessageParsed += (req) =>
     {
         items.Add(req);
     };
     parser.Error += (error) =>
     {
         Assert.Fail("ErrorCode={0}, Description={1}", error.ErrorCode, error.ErrorDescription);
     };
     ParseAll(parser);
     Assert.IsTrue(items.Count > 0);
     foreach (var item in items) {
         if (item.Directive == RequestType.NOTIFY) {
             var nLog = NeithNotificationRec.FromHeaders(item.Headers);
         }
         if (item.Directive == RequestType.REGISTER) {
             var app = Application.FromHeaders(item.Headers);
             Assert.AreEqual("SurfWriter", app.Name);
         }
     }
 }
 public void SetsContentNullIfBodyParameterInfoNull()
 {
     var requestInfo = new RequestInfo(HttpMethod.Get, "foo");
     // Not calling SetBodyParameterInfo
     var content = this.requester.ConstructContent(requestInfo);
     Assert.Null(content);
 }
 public void SubstitutesPathParameters()
 {
     var requestInfo = new RequestInfo(HttpMethod.Get, "/foo/{bar}/{baz}");
     requestInfo.AddPathParameter("bar", "yay");
     requestInfo.AddPathParameter("baz", "woo");
     var uri = this.requester.SubstitutePathParameters(requestInfo);
     Assert.Equal("/foo/yay/woo", uri);
 }
        public void SetsContentAsHttpContentIfBodyIsHttpContent()
        {
            var requestInfo = new RequestInfo(HttpMethod.Get, "foo");
            var content = new StringContent("test");
            requestInfo.SetBodyParameterInfo(BodySerializationMethod.Serialized, content);

            Assert.Equal(content, this.requester.ConstructContent(requestInfo));
        }
 public HttpResponse Process(RequestInfo requestInfo)
 {
     var ctx = requestInfo.Context;
     Trace.TraceInformation("[LogFilter]: Request for URI '{0}'", ctx.Request.Url);
     var resp = _nextFilter.Process(requestInfo);
     Trace.TraceInformation("[LogFilter]: User '{0}'", requestInfo.User != null ? requestInfo.User.Identity.Name : String.Empty);
     return resp;
 }
        public void SetsContentAsStringContentIfBodyIsString()
        {
            var requestInfo = new RequestInfo(HttpMethod.Get, "foo");
            requestInfo.SetBodyParameterInfo(BodySerializationMethod.Serialized, "hello");
            var content = this.requester.ConstructContent(requestInfo);

            Assert.IsType<StringContent>(content);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GNTPWebSocketReader"/> class.
        /// </summary>
        /// <param name="socket">The <see cref="AsyncSocket"/></param>
        /// <param name="passwordManager">The <see cref="PasswordManager"/> containing a list of allowed passwords</param>
        /// <param name="passwordRequired">Indicates if a password is required</param>
        /// <param name="allowNetworkNotifications">Indicates if network requests are allowed</param>
        /// <param name="allowBrowserConnections">Indicates if browser requests are allowed</param>
        /// <param name="allowSubscriptions">Indicates if SUBSCRIPTION requests are allowed</param>
        /// <param name="requestInfo">The <see cref="RequestInfo"/> associated with this request</param>
        public GNTPWebSocketReader(AsyncSocket socket, PasswordManager passwordManager, bool passwordRequired, bool allowNetworkNotifications, bool allowBrowserConnections, bool allowSubscriptions, RequestInfo requestInfo)
            : base(socket, passwordManager, passwordRequired, allowNetworkNotifications, allowBrowserConnections, allowSubscriptions, requestInfo)
        {
            this.allowed = allowBrowserConnections;

            parser = new GNTPParser2(passwordManager, passwordRequired, allowNetworkNotifications, allowBrowserConnections, allowSubscriptions, requestInfo);
            parser.MessageParsed += new GNTPParser2.GNTPParserMessageParsedEventHandler(parser_MessageParsed);
            parser.Error += new GNTPParser2.GNTPParserErrorEventHandler(parser_Error);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GNTPSocketReader"/> class.
        /// </summary>
        /// <param name="socket">The <see cref="AsyncSocket"/></param>
        /// <param name="passwordManager">The <see cref="PasswordManager"/> containing a list of allowed passwords</param>
        /// <param name="passwordRequired">Indicates if a password is required</param>
        /// <param name="allowNetworkNotifications">Indicates if network requests are allowed</param>
        /// <param name="allowBrowserConnections">Indicates if browser requests are allowed</param>
        /// <param name="allowSubscriptions">Indicates if SUBSCRIPTION requests are allowed</param>
        /// <param name="requestInfo">The <see cref="RequestInfo"/> associated with this request</param>
        public GNTPSocketReader(AsyncSocket socket, PasswordManager passwordManager, bool passwordRequired, bool allowNetworkNotifications, bool allowBrowserConnections, bool allowSubscriptions, RequestInfo requestInfo)
        {
            this.parser = new GNTPParser(passwordManager, passwordRequired, allowNetworkNotifications, allowBrowserConnections, allowSubscriptions, requestInfo);
            parser.Error += new GNTPParser.GNTPParserErrorEventHandler(parser_Error);
            parser.MessageParsed += new GNTPParser.GNTPParserMessageParsedEventHandler(parser_MessageParsed);

            this.socket = socket;
            this.socket.Tag = parser;
        }
        public void RequestVoidAsyncSendsRequest()
        {
            var requester = new RequesterWithStubbedSendRequestAsync(null);
            requester.ResponseMessage = Task.FromResult(new HttpResponseMessage());

            var requestInfo = new RequestInfo(HttpMethod.Get, "foo");
            requester.RequestVoidAsync(requestInfo).Wait();

            Assert.Equal(requestInfo, requester.RequestInfo);
        }
Exemple #26
0
        public void AppliesHeadersFromParams()
        {
            var requestInfo = new RequestInfo(HttpMethod.Get, "foo");
            requestInfo.AddHeaderParameter("User-Agent", "RestEase");
            requestInfo.AddHeaderParameter("X-API-Key", "Foo");

            var message = new HttpRequestMessage();
            this.requester.ApplyHeaders(requestInfo, message);

            Assert.Equal("User-Agent: RestEase\r\nX-API-Key: Foo\r\n", message.Headers.ToString());
        }
        protected IEnumerable<string> GetIpAddresses(PersistentEvent ev, RequestInfo request) {
            if (request != null && !String.IsNullOrWhiteSpace(request.ClientIpAddress))
                yield return request.ClientIpAddress;

            var environmentInfo = ev.GetEnvironmentInfo();
            if (environmentInfo == null || String.IsNullOrWhiteSpace(environmentInfo.IpAddress))
                yield break;

            foreach (var ip in environmentInfo.IpAddress.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                yield return ip;
        }
        public string GetAnswer(RequestInfo info)
        {
            string answer = cachedAnswers.GetAnswer(info);

            if (answer == string.Empty)
            {
                var searchingResult = GetAnswer(info.Data);
                answer = new TextRange(searchingResult.ContentStart, searchingResult.ContentEnd).Text;
                cachedAnswers.Cache(info, answer);
            }

            return answer;
        }
        /// <summary>
        /// Gets cached answer on request.
        /// </summary>
        /// <param name="handler">Type of request.</param>
        /// <param name="request"></param>
        /// <returns>Null if there is no answer.</returns>
        public string GetAnswer(RequestInfo requestInfo)
        {
            var firstOrDefault = work.HashAnswers.GetAll().FirstOrDefault(
                x => x.QuestionText == requestInfo.Data
                     && x.Handler.Name == requestInfo.HandlerName);

            if (firstOrDefault != null)
            {
                return firstOrDefault.Answer;
            }

            return string.Empty;
        }
Exemple #30
0
        public void AppliesHeadersFromClass()
        {
            var requestInfo = new RequestInfo(HttpMethod.Get, "foo");
            requestInfo.ClassHeaders = new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("User-Agent", "RestEase"),
                new KeyValuePair<string, string>("X-API-Key", "Foo"),
            };

            var message = new HttpRequestMessage();
            this.requester.ApplyHeaders(requestInfo, message);

            Assert.Equal("User-Agent: RestEase\r\nX-API-Key: Foo\r\n", message.Headers.ToString());
        }
Exemple #31
0
        async Task <JObject> CreateContentAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
        {
            // check permission on convert
            if (requestInfo.Extra != null && requestInfo.Extra.ContainsKey("x-convert"))
            {
                if (!await this.IsSystemAdministratorAsync(requestInfo).ConfigureAwait(false))
                {
                    throw new AccessDeniedException();
                }
            }

            // check permission on create new
            else if (!await this.IsAuthorizedAsync(requestInfo, "content", Components.Security.Action.Update, cancellationToken).ConfigureAwait(false))
            {
                throw new AccessDeniedException();
            }

            // update information
            var body    = requestInfo.GetBodyExpando();
            var content = body.Copy <Content>("ID,LastUpdated,LastModified,LastModifiedID,Created,CreatedID,EndingTime,Images,Counters".ToHashSet());

            content.ID        = UtilityService.NewUUID;
            content.Created   = content.LastModified = content.LastUpdated = DateTime.Now;
            content.CreatedID = content.LastModifiedID = requestInfo.Session.User.ID;
            content.MediaURI  = string.IsNullOrWhiteSpace(content.MediaURI)
                                ? ""
                                : content.MediaURI.IsStartsWith(this.FilesHttpURI)
                                        ? content.MediaURI.Replace(this.FilesHttpURI, "~~")
                                        : content.MediaURI;

            var endingTime = body.Get <string>("EndingTime");

            content.EndingTime = endingTime != null?DateTime.Parse(endingTime).ToDTString() : "-";

            if (string.IsNullOrWhiteSpace(content.ParentID))
            {
                content.ParentID = content.OrderIndex = null;
            }

            // update database
            await Content.CreateAsync(content, cancellationToken).ConfigureAwait(false);

            // get files and generate JSON
            var files = await this.GetFilesAsync(requestInfo, content.ID, content.Title, cancellationToken).ConfigureAwait(false);

            var json = content.ToJson(files, ojson => ojson["MediaURI"] = content.MediaURI.Replace("~~", this.FilesHttpURI));

            // send update message
            if (content.Status.Equals(ApprovalStatus.Published))
            {
                await this.SendUpdateMessageAsync(new UpdateMessage
                {
                    Type             = $"{this.ServiceName}#Content#Update",
                    DeviceID         = "*",
                    ExcludedDeviceID = requestInfo.Session.DeviceID,
                    Data             = json
                }, cancellationToken).ConfigureAwait(false);
            }

            // return
            return(json);
        }
Exemple #32
0
        public ActionResult Napthe(FormCollection collection)
        {
            if (Session["login"] == null)
            {
                HttpContext.Application["_controler"] = "Service";
                HttpContext.Application["_action"]    = "Napthe";
                return(RedirectToAction("Index", "Account"));
                //return RedirectToAction("Index", HttpContext.Application["_controler"] as string);
            }

            if (collection["seri"].ToString() == "" || collection["pin"].ToString() == "")
            {
                TempData["errorcard"]   = "Vui lòng nhập đầy đủ thông tin thẻ cào.";
                TempData["successcard"] = null;
                _9d_percen p = accountContext._9d_percens.FirstOrDefault();
                TempData["status"] = p.status;
                return(View());
            }

            try
            {
                _9d_percen p = accountContext._9d_percens.FirstOrDefault();
                TempData["status"] = p.status;

                RequestInfo info = new RequestInfo();
                info.Merchant_id       = "36680";
                info.Merchant_acount   = "*****@*****.**";
                info.Merchant_password = "******";

                //Nhà mạng
                info.CardType = collection["MovieType"].ToString();
                info.Pincard  = collection["pin"].ToString();

                //Mã đơn hàng
                info.Refcode    = (new Random().Next(0, 10000)).ToString();
                info.SerialCard = collection["seri"].ToString();

                ResponseInfo resutl = NLCardLib.CardChage(info);

                if (resutl.Errorcode.Equals("00"))
                {
                    _9d_user user     = accountContext._9d_users.Where(c => c.user_name == Session["login"].ToString() && c.delete_flag == false).FirstOrDefault();
                    int      coutncar = (Convert.ToInt32(resutl.Card_amount) * p.percen) / 100;
                    user.balance = user.balance + coutncar;
                    accountContext.SubmitChanges();

                    User_History addhistory = new User_History();
                    addhistory.user_name = Session["login"].ToString();
                    addhistory.time_into = DateTime.Now;
                    addhistory.car_info  = coutncar.ToString();
                    addhistory.car_type  = collection["MovieType"].ToString();
                    accountContext.User_Histories.InsertOnSubmit(addhistory);
                    accountContext.SubmitChanges();
                    _9d_user u = common.getUserInfo(Session["login"].ToString());
                    ViewBag.balance = u != null?u.balance.ToString() : "0";

                    TempData["errorcard"]   = null;
                    TempData["successcard"] = "Chúc mừng, bạn đã nạp thành công thẻ mệnh giá " + coutncar.ToString() + ".";
                }
                else
                {
                    TempData["errorcard"]   = resutl.Message.ToString();
                    TempData["successcard"] = null;
                }

                return(View());
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #33
0
 public static void DoProcess(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session, string method, string module, string key)
 {
     using (var reqinfo = new RequestInfo(request, response, session))
         DoProcess(reqinfo, method, module, key);
 }
Exemple #34
0
        /// <summary>
        /// Creates an instance of ODataMessageWriter.
        /// </summary>
        /// <param name="requestMessage">Instance of IODataRequestMessage.</param>
        /// <param name="requestInfo">RequestInfo containing information about the client settings.</param>
        /// <param name="isParameterPayload">true if the writer is intended to for a parameter payload, false otherwise.</param>
        /// <returns>An instance of ODataMessageWriter.</returns>
        internal static ODataMessageWriter CreateMessageWriter(ODataRequestMessageWrapper requestMessage, RequestInfo requestInfo, bool isParameterPayload)
        {
            var writerSettings = requestInfo.WriteHelper.CreateSettings(requestMessage.IsBatchPartRequest, requestInfo.Context.EnableWritingODataAnnotationWithoutPrefix);

            return(requestMessage.CreateWriter(writerSettings, isParameterPayload));
        }
Exemple #35
0
        /// <inheritdoc/>
        public IEnumerable <Func <Task <HttpContext> > > TransformToInternalRequests(IEnumerable <RequestInfo> requestInfos)
        {
            RequestInfo[] allRequestInfos = requestInfos.ToArray();
            // Check if all requestInfo's contain a valid HttpMethod
            string[] httpMethods = Enum.GetValues(typeof(HttpMethod))
                                   .Cast <HttpMethod>()
                                   .Select(method => method.ToString().ToLower())
                                   .ToArray();
            if (!allRequestInfos.Select(requestInfo => requestInfo.Method.ToLower()).All(httpMethods.Contains))
            {
                return(null);
            }

            bool[] processedRequestInfos             = new bool[allRequestInfos.Length];
            Func <Task <HttpContext> >[] resultFuncs = new Func <Task <HttpContext> > [allRequestInfos.Length];
            foreach (RouteEndpoint routeEndpoint in _routeEndpoints)
            {
                for (int i = 0; i < resultFuncs.Length; i++)
                {
                    if (processedRequestInfos[i])
                    {                     // Already processed this RequestInfo object
                        continue;
                    }

                    RequestInfo         requestInfo = allRequestInfos[i];
                    EndpointMatchResult matchResult = EndpointMatches(routeEndpoint, requestInfo, out RouteValueDictionary routeValues);
                    if (matchResult == EndpointMatchResult.Match || matchResult == EndpointMatchResult.Ignored)
                    {
                        processedRequestInfos[i] = true;
                        if (matchResult == EndpointMatchResult.Ignored)
                        {
                            resultFuncs[i] = GetNotFoundResult;
                            continue;
                        }
                    }
                    else if (matchResult == EndpointMatchResult.NoMatch)
                    {
                        continue;
                    }
                    else
                    {
                        throw new NotImplementedException("Match result " + matchResult.ToString());
                    }

                    // Attempt to build the HTTP Context
                    HttpContext httpContext = BuildHttpContext(routeEndpoint, requestInfo, routeValues);
                    resultFuncs[i] = () =>
                    {
                        TaskCompletionSource <HttpContext> taskCompletionSource = new TaskCompletionSource <HttpContext>();
                        routeEndpoint.RequestDelegate.Invoke(httpContext).ContinueWith(task =>
                        {
                            if (task.IsFaulted)
                            {
                                taskCompletionSource.SetException(task.Exception);
                            }
                            else if (task.IsCanceled)
                            {
                                taskCompletionSource.SetCanceled();
                            }
                            else
                            {
                                taskCompletionSource.SetResult(httpContext);
                            }
                        });

                        return(taskCompletionSource.Task);
                    };
                }
            }

            // Not all supplied requestInfo's have to be found at this point
            // Set the results to 404 where the request info has not been found
            for (int i = 0; i < processedRequestInfos.Length; i++)
            {
                if (!processedRequestInfos[i])
                {
                    resultFuncs[i] = GetNotFoundResult;
                }
            }

            return(resultFuncs);
        }
Exemple #36
0
 /// <summary>
 /// Creates a new instance of the Serializer.
 /// </summary>
 /// <param name="requestInfo">the request info.</param>
 /// <param name="options">the save change options.</param>
 internal Serializer(RequestInfo requestInfo, SaveChangesOptions options)
     : this(requestInfo)
 {
     this.options = options;
 }
Exemple #37
0
        public static async Task <ResponseData> ConnectRestAPI(RequestInfo requestInfor, MethodType type)
        {
            ResponseData responseData = new ResponseData();

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    if (requestInfor.HeaderValue != null && requestInfor.HeaderValue.AuthorizationType != null && requestInfor.HeaderValue.AuthorizationValue != null)
                    {
                        client.DefaultRequestHeaders.Authorization =
                            new AuthenticationHeaderValue(requestInfor.HeaderValue.AuthorizationType, requestInfor.HeaderValue.AuthorizationValue);
                    }

                    if (requestInfor.HeaderValue != null && requestInfor.HeaderValue.ListHeader != null && requestInfor.HeaderValue.ListHeader.Any())
                    {
                        foreach (var item in requestInfor.HeaderValue.ListHeader)
                        {
                            client.DefaultRequestHeaders.Add(item.Key, item.Value);
                        }
                    }

                    var request = new HttpResponseMessage();
                    switch (type)
                    {
                    case MethodType.GET:
                        request = await client.GetAsync(requestInfor.UrlBase);

                        break;

                    case MethodType.POST:
                        request = await client.PostAsync(requestInfor.UrlBase, new FormUrlEncodedContent(requestInfor.FormValue));

                        break;

                    case MethodType.PUT:
                        request = await client.PutAsync(requestInfor.UrlBase, new FormUrlEncodedContent(requestInfor.FormValue));

                        break;

                    case MethodType.DELETE:
                        request = await client.DeleteAsync(requestInfor.UrlBase);

                        break;

                    default:
                        break;
                    }

                    if (request.StatusCode == HttpStatusCode.OK)
                    {
                        string resultData = request.Content.ReadAsStringAsync().Result;

                        responseData = new ResponseData()
                        {
                            Code = (int)HttpStatusCode.OK,
                            Data = resultData
                        };
                    }
                    else if (request.StatusCode == HttpStatusCode.NoContent)
                    {
                        responseData = new ResponseData()
                        {
                            Code    = (int)HttpStatusCode.NoContent,
                            Message = "NoContent",
                        };
                    }
                    else
                    {
                        var errorData = ConvertJson.Deserialize <ErrorData>(request.Content.ReadAsStringAsync().Result);
                        if (errorData != null)
                        {
                            responseData = new ResponseData()
                            {
                                Code    = (int)request.StatusCode,
                                Message = errorData.error + " - " + errorData.error_description
                            };
                        }
                        else
                        {
                            responseData = new ResponseData()
                            {
                                Code    = (int)request.StatusCode,
                                Message = "Unknown Error: " + request.Content.ReadAsStringAsync().Result
                            };
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }

            return(responseData);
        }
        public static RequestInfo Collect(HttpContext context, ExceptionlessConfiguration config)
        {
            if (context == null)
            {
                return(null);
            }

            var info = new RequestInfo {
                HttpMethod = context.Request.Method,
                IsSecure   = context.Request.IsHttps,
                Path       = context.Request.Path.HasValue ? context.Request.Path.Value : "/",
            };

            if (config.IncludeIpAddress)
            {
                info.ClientIpAddress = context.GetClientIpAddress();
            }

            if (!String.IsNullOrEmpty(context.Request.Host.Host))
            {
                info.Host = context.Request.Host.Host;
            }

            if (context.Request.Host.Port.HasValue)
            {
                info.Port = context.Request.Host.Port.Value;
            }

            if (context.Request.Headers.ContainsKey(HeaderNames.UserAgent))
            {
                info.UserAgent = context.Request.Headers[HeaderNames.UserAgent].ToString();
            }

            if (context.Request.Headers.ContainsKey(HeaderNames.Referer))
            {
                info.Referrer = context.Request.Headers[HeaderNames.Referer].ToString();
            }

            var exclusionList = config.DataExclusions as string[] ?? config.DataExclusions.ToArray();

            if (config.IncludeCookies)
            {
                info.Cookies = context.Request.Cookies.ToDictionary(exclusionList);
            }

            if (config.IncludeQueryString)
            {
                info.QueryString = context.Request.Query.ToDictionary(exclusionList);
            }

            if (config.IncludePostData)
            {
                if (context.Request.HasFormContentType && context.Request.Form.Count > 0)
                {
                    info.PostData = context.Request.Form.ToDictionary(exclusionList);
                }
                else if (context.Request.ContentLength.HasValue && context.Request.ContentLength.Value > 0)
                {
                    if (context.Request.ContentLength.Value < 1024 * 50)
                    {
                        try {
                            if (context.Request.Body.CanSeek && context.Request.Body.Position > 0)
                            {
                                context.Request.Body.Position = 0;
                            }

                            if (context.Request.Body.Position == 0)
                            {
                                using (var inputStream = new StreamReader(context.Request.Body))
                                    info.PostData = inputStream.ReadToEnd();
                            }
                            else
                            {
                                info.PostData = "Unable to get POST data: The stream could not be reset.";
                            }
                        } catch (Exception ex) {
                            info.PostData = "Error retrieving POST data: " + ex.Message;
                        }
                    }
                    else
                    {
                        string value = Math.Round(context.Request.ContentLength.Value / 1024m, 0).ToString("N0");
                        info.PostData = String.Format("Data is too large ({0}kb) to be included.", value);
                    }
                }
            }

            return(info);
        }
 partial void ResolveGenerated(ref object service, Type serviceType, object serviceKey,
                               Type requiredServiceType, RequestInfo preRequestParent, IScope scope)
 {
 }
Exemple #40
0
 public GetUsersSheetCommand(RequestInfo requestData)
 {
     this.requestData = requestData;
 }
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            RequestInfo requestInfo = request.GetProperty <RequestInfo>("");

            if (requestInfo == null)
            {
                requestInfo = RequestHelper.BuildRequestInfo(request);
                request.AddProperty <RequestInfo>(requestInfo, "");
            }
            return(base.SendAsync(request, cancellationToken).ContinueWith <HttpResponseMessage>(delegate(Task <HttpResponseMessage> task)
            {
                object obj2;
                InterfaceSetting property = request.GetProperty <InterfaceSetting>("");
                if ((requestInfo.HttpMethod == HttpMethod.Options) || ((property != null) && property.DisableLog))
                {
                    return task.Result;
                }
                RequestLog log = RequestHelper.BuildRequestLog(request, requestInfo);
                HttpResponseMessage message = task.Result;
                string str = string.Empty;
                ObjectContent content = message.Content as ObjectContent;
                if (content != null)
                {
                    QiuxunLogResult result = content.Value as QiuxunLogResult;
                    if (result != null)
                    {
                        log.ApiStatus = result.LogCode;
                        log.ApiDesc = result.LogDesc;
                        log.ApiDescDetail = result.LogDescDetail;
                    }
                    else
                    {
                        ApiResult result2 = content.Value as ApiResult;
                        if (result2 != null)
                        {
                            log.ApiStatus = result2.Code;
                            log.ApiDesc = result2.Desc;
                            if (((property != null) && property.IsRecordResponseData) && (result2.Code == 100))
                            {
                                str = result2.ToJsonString();
                            }
                        }
                    }
                }
                if (request.Properties.TryGetValue("eprepare-set-cookie", out obj2))
                {
                    IEnumerable <CookieHeaderValue> enumerable = (IEnumerable <CookieHeaderValue>)obj2;
                    foreach (CookieHeaderValue value2 in enumerable)
                    {
                        log.ResponseCookie = log.ResponseCookie + string.Format("{0}~", value2.ToString());
                    }
                    if (log.ResponseCookie.Length > 0)
                    {
                        log.ResponseCookie = log.ResponseCookie.TrimEnd(new char[] { '~' });
                    }
                }
                log.HttpStatus = (int)message.StatusCode;
                if (this.allWebRequest)
                {
                    RequestHelper.WriteAllWebRequestLog(log);
                    return message;
                }
                if (((property != null) && property.IsRecordResponseData) && !string.IsNullOrEmpty(str))
                {
                    RequestHelper.WriteWebRequestLog(log, str);
                    return message;
                }
                RequestHelper.WriteWebRequestLog(log, str);
                return message;
            }));
        }
Exemple #42
0
        private IEnumerable <IRequestChain> GetRequestChains(HttpContext context, RequestInfo request)
        {
            var list = context.Items.ToList();

            return(null);
        }
Exemple #43
0
        private RequestDetail GetRequestDetail(HttpContext context, RequestInfo request)
        {
            RequestDetail model = ModelCreator.CreateRequestDetail();

            if (context.Request != null)
            {
                model.Id        = context.GetUniqueId();
                model.RequestId = request.Id;

                Dictionary <string, string> cookies = context.Request.Cookies.ToList().ToDictionary(x => x.Key, x => x.Value);

                if (cookies != null && cookies.Count > 0)
                {
                    model.Cookie = JsonConvert.SerializeObject(cookies);
                }

                Dictionary <string, string> headers = context.Request.Headers.ToList().ToDictionary(x => x.Key, x => x.Value.ToString());

                if (headers != null && headers.Count > 0)
                {
                    model.Header = HttpUtility.HtmlDecode(JsonConvert.SerializeObject(headers));
                }

                if (context.Items.ContainsKey(BasicConfig.HttpReportsGlobalException))
                {
                    Exception ex = context.Items[BasicConfig.HttpReportsGlobalException] as Exception;

                    if (ex != null)
                    {
                        model.ErrorMessage = ex.Message;
                        model.ErrorStack   = HttpUtility.HtmlDecode(ex.StackTrace);
                    }

                    context.Items.Remove(BasicConfig.HttpReportsGlobalException);
                }

                if (context.Items.ContainsKey(BasicConfig.HttpReportsRequestBody))
                {
                    string requestBody = context.Items[BasicConfig.HttpReportsRequestBody] as string;

                    if (requestBody != null)
                    {
                        model.RequestBody = requestBody;
                    }

                    context.Items.Remove(BasicConfig.HttpReportsRequestBody);
                }

                if (context.Items.ContainsKey(BasicConfig.HttpReportsResponseBody))
                {
                    string responseBody = context.Items[BasicConfig.HttpReportsResponseBody] as string;

                    if (responseBody != null)
                    {
                        model.ResponseBody = responseBody;
                    }

                    context.Items.Remove(BasicConfig.HttpReportsResponseBody);
                }

                model.CreateTime = context.Items[BasicConfig.ActiveTraceCreateTime].ToDateTime();

                model.Scheme      = context.Request.Scheme;
                model.QueryString = HttpUtility.UrlDecode(context.Request.QueryString.Value);
            }

            return(model);
        }
Exemple #44
0
 public void CallbackFun(RequestInfo rqInfo, ResponseAckInfo ackInfo)
 {
     Log(string.Format("client:{0}\r\nserver:{1}", rqInfo.ToJsonString(), ackInfo.ToJsonString()));
 }
Exemple #45
0
        async Task <JObject> SearchContentsAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
        {
            // check permissions
            if (!await this.IsAuthorizedAsync(requestInfo, "content", Components.Security.Action.View, cancellationToken).ConfigureAwait(false))
            {
                throw new AccessDeniedException();
            }

            // prepare
            var request = requestInfo.GetRequestExpando();

            var query = request.Get <string>("FilterBy.Query");

            if (request.Get <ExpandoObject>("FilterBy", null)?.ToFilterBy <Content>() is FilterBys <Content> filter)
            {
                if (filter.Children.FirstOrDefault(f => f is FilterBy <Content> && (f as FilterBy <Content>).Attribute.IsEquals("Status")) == null && !await this.IsServiceAdministratorAsync(requestInfo).ConfigureAwait(false))
                {
                    filter.Add(Filters <Content> .Equals("Status", $"{ApprovalStatus.Published}"));
                }
            }
            else
            {
                filter = Filters <Content> .And(
                    Filters <Content> .Equals("Status", $"{ApprovalStatus.Published}"),
                    Filters <Content> .GreaterOrEquals("StartingTime", "@nowHourQuater()"),
                    Filters <Content> .Or(
                        Filters <Content> .Equals("EndingTime", "-"),
                        Filters <Content> .LessThan("EndingTime", "@nowHourQuater()")
                        ),
                    Filters <Content> .IsNull("ParentID")
                    );
            }

            var filterBy = filter.Clone();

            if (filterBy.Children.FirstOrDefault(f => f is FilterBy <Content> && (f as FilterBy <Content>).Attribute.IsEquals("StartingTime")) is FilterBy <Content> startingTime && "@nowHourQuater()".IsStartsWith(startingTime.Value as string))
            {
                startingTime.Value = this.GetNowHourQuater();
            }
            if (filterBy.Children.FirstOrDefault(f => f is FilterBy <Content> && (f as FilterBy <Content>).Attribute.IsEquals("EndingTime")) is FilterBy <Content> endingTime && "@nowHourQuater()".IsStartsWith(endingTime.Value as string))
            {
                endingTime.Value = this.GetNowHourQuater().ToDTString();
            }
            if (filterBy.Children.FirstOrDefault(f => f is FilterBys <Content> && (f as FilterBys <Content>).Operator.Equals(GroupOperator.Or) && (f as FilterBys <Content>).Children.FirstOrDefault(cf => cf is FilterBy <Content> && (cf as FilterBy <Content>).Attribute.IsEquals("EndingTime")) != null) is FilterBys <Content> orEndingTime)
            {
                orEndingTime.Children.Where(f => f is FilterBy <Content> && (f as FilterBy <Content>).Attribute.IsEquals("EndingTime") && "@nowHourQuater()".IsStartsWith((f as FilterBy <Content>).Value as string)).ForEach(f => (f as FilterBy <Content>).Value = this.GetNowHourQuater().ToDTString());
            }

            Func <string> func_GetNowHourQuater = () => this.GetNowHourQuater().ToDTString();

            filterBy.Prepare(null, requestInfo, new Dictionary <string, object>
            {
                { "nowHourQuater", func_GetNowHourQuater }
            });

            var sortBy = request.Get <ExpandoObject>("SortBy", null)?.ToSortBy <Content>();

            if (sortBy == null && string.IsNullOrWhiteSpace(query))
            {
                var filterByParentID = filterBy.Children.FirstOrDefault(f => f is FilterBy <Content> && (f as FilterBy <Content>).Attribute.IsEquals("ParentID"));
                sortBy = filterByParentID != null && filterByParentID is FilterBy <Content> && (filterByParentID as FilterBy <Content>).Value != null && (filterByParentID as FilterBy <Content>).Value.ToString().IsValidUUID()
                                        ? Sorts <Content> .Descending("OrderIndex")
                                        : Sorts <Content> .Descending("StartingTime").ThenByDescending("LastUpdated");
            }

            var pagination = request.Has("Pagination")
                                ? request.Get <ExpandoObject>("Pagination").GetPagination()
                                : new Tuple <long, int, int, int>(-1, 0, 20, 1);

            var pageNumber = pagination.Item4;

            // check cache
            var cacheKey = string.IsNullOrWhiteSpace(query)
                                ? this.GetCacheKey(filterBy, sortBy)
                                : "";

            var json = !cacheKey.Equals("")
                                ? await Utility.Cache.GetAsync <string>($"{cacheKey }{pageNumber}:json").ConfigureAwait(false)
                                : "";

            if (!string.IsNullOrWhiteSpace(json))
            {
                return(JObject.Parse(json));
            }

            // prepare pagination
            var totalRecords = pagination.Item1 > -1
                                ? pagination.Item1
                                : string.IsNullOrWhiteSpace(query)
                                        ? await Content.CountAsync(filterBy, $"{cacheKey}total", cancellationToken).ConfigureAwait(false)
                                        : await Content.CountAsync(query, filterBy, cancellationToken).ConfigureAwait(false);

            var pageSize = pagination.Item3;

            var totalPages = (new Tuple <long, int>(totalRecords, pageSize)).GetTotalPages();

            if (totalPages > 0 && pageNumber > totalPages)
            {
                pageNumber = totalPages;
            }

            // search
            var objects = totalRecords > 0
                                ? string.IsNullOrWhiteSpace(query)
                                        ? await Content.FindAsync(filterBy, sortBy, pageSize, pageNumber, $"{cacheKey}{pageNumber}", cancellationToken).ConfigureAwait(false)
                                        : await Content.SearchAsync(query, filterBy, pageSize, pageNumber, cancellationToken).ConfigureAwait(false)
                                : new List <Content>();

            // build the result
            pagination = new Tuple <long, int, int, int>(totalRecords, totalPages, pageSize, pageNumber);
            var files = totalRecords > 0
                                ? await this.GetFilesAsync(requestInfo, objects.Select(obj => obj.ID).ToString(",") + ",", objects.ToJObject("ID", obj => new JValue(obj.Title)).ToString(Formatting.None), cancellationToken).ConfigureAwait(false)
                                : new JObject();

            var result = new JObject
            {
                { "FilterBy", filter.ToClientJson(query) },
                { "SortBy", sortBy?.ToClientJson() },
                { "Pagination", pagination.GetPagination() },
                { "Objects", objects.ToJsonArray(ojson =>
                    {
                        ojson["MediaURI"] = ojson.Get <string>("MediaURI").Replace("~~", this.FilesHttpURI);
                        ojson.UpdateFiles(files[ojson.Get <string>("ID")]);
                    }) }
            };

            // update cache
            if (!cacheKey.Equals(""))
            {
                await Utility.Cache.SetAsync($"{cacheKey }{pageNumber}:json", result.ToString(this.IsDebugLogEnabled ? Formatting.Indented : Formatting.None), Utility.Cache.ExpirationTime / 2, cancellationToken).ConfigureAwait(false);
            }

            // return the result
            return(result);
        }
Exemple #46
0
        public override async Task <JToken> ProcessRequestAsync(RequestInfo requestInfo, CancellationToken cancellationToken = default(CancellationToken))
        {
            var stopwatch = Stopwatch.StartNew();

            this.WriteLogs(requestInfo, $"Begin request ({requestInfo.Verb} {requestInfo.GetURI()})");
            using (var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, this.CancellationTokenSource.Token))
                try
                {
                    JToken json = null;
                    switch (requestInfo.ObjectName.ToLower())
                    {
                    case "content":
                        json = await this.ProcessContentAsync(requestInfo, cts.Token).ConfigureAwait(false);

                        break;

                    case "profile":
                        json = await this.ProcessProfileAsync(requestInfo, cts.Token).ConfigureAwait(false);

                        break;

                    case "definitions":
                        var objectIdentity = (requestInfo.GetObjectIdentity() ?? "").ToLower();
                        switch (objectIdentity)
                        {
                        case "categories":
                        case "groups":
                        case "lists":
                            json = JArray.Parse((await UtilityService.ReadTextFileAsync(Path.Combine(this.GetPath("StaticFiles"), this.ServiceName.ToLower(), $"{objectIdentity.ToLower()}.json"), null, cts.Token).ConfigureAwait(false)).Replace("\r", "").Replace("\t", ""));
                            break;

                        case "content":
                            if (!requestInfo.Query.TryGetValue("mode", out string mode) || "forms".IsEquals(mode))
                            {
                                json = this.GenerateFormControls <Content>();
                            }
                            else
                            {
                                throw new InvalidRequestException($"The request is invalid [({requestInfo.Verb}): {requestInfo.GetURI()}]");
                            }
                            break;

                        default:
                            throw new InvalidRequestException($"The request is invalid [({requestInfo.Verb}): {requestInfo.GetURI()}]");
                        }
                        break;

                    default:
                        throw new InvalidRequestException($"The request is invalid [({requestInfo.Verb}): {requestInfo.GetURI()}]");
                    }
                    stopwatch.Stop();
                    this.WriteLogs(requestInfo, $"Success response - Execution times: {stopwatch.GetElapsedTimes()}");
                    if (this.IsDebugResultsEnabled)
                    {
                        this.WriteLogs(requestInfo,
                                       $"- Request: {requestInfo.ToJson().ToString(this.IsDebugLogEnabled ? Formatting.Indented : Formatting.None)}" + "\r\n" +
                                       $"- Response: {json?.ToString(this.IsDebugLogEnabled ? Formatting.Indented : Formatting.None)}"
                                       );
                    }
                    return(json);
                }
                catch (Exception ex)
                {
                    throw this.GetRuntimeException(requestInfo, ex, stopwatch);
                }
        }
Exemple #47
0
        public static void DoProcess(RequestInfo info, string method, string module, string key)
        {
            var ci = ParseRequestCulture(info);

            using (Library.Localization.LocalizationService.TemporaryContext(ci))
                try
                {
                    if (ci != null)
                    {
                        info.Response.AddHeader("Content-Language", ci.Name);
                    }

                    IRESTMethod mod;
                    _modules.TryGetValue(module, out mod);

                    if (mod == null)
                    {
                        info.Response.Status = System.Net.HttpStatusCode.NotFound;
                        info.Response.Reason = "No such module";
                    }
                    else if (method == HttpServer.Method.Get && mod is IRESTMethodGET)
                    {
                        if (info.Request.Form != HttpServer.HttpForm.EmptyForm)
                        {
                            if (info.Request.QueryString == HttpServer.HttpInput.Empty)
                            {
                                var r = info.Request.GetType().GetField("_queryString", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                                r.SetValue(info.Request, new HttpServer.HttpInput("formdata"));
                            }

                            foreach (HttpServer.HttpInputItem v in info.Request.Form)
                            {
                                if (!info.Request.QueryString.Contains(v.Name))
                                {
                                    info.Request.QueryString.Add(v.Name, v.Value);
                                }
                            }
                        }
                        ((IRESTMethodGET)mod).GET(key, info);
                    }
                    else if (method == HttpServer.Method.Put && mod is IRESTMethodPUT)
                    {
                        ((IRESTMethodPUT)mod).PUT(key, info);
                    }
                    else if (method == HttpServer.Method.Post && mod is IRESTMethodPOST)
                    {
                        if (info.Request.Form == HttpServer.HttpForm.EmptyForm)
                        {
                            var r = info.Request.GetType().GetMethod("AssignForm", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, null, new Type[] { typeof(HttpServer.HttpForm) }, null);
                            r.Invoke(info.Request, new object[] { new HttpServer.HttpForm(info.Request.QueryString) });
                        }
                        else
                        {
                            foreach (HttpServer.HttpInputItem v in info.Request.QueryString)
                            {
                                if (!info.Request.Form.Contains(v.Name))
                                {
                                    info.Request.Form.Add(v.Name, v.Value);
                                }
                            }
                        }
                        ((IRESTMethodPOST)mod).POST(key, info);
                    }
                    else if (method == HttpServer.Method.Delete && mod is IRESTMethodDELETE)
                    {
                        ((IRESTMethodDELETE)mod).DELETE(key, info);
                    }
                    else if (method == "PATCH" && mod is IRESTMethodPATCH)
                    {
                        ((IRESTMethodPATCH)mod).PATCH(key, info);
                    }
                    else
                    {
                        info.Response.Status = System.Net.HttpStatusCode.MethodNotAllowed;
                        info.Response.Reason = "Method is not allowed";
                    }
                }
                catch (Exception ex)
                {
                    Program.DataConnection.LogError("", string.Format("Request for {0} gave error", info.Request.Uri), ex);
                    Console.WriteLine(ex);

                    try
                    {
                        if (!info.Response.HeadersSent)
                        {
                            info.Response.Status      = System.Net.HttpStatusCode.InternalServerError;
                            info.Response.Reason      = "Error";
                            info.Response.ContentType = "text/plain";

                            var wex = ex;
                            while (wex is System.Reflection.TargetInvocationException && wex.InnerException != wex)
                            {
                                wex = wex.InnerException;
                            }


                            info.BodyWriter.WriteJsonObject(new
                            {
                                Message = ex.Message,
                                Type    = ex.GetType().Name,
                            #if DEBUG
                                Stacktrace = ex.ToString()
                            #endif
                            });
                            info.BodyWriter.Flush();
                        }
                    }
                    catch (Exception flex)
                    {
                        Program.DataConnection.LogError("", "Reporting error gave error", flex);
                    }
                }
        }
Exemple #48
0
        /// <summary>
        /// Checks whether the endpoint is matched the relative uri specified int the request info.
        /// </summary>
        /// <param name="routeEndpoint">The route endpoint.</param>
        /// <param name="requestInfo">The request information.</param>
        /// <param name="routeValueDictionary">The route value dictionary.</param>
        /// <returns>
        /// Whether the endpoint matches the request info relative uri.
        /// </returns>
        private static EndpointMatchResult EndpointMatches(RouteEndpoint routeEndpoint, RequestInfo requestInfo, out RouteValueDictionary routeValueDictionary)
        {
            if (!_templateMatcherCache.TryGetValue(routeEndpoint.RoutePattern.RawText, out TemplateMatcher templateMatcher))
            {
                RouteTemplate template = TemplateParser.Parse(routeEndpoint.RoutePattern.RawText);
                templateMatcher = new TemplateMatcher(template, GetDefaultRouteValues(template));
                _templateMatcherCache.TryAdd(routeEndpoint.RoutePattern.RawText, templateMatcher);
            }

            routeValueDictionary = new RouteValueDictionary();
            if (templateMatcher.TryMatch(new PathString(requestInfo.RelativeUri), routeValueDictionary))
            {
                // Check if the HTTP method matches
                string requestHttpMethod = requestInfo.Method.ToLower();

                HttpMethodMetadata httpMethodMetadata = routeEndpoint.Metadata.GetMetadata <HttpMethodMetadata>();
                if (httpMethodMetadata == null && requestHttpMethod != HttpMethod.Get.ToString().ToLower())
                {                 // Assume get if no metadata is found
                    return(EndpointMatchResult.NoMatch);
                }
                if (!httpMethodMetadata.HttpMethods.Any(httpMethod => httpMethod.ToLower() == requestHttpMethod))
                {                 // Http method is not matching
                    return(EndpointMatchResult.NoMatch);
                }

                // Check if this endpoint is ignored, allowed takes precedence
                IgnoreForBatchRequestAttribute ignoreAttribute = routeEndpoint.Metadata.GetMetadata <IgnoreForBatchRequestAttribute>();
                AllowForBatchRequestAttribute  allowAttribute  = routeEndpoint.Metadata.GetMetadata <AllowForBatchRequestAttribute>();
                if (ignoreAttribute != null && allowAttribute == null)
                {
                    return(EndpointMatchResult.Ignored);
                }

                return(EndpointMatchResult.Match);
            }
            return(EndpointMatchResult.NoMatch);
        }
Exemple #49
0
 /// <summary>
 /// Creates a new instance of the Serializer.
 /// </summary>
 /// <param name="requestInfo">the request info.</param>
 /// <param name="sendOption">The option to send entity operation parameters.</param>
 internal Serializer(RequestInfo requestInfo, EntityParameterSendOption sendOption)
     : this(requestInfo)
 {
     this.sendOption = sendOption;
 }
Exemple #50
0
        public ActionResult CreateOrder(string orderViewModel)
        {
            if (!Request.IsAuthenticated)
            {
                TempData["UnAuthenticated"] = "Bạn phải đăng nhập để thanh toán";
                return(Json(new { status = false }));
            }
            var  order    = new JavaScriptSerializer().Deserialize <OrderViewModel>(orderViewModel);
            var  orderNew = new Order();
            bool isEnough = true;

            orderNew.UpdateOrder(order);
            if (Request.IsAuthenticated)
            {
                var userId = User.Identity.GetUserId();
                orderNew.CustomerId = userId;
                orderNew.CreatedBy  = User.Identity.GetUserName();
            }
            var cart         = (List <ShoppingCartViewModel>)Session[CommonConstants.ShoppingCartSession];
            var orderDetails = new List <OrderDetail>();

            foreach (var item in cart)
            {
                var detail = new OrderDetail
                {
                    ProductID = item.ProductId,
                    Quantity  = item.Quantity,
                    Price     = item.Product.Price
                };
                orderDetails.Add(detail);
                isEnough = _productService.SellingProduct(item.ProductId, item.Quantity);
            }
            if (!isEnough)
            {
                return(Json(new
                {
                    status = false,
                    message = "Sản phẩm này hiện tại đang hết hàng."
                }));
            }

            var orderReturn = _orderService.Add(ref orderNew, orderDetails);

            _orderService.SaveChanges();

            var totalAmount = orderDetails.Sum(x => x.Quantity * x.Price).ToString();

            Session["totalAmount"] = totalAmount;

            if (order.PaymentMethod == "CASH")
            {
                ApplySendHtmlOrder();
                return(Json(new
                {
                    status = true
                }));
            }


            var currentLink = ConfigHelper.GetByKey("CurrentLink");
            var info        = new RequestInfo
            {
                Merchant_id       = _merchantId,
                Merchant_password = _merchantPassword,
                Receiver_email    = _merchantEmail,
                cur_code          = "vnd",
                bank_code         = order.BankCode,
                Order_code        = orderReturn.ID.ToString(),
                Total_amount      = totalAmount,
                fee_shipping      = "0",
                Discount_amount   = "0",
                order_description = "Thanh toán đơn hàng tại uStora shop",
                return_url        = currentLink + "/xac-nhan-don-hang.htm",
                cancel_url        = currentLink + "/huy-don-hang.htm",
                Buyer_fullname    = order.CustomerName,
                Buyer_email       = order.CustomerEmail,
                Buyer_mobile      = order.CustomerMobile
            };

            Session["OrderId"] = orderReturn.ID;

            var objNlChecout = new APICheckout();
            var result       = objNlChecout.GetUrlCheckout(info, order.PaymentMethod);

            if (result.Error_code == "00")
            {
                return(Json(new
                {
                    status = true,
                    urlCheckout = result.Checkout_url,
                    message = result.Description
                }));
            }
            return(Json(new
            {
                status = false,
                message = result.Description
            }));
        }
Exemple #51
0
 /// <summary>
 /// Creates a new instance of the Serializer.
 /// </summary>
 /// <param name="requestInfo">the request info.</param>
 internal Serializer(RequestInfo requestInfo)
 {
     Debug.Assert(requestInfo != null, "requestInfo != null");
     this.requestInfo       = requestInfo;
     this.propertyConverter = new ODataPropertyConverter(this.requestInfo);
 }
        public ActionResult Create([Bind(Include = "Id,PrasymoPateikimoData,VaikoId,VaikoGimimoData,LankymoData,VaikoSeniunija,Prioritetas_DeklaruotasMiestas,Prioritetas_3_ar_Daugiau_Vaiku,Prioritetas_seimosdarbingumoLygis,Prioritetas_auginaTikVienasTevas,PasirinktasDarzelis_1,UzpildytasDarzelis_1,DarzelioVietaEileje_1,Darzelio_seniūnija_1,DarzelioGrupesUgdymojiKalba_1,DarzelioGrupesUgdymoMetodika_1,DarzelioGrupesTipas_1,DarzelioAmziausIntervalas_1,AtitinkaDarzelioPriskirtaTeritorija_1,DarzeliLankoBrolysSeserys_1,TinkamaGrupeDarzelyje_1,PasirinktasDarzelis_2,UzpildytasDarzelis_2,DarzelioVietaEileje_2,Darzelio_seniūnija_2,DarzelioGrupesUgdymojiKalba_2,DarzelioGrupesUgdymoMetodika_2,DarzelioGrupesTipas_2,DarzelioAmziausIntervalas_2,AtitinkaDarzelioPriskirtaTeritorija_2,DarzeliLankoBrolysSeserys_2,TinkamaGrupeDarzelyje_2,PasirinktasDarzelis_3,UzpildytasDarzelis_3,DarzelioVietaEileje_3,Darzelio_seniūnija_3,DarzelioGrupesUgdymojiKalba_3,DarzelioGrupesUgdymoMetodika_3,DarzelioGrupesTipas_3,DarzelioAmziausIntervalas_3,AtitinkaDarzelioPriskirtaTeritorija_3,DarzeliLankoBrolysSeserys_3,TinkamaGrupeDarzelyje_3,PasirinktasDarzelis_4,UzpildytasDarzelis_4,DarzelioVietaEileje_4,Darzelio_seniūnija_4,DarzelioGrupesUgdymojiKalba_4,DarzelioGrupesUgdymoMetodika_4,DarzelioGrupesTipas_4,DarzelioAmziausIntervalas_4,AtitinkaDarzelioPriskirtaTeritorija_4,DarzeliLankoBrolysSeserys_4,TinkamaGrupeDarzelyje_4,PasirinktasDarzelis_5,UzpildytasDarzelis_5,DarzelioVietaEileje_5,Darzelio_seniūnija_5,DarzelioGrupesUgdymojiKalba_5,DarzelioGrupesUgdymoMetodika_5,DarzelioGrupesTipas_5,DarzelioAmziausIntervalas_5,AtitinkaDarzelioPriskirtaTeritorija_5,DarzeliLankoBrolysSeserys_5,TinkamaGrupeDarzelyje_5")] RequestModel requestModel)
        {
            if (requestModel.PasirinktasDarzelis_1 == requestModel.PasirinktasDarzelis_2 ||
                requestModel.PasirinktasDarzelis_1 == requestModel.PasirinktasDarzelis_3 ||
                requestModel.PasirinktasDarzelis_1 == requestModel.PasirinktasDarzelis_4 ||
                requestModel.PasirinktasDarzelis_1 == requestModel.PasirinktasDarzelis_5

                || requestModel.PasirinktasDarzelis_2 == requestModel.PasirinktasDarzelis_1 ||
                requestModel.PasirinktasDarzelis_2 == requestModel.PasirinktasDarzelis_3 ||
                requestModel.PasirinktasDarzelis_2 == requestModel.PasirinktasDarzelis_4 ||
                requestModel.PasirinktasDarzelis_2 == requestModel.PasirinktasDarzelis_5

                || requestModel.PasirinktasDarzelis_3 == requestModel.PasirinktasDarzelis_1 ||
                requestModel.PasirinktasDarzelis_3 == requestModel.PasirinktasDarzelis_2 ||
                requestModel.PasirinktasDarzelis_3 == requestModel.PasirinktasDarzelis_4 ||
                requestModel.PasirinktasDarzelis_3 == requestModel.PasirinktasDarzelis_5

                || requestModel.PasirinktasDarzelis_4 == requestModel.PasirinktasDarzelis_1 ||
                requestModel.PasirinktasDarzelis_4 == requestModel.PasirinktasDarzelis_2 ||
                requestModel.PasirinktasDarzelis_4 == requestModel.PasirinktasDarzelis_3 ||
                requestModel.PasirinktasDarzelis_4 == requestModel.PasirinktasDarzelis_5

                || requestModel.PasirinktasDarzelis_5 == requestModel.PasirinktasDarzelis_1 ||
                requestModel.PasirinktasDarzelis_5 == requestModel.PasirinktasDarzelis_2 ||
                requestModel.PasirinktasDarzelis_5 == requestModel.PasirinktasDarzelis_3 ||
                requestModel.PasirinktasDarzelis_5 == requestModel.PasirinktasDarzelis_4)
            {
                //requestModel.ErrorMessage = "Pasirinkite skirtingus darželius";

                return(RedirectToAction("Create", "RequestModels", new { errorMessage = "Pasirinkite skirtingus darželius" }));
            }

            if (ModelState.IsValid)
            {
                PreRequestSchool pasrinktaMokykla1 = new PreRequestSchool();
                pasrinktaMokykla1.DarzelioVietaEileje                 = requestModel.DarzelioVietaEileje_1;
                pasrinktaMokykla1.Darzelio_seniūnija                  = requestModel.Darzelio_seniūnija_1;
                pasrinktaMokykla1.DarzelioGrupesUgdymojiKalba         = requestModel.DarzelioGrupesUgdymojiKalba_1;
                pasrinktaMokykla1.DarzelioGrupesUgdymoMetodika        = requestModel.DarzelioGrupesUgdymoMetodika_1;
                pasrinktaMokykla1.DarzelioGrupesTipas                 = requestModel.DarzelioGrupesTipas_1;
                pasrinktaMokykla1.DarzelioAmziausIntervalas           = requestModel.DarzelioAmziausIntervalas_1;
                pasrinktaMokykla1.AtitinkaDarzelioPriskirtaTeritorija = requestModel.AtitinkaDarzelioPriskirtaTeritorija_1;
                pasrinktaMokykla1.DarzeliLankoBrolysSeserys           = requestModel.DarzeliLankoBrolysSeserys_1;
                pasrinktaMokykla1.TinkamaGrupeDarzelyje               = requestModel.TinkamaGrupeDarzelyje_1;

                PreRequestSchool pasrinktaMokykla2 = new PreRequestSchool();
                pasrinktaMokykla2.DarzelioVietaEileje                 = requestModel.DarzelioVietaEileje_2;
                pasrinktaMokykla2.Darzelio_seniūnija                  = requestModel.Darzelio_seniūnija_2;
                pasrinktaMokykla2.DarzelioGrupesUgdymojiKalba         = requestModel.DarzelioGrupesUgdymojiKalba_2;
                pasrinktaMokykla2.DarzelioGrupesUgdymoMetodika        = requestModel.DarzelioGrupesUgdymoMetodika_2;
                pasrinktaMokykla2.DarzelioGrupesTipas                 = requestModel.DarzelioGrupesTipas_2;
                pasrinktaMokykla2.DarzelioAmziausIntervalas           = requestModel.DarzelioAmziausIntervalas_2;
                pasrinktaMokykla2.AtitinkaDarzelioPriskirtaTeritorija = requestModel.AtitinkaDarzelioPriskirtaTeritorija_2;
                pasrinktaMokykla2.DarzeliLankoBrolysSeserys           = requestModel.DarzeliLankoBrolysSeserys_2;
                pasrinktaMokykla2.TinkamaGrupeDarzelyje               = requestModel.TinkamaGrupeDarzelyje_2;


                PreRequestSchool pasrinktaMokykla3 = new PreRequestSchool();
                pasrinktaMokykla3.DarzelioVietaEileje                 = requestModel.DarzelioVietaEileje_3;
                pasrinktaMokykla3.Darzelio_seniūnija                  = requestModel.Darzelio_seniūnija_3;
                pasrinktaMokykla3.DarzelioGrupesUgdymojiKalba         = requestModel.DarzelioGrupesUgdymojiKalba_3;
                pasrinktaMokykla3.DarzelioGrupesUgdymoMetodika        = requestModel.DarzelioGrupesUgdymoMetodika_3;
                pasrinktaMokykla3.DarzelioGrupesTipas                 = requestModel.DarzelioGrupesTipas_3;
                pasrinktaMokykla3.DarzelioAmziausIntervalas           = requestModel.DarzelioAmziausIntervalas_3;
                pasrinktaMokykla3.AtitinkaDarzelioPriskirtaTeritorija = requestModel.AtitinkaDarzelioPriskirtaTeritorija_3;
                pasrinktaMokykla3.DarzeliLankoBrolysSeserys           = requestModel.DarzeliLankoBrolysSeserys_3;
                pasrinktaMokykla3.TinkamaGrupeDarzelyje               = requestModel.TinkamaGrupeDarzelyje_3;

                PreRequestSchool pasrinktaMokykla4 = new PreRequestSchool();
                pasrinktaMokykla4.DarzelioVietaEileje                 = requestModel.DarzelioVietaEileje_4;
                pasrinktaMokykla4.Darzelio_seniūnija                  = requestModel.Darzelio_seniūnija_4;
                pasrinktaMokykla4.DarzelioGrupesUgdymojiKalba         = requestModel.DarzelioGrupesUgdymojiKalba_4;
                pasrinktaMokykla4.DarzelioGrupesUgdymoMetodika        = requestModel.DarzelioGrupesUgdymoMetodika_4;
                pasrinktaMokykla4.DarzelioGrupesTipas                 = requestModel.DarzelioGrupesTipas_4;
                pasrinktaMokykla4.DarzelioAmziausIntervalas           = requestModel.DarzelioAmziausIntervalas_4;
                pasrinktaMokykla4.AtitinkaDarzelioPriskirtaTeritorija = requestModel.AtitinkaDarzelioPriskirtaTeritorija_4;
                pasrinktaMokykla4.DarzeliLankoBrolysSeserys           = requestModel.DarzeliLankoBrolysSeserys_4;
                pasrinktaMokykla4.TinkamaGrupeDarzelyje               = requestModel.TinkamaGrupeDarzelyje_4;

                PreRequestSchool pasrinktaMokykla5 = new PreRequestSchool();
                pasrinktaMokykla5.DarzelioVietaEileje                 = requestModel.DarzelioVietaEileje_5;
                pasrinktaMokykla5.Darzelio_seniūnija                  = requestModel.Darzelio_seniūnija_5;
                pasrinktaMokykla5.DarzelioGrupesUgdymojiKalba         = requestModel.DarzelioGrupesUgdymojiKalba_5;
                pasrinktaMokykla5.DarzelioGrupesUgdymoMetodika        = requestModel.DarzelioGrupesUgdymoMetodika_5;
                pasrinktaMokykla5.DarzelioGrupesTipas                 = requestModel.DarzelioGrupesTipas_5;
                pasrinktaMokykla5.DarzelioAmziausIntervalas           = requestModel.DarzelioAmziausIntervalas_5;
                pasrinktaMokykla5.AtitinkaDarzelioPriskirtaTeritorija = requestModel.AtitinkaDarzelioPriskirtaTeritorija_5;
                pasrinktaMokykla5.DarzeliLankoBrolysSeserys           = requestModel.DarzeliLankoBrolysSeserys_5;
                pasrinktaMokykla5.TinkamaGrupeDarzelyje               = requestModel.TinkamaGrupeDarzelyje_5;


                Request naujas = new Request();

                naujas.LankymoData                       = requestModel.LankymoData;
                naujas.PrasymoPateikimoData              = requestModel.PrasymoPateikimoData;
                naujas.Prioritetas_3_ar_Daugiau_Vaiku    = requestModel.Prioritetas_3_ar_Daugiau_Vaiku;
                naujas.Prioritetas_auginaTikVienasTevas  = requestModel.Prioritetas_auginaTikVienasTevas;
                naujas.Prioritetas_DeklaruotasMiestas    = requestModel.Prioritetas_DeklaruotasMiestas;
                naujas.Prioritetas_seimosdarbingumoLygis = requestModel.Prioritetas_seimosdarbingumoLygis;
                //naujas = requestModel.VaikoId;
                naujas.VaikoId              = requestModel.VaikoId;
                naujas.VaikoGimimoData      = requestModel.VaikoGimimoData;
                naujas.PrasymoPateikimoData = requestModel.PrasymoPateikimoData;
                User updateUser = db.Users.ToList().FirstOrDefault(x => x.Id == requestModel.VaikoId);
                updateUser.RequestCreated = true;
                naujas.VaikoIDNF          = updateUser;


                db.Requests.Add(naujas);
                db.SaveChanges();

                Request     getNaujas   = Uow.Requests.GetAll().ToList().FirstOrDefault(x => x.VaikoId == requestModel.VaikoId);
                RequestInfo updateInfo1 = new RequestInfo();
                updateInfo1.PasirinktasDarzelis      = requestModel.PasirinktasDarzelis_1;
                updateInfo1.PreRequestSchool         = pasrinktaMokykla1;
                updateInfo1.RequestIdRef             = getNaujas.Id;
                updateInfo1.DarzelioEilesPrioritetas = 1;

                db.RequestInfo.Add(updateInfo1);
                db.SaveChanges();

                RequestInfo updateInfo2 = new RequestInfo();
                updateInfo2.PasirinktasDarzelis      = requestModel.PasirinktasDarzelis_2;
                updateInfo2.PreRequestSchool         = pasrinktaMokykla2;
                updateInfo2.RequestIdRef             = getNaujas.Id;
                updateInfo2.DarzelioEilesPrioritetas = 2;
                db.RequestInfo.Add(updateInfo2);
                db.SaveChanges();

                RequestInfo updateInfo3 = new RequestInfo();
                updateInfo3.PasirinktasDarzelis      = requestModel.PasirinktasDarzelis_3;
                updateInfo3.PreRequestSchool         = pasrinktaMokykla3;
                updateInfo3.RequestIdRef             = getNaujas.Id;
                updateInfo3.DarzelioEilesPrioritetas = 3;
                db.RequestInfo.Add(updateInfo3);
                db.SaveChanges();

                RequestInfo updateInfo4 = new RequestInfo();
                updateInfo4.PasirinktasDarzelis      = requestModel.PasirinktasDarzelis_4;
                updateInfo4.PreRequestSchool         = pasrinktaMokykla4;
                updateInfo4.RequestIdRef             = getNaujas.Id;
                updateInfo4.DarzelioEilesPrioritetas = 4;
                db.RequestInfo.Add(updateInfo4);
                db.SaveChanges();

                RequestInfo updateInfo5 = new RequestInfo();
                updateInfo5.PasirinktasDarzelis      = requestModel.PasirinktasDarzelis_5;
                updateInfo5.PreRequestSchool         = pasrinktaMokykla5;
                updateInfo5.RequestIdRef             = getNaujas.Id;
                updateInfo5.DarzelioEilesPrioritetas = 5;
                db.RequestInfo.Add(updateInfo5);
                db.SaveChanges();



                return(RedirectToAction("Index", "Home"));
            }

            return(View(requestModel));
        }
Exemple #53
0
        public void UpdateSession(Session session, RequestInfo requestInfo)
        {
            #region Local Declarations

            var  firstNameValue   = string.Empty;
            var  lastNameValue    = string.Empty;
            var  emailValue       = string.Empty;
            var  genderValue      = string.Empty;
            var  phoneNumberValue = string.Empty;
            var  birthDateValue   = DateTime.MinValue;
            var  jobTitleValue    = string.Empty;
            var  phoneNumber      = string.Empty;
            var  avatar           = string.Empty;
            var  addressValue     = string.Empty;
            Item itemValue        = null;

            #endregion

            #region Get Personal Contact Information

            //First Name
            requestInfo.SetIfVariablePresent("ContactFirstName", firstName =>
            {
                firstNameValue = firstName;
            });
            //Last Name
            requestInfo.SetIfVariablePresent("ContactLastName", lastName =>
            {
                lastNameValue = lastName;
            });
            //Gender
            requestInfo.SetIfVariablePresent("ContactGender", gender =>
            {
                genderValue = gender;
            });
            //Birth Date
            requestInfo.SetIfVariablePresent("ContactBirthDate", date =>
            {
                if (string.IsNullOrEmpty(date))
                {
                    return;
                }

                birthDateValue = DateTime.ParseExact(date.Substring(0, 8), "yyyyMMdd", null);
            });
            //Job Title
            requestInfo.SetIfVariablePresent("ContactJobTitle", jobTitle =>
            {
                jobTitleValue = jobTitle;
            });

            #endregion

            #region Get Address Information

            //Address
            requestInfo.SetIfVariablePresent("ContactAddress", address =>
            {
                addressValue = address;
            });

            #endregion

            #region Get PhoneNumber

            //Phone Number
            requestInfo.SetIfVariablePresent("ContactPhone", phone =>
            {
                phoneNumberValue = phone;
            });

            #endregion

            #region Get Avatar Information

            //Picture
            requestInfo.SetIfVariablePresent("ContactPicture", pictureItemID =>
            {
                if (string.IsNullOrEmpty(pictureItemID))
                {
                    return;
                }

                var item = (Context.ContentDatabase ?? Context.Database).GetItem(pictureItemID);

                if (item == null)
                {
                    return;
                }

                itemValue = item;
            });

            #endregion

            #region Get Email Information

            requestInfo.SetIfVariablePresent("ContactEmail", email =>
            {
                emailValue = email;
            });

            #endregion

            var manager = Sitecore.Configuration.Factory.CreateObject("tracking/contactManager", true) as Sitecore.Analytics.Tracking.ContactManager;

            if (Tracker.Current.Contact.IsNew)
            {
                Log.Info($"ExperienceGenerator ContactDataProcessor: Tracker.Current.Contact.IsNew: {Tracker.Current.Contact.IsNew}, TrackerContactId: {Tracker.Current.Contact.ContactId:N}", this);

                if (manager != null)
                {
                    // Save contact to xConnect; at this point, a contact has an anonymous
                    // TRACKER IDENTIFIER, which follows a specific format. Do not use the contactId overload
                    // and make sure you set the ContactSaveMode as demonstrated
                    //Tracker.Current.Contact.ContactSaveMode = ContactSaveMode.AlwaysSave;
                    //manager.SaveContactToCollectionDb(Sitecore.Analytics.Tracker.Current.Contact);
                    Tracker.Current.Session.IdentifyAs("xGenerator", Tracker.Current.Contact.ContactId.ToString("N"));

                    Log.Info($"ExperienceGenerator ContactDataProcessor: Session Identified using xGenerator", this);

                    // Now that the contact is saved, you can retrieve it using the tracker identifier
                    // NOTE: Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource is marked internal in 9.0 Initial - use "xDB.Tracker"
                    var trackerIdentifier = new IdentifiedContactReference(Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource, Tracker.Current.Contact.ContactId.ToString("N"));

                    using (var client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
                    {
                        try
                        {
                            var contact = client.Get <Contact>(trackerIdentifier, new ContactExpandOptions());

                            if (contact != null)
                            {
                                Log.Info($"ExperienceGenerator ContactDataProcessor: FirstName: {firstNameValue}, LastName: {lastNameValue}, Email: {emailValue}", this);

                                client.SetFacet <PersonalInformation>(contact, PersonalInformation.DefaultFacetKey, new PersonalInformation()
                                {
                                    FirstName = firstNameValue ?? string.Empty,
                                    LastName  = lastNameValue ?? string.Empty,
                                    Birthdate = birthDateValue,
                                    JobTitle  = jobTitleValue ?? string.Empty,
                                    Gender    = genderValue ?? string.Empty
                                });

                                Log.Info($"ExperienceGenerator ContactDataProcessor: PersonalInformationFacet set for New Contact", this);

                                var emails = new EmailAddressList(new EmailAddress(emailValue, true), "Home");
                                client.SetFacet(contact, EmailAddressList.DefaultFacetKey, emails);
                                Log.Info($"ExperienceGenerator ContactDataProcessor: EmailFacet set for New Contact", this);

                                var addresses = new AddressList(new Address {
                                    AddressLine1 = addressValue
                                }, "Home");
                                client.SetFacet(contact, AddressList.DefaultFacetKey, addresses);
                                Log.Info($"ExperienceGenerator ContactDataProcessor: AddressFacet set for New Contact", this);

                                var phoneNumbers = new PhoneNumberList(new PhoneNumber("1", phoneNumberValue), "Home");
                                client.SetFacet(contact, PhoneNumberList.DefaultFacetKey, phoneNumbers);
                                Log.Info($"ExperienceGenerator ContactDataProcessor: PhoneNumberFacet set for New Contact", this);

                                client.Submit();

                                //var contactRemovedFromSession = manager.RemoveFromSession(Tracker.Current.Contact.ContactId);
                            }
                        }
                        catch (XdbExecutionException ex)
                        {
                            Log.Error($"ExperienceGenerator ContactDataProcessor: There was an exception while trying to set facet information for new contact, ContactId: {Tracker.Current.Contact.ContactId:N}", ex, this);
                        }
                    }
                }
            }
            else if (!Tracker.Current.Contact.IsNew && manager != null)
            {
                Log.Info($"ExperienceGenerator ContactDataProcessor: Tracker.Current.Contact.IsNew: {Tracker.Current.Contact.IsNew}, TrackerContactId: {Tracker.Current.Contact.ContactId:N}", this);
                var anyIdentifier = Tracker.Current.Contact.Identifiers.FirstOrDefault();

                if (anyIdentifier != null)
                {
                    Log.Info($"ExperienceGenerator ContactDataProcessor: FirstName: {firstNameValue}, LastName: {lastNameValue}, Email: {emailValue}", this);
                    Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, Tracker.Current.Contact.IsNew: False, Tracker.Current.Contact.Facets: {Tracker.Current.Contact.Facets.Count}", this);
                    using (var client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
                    {
                        try
                        {
                            var contact = client.Get <Contact>(
                                new IdentifiedContactReference(anyIdentifier.Source, anyIdentifier.Identifier),
                                new ContactExpandOptions(PersonalInformation.DefaultFacetKey,
                                                         EmailAddressList.DefaultFacetKey, PhoneNumberList.DefaultFacetKey,
                                                         AddressList.DefaultFacetKey));

                            if (contact != null)
                            {
                                Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, Contact using anyIdentifier loaded with requested ContactExpandOptions", this);

                                var personalInformationFacet = contact.GetFacet <PersonalInformation>(PersonalInformation.DefaultFacetKey);
                                var emailFacet        = contact.GetFacet <EmailAddressList>(EmailAddressList.DefaultFacetKey);
                                var phoneNumbersFacet = contact.GetFacet <PhoneNumberList>(PhoneNumberList.DefaultFacetKey);
                                var addressFacet      = contact.GetFacet <AddressList>(AddressList.DefaultFacetKey);

                                if (personalInformationFacet != null)
                                {
                                    Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, PersonalInformationFacet is not null", this);
                                    personalInformationFacet.FirstName = firstNameValue ?? string.Empty;
                                    personalInformationFacet.LastName  = lastNameValue ?? string.Empty;
                                    personalInformationFacet.Birthdate = birthDateValue;
                                    personalInformationFacet.JobTitle  = jobTitleValue ?? string.Empty;
                                    personalInformationFacet.Gender    = genderValue ?? string.Empty;

                                    client.SetFacet(contact, PersonalInformation.DefaultFacetKey, personalInformationFacet);
                                }
                                else
                                {
                                    Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, PersonalInformationFacet is null", this);
                                    client.SetFacet <PersonalInformation>(contact, PersonalInformation.DefaultFacetKey, new PersonalInformation()
                                    {
                                        FirstName = firstNameValue ?? string.Empty,
                                        LastName  = lastNameValue ?? string.Empty,
                                        Birthdate = birthDateValue,
                                        JobTitle  = jobTitleValue ?? string.Empty,
                                        Gender    = genderValue ?? string.Empty
                                    });
                                }

                                if (emailFacet != null)
                                {
                                    if (string.IsNullOrEmpty(emailFacet.PreferredEmail.SmtpAddress))
                                    {
                                        Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, EmailFacet is not null", this);
                                        emailFacet.PreferredEmail = new EmailAddress(emailValue, true);
                                        emailFacet.PreferredKey   = "Home";
                                        client.SetFacet(contact, EmailAddressList.DefaultFacetKey, emailFacet);
                                    }
                                }
                                else
                                {
                                    Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, EmailFacet is null", this);
                                    var emails = new EmailAddressList(new EmailAddress(emailValue, true), "Home");
                                    client.SetFacet(contact, EmailAddressList.DefaultFacetKey, emails);
                                }

                                if (addressFacet != null)
                                {
                                    if (string.IsNullOrEmpty(addressFacet.PreferredAddress.AddressLine1))
                                    {
                                        Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, AddressFacet is not null", this);
                                        addressFacet.PreferredAddress = new Address()
                                        {
                                            AddressLine1 = addressValue
                                        };
                                        addressFacet.PreferredKey = "Home";
                                        client.SetFacet(contact, AddressList.DefaultFacetKey, addressFacet);
                                    }
                                }
                                else
                                {
                                    Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, AddressFacet is null", this);
                                    var addresses = new AddressList(new Address {
                                        AddressLine1 = addressValue
                                    }, "Home");
                                    client.SetFacet(contact, AddressList.DefaultFacetKey, addresses);
                                }

                                if (phoneNumbersFacet != null)
                                {
                                    if (string.IsNullOrEmpty(phoneNumbersFacet.PreferredPhoneNumber.Number))
                                    {
                                        Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, PhoneNumbersFacet is not null", this);
                                        phoneNumbersFacet.PreferredPhoneNumber = new PhoneNumber("1", phoneNumberValue);
                                        phoneNumbersFacet.PreferredKey         = "Home";
                                        client.SetFacet(contact, PhoneNumberList.DefaultFacetKey, phoneNumbersFacet);
                                    }
                                }
                                else
                                {
                                    Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, PhoneNumbersFacet is null", this);
                                    var phoneNumbers = new PhoneNumberList(new PhoneNumber("1", phoneNumberValue), "Home");
                                    client.SetFacet(contact, PhoneNumberList.DefaultFacetKey, phoneNumbers);
                                }

                                client.Submit();
                                //var contactRemovedFromSession = manager.RemoveFromSession(Tracker.Current.Contact.ContactId);
                            }
                        }
                        catch (XdbExecutionException ex)
                        {
                            Log.Error($"ExperienceGenerator ContactDataProcessor: There was an exception while trying to set facet information for known contact, ContactId: {Tracker.Current.Contact.ContactId:N}", ex, this);
                        }
                    }
                }
            }
        }
Exemple #54
0
 private static System.Globalization.CultureInfo ParseRequestCulture(RequestInfo info)
 {
     // Inject the override
     return(ParseRequestCulture(string.Format("{0},{1}", info.Request.Headers["X-UI-Language"], info.Request.Headers["Accept-Language"])));
 }
Exemple #55
0
        public override Result Invoke(ClientInfo ci, RequestInfo ri, DbConnections db, ref Log lg)
        {
            Result res = new Result();

            try
            {
                first = DateTime.Now;
                switch (ri.FunctionNo)
                {
                    #region [Урьдчилсан борлуулалтын үндсэн бүтээгдэхүүн]
                case 130326:                            //	Урьдчилсан борлуулалтын үндсэн бүтээгдэхүүн жагсаалт мэдээлэл авах
                    res = Txn130326(ci, ri, db, ref lg);
                    break;

                case 130327:                            //  Урьдчилсан борлуулалтын үндсэн бүтээгдэхүүн дэлгэрэнгүй мэдээлэл авах
                    res = Txn130327(ci, ri, db, ref lg);
                    break;

                case 130328:                            //	Урьдчилсан борлуулалтын үндсэн бүтээгдэхүүн бүртгэл нэмэх
                    res = Txn130328(ci, ri, db, ref lg);
                    break;

                case 130329:                            //	Урьдчилсан борлуулалтын үндсэн бүтээгдэхүүн бүртгэл засах
                    res = Txn130329(ci, ri, db, ref lg);
                    break;

                case 130330:                            //	Урьдчилсан борлуулалтын үндсэн бүтээгдэхүүн бүртгэл устгах
                    res = Txn130330(ci, ri, db, ref lg);
                    break;

                    #endregion
                    #region [Урьдчилсан борлуулалтын үндсэн бүртгэл]
                case 130301:                            //	Урьдчилсан борлуулалтын үндсэн бүртгэл жагсаалт мэдээлэл авах
                    res = Txn130301(ci, ri, db, ref lg);
                    break;

                case 130302:                            //  Урьдчилсан борлуулалтын үндсэн бүртгэл дэлгэрэнгүй мэдээлэл авах
                    res = Txn130302(ci, ri, db, ref lg);
                    break;

                case 130303:                            //	Урьдчилсан борлуулалтын үндсэн бүртгэл нэмэх
                    res = Txn130303(ci, ri, db, ref lg);
                    break;

                case 130304:                            //	Урьдчилсан борлуулалтын үндсэн бүртгэл засах
                    res = Txn130304(ci, ri, db, ref lg);
                    break;

                case 130305:                            //	Урьдчилсан борлуулалтын үндсэн бүртгэл устгах
                    res = Txn130305(ci, ri, db, ref lg);
                    break;
                    #endregion

                    #region [Урьдчилсан борлуулалтын өгсөн үйлчлүүлэгчид]
                case 130306:                            //
                    res = Txn130306(ci, ri, db, ref lg);
                    break;

                case 130307:                            //
                    res = Txn130307(ci, ri, db, ref lg);
                    break;

                case 130308:                            //
                    res = Txn130308(ci, ri, db, ref lg);
                    break;

                case 130309:                            //
                    res = Txn130309(ci, ri, db, ref lg);
                    break;

                case 130310:                            //
                    res = Txn130310(ci, ri, db, ref lg);
                    break;

                    #endregion
                    #region [Урьдчилсан борлуулалтын өгсөн үйлчлүүлэгчийн захиалсан бүтээгдэхүүн]
                case 130350:                            //Жагсаалт
                    res = Txn130350(ci, ri, db, ref lg);
                    break;

                case 130351:                            //Дэлгэрэнгүй
                    res = Txn130351(ci, ri, db, ref lg);
                    break;

                case 130352:                            //Нэмэх
                    res = Txn130352(ci, ri, db, ref lg);
                    break;

                case 130353:                            //Засварлах
                    res = Txn130353(ci, ri, db, ref lg);
                    break;

                case 130354:                            //Устгах
                    res = Txn130354(ci, ri, db, ref lg);
                    break;

                    #endregion
                    #region [Урьдчилсан борлуулалтын доторх багц дахь бүтээгдэхүүн]
                case 130311:                            //	Урьдчилсан борлуулалтын доторх багц дахь бүтээгдэхүүн жагсаалт мэдээлэл авах
                    res = Txn130311(ci, ri, db, ref lg);
                    break;

                case 130312:                            //  Урьдчилсан борлуулалтын доторх багц дахь бүтээгдэхүүн дэлгэрэнгүй мэдээлэл авах
                    res = Txn130312(ci, ri, db, ref lg);
                    break;

                case 130313:                            //	Урьдчилсан борлуулалтын доторх багц дахь бүтээгдэхүүн нэмэх
                    res = Txn130313(ci, ri, db, ref lg);
                    break;

                case 130314:                            //	Урьдчилсан борлуулалтын доторх багц дахь бүтээгдэхүүн засах
                    res = Txn130314(ci, ri, db, ref lg);
                    break;

                case 130315:                            //	Урьдчилсан борлуулалтын доторх багц дахь бүтээгдэхүүн устгах
                    res = Txn130315(ci, ri, db, ref lg);
                    break;

                    #endregion
                    #region [Урьдчилсан борлуулалтын доторх багц дахь бүтээгдэхүүний үнийн бүртгэл]
                case 130316:                            //	Урьдчилсан борлуулалтын доторх багц дахь бүтээгдэхүүний үнийн бүртгэл жагсаалт мэдээлэл авах
                    res = Txn130316(ci, ri, db, ref lg);
                    break;

                case 130317:                            //  Урьдчилсан борлуулалтын доторх багц дахь бүтээгдэхүүний үнийн бүртгэл дэлгэрэнгүй мэдээлэл авах
                    res = Txn130317(ci, ri, db, ref lg);
                    break;

                case 130318:                            //	Урьдчилсан борлуулалтын доторх багц дахь бүтээгдэхүүний үнийн бүртгэл нэмэх
                    res = Txn130318(ci, ri, db, ref lg);
                    break;

                case 130319:                            //	Урьдчилсан борлуулалтын доторх багц дахь бүтээгдэхүүний үнийн бүртгэл засах
                    res = Txn130319(ci, ri, db, ref lg);
                    break;

                case 130320:                            //	Урьдчилсан борлуулалтын доторх багц дахь бүтээгдэхүүний үнийн бүртгэл устгах
                    res = Txn130320(ci, ri, db, ref lg);
                    break;
                    #endregion

                    #region [Урьдчилсан борлуулалтын баталгаажуулах]
                case 130331:                            //
                    res = Txn130331(ci, ri, db, ref lg);
                    break;

                    #endregion
                    #region [Урьдчилсан борлуулалтын цуцлах]
                case 130332:                            //
                    res = Txn130332(ci, ri, db, ref lg);
                    break;

                    #endregion
                    #region [Урьдчилсан борлуулалтын сунгах]
                case 130333:                            //
                    res = Txn130333(ci, ri, db, ref lg);
                    break;

                    #endregion
                default:
                    res.ResultNo   = 9110009;
                    res.ResultDesc = "Функц тодорхойлогдоогүй байна";
                    break;
                }
                return(res);
            }
            catch (Exception ex)
            {
                res.ResultNo   = 9110002;
                res.ResultDesc = "Програм руу нэвтрэхэд алдаа гарлаа" + ex.Message;

                EServ.Shared.Static.WriteToLogFile("Error.log", ex.Message + ex.Source + ex.StackTrace);

                return(res);
            }
            finally
            {
                string ResultDesk = "OK";
                if (res.ResultNo != 0)
                {
                    ResultDesk = res.ResultDesc;
                }
                DateTime second = DateTime.Now;
                ISM.Lib.Static.WriteToLogFile("IPos.Contract", "\r\n<<Start:" + Static.ToStr(first) + ">>\r\n UserNo:" + Static.ToStr(ri.UserNo) + "\r\n Description:" + Static.ToStr(lg.item.Desc) + "\r\n ResultNo:" + Static.ToStr(res.ResultNo) + "\r\n ResultDescription:" + ResultDesk + "\r\n<<End " + Static.ToStr(second) + ">>");
            }
        }
Exemple #56
0
        public override async Task <JToken> ProcessRequestAsync(RequestInfo requestInfo, CancellationToken cancellationToken = default)
        {
            var stopwatch = Stopwatch.StartNew();

            this.WriteLogs(requestInfo, $"Begin request ({requestInfo.Verb} {requestInfo.GetURI()})");
            using (var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, this.CancellationTokenSource.Token))
                try
                {
                    // prepare
                    if (!requestInfo.Verb.IsEquals("GET"))
                    {
                        throw new InvalidRequestException($"The request is invalid ({requestInfo.Verb} {requestInfo.GetURI()})");
                    }

                    JObject json = null;
                    switch (requestInfo.ObjectName.ToLower())
                    {
                    case "public":
                    case "public-ips":
                        var publicAddresses = new JArray();
                        Utility.PublicAddresses.ForEach(addr => publicAddresses.Add(new JValue($"{addr}")));
                        json = new JObject
                        {
                            { "IPs", publicAddresses }
                        };
                        break;

                    case "local":
                    case "local-ips":
                        var localAddresses = new JArray();
                        Utility.LocalAddresses.ForEach(addr => localAddresses.Add(new JValue($"{addr}")));
                        json = new JObject
                        {
                            { "IPs", localAddresses }
                        };
                        break;

                    case "current":
                    case "currentlocation":
                        json = (await Utility.GetCurrentLocationAsync(cts.Token, this.Logger, requestInfo.Session.User.ID).ConfigureAwait(false)).ToJson(obj => obj.Remove("LastUpdated"));
                        break;

                    default:
                        // prepare
                        var ipAddress = requestInfo.GetQueryParameter("ip-address") ?? requestInfo.Session.IP;
                        if (string.IsNullOrWhiteSpace(ipAddress))
                        {
                            throw new InvalidRequestException($"The request is invalid ({requestInfo.Verb} {requestInfo.GetURI()})");
                        }

                        // same location
                        json = (Utility.IsSameLocation(ipAddress)
                                                                ? new IPLocation
                        {
                            ID = ipAddress.GetMD5(),
                            IP = ipAddress,
                            City = "N/A",
                            Region = "N/A",
                            Country = "N/A",
                            Continent = "N/A",
                            Latitude = "N/A",
                            Longitude = "N/A",
                        }
                                                                : await Utility.GetLocationAsync(ipAddress, cts.Token, this.Logger, requestInfo.Session.User.ID).ConfigureAwait(false)).ToJson(obj => obj.Remove("LastUpdated"));
                        break;
                    }

                    // response
                    stopwatch.Stop();
                    this.WriteLogs(requestInfo, $"Success response - Execution times: {stopwatch.GetElapsedTimes()}");
                    if (this.IsDebugResultsEnabled)
                    {
                        this.WriteLogs(requestInfo, $"- Request: {requestInfo.ToString(this.JsonFormat)}" + "\r\n" + $"- Response: {json?.ToString(this.JsonFormat)}");
                    }
                    return(json);
                }
                catch (Exception ex)
                {
                    throw this.GetRuntimeException(requestInfo, ex, stopwatch);
                }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ChannelRequestMessage"/> class.
 /// </summary>
 /// <param name="localChannelNumber">The local channel number.</param>
 /// <param name="info">The info.</param>
 public ChannelRequestMessage(uint localChannelNumber, RequestInfo info)
     : base(localChannelNumber)
 {
     RequestName = info.RequestName;
     RequestData = info.GetBytes();
 }
        public async Task <IActionResult> Checkout([FromForm] ShippingInfo shippingInfo,
                                                   CancellationToken requestAborted)
        {
            if (_cart.LineItems.Count() == 0)
            {
                ModelState.AddModelError("", "Sorry, your cart is empty!");
            }
            var formCollection = await HttpContext.Request.ReadFormAsync();

            if (ModelState.IsValid)
            {
                shippingInfo.LineItems = _cart.LineItems;

                await _repository.SaveOrderAsync(shippingInfo);

                var         currentLink = "http://localhost:17352/";
                RequestInfo info        = new RequestInfo();
                info.Merchant_id       = merchantId;
                info.Merchant_password = merchantPassword;
                info.Receiver_email    = merchantEmail;

                var money = shippingInfo.LineItems.Sum(e => e.Product.Price * e.Quanlity) * 20000;

                info.cur_code          = "vnd";
                info.bank_code         = shippingInfo.BankCode;
                info.Order_code        = shippingInfo.ShippingInfoID + "dasdasdas";
                info.Total_amount      = money + "";
                info.fee_shipping      = "0";
                info.Discount_amount   = "0";
                info.order_description = "Thanh toán đơn hàng";
                info.return_url        = currentLink + "xac-nhan-don-hang.html";
                info.cancel_url        = currentLink + "huy-don-hang.html";

                info.Buyer_fullname = shippingInfo.Name;
                info.Buyer_email    = shippingInfo.Email;
                info.Buyer_mobile   = shippingInfo.PhoneNumber;

                APICheckoutV3 objNLChecout = new APICheckoutV3();
                ResponseInfo  result       = await objNLChecout.GetUrlCheckoutAsync(info);

                //ResponseInfo result = await objNLChecout.GetUrlCheckoutAsync(info, order.PaymentMethod);
                if (result.Error_code == "00")
                {
                    return(Redirect(result.Checkout_url));
                    //return Json(new
                    //{
                    //    status = true,
                    //    urlCheckout = result.Checkout_url,
                    //    message = result.Description
                    //});
                }
                else
                {
                    return(Json(new
                    {
                        status = false,
                        message = result.Description,
                        result = result.Error_code
                    }));
                }


                // Save all changes
                // await dbContext.SaveChangesAsync(requestAborted);


                return(RedirectToAction(nameof(Completed)));
            }
            else
            {
                return(View(shippingInfo));
            }
        }
        public async Task <IActionResult> VerifyAndCheckout(CheckoutSum sum, String code, String bankcode)
        {
            //convert currency
            var currencyConvertAPI = _configuration["currencycovertApi:API"];
            var cli     = new HttpClient();
            var fullApi = "https://free.currconv.com/api/v7/convert?q=USD_VND&compact=ultra&apiKey=" + currencyConvertAPI;
            HttpResponseMessage getConttent = await cli.GetAsync(fullApi);

            HttpContent respon = getConttent.Content;

            Debug.WriteLine(currencyConvertAPI + "cec");

            using (var read = new StreamReader(await respon.ReadAsStreamAsync()))
            {
                var resss = await read.ReadToEndAsync();

                Debug.WriteLine(resss + "cecc");
                resss = @"[" + resss + "]";
                dynamic ketqua  = JArray.Parse(resss);
                dynamic kq      = ketqua[0];
                string  convert = kq.USD_VND;
                ViewBag.tyso = convert;
                USDtoVND     = float.Parse(convert);
                Debug.WriteLine(USDtoVND);
            }

            //end convert

            //---------------------- Mở ra khi  Hoàn Tất Hết

            var clientt = new HttpClient();

            // Add authentication header
            clientt.DefaultRequestHeaders.Add("X-Authy-API-Key", AuthyAPIKey);

            // https://api.authy.com/protected/json/phones/verification/check?phone_number=$USER_PHONE&country_code=$USER_COUNTRY&verification_code=$VERIFY_CODE
            var api = "https://api.authy.com/protected/json/phones/verification/check?phone_number=" + sum.khachhang.Sdt + "&country_code=84&verification_code=" + code;
            HttpResponseMessage response = await clientt.GetAsync(api);

            // Get the response content.
            HttpContent responseContent = response.Content;

            // Get the stream of the content.
            using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
            {
                // Write the output.

                var result = await reader.ReadToEndAsync();

                // parse json string to array
                result = @"[" + result + "]";

                dynamic blogPosts = JArray.Parse(result);

                dynamic blogPost = blogPosts[0];
                string  isTrue   = blogPost.success;
                //string isTrue = "True"; // dong lai khi hoan tat
                // -- End Mở ra
                if (isTrue == "True") // Code = Code : Success : True
                {
                    if (_KhachHang.GetKhachHang(sum.khachhang.Email) != null)
                    {
                        _KhachHang.UpdateKhachHang(sum.khachhang);
                    }
                    _KhachHang.AddKhachHang(sum.khachhang, HttpContext.Session.GetInt32("Id"));
                    _Donhang.UpdatePhuongThuc(HttpContext.Session.GetInt32("Id"), sum.PhuongThucThanhToan);
                    _Donhang.UpdateDescription(HttpContext.Session.GetInt32("Id"), "Chưa Thanh Toán");

                    if (sum.PhuongThucThanhToan == "Thanh Toán Khi Nhận Hàng")
                    {
                        return(View("../Checkout/Success"));
                    } // end thanh toan khi nhan hang
                    else if (sum.PhuongThucThanhToan == "PayPal")
                    {
                        Double summ      = 0;
                        var    PayPalAPI = new PayPalAPI(_configuration);
                        var    itemList  = new ItemList()
                        {
                            Items = new List <Item>()
                        };
                        IEnumerable <Chitietdonhang> a = _DonhangAdmin.GetChitietdonhang((int)HttpContext.Session.GetInt32("Id"));
                        foreach (var item in a)
                        {
                            Decimal soluong = 0;
                            string  des     = "";
                            Sanpham sp      = _Sanpham.GetSanPham(item.IdSanPham);
                            if (sp.IdLoaiSanPham == 4)
                            {
                                soluong = (Decimal)item.SoLuong;
                                des     = "unit: 1 cup";
                            }
                            else
                            {
                                soluong = (Decimal)item.SoLuong / 100;
                                des     = "Unit: 100 gam";
                            }
                            itemList.Items.Add(new Item()
                            {
                                Name        = sp.Ten,
                                Currency    = "USD",
                                Price       = Math.Round(((Decimal)item.Gia / (Decimal)USDtoVND / soluong), 2).ToString(),
                                Quantity    = soluong.ToString(),
                                Description = des
                            });
                        }
                        foreach (var item in itemList.Items)
                        {
                            Debug.WriteLine(item.Name + " " + item.Quantity + " " + item.Price); // debug log
                            summ = summ + Math.Round((double.Parse(item.Price) * double.Parse(item.Quantity)), 2);
                        }
                        string URL = await PayPalAPI.getRedirectURLtoPayPal(summ, "USD", itemList);

                        return(Redirect(URL));
                    }
                    else if (sum.PhuongThucThanhToan == "Ví Ngân Lượng" || sum.PhuongThucThanhToan == "Thẻ VISA" || sum.PhuongThucThanhToan == "Thẻ ATM")
                    {
                        Double summ                    = 0;
                        string payment_method          = "";
                        string str_bankcode            = bankcode;
                        IEnumerable <Chitietdonhang> a = _DonhangAdmin.GetChitietdonhang((int)HttpContext.Session.GetInt32("Id"));
                        if (sum.PhuongThucThanhToan == "Ví Ngân Lượng")
                        {
                            payment_method = "nl";
                        }
                        else if (sum.PhuongThucThanhToan == "Thẻ VISA")
                        {
                            payment_method = "VISA";
                        }
                        else if (sum.PhuongThucThanhToan == "Thẻ ATM")
                        {
                            payment_method = "ATM_ONLINE";
                        }
                        else
                        {
                            payment_method = "ATM_ONLINE";
                        }


                        RequestInfo info = new RequestInfo();
                        foreach (var item in a)
                        {
                            //Decimal soluong = 0;
                            //string des = "";
                            //Sanpham sp = _Sanpham.GetSanPham(item.IdSanPham);
                            //if (sp.IdLoaiSanPham == 4)
                            //{
                            //    soluong = (Decimal)item.SoLuong;
                            //    des = "unit: 1 cup";
                            //}
                            //else
                            //{
                            //    soluong = (Decimal)item.SoLuong / 100;
                            //    des = "Unit: 100 gam";
                            //}
                            summ = summ + ((double)item.Gia);
                        }
                        info.Merchant_id       = _configuration["NganLuong:mechant_id"];
                        info.Merchant_password = _configuration["NganLuong:mechant_pass"];
                        info.Receiver_email    = _configuration["NganLuong:seller_email"];



                        info.cur_code  = "vnd";
                        info.bank_code = str_bankcode;

                        info.Order_code        = HttpContext.Session.GetInt32("Id").ToString();
                        info.Total_amount      = summ.ToString();
                        info.order_description = "Đây Là Đơn Hàng Từ " + sum.khachhang.Ten + " có email là " + sum.khachhang.Email;
                        info.return_url        = _configuration["NganLuong:returnURL"];
                        info.cancel_url        = _configuration["NganLuong:cancelURL"];

                        info.Buyer_fullname = sum.khachhang.Ten;
                        info.Buyer_email    = sum.khachhang.Email;
                        info.Buyer_mobile   = sum.khachhang.Sdt;
                        info.Total_item     = a.Count().ToString();

                        APICheckoutV3 objNLChecout = new APICheckoutV3(_configuration);
                        ResponseInfo  resultt      = objNLChecout.GetUrlCheckout(info, payment_method);

                        if (resultt.Error_code == "00")
                        {
                            return(Redirect(resultt.Checkout_url));
                        }
                        else
                        {
                            Debug.WriteLine(resultt.Description);
                            return(RedirectToAction("Fail", "Checkout", new { message = resultt.Description }));
                        }
                    }
                    else
                    {
                        return(RedirectToAction("Fail"));
                    }
                }
                else // Code != Code : Success : False
                {
                    return(RedirectToAction("Fail", "Checkout", new { message = "Sai Mã Xác Nhận!!" }));
                }
            }
            //mở ra khi xong het
        }
Exemple #60
0
            public RequestInfoResponse Any(RequestInfo request)
            {
                var requestInfo = RequestInfoHandler.GetRequestInfo(base.Request);

                return(requestInfo);
            }