/// <summary>
 /// Success call constructor.
 /// </summary>
 /// <param name="publishResponse">Google PubSub response data.</param>
 public GoogleCloudPubSubClientResponse(PublishResponse publishResponse)
     : this()
 {
     this.Success = true;
     this.ErrorMessage = null;
     this.PublishResponse = publishResponse;
 }
コード例 #2
0
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>  
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            PublishResponse response = new PublishResponse();


            return response;
        }
コード例 #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AsyncPublishOperation"/> class.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="request">The request.</param>
 /// <param name="server">The server.</param>
 public AsyncPublishOperation(
      OperationContext context,
      IEndpointIncomingRequest request,
      StandardServer server)
 {
     m_context = context;
     m_request = request;
     m_server = server;
     m_response = new PublishResponse();
     m_request.Calldata = this;
 }
コード例 #4
0
        public async Task PublishAsync()
        {
            Mock <Publisher.PublisherClient> mockGrpcClient = new Mock <Publisher.PublisherClient>(MockBehavior.Strict);

            mockGrpcClient.Setup(x => x.CreateIAMPolicyClient())
            .Returns(new Mock <IAMPolicy.IAMPolicyClient>().Object);
            PublishRequest expectedRequest = new PublishRequest
            {
                TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"),
                Messages         =
                {
                    new PubsubMessage
                    {
                        Data = ByteString.CopyFromUtf8("-86"),
                    },
                },
            };
            PublishResponse expectedResponse = new PublishResponse
            {
                MessageIds =
                {
                    "messageIdsElement-744837059",
                },
            };

            mockGrpcClient.Setup(x => x.PublishAsync(expectedRequest, It.IsAny <CallOptions>()))
            .Returns(new Grpc.Core.AsyncUnaryCall <PublishResponse>(Task.FromResult(expectedResponse), null, null, null, null));
            PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null);
            TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
            IEnumerable <PubsubMessage> messages = new[]
            {
                new PubsubMessage
                {
                    Data = ByteString.CopyFromUtf8("-86"),
                },
            };
            PublishResponse response = await client.PublishAsync(topic, messages);

            Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
コード例 #5
0
ファイル: SelfMessages.cs プロジェクト: thisisvoa/SharpShark
        private void HandleSelfMessages(PublishResponse p_Message)
        {
            if (UID != p_Message.Publish.ID["uid"].ToObject <String>() || p_Message.Publish.Value == null)
            {
                return;
            }

            var s_Params = p_Message.Publish.Value["params"].ToObject <Dictionary <String, JToken> >();
            var s_UID    = p_Message.Publish.ID["uid"].ToObject <String>();

            switch (p_Message.Publish.Value["type"].ToObject <String>())
            {
            case "statusRequest":
                BroadcastMessageToSelf(GetCurrentPublicStatus(), "statusReply");
                break;

            case "masterPing":
                if (LoggedInMaster.UUID == UID)
                {
                    BroadcastMessageToSelf(GetPrivateStatus(), "masterPong");
                }

                break;

            case "masterPong":
                UpdateLoggedInMaster(s_Params);
                break;

            case "masterPromotion":
                UpdateLoggedInMaster(s_Params);
                break;

            case "statusUpdate":
                if (LoggedInMaster != null && LoggedInMaster.UUID == s_UID)
                {
                    LoggedInMaster.LastUpdate = DateTime.UtcNow.ToUnixTimestampMillis();
                }

                break;
            }
        }
コード例 #6
0
ファイル: AwsSnshelper.cs プロジェクト: hamza661/AmazonSNS
        private void PublishSNSEvent(string Message, string AmazonSNSKey, string AmazonSNSSecretKey, string TopicName, string EventType)
        {
            string topicname = ProcessSNSTopicName(TopicName);

            try
            {
                var           client        = new AmazonSimpleNotificationServiceClient(AmazonSNSKey, AmazonSNSSecretKey);
                string        topicarn      = string.Empty;
                PublishResult publishResult = new PublishResult();
                if (IsTopicExists(client, topicname, out topicarn))
                {
                    PublishRequest publishRequest = new PublishRequest();
                    publishRequest.Message  = Message;
                    publishRequest.TopicArn = topicarn;
                    PublishResponse publishResponse = client.Publish(publishRequest);
                    publishResult = publishResponse.PublishResult;
                }
                else
                {
                    CreateTopicRequest topicRequest = new CreateTopicRequest();
                    topicRequest.Name = topicname;
                    CreateTopicResponse topicResponse  = client.CreateTopic(topicRequest);
                    CreateTopicResult   result         = topicResponse.CreateTopicResult;
                    PublishRequest      publishRequest = new PublishRequest();
                    publishRequest.Message  = Message;
                    publishRequest.TopicArn = result.TopicArn;
                    PublishResponse publishResponse = client.Publish(publishRequest);
                    publishResult = publishResponse.PublishResult;
                }
                if (publishResult.IsSetMessageId())
                {
                    CreateLogs(Message, EventType, topicname, true);
                }
            }
            catch (AmazonSimpleNotificationServiceException ex)
            {
                /*Log details to logentries server.*/
                CreateLogs(Message, EventType, topicname, false);
                throw ex;
            }
        }
コード例 #7
0
        /// <summary>Snippet for PublishAsync</summary>
        public async Task PublishRequestObjectAsync()
        {
            // Snippet: PublishAsync(PublishRequest, CallSettings)
            // Additional: PublishAsync(PublishRequest, CancellationToken)
            // Create client
            PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();

            // Initialize request argument(s)
            PublishRequest request = new PublishRequest
            {
                TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
                Messages         =
                {
                    new PubsubMessage(),
                },
            };
            // Make the request
            PublishResponse response = await publisherServiceApiClient.PublishAsync(request);

            // End snippet
        }
 public void Publish_RequestObject()
 {
     // Snippet: Publish(PublishRequest,CallSettings)
     // Create client
     PublisherClient publisherClient = PublisherClient.Create();
     // Initialize request argument(s)
     PublishRequest request = new PublishRequest
     {
         TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"),
         Messages         =
         {
             new PubsubMessage
             {
                 Data = ByteString.CopyFromUtf8(""),
             },
         },
     };
     // Make the request
     PublishResponse response = publisherClient.Publish(request);
     // End snippet
 }
コード例 #9
0
        /// <summary>
        /// Envia um notification push para um device usando o sistema de notificações da Microsoft
        /// </summary>
        /// <param name="device">ARN registrado no amazon</param>
        /// <param name="title"></param>
        /// <param name="message"></param>
        /// <param name="extra"></param>
        /// <returns></returns>
        protected override bool SendMessage(DeviceEntity device, string title, string message, bool silent, string extra = "")
        {
            string toast = "{ " + GetMessage(title, message, silent, extra) + " } ";

            PublishRequest snsRequest = new PublishRequest()
            {
                Message           = toast,
                MessageStructure  = "json",
                MessageAttributes = GetWNSHeaders(silent),
                TargetArn         = device.BrokerEndpoint
            };

            PublishResponse response = AWSFactory.SNSClient.Publish(snsRequest);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                return(true);
            }

            return(false);
        }
コード例 #10
0
        public async Task PublishAsync()
        {
            // Snippet: PublishAsync(TopicName,IEnumerable<PubsubMessage>,CallSettings)
            // Additional: PublishAsync(TopicName,IEnumerable<PubsubMessage>,CancellationToken)
            // Create client
            PublisherClient publisherClient = await PublisherClient.CreateAsync();

            // Initialize request argument(s)
            TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
            IEnumerable <PubsubMessage> messages = new[]
            {
                new PubsubMessage
                {
                    Data = ByteString.CopyFromUtf8(""),
                },
            };
            // Make the request
            PublishResponse response = await publisherClient.PublishAsync(topic, messages);

            // End snippet
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: AEJS1982/MyWorks
        static async Task sendSNSMessageAsync()
        {
            //Send a message to the SNS event topic

            var snsClient = new AmazonSimpleNotificationServiceClient();

            // Creating the topic request and the topic and response
            var topicRequest = new CreateTopicRequest
            {
                Name = "TestSNSTopic"
            };

            var topicResponse = await snsClient.CreateTopicAsync(topicRequest);

            var subscribeRequest = new SubscribeRequest()
            {
                TopicArn = topicResponse.TopicArn,
                Protocol = "application", // important to chose the protocol as I am sending notification to applications I have chosen application here.
                Endpoint = ""
            };

            var reqObj = new Dictionary <String, String>();

            reqObj["field1"] = "123";
            reqObj["field2"] = "ABC";

            PublishRequest publishReq = new PublishRequest()
            {
                TargetArn        = subscribeRequest.Endpoint,
                MessageStructure = "json",
                Message          = JsonConvert.SerializeObject(reqObj)
            };

            PublishResponse response = await snsClient.PublishAsync(publishReq);

            if (response != null && response.MessageId != null)
            {
                Console.WriteLine("Notification Send Successfully");
            }
        }
        /// <summary>
        /// Publish MetaData to Cloud
        /// </summary>
        /// <param name="pRequestMessage"></param>
        /// <returns></returns>
        public PublishResponse MetaDataToCloud(PublishRequest pRequest)
        {
            bool            pCloud = true;
            MetaDataToCloud _publishMetaDataToCloud = new MetaDataToCloud();

            try
            {
                //pRequest.RequestId = "2";
                PublishResponse result = new PublishResponse(pRequest.RequestId);

                if (pCloud)
                {
                    //Stop Web Job
                    if (_publishMetaDataToCloud.StartAndStopWebJob(Constant.WebJob.Stop))
                    {
                        //Update SurveyMetaData table in Cloud
                        Epi.Web.Enter.Interfaces.DataInterfaces.ISurveyInfoDao   SurveyInfoDao   = new EFwcf.EntitySurveyInfoDao();
                        Epi.Web.Enter.Interfaces.DataInterfaces.IOrganizationDao OrganizationDao = new EFwcf.EntityOrganizationDao();
                        Epi.Web.BLL.Publisher Implementation        = new Epi.Web.BLL.Publisher(SurveyInfoDao, OrganizationDao);
                        SurveyInfoBO          surveyInfoBO          = Mapper.ToBusinessObject(pRequest.SurveyInfo);
                        SurveyRequestResultBO surveyRequestResultBO = Implementation.PublishSurvey(surveyInfoBO);
                        result.PublishInfo = Mapper.ToDataTransferObject(surveyRequestResultBO);
                        EpiCloudOperation();
                    }
                }
                else
                {
                }
                return(result);
            }
            catch (Exception ex)
            {
                CustomFaultException customFaultException = new CustomFaultException();
                customFaultException.CustomMessage = ex.Message;
                customFaultException.Source        = ex.Source;
                customFaultException.StackTrace    = ex.StackTrace;
                customFaultException.HelpLink      = ex.HelpLink;
                throw new FaultException <CustomFaultException>(customFaultException);
            }
        }
コード例 #13
0
ファイル: Function.cs プロジェクト: mattschwartz/picshift-www
        private APIGatewayProxyResponse ProcessRequest(APIGatewayProxyRequest request)
        {
            Console.WriteLine($"Received API request: '{request.RequestContext.RequestId}'.");
            Console.WriteLine($"Request body: '{request.Body}'.");

            WebsiteMessageRequestModel requestModel = SafeBuildRequestModel(request.Body);

            Console.WriteLine($"Received input: {requestModel}");

            PublishResponse snsPublishResponse = PublishToSns(requestModel);

            return(new APIGatewayProxyResponse
            {
                StatusCode = (int)snsPublishResponse.HttpStatusCode,
                Headers = new Dictionary <string, string>
                {
                    ["Content-Type"] = "application/json",
                    ["Access-Control-Allow-Origin"] = "*",
                },
                Body = $"{{ \"message\": \"Your response has been sent dutifully.\" }}"
            });
        }
コード例 #14
0
ファイル: Function.cs プロジェクト: mattschwartz/picshift-www
        private PublishResponse PublishToSns(WebsiteMessageRequestModel requestModel)
        {
            var snsModel = new SnsMessageModel
            {
                FromEmail   = requestModel.FromEmail,
                CreatedAt   = DateTime.UtcNow,
                MessageBody = requestModel.MessageContents
            };
            string snsMessage = snsModel.GetSnsMessage();

            Console.WriteLine($"Posting message to SNS: {snsMessage}");

            PublishResponse response = _snsClient.PublishAsync(_emailTopicArn, snsMessage).Result;

            Console.WriteLine("Received SNS publish response: [{0}= '{1}', {2}= '{3}'].",
                              nameof(PublishResponse.HttpStatusCode),
                              response.HttpStatusCode,
                              nameof(PublishResponse.MessageId),
                              response.MessageId);

            return(response);
        }
コード例 #15
0
        static async Task SNSAsync()
        {
            var topicArn  = ConfigurationManager.AppSettings["DemoTopicArn"];
            var snsClient = new AmazonSimpleNotificationServiceClient(ConfigurationManager.AppSettings["AccessId"], ConfigurationManager.AppSettings["SecretKey"], RegionEndpoint.USEast1);

            var             publisher = new SNSPublisher();
            PublishResponse response  = await publisher.SendMessage(snsClient, topicArn, "MESSAGE");

            Console.WriteLine(response.MessageId);

            MessageAttributes messageAttributes = new MessageAttributes();

            messageAttributes.Add("provider_type", "LOA");
            response = await publisher.SendMessage(snsClient, topicArn, "MESSAGE WITH MATCHING ATTRIBUTES", messageAttributes);

            Console.WriteLine(response.MessageId);

            messageAttributes.Add("provider_type", "MR");
            response = await publisher.SendMessage(snsClient, topicArn, "MESSAGE WITH NON-MATCHING ATTRIBUTES", messageAttributes);

            Console.WriteLine(response.MessageId);
        }
コード例 #16
0
        private async Task <PublishResponse> PublishMessage(string topic, string message, int retries = 3)
        {
            PublishResponse response         = null;
            bool            isSuccessPublish = false;

            do
            {
                try
                {
                    var findTopicRequest = SnsClient.FindTopic(topic);
                    if (findTopicRequest == null)
                    {
                        throw new Exception(String.Format("Topic {0} NotFound", topic));
                    }
                    response = await SnsClient.PublishAsync(findTopicRequest.TopicArn, message);

                    isSuccessPublish = true;
                }
                catch (Exception e)
                {
                    var fg = Console.ForegroundColor;
                    if (retries > 0)
                    {
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine("--WARNING-- Encountered error while publishing message to SNS topic: {0}",
                                          topic);
                        Console.WriteLine("--EXCEPTION-- {0}", e);
                        Console.WriteLine("Retrying...");
                        Console.ForegroundColor = fg;
                        retries -= 1;
                    }
                    else
                    {
                        throw;
                    }
                }
            } while (retries > 0 && !isSuccessPublish);
            return(response);
        }
コード例 #17
0
        public void sendSms(string phoneNumber, string messageBody, out string messageid, out string messagestatus)
        {
            string AWSAccessKeyId = ConfigurationManager.AppSettings["AWSAccessKeyId"].ToString();
            string AWSSecretKey   = ConfigurationManager.AppSettings["AWSSecretKey"].ToString();
            var    sns            = new AmazonSimpleNotificationServiceClient(AWSAccessKeyId, AWSSecretKey, Amazon.RegionEndpoint.USEast1);


            var smsAttributes = new Dictionary <string, MessageAttributeValue>();


            MessageAttributeValue sMSType = new MessageAttributeValue();

            sMSType.DataType    = "String";
            sMSType.StringValue = "Transactional";



            CancellationTokenSource source = new CancellationTokenSource();
            CancellationToken       token  = source.Token;


            smsAttributes.Add("AWS.SNS.SMS.SMSType", sMSType);


            PublishRequest publishRequest = new PublishRequest();

            publishRequest.Message           = "This is 2nd sample message";
            publishRequest.MessageAttributes = smsAttributes;
            publishRequest.PhoneNumber       = "received phone no with + and country code";

            PublishResponse message = sns.Publish(new PublishRequest()
            {
                PhoneNumber = phoneNumber, MessageAttributes = smsAttributes, Message = messageBody, Subject = "NeeoApp Activation"
            });

            messageid     = message.MessageId;
            messagestatus = message.HttpStatusCode.ToString();
        }
コード例 #18
0
        public async Task ItShouldPublishASingleMessageToSns()
        {
            var publishRequest = new PublishRequest("topic-arn", "sns-message");
            var publishResult  = new PublishResponse {
                MessageId = "message-id"
            };

            var snsService = Substitute.For <IAmazonSimpleNotificationService>();

            snsService.PublishAsync(Arg.Any <PublishRequest>())
            .Returns(publishResult);

            var(probe, task) = this.SourceProbe <string>()
                               .Via(SnsPublisher.PlainFlow("topic-arn", snsService))
                               .ToMaterialized(Sink.Seq <PublishResponse>(), Keep.Both)
                               .Run(this._materializer);

            probe.SendNext("sns-message").SendComplete();
            var actualResult = (await task).FirstOrDefault();

            actualResult.Should().Be(publishResult);
            await snsService.Received(1).PublishAsync(Arg.Any <PublishRequest>());
        }
コード例 #19
0
 internal void OnPublishResponse(PublishResponse publishResponse)
 {
     isPublishing = true;
     try
     {
         var nd = publishResponse.NotificationMessage?.NotificationData;
         if (nd == null)
         {
             return;
         }
         foreach (var n in nd)
         {
             if (n is DataChangeNotification dcn)
             {
                 CheckNotifications(dcn);
             }
         }
     }
     finally
     {
         isPublishing = false;
     }
 }
コード例 #20
0
ファイル: Subscription.cs プロジェクト: hookttg/opc-ua-client
        /// <summary>
        /// Receive PublishResponse message.
        /// </summary>
        /// <param name="response">The publish response.</param>
        public void OnPublishResponse(PublishResponse response)
        {
            if (response.SubscriptionId != this.Id)
            {
                return;
            }

            try
            {
                if (this.synchronizationContext != null)
                {
                    this.synchronizationContext.Post(this.ProcessNotifications, response);
                }
                else
                {
                    this.ProcessNotifications(response);
                }
            }
            finally
            {
                response.MoreNotifications = false; // reset flag indicates message handled.
            }
        }
コード例 #21
0
        /// <summary>Snippet for PublishAsync</summary>
        public async Task PublishAsync_RequestObject()
        {
            // Snippet: PublishAsync(PublishRequest,CallSettings)
            // Create client
            PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();

            // Initialize request argument(s)
            PublishRequest request = new PublishRequest
            {
                TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"),
                Messages         =
                {
                    new PubsubMessage
                    {
                        Data = ByteString.CopyFromUtf8(""),
                    },
                },
            };
            // Make the request
            PublishResponse response = await publisherServiceApiClient.PublishAsync(request);

            // End snippet
        }
コード例 #22
0
        public async Task PublishEventAsync <TEvent>(TEvent @event)
        {
            var endpoint = RegionEndpoint.GetBySystemName(_options.Value.Region);
            var client   = new AmazonSimpleNotificationServiceClient(endpoint);

            Type eventType = typeof(TEvent);
            AmazonSnsTopicAttribute attr = eventType
                                           .GetCustomAttributes(typeof(AmazonSnsTopicAttribute), inherit: false)
                                           .OfType <AmazonSnsTopicAttribute>()
                                           .FirstOrDefault();
            string topicName = attr == null
                ? eventType.FullName.ToLower().Replace('.', '-')
                : attr.Name;

            var createTopicRequest = new CreateTopicRequest(topicName);
            CreateTopicResponse createTopicResponse = await client.CreateTopicAsync(createTopicRequest);

            string topicArn = createTopicResponse.TopicArn;

            string          message         = _eventSerializer.Serialize(@event);
            var             publishRequest  = new PublishRequest(topicArn, message);
            PublishResponse publishResponse = await client.PublishAsync(publishRequest);
        }
コード例 #23
0
        public string SendMessage(IMessageRequest request)
        {
            PublishRequest publishRequest = new PublishRequest();
            bool           valid          = Helpers.IsPhoneNumberValid(request.PhoneNumber);

            if (valid)
            {
                try
                {
                    string phone = Helpers.GetPhoneDigits(request.PhoneNumber);
                    publishRequest.Message     = request.Message;
                    publishRequest.PhoneNumber = $"+1{phone}";
                    PublishResponse response = this.snsService.PublishAsync(publishRequest).Result;
                    return(response.MessageId);
                }
                catch (Exception ex) {
                    throw ex;
                }
            }
            else
            {
                throw new ArgumentException($"{request.PhoneNumber} is not a valid phone format");
            }
        }
コード例 #24
0
        public async Task PublishAsync(Message message, PublishMetadata metadata, CancellationToken cancellationToken)
        {
            var             request  = BuildPublishRequest(message, metadata);
            PublishResponse response = null;

            try
            {
                response = await Client.PublishAsync(request, cancellationToken).ConfigureAwait(false);
            }
            catch (AmazonServiceException ex)
            {
                if (!ClientExceptionHandler(ex, message))
                {
                    throw new PublishException(
                              $"Failed to publish message to SNS. Topic ARN: '{request.TopicArn}', Subject: '{request.Subject}', Message: '{request.Message}'.",
                              ex);
                }
            }

            _logger.LogInformation(
                "Published message: '{SnsSubject}' with content {SnsMessage} and request Id '{SnsRequestId}'",
                request.Subject,
                request.Message,
                response?.ResponseMetadata?.RequestId);

            if (MessageResponseLogger != null)
            {
                var responseData = new MessageResponse
                {
                    HttpStatusCode   = response?.HttpStatusCode,
                    MessageId        = response?.MessageId,
                    ResponseMetadata = response?.ResponseMetadata
                };
                MessageResponseLogger.Invoke(responseData, message);
            }
        }
コード例 #25
0
        public async Task <IHttpActionResult> PostPublishAsync(RouteIdentifier identifier)
        {
            // Load route to get source code.
            var route = await _routeRepository.GetRouteByIdentifierAsync(identifier);

            var code   = route.Code;
            var source = new Source(code, route.RoutePackages.Select(p => new Dependency
            {
                Id      = p.Id,
                Version = p.Version,
                Type    = p.Type
            }).ToArray());

            // Compile code and get assembly as byte array.
            var compilationResult = _compilationService.Compile(source);

            // We'll save the assembly and mark the route as published if the compilation was successful.
            if (compilationResult.Success)
            {
                route.Assembly    = compilationResult.Assembly;
                route.IsCurrent   = true;
                route.IsOnline    = true;
                route.PublishedOn = DateTimeOffset.UtcNow;

                route = await _routeRepository.UpdateRouteAsync(route);
            }

            var result = new PublishResponse
            {
                Compilation = compilationResult,
                Route       = RouteResponse.Map(route)
            };

            // Return an error response if compile was unsuccessful, otherwise the response was successful.
            return(Content(compilationResult.Success ? HttpStatusCode.OK : HttpStatusCode.InternalServerError, result));
        }
コード例 #26
0
        public async Task ShouldPublish()
        {
            //Arrange
            var publishAsyncReturns = new PublishResponse()
            {
                HttpStatusCode = HttpStatusCode.OK
            };
            var options = new NotificationOptions()
            {
                Region = "us-east-1", ClientId = "123456789012"
            };
            var findTopicAsyncReturns = new Topic();

            var amazonSnsMock = new Mock <IAmazonSimpleNotificationService>();

            amazonSnsMock.Setup(x => x.PublishAsync(It.IsAny <string>(), It.IsAny <string>(), default))
            .ReturnsAsync(publishAsyncReturns).Verifiable();

            var notification = new TestNotification {
                Message = Guid.NewGuid().ToString()
            };

            var notificationAttributesReaderMock = new Mock <INotificationAttributesReader>();

            notificationAttributesReaderMock.Setup(x => x.GetTopicName(It.IsAny <Type>()))
            .Returns($"{nameof(TestNotification)}Topic");

            var notificationSns = new NotificationSns(amazonSnsMock.Object, Options.Create(options), notificationAttributesReaderMock.Object);


            //Act
            await notificationSns.Publish(notification);

            //Assert
            amazonSnsMock.VerifyAll();
        }
コード例 #27
0
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            PublishResponse response = new PublishResponse();

            while (context.Read())
            {
                if (context.IsStartElement)
                {
                    if (context.TestExpression("PublishResult", 2))
                    {
                        UnmarshallResult(context, response);
                        continue;
                    }

                    if (context.TestExpression("ResponseMetadata", 2))
                    {
                        response.ResponseMetadata = ResponseMetadataUnmarshaller.GetInstance().Unmarshall(context);
                    }
                }
            }


            return(response);
        }
コード例 #28
0
ファイル: PublishDemo.cs プロジェクト: breakawayz/smn-sdk-net
        /// <summary>
        /// 消息发布
        /// </summary>
        public void PublishWithMessage()
        {
            // 设置请求对象
            PublishRequest request = new PublishRequest
            {
                TopicUrn = "urn:smn:cn-north-1:cffe4fc4c9a54219b60dbaf7b586e132:create_by_zhangyx_test_csharp",
                Subject  = "hello csharp",
                Message  = "a test messag from csharp sdk"
            };

            try
            {
                // 发送请求并返回响应
                PublishResponse response = smnClient.SendRequest(request);
                string          result   = response.MessageId;
                Console.WriteLine("{0}", result);
                Console.ReadLine();
            }
            catch (Exception e)
            {
                // 处理异常
                Console.WriteLine("{0}", e.Message);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="pRequestMessage"></param>
        /// <returns></returns>
        public PublishResponse RePublishSurvey(PublishRequest pRequest)
        {
            try
            {
                PublishResponse result = new PublishResponse(pRequest.RequestId);
                Epi.Web.Enter.Interfaces.DataInterfaces.ISurveyInfoDao   SurveyInfoDao   = new EFwcf.EntitySurveyInfoDao();
                Epi.Web.Enter.Interfaces.DataInterfaces.IOrganizationDao OrganizationDao = new EFwcf.EntityOrganizationDao();
                Epi.Web.BLL.Publisher Implementation        = new Epi.Web.BLL.Publisher(SurveyInfoDao, OrganizationDao);
                SurveyInfoBO          surveyInfoBO          = Mapper.ToBusinessObject(pRequest.SurveyInfo);
                SurveyRequestResultBO surveyRequestResultBO = Implementation.RePublishSurvey(surveyInfoBO);
                result.PublishInfo = Mapper.ToDataTransferObject(surveyRequestResultBO);

                return(result);
            }
            catch (Exception ex)
            {
                CustomFaultException customFaultException = new CustomFaultException();
                customFaultException.CustomMessage = ex.Message;
                customFaultException.Source        = ex.Source;
                customFaultException.StackTrace    = ex.StackTrace;
                customFaultException.HelpLink      = ex.HelpLink;
                throw new FaultException <CustomFaultException>(customFaultException);
            }
        }
コード例 #30
0
        /// <summary>
        /// Handle PublishResponse message.
        /// </summary>
        /// <param name="publishResponse">The publish response.</param>
        private void OnPublishResponse(PublishResponse publishResponse)
        {
            this.isPublishing = true;
            try
            {
                // loop thru all the notifications
                var nd = publishResponse.NotificationMessage?.NotificationData;
                if (nd == null)
                {
                    return;
                }

                foreach (var n in nd)
                {
                    // if data change.
                    var dcn = n as DataChangeNotification;
                    if (dcn != null)
                    {
                        MonitoredItemBase item;
                        foreach (var min in dcn.MonitoredItems)
                        {
                            if (this.monitoredItems.TryGetValueByClientId(min.ClientHandle, out item))
                            {
                                try
                                {
                                    item.Publish(min.Value);
                                }
                                catch (Exception ex)
                                {
                                    this.logger?.LogError($"Error publishing value for NodeId {item.NodeId}. {ex.Message}");
                                }
                            }
                        }

                        continue;
                    }

                    // if event.
                    var enl = n as EventNotificationList;
                    if (enl != null)
                    {
                        MonitoredItemBase item;
                        foreach (var efl in enl.Events)
                        {
                            if (this.monitoredItems.TryGetValueByClientId(efl.ClientHandle, out item))
                            {
                                try
                                {
                                    item.Publish(efl.EventFields);
                                }
                                catch (Exception ex)
                                {
                                    this.logger?.LogError($"Error publishing event for NodeId {item.NodeId}. {ex.Message}");
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                this.isPublishing = false;
            }
        }
コード例 #31
0
ファイル: Opc.Ua.Messages.cs プロジェクト: yuriik83/UA-.NET
        /// <summary cref="IServiceMessage.CreateResponse" />
        public object CreateResponse(IServiceResponse response)
        {
            PublishResponse body = response as PublishResponse;

            if (body == null)
            {
                body = new PublishResponse();
                body.ResponseHeader = ((ServiceFault)response).ResponseHeader;
            }

            return new PublishResponseMessage(body);
        }
コード例 #32
0
        public async Task <IActionResult> EditUser([Bind("Username", "Name", "PhoneNumber", "EmailAddress", "Role")] UserDataManagementViewModel existingUser)
        {
            bool change   = false;
            User identity = await _context.Users.Where(u => u.Username == existingUser.Username).FirstOrDefaultAsync();

            if (identity == null)
            {
                return(StatusCode(404));
            }
            else if (existingUser.PhoneNumber == null && existingUser.EmailAddress == null)
            {
                ViewData["Alert"]     = "Danger";
                ViewData["Message"]   = "You must specify either a Phone Number or Email Address";
                existingUser.user     = identity;
                existingUser.allRoles = await _context.Roles.ToListAsync();

                return(View(existingUser));
            }
            else
            {
                NotificationToken token = new NotificationToken
                {
                    Type       = Models.Type.Verify,
                    Vaild      = true,
                    LinkedUser = identity
                };
                if (identity.Existence == Existence.Internal && !existingUser.Username.Equals(identity.Username))
                {
                    identity.Username = existingUser.Username;
                    change            = true;
                }
                if (identity.Existence == Existence.Internal && !existingUser.Name.Equals(identity.Name))
                {
                    identity.Name = existingUser.Name;
                    change        = true;
                }
                if (!existingUser.Role.Equals("User") && identity.Existence == Existence.Internal)
                {
                    Role role = await _context.Roles.Where(r => r.RoleName == existingUser.Role).FirstOrDefaultAsync();

                    if (identity.LinkedRole != role)
                    {
                        identity.LinkedRole = role;
                        change = true;
                    }
                }
                else if (existingUser.Role.Equals("User") && identity.Existence == Existence.Internal && identity.LinkedRole != null)
                {
                    identity.LinkedRole = null;
                    change = true;
                }
                if (existingUser.PhoneNumber != null && (identity.PhoneNumber == null || !identity.PhoneNumber.Equals(existingUser.PhoneNumber)) && (identity.OverridableField == OverridableField.PhoneNumber || identity.OverridableField == OverridableField.Both))
                {
                    identity.PhoneNumber         = existingUser.PhoneNumber;
                    identity.VerifiedPhoneNumber = false;
                    token.Token = Areas.Internal.Controllers.AccountController.TokenGenerator();
                    PublishRequest SNSrequest = new PublishRequest
                    {
                        Message     = HttpContext.User.Claims.First(c => c.Type == "name").Value + " has changed the phone number on your account. To confirm this change, please click on this link: " + "https://" + HttpContext.Request.Host + "/Internal/Account/VerifyPhoneNumber?token=" + token.Token,
                        PhoneNumber = "+65" + identity.PhoneNumber
                    };
                    SNSrequest.MessageAttributes["AWS.SNS.SMS.SenderID"] = new MessageAttributeValue {
                        StringValue = "SmartIS", DataType = "String"
                    };
                    SNSrequest.MessageAttributes["AWS.SNS.SMS.SMSType"] = new MessageAttributeValue {
                        StringValue = "Transactional", DataType = "String"
                    };
                    PublishResponse response = await _snsClient.PublishAsync(SNSrequest);

                    if (response.HttpStatusCode != HttpStatusCode.OK)
                    {
                        return(StatusCode(500));
                    }
                    token.Mode = Mode.SMS;
                    _context.NotificationTokens.Add(token);
                    change = true;
                }
                else if (existingUser.PhoneNumber == null && identity.PhoneNumber != null && (identity.OverridableField == OverridableField.PhoneNumber || identity.OverridableField == OverridableField.Both))
                {
                    identity.PhoneNumber         = null;
                    identity.VerifiedPhoneNumber = false;
                    change = true;
                }
                if (existingUser.EmailAddress != null && (identity.EmailAddress == null || !identity.EmailAddress.Equals(existingUser.EmailAddress)) && (identity.OverridableField == OverridableField.EmailAddress || identity.OverridableField == OverridableField.Both))
                {
                    identity.EmailAddress         = existingUser.EmailAddress;
                    identity.VerifiedEmailAddress = false;
                    token.Token = Areas.Internal.Controllers.AccountController.TokenGenerator();
                    SendEmailRequest SESrequest = new SendEmailRequest
                    {
                        Source      = Environment.GetEnvironmentVariable("SES_EMAIL_FROM-ADDRESS"),
                        Destination = new Destination
                        {
                            ToAddresses = new List <string>
                            {
                                identity.EmailAddress
                            }
                        },
                        Message = new Message
                        {
                            Subject = new Content("Verify your email address for SmartInsights"),
                            Body    = new Body
                            {
                                Text = new Content
                                {
                                    Charset = "UTF-8",
                                    Data    = "Hi " + identity.Name + ",\r\n\n" + HttpContext.User.Claims.First(c => c.Type == "name").Value + " has changed the email address on your account. To confirm this change, please click on this link: " + "https://" + HttpContext.Request.Host + "/Internal/Account/VerifyEmailAddress?token=" + token.Token + "\r\n\n\nThis is a computer-generated email, please do not reply"
                                }
                            }
                        }
                    };
                    SendEmailResponse response = await _sesClient.SendEmailAsync(SESrequest);

                    if (response.HttpStatusCode != HttpStatusCode.OK)
                    {
                        return(StatusCode(500));
                    }
                    token.Mode = Mode.EMAIL;
                    _context.NotificationTokens.Add(token);
                    change = true;
                }
                else if (existingUser.EmailAddress == null && identity.EmailAddress != null && (identity.OverridableField == OverridableField.EmailAddress || identity.OverridableField == OverridableField.Both))
                {
                    identity.EmailAddress         = null;
                    identity.VerifiedEmailAddress = false;
                    change = true;
                }
                _context.Users.Update(identity);
                try
                {
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateException)
                {
                    ViewData["Alert"]   = "Danger";
                    ViewData["Message"] = "Something went wrong. Maybe try again?";
                    return(View(existingUser));
                }
                if (change)
                {
                    TempData["Message"] = "Succesfully edited " + identity.Name + "'s account details";
                    TempData["Alert"]   = "Success";
                }
                else
                {
                    TempData["Message"] = "No changes made to " + identity.Name + "'s account details";
                    TempData["Alert"]   = "Warning";
                }
                return(RedirectToAction("Manage"));
            }
        }
コード例 #33
0
        public async Task <IActionResult> CreateUser([Bind("Username", "Name", "PhoneNumber", "EmailAddress", "Role")] UserDataManagementViewModel newUser)
        {
            if (newUser.PhoneNumber == null && newUser.EmailAddress == null)
            {
                ViewData["Alert"]   = "Danger";
                ViewData["Message"] = "You must specify either a Phone Number or Email Address";
                newUser.allRoles    = await _context.Roles.ToListAsync();

                return(View(newUser));
            }
            else
            {
                User addition = new User
                {
                    Username         = newUser.Username,
                    Name             = newUser.Name,
                    Existence        = Existence.Internal,
                    Password         = Password.GetRandomSalt(),
                    Status           = UserStatus.Pending,
                    OverridableField = OverridableField.Both
                };
                if (!newUser.Role.Equals("User"))
                {
                    Role role = await _context.Roles.Where(r => r.RoleName == newUser.Role).FirstOrDefaultAsync();

                    addition.LinkedRole = role;
                }
                if (newUser.PhoneNumber == null)
                {
                    addition.EmailAddress = newUser.EmailAddress;
                }
                else
                {
                    addition.PhoneNumber = newUser.PhoneNumber;
                }
                _context.Users.Add(addition);
                try
                {
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateException)
                {
                    ViewData["Alert"]   = "Danger";
                    ViewData["Message"] = "Something went wrong. Maybe try again?";
                    return(View(newUser));
                }
                addition = await _context.Users.Where(u => u.Username == newUser.Username).FirstOrDefaultAsync();

                Settings settings = new Settings
                {
                    LinkedUserID = addition.ID,
                    LinkedUser   = addition
                };
                await _context.Settings.AddAsync(settings);

                NotificationToken token = new NotificationToken
                {
                    Type       = Models.Type.Activate,
                    Vaild      = true,
                    LinkedUser = addition
                };
                if (addition.EmailAddress != null)
                {
                    token.Token = Areas.Internal.Controllers.AccountController.TokenGenerator();
                    SendEmailRequest SESrequest = new SendEmailRequest
                    {
                        Source      = Environment.GetEnvironmentVariable("SES_EMAIL_FROM-ADDRESS"),
                        Destination = new Destination
                        {
                            ToAddresses = new List <string>
                            {
                                addition.EmailAddress
                            }
                        },
                        Message = new Message
                        {
                            Subject = new Content("Welcome to SmartInsights"),
                            Body    = new Body
                            {
                                Text = new Content
                                {
                                    Charset = "UTF-8",
                                    Data    = "Hi " + addition.Name + ",\r\n\n" + HttpContext.User.Claims.First(c => c.Type == "name").Value + " has created an account for you on SmartInsights. Your username to login is:\r\n" + addition.Username + "\r\n\nTo enable your account, you will need to set your password and verify this email address. Please click on this link: " + "https://" + HttpContext.Request.Host + "/Internal/Account/SetPassword?token=" + token.Token + " to do so.\r\n\n\nThis is a computer-generated email, please do not reply"
                                }
                            }
                        }
                    };
                    SendEmailResponse response = await _sesClient.SendEmailAsync(SESrequest);

                    if (response.HttpStatusCode != HttpStatusCode.OK)
                    {
                        return(StatusCode(500));
                    }
                    token.Mode = Mode.EMAIL;
                }
                else
                {
                    PublishRequest SNSrequest = new PublishRequest
                    {
                        Message     = HttpContext.User.Claims.First(c => c.Type == "name").Value + " has created an account for you on SmartInsights. Your username to login is: " + addition.Username + ". Please click on this link to set your password and verify this phone number: " + "https://" + HttpContext.Request.Host + "/Internal/Account/SetPassword?token=" + token.Token,
                        PhoneNumber = "+65" + addition.PhoneNumber
                    };
                    SNSrequest.MessageAttributes["AWS.SNS.SMS.SenderID"] = new MessageAttributeValue {
                        StringValue = "SmartIS", DataType = "String"
                    };
                    SNSrequest.MessageAttributes["AWS.SNS.SMS.SMSType"] = new MessageAttributeValue {
                        StringValue = "Transactional", DataType = "String"
                    };
                    PublishResponse response = await _snsClient.PublishAsync(SNSrequest);

                    if (response.HttpStatusCode != HttpStatusCode.OK)
                    {
                        return(StatusCode(500));
                    }
                    token.Mode = Mode.SMS;
                }
                await _context.NotificationTokens.AddAsync(token);

                await _context.SaveChangesAsync();

                TempData["Message"] = "Succesfully created " + addition.Name + "'s account. Please ask " + addition.Name + " to look at the email/SMS to activate the account";
                TempData["Alert"]   = "Success";
                return(RedirectToAction("Manage"));
            }
        }
コード例 #34
0
ファイル: Opc.Ua.Messages.cs プロジェクト: yuriik83/UA-.NET
 /// <summary>
 /// Initializes the message with the body.
 /// </summary>
 public PublishResponseMessage(PublishResponse PublishResponse)
 {
     this.PublishResponse = PublishResponse;
 }
コード例 #35
0
ファイル: Opc.Ua.Messages.cs プロジェクト: yuriik83/UA-.NET
        /// <summary>
        /// Initializes the message with a service fault.
        /// </summary>
        public PublishResponseMessage(ServiceFault ServiceFault)
        {
            this.PublishResponse = new PublishResponse();

            if (ServiceFault != null)
            {
                this.PublishResponse.ResponseHeader = ServiceFault.ResponseHeader;
            }
        }
コード例 #36
0
ファイル: Opc.Ua.Endpoints.cs プロジェクト: zryska/UA-.NET
        /// <summary>
        /// Invokes the Publish service.
        /// </summary>
        public IServiceResponse Publish(IServiceRequest incoming)
        {
            PublishResponse response = null;

            PublishRequest request = (PublishRequest)incoming;

            uint subscriptionId = 0;
            UInt32Collection availableSequenceNumbers = null;
            bool moreNotifications = false;
            NotificationMessage notificationMessage = null;
            StatusCodeCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            response = new PublishResponse();

            response.ResponseHeader = ServerInstance.Publish(
               request.RequestHeader,
               request.SubscriptionAcknowledgements,
               out subscriptionId,
               out availableSequenceNumbers,
               out moreNotifications,
               out notificationMessage,
               out results,
               out diagnosticInfos);

            response.SubscriptionId           = subscriptionId;
            response.AvailableSequenceNumbers = availableSequenceNumbers;
            response.MoreNotifications        = moreNotifications;
            response.NotificationMessage      = notificationMessage;
            response.Results                  = results;
            response.DiagnosticInfos          = diagnosticInfos;

            return response;
        }
コード例 #37
0
        private async Task<IServiceResponse> ReceiveResponseAsync(CancellationToken token = default(CancellationToken))
        {
            await this.receivingSemaphore.WaitAsync(token).ConfigureAwait(false);
            try
            {
                token.ThrowIfCancellationRequested();
                this.ThrowIfClosedOrNotOpening();
                uint sequenceNumber;
                uint requestId;
                int paddingHeaderSize;
                int plainHeaderSize;
                int bodySize;
                int paddingSize;

                var bodyStream = SerializableBytes.CreateWritableStream();
                var bodyDecoder = new BinaryDecoder(bodyStream, this);
                try
                {
                    // read chunks
                    int chunkCount = 0;
                    bool isFinal = false;
                    do
                    {
                        chunkCount++;
                        if (this.LocalMaxChunkCount > 0 && chunkCount > this.LocalMaxChunkCount)
                        {
                            throw new ServiceResultException(StatusCodes.BadEncodingLimitsExceeded);
                        }

                        var count = await this.ReceiveAsync(this.receiveBuffer, 0, (int)this.LocalReceiveBufferSize, token).ConfigureAwait(false);
                        if (count == 0)
                        {
                            return null;
                        }

                        var stream = new MemoryStream(this.receiveBuffer, 0, count, true, true);
                        var decoder = new BinaryDecoder(stream, this);
                        try
                        {
                            uint channelId;
                            uint messageType = decoder.ReadUInt32(null);
                            int messageLength = (int)decoder.ReadUInt32(null);
                            Debug.Assert(count == messageLength, "Bytes received not equal to encoded Message length");
                            switch (messageType)
                            {
                                case UaTcpMessageTypes.MSGF:
                                case UaTcpMessageTypes.MSGC:
                                    // header
                                    channelId = decoder.ReadUInt32(null);
                                    if (channelId != this.ChannelId)
                                    {
                                        throw new ServiceResultException(StatusCodes.BadTcpSecureChannelUnknown);
                                    }

                                    // symmetric security header
                                    var tokenId = decoder.ReadUInt32(null);

                                    // detect new token
                                    if (tokenId != this.currentServerTokenId)
                                    {
                                        this.currentServerTokenId = tokenId;

                                        // update with new keys
                                        if (this.symIsSigned)
                                        {
                                            this.symVerifier.Key = this.serverSigningKey;
                                            if (this.symIsEncrypted)
                                            {
                                                this.currentServerEncryptingKey = this.serverEncryptingKey;
                                                this.currentServerInitializationVector = this.serverInitializationVector;
                                                this.symDecryptor = this.symEncryptionAlgorithm.CreateDecryptor(this.currentServerEncryptingKey, this.currentServerInitializationVector);
                                            }
                                        }
                                    }

                                    plainHeaderSize = decoder.Position;

                                    // decrypt
                                    if (this.symIsEncrypted)
                                    {
                                        using (var symDecryptor = this.symEncryptionAlgorithm.CreateDecryptor(this.currentServerEncryptingKey, this.currentServerInitializationVector))
                                        {
                                            int inputCount = messageLength - plainHeaderSize;
                                            Debug.Assert(inputCount % symDecryptor.InputBlockSize == 0, "Input data is not an even number of encryption blocks.");
                                            symDecryptor.TransformBlock(this.receiveBuffer, plainHeaderSize, inputCount, this.receiveBuffer, plainHeaderSize);
                                            symDecryptor.TransformFinalBlock(this.receiveBuffer, messageLength, 0);
                                        }
                                    }

                                    // verify
                                    if (this.symIsSigned)
                                    {
                                        var datalen = messageLength - this.symSignatureSize;
                                        byte[] signature = this.symVerifier.ComputeHash(this.receiveBuffer, 0, datalen);
                                        if (!signature.SequenceEqual(this.receiveBuffer.AsArraySegment(datalen, this.symSignatureSize)))
                                        {
                                            throw new ServiceResultException(StatusCodes.BadSecurityChecksFailed);
                                        }
                                    }

                                    // read sequence header
                                    sequenceNumber = decoder.ReadUInt32(null);
                                    requestId = decoder.ReadUInt32(null);

                                    // body
                                    if (this.symIsEncrypted)
                                    {
                                        if (this.symEncryptionBlockSize > 256)
                                        {
                                            paddingHeaderSize = 2;
                                            paddingSize = BitConverter.ToInt16(this.receiveBuffer, messageLength - this.symSignatureSize - paddingHeaderSize);
                                        }
                                        else
                                        {
                                            paddingHeaderSize = 1;
                                            paddingSize = this.receiveBuffer[messageLength - this.symSignatureSize - paddingHeaderSize];
                                        }

                                        bodySize = messageLength - plainHeaderSize - SequenceHeaderSize - paddingSize - paddingHeaderSize - this.symSignatureSize;
                                    }
                                    else
                                    {
                                        bodySize = messageLength - plainHeaderSize - SequenceHeaderSize - this.symSignatureSize;
                                    }

                                    bodyStream.Write(this.receiveBuffer, plainHeaderSize + SequenceHeaderSize, bodySize);
                                    isFinal = messageType == UaTcpMessageTypes.MSGF;
                                    break;

                                case UaTcpMessageTypes.OPNF:
                                case UaTcpMessageTypes.OPNC:
                                    // header
                                    channelId = decoder.ReadUInt32(null);

                                    // asymmetric header
                                    var securityPolicyUri = decoder.ReadString(null);
                                    var serverCertificateByteString = decoder.ReadByteString(null);
                                    var clientThumbprint = decoder.ReadByteString(null);
                                    plainHeaderSize = decoder.Position;

                                    // decrypt
                                    if (this.asymIsEncrypted)
                                    {
                                        byte[] cipherTextBlock = new byte[this.asymLocalCipherTextBlockSize];
                                        int jj = plainHeaderSize;
                                        for (int ii = plainHeaderSize; ii < messageLength; ii += this.asymLocalCipherTextBlockSize)
                                        {
                                            Buffer.BlockCopy(this.receiveBuffer, ii, cipherTextBlock, 0, this.asymLocalCipherTextBlockSize);

                                            // decrypt with local private key.
                                            byte[] plainTextBlock = this.LocalPrivateKey.Decrypt(cipherTextBlock, this.asymEncryptionPadding);
                                            Debug.Assert(plainTextBlock.Length == this.asymLocalPlainTextBlockSize, "Decrypted block length was not as expected.");
                                            Buffer.BlockCopy(plainTextBlock, 0, this.receiveBuffer, jj, this.asymLocalPlainTextBlockSize);
                                            jj += this.asymLocalPlainTextBlockSize;
                                        }

                                        messageLength = jj;
                                        decoder.Position = plainHeaderSize;
                                    }

                                    // verify
                                    if (this.asymIsSigned)
                                    {
                                        // verify with remote public key.
                                        var datalen = messageLength - this.asymRemoteSignatureSize;
                                        if (!this.RemotePublicKey.VerifyData(this.receiveBuffer, 0, datalen, this.receiveBuffer.AsArraySegment(datalen, this.asymRemoteSignatureSize).ToArray(), this.asymSignatureHashAlgorithmName, RSASignaturePadding.Pkcs1))
                                        {
                                            throw new ServiceResultException(StatusCodes.BadSecurityChecksFailed);
                                        }
                                    }

                                    // sequence header
                                    sequenceNumber = decoder.ReadUInt32(null);
                                    requestId = decoder.ReadUInt32(null);

                                    // body
                                    if (this.asymIsEncrypted)
                                    {
                                        if (this.asymLocalCipherTextBlockSize > 256)
                                        {
                                            paddingHeaderSize = 2;
                                            paddingSize = BitConverter.ToInt16(this.receiveBuffer, messageLength - this.asymRemoteSignatureSize - paddingHeaderSize);
                                        }
                                        else
                                        {
                                            paddingHeaderSize = 1;
                                            paddingSize = this.receiveBuffer[messageLength - this.asymRemoteSignatureSize - paddingHeaderSize];
                                        }

                                        bodySize = messageLength - plainHeaderSize - SequenceHeaderSize - paddingSize - paddingHeaderSize - this.asymRemoteSignatureSize;
                                    }
                                    else
                                    {
                                        bodySize = messageLength - plainHeaderSize - SequenceHeaderSize - this.asymRemoteSignatureSize;
                                    }

                                    bodyStream.Write(this.receiveBuffer, plainHeaderSize + SequenceHeaderSize, bodySize);
                                    isFinal = messageType == UaTcpMessageTypes.OPNF;
                                    break;

                                case UaTcpMessageTypes.ERRF:
                                case UaTcpMessageTypes.MSGA:
                                case UaTcpMessageTypes.OPNA:
                                case UaTcpMessageTypes.CLOA:
                                    var code = (StatusCode)decoder.ReadUInt32(null);
                                    var message = decoder.ReadString(null);
                                    throw new ServiceResultException(code, message);

                                default:
                                    throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                            }

                            if (this.LocalMaxMessageSize > 0 && bodyStream.Position > this.LocalMaxMessageSize)
                            {
                                throw new ServiceResultException(StatusCodes.BadEncodingLimitsExceeded);
                            }
                        }
                        finally
                        {
                            decoder.Dispose();
                        }
                    }
                    while (!isFinal);
                    bodyStream.Seek(0L, SeekOrigin.Begin);
                    var nodeId = bodyDecoder.ReadNodeId(null);
                    IServiceResponse response;

                    // fast path
                    if (nodeId == PublishResponseNodeId)
                    {
                        response = new PublishResponse();
                    }
                    else if (nodeId == ReadResponseNodeId)
                    {
                        response = new ReadResponse();
                    }
                    else
                    {
                        // find node in dictionary
                        Type type2;
                        if (!BinaryEncodingIdToTypeDictionary.TryGetValue(NodeId.ToExpandedNodeId(nodeId, this.NamespaceUris), out type2))
                        {
                            throw new ServiceResultException(StatusCodes.BadEncodingError, "NodeId not registered in dictionary.");
                        }

                        // create response
                        response = (IServiceResponse)Activator.CreateInstance(type2);
                    }

                    // set properties from message stream
                    response.Decode(bodyDecoder);
                    return response;
                }
                finally
                {
                    bodyDecoder.Dispose();
                }
            }
            finally
            {
                this.receivingSemaphore.Release();
            }
        }
コード例 #38
0
        public async Task <IActionResult> SNS()
        {
            var results = new List <string>();

            var topicRequest = new CreateTopicRequest {
                Name = "borislav-topic-1"
            };
            var topicResponse = await _snsClient.CreateTopicAsync(topicRequest);

            results.Add($"Topic '{topicRequest.Name}' created with status {topicResponse.HttpStatusCode}");

            var topicAttrRequest = new SetTopicAttributesRequest
            {
                TopicArn       = topicResponse.TopicArn,
                AttributeName  = "DisplayName",
                AttributeValue = "Coding Test Results"
            };
            await _snsClient.SetTopicAttributesAsync(topicAttrRequest);

            var subscribeRequest = new SubscribeRequest
            {
                Endpoint = "*****@*****.**",
                Protocol = "email",
                TopicArn = topicResponse.TopicArn
            };
            SubscribeResponse subscribeResponse = await _snsClient.SubscribeAsync(subscribeRequest);

            results.Add($"Invitation sent by email with status {subscribeResponse.HttpStatusCode}");
            results.Add("Wait for up to 2 min for the user to confirm the subscription");

            // Wait for up to 2 minutes for the user to confirm the subscription.
            DateTime latest = DateTime.Now + TimeSpan.FromMinutes(2);

            while (DateTime.Now < latest)
            {
                var subsRequest = new ListSubscriptionsByTopicRequest
                {
                    TopicArn = topicResponse.TopicArn
                };

                var subs = _snsClient.ListSubscriptionsByTopicAsync(subsRequest).Result.Subscriptions;

                if (!string.Equals(subs[0].SubscriptionArn, "PendingConfirmation", StringComparison.Ordinal))
                {
                    break;
                }

                // Wait 15 seconds before trying again.
                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(15));
            }

            var publishRequest = new PublishRequest
            {
                Subject  = "Coding Test Results for " + DateTime.Today.ToShortDateString(),
                Message  = "All of today's coding tests passed",
                TopicArn = topicResponse.TopicArn
            };
            PublishResponse publishResponse = await _snsClient.PublishAsync(publishRequest);

            results.Add($"Message '{publishRequest.Message}' published with status {topicResponse.HttpStatusCode}");

            ViewBag.Results = new List <string>();
            ViewBag.Results.AddRange(results);

            return(View());
        }