public void SerializeError_Error_CanSerialize()
        {
            // Arrange
            var error = new Error(HttpStatusCode.InsufficientStorage)
            {
                Title  = "title",
                Detail = "detail"
            };

            var errorDocument = new ErrorDocument(error);

            string expectedJson = JsonConvert.SerializeObject(new
            {
                errors = new[]
                {
                    new
                    {
                        id     = error.Id,
                        status = "507",
                        title  = "title",
                        detail = "detail"
                    }
                }
            });

            ResponseSerializer <OneToManyPrincipal> serializer = GetResponseSerializer <OneToManyPrincipal>();

            // Act
            string result = serializer.Serialize(errorDocument);

            // Assert
            Assert.Equal(expectedJson, result);
        }
 public void Deserializes_response_type_abort()
 {
     string input = "Response=ABORT";
     var serializer = new ResponseSerializer();
     var result = serializer.Deserialize<TestClass>(input);
     result.Response.ShouldEqual(ResponseType.Abort);
 }
 public void Deserializes_response_type_malformed()
 {
     string input = "Response=MALFORMED";
     var serializer = new ResponseSerializer();
     var result = serializer.Deserialize<TestClass>(input);
     result.Response.ShouldEqual(ResponseType.Malformed);
 }
 public void Deserializes_response_type_error()
 {
     string input = "Response=ERROR";
     var serializer = new ResponseSerializer();
     var result = serializer.Deserialize<TestClass>(input);
     result.Response.ShouldEqual(ResponseType.Error);
 }
 public void Deserializes_response_type_invalid()
 {
     string input = "Response=INVALID";
     var serializer = new ResponseSerializer();
     var result = serializer.Deserialize<TestClass>(input);
     result.Response.ShouldEqual(ResponseType.Invalid);
 }
Esempio n. 6
0
 /// <summary>
 /// Creates a new instance of the TransactionRegistrar
 /// </summary>
 public TransactionRegistrar(Configuration configuration, IHttpRequestSender requestSender)
 {
     this.configuration = configuration;
     this.requestSender = requestSender;
     this.serializer = new HttpPostSerializer();
     this.deserializer = new ResponseSerializer();
 }
 public void Deserializes_response_type_authenticated()
 {
     string input = "Response=AUTHENTICATED";
     var serializer = new ResponseSerializer();
     var result = serializer.Deserialize<TestClass>(input);
     result.Response.ShouldEqual(ResponseType.Authenticated);
 }
        public void SerializeSingle_ResourceWithMeta_IncludesMetaInResult()
        {
            // Arrange
            var meta = new Dictionary <string, object>
            {
                ["test"] = "meta"
            };

            var resource = new OneToManyPrincipal
            {
                Id = 10
            };

            ResponseSerializer <OneToManyPrincipal> serializer = GetResponseSerializer <OneToManyPrincipal>(metaDict: meta);

            // Act
            string serialized = serializer.SerializeSingle(resource);

            // Assert
            const string expectedFormatted = @"{
                ""meta"":{ ""test"": ""meta"" },
                ""data"":{
                    ""type"":""oneToManyPrincipals"",
                    ""id"":""10"",
                    ""attributes"":{
                        ""attributeMember"":null
                    }
                }
            }";

            string expected = Regex.Replace(expectedFormatted, @"\s+", "");

            Assert.Equal(expected, serialized);
        }
        public void SerializeSingle_NullWithLinksAndMeta_StillShowsLinksAndMeta()
        {
            // Arrange
            var meta = new Dictionary <string, object>
            {
                ["test"] = "meta"
            };

            ResponseSerializer <OneToManyPrincipal> serializer = GetResponseSerializer <OneToManyPrincipal>(metaDict: meta, topLinks: DummyTopLevelLinks,
                                                                                                            relationshipLinks: DummyRelationshipLinks, resourceLinks: DummyResourceLinks);

            // Act
            string serialized = serializer.SerializeSingle(null);

            // Assert
            const string expectedFormatted = @"{
                ""meta"":{ ""test"": ""meta"" },
                ""links"":{
                    ""self"":""http://www.dummy.com/dummy-self-link"",
                    ""first"":""http://www.dummy.com/dummy-first-link"",
                    ""last"":""http://www.dummy.com/dummy-last-link"",
                    ""prev"":""http://www.dummy.com/dummy-prev-link"",
                    ""next"":""http://www.dummy.com/dummy-next-link""
                },
                ""data"": null
            }";

            string expected = Regex.Replace(expectedFormatted, @"\s+", "");

            Assert.Equal(expected, serialized);
        }
Esempio n. 10
0
        public static Task ResponseForHttpException(IHttpContext context, IHttpException httpException)
        {
            context.Response.StatusCode = httpException.StatusCode;
            object data = new { message = httpException.Message };

            return(ResponseSerializer.Json(context, data));
        }
Esempio n. 11
0
        public void Deserializes_response_type_invalid()
        {
            string input      = "Response=INVALID";
            var    serializer = new ResponseSerializer();
            var    result     = serializer.Deserialize <TestClass>(input);

            result.Response.ShouldEqual(ResponseType.Invalid);
        }
Esempio n. 12
0
        public void Deserializes_response_type_starting_with_ok()
        {
            string input      = "Response=OK 1 2 3";
            var    serializer = new ResponseSerializer();
            var    result     = serializer.Deserialize <TestClass>(input);

            result.Response.ShouldEqual(ResponseType.Ok);
        }
Esempio n. 13
0
        public void Deserializes_response_with_equals_in_value()
        {
            string input      = "Name=foo=bar\r\nId=0";
            var    serializer = new ResponseSerializer();
            var    result     = serializer.Deserialize <TestClass>(input);

            result.Name.ShouldEqual("foo=bar");
        }
Esempio n. 14
0
        public void Deserializes_response_type_unknown()
        {
            string input      = "Response=UNKNOWN";
            var    serializer = new ResponseSerializer();
            var    result     = serializer.Deserialize <TestClass>(input);

            result.Response.ShouldEqual(ResponseType.Unknown);
        }
Esempio n. 15
0
        public void Deserializes_response_type_notauthed()
        {
            string input      = "Response=NOTAUTHED";
            var    serializer = new ResponseSerializer();
            var    result     = serializer.Deserialize <TestClass>(input);

            result.Response.ShouldEqual(ResponseType.NotAuthed);
        }
Esempio n. 16
0
        public void Deserializes_response_type_abort()
        {
            string input      = "Response=ABORT";
            var    serializer = new ResponseSerializer();
            var    result     = serializer.Deserialize <TestClass>(input);

            result.Response.ShouldEqual(ResponseType.Abort);
        }
Esempio n. 17
0
        public void Deserializes_response_type_rejected()
        {
            string input      = "Response=REJECTED";
            var    serializer = new ResponseSerializer();
            var    result     = serializer.Deserialize <TestClass>(input);

            result.Response.ShouldEqual(ResponseType.Rejected);
        }
		public void Deserializes_object() {
			string input = "Name=Foo\r\nId=1";
			var serializer = new ResponseSerializer();

			var result = serializer.Deserialize<TestClass>(input);
			result.Name.ShouldEqual("Foo");
			result.Id.ShouldEqual(1);
		}
Esempio n. 19
0
        public void Deserializes_response_type_authenticated()
        {
            string input      = "Response=AUTHENTICATED";
            var    serializer = new ResponseSerializer();
            var    result     = serializer.Deserialize <TestClass>(input);

            result.Response.ShouldEqual(ResponseType.Authenticated);
        }
Esempio n. 20
0
        public void Deserializes_response_type_error()
        {
            string input      = "Response=ERROR";
            var    serializer = new ResponseSerializer();
            var    result     = serializer.Deserialize <TestClass>(input);

            result.Response.ShouldEqual(ResponseType.Error);
        }
Esempio n. 21
0
        public void Deserializes_response_type_malformed()
        {
            string input      = "Response=MALFORMED";
            var    serializer = new ResponseSerializer();
            var    result     = serializer.Deserialize <TestClass>(input);

            result.Response.ShouldEqual(ResponseType.Malformed);
        }
Esempio n. 22
0
        public void Deserializes_object()
        {
            string input      = "Name=Foo\r\nId=1";
            var    serializer = new ResponseSerializer();

            var result = serializer.Deserialize <TestClass>(input);

            result.Name.ShouldEqual("Foo");
            result.Id.ShouldEqual(1);
        }
Esempio n. 23
0
        public void ShouldSerializeNullBody()
        {
            ResponseSerializer serializer;
            Response           response;

            serializer = new ResponseSerializer();
            response   = serializer.Serialize(null);
            Assert.AreEqual(ResponseCodes.NoContent, response.ResponseCode);
            Assert.AreEqual("", response.Body);
        }
Esempio n. 24
0
        private async Task <TResp> GetResponse <TResp>(HttpResponseMessage response)
        {
            if (!response.IsSuccessStatusCode)
            {
                await HandleError(response);
            }

            var resp = await ResponseSerializer.DeserializeAsync <TResp>(response.Content);

            return(resp);
        }
Esempio n. 25
0
        public void ShouldSerializeAtomBoolean()
        {
            "ResponseSerializer should handle bollean atom values".x(() =>
            {
                var response = new List <PathValue>
                {
                    new PathValue(FalcorPath.Create("todos", 1, "done"), new Atom(true))
                };
                var serialize  = new ResponseSerializer().Serialize(FalcorResponse.From(response.AsReadOnly()));
                dynamic result = JsonConvert.DeserializeObject(serialize);

                Assert.Equal(result["jsonGraph"]["todos"]["1"]["done"]["value"].Value, true);
            });
        }
        public void SerializeList_EmptyList_CanSerialize()
        {
            // Arrange
            ResponseSerializer <TestResource> serializer = GetResponseSerializer <TestResource>();

            // Act
            string serialized = serializer.SerializeMany(new List <TestResource>());

            // Assert
            const string expectedFormatted = @"{ ""data"": [] }";
            string       expected          = Regex.Replace(expectedFormatted, @"\s+", "");

            Assert.Equal(expected, serialized);
        }
        public void SerializeSingle_Null_CanSerialize()
        {
            // Arrange
            ResponseSerializer <TestResource> serializer = GetResponseSerializer <TestResource>();

            // Act
            string serialized = serializer.SerializeSingle(null);

            // Assert
            const string expectedFormatted = @"{ ""data"": null }";
            string       expected          = Regex.Replace(expectedFormatted, @"\s+", "");

            Assert.Equal(expected, serialized);
        }
        public void SerializeSingle_ResourceWithLinksEnabled_CanSerialize()
        {
            // Arrange
            var resource = new OneToManyPrincipal
            {
                Id = 10
            };

            ResponseSerializer <OneToManyPrincipal> serializer = GetResponseSerializer <OneToManyPrincipal>(topLinks: DummyTopLevelLinks,
                                                                                                            relationshipLinks: DummyRelationshipLinks, resourceLinks: DummyResourceLinks);

            // Act
            string serialized = serializer.SerializeSingle(resource);

            // Assert
            const string expectedFormatted = @"{
               ""links"":{
                  ""self"":""http://www.dummy.com/dummy-self-link"",
                  ""first"":""http://www.dummy.com/dummy-first-link"",
                  ""last"":""http://www.dummy.com/dummy-last-link"",
                  ""prev"":""http://www.dummy.com/dummy-prev-link"",
                  ""next"":""http://www.dummy.com/dummy-next-link""
               },
               ""data"":{
                  ""type"":""oneToManyPrincipals"",
                  ""id"":""10"",
                  ""attributes"":{
                     ""attributeMember"":null
                  },
                  ""relationships"":{
                     ""dependents"":{
                        ""links"":{
                           ""self"":""http://www.dummy.com/dummy-relationship-self-link"",
                           ""related"":""http://www.dummy.com/dummy-relationship-related-link""
                        }
                     }
                  },
                  ""links"":{
                     ""self"":""http://www.dummy.com/dummy-resource-self-link""
                  }
               }
            }";

            string expected = Regex.Replace(expectedFormatted, @"\s+", "");

            Assert.Equal(expected, serialized);
        }
Esempio n. 29
0
        public TransactionRegistrationResponse Register(CartModel cartModel)
        {
            string sagePayUrl = _sagePaySettings.RegistrationUrl;

            var registration = _transactionRegistrationBuilder.BuildRegistration(cartModel);

            var serializer = new HttpPostSerializer();
            var postData = serializer.Serialize(registration);

            var response = _httpRequestSender.SendRequest(sagePayUrl, postData);

            var deserializer = new ResponseSerializer();
            var registrationResponse = deserializer.Deserialize<TransactionRegistrationResponse>(response);
            if (registrationResponse.StatusDetail.StartsWith("4042"))
                registrationResponse.Status = ResponseType.Invalid;
            registrationResponse.VendorTxCode = registration.VendorTxCode;
            registrationResponse.CartTotal = cartModel.TotalToPay;
            return registrationResponse;
        }
Esempio n. 30
0
		public RefundResponse Send(string vendorTxCode, string refundReason, decimal amount, string relatedVpsTxId,
		                           string relatedVendorTxCode, string relatedSecurityKey, string relatedAuthNo) {
			var registration = new RefundRegistration(configuration.VendorName,
			                                          vendorTxCode,
			                                          amount,
			                                          refundReason,
			                                          relatedVpsTxId,
			                                          relatedVendorTxCode,
			                                          relatedSecurityKey,
			                                          relatedAuthNo);

			string sagePayUrl = configuration.RefundUrl;

			var serializer = new HttpPostSerializer();
			var postData = serializer.Serialize(registration);
			var response = requestSender.SendRequest(sagePayUrl, postData);
			var deserializer = new ResponseSerializer();
			return deserializer.Deserialize<RefundResponse>(response);
		}
Esempio n. 31
0
        public TransactionRegistrationResponse Send(RequestContext context, string vendorTxCode, ShoppingBasket basket,
            Address billingAddress, Address deliveryAddress, string customerEmail)
        {
            string sagePayUrl = configuration.RegistrationUrl;
            string notificationUrl = urlResolver.BuildNotificationUrl(context);

            var registration = new TransactionRegistration(
                vendorTxCode, basket, notificationUrl,
                billingAddress, deliveryAddress, customerEmail,
                configuration.VendorName);

            var serializer = new HttpPostSerializer();
            var postData = serializer.Serialize(registration);

            var response = requestSender.SendRequest(sagePayUrl, postData);

            var deserializer = new ResponseSerializer();
            return deserializer.Deserialize<TransactionRegistrationResponse>(response);
        }
Esempio n. 32
0
		public TransactionRegistrationResponse Send(RequestContext context, string vendorTxCode, ShoppingBasket basket,
								Address billingAddress, Address deliveryAddress, string customerEmail, PaymentFormProfile paymentFormProfile = PaymentFormProfile.Normal, string currencyCode="GBP",
								MerchantAccountType accountType=MerchantAccountType.Ecommerce, TxType txType=TxType.Payment) {
			string sagePayUrl = configuration.RegistrationUrl;
			string notificationUrl = urlResolver.BuildNotificationUrl(context);

			var registration = new TransactionRegistration(
				vendorTxCode, basket, notificationUrl,
				billingAddress, deliveryAddress, customerEmail,
				configuration.VendorName,
				paymentFormProfile, currencyCode, accountType, txType);

			var serializer = new HttpPostSerializer();
			var postData = serializer.Serialize(registration);

			var response = requestSender.SendRequest(sagePayUrl, postData);

			var deserializer = new ResponseSerializer();
			return deserializer.Deserialize<TransactionRegistrationResponse>(response);
		}
Esempio n. 33
0
        public TransactionRegistrationResponse Send(RequestContext context, string vendorTxCode, ShoppingBasket basket,
                                                    Address billingAddress, Address deliveryAddress, string customerEmail)
        {
            string sagePayUrl      = configuration.RegistrationUrl;
            string notificationUrl = urlResolver.BuildNotificationUrl(context);

            var registration = new TransactionRegistration(
                vendorTxCode, basket, notificationUrl,
                billingAddress, deliveryAddress, customerEmail,
                configuration.VendorName);

            var serializer = new HttpPostSerializer();
            var postData   = serializer.Serialize(registration);

            var response = requestSender.SendRequest(sagePayUrl, postData);

            var deserializer = new ResponseSerializer();

            return(deserializer.Deserialize <TransactionRegistrationResponse>(response));
        }
Esempio n. 34
0
        private async Task HandleError(HttpResponseMessage response)
        {
            var res = await ResponseSerializer.DeserializeAsync <ErrorResponse>(response.Content);

            if (res == null)
            {
                throw new ServerException(
                          response.ReasonPhrase,
                          (int)response.StatusCode,
                          -1,
                          ""
                          );
            }
            else if ((int)response.StatusCode == 500)
            {
                throw new ServerException(
                          response.ReasonPhrase,
                          (int)response.StatusCode,
                          res.code,
                          res.name
                          );
            }
            else if (res.code == 102)
            {
                throw new TokenExpireException(
                          res.message,
                          (int)response.StatusCode,
                          res.code,
                          res.name
                          );
            }
            else
            {
                throw new HttpException(
                          res.message,
                          (int)response.StatusCode,
                          res.code,
                          res.name
                          );
            }
        }
Esempio n. 35
0
        public RefundResponse Send(string vendorTxCode, string refundReason, decimal amount, string relatedVpsTxId,
                                   string relatedVendorTxCode, string relatedSecurityKey, string relatedAuthNo)
        {
            var registration = new RefundRegistration(configuration.VendorName,
                                                      vendorTxCode,
                                                      amount,
                                                      refundReason,
                                                      relatedVpsTxId,
                                                      relatedVendorTxCode,
                                                      relatedSecurityKey,
                                                      relatedAuthNo);

            string sagePayUrl = configuration.RefundUrl;

            var serializer   = new HttpPostSerializer();
            var postData     = serializer.Serialize(registration);
            var response     = requestSender.SendRequest(sagePayUrl, postData);
            var deserializer = new ResponseSerializer();

            return(deserializer.Deserialize <RefundResponse>(response));
        }
Esempio n. 36
0
        public TransactionRegistrationResponse Send(RequestContext context, string vendorTxCode, ShoppingBasket basket,
                                                    Address billingAddress, Address deliveryAddress, string customerEmail, PaymentFormProfile paymentFormProfile = PaymentFormProfile.Normal, string currencyCode = "GBP",
                                                    MerchantAccountType accountType = MerchantAccountType.Ecommerce, TxType txType = TxType.Payment)
        {
            string sagePayUrl      = configuration.RegistrationUrl;
            string notificationUrl = urlResolver.BuildNotificationUrl(context);

            var registration = new TransactionRegistration(
                vendorTxCode, basket, notificationUrl,
                billingAddress, deliveryAddress, customerEmail,
                configuration.VendorName,
                paymentFormProfile, currencyCode, accountType, txType);

            var serializer = new HttpPostSerializer();
            var postData   = serializer.Serialize(registration);

            var response = requestSender.SendRequest(sagePayUrl, postData);

            var deserializer = new ResponseSerializer();

            return(deserializer.Deserialize <TransactionRegistrationResponse>(response));
        }
Esempio n. 37
0
 public static void SendResult(HttpListenerResponse response, IMethodResult result)
 {
     try
     {
         var outputStream = response.OutputStream;
         response.StatusCode = (int)result.StatusCode();
         var serializeResult = ResponseSerializer.GetData(result);
         if (serializeResult.IsOk)
         {
             outputStream.Write(serializeResult.Data);
             outputStream.Close();
         }
         else
         {
             outputStream.Close();
         }
     }
     catch (Exception e)
     {
         throw new Exception($"ResultHelper SendResult Error: {e.Message}");
     }
 }
        public void SerializeMany_ResourceWithDefaultTargetFields_CanSerialize()
        {
            // Arrange
            var resource = new TestResource
            {
                Id               = 1,
                StringField      = "value",
                NullableIntField = 123
            };

            ResponseSerializer <TestResource> serializer = GetResponseSerializer <TestResource>();

            // Act
            string serialized = serializer.SerializeMany(resource.AsArray());

            // Assert
            const string expectedFormatted = @"{
               ""data"":[{
                  ""type"":""testResource"",
                  ""id"":""1"",
                  ""attributes"":{
                     ""stringField"":""value"",
                     ""dateTimeField"":""0001-01-01T00:00:00"",
                     ""nullableDateTimeField"":null,
                     ""intField"":0,
                     ""nullableIntField"":123,
                     ""guidField"":""00000000-0000-0000-0000-000000000000"",
                     ""complexField"":null
                  }
               }]
            }";

            string expected = Regex.Replace(expectedFormatted, @"\s+", "");

            Assert.Equal(expected, serialized);
        }
		public void Deserializes_response_type_unknown() {
			string input = "Response=UNKNOWN";
			var serializer = new ResponseSerializer();
			var result = serializer.Deserialize<TestClass>(input);
			result.Response.ShouldEqual(ResponseType.Unknown);
		}
Esempio n. 40
0
 public static Task DataResponseForHttpException(IHttpContext context, IHttpException httpException)
 {
     context.Response.StatusCode = (int)System.Net.HttpStatusCode.OK;
     return(ResponseSerializer.Json(context, httpException.Message));
 }
Esempio n. 41
0
        private void daemonPipe_OnReceiveLine(string line)
        {
            if (line.Substring(0, 10) == "<Response ")
            {
                VoiceResponse rsp = null;
                try
                {
                    rsp = (VoiceResponse)ResponseSerializer.Deserialize(new StringReader(line));
                }
                catch (Exception e)
                {
                    Logger.Log("Failed to deserialize voice daemon response", Helpers.LogLevel.Error, e);
                    return;
                }

                switch (rsp.Action)
                {
                case "Connector.Create.1":
                    if (OnConnectorCreateResponse != null)
                    {
                        OnConnectorCreateResponse(int.Parse(rsp.ReturnCode), rsp.Results.VersionID, int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.ConnectorHandle, rsp.InputXml.Request);
                    }
                    break;

                case "Connector.InitiateShutdown.1":
                    if (OnConnectorInitiateShutdownResponse != null)
                    {
                        OnConnectorInitiateShutdownResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.InputXml.Request);
                    }
                    break;

                case "Connector.MuteLocalMic.1":
                    if (OnConnectorMuteLocalMicResponse != null)
                    {
                        OnConnectorMuteLocalMicResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.InputXml.Request);
                    }
                    break;

                case "Connector.MuteLocalSpeaker.1":
                    if (OnConnectorMuteLocalSpeakerResponse != null)
                    {
                        OnConnectorMuteLocalSpeakerResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.InputXml.Request);
                    }
                    break;

                case "Connector.SetLocalMicVolume.1":
                    if (OnConnectorSetLocalMicVolumeResponse != null)
                    {
                        OnConnectorSetLocalMicVolumeResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.InputXml.Request);
                    }
                    break;

                case "Connector.SetLocalSpeakerVolume.1":
                    if (OnConnectorSetLocalSpeakerVolumeResponse != null)
                    {
                        OnConnectorSetLocalSpeakerVolumeResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.InputXml.Request);
                    }
                    break;

                case "Aux.GetCaptureDevices.1":
                    if (OnAuxGetCaptureDevicesResponse != null)
                    {
                        List <string> CaptureDevices = new List <string>();
                        foreach (CaptureDevice device in rsp.Results.CaptureDevices)
                        {
                            CaptureDevices.Add(device.Device);
                        }

                        OnAuxGetCaptureDevicesResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, CaptureDevices, rsp.Results.CurrentCaptureDevice.Device, rsp.InputXml.Request);
                    }
                    break;

                case "Aux.GetRenderDevices.1":
                    if (OnAuxGetRenderDevicesResponse != null)
                    {
                        List <string> RenderDevices = new List <string>();
                        foreach (RenderDevice device in rsp.Results.RenderDevices)
                        {
                            RenderDevices.Add(device.Device);
                        }

                        OnAuxGetRenderDevicesResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, RenderDevices, rsp.Results.CurrentRenderDevice.Device, rsp.InputXml.Request);
                    }
                    break;

                case "Aux.SetRenderDevice.1":
                    if (OnAuxSetRenderDeviceResponse != null)
                    {
                        OnAuxSetRenderDeviceResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.InputXml.Request);
                    }
                    break;

                case "Aux.SetCaptureDevice.1":
                    if (OnAuxSetCaptureDeviceResponse != null)
                    {
                        OnAuxSetCaptureDeviceResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.InputXml.Request);
                    }
                    break;

                case "Session.RenderAudioStart.1":
                    if (OnSessionRenderAudioStartResponse != null)
                    {
                        OnSessionRenderAudioStartResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.InputXml.Request);
                    }
                    break;

                case "Session.RenderAudioStop.1":
                    if (OnSessionRenderAudioStopResponse != null)
                    {
                        OnSessionRenderAudioStopResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.InputXml.Request);
                    }
                    break;

                case "Aux.CaptureAudioStart.1":
                    if (OnAuxCaptureAudioStartResponse != null)
                    {
                        OnAuxCaptureAudioStartResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.InputXml.Request);
                    }
                    break;

                case "Aux.CaptureAudioStop.1":
                    if (OnAuxCaptureAudioStopResponse != null)
                    {
                        OnAuxCaptureAudioStopResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.InputXml.Request);
                    }
                    break;

                case "Aux.SetMicLevel.1":
                    if (OnAuxSetMicLevelResponse != null)
                    {
                        OnAuxSetMicLevelResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.InputXml.Request);
                    }
                    break;

                case "Aux.SetSpeakerLevel.1":
                    if (OnAuxSetSpeakerLevelResponse != null)
                    {
                        OnAuxSetSpeakerLevelResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.InputXml.Request);
                    }
                    break;

                case "Account.Login.1":
                    if (OnAccountLoginResponse != null)
                    {
                        OnAccountLoginResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.AccountHandle, rsp.InputXml.Request);
                    }
                    break;

                case "Account.Logout.1":
                    if (OnAccountLogoutResponse != null)
                    {
                        OnAccountLogoutResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.InputXml.Request);
                    }
                    break;

                case "Session.Create.1":
                    if (OnSessionCreateResponse != null)
                    {
                        OnSessionCreateResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.Results.SessionHandle, rsp.InputXml.Request);
                    }
                    break;

                case "Session.Connect.1":
                    if (OnSessionConnectResponse != null)
                    {
                        OnSessionConnectResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.InputXml.Request);
                    }
                    break;

                case "Session.Terminate.1":
                    if (OnSessionTerminateResponse != null)
                    {
                        OnSessionTerminateResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.InputXml.Request);
                    }
                    break;

                case "Session.SetParticipantVolumeForMe.1":
                    if (OnSessionSetParticipantVolumeForMeResponse != null)
                    {
                        OnSessionSetParticipantVolumeForMeResponse(int.Parse(rsp.ReturnCode), int.Parse(rsp.Results.StatusCode), rsp.Results.StatusString, rsp.InputXml.Request);
                    }
                    break;

                default:
                    Logger.Log("Unimplemented response from the voice daemon: " + line, Helpers.LogLevel.Error);
                    break;
                }
            }
            else if (line.Substring(0, 7) == "<Event ")
            {
                VoiceEvent evt = null;
                try
                {
                    evt = (VoiceEvent)EventSerializer.Deserialize(new StringReader(line));
                }
                catch (Exception e)
                {
                    Logger.Log("Failed to deserialize voice daemon event", Helpers.LogLevel.Error, e);
                    return;
                }

                switch (evt.Type)
                {
                case "LoginStateChangeEvent":
                    if (OnAccountLoginStateChangeEvent != null)
                    {
                        OnAccountLoginStateChangeEvent(evt.AccountHandle, int.Parse(evt.StatusCode), evt.StatusString, (LoginState)int.Parse(evt.State));
                    }
                    break;

                case "SessionNewEvent":
                    if (OnSessionNewEvent != null)
                    {
                        OnSessionNewEvent(evt.AccountHandle, evt.SessionHandle, evt.URI, bool.Parse(evt.IsChannel), evt.Name, evt.AudioMedia);
                    }
                    break;

                case "SessionStateChangeEvent":
                    if (OnSessionStateChangeEvent != null)
                    {
                        OnSessionStateChangeEvent(evt.SessionHandle, int.Parse(evt.StatusCode), evt.StatusString, (SessionState)int.Parse(evt.State), evt.URI, bool.Parse(evt.IsChannel), evt.ChannelName);
                    }
                    break;

                case "ParticipantStateChangeEvent":
                    if (OnSessionParticipantStateChangeEvent != null)
                    {
                        OnSessionParticipantStateChangeEvent(evt.SessionHandle, int.Parse(evt.StatusCode), evt.StatusString, (ParticipantState)int.Parse(evt.State), evt.ParticipantURI, evt.AccountName, evt.DisplayName, (ParticipantType)int.Parse(evt.ParticipantType));
                    }
                    break;

                case "ParticipantPropertiesEvent":
                    if (OnSessionParticipantPropertiesEvent != null)
                    {
                        OnSessionParticipantPropertiesEvent(evt.SessionHandle, evt.ParticipantURI, bool.Parse(evt.IsLocallyMuted), bool.Parse(evt.IsModeratorMuted), bool.Parse(evt.IsSpeaking), int.Parse(evt.Volume), float.Parse(evt.Energy));
                    }
                    break;

                case "AuxAudioPropertiesEvent":
                    if (OnAuxAudioPropertiesEvent != null)
                    {
                        OnAuxAudioPropertiesEvent(bool.Parse(evt.MicIsActive), float.Parse(evt.MicEnergy), float.Parse(evt.MicVolume), float.Parse(evt.SpeakerVolume));
                    }
                    break;

                case "SessionMediaEvent":
                    if (OnSessionMediaEvent != null)
                    {
                        OnSessionMediaEvent(evt.SessionHandle, bool.Parse(evt.HasText), bool.Parse(evt.HasAudio), bool.Parse(evt.HasVideo), bool.Parse(evt.Terminated));
                    }
                    break;

                default:
                    Logger.Log("Unimplemented event from the voice daemon: " + line, Helpers.LogLevel.Error);
                    break;
                }
            }
            else
            {
                Logger.Log("Unrecognized data from the voice daemon: " + line, Helpers.LogLevel.Error);
            }
        }
		public void Deserializes_response_type_starting_with_ok() {
			string input = "Response=OK 1 2 3";
			var serializer = new ResponseSerializer();
			var result = serializer.Deserialize<TestClass>(input);
			result.Response.ShouldEqual(ResponseType.Ok);
		}
		public void Deserializes_response_type_rejected() {
			string input = "Response=REJECTED";
			var serializer = new ResponseSerializer();
			var result = serializer.Deserialize<TestClass>(input);
			result.Response.ShouldEqual(ResponseType.Rejected);
		}
		public void Deserializes_response_type_notauthed() {
			string input = "Response=NOTAUTHED";
			var serializer = new ResponseSerializer();
			var result = serializer.Deserialize<TestClass>(input);
			result.Response.ShouldEqual(ResponseType.NotAuthed);
		}
Esempio n. 45
0
        private void daemonPipe_OnReceiveLine(string line)
        {
#if DEBUG
            Logger.Log(line, Helpers.LogLevel.Debug);
#endif

            if (line.Substring(0, 10) == "<Response ")
            {
                VoiceResponse rsp = null;
                try
                {
                    rsp = (VoiceResponse)ResponseSerializer.Deserialize(new StringReader(line));
                }
                catch (Exception e)
                {
                    Logger.Log("Failed to deserialize voice daemon response", Helpers.LogLevel.Error, e);
                    return;
                }

                ResponseType genericResponse = ResponseType.None;

                switch (rsp.Action)
                {
                // These first responses carry useful information beyond simple status,
                // so they each have a specific Event.
                case "Connector.Create.1":
                    if (OnConnectorCreateResponse != null)
                    {
                        OnConnectorCreateResponse(
                            rsp.InputXml.Request,
                            new VoiceConnectorEventArgs(
                                int.Parse(rsp.ReturnCode),
                                int.Parse(rsp.Results.StatusCode),
                                rsp.Results.StatusString,
                                rsp.Results.VersionID,
                                rsp.Results.ConnectorHandle));
                    }
                    break;

                case "Aux.GetCaptureDevices.1":
                    inputDevices = new List <string>();

                    if (rsp.Results.CaptureDevices.Count == 0 || rsp.Results.CurrentCaptureDevice == null)
                    {
                        break;
                    }

                    foreach (CaptureDevice device in rsp.Results.CaptureDevices)
                    {
                        inputDevices.Add(device.Device);
                    }
                    currentCaptureDevice = rsp.Results.CurrentCaptureDevice.Device;

                    if (OnAuxGetCaptureDevicesResponse != null && rsp.Results.CaptureDevices.Count > 0)
                    {
                        OnAuxGetCaptureDevicesResponse(
                            rsp.InputXml.Request,
                            new VoiceDevicesEventArgs(
                                ResponseType.GetCaptureDevices,
                                int.Parse(rsp.ReturnCode),
                                int.Parse(rsp.Results.StatusCode),
                                rsp.Results.StatusString,
                                rsp.Results.CurrentCaptureDevice.Device,
                                inputDevices));
                    }
                    break;

                case "Aux.GetRenderDevices.1":
                    outputDevices = new List <string>();

                    if (rsp.Results.RenderDevices.Count == 0 || rsp.Results.CurrentRenderDevice == null)
                    {
                        break;
                    }

                    foreach (RenderDevice device in rsp.Results.RenderDevices)
                    {
                        outputDevices.Add(device.Device);
                    }


                    currentPlaybackDevice = rsp.Results.CurrentRenderDevice.Device;

                    if (OnAuxGetRenderDevicesResponse != null)
                    {
                        OnAuxGetRenderDevicesResponse(
                            rsp.InputXml.Request,
                            new VoiceDevicesEventArgs(
                                ResponseType.GetCaptureDevices,
                                int.Parse(rsp.ReturnCode),
                                int.Parse(rsp.Results.StatusCode),
                                rsp.Results.StatusString,
                                rsp.Results.CurrentRenderDevice.Device,
                                outputDevices));
                    }
                    break;

                case "Account.Login.1":
                    if (OnAccountLoginResponse != null)
                    {
                        OnAccountLoginResponse(rsp.InputXml.Request,
                                               new VoiceAccountEventArgs(
                                                   int.Parse(rsp.ReturnCode),
                                                   int.Parse(rsp.Results.StatusCode),
                                                   rsp.Results.StatusString,
                                                   rsp.Results.AccountHandle));
                    }
                    break;

                case "Session.Create.1":
                    if (OnSessionCreateResponse != null)
                    {
                        OnSessionCreateResponse(
                            rsp.InputXml.Request,
                            new VoiceSessionEventArgs(
                                int.Parse(rsp.ReturnCode),
                                int.Parse(rsp.Results.StatusCode),
                                rsp.Results.StatusString,
                                rsp.Results.SessionHandle));
                    }
                    break;

                // All the remaining responses below this point just report status,
                // so they all share the same Event.  Most are useful only for
                // detecting coding errors.
                case "Connector.InitiateShutdown.1":
                    genericResponse = ResponseType.ConnectorInitiateShutdown;
                    break;

                case "Aux.SetRenderDevice.1":
                    genericResponse = ResponseType.SetRenderDevice;
                    break;

                case "Connector.MuteLocalMic.1":
                    genericResponse = ResponseType.MuteLocalMic;
                    break;

                case "Connector.MuteLocalSpeaker.1":
                    genericResponse = ResponseType.MuteLocalSpeaker;
                    break;

                case "Connector.SetLocalMicVolume.1":
                    genericResponse = ResponseType.SetLocalMicVolume;
                    break;

                case "Connector.SetLocalSpeakerVolume.1":
                    genericResponse = ResponseType.SetLocalSpeakerVolume;
                    break;

                case "Aux.SetCaptureDevice.1":
                    genericResponse = ResponseType.SetCaptureDevice;
                    break;

                case "Session.RenderAudioStart.1":
                    genericResponse = ResponseType.RenderAudioStart;
                    break;

                case "Session.RenderAudioStop.1":
                    genericResponse = ResponseType.RenderAudioStop;
                    break;

                case "Aux.CaptureAudioStart.1":
                    genericResponse = ResponseType.CaptureAudioStart;
                    break;

                case "Aux.CaptureAudioStop.1":
                    genericResponse = ResponseType.CaptureAudioStop;
                    break;

                case "Aux.SetMicLevel.1":
                    genericResponse = ResponseType.SetMicLevel;
                    break;

                case "Aux.SetSpeakerLevel.1":
                    genericResponse = ResponseType.SetSpeakerLevel;
                    break;

                case "Account.Logout.1":
                    genericResponse = ResponseType.AccountLogout;
                    break;

                case "Session.Connect.1":
                    genericResponse = ResponseType.SessionConnect;
                    break;

                case "Session.Terminate.1":
                    genericResponse = ResponseType.SessionTerminate;
                    break;

                case "Session.SetParticipantVolumeForMe.1":
                    genericResponse = ResponseType.SetParticipantVolumeForMe;
                    break;

                case "Session.SetParticipantMuteForMe.1":
                    genericResponse = ResponseType.SetParticipantMuteForMe;
                    break;

                case "Session.Set3DPosition.1":
                    genericResponse = ResponseType.Set3DPosition;
                    break;

                default:
                    Logger.Log("Unimplemented response from the voice daemon: " + line, Helpers.LogLevel.Error);
                    break;
                }

                // Send the Response Event for all the simple cases.
                if (genericResponse != ResponseType.None && OnVoiceResponse != null)
                {
                    OnVoiceResponse(rsp.InputXml.Request,
                                    new VoiceResponseEventArgs(
                                        genericResponse,
                                        int.Parse(rsp.ReturnCode),
                                        int.Parse(rsp.Results.StatusCode),
                                        rsp.Results.StatusString));
                }
            }
            else if (line.Substring(0, 7) == "<Event ")
            {
                VoiceEvent evt = null;
                try
                {
                    evt = (VoiceEvent)EventSerializer.Deserialize(new StringReader(line));
                }
                catch (Exception e)
                {
                    Logger.Log("Failed to deserialize voice daemon event", Helpers.LogLevel.Error, e);
                    return;
                }

                switch (evt.Type)
                {
                case "LoginStateChangeEvent":
                case "AccountLoginStateChangeEvent":
                    if (OnAccountLoginStateChangeEvent != null)
                    {
                        OnAccountLoginStateChangeEvent(this,
                                                       new AccountLoginStateChangeEventArgs(
                                                           evt.AccountHandle,
                                                           int.Parse(evt.StatusCode),
                                                           evt.StatusString,
                                                           (LoginState)int.Parse(evt.State)));
                    }
                    break;

                case "SessionNewEvent":
                    if (OnSessionNewEvent != null)
                    {
                        OnSessionNewEvent(this,
                                          new NewSessionEventArgs(
                                              evt.AccountHandle,
                                              evt.SessionHandle,
                                              evt.URI,
                                              bool.Parse(evt.IsChannel),
                                              evt.Name,
                                              evt.AudioMedia));
                    }
                    break;

                case "SessionStateChangeEvent":
                    if (OnSessionStateChangeEvent != null)
                    {
                        OnSessionStateChangeEvent(this,
                                                  new SessionStateChangeEventArgs(
                                                      evt.SessionHandle,
                                                      int.Parse(evt.StatusCode),
                                                      evt.StatusString,
                                                      (SessionState)int.Parse(evt.State),
                                                      evt.URI,
                                                      bool.Parse(evt.IsChannel),
                                                      evt.ChannelName));
                    }
                    break;

                case "ParticipantAddedEvent":
                    Logger.Log("Add participant " + evt.ParticipantUri, Helpers.LogLevel.Debug);
                    if (OnSessionParticipantAddedEvent != null)
                    {
                        OnSessionParticipantAddedEvent(this,
                                                       new ParticipantAddedEventArgs(
                                                           evt.SessionGroupHandle,
                                                           evt.SessionHandle,
                                                           evt.ParticipantUri,
                                                           evt.AccountName,
                                                           evt.DisplayName,
                                                           (ParticipantType)int.Parse(evt.ParticipantType),
                                                           evt.Application));
                    }
                    break;

                case "ParticipantRemovedEvent":
                    if (OnSessionParticipantRemovedEvent != null)
                    {
                        OnSessionParticipantRemovedEvent(this,
                                                         new ParticipantRemovedEventArgs(
                                                             evt.SessionGroupHandle,
                                                             evt.SessionHandle,
                                                             evt.ParticipantUri,
                                                             evt.AccountName,
                                                             evt.Reason));
                    }
                    break;

                case "ParticipantStateChangeEvent":
                    // Useful in person-to-person calls
                    if (OnSessionParticipantStateChangeEvent != null)
                    {
                        OnSessionParticipantStateChangeEvent(this,
                                                             new ParticipantStateChangeEventArgs(
                                                                 evt.SessionHandle,
                                                                 int.Parse(evt.StatusCode),
                                                                 evt.StatusString,
                                                                 (ParticipantState)int.Parse(evt.State), // Ringing, Connected, etc
                                                                 evt.ParticipantUri,
                                                                 evt.AccountName,
                                                                 evt.DisplayName,
                                                                 (ParticipantType)int.Parse(evt.ParticipantType)));
                    }
                    break;

                case "ParticipantPropertiesEvent":
                    if (OnSessionParticipantPropertiesEvent != null)
                    {
                        OnSessionParticipantPropertiesEvent(this,
                                                            new ParticipantPropertiesEventArgs(
                                                                evt.SessionHandle,
                                                                evt.ParticipantUri,
                                                                bool.Parse(evt.IsLocallyMuted),
                                                                bool.Parse(evt.IsModeratorMuted),
                                                                bool.Parse(evt.IsSpeaking),
                                                                int.Parse(evt.Volume),
                                                                float.Parse(evt.Energy)));
                    }
                    break;

                case "ParticipantUpdatedEvent":
                    if (OnSessionParticipantUpdatedEvent != null)
                    {
                        OnSessionParticipantUpdatedEvent(this,
                                                         new ParticipantUpdatedEventArgs(
                                                             evt.SessionHandle,
                                                             evt.ParticipantUri,
                                                             bool.Parse(evt.IsModeratorMuted),
                                                             bool.Parse(evt.IsSpeaking),
                                                             int.Parse(evt.Volume),
                                                             float.Parse(evt.Energy)));
                    }
                    break;

                case "SessionGroupAddedEvent":
                    if (OnSessionGroupAddedEvent != null)
                    {
                        OnSessionGroupAddedEvent(this,
                                                 new SessionGroupAddedEventArgs(
                                                     evt.AccountHandle,
                                                     evt.SessionGroupHandle,
                                                     evt.Type));
                    }
                    break;

                case "SessionAddedEvent":
                    if (OnSessionAddedEvent != null)
                    {
                        OnSessionAddedEvent(this,
                                            new SessionAddedEventArgs(
                                                evt.SessionGroupHandle,
                                                evt.SessionHandle,
                                                evt.Uri,
                                                bool.Parse(evt.IsChannel),
                                                bool.Parse(evt.Incoming)));
                    }
                    break;

                case "SessionRemovedEvent":
                    if (OnSessionRemovedEvent != null)
                    {
                        OnSessionRemovedEvent(this,
                                              new SessionRemovedEventArgs(
                                                  evt.SessionGroupHandle,
                                                  evt.SessionHandle,
                                                  evt.Uri));
                    }
                    break;

                case "SessionUpdatedEvent":
                    if (OnSessionRemovedEvent != null)
                    {
                        OnSessionUpdatedEvent(this,
                                              new SessionUpdatedEventArgs(
                                                  evt.SessionGroupHandle,
                                                  evt.SessionHandle,
                                                  evt.Uri,
                                                  int.Parse(evt.IsMuted) != 0,
                                                  int.Parse(evt.Volume),
                                                  int.Parse(evt.TransmitEnabled) != 0,
                                                  +int.Parse(evt.IsFocused) != 0));
                    }
                    break;

                case "AuxAudioPropertiesEvent":
                    if (OnAuxAudioPropertiesEvent != null)
                    {
                        OnAuxAudioPropertiesEvent(this,
                                                  new AudioPropertiesEventArgs(
                                                      bool.Parse(evt.MicIsActive),
                                                      float.Parse(evt.MicEnergy),
                                                      int.Parse(evt.MicVolume),
                                                      int.Parse(evt.SpeakerVolume)));
                    }
                    break;

                case "SessionMediaEvent":
                    if (OnSessionMediaEvent != null)
                    {
                        OnSessionMediaEvent(this,
                                            new SessionMediaEventArgs(
                                                evt.SessionHandle,
                                                bool.Parse(evt.HasText),
                                                bool.Parse(evt.HasAudio),
                                                bool.Parse(evt.HasVideo),
                                                bool.Parse(evt.Terminated)));
                    }
                    break;

                case "BuddyAndGroupListChangedEvent":
                    // TODO   * <AccountHandle>c1_m1000xrjiQgi95QhCzH_D6ZJ8c5A==</AccountHandle><Buddies /><Groups />
                    break;

                case "MediaStreamUpdatedEvent":
                    // TODO <SessionGroupHandle>c1_m1000xrjiQgi95QhCzH_D6ZJ8c5A==_sg0</SessionGroupHandle>
                    // <SessionHandle>c1_m1000xrjiQgi95QhCzH_D6ZJ8c5A==0</SessionHandle>
                    //<StatusCode>0</StatusCode><StatusString /><State>1</State><Incoming>false</Incoming>

                    break;

                default:
                    Logger.Log("Unimplemented event from the voice daemon: " + line, Helpers.LogLevel.Error);
                    break;
                }
            }
            else
            {
                Logger.Log("Unrecognized data from the voice daemon: " + line, Helpers.LogLevel.Error);
            }
        }
		public void Deserializes_response_with_equals_in_value() {
			string input = "Name=foo=bar\r\nId=0";
			var serializer = new ResponseSerializer();
			var result = serializer.Deserialize<TestClass>(input);
			result.Name.ShouldEqual("foo=bar");
		}