예제 #1
0
        public void TestDeleteItemFromSelectList()
        {
            using (RpcBroker broker = GetConnectedBroker())
            {
                this.SignonToBroker(broker, 2);

                DsioSelectListCommand command = new DsioSelectListCommand(broker);

                command.AddCommandArguments("R", "Bogus Reason", DsioSelectListCommand.SelectListOperation.Delete);

                RpcResponse response = command.Execute();

                Assert.AreEqual(RpcResponseStatus.Success, response.Status);

                broker.Disconnect();
            }
        }
예제 #2
0
        public async Task <PayRequestOM> CreateNewPaymentRequest(string accountId, string tag, long amount, string comment)
        {
            AuthenticationHeaderValue authHeaderValue = null;
            RpcClient  client  = new RpcClient(new Uri("http://localhost:5006"), authHeaderValue, null, null, "application/json");
            RpcRequest request = RpcRequest.WithParameterList("CreateNewPaymentRequest", new List <object> {
                accountId, tag, amount, comment
            }, 1);
            RpcResponse response = await client.SendRequestAsync(request);

            if (response.HasError)
            {
                throw new ApiCustomException(response.Error.Code, response.Error.Message);
            }
            PayRequestOM responseValue = response.GetResult <PayRequestOM>();

            return(responseValue);
        }
        public void Should_return_and_log_warn_msg_if_the_waitHandlers_does_not_contain_requestId()
        {
            // Arrange
            InternalDependencies.RpcQueueHelper = Substitute.For <IRpcQueueHelper>();
            var client = new BurrowRpcClientCoordinator <ISomeService>(null, Substitute.For <IRpcRouteFinder>());

            var res = new RpcResponse
            {
                RequestId = Guid.NewGuid()
            };

            // Action
            client.ReceiveResponse(res);

            // Assert
            Global.DefaultWatcher.Received(1).WarnFormat(Arg.Any <string>(), Arg.Any <object[]>());
        }
예제 #4
0
        public void TestGetSelectList()
        {
            using (RpcBroker broker = GetConnectedBroker())
            {
                this.SignonToBroker(broker, 2);

                DsioSelectListCommand command = new DsioSelectListCommand(broker);

                command.AddCommandArguments("R");

                RpcResponse response = command.Execute();

                Assert.AreEqual(RpcResponseStatus.Success, response.Status);

                broker.Disconnect();
            }
        }
        public ObservationListResult GetObservations(string patientDfn, string pregnancyIen, string babyIen, string fromDate, string toDate, string category, int page, int itemsPerPage)
        {
            // *** Get a list of observations matching criteria ***

            ObservationListResult result = new ObservationListResult();

            // *** Create command ***
            DsioGetObservationsCommand command = new DsioGetObservationsCommand(this.broker);

            // *** Add command arguments ***
            command.AddCommandArguments(patientDfn, "", pregnancyIen, babyIen, "", fromDate, toDate, category, page, itemsPerPage);

            // *** Execute ***
            RpcResponse response = command.Execute();

            // *** Add response to result ***
            result.Success = response.Status == RpcResponseStatus.Success;
            result.Message = response.InformationalMessage;

            // *** Add observations ***
            if (result.Success)
            {
                result.TotalResults = command.TotalResults;

                if (command.ObservationsList != null)
                {
                    if (command.ObservationsList.Count > 0)
                    {
                        //result.Observations.AddRange(command.ObservationsList);

                        foreach (DsioObservation dsioObs in command.ObservationsList)
                        {
                            Observation obs = ObservationUtility.GetObservation(dsioObs);

                            if (obs != null)
                            {
                                result.Observations.Add(obs);
                            }
                        }
                    }
                }
            }

            return(result);
        }
        public PatientEducationItemsResult GetPatientItems(string patientDfn, string ien, DateTime fromDate, DateTime toDate, EducationItemType itemType, int page, int itemsPerPage)
        {
            PatientEducationItemsResult result = new PatientEducationItemsResult();

            if (this.broker != null)
            {
                DsioGetPatientEducationCommand command = new DsioGetPatientEducationCommand(this.broker);

                string dsioItemType = GetDsioItemType(itemType);

                string fmFromDate = Util.GetFileManDate(fromDate);
                string fmToDate   = Util.GetFileManDate(toDate);

                command.AddCommandArguments(patientDfn, ien, fmFromDate, fmToDate, dsioItemType, page, itemsPerPage);

                RpcResponse response = command.Execute();

                result.SetResult(response.Status == RpcResponseStatus.Success, response.InformationalMessage);

                if (result.Success)
                {
                    if (command.Items != null)
                    {
                        if (command.Items.Count > 0)
                        {
                            foreach (DsioPatientEducationItem dsioItem in command.Items)
                            {
                                EducationItem item = GetItem(dsioItem);

                                PatientEducationItem patItem = new PatientEducationItem(item);

                                patItem.CompletedOn = Util.GetDateTime(dsioItem.CompletedOn);
                                patItem.CompletedBy = dsioItem.CompletedBy;

                                result.Items.Add(patItem);
                            }

                            result.TotalResults = command.TotalResults;
                        }
                    }
                }
            }

            return(result);
        }
        public void TestSaveEducationItem()
        {
            using (RpcBroker broker = this.GetConnectedBroker())
            {
                this.SignonToBroker(broker, 2);

                DsioSaveEducationItemCommand command = new DsioSaveEducationItemCommand(broker);

                DsioEducationItem edItem = new DsioEducationItem()
                {
                    Description = "-----Purple Book",
                    Category    = "Other",
                    ItemType    = "L",
                    Url         = "http://www.medlineplus.com",
                    CodeSystem  = "L",
                    Code        = "11779-6"
                };

                //DsioEducationItem edItem = new DsioEducationItem()
                //{
                //    Description = "Link to smoking in pregnancy video",
                //    Category = "Smoking",
                //    ItemType = "L",
                //    CodeSystem = "None",
                //    Url = "http://www.va.gov/vdl"
                //};

                //DsioEducationItem edItem = new DsioEducationItem()
                //{
                //    Description = "D234567891123456789212345678931234567894123456789512345678961234567897123456789812345678991234567890",
                //    Category = "C234567891123456789212345678931234567894123456789512345678961234567897123456789812345678991234567890",
                //    ItemType = "L",
                //    CodeSystem = "None",
                //    Url = "U234567891123456789212345678931234567894123456789512345678961234567897123456789812345678991234567890"
                //};
                command.AddCommandArguments(edItem);

                RpcResponse response = command.Execute();

                Assert.AreEqual(RpcResponseStatus.Success, response.Status);
                Assert.IsNotNull(command.Ien);

                broker.Disconnect();
            }
        }
예제 #8
0
        public void TestGetTracking_TrackedPatients()
        {
            using (RpcBroker broker = GetConnectedBroker())
            {
                this.SignonToBroker(broker, 2);

                DsioGetTrackingCommand command = new DsioGetTrackingCommand(broker);

                command.AddGetTrackedPatientsParameters(1, 100);

                RpcResponse response = command.Execute();

                Assert.AreEqual(RpcResponseStatus.Success, response.Status);
                Assert.IsNotNull(command.TrackedPatients);

                broker.Disconnect();
            }
        }
예제 #9
0
        public void TestSaveIHE()
        {
            using (RpcBroker broker = this.GetConnectedBroker())
            {
                this.SignonToBroker(broker, 2);

                DsioSaveIheDocCommand command = new DsioSaveIheDocCommand(broker);

                string content = File.ReadAllText(testFile);

                command.AddCommandArguments("", Guid.NewGuid().ToString("B"), TestConfiguration.DefaultPatientDfn, "OUT", DateTime.Now.ToString(), DateTime.Now.ToString(), "APS", "This is a Test Title", "VA", "Outside Clinic", content);

                RpcResponse response = command.Execute();

                Assert.IsNotNull(response);
                Assert.AreEqual(RpcResponseStatus.Success, response.Status);
            }
        }
예제 #10
0
        public void TestPatientSearch2()
        {
            using (RpcBroker broker = GetConnectedBroker())
            {
                this.SignonToBroker(broker, 2);

                //DsioFemalePatientSearchCommand command = new DsioFemalePatientSearchCommand(broker);
                DsioPatientListCommand command = new DsioPatientListCommand(broker);

                command.AddCommandArguments("Ay", 1, 10);

                RpcResponse response = command.Execute();

                Assert.AreEqual(RpcResponseStatus.Success, response.Status);

                broker.Disconnect();
            }
        }
예제 #11
0
        public void TestGetTracking_AllEntriesByPatient()
        {
            using (RpcBroker broker = GetConnectedBroker())
            {
                this.SignonToBroker(broker, 2);

                DsioGetTrackingCommand command = new DsioGetTrackingCommand(broker);

                command.AddPatientLogsParameter(TestConfiguration.DefaultPatientDfn, 1, 3);

                RpcResponse response = command.Execute();

                Assert.AreEqual(RpcResponseStatus.Success, response.Status);
                Assert.IsNotNull(command.TrackingItems);

                broker.Disconnect();
            }
        }
예제 #12
0
        public void TestCreateContext()
        {
            using (RpcBroker broker = new RpcBroker("", validServerPort))
            {
                if (broker.Connect())
                {
                    RpcResponse response = broker.CreateContext("XUS SIGNON");

                    Assert.AreSame(broker.CurrentContext, "XUS SIGNON");

                    broker.Disconnect();
                }
                else
                {
                    Assert.Fail("No connection");
                }
            }
        }
예제 #13
0
    private async Task <RpcResponse <EquihashBlockTemplate> > GetBlockTemplateAsync(CancellationToken ct)
    {
        var subsidyResponse = await rpc.ExecuteAsync <ZCashBlockSubsidy>(logger, BitcoinCommands.GetBlockSubsidy, ct);

        var result = await rpc.ExecuteAsync <EquihashBlockTemplate>(logger,
                                                                    BitcoinCommands.GetBlockTemplate, ct, extraPoolConfig?.GBTArgs ?? (object)GetBlockTemplateParams());

        if (subsidyResponse.Error == null && result.Error == null && result.Response != null)
        {
            result.Response.Subsidy = subsidyResponse.Response;
        }
        else if (subsidyResponse.Error?.Code != (int)BitcoinRPCErrorCode.RPC_METHOD_NOT_FOUND)
        {
            result = new RpcResponse <EquihashBlockTemplate>(null, new JsonRpcError(-1, $"{BitcoinCommands.GetBlockSubsidy} failed", null));
        }

        return(result);
    }
        public void TestGetEducationItemsFiltered()
        {
            using (RpcBroker broker = this.GetConnectedBroker())
            {
                this.SignonToBroker(broker, 2);

                DsioGetEducationItemsCommand command = new DsioGetEducationItemsCommand(broker);

                //command.AddCommandArguments("", "","PRINTED MATERIAL", 2, 2);
                command.AddCommandArguments("", "", "PRINTED MATERIAL", 0, 0, 0);

                RpcResponse response = command.Execute();

                Assert.AreEqual(RpcResponseStatus.Success, response.Status);

                broker.Disconnect();
            }
        }
예제 #15
0
        public BrokerOperationResult SignNote(string ien, string sig)
        {
            BrokerOperationResult result = new BrokerOperationResult();

            if (this.broker != null)
            {
                DsioSignANoteCommand command = new DsioSignANoteCommand(this.broker);

                command.AddCommandArguments(ien, sig);

                RpcResponse response = command.Execute();

                result.Success = (response.Status == RpcResponseStatus.Success);
                result.Message = response.InformationalMessage;
            }

            return(result);
        }
예제 #16
0
        public void TestCreateANoteWithPregnancy()
        {
            using (RpcBroker broker = GetConnectedBroker())
            {
                this.SignonToBroker(broker, 2);

                DsioCreateANoteCommand command = new DsioCreateANoteCommand(broker);

                // TODO: Use a real pregnancy...
                //command.AddCommandArguments("197", "PHONE CALL #1 (FIRST CONTACT)", "Final Tuesday Testing?", "A Subject Goes Here", new DsioNoteData(), "140");
                //command.AddCommandArguments("197", "PHONE CALL #1 (FIRST CONTACT)", "Wed Note", "A Subject Goes Here", new DsioNoteData(), "");
                command.AddCommandArguments("100017", "PHONE CALL #1 (FIRST CONTACT)", "Tue Note", "A Subject Goes Here", new DsioNoteData(), "57");

                RpcResponse response = command.Execute();

                Assert.AreEqual(RpcResponseStatus.Success, response.Status);
            }
        }
예제 #17
0
        public void TestConsultDetail()
        {
            using (RpcBroker broker = this.GetConnectedBroker())
            {
                // TODO: Get working with non-programmer
                this.SignonToBroker(broker, 2);

                OrqqcnDetailCommand command = new OrqqcnDetailCommand(broker);

                command.AddCommandArguments("554");

                RpcResponse response = command.Execute();

                Assert.AreEqual(RpcResponseStatus.Success, response.Status);

                broker.Disconnect();
            }
        }
        public void TestConsultList()
        {
            using (RpcBroker broker = this.GetConnectedBroker())
            {
                this.SignonToBroker(broker, 2);

                OrqqcnListCommand command = new OrqqcnListCommand(broker);

                //command.AddCommandArguments("715");
                command.AddCommandArguments(TestConfiguration.DefaultPatientDfn);

                RpcResponse response = command.Execute();

                Assert.AreEqual(RpcResponseStatus.Success, response.Status);

                broker.Disconnect();
            }
        }
예제 #19
0
        public void TestValidRpc()
        {
            using (RpcBroker broker = new RpcBroker("", validServerPort))
            {
                if (broker.Connect())
                {
                    RpcResponse response = broker.CallRpc("", "XUS INTRO MSG", "0", null);

                    Assert.AreEqual(RpcResponseStatus.Success, response.Status);

                    broker.Disconnect();
                }
                else
                {
                    Assert.Fail("No connection");
                }
            }
        }
예제 #20
0
        public async Task <RpcResponse> SendAsync(RpcRequest request)
        {
            var requestJson = request.ToJson().ToString();
            var result      = await httpClient.PostAsync(httpClient.BaseAddress, new StringContent(requestJson, Encoding.UTF8));

            var content = await result.Content.ReadAsStringAsync();

            var response = RpcResponse.FromJson(JObject.Parse(content));

            response.RawResponse = content;

            if (response.Error != null)
            {
                throw new RpcException(response.Error.Code, response.Error.Message);
            }

            return(response);
        }
예제 #21
0
        public static async void UnclaimObject <T>([FromSource] Player player, string json) where T : class, IObject
        {
            var response = RpcResponse <int> .Parse(json);

            int netId = response.Result;
            T   obj   = Server.Db.Set <T>().FirstOrDefault(c => c.NetId == netId);

            if (obj == null)
            {
                return;
            }
            obj.TrackingUserId = Guid.Empty;
            obj.Handle         = null;
            obj.NetId          = null;

            Server.Db.Set <T>().AddOrUpdate(obj);
            await Server.Db.SaveChangesAsync();
        }
        public void TestDeleteEducationItem()
        {
            using (RpcBroker broker = this.GetConnectedBroker())
            {
                this.SignonToBroker(broker, 2);

                DsioSaveEducationItemCommand command = new DsioSaveEducationItemCommand(broker);

                DsioEducationItem edItem = new DsioEducationItem()
                {
                    Description = "This is something I want to delete on Tuesday",
                    Category    = "Smoking",
                    ItemType    = "L",
                    CodeSystem  = "None",
                    Url         = "http://www.va.gov/vdl"
                };

                command.AddCommandArguments(edItem);

                RpcResponse response = command.Execute();

                Assert.AreEqual(RpcResponseStatus.Success, response.Status);
                Assert.IsNotNull(command.Ien);

                DsioDeleteEducationItemCommand delCommand = new DsioDeleteEducationItemCommand(broker);

                delCommand.AddCommandArguments(command.Ien);

                response = delCommand.Execute();

                Assert.AreEqual(RpcResponseStatus.Success, response.Status);

                DsioGetEducationItemsCommand getCommand = new DsioGetEducationItemsCommand(broker);

                getCommand.AddCommandArguments(command.Ien, "", "", 0, 0, 0);

                response = getCommand.Execute();

                Assert.AreEqual(RpcResponseStatus.Success, response.Status);
                Assert.IsNull(getCommand.EducationItems);

                broker.Disconnect();
            }
        }
        public PregnancyListResult GetPregnancies(string patientDfn, string pregnancyIen)
        {
            PregnancyListResult result = new PregnancyListResult();

            // *** Create the command ***
            DsioGetPregDetailsCommand command = new DsioGetPregDetailsCommand(this.broker);

            // *** Add arguments...gets all ***
            command.AddCommandArguments(patientDfn, pregnancyIen);

            // *** Execute command ***
            RpcResponse response = command.Execute();

            // *** Add response to result ***
            result.SetResult(response.Status == RpcResponseStatus.Success, response.InformationalMessage);

            // *** Check for success ***
            if (result.Success)
            {
                // *** Loop through the list and create strongly typed pregnancy list ***
                if (command.PregnancyList != null)
                {
                    foreach (DsioPregnancy dsioPreg in command.PregnancyList)
                    {
                        if (result.Pregnancies == null)
                        {
                            result.Pregnancies = new List <PregnancyDetails>();
                        }

                        PregnancyDetails tempPregnancy = CreatePregnancy(dsioPreg);

                        result.Pregnancies.Add(tempPregnancy);
                    }
                }

                // *** If no pregnancies, then nothing found ***
                if (result.Pregnancies == null)
                {
                    result.SetResult(true, "No Pregnancy Data Found");
                }
            }

            return(result);
        }
예제 #24
0
        public void TestDeletePatientChecklistItem()
        {
            using (RpcBroker broker = this.GetConnectedBroker())
            {
                // TODO: Test with non-programmer user
                this.SignonToBroker(broker, 2);
                //this.SignonToBroker(broker, 0);

                DsioSaveMccPatChecklistCommand saveCommand = new DsioSaveMccPatChecklistCommand(broker);

                DsioPatientChecklistItem item = new DsioPatientChecklistItem()
                {
                    PatientDfn          = "28",
                    PregnancyIen        = "4",
                    Category            = "First Trimester Requirements",
                    Description         = "Friday Tests",
                    ItemType            = DsioChecklistItemType.Lab,
                    DueCalculationType  = DsioChecklistCalculationType.None,
                    DueCalculationValue = "0",
                    CompletionStatus    = DsioChecklistCompletionStatus.Complete,
                    Link            = "12345",
                    SpecificDueDate = Util.GetFileManDate(new DateTime(2014, 9, 1)),
                    CompletionLink  = "54321",
                    Note            = "Checklist Item Note Text",
                    InProgress      = "1"
                };

                saveCommand.AddCommandArguments(item);

                RpcResponse response = saveCommand.Execute();

                Assert.AreEqual(RpcResponseStatus.Success, response.Status);

                Assert.IsFalse(string.IsNullOrWhiteSpace(saveCommand.Ien));

                DsioDeleteMccPatChklstCommand delCommand = new DsioDeleteMccPatChklstCommand(broker);

                delCommand.AddCommandArguments("28", saveCommand.Ien);

                response = delCommand.Execute();

                Assert.AreEqual(RpcResponseStatus.Success, response.Status);
            }
        }
예제 #25
0
        public void TestUpdateNonVAItem()
        {
            using (RpcBroker broker = GetConnectedBroker())
            {
                this.SignonToBroker(broker, 3);

                DsioGetExternalEntityCommand getCommand = new DsioGetExternalEntityCommand(broker);

                getCommand.AddCommandArguments("7", 1, 10);

                RpcResponse response = getCommand.Execute();

                Assert.AreEqual(RpcResponseStatus.Success, response.Status);

                DsioSaveExternalEntityCommand command = new DsioSaveExternalEntityCommand(broker);

                Assert.IsNotNull(getCommand.NonVAEntities);
                Assert.IsTrue(getCommand.NonVAEntities.Count == 1);

                DsioNonVAItem nonVAEntity = getCommand.NonVAEntities[0];

                nonVAEntity.EntityName = "Smallest Hospital Four";

                //nonVAEntity.Ien = "";
                //nonVAEntity.EntityName = "Smallish Hospital Four";
                //nonVAEntity.EntityType = "F";
                //nonVAEntity.Address.StreetLine1 = "789 Test Street";
                //nonVAEntity.Address.StreetLine2 = "Suite XFD";
                //nonVAEntity.Address.City = "Sacramento";
                //nonVAEntity.Address.State = "CA";
                //nonVAEntity.Address.ZipCode = "93939";
                //nonVAEntity.TelephoneList.Add(new DsioTelephone() { Number = "8009008000", Usage = DsioTelephone.WorkPhoneUsage });
                //nonVAEntity.TelephoneList.Add(new DsioTelephone() { Number = "8887776666", Usage = DsioTelephone.FaxUsage });

                //nonVAEntity.PrimaryContact = "Extra Important";
                //nonVAEntity.Inactive = "0";

                command.AddCommandArguments(nonVAEntity);

                response = command.Execute();

                Assert.AreEqual(RpcResponseStatus.Success, response.Status);
            }
        }
        public int GetUserTimeout()
        {
            // *** Returns value in seconds ***

            int returnVal = 600;

            if (this.broker != null)
            {
                OrwuUserInfoCommand command  = new OrwuUserInfoCommand(broker);
                RpcResponse         response = command.Execute();

                if (command.Response.Status == RpcResponseStatus.Success)
                {
                    returnVal = command.UserInfo.Timeout;
                }
            }

            return(returnVal);
        }
예제 #27
0
        public async Task InvokeRequest_BoolDictParam_Valid()
        {
            string            methodName = nameof(TestRouteClass.BoolParameter);
            DefaultRpcInvoker invoker    = this.GetInvoker(methodName);

            bool expectedValue = true;
            var  param         = JsonBytesRpcParameter.FromRaw(expectedValue);
            var  paramDict     = new Dictionary <string, IRpcParameter>
            {
                ["a"] = param
            };
            RpcRequest  stringRequest = new RpcRequest("1", methodName, parameters: new RpcParameters(paramDict));
            RpcResponse?response      = await invoker.InvokeRequestAsync(stringRequest);

            RpcResponse resultResponse = Assert.IsType <RpcResponse>(response);

            Assert.False(resultResponse.HasError);
            Assert.Equal(expectedValue, resultResponse.Result);
        }
예제 #28
0
        public async Task InvokeRequest_ComplexParam_Valid()
        {
            string            methodName = nameof(TestRouteClass.ComplexParam);
            DefaultRpcInvoker invoker    = this.GetInvoker(methodName);

            TestComplexParam param = new TestComplexParam
            {
                A = "Test",
                B = 5
            };
            var         rpcParameter  = JsonBytesRpcParameter.FromRaw(param);
            RpcRequest  stringRequest = new RpcRequest("1", methodName, parameters: new RpcParameters(rpcParameter));
            RpcResponse?response      = await invoker.InvokeRequestAsync(stringRequest);

            RpcResponse resultResponse = Assert.IsType <RpcResponse>(response);

            Assert.False(resultResponse.HasError);
            Assert.Equal(param, resultResponse.Result);
        }
        public void TestIntroMsg()
        {
            Queue <CommandBase> commandQueue = new Queue <CommandBase>();

            using (RpcBroker broker = GetConnectedBroker())
            {
                XusIntroMsgCommand testCommand = new XusIntroMsgCommand(broker);

                commandQueue.Enqueue(testCommand);

                RpcResponse response = ExecuteCommandQueue(commandQueue);

                // *** Check results ***
                Assert.AreEqual(RpcResponseStatus.Success, response.Status);
                Assert.IsFalse(string.IsNullOrWhiteSpace(response.Data));

                broker.Disconnect();
            }
        }
예제 #30
0
        private static void LoadNearbyVehicles([FromSource] Player citizen, string charJson)
        {
            var requestResponse = RpcResponse <Character> .Parse(charJson);

            Character character = requestResponse.Result;

            foreach (Vehicle vehicle in Server.Db.Vehicles.Where(v => v.Handle == null).ToArray())
            {
                if (!(Vector3.Distance(vehicle.Position, character.Position) < VehicleLoadDistance))
                {
                    continue;
                }

                Server.Log($"Spawning vehicle to {citizen.Name} via event: 'igi:{vehicle.VehicleType().Name}:spawn'");
                citizen.Event($"igi:{vehicle.VehicleType().Name}:spawn")
                .Attach(vehicle)
                .Trigger();
            }
        }
예제 #31
0
파일: Json.cs 프로젝트: Abitech/m3o
        public static RpcResponse<string> Deserialize(string s)
        {
            var response = new RpcResponse<string>();
            var match = new Regex("{\"result\":\"?(.*?)\"?,\"error\":\"?(.*?)\"?}").Match(s);
            if (match.Success)
            {
                if (match.Groups[1].Value == "null")
                {
                    response.result = null;
                }
                else
                {
                    response.result = match.Groups[1].Value;
                }

                if (match.Groups[2].Value == "null")
                {
                    response.error = null;
                }
                else
                {
                    try
                    {
                        response.error = ((ResponseCode)Int32.Parse(match.Groups[2].Value)).ToString();
                    }
                    catch (Exception e)
                    {
                        response.result = e.Message;
                        response.error = ResponseCode.InternalServerError.ToString();
                        return response;
                    }
                }
            }
            else
            {
                response.result = null;
                response.error = ResponseCode.CorruptedResponse.ToString();
            }

            return response;
        }
예제 #32
0
 public RpcResponseException(RpcResponse rpcResponse):base(rpcResponse.Error.Message)
 {
     this.RpcResponse = rpcResponse;
 }
예제 #33
0
		/// <summary>
		/// Call the incoming Rpc request method and gives the appropriate response
		/// </summary>
		/// <param name="request">Rpc request</param>
		/// <param name="route">Rpc route that applies to the current request</param>
		/// <param name="httpContext">The context of the current http request</param>
		/// <param name="jsonSerializerSettings">Json serialization settings that will be used in serialization and deserialization for rpc requests</param>
		/// <returns>An Rpc response for the request</returns>
		public async Task<RpcResponse> InvokeRequestAsync(RpcRequest request, RpcRoute route, HttpContext httpContext, JsonSerializerSettings jsonSerializerSettings = null)
		{
			try
			{
				if (request == null)
				{
					throw new ArgumentNullException(nameof(request));
				}
				if (route == null)
				{
					throw new ArgumentNullException(nameof(route));
				}
			}
			catch (ArgumentNullException ex) // Dont want to throw any exceptions when doing async requests
			{
				return this.GetUnknownExceptionReponse(request, ex);
			}

			this.logger?.LogDebug($"Invoking request with id '{request.Id}'");
			RpcResponse rpcResponse;
			try
			{
				if (!string.Equals(request.JsonRpcVersion, JsonRpcContants.JsonRpcVersion))
				{
					throw new RpcInvalidRequestException($"Request must be jsonrpc version '{JsonRpcContants.JsonRpcVersion}'");
				}

				object[] parameterList;
				RpcMethod rpcMethod = this.GetMatchingMethod(route, request, out parameterList, httpContext.RequestServices, jsonSerializerSettings);

				bool isAuthorized = await this.IsAuthorizedAsync(rpcMethod, httpContext);

				if (isAuthorized)
				{

					this.logger?.LogDebug($"Attempting to invoke method '{request.Method}'");
					object result = await rpcMethod.InvokeAsync(parameterList);
					this.logger?.LogDebug($"Finished invoking method '{request.Method}'");

					JsonSerializer jsonSerializer = JsonSerializer.Create(jsonSerializerSettings);
					if (result is IRpcMethodResult)
					{
						this.logger?.LogTrace($"Result is {nameof(IRpcMethodResult)}.");
						rpcResponse = ((IRpcMethodResult)result).ToRpcResponse(request.Id, obj => JToken.FromObject(obj, jsonSerializer));
					}
					else
					{
						this.logger?.LogTrace($"Result is plain object.");
						JToken resultJToken = result != null ? JToken.FromObject(result, jsonSerializer) : null;
						rpcResponse = new RpcResponse(request.Id, resultJToken);
					}
				}
				else
				{
					var authError = new RpcError(RpcErrorCode.InvalidRequest, "Unauthorized");
					rpcResponse = new RpcResponse(request.Id, authError);
				}
			}
			catch (RpcException ex)
			{
				this.logger?.LogException(ex, "An Rpc error occurred. Returning an Rpc error response");
				RpcError error = new RpcError(ex, this.serverConfig.Value.ShowServerExceptions);
				rpcResponse = new RpcResponse(request.Id, error);
			}
			catch (Exception ex)
			{
				rpcResponse = this.GetUnknownExceptionReponse(request, ex);
			}

			if (request.Id != null)
			{
				this.logger?.LogDebug($"Finished request with id '{request.Id}'");
				//Only give a response if there is an id
				return rpcResponse;
			}
			this.logger?.LogDebug($"Finished request with no id. Not returning a response");
			return null;
		}
예제 #34
0
		/// <summary>
		/// Converts an unknown caught exception into a Rpc response
		/// </summary>
		/// <param name="request">Current Rpc request</param>
		/// <param name="ex">Unknown exception</param>
		/// <returns>Rpc error response from the exception</returns>
		private RpcResponse GetUnknownExceptionReponse(RpcRequest request, Exception ex)
		{
			this.logger?.LogException(ex, "An unknown error occurred. Returning an Rpc error response");

			RpcUnknownException exception = new RpcUnknownException("An internal server error has occurred", ex);
			RpcError error = new RpcError(exception, this.serverConfig.Value.ShowServerExceptions);
			if (request?.Id == null)
			{
				return null;
			}
			RpcResponse rpcResponse = new RpcResponse(request.Id, error);
			return rpcResponse;
		}