Exemplo n.º 1
0
        public void GetInformations()
        {
            // Get the test source
            var testSource = Profile.FindSource( ConfigurationManager.AppSettings["Station"] )[0];

            // Activate
            ServerImplementation.EndRequest( CardServer.BeginSelect( testSource.SelectionKey ) );

            // Create request helper
            var requestor = new RequestInformation( CardServer );

            // Remember
            var sources = ((GenericInformationResponse) requestor.BeginGetGroupInformation().Result).Strings.Select( s => SourceIdentifier.Parse( s ) ).ToArray();

            // Request data
            foreach (var group in ((NetworkInformationResponse) requestor.BeginGetNetworkInformation().Result).Groups)
                Console.WriteLine( group );

            // Resolve names
            var names = ((GenericInformationResponse) requestor.BeginGetSourceInformation( sources ).Result).Strings;

            // Report
            for (int i = 0, imax = Math.Max( sources.Length, names.Length ); i < imax; i++)
                Console.WriteLine( "{0} => {1}", sources[i], names[i] );
        }
Exemplo n.º 2
0
        /// <summary>
        /// Update the navigation property exportJobs in deviceManagement
        /// <param name="body"></param>
        /// <param name="requestConfiguration">Configuration for the request such as headers, query parameters, and middleware options.</param>
        /// </summary>
        public RequestInformation CreatePatchRequestInformation(DeviceManagementExportJob body, Action <DeviceManagementExportJobItemRequestBuilderPatchRequestConfiguration> requestConfiguration = default)
        {
            _ = body ?? throw new ArgumentNullException(nameof(body));
            var requestInfo = new RequestInformation {
                HttpMethod     = Method.PATCH,
                UrlTemplate    = UrlTemplate,
                PathParameters = PathParameters,
            };

            requestInfo.SetContentFromParsable(RequestAdapter, "application/json", body);
            if (requestConfiguration != null)
            {
                var requestConfig = new DeviceManagementExportJobItemRequestBuilderPatchRequestConfiguration();
                requestConfiguration.Invoke(requestConfig);
                requestInfo.AddRequestOptions(requestConfig.Options);
                requestInfo.AddHeaders(requestConfig.Headers);
            }
            return(requestInfo);
        }
        /// <summary>
        /// Update media content for the navigation property photos in groups
        /// <param name="body">Binary request body</param>
        /// <param name="requestConfiguration">Configuration for the request such as headers, query parameters, and middleware options.</param>
        /// </summary>
        public RequestInformation CreatePutRequestInformation(Stream body, Action <ContentRequestBuilderPutRequestConfiguration> requestConfiguration = default)
        {
            _ = body ?? throw new ArgumentNullException(nameof(body));
            var requestInfo = new RequestInformation {
                HttpMethod     = Method.PUT,
                UrlTemplate    = UrlTemplate,
                PathParameters = PathParameters,
            };

            requestInfo.SetStreamContent(body);
            if (requestConfiguration != null)
            {
                var requestConfig = new ContentRequestBuilderPutRequestConfiguration();
                requestConfiguration.Invoke(requestConfig);
                requestInfo.AddRequestOptions(requestConfig.Options);
                requestInfo.AddHeaders(requestConfig.Headers);
            }
            return(requestInfo);
        }
        /// <summary>
        /// Create new navigation property to extensions for me
        /// <param name="body"></param>
        /// <param name="requestConfiguration">Configuration for the request such as headers, query parameters, and middleware options.</param>
        /// </summary>
        public RequestInformation CreatePostRequestInformation(Extension body, Action <ExtensionsRequestBuilderPostRequestConfiguration> requestConfiguration = default)
        {
            _ = body ?? throw new ArgumentNullException(nameof(body));
            var requestInfo = new RequestInformation {
                HttpMethod     = Method.POST,
                UrlTemplate    = UrlTemplate,
                PathParameters = PathParameters,
            };

            requestInfo.SetContentFromParsable(RequestAdapter, "application/json", body);
            if (requestConfiguration != null)
            {
                var requestConfig = new ExtensionsRequestBuilderPostRequestConfiguration();
                requestConfiguration.Invoke(requestConfig);
                requestInfo.AddRequestOptions(requestConfig.Options);
                requestInfo.AddHeaders(requestConfig.Headers);
            }
            return(requestInfo);
        }
        public void RequestInformationConstructorTest()
        {
            string             expected   = "TaekyuKimrequeststatusJhon50";
            string             firstName  = "Taekyu";                                                                        // TODO: Initialize to an appropriate value
            string             lastName   = "Kim";                                                                           // TODO: Initialize to an appropriate value
            string             request    = "request";                                                                       // TODO: Initialize to an appropriate value
            string             status     = "status";                                                                        // TODO: Initialize to an appropriate value
            string             assignment = "Jhon";                                                                          // TODO: Initialize to an appropriate value
            double             grade      = 50;                                                                              // TODO: Initialize to an appropriate value
            RequestInformation target     = new RequestInformation(firstName, lastName, request, status, assignment, grade); // TODO: Initialize to an appropriate value
            string             b          = target.getFirstName;
            string             c          = target.getLastName;
            string             d          = target.getRequest;
            string             e          = target.getStatus;
            string             a          = target.getAssignment;
            string             f          = target.getGrade.ToString();
            string             actual     = b + c + d + e + a + f;

            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 6
0
        public async Task <int> UpdateRequestInfo(int id, TaskTypeViewModel taskTypeViewModel)
        {
            if (_db != null)
            {
                RequestInformation existItem = _db.RequestInformation.Where(f => f.IdrequestInformation == id).FirstOrDefault();
                if (existItem != null)
                {
                    existItem.SenderId   = taskTypeViewModel.reqInfo.SenderId;
                    existItem.RecieverId = taskTypeViewModel.reqInfo.RecieverId;
                    existItem.Notes      = taskTypeViewModel.reqInfo.Notes;
                    existItem.FileId     = taskTypeViewModel.reqInfo.FileId;
                    existItem.TaskId     = taskTypeViewModel.reqInfo.TaskId;
                }

                _db.RequestInformation.Update(existItem);
                await _db.SaveChangesAsync();

                return(1);
            }
            return(0);
        }
Exemplo n.º 7
0
        public async Task ExponentialRetryRetriesOnBatchException()
        {
            TimeSpan         interval         = TimeSpan.FromSeconds(5);
            const int        maxRetries       = 10;
            ExponentialRetry exponentialRetry = new ExponentialRetry(interval, maxRetries);

            RequestInformation reqInfo = new RequestInformation()
            {
                HttpStatusCode = HttpStatusCode.InternalServerError
            };
            BatchException batchException = new BatchException(reqInfo, "Message", null);

            OperationContext context = new OperationContext();

            context.RequestResults.Add(new RequestResult(new RequestInformation(), batchException));

            RetryDecision retryDecision = await exponentialRetry.ShouldRetryAsync(batchException, context);

            Assert.Equal(interval, retryDecision.RetryDelay);
            Assert.Equal(true, retryDecision.ShouldRetry);
        }
        public async Task ExponentialRetryHonorsRetryAfter()
        {
            TimeSpan         interval         = TimeSpan.FromSeconds(60);
            TimeSpan         retryAfter       = TimeSpan.FromSeconds(10);
            const int        maxRetries       = 10;
            ExponentialRetry exponentialRetry = new ExponentialRetry(interval, maxRetries);

            RequestInformation reqInfo = new RequestInformation()
            {
                HttpStatusCode = (HttpStatusCode)429,
                RetryAfter     = retryAfter
            };
            BatchException batchException = new BatchException(reqInfo, "Message", null);

            OperationContext context = new OperationContext();

            context.RequestResults.Add(new RequestResult(new RequestInformation(), batchException));

            RetryDecision retryDecision = await exponentialRetry.ShouldRetryAsync(batchException, context);

            Assert.Equal(retryAfter, retryDecision.RetryDelay);
            Assert.True(retryDecision.ShouldRetry);
        }
Exemplo n.º 9
0
            public object AfterReceiveRequest(ref Message request,
                                              IClientChannel channel, InstanceContext instanceContext)
            {
                if (OperationContext.Current.OutgoingMessageProperties.ContainsKey(
                        HttpRequestInformationProperty))
                {
                    return(null);
                }

                var info = new RequestInformation();

                var contentLengthHeader =
                    WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.ContentLength];

                long contentLength;

                if (!string.IsNullOrEmpty(contentLengthHeader))
                {
                    long.TryParse(contentLengthHeader, out contentLength);
                }
                else
                {
                    contentLength = -1;
                }

                info.ContentLength = contentLength;
                info.Uri           = OperationContext.Current.IncomingMessageHeaders.To;
                info.Method        = WebOperationContext.Current.IncomingRequest.Method;
                info.ContentType   = WebOperationContext.Current.IncomingRequest.ContentType;
                info.Accept        = WebOperationContext.Current.IncomingRequest.Accept;
                info.UserAgent     = WebOperationContext.Current.IncomingRequest.UserAgent;
                info.Headers       = WebOperationContext.Current.IncomingRequest.Headers;

                OperationContext.Current.OutgoingMessageProperties.Add(
                    HttpRequestInformationProperty, info);
                return(null);
            }
Exemplo n.º 10
0
        public void WebAppChainingTest19()
        {
            HttpWebRequest request = CreateRequest1();

            request.Headers.Add("X-Version", "1.9");
            request.Headers.Add("X-AUTHENTICATE-participantId", "UnitTest");
            request.Headers.Add("X-AUTHENTICATE-UserID", "WebAppChainingTest");

            Exception       e        = null;
            HttpWebResponse response = GetResponse(request, out e);

            Assert.IsNotNull(response, "Response");

            responseStream = response.GetResponseStream();
            string errorPage;

            if (e != null)
            {
                errorPage = new StreamReader(responseStream).ReadToEnd();
            }
            Assert.IsNull(e);
            XmlSerializer      serializer = new XmlSerializer(typeof(RequestInformation));
            RequestInformation info       = (RequestInformation)serializer.Deserialize(responseStream);

            Assert.IsNotNull(info, "RequestInformation");
            Assert.AreEqual("1.9", info.GetHeader("X-01-Version"));

            Assert.IsNotNull(info.GetHeader("X-AUTHENTICATE-cn"), "X-AUTHENTICATE-cn");
            Assert.AreEqual("common name", info.GetHeader("X-AUTHENTICATE-cn"));

            Assert.IsNotNull(info.GetHeader("X-01-AUTHENTICATE-participantId"), "X-01-AUTHENTICATE-participantId");
            Assert.AreEqual("UnitTest", info.GetHeader("X-01-AUTHENTICATE-participantId"));

            Assert.IsNotNull(info.GetHeader("X-01-AUTHENTICATE-UserID"), "X-01-AUTHENTICATE-UserID");
            Assert.AreEqual("WebAppChainingTest", info.GetHeader("X-01-AUTHENTICATE-UserID"));
        }
        private static void InternalHandleError(Exception error)
        {
            var behavior = GetWebErrorHandlerConfiguration();

            if (behavior == null || behavior.LogHandler == null)
            {
                return;
            }

            RequestInformation info;

            if (OperationContext.Current.OutgoingMessageProperties.ContainsKey(
                    ErrorHandlerBehavior.HttpRequestInformationProperty))
            {
                info = (RequestInformation)OperationContext.Current.OutgoingMessageProperties[
                    ErrorHandlerBehavior.HttpRequestInformationProperty];
            }
            else
            {
                info = new RequestInformation();
            }

            behavior.LogHandler.Write(error, info);
        }
Exemplo n.º 12
0
        public void RequestType_Success_Should_BeQuery()
        {
            IRequestInformation <TestQuery> requestInformation = new RequestInformation <TestQuery>();

            requestInformation.RequestType.Should().Be(ERequestType.Query);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Executes the request.
        /// </summary>
        /// <returns>An asynchronous operation of return type <typeparamref name="TResponse"/>.</returns>
        public async Task <TResponse> ExecuteRequestAsync()
        {
            this.hasRequestExecutionStarted = true;

            bool shouldRetry;

            do
            {
                shouldRetry = false; //Start every request execution assuming there will be no retry
                Task <TResponse> serviceRequestTask = null;
                Exception        capturedException;

                //Participate in cooperative cancellation
                this.CancellationToken.ThrowIfCancellationRequested();

                try
                {
                    this.ApplyClientRequestIdBehaviorToParams();

                    serviceRequestTask = this.ExecuteRequestWithCancellationAsync(this.ServiceRequestFunc);

                    TResponse response = await serviceRequestTask.ConfigureAwait(continueOnCapturedContext : false);

                    //TODO: It would be nice if we could add to OperationContext.RequestResults here
                    return(response);
                }
                catch (Exception e)
                {
                    //If the caught exception was a BatchErrorException, we wrap it in the object model exception type
                    BatchException batchException = null;
                    if (e is BatchErrorException)
                    {
                        batchException = new BatchException(e as BatchErrorException);
                    }

                    Exception wrappedException = batchException ?? e;

                    if (this.RetryPolicy != null &&
                        //If cancellation is requested at this point, just skip calling the retry policy and throw
                        //This is the most honest thing to do since we will not be issuing another request on the users behalf
                        //(since the cancellation token has already been set) and thus calling their retry policy would just
                        //be confusing.
                        !this.CancellationToken.IsCancellationRequested)
                    {
                        RequestInformation requestInformation;

                        if (batchException != null)
                        {
                            //If there is a BatchException, extract the RequestInformation and capture it
                            requestInformation = batchException.RequestInformation;
                        }
                        else
                        {
                            requestInformation = new RequestInformation()
                            {
                                ClientRequestId = this.Options.ClientRequestId
                            };
                        }

                        this.OperationContext.RequestResults.Add(new RequestResult(requestInformation, wrappedException)
                        {
                            Task = serviceRequestTask
                        });
                        capturedException = wrappedException;
                    }
                    else
                    {
                        if (batchException != null)
                        {
                            throw batchException; //Just forward the wrapped exception if there was one
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                if (capturedException != null)
                {
                    //On an exception, invoke the retry policy
                    RetryDecision retryDecision = await this.RetryPolicy.ShouldRetryAsync(capturedException, this.OperationContext).ConfigureAwait(continueOnCapturedContext: false);

                    shouldRetry = retryDecision.ShouldRetry;

                    if (!shouldRetry)
                    {
                        //Rethrow the exception and explicitly preserve the stack trace
                        ExceptionDispatchInfo.Capture(capturedException).Throw();
                    }
                    else
                    {
                        if (retryDecision.RetryDelay.HasValue)
                        {
                            await Task.Delay(retryDecision.RetryDelay.Value).ConfigureAwait(continueOnCapturedContext: false);
                        }
                        else
                        {
                            Debug.Assert(false, "RetryDecision.ShouldRetry = true but RetryDelay has no value");
                        }
                    }
                }
            } while (shouldRetry);

            //Reaching here is a bug, by now the request should have either thrown or returned
            const string errorMessage = "Exited ExecuteRequestAsync without throwing or returning";

            Debug.Assert(false, errorMessage);
            throw new InvalidOperationException(errorMessage);
        }
Exemplo n.º 14
0
 public override Task <SkillResponse> Handle(RequestInformation information)
 {
     throw new InvalidOperationException("You shouldn't have done that");
 }
Exemplo n.º 15
0
        /// <summary>Sends an UDP message to a given node.</summary>
        /// <param name="message">The message to be sent.</param>
        /// <param name="target">The address of the target node.</param>
        /// <param name="targetNodeId">The target node ID.</param>
        internal void SendUdpMessage(UdpMessage message, IPEndPoint target, KademliaId targetNodeId)
        {
            message.RequestId = Random.UInt64();
            message.SenderNodeId = Id;

            var requestIdentifier = new RequestIdentifier {EndPoint = target, RequestId = message.RequestId};
            var requestInformation = new RequestInformation {OutgoingMessage = message, SecondAttempt = false, NodeId = targetNodeId};

            if (message.IsRequest)
            {
                lock (outstandingRequests)
                {
                    outstandingRequests.Add(requestIdentifier, requestInformation);
                }
            }

            SendUdp(message, target);
        }
Exemplo n.º 16
0
 public override bool CanHandle(RequestInformation information)
 {
     return(information.SkillRequest.Request is LaunchRequest);
 }
Exemplo n.º 17
0
 public override SkillResponse HandleSyncRequest(RequestInformation information)
 {
     return(ResponseBuilder.Tell("okay, I hope you found it interesting"));
 }
        private void socketHelper_SocketDataReceived(string data)
        {
            if (socketHelper.IsHandshake)
            {
                BaseResponse <AccountInformation> response = JsonConvert.DeserializeObject <BaseResponse <AccountInformation> >(data);

                if (response != null && response.Status == 200)
                {
                    this.accountInfo = response.Data;

                    this.contacts = WebConnector.GetContactsData(accountInfo.Id);
                    this.requests = WebConnector.GetAvailableRequests(accountInfo.Id);

                    this.DisplayContactsAndRequests();

                    this.socketHelper.IsHandshake  = false;
                    this.socketHelper.IsAuthorized = true;

                    this.UpdateClientMenu(true);
                }
                else
                {
                    MessageBox.Show("An error occurred: " + response.ErrorMessage, "Error logging in", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    this.socketHelper.CloseConnection();
                    this.UpdateClientMenu(false);
                }

                return;
            }

            Message message       = Message.CreateMessageObject(data);
            bool    isCallContent = false;

            if (message == null || (message.Command.Equals("/disconnect") && message.Content.Equals("OK")))
            {
                socketHelper.CloseConnection();

                UpdateClientOnDisconnect();
                return;
            }
            else if (message.Command.Equals(@"/online"))
            {
                string username = message.Content;
                ChangeOnlineStatus(username);

                return;
            }
            else if (message.Command.Equals(@"/request"))
            {
                RequestInformation request = null;

                try
                {
                    //Console.WriteLine(message.Content);
                    request = JsonConvert.DeserializeObject <RequestInformation>(message.Content);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("An error occurred while parsing request command: " + ex.Message);
                }

                if (request != null)
                {
                    this.requests.Add(request);
                    this.FillRequestsList();
                }

                return;
            }
            else if (message.Command.Equals(@"/accept"))
            {
                AccountInformation contact = null;

                try
                {
                    contact = JsonConvert.DeserializeObject <AccountInformation>(message.Content);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("An error occurred while parsing accept command: " + ex.Message);
                }

                if (contact != null)
                {
                    this.contacts.ContactsList.Add(contact);
                    this.AppendContact(contact);

                    this.ChangeOnlineStatus(contact.Username);

                    socketHelper.SendMessage(contact.Username, this.accountInfo.Username, this.accountInfo.Username, @"/online");
                }

                return;
            }
            else if (message.Command.Equals(@"/offline"))
            {
                string username = message.Content;
                ChangeOnlineStatus(username);

                return;
            }
            else if (message.Command.Contains("call"))
            {
                isCallContent = true; // We set it to true to avoid dumping call ID's into the message box

                if (message.Command.Equals("/call"))
                {
                    this.callSoundPlayer.PlayLooping();

                    MessengerContainer msgWindow = GetActiveMessengerContainer(message.Sender);
                    if (msgWindow != null)
                    {
                        msgWindow.CreateCallDialog(message.Sender);
                        msgWindow.callDialog.CallStateChanged += callDialog_CallStateChanged;
                    }
                }
                else if (message.Command.Contains("/accept"))
                {
                    MessengerContainer msgWindow = GetActiveMessengerContainer(message.Sender);

                    if (msgWindow != null)
                    {
                        msgWindow.InitiatingCall = false;
                    }

                    this.socketHelper.EstablishCall(this.accountInfo.Username);
                }
                else if (message.Command.Contains("/close"))
                {
                    if (this.socketHelper.CallHelper != null)
                    {
                        this.socketHelper.CloseCall();
                    }

                    MessengerContainer msgWindow = GetActiveMessengerContainer(message.Sender);
                    if (msgWindow != null)
                    {
                        msgWindow.InitiatingCall = false;

                        msgWindow.UpdateCallState();
                        msgWindow.callDialog.CallStateChanged -= callDialog_CallStateChanged;
                    }
                }
            }

            if (message.Content != string.Empty && !isCallContent)
            {
                if (message.Sender == this.accountInfo.Username)
                {
                    this.DumpMessage(message, true);
                }
                else
                {
                    this.DumpMessage(message);

                    this.notificationSoundPlayer.Play();
                    SetContainerNotification(message.Sender);
                }
            }
        }
Exemplo n.º 19
0
 public override async Task <SkillResponse> Handle(RequestInformation information, Exception exception)
 {
     Console.WriteLine(exception.ToString());
     return(ResponseBuilder.Tell("So sorry, but something appears to have gone wrong"));
 }
Exemplo n.º 20
0
        public void RequestType_Success_Should_BeCommand()
        {
            IRequestInformation <TestCommand> requestInformation = new RequestInformation <TestCommand>();

            requestInformation.RequestType.Should().Be(ERequestType.Command);
        }
Exemplo n.º 21
0
 public override SkillResponse HandleSyncRequest(RequestInformation information)
 {
     return(ResponseBuilder.Ask(response, new Reprompt(reprompt)));
 }
Exemplo n.º 22
0
        public void RequestType_Success_Should_BeNotification()
        {
            IRequestInformation <AfterSaveETO> requestInformation = new RequestInformation <AfterSaveETO>();

            requestInformation.RequestType.Should().Be(ERequestType.Notification);
        }
Exemplo n.º 23
0
 public override SkillResponse HandleSyncRequest(RequestInformation information)
 {
     return(ResponseBuilder.Ask(
                "Hi there, thanks for wanting to learn more about Alexa dot net. What feature would you like to find out about?",
                new Reprompt("What feature would you like to find out about?")));
 }
Exemplo n.º 24
0
        public void RequestType_Success_Should_BeRequest()
        {
            IRequestInformation <TestRequest> requestInformation = new RequestInformation <TestRequest>();

            requestInformation.RequestType.Should().Be(ERequestType.Request);
        }