Esempio n. 1
0
        public async Task Invoke(HttpContext context)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                return;
            }

            BasicAuthenticator basicAuthn = new BasicAuthenticator();

            SkunkLab.Security.Tokens.SecurityTokenType tokenType = Enum.Parse <SkunkLab.Security.Tokens.SecurityTokenType>(config.ClientTokenType, true);
            basicAuthn.Add(tokenType, config.ClientSymmetricKey, config.ClientIssuer, config.ClientAudience, context);
            IAuthenticator authn = basicAuthn;

            WebSocket socket = await context.WebSockets.AcceptWebSocketAsync();

            source = new CancellationTokenSource();
            ProtocolAdapter adapter = ProtocolAdapterFactory.Create(config, graphManager, context, socket, logger, authn, source.Token);

            container.Add(adapter.Channel.Id, adapter);
            adapter.OnClose += Adapter_OnClose;
            adapter.OnError += Adapter_OnError;
            adapter.Init();


            await adapter.Channel.OpenAsync();

            await _next(context);

            Console.WriteLine("Exiting WS Invoke");
        }
Esempio n. 2
0
        private void Adapter_OnError(object sender, ProtocolAdapterErrorEventArgs args)
        {
            //Trace.TraceError("{0} - Protocol Adapter on channel {1} threw error {2}", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), args.ChannelId, args.Error.Message);
            Console.WriteLine("{0} - Adpater exception - {1}", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), args.Error.Message);

            Exception inner = args.Error.InnerException;

            while (inner != null)
            {
                Console.WriteLine("{0} - Adapter Exception Inner - {1}", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), inner.Message);
                inner = inner.InnerException;
            }

            //Trace.WriteLine("------ Stack Trace -------");
            //Trace.TraceError(args.Error.StackTrace);
            //Trace.WriteLine("------ End Stack Trace -------");

            try
            {
                if (dict.ContainsKey(args.ChannelId))
                {
                    ProtocolAdapter adapter = dict[args.ChannelId];
                    dict.Remove(args.ChannelId);
                    adapter.Dispose();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0} - Exception disposing adapter Listener_OnError - {1}", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), ex.Message);
                //Trace.TraceWarning("{0} - TCP Listener exception disposing adapter Listener_OnError", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"));
                //Trace.TraceError("{0} - Adapter dispose exception Listener_OnError - '{1}'", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"),ex.Message);
                //Trace.TraceError("{0} - Adapter dispose stack trace Listener_OnError - {1}", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), ex.StackTrace);
            }
        }
Esempio n. 3
0
        public HttpResponseMessage Get()
        {
            try
            {
                SkunkLab.Security.Authentication.BasicAuthenticator authn = new SkunkLab.Security.Authentication.BasicAuthenticator();

                HttpContext context = HttpContext.Current;

                if (context.IsWebSocketRequest ||
                    context.IsWebSocketRequestUpgrading)
                {
                    PiraeusConfig config = Piraeus.Configuration.PiraeusConfigManager.Settings;

                    adapter          = ProtocolAdapterFactory.Create(config, Request, source.Token);
                    adapter.OnClose += Adapter_OnClose;
                    adapter.OnError += Adapter_OnError;
                    adapter.Init();
                    return(new HttpResponseMessage(HttpStatusCode.SwitchingProtocols));
                }
                else //long polling
                {
                    adapter            = ProtocolAdapterFactory.Create(config, Request, source.Token);
                    adapter.OnObserve += Adapter_OnObserve;
                    adapter.Init();
                    ThreadPool.QueueUserWorkItem(new WaitCallback(Listen), waitHandles[0]);
                    WaitHandle.WaitAll(waitHandles);

                    return(response);
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
        public async Task <HttpResponseMessage> Get()
        {
            source = new CancellationTokenSource();
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                try
                {
                    socket = await HttpContext.WebSockets.AcceptWebSocketAsync();

                    adapter          = ProtocolAdapterFactory.Create(config, graphManager, HttpContext, socket, null, authn, source.Token);
                    adapter.OnClose += Adapter_OnClose;
                    adapter.OnError += Adapter_OnError;
                    adapter.Init();
                    await adapter.Channel.OpenAsync();

                    return(new HttpResponseMessage(HttpStatusCode.SwitchingProtocols));
                }
                catch (Exception ex)
                {
                    StatusCode(500);
                    Console.WriteLine(ex.Message);
                    return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                }
            }
            else
            {
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
        }
Esempio n. 5
0
        public async Task Invoke(HttpContext context)
        {
            source = new CancellationTokenSource();
            if (context.Request.Method.ToUpperInvariant() == "POST")
            {
                //sending a message
                //adapter = ProtocolAdapterFactory.Create(config, context, source.Token);
                adapter = ProtocolAdapterFactory.Create(config, context, null, null, source.Token);
                adapter.Init();
            }
            else if (context.Request.Method.ToUpperInvariant() == "GET")
            {
                //long polling
                //adapter = ProtocolAdapterFactory.Create(config, context, source.Token);
                adapter            = ProtocolAdapterFactory.Create(config, context, null, null, source.Token);
                adapter.OnObserve += Adapter_OnObserve;
                adapter.Init();
                this.context = context;
                ThreadPool.QueueUserWorkItem(new WaitCallback(Listen), waitHandles[0]);
                WaitHandle.WaitAll(waitHandles);
                await adapter.Channel.CloseAsync();

                await _next(context);
            }
            else
            {
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Verify a new upload file's task data, if there are any task data for a new upload file, method will throw a Assert.Fail exception.
        /// </summary>
        /// <param name="uploadedFileUrl">A parameter represents a URL of document item which the method check.</param>
        /// <param name="taskIndex">A parameter represents the index of a z:row item in a zrow collection. Each z:row item means a task item.It start on "Zero".</param>
        protected void VerifyAssignToValueForSingleTodoItem(string uploadedFileUrl, int taskIndex)
        {
            GetToDosForItemResponseGetToDosForItemResult todosAfterStartTask = ProtocolAdapter.GetToDosForItem(uploadedFileUrl);

            if (null == todosAfterStartTask || null == todosAfterStartTask.ToDoData || null == todosAfterStartTask.ToDoData.xml ||
                null == todosAfterStartTask.ToDoData.xml.data || null == todosAfterStartTask.ToDoData.xml.data.Any)
            {
                this.Site.Assert.Fail("The response of GetToDosForItem operation should contain valid data.");
            }

            this.Site.Assert.AreEqual(1, todosAfterStartTask.ToDoData.xml.data.Any.Length, "The response of GetToDosForItem operation for new file should contain only one task data.");
            string expectedAssignToValue = Common.GetConfigurationPropertyValue("KeyWordForAssignedToField", this.Site).ToLower();

            // Get the assign to value from actual response, "ows_AssignedTo" means get required field "AssignedTo" of task list.
            string actualAssignToValue = Common.GetZrowAttributeValue(todosAfterStartTask.ToDoData.xml.data.Any, taskIndex, "ows_AssignedTo");

            this.Site.Assert.IsFalse(string.IsNullOrEmpty(actualAssignToValue), "The response of GetToDosForItem should contain valid value for [AssignedTo] field.");

            bool isassignToExpectedValue = actualAssignToValue.IndexOf(expectedAssignToValue, StringComparison.OrdinalIgnoreCase) >= 0;

            this.Site.Assert.IsTrue(
                isassignToExpectedValue,
                @"The actual ""AssignedTo"" value [{0}] should contain to expected keyword value[{1}]",
                actualAssignToValue,
                expectedAssignToValue);
        }
Esempio n. 7
0
        public async Task <HttpResponseMessage> Get()
        {
            source = new CancellationTokenSource();
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                try
                {
                    socket = await HttpContext.WebSockets.AcceptWebSocketAsync();

                    adapter = ProtocolAdapterFactory.Create(config, graphManager, HttpContext, socket, null, authn,
                                                            source.Token);
                    adapter.OnClose += Adapter_OnClose;
                    adapter.OnError += Adapter_OnError;
                    adapter.Init();
                    await adapter.Channel.OpenAsync();

                    await logger.LogDebugAsync("Websocket channel open.");

                    return(new HttpResponseMessage(HttpStatusCode.SwitchingProtocols));
                }
                catch (Exception ex)
                {
                    StatusCode(500);
                    await logger.LogErrorAsync(ex, "WebSocket get - 500");

                    return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                }
            }

            await logger.LogWarningAsync($"WebSocket status code {HttpStatusCode.NotFound}");

            return(new HttpResponseMessage(HttpStatusCode.NotFound));
        }
Esempio n. 8
0
        public async Task Get()
        {
            
            source = new CancellationTokenSource();
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                //string subprotocol = HttpContext.WebSockets.WebSocketRequestedProtocols[0];
                socket = await HttpContext.WebSockets.AcceptWebSocketAsync();
                //socket = HttpContext.WebSockets.AcceptWebSocketAsync().GetAwaiter().GetResult();


                try
                {
                    //adapter = ProtocolAdapterFactory.Create(config, HttpContext, socket, authn, source.Token);
                    adapter = ProtocolAdapterFactory.Create(config, HttpContext, socket, null, authn, source.Token);
                    adapter.OnClose += Adapter_OnClose;
                    adapter.OnError += Adapter_OnError;
                    adapter.Init();
                    //StatusCode(101);
                    //return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
                }
                catch(Exception ex)
                {
                    StatusCode(500);
                    Console.WriteLine(ex.Message);
                    //return new HttpResponseMessage(HttpStatusCode.InternalServerError);
                }
            }
            else
            {
                //return new HttpResponseMessage(HttpStatusCode.NotFound);
            }
        }
Esempio n. 9
0
        public void MSWWSP_S02_TC04_GetWorkflowTaskData_Success()
        {
            // Upload a file.
            string uploadFileUrl = this.UploadFileToSut(DocLibraryName);

            this.VerifyTaskDataOfNewUploadFile(uploadFileUrl);

            // Start a normal work flow
            string taskIdValue = this.StartATaskWithNewFile(uploadFileUrl, false);

            // Verify whether the task is assign to expected user group for new uploaded file, only have one task currently.
            this.VerifyAssignToValueForSingleTodoItem(uploadFileUrl, 0);

            // Call method GetWorkflowTaskData to retrieve data about a single workflow task.
            GetWorkflowTaskDataResponseGetWorkflowTaskDataResult askDataResult = ProtocolAdapter.GetWorkflowTaskData(uploadFileUrl, int.Parse(taskIdValue), new Guid(TaskListId));

            // If the response from the GetWorkflowTaskData is not null, then R295 should be covered.
            // Verify MS-WWSP requirement: MS-WWSP_R295
            Site.CaptureRequirementIfIsNotNull(
                askDataResult,
                295,
                @"[In GetWorkflowTaskData] The protocol client sends a GetWorkflowTaskDataSoapIn request message, and the protocol server responds with a GetWorkflowTaskDataSoapOut response message.");

            // For a new upload file, start only one task currently, if the GetWorkflowTaskData operation return only one record of the task, then R411, R292, R196, R298 and R307 should be covered.
            // Verify MS-WWSP requirement: MS-WWSP_R411
            Site.CaptureRequirementIfAreEqual(
                1,
                askDataResult.Any.Length,
                411,
                @"[In Message Processing Events and Sequencing Rules] GetWorkflowTaskData retrieves data about a single workflow task.");

            // Verify MS-WWSP requirement: MS-WWSP_R292
            Site.CaptureRequirementIfAreEqual(
                1,
                askDataResult.Any.Length,
                292,
                @"[In GetWorkflowTaskData] This operation retrieves data about a single workflow task.");

            // Verify MS-WWSP requirement: MS-WWSP_R196
            Site.CaptureRequirementIfAreEqual(
                1,
                askDataResult.Any.Length,
                196,
                @"[In GetWorkflowDataForItem] This operation[GetWorkflowDataForItem] retrieves some of the same data that GetToDosForItem and GetTemplatesForItem retrieve, as well as additional data.");

            // Verify MS-WWSP requirement: MS-WWSP_R298
            Site.CaptureRequirementIfAreEqual(
                1,
                askDataResult.Any.Length,
                298,
                @"[In Messages] GetWorkflowTaskDataSoapOut specifies the response to a request to retrieve data about a single workflow task.");

            // Verify MS-WWSP requirement: MS-WWSP_R307
            Site.CaptureRequirementIfAreEqual(
                1,
                askDataResult.Any.Length,
                307,
                @"[In Elements] GetWorkflowTaskDataResponse contains the response to a request to retrieve data about a single workflow task.");
        }
Esempio n. 10
0
 public HttpResponseMessage Post()
 {
     context          = HttpContext;
     source           = new CancellationTokenSource();
     adapter          = ProtocolAdapterFactory.Create(config, graphManager, context, null, null, source.Token);
     adapter.OnClose += Adapter_OnClose;
     adapter.Init();
     return(new HttpResponseMessage(HttpStatusCode.Accepted));
 }
Esempio n. 11
0
        public async Task StartAsync()
        {
            listener.ExclusiveAddressUse = false;
            listener.DontFragment        = true;
            listener.Client.Bind(localEP);

            await logger.LogDebugAsync($"UDP Gateway started on {localEP.Address} and port {localEP.Port}");

            while (!token.IsCancellationRequested)
            {
                try
                {
                    UdpReceiveResult result = await listener.ReceiveAsync();

                    if (result.Buffer.Length > 0)
                    {
                        string key = CreateNamedKey($"{result.RemoteEndPoint.Address}:{result.RemoteEndPoint.Port}");
                        if (cache.Contains(key))
                        {
                            Tuple <ProtocolAdapter, CancellationTokenSource> tuple =
                                (Tuple <ProtocolAdapter, CancellationTokenSource>)cache.Get(key);
                            if (tuple != null && tuple.Item1 != null)
                            {
                                cache.Get(CreateNamedKey(tuple.Item1.Channel.Id));
                                if (tuple.Item1.Channel.State == ChannelState.Open)
                                {
                                    await tuple.Item1.Channel.AddMessageAsync(result.Buffer);
                                }
                            }
                        }
                        else
                        {
                            CancellationTokenSource cts     = new CancellationTokenSource();
                            ProtocolAdapter         adapter = ProtocolAdapterFactory.Create(config, graphManager, authn,
                                                                                            listener, result.RemoteEndPoint, logger, cts.Token);
                            string namedKey = CreateNamedKey(adapter.Channel.Id);
                            cache.Add(namedKey, key, GetCachePolicy(5.0 * 60.0));
                            cache.Add(key, new Tuple <ProtocolAdapter, CancellationTokenSource>(adapter, cts),
                                      GetCachePolicy(5.0 * 60.0));

                            adapter.OnError   += Adapter_OnError;
                            adapter.OnClose   += Adapter_OnClose;
                            adapter.OnObserve += Adapter_OnObserve;
                            await adapter.Channel.OpenAsync();

                            adapter.Init();
                            await adapter.Channel.AddMessageAsync(result.Buffer);
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger?.LogErrorAsync(ex, "Fault UDP listener.");
                    throw ex;
                }
            }
        }
Esempio n. 12
0
 private void Adapter_OnError(object sender, ProtocolAdapterErrorEventArgs e)
 {
     Console.WriteLine($"Adapter OnError - {e.Error.Message}");
     if (container.ContainsKey(e.ChannelId))
     {
         ProtocolAdapter adapter = container[e.ChannelId];
         adapter.Channel.CloseAsync().GetAwaiter();
         Console.WriteLine("Adapter channel closed due to error.");
     }
 }
        public async void SendRequestAsync_With_No_StreamingRequest_Should_Fail()
        {
            var requestHandler  = new Mock <RequestHandler>();
            var requestManager  = new Mock <RequestManager>();
            var payloadSender   = new Mock <PayloadSender>();
            var payloadReceiver = new Mock <PayloadReceiver>();
            var protocolAdapter = new ProtocolAdapter(requestHandler.Object, requestManager.Object, payloadSender.Object, payloadReceiver.Object);

            await Assert.ThrowsAsync <ArgumentNullException>(() => protocolAdapter.SendRequestAsync(null));
        }
        public void MSWWSP_S03_TC03_AlterToDo_IgnoreItem()
        {
            // Upload a file.
            string uploadFileUrl = this.UploadFileToSut(DocLibraryName);

            this.VerifyTaskDataOfNewUploadFile(uploadFileUrl);

            // Start a normal work flow
            string taskIdValue = this.StartATaskWithNewFile(uploadFileUrl, false);

            // Verify whether the task is assign to expected user group. for new uploaded file, only have one task currently.
            this.VerifyAssignToValueForSingleTodoItem(uploadFileUrl, 0);

            // initialize the value which will be updated in AlterToDo operation, and this value is unique.
            string alaterValueFirst = this.GenerateRandomValue();

            // Call method AlterToDo to modify the values of fields on a workflow task.
            XmlElement taskData = this.GetAlerToDoTaskData(this.Site, alaterValueFirst);
            AlterToDoResponseAlterToDoResult alterToDoResult = ProtocolAdapter.AlterToDo(uploadFileUrl, int.Parse(taskIdValue), new Guid(TaskListId), taskData);

            // Call method GetToDosForItem to get a set of Workflow Tasks for a document.
            GetToDosForItemResponseGetToDosForItemResult todosAfterStartTask = ProtocolAdapter.GetToDosForItem(uploadFileUrl);
            var matchAttributeitemsFirst = from XmlAttribute attributeitem in todosAfterStartTask.ToDoData.xml.data.Any[0].Attributes
                                           where attributeitem.Value.Equals(alaterValueFirst, StringComparison.OrdinalIgnoreCase)
                                           select attributeitem;

            // initialize an not existing file Url.
            string notExistingFileUrl = this.GenerateRandomValue();

            // initialize the value which will be updated in AlterToDo operation, and this value is unique.
            string alaterValueSecond = this.GenerateRandomValue();

            // Call method AlterToDo to modify the values of fields on a workflow task.
            taskData        = this.GetAlerToDoTaskData(this.Site, alaterValueSecond);
            alterToDoResult = ProtocolAdapter.AlterToDo(notExistingFileUrl, int.Parse(taskIdValue), new Guid(TaskListId), taskData);

            // Call method GetToDosForItem to get a set of Workflow Tasks for a document.
            todosAfterStartTask = ProtocolAdapter.GetToDosForItem(uploadFileUrl);
            var matchAttributeitemsSecond = from XmlAttribute attributeitem in todosAfterStartTask.ToDoData.xml.data.Any[0].Attributes
                                            where attributeitem.Value.Equals(alaterValueSecond, StringComparison.OrdinalIgnoreCase)
                                            select attributeitem;

            // Verify MS-WWSP requirement: MS-WWSP_R97
            // If the altered value present in response of GetToDosForItem operation, the AlterToDo operation succeed.
            bool isVerifyR97 = matchAttributeitemsFirst.Count() == 1;

            // If the task is modified successfully in the first and second AlterToDo operation, then R97 should be covered.
            isVerifyR97 = isVerifyR97 && matchAttributeitemsSecond.Count() == 1;

            // Verify MS-WWSP requirement: MS-WWSP_R97
            Site.CaptureRequirementIfIsTrue(
                isVerifyR97,
                97,
                @"[In AlterToDo] Set the different string as the item value, server reply same if the site (2) of the SOAP request URL contains a list with the specified todoListId.");
        }
Esempio n. 15
0
        private void Adapter_OnError(object sender, ProtocolAdapterErrorEventArgs e)
        {
            logger.LogErrorAsync(e.Error, "Adapter OnError").GetAwaiter();

            if (container.ContainsKey(e.ChannelId))
            {
                ProtocolAdapter adapter = container[e.ChannelId];
                adapter.Channel.CloseAsync().GetAwaiter();
                logger.LogWarningAsync("Adapter channel closed due to error.").GetAwaiter();
            }
        }
Esempio n. 16
0
        private void ManageConnection(TcpClient client)
        {
            ProtocolAdapter adapter = ProtocolAdapterFactory.Create(config, authn, client, logger, token);

            dict.Add(adapter.Channel.Id, adapter);
            adapter.OnError += Adapter_OnError;
            adapter.OnClose += Adapter_OnClose;
            adapter.Init();
            adapter.Channel.OpenAsync().LogExceptions();
            adapter.Channel.ReceiveAsync().LogExceptions();
        }
            public async void GetProtocol_Valid_IsProtocol_Test()
            {
                //Arrange
                const int idToRead = 0;
                _repositoryMock.Setup(r => r.Read(idToRead)).Returns(Task.FromResult(_storedProtocol));
                var protocolAdapter = new ProtocolAdapter(_repositoryMock.Object);

                //Act
                var returnedProtocol = await protocolAdapter.Read(idToRead);

                //Assert
                Assert.IsInstanceOfType(returnedProtocol, typeof(Protocol));
            }
            public void CreateProtocol_Success_Test()
            {
                //Arrange 
                const int expectedReturnId = 0;
                _repositoryMock.Setup(r => r.Create(_storedProtocol)).Returns(Task.FromResult(expectedReturnId));
                var protocolAdapter = new ProtocolAdapter(_repositoryMock.Object);

                //Act
                var actualId = protocolAdapter.Read(_storedProtocol.Id).Id;

                //Assert
                Assert.IsTrue(expectedReturnId == actualId);
            }
Esempio n. 19
0
        public async Task StartAsync()
        {
            UdpClient listener = new UdpClient();

            listener.ExclusiveAddressUse = false;
            listener.DontFragment        = true;
            listener.Client.Bind(localEP);

            Console.WriteLine("UDP listener initialized on port {0}", localEP.Port);

            while (!token.IsCancellationRequested)
            {
                try
                {
                    UdpReceiveResult result = await listener.ReceiveAsync();

                    if (result.Buffer.Length > 0)
                    {
                        string key = String.Format("{0}:{1}", result.RemoteEndPoint.Address.ToString(), result.RemoteEndPoint.Port);

                        if (!cache.ContainsKey(key))
                        {
                            CancellationTokenSource cts = new CancellationTokenSource();
                            //ProtocolAdapter adapter = ProtocolAdapterFactory.Create(config, authn, listener, result.RemoteEndPoint, cts.Token);
                            ProtocolAdapter adapter = ProtocolAdapterFactory.Create(config, authn, listener, result.RemoteEndPoint, null, cts.Token);
                            adapter.OnError += Adapter_OnError;
                            adapter.OnClose += Adapter_OnClose;
                            await adapter.Channel.OpenAsync();

                            container.Add(adapter.Channel.Id, key);
                            cache.Add(key, new Tuple <ProtocolAdapter, CancellationTokenSource>(adapter, cts));
                            adapter.Init();
                            await adapter.Channel.AddMessageAsync(result.Buffer);
                        }
                        else
                        {
                            Tuple <ProtocolAdapter, CancellationTokenSource> tuple = cache[key];
                            if (tuple.Item1.Channel.State == ChannelState.Open)
                            {
                                await tuple.Item1.Channel.AddMessageAsync(result.Buffer);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    OnError?.Invoke(this, new ServerFailedEventArgs("UDP", localEP.Port));
                    //await Log.LogErrorAsync("UDP server channel error {0}", ex.Message);
                }
            }
        }
Esempio n. 20
0
 public HttpResponseMessage Post()
 {
     try
     {
         adapter          = ProtocolAdapterFactory.Create(config, Request, source.Token);
         adapter.OnClose += Adapter_OnClose;
         adapter.Init();
         return(new HttpResponseMessage(HttpStatusCode.Accepted));
     }
     catch (Exception ex)
     {
         return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="WebSocketServer"/> class.
        /// Throws <see cref="ArgumentNullException"/> on null arguments.
        /// </summary>
        /// <param name="socket">The <see cref="WebSocket"/> of the underlying connection for this server to be built on top of.</param>
        /// <param name="requestHandler">A <see cref="RequestHandler"/> to process incoming messages received by this server.</param>
        public WebSocketServer(WebSocket socket, RequestHandler requestHandler)
        {
            if (socket == null)
            {
                throw new ArgumentNullException(nameof(socket));
            }

            _websocketTransport     = new WebSocketTransport(socket);
            _requestHandler         = requestHandler ?? throw new ArgumentNullException(nameof(requestHandler));
            _requestManager         = new RequestManager();
            _sender                 = new PayloadSender();
            _sender.Disconnected   += OnConnectionDisconnected;
            _receiver               = new PayloadReceiver();
            _receiver.Disconnected += OnConnectionDisconnected;
            _protocolAdapter        = new ProtocolAdapter(_requestHandler, _requestManager, _sender, _receiver);
        }
Esempio n. 22
0
 private async void Adapter_OnClose(object sender, ProtocolAdapterCloseEventArgs args)
 {
     try
     {
         if (dict.ContainsKey(args.ChannelId))
         {
             ProtocolAdapter adapter = dict[args.ChannelId];
             dict.Remove(args.ChannelId);
             adapter.Dispose();
         }
     }
     catch (Exception ex)
     {
         await logger.LogErrorAsync(ex, "Disposing adapter.");
     }
 }
Esempio n. 23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NamedPipeServer"/> class.
        /// Throws <see cref="ArgumentNullException"/> on null arguments.
        /// </summary>
        /// <param name="baseName">The named pipe to connect to.</param>
        /// <param name="requestHandler">A <see cref="RequestHandler"/> to process incoming messages received by this server.</param>
        /// <param name="autoReconnect">Optional setting to determine if the server sould attempt to reconnect
        /// automatically on disconnection events. Defaults to true.
        /// </param>
        public NamedPipeServer(string baseName, RequestHandler requestHandler, bool autoReconnect = true)
        {
            if (string.IsNullOrWhiteSpace(baseName))
            {
                throw new ArgumentNullException(nameof(baseName));
            }

            _baseName               = baseName;
            _requestHandler         = requestHandler ?? throw new ArgumentNullException(nameof(requestHandler));
            _autoReconnect          = autoReconnect;
            _requestManager         = new RequestManager();
            _sender                 = new PayloadSender();
            _sender.Disconnected   += OnConnectionDisconnected;
            _receiver               = new PayloadReceiver();
            _receiver.Disconnected += OnConnectionDisconnected;
            _protocolAdapter        = new ProtocolAdapter(_requestHandler, _requestManager, _sender, _receiver);
        }
Esempio n. 24
0
        public async Task StopAsync()
        {
            await logger?.LogInformationAsync(
                $"UDP Listener stopping on Address {localEP.Address} and Port {localEP.Port}");

            if ((dict != null) & (dict.Count > 0))
            {
                var keys = dict.Keys;
                if (keys != null && keys.Count > 0)
                {
                    try
                    {
                        string[] keysArray = keys.ToArray();
                        foreach (var key in keysArray)
                        {
                            if (dict.ContainsKey(key))
                            {
                                ProtocolAdapter adapter = dict[key];
                                dict.Remove(key);
                                try
                                {
                                    adapter.Dispose();
                                    await logger.LogWarningAsync(
                                        $"UDP Listener stopping and dispose Protcol adapter {key}");
                                }
                                catch (Exception ex)
                                {
                                    await logger.LogErrorAsync(ex,
                                                               "Fault dispose protcol adaper while Stopping UDP Listener - {ex.Message}");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        await logger.LogErrorAsync(ex, "UDP Listener fault during stop.'");
                    }
                }
            }
            else
            {
                await logger.LogWarningAsync("No protocol adapters in TCP Listener dictionary to dispose and remove");
            }

            listener.Close();
        }
Esempio n. 25
0
        private void Adapter_OnClose(object sender, ProtocolAdapterCloseEventArgs e)
        {
            logger.LogInformationAsync("Adapter closing.").GetAwaiter();
            ProtocolAdapter adapter = null;

            try
            {
                if (container.ContainsKey(e.ChannelId))
                {
                    adapter = container[e.ChannelId];
                    logger.LogInformationAsync("Adapter on close channel id found adapter to dispose.").GetAwaiter();
                }
                else
                {
                    logger.LogInformationAsync("Adapter on close did not find a channel id available for the adapter.")
                    .GetAwaiter();
                }

                if (adapter != null && adapter.Channel != null && (adapter.Channel.State == ChannelState.Closed ||
                                                                   adapter.Channel.State == ChannelState.Aborted ||
                                                                   adapter.Channel.State ==
                                                                   ChannelState.ClosedReceived ||
                                                                   adapter.Channel.State == ChannelState.CloseSent))
                {
                    adapter.Dispose();
                    logger.LogInformationAsync("Adapter disposed.").GetAwaiter();
                }
                else
                {
                    try
                    {
                        logger.LogInformationAsync("Adpater trying to close channel.").GetAwaiter();
                        adapter.Channel.CloseAsync().GetAwaiter();
                        logger.LogInformationAsync("Adapter has closed the channel").GetAwaiter();
                    }
                    catch { }

                    adapter.Dispose();
                    logger.LogWarningAsync("Adapter disposed by default").GetAwaiter();
                }
            }
            catch (Exception ex)
            {
                logger.LogErrorAsync(ex, "Adapter on close fault").GetAwaiter();
            }
        }
Esempio n. 26
0
        public async Task StopAsync()
        {
            logger?.LogInformation("TCP Listener stopping on Address {0} and Port {1}", serverIP.ToString(), serverPort);
            //dispose all adapters first
            if (dict != null & dict.Count > 0)
            {
                var keys = dict.Keys;
                if (keys != null && keys.Count > 0)
                {
                    try
                    {
                        string[] keysArray = keys.ToArray();
                        foreach (var key in keysArray)
                        {
                            if (dict.ContainsKey(key))
                            {
                                ProtocolAdapter adapter = dict[key];
                                dict.Remove(key);
                                try
                                {
                                    adapter.Dispose();
                                    logger.LogWarning("TCP Listener stopping and dispose Protcol adapter {0}", key);
                                }
                                catch (Exception ex)
                                {
                                    logger.LogError("Fault dispose protcol adaper while Stopping TCP Listener - {0}", ex.Message);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.LogError("{TCP Listener fault during stop '{0}'", ex.Message);
                    }
                }
            }
            else
            {
                logger.LogWarning("No protocol adapters in TCP Listener dictionary to dispose and remove");
            }

            listener.Stop();

            await Task.CompletedTask;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="WebSocketClient"/> class.
        /// Throws <see cref="ArgumentNullException"/> if URL is null, empty, or whitespace.
        /// </summary>
        /// <param name="url">The URL of the remote server to connect to.</param>
        /// <param name="requestHandler">Optional <see cref="RequestHandler"/> to process incoming messages received by this server.</param>
        /// <param name="handlerContext">Optional context for the <see cref="RequestHandler"/> to operate within.</param>
        public WebSocketClient(string url, RequestHandler requestHandler = null, object handlerContext = null)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                throw new ArgumentNullException(nameof(url));
            }

            _url            = url;
            _requestHandler = requestHandler;
            _requestManager = new RequestManager();

            _sender   = new PayloadSender();
            _receiver = new PayloadReceiver();

            _protocolAdapter = new ProtocolAdapter(_requestHandler, _requestManager, _sender, _receiver, handlerContext);

            IsConnected = false;
        }
Esempio n. 28
0
        /// <summary>
        /// Start workflow task for specified document item and record the task id in order to cleanup the task in test suite clean up process.
        /// </summary>
        /// <param name="uploadedFileUrl">A parameter represents a URL of document item where the task starts.</param>
        /// <param name="isClaim">A parameter represents a Boolean value indicate whether the task is started for Claim usage.</param>
        /// <returns>A return value represents the id of the task started by this method.</returns>
        protected string StartATaskWithNewFile(string uploadedFileUrl, bool isClaim)
        {
            if (string.IsNullOrEmpty(uploadedFileUrl))
            {
                throw new ArgumentException("Should specify valid value to indicate the URL of a uploaded file", "uploadedFileUrl");
            }

            GetToDosForItemResponseGetToDosForItemResult todosInfo = null;

            try
            {
                XmlElement startWorkFlowData = null;
                if (isClaim)
                {
                    startWorkFlowData = this.GetStartWorkflowParameterForClaim(this.Site);
                }
                else
                {
                    string assignToUserValue = Common.GetConfigurationPropertyValue("MSWWSPTestAccount", this.Site);
                    startWorkFlowData = this.GetStartWorkflowParameter(this.Site, assignToUserValue);
                }

                Guid currentWorkflowAsscociationId = new Guid(WorkflowAssociationId);
                ProtocolAdapter.StartWorkflow(uploadedFileUrl, currentWorkflowAsscociationId, startWorkFlowData);
                todosInfo = ProtocolAdapter.GetToDosForItem(uploadedFileUrl);
            }
            catch (SoapException soapEx)
            {
                throw new Exception("There are errors generated during start workflow task and GetToDos process.", soapEx);
            }

            // Get the task id from the response. there have only one task data in the response, because test suite only start one for new upload file.
            string taskId = this.GetZrowAttributeValueFromGetToDosForItemResponse(todosInfo, 0, "ows_ID");

            if (string.IsNullOrEmpty(taskId))
            {
                this.Site.Assert.Fail("Could Not get the id of started task from the document item[{0}]", uploadedFileUrl);
            }

            StartedTaskIdsRecorder.Add(taskId);
            return(taskId);
        }
Esempio n. 29
0
        /// <summary>
        /// Verify a new upload file's task data, if there are any task data for a new upload file, method will throw a Assert.Fail exception.
        /// </summary>
        /// <param name="uploadedFileUrl">A parameter represents a URL of document item which the method check.</param>
        protected void VerifyTaskDataOfNewUploadFile(string uploadedFileUrl)
        {
            if (string.IsNullOrEmpty(uploadedFileUrl))
            {
                throw new ArgumentException("Should specify valid value to indicate the URL of a uploaded file", "uploadedFileUrl");
            }

            GetToDosForItemResponseGetToDosForItemResult gettodosResult = ProtocolAdapter.GetToDosForItem(uploadedFileUrl);

            this.Site.Assert.IsNotNull(gettodosResult, "The response of GetToDosForItem operation should have instance.");

            // Verify there are no any task data for the new upload file.
            if (gettodosResult.ToDoData != null && gettodosResult.ToDoData.xml != null && gettodosResult.ToDoData.xml != null &&
                gettodosResult.ToDoData.xml.data != null && gettodosResult.ToDoData.xml.data.Any != null && gettodosResult.ToDoData.xml.data.Any.Length > 0)
            {
                this.Site.Assert.Fail(
                    "The response of GetToDosForItem operation should not contain any task data for a new uploaded file, actual task number:[{0}]",
                    gettodosResult.ToDoData.xml.data.Any.Length);
            }
        }
Esempio n. 30
0
        public IActionResult Get()
        {
            context            = HttpContext;
            source             = new CancellationTokenSource();
            adapter            = ProtocolAdapterFactory.Create(config, graphManager, context, null, null, source.Token);
            adapter.OnObserve += Adapter_OnObserve;
            adapter.Init();
            ThreadPool.QueueUserWorkItem(Listen, waitHandles[0]);
            WaitHandle.WaitAll(waitHandles);
            Task task = adapter.Channel.CloseAsync();

            Task.WhenAll(task);
            Response.Headers.Add("x-sl-resource", longpollResource);
            Response.ContentLength = longpollValue.Length;
            Response.ContentType   = contentType;
            ReadOnlyMemory <byte> rom = new ReadOnlyMemory <byte>(longpollValue);

            Response.BodyWriter.WriteAsync(rom);
            return(StatusCode(200));
        }
Esempio n. 31
0
        private void Adapter_OnClose(object sender, ProtocolAdapterCloseEventArgs args)
        {
            //Trace.TraceWarning("{0} - Protocol adapter on channel {1} closing.", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), args.ChannelId);

            try
            {
                if (dict.ContainsKey(args.ChannelId))
                {
                    ProtocolAdapter adapter = dict[args.ChannelId];
                    dict.Remove(args.ChannelId);
                    adapter.Dispose();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0} - Exception disposing adapter Listener_OnClose - {1}", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), ex.Message);
                //Trace.TraceWarning("{0} - TCP Listener exception disposing adapter Listener_OnClose", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"));
                //Trace.TraceError("{0} - Adapter dispose exception Listener_OnClose - '{1}'", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"),ex.Message);
                //Trace.TraceError("{0} - Adapter dispose stack trace Listener_OnClose - {1}", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), ex.StackTrace);
            }
        }
Esempio n. 32
0
        public void MSWWSP_S02_TC05_GetWorkflowTaskData_IgnoreItem()
        {
            // Upload a file.
            string uploadFileUrl = this.UploadFileToSut(DocLibraryName);

            this.VerifyTaskDataOfNewUploadFile(uploadFileUrl);

            // Start a normal work flow
            string taskIdValue = this.StartATaskWithNewFile(uploadFileUrl, false);

            // Verify whether the task is assign to expected user group. for new uploaded file, only have one task currently.
            this.VerifyAssignToValueForSingleTodoItem(uploadFileUrl, 0);

            // Call method GetWorkflowTaskData to retrieve data about a single workflow task.
            GetWorkflowTaskDataResponseGetWorkflowTaskDataResult askDataResult = ProtocolAdapter.GetWorkflowTaskData(uploadFileUrl, int.Parse(taskIdValue), new Guid(TaskListId));

            if (askDataResult == null || askDataResult.Any.Length == 0)
            {
                this.Site.Assume.Fail("GetWorkflowTaskData operation is failed, the response is null.");
            }

            // Initialize an invalid file URL.
            string notExistFileUrl = this.GenerateRandomValue().ToString();

            GetWorkflowTaskDataResponseGetWorkflowTaskDataResult askDataResultInvalieURL = ProtocolAdapter.GetWorkflowTaskData(notExistFileUrl, int.Parse(taskIdValue), new Guid(TaskListId));

            if (askDataResultInvalieURL == null || askDataResultInvalieURL.Any.Length == 0)
            {
                this.Site.Assume.Fail("GetWorkflowTaskData operation is failed when the file URL is not existing.");
            }

            // Call method GetWorkflowTaskData to retrieve data about a single workflow task, with an invalid URL.
            // If the server replay the same, then R313 should be covered.
            // Verify MS-WWSP requirement: MS-WWSP_R313
            Site.CaptureRequirementIfAreEqual(
                askDataResult.Any.Length,
                askDataResultInvalieURL.Any.Length,
                313,
                @"[In GetWorkflowTaskData] Set the different string as the item value, server reply same if the site (2) of the SOAP request URL contains a list with the specified ListId.");
        }
            public async void GetProtocol_Invalid_NoExistingProtocol_Test()
            {
                //Arrange
                const int idToRead = 0;
                _repositoryMock.Setup(r => r.Read(idToRead));
                var adapter = new ProtocolAdapter(_repositoryMock.Object);

                //Act
                var returnedProtocol = await adapter.Read(idToRead);

                //Assert
                Assert.IsNull(returnedProtocol);
            }
            public void GetAllProtocols_Valid_ReturnsCorrectProtocols_Test()
            {
                // TODO add property values 
                //Arrange
                var protocol1 = new StoredProtocol {};
                var protocol2 = new StoredProtocol {};
                var protocol3 = new StoredProtocol {};
                var protocolList = new List<StoredProtocol> { protocol1, protocol2, protocol3 }.AsQueryable();

                _repositoryMock.Setup(r => r.Read()).Returns(protocolList);
                var adapter = new ProtocolAdapter(_repositoryMock.Object);

                //Act
                var result = adapter.Read();
                var actualProtocols = result.ToList();

                //Assert
                var counter = 0;
                foreach (var actualProtocol in protocolList.AsEnumerable())
                {
                    var returnedProtocol = actualProtocols[counter];
                    // Todo add property asserts 
                    Assert.IsTrue(returnedProtocol.StudyName == actualProtocol.StudyName);
                    counter++;
                }

            }
            public async void DeleteProtocol_Success_Test()
            {
                //Arrange
                var repositoryMock = new Mock<IRepository<StoredProtocol>>();
                const int toDeleteId = 0;
                repositoryMock.Setup(r => r.DeleteIfExists(toDeleteId)).Returns(Task.FromResult(true));
                var adapter = new ProtocolAdapter(repositoryMock.Object);

                //Act
                var result = await adapter.DeleteIfExists(toDeleteId);

                //Assert
                Assert.IsTrue(result);
            }
            [ExpectedException(typeof(NullReferenceException))] // Assert 
            public async void DeleteProtocol_Fail_ProtocolDoesNotExist_Test()
            {
                //Arrange
                var repositoryMock = new Mock<IRepository<StoredProtocol>>();
                const int toDeleteId = 0;
                repositoryMock.Setup(r => r.DeleteIfExists(toDeleteId)).Returns(Task.FromResult(false));
                var adapter = new ProtocolAdapter(repositoryMock.Object);

                //Act
                await adapter.DeleteIfExists(toDeleteId);
            }
            public async void GetProtocol_Valid_CorrectProtocolInfo_Test()
            {
                //Arrange
                const int idToRead = 0;
                _repositoryMock.Setup(r => r.Read(idToRead)).Returns(Task.FromResult(_storedProtocol));
                var adapter = new ProtocolAdapter(_repositoryMock.Object);

                //Act
                var actualProtocol = await adapter.Read(idToRead);

                //Assert 
                Assert.IsTrue(_protocol.StudyName == actualProtocol.StudyName);
                // TODO add more? 

            }
            public void GetAllProtocols_Valid_ReturnsCorrectNumberOfProtocols_Test()
            {
                //Arrange
                var protocol1 = new StoredProtocol { };
                var protocol2 = new StoredProtocol { };
                var protocol3 = new StoredProtocol { };
                var protocolList = new List<StoredProtocol> { protocol1, protocol2, protocol3 }.AsQueryable();

                _repositoryMock.Setup(r => r.Read()).Returns(protocolList);
                var adapter = new ProtocolAdapter(_repositoryMock.Object);
                const int expectedCount = 3;

                //Act
                var result = adapter.Read();
                var actualCount = result.ToList().Count;

                //Assert
                Assert.IsTrue(expectedCount == actualCount);
            }