Beispiel #1
0
        internal Response(
            CDPSession client,
            Request request,
            ResponsePayload responseMessage)
        {
            _client           = client;
            Request           = request;
            Status            = responseMessage.Status;
            StatusText        = responseMessage.StatusText;
            Url               = request.Url;
            _fromDiskCache    = responseMessage.FromDiskCache;
            FromServiceWorker = responseMessage.FromServiceWorker;

            Headers = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);
            if (responseMessage.Headers != null)
            {
                foreach (var keyValue in responseMessage.Headers)
                {
                    Headers[keyValue.Key] = keyValue.Value;
                }
            }
            SecurityDetails = responseMessage.SecurityDetails;
            RemoteAddress   = new RemoteAddress
            {
                IP   = responseMessage.RemoteIPAddress,
                Port = responseMessage.RemotePort
            };

            BodyLoadedTaskWrapper = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously);
        }
Beispiel #2
0
        public async Task <IActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            ResetPassword resetPassword = new ResetPassword
            {
                Email    = model.Email,
                Code     = model.Code,
                Password = model.Password,
            };

            using HttpClient client = _httpClientFactory.CreateClient(_configuration["ApplicationIds:IdManagementId"]);
            client.BaseAddress      = new Uri(_configuration["AppURLS:IdApiBaseUrl"]);

            string        asJson  = JsonSerializer.Serialize <ResetPassword>(resetPassword);
            StringContent content = new StringContent(asJson, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await client.PostAsync("/api/v1/Account/ResetPasswordAsync", content);

            if (!response.IsSuccessStatusCode)
            {
                string badResponse = await response.Content.ReadAsStringAsync();

                ResponsePayload badResponseObj = JsonSerializer.Deserialize <ResponsePayload>(badResponse);
                _logger.LogError("~/Account/ResetPassword(ResetPasswordViewModel) - Error from IdApi - An Error occurred resetting the account password. StatusCode:{0}, Error Message:{1}", badResponseObj.StatusCode, badResponseObj.Message);
                return(Redirect(_configuration["AppURLS:PublicError"] + $"?statusCode={badResponseObj.StatusCode}"));
            }
            response.EnsureSuccessStatusCode();

            return(RedirectToAction(nameof(ResetPasswordConfirmation)));
        }
        internal Response(
            CDPSession client,
            Request request,
            ResponsePayload responseMessage)
        {
            _client           = client;
            Request           = request;
            Status            = responseMessage.Status;
            StatusText        = responseMessage.StatusText;
            Url               = request.Url;
            _fromDiskCache    = responseMessage.FromDiskCache;
            FromServiceWorker = responseMessage.FromServiceWorker;

            Headers = new Dictionary <string, object>();
            if (responseMessage.Headers != null)
            {
                foreach (var keyValue in responseMessage.Headers)
                {
                    Headers[keyValue.Key] = keyValue.Value;
                }
            }
            SecurityDetails = responseMessage.SecurityDetails;
            RemoteAddress   = new RemoteAddress
            {
                IP   = responseMessage.RemoteIPAddress,
                Port = responseMessage.RemotePort
            };

            BodyLoadedTaskWrapper = new TaskCompletionSource <bool>();
        }
Beispiel #4
0
 public JsonResult ExecService(ResponseDelegate serviceDelegate, ResponsePayload response)
 {
     try
     {
         serviceDelegate(); //執行服務
         response.Success = true;
     }
     catch (ValidationErrors errors)
     {
         response.Success = false;
         foreach (var error in errors.Errors)
         {
             response.Message += error.PropertyExceptionMessage + "<br>";
         }
     }
     catch (Exception ex)
     {
         if (ex.InnerException != null)
         {
             ex = ex.InnerException;
         }
         response.Success = false;
         response.Message = ex.Message;
     }
     return(Json(response));
 }
Beispiel #5
0
        private void HandleRequestRedirect(Request request, ResponsePayload responseMessage)
        {
            var response = new Response(
                _client,
                request,
                responseMessage);

            request.Response = response;
            request.RedirectChainList.Add(request);
            response.BodyLoadedTaskWrapper.TrySetException(
                new PuppeteerException("Response body is unavailable for redirect responses"));

            if (request.RequestId != null)
            {
                _requestIdToRequest.TryRemove(request.RequestId, out _);
            }

            if (request.InterceptionId != null)
            {
                _attemptedAuthentications.Remove(request.InterceptionId);
            }

            Response?.Invoke(this, new ResponseCreatedEventArgs
            {
                Response = response
            });

            RequestFinished?.Invoke(this, new RequestEventArgs
            {
                Request = request
            });
        }
Beispiel #6
0
        /// <summary> Called after an action has thrown an <see cref="T:System.Exception" /> </summary>
        /// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ExceptionContext"/></param>
        public void OnException(ExceptionContext context)
        {
            if (context.Exception != null)
            {
                var responseStatus = new ResponseStatus
                {
                    Code = SystemErrorCode,
                    Type = ResponsePayloadType.SystemException
                };

                responseStatus.Errors.Add(new ErrorResponse(_env.IsProduction() ? ProductionErrorMessage : context.Exception.ToString(),
                                                            SystemErrorCode, ResponsePayloadType.SystemException));

                var responsePayload = new ResponsePayload <string>
                {
                    ResponseStatus = responseStatus
                };

                context.Result = new JsonResult(responsePayload)
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError
                };

                _logger.LogError(context.Exception, nameof(GlobalExceptionFilter));
            }
        }
        /// <summary>
        /// Returns true if MethodRequestAndResponse instances are equal
        /// </summary>
        /// <param name="other">Instance of MethodRequestAndResponse to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(MethodRequestAndResponse other)
        {
            if (ReferenceEquals(null, other))
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     RequestPayload == other.RequestPayload ||
                     RequestPayload != null &&
                     RequestPayload.Equals(other.RequestPayload)
                     ) &&
                 (
                     ResponsePayload == other.ResponsePayload ||
                     ResponsePayload != null &&
                     ResponsePayload.Equals(other.ResponsePayload)
                 ) &&
                 (
                     StatusCode == other.StatusCode ||
                     StatusCode != null &&
                     StatusCode.Equals(other.StatusCode)
                 ));
        }
Beispiel #8
0
        private bool TryParsePayload(byte[] data, out ResponsePayload payload)
        {
            payload = null;

            var command     = ParseCommand(data);
            var payloadData = ParsePayloadData(data);

            switch (command)
            {
            case Command.DeviceAcknowledgement:
                payload = ResponsePayload.Empty;
                break;

            case Command.DeviceStateVersion:
                payload = _stateVersionResponsePayloadParser.Parse(payloadData);
                break;

            case Command.LightState:
                payload = _stateResponsePayloadParser.Parse(payloadData);
                break;

            default:
                return(false);
            }

            return(true);
        }
Beispiel #9
0
        protected override void Execute(CodeActivityContext context)
        {
            var content = new ResponsePayload
            {
                message = Message.Get(context),
                target  = Target.Get(context),
                channel = Channel.Get(context),
                botId   = BotId.Get(context)
            };

            var url = $"{ExternalURL.Get(context)}/api/v1/bots/___/mod/uipath/message";

            using (var client = new HttpClient())
                using (var request = new HttpRequestMessage(HttpMethod.Post, url))
                {
                    request.Headers.Add("Authorization", $"bearer {BotpressToken.Get(context)}");
                    var json = JsonConvert.SerializeObject(content);
                    using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
                    {
                        request.Content = stringContent;

                        using (var response = client.SendAsync(request).Result)
                        {
                            response.EnsureSuccessStatusCode();
                        }
                    }
                }
        }
Beispiel #10
0
            protected override async Task WhenAsync()
            {
                await using (_testServer.Start()
                             .ConfigureAwait(false))
                {
                    var client = await _testServer
                                 .CreateRequestClientAsync()
                                 .ConfigureAwait(false);

                    var requestPayload = new RequestPayload(
                        new RequestHeader(RequestHeader.MaxVersion)
                        .WithRequestApiKey(ApiVersionsRequest.ApiKey)
                        .WithRequestApiVersion(
                            ApiVersionsRequest.MaxVersion)
                        .WithCorrelationId(Int32.From(12)),
                        new ApiVersionsRequest(ApiVersionsRequest.MaxVersion));

                    await client
                    .SendAsync(requestPayload)
                    .ConfigureAwait(false);

                    _response = await client
                                .ReadAsync(requestPayload)
                                .ConfigureAwait(false);
                }
            }
        public void ResponsePayloadModelStateService()
        {
            var modelState = new ModelStateDictionary();

            _responsePayload = new ResponsePayload <string>(modelState, string.Empty);
            Assert.IsType <ResponseStatus>(_responsePayload.ResponseStatus);
        }
Beispiel #12
0
        public async Task <IActionResult> EnableAuthenticator(EnableAuthenticatorViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var id = User?.FindFirstValue("sub");

            string accessToken = await GetAccessToken();

            EnableAuthenticator contentModel = new EnableAuthenticator
            {
                Id = id,
                AuthenticatorUri = model.AuthenticatorUri,
                Code             = model.Code,
                SharedKey        = model.SharedKey,
            };

            string        asJson  = JsonSerializer.Serialize <EnableAuthenticator>(contentModel);
            StringContent content = new StringContent(asJson, Encoding.UTF8, "application/json");

            HttpClient client = _httpClientFactory.CreateClient("IdApiAccount");

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, $"{_configuration["AppURLS:IdApiBaseUrl"]}/api/v1/Account/EnableAuthenticatorAsync")
            {
                Content = content
            };

            using HttpResponseMessage response = await client.SendAsync(request);

            if (!response.IsSuccessStatusCode)
            {
                string badResponse = await response.Content.ReadAsStringAsync();

                ResponsePayload badResponseObj = JsonSerializer.Deserialize <ResponsePayload>(badResponse);
                if (badResponseObj.StatusCode == 400)
                {
                    ModelState.AddModelError("Code", "Verification code is invalid. Please scan the QR Code or enter the above Verification Code Key. Then use the One-Time password code generated by the Authenticator App to verify and complete 2FA set up.");
                    return(View(model));
                }

                _logger.LogError("~/Account/EnableAuthenticator(EnableAuthenticatorViewModel) - Error from IdApi - {0}", badResponseObj);
                TempData["ErrorMessage"] = "An error occurred while setting up your account for 2 factor authentication.";
                return(RedirectToAction(nameof(Index)));
            }

            string responseObj = await response.Content.ReadAsStringAsync();

            EnableAuthenticatorViewModel responseModel = JsonSerializer.Deserialize <EnableAuthenticatorViewModel>(responseObj);

            response.EnsureSuccessStatusCode();

            _logger.LogInformation("User with id:{0} has enabled 2FA with an authenticator app.", id);

            return(View("ShowCodes", responseModel));
        }
        public static string ToBase64(this ResponsePayload request)
        {
            var sb = new StringBuilder()
                     .AppendLine(request.Identifier)
                     .AppendLine(request.RequestCount);

            return(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sb.ToString())));
        }
Beispiel #14
0
        private string CreateDebugBody(SlackMessage order)
        {
            var payload = new ResponsePayload
            {
                Text = JsonConvert.SerializeObject(this._body)
            };

            return(JsonConvert.SerializeObject(payload));
        }
Beispiel #15
0
        /// <summary>
        /// 指定のバッファから初期化
        /// </summary>
        /// <param name="buffer">フレームのバッファ</param>
        /// <param name="index">フレームの開始位置</param>
        /// <param name="count">フレームのバイト数</param>
        public Frame(byte[] buffer, int index, int count)
        {
            using (var memoryStream = new MemoryStream(buffer, index, count, false))
                using (var binaryReader = new BinaryReader(memoryStream))
                {
                    // データ長チェック
                    if (count < MinimumSize)
                    {
                        throw new DamagedDataException($"データ長が 共通フレームの長さに満たない。{nameof(count)}={count} {nameof(MinimumSize)}={MinimumSize}");
                    }
                    //
                    Header = binaryReader.ReadUInt16();

                    DebugWriteLine($"{nameof(Header)}={Header.ToString("X4")}");

                    if (Header != MagicNumber)
                    {
                        // 対応してるデータではない
                        throw new NotSupportedException($"Header={Header.ToString("X4")}");
                    }
                    Length = binaryReader.ReadUInt16();

                    DebugWriteLine($"{nameof(Length)}={Length}");

                    // データ長チェック
                    {
                        // 本来あるべき全体のサイズ
                        var requestedLength = Length + TopSize;
                        if (count < requestedLength)
                        {
                            throw new DamagedDataException($"データ長が短い。{nameof(count)}={count} {nameof(requestedLength)}={requestedLength}");
                        }
                    }
                    // CRCチェック
                    {
                        memoryStream.Seek(0, SeekOrigin.Begin);// 最初に戻る
                        var tempBuffer = new byte[Length + TopSize - CRC16Size];
                        memoryStream.Read(tempBuffer, 0, tempBuffer.Length);
                        var computedCRC16 = crc16.ComputeHash(tempBuffer);
                        CRC16 = binaryReader.ReadUInt16();

                        DebugWriteLine($"{nameof(CRC16)}={CRC16}");

                        if (CRC16 != computedCRC16)
                        {
                            // CRCの結果 データ破損
                            throw new DamagedDataException($"CRC値の不一致。{nameof(CRC16)}={CRC16.ToString("X4")} {nameof(computedCRC16)}={computedCRC16.ToString("X4")}");
                        }
                    }
                    // Payload読み込み
                    {
                        Payload = ResponsePayload.Create(binaryReader, TopSize);
                    }
                }
        }
Beispiel #16
0
        private static bool Connect()
        {
            bool result = false;

            IntelliSenseServer.Register();

            // Create a client connector which will do an initial request to the Opus ServerSocket and retrieve all available methods.
            var            socketConnector = new SocketConnector();
            MethodRegistry registry        = new MethodRegistry(socketConnector);

            // Execute the INITIALIZE function to retrieve all available functions from the client
            ResponsePayload response = socketConnector.executeFn(new FunctionPayload(SocketConnector.INITIALIZE));

            if (response != null && response.matrix != null && response.matrix.data != null)
            {
                // The inital request returns the available functions.
                // Example Message from Client:
                // { "name":"INITIALIZE",
                //   "matrix":[["getVersion",[]],["getPortfolio",[["accountSegmentId","The Account Segment Id for which the Portfolio will be fetched."]]],["getCurrencies",[]]],"error":""}
                response.matrix.data.ForEach(entry =>
                {
                    // TODO: Create a serializable Wrapper Class to do this.
                    var arguments = new List <OpuxlArgumentAttribute>();
                    // First Element is the function name
                    string functionName        = (string)entry.ElementAt(0);
                    string functionDescription = (string)entry.ElementAt(1);
                    // and second Element is an array of parameterName/parameterDescription pairs.
                    JArray argsArray = (JArray)entry.ElementAt(2);

                    foreach (JArray arg in argsArray)
                    {
                        // Create an Excel Argument for each Function Parameter.
                        arguments.Add(new OpuxlArgumentAttribute
                        {
                            Name        = arg.ElementAt(0).ToString(),
                            Description = arg.ElementAt(1).ToString(),
                            Type        = Main.ParseEnum <ExcelType>(arg.ElementAt(2).ToString()),
                            Optional    = Boolean.Parse(arg.ElementAt(3).ToString())
                        });
                    }
                    // Create a delegate in our registry for each function
                    registry.addDelegate(functionName, functionDescription, arguments);
                });
                result = true;
            }
            else
            {
                Debug.WriteLine("Response not set, cant register functions.");
            }


            // Register all retrieves functions as delegates which are going to be available in excel.
            registry.createDelegates();
            return(result);
        }
Beispiel #17
0
        public override JsonResult GetAll()
        {
            ResponsePayload  response   = new ResponsePayload();
            ResponseDelegate myDelegate = () =>
            {
                var result = empService.GetAllEmployees();
                response.Data = new { data = result };
            };

            return(ExecService(myDelegate, response));
        }
Beispiel #18
0
 public async ValueTask <ResponsePayload> ReadAsync(
     RequestPayload requestPayload,
     CancellationToken cancellationToken = default)
 {
     return(await ResponsePayload
            .ReadFromAsync(
                requestPayload,
                Reader,
                cancellationToken)
            .ConfigureAwait(false));
 }
Beispiel #19
0
        public async Task ShouldReceive200AndValueOnIncrementRequestCount()
        {
            var client = new HttpClient();

            var url    = string.Concat(_address, "/api/values/5");
            var result = await client.GetAsync(url);

            var wwwAuthenticate = result.Headers.WwwAuthenticate.First();

            Assert.AreEqual(HttpStatusCode.Unauthorized, result.StatusCode);
            StringAssert.Equals(wwwAuthenticate.Scheme, "AuthAPI");

            var responsePayload = new ResponsePayload(wwwAuthenticate.Parameter);

            var requestPayload = new RequestPayload
            {
                ClientId     = "TestAPI",
                Identifier   = responsePayload.Identifier,
                RequestCount = string.Format("{0:D8}", int.Parse(responsePayload.RequestCount) + 1),
                UserName     = "******"
            };

            var dataPayload = new DataPayload
            {
                ClientId          = "TestAPI",
                Method            = "GET",
                Password          = "******",
                RequestBodyBase64 = string.Empty,
                RequestURI        = "/api/values/5",
                UserName          = "******"
            };

            var authHeader = new AuthHeader
            {
                Data    = dataPayload,
                Request = requestPayload
            };

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("AuthAPI", authHeader.ToAuthorizationHeader("QiU6bSt3anE2OURfX3IsKlVZen05K1tBLW5AQ1x1d0xIXVZwaGE7Zj83QTc0ZXthVy9aWV9UZ0tUcnRUVEQ6d2JxTEhGOi9fMitBfiNZOS5NXHlyJzNnNSl1VzxNQExkQXtHJEQ+fWElMkMhWUJhLT8kbUFeQERWa310J2N+NkQ="));

            result = await client.GetAsync(url);

            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            Assert.AreEqual(await result.Content.ReadAsAsync <string>(), "value");

            authHeader.Request.RequestCount = string.Format("{0:D8}", int.Parse(authHeader.Request.RequestCount) + 1);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("AuthAPI", authHeader.ToAuthorizationHeader("QiU6bSt3anE2OURfX3IsKlVZen05K1tBLW5AQ1x1d0xIXVZwaGE7Zj83QTc0ZXthVy9aWV9UZ0tUcnRUVEQ6d2JxTEhGOi9fMitBfiNZOS5NXHlyJzNnNSl1VzxNQExkQXtHJEQ+fWElMkMhWUJhLT8kbUFeQERWa310J2N+NkQ="));
            result = await client.GetAsync(url);

            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
        }
Beispiel #20
0
        static int Main(string[] args)
        {
            System.Diagnostics.Debug.WriteLine("Starting ...");
            var             server   = new SocketConnector();
            ResponsePayload response = server.executeFn(new FunctionPayload(SocketConnector.INITIALIZE));

            if (response.name.Equals(SocketConnector.INITIALIZE))
            {
                System.Diagnostics.Debug.WriteLine("Register the following methods: " + response.ToString());
            }

            return(0);
        }
        public void ResponsePayloadModelStateServiceReturnType()
        {
            var error      = new ErrorResponse("Sample ErrorResponse", 400, ResponsePayloadType.BusinessException, "Sample Service");
            var modelState = new ModelStateDictionary();

            modelState.AddModelError("SampleError", "Sample ErrorResponse Message");
            _responsePayload = new ResponsePayload <string>(modelState, "Sample Service", ResponsePayloadType.BusinessException, 500);
            _responsePayload.ResponseStatus.Errors.Add(error);
            Assert.IsType <ResponseStatus>(_responsePayload.ResponseStatus);
            Assert.Equal(ResponsePayloadType.BusinessException, _responsePayload.ResponseStatus.Type);
            Assert.Equal(500, _responsePayload.ResponseStatus.Code);
            Assert.Equal(2, _responsePayload.ResponseStatus.Errors.Count);
        }
Beispiel #22
0
        public async Task ShouldReceive200OnPost()
        {
            var client = new HttpClient();

            var valuesModel = new ValuesModel
            {
                Id   = 1,
                Name = "oi"
            };
            var url    = string.Concat(_address, "/api/values");
            var result = await client.PostAsJsonAsync <ValuesModel>(url, valuesModel);

            var wwwAuthenticate = result.Headers.WwwAuthenticate.First();

            Assert.AreEqual(HttpStatusCode.Unauthorized, result.StatusCode);
            StringAssert.Equals(wwwAuthenticate.Scheme, "AuthAPI");

            var responsePayload = new ResponsePayload(wwwAuthenticate.Parameter);

            var requestPayload = new RequestPayload
            {
                ClientId     = "TestAPI",
                Identifier   = responsePayload.Identifier,
                RequestCount = string.Format("{0:D8}", int.Parse(responsePayload.RequestCount) + 1),
                UserName     = "******"
            };

            var json = JsonConvert.SerializeObject(valuesModel);

            var dataPayload = new DataPayload
            {
                ClientId          = "TestAPI",
                Method            = "POST",
                Password          = "******",
                RequestBodyBase64 = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(valuesModel))),
                RequestURI        = "/api/values",
                UserName          = "******"
            };

            var authHeader = new AuthHeader
            {
                Data    = dataPayload,
                Request = requestPayload
            };

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("AuthAPI", authHeader.ToAuthorizationHeader("QiU6bSt3anE2OURfX3IsKlVZen05K1tBLW5AQ1x1d0xIXVZwaGE7Zj83QTc0ZXthVy9aWV9UZ0tUcnRUVEQ6d2JxTEhGOi9fMitBfiNZOS5NXHlyJzNnNSl1VzxNQExkQXtHJEQ+fWElMkMhWUJhLT8kbUFeQERWa310J2N+NkQ="));

            result = result = await client.PostAsJsonAsync <ValuesModel>(url, valuesModel);

            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
        }
        private int parseFrequency(ResponsePayload payload)
        {
            int value = 2;

            try
            {
                Int32.TryParse(payload.entities.First(e => e.type == "builtin.number").entity, out value);
                return(value);
            }
            catch
            {
                return(value);
            }
        }
        public Task <bool> UpdateResponse(string identifier, ResponsePayload newResponse)
        {
            var currentCache = _cache.Remove(identifier);

            var result = false;

            if (currentCache != null)
            {
                var transformedRequest = (StoredResponse)currentCache;
                result = _cache.Add(identifier, newResponse.ToStoredResponse(transformedRequest.Expiration), transformedRequest.Expiration);
            }

            return(Task.FromResult(result));
        }
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
             if (RequestPayload != null)
             hashCode = hashCode * 59 + RequestPayload.GetHashCode();
             if (ResponsePayload != null)
             hashCode = hashCode * 59 + ResponsePayload.GetHashCode();
             if (StatusCode != null)
             hashCode = hashCode * 59 + StatusCode.GetHashCode();
         return hashCode;
     }
 }
Beispiel #26
0
 public void Insert(ResponsePayload entity)
 {
     Connection.Execute(
         "SProc_ResponsePayload_Insert",
         commandType: CommandType.StoredProcedure,
         param: new
     {
         entity.Id
         , entity.ResponseHeaders
         , entity.ContentHeaders
         , entity.JsonContent
         , entity.Created
     }
         );
 }
        public static List <ErrorModel> ToErrorList <T>(this ResponsePayload <T> response)
        {
            var errors = new List <ErrorModel>();

            if (response == null || !response.Errors.Any())
            {
                return(errors);
            }

            for (int i = 0; i < response.Errors.Count; i++)
            {
                errors.Add(new ErrorModel(response.ErrorCodes[i], response.Errors[i]));
            }

            return(errors);
        }
Beispiel #28
0
        public override async Task OnRequest()
        {
            //Check to see if this is a valid ARK server
            if (!e.Request.Query.ContainsKey("client_version"))
            {
                e.Response.StatusCode = 400;
                await Program.WriteStringToStream(e.Response.Body, "Required information was not sent, this is likely not a valid ARK server.\r\n\r\nIt's likely that you're looking into how things here work. More information: https://github.com/deltawebmap/Docs/blob/master/basics.md \r\n\r\n(C) DeltaWebMap 2020, RomanPort 2020");

                return;
            }

            //Get version
            int clientVersion = int.Parse(e.Request.Query["client_version"]);

            //If the version is too old, reject
            if (clientVersion < MIN_ALLOWED_VERSION)
            {
                //Create a response
                ResponsePayload r = new ResponsePayload
                {
                    start_allowed = false,
                    start_msg     = "Can't Connect: This version of the mod, " + clientVersion + ", is too old. Please upgrade to a newer version using the Steam Workshop. Need help? https://deltamap.net/support/."
                };

                //Write response
                await Program.WriteStringToStream(e.Response.Body, "D001" + Newtonsoft.Json.JsonConvert.SerializeObject(r));

                return;
            }

            //Create the requested INI settings
            List <ResponsePayload_ConfigRequest> iniSettings = CreateIniRequestData();

            //Create a response
            ResponsePayload response = new ResponsePayload
            {
                delta_config     = Program.clientConfig,
                ini_settings     = iniSettings,
                start_allowed    = true,
                start_msg        = "Connected! Welcome to the Delta Web Map beta!",
                debug_timings    = false,
                debug_remote_log = false
            };

            //Write response
            await Program.WriteStringToStream(e.Response.Body, "D001" + Newtonsoft.Json.JsonConvert.SerializeObject(response));
        }
Beispiel #29
0
        public async Task SendResponseAsync(Header header, StreamingResponse response, CancellationToken cancellationToken)
        {
            if (header == null)
            {
                throw new ArgumentNullException(nameof(header));
            }

            if (header.Type != PayloadTypes.Response)
            {
                throw new InvalidOperationException($"StreamingSession SendResponseAsync expected Response payload, but instead received a payload of type {header.Type}");
            }

            if (response == null)
            {
                throw new ArgumentNullException(nameof(response));
            }

            var payload = new ResponsePayload()
            {
                StatusCode = response.StatusCode,
            };

            if (response.Streams != null)
            {
                payload.Streams = new List <StreamDescription>();
                foreach (var contentStream in response.Streams)
                {
                    var description = GetStreamDescription(contentStream);

                    payload.Streams.Add(description);
                }
            }

            await _sender.SendResponseAsync(header.Id, payload, cancellationToken).ConfigureAwait(false);

            if (response.Streams != null)
            {
                foreach (var stream in response.Streams)
                {
                    await _sender.SendStreamAsync(stream.Id, await stream.Content.ReadAsStreamAsync().ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
                }
            }
        }
Beispiel #30
0
        public T CallAction <T>(string actionName, BaseRequest request, Context context) where T : BaseResponse
        {
            ResponsePayload response = CallAction(actionName, request, context);

            if (response != null)
            {
                ContextProvider.SetContext(response.Context);
                if (response.Context.ActiveResult?.IsSuccess == true)
                {
                    return((T)response.Response);
                }
                else
                {
                    throw new JMException(response.Context.ActiveResult.Errors[0].Code, response.Context.ActiveResult.Errors[0].Message);
                }
            }
            else
            {
                return(default(T));
            }
        }