예제 #1
0
 Task <Net.Http.HttpResponseMessage> IActionFilter.ExecuteActionFilterAsync(
     Controllers.HttpActionContext actionContext,
     Threading.CancellationToken cancellationToken,
     Func <Threading.Tasks.Task <Net.Http.HttpResponseMessage> > continuation
     )
 {
     throw new NotImplementedException();
 }
 public override Threading.Tasks.Task ExecuteBindingAsync(
     Metadata.ModelMetadataProvider metadataProvider,
     HttpActionContext actionContext,
     Threading.CancellationToken cancellationToken
     )
 {
     throw new NotImplementedException();
 }
        public Task CloseAsync(Threading.CancellationToken cancellationToken)
        {
            Program.ServiceAgent.UnregisterService(
                this.serviceContext.PartitionId,
                this.serviceContext.ReplicaId);

            return(Task.FromResult(0));
        }
        protected override HttpResponseMessage Send(HttpRequestMessage request, Threading.CancellationToken cancellationToken)
        {
            if (request.Version == _useVersion)
            {
                request.VersionPolicy = HttpVersionPolicy.RequestVersionExact;
            }

            return(base.Send(request, cancellationToken));
        }
        public Task <string> OpenAsync(Threading.CancellationToken cancellationToken)
        {
            var serviceEndPoint = Program.ServiceAgent.RegisterService(
                this.serviceContext.PartitionId,
                this.serviceContext.ReplicaId,
                this.service);

            return(Task.FromResult(serviceEndPoint));
        }
예제 #6
0
            public override async Task <HttpResponseMessage> SendAsync(
                HttpRequestMessage request,
                Threading.CancellationToken cancellationToken
                )
            {
                var stream = new MemoryStream();
                await request.Content.CopyToAsync(stream);

                stream.Position = 0;

                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StreamContent(stream),
                });
            }
예제 #7
0
        protected override Task <HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            Threading.CancellationToken cancellationToken
            )
        {
            Task <HttpResponseMessage> t = base.SendAsync(request, cancellationToken);

            if (!ReturnNull)
            {
                return(t);
            }

            TaskCompletionSource <HttpResponseMessage> tcs =
                new TaskCompletionSource <HttpResponseMessage>();

            tcs.SetResult(null);
            return(tcs.Task);
        }
예제 #8
0
 protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, Threading.CancellationToken cancellationToken)
 {
     throw new PlatformNotSupportedException();
 }
예제 #9
0
 public override Task WriteAsync(byte[] buffer, int offset, int count, Threading.CancellationToken cancellationToken)
 {
     throw new NotSupportedException(SR.net_http_content_readonly_stream);
 }
 public override Task <int> ReadAsync(byte[] buffer, int offset, int count, Threading.CancellationToken cancellationToken)
 {
     return(_fs.ReadAsync(buffer, offset, count, cancellationToken));
 }
예제 #11
0
        public override async Task <int> ReadAsync(byte[] buffer, int offset, int count, Threading.CancellationToken cancellationToken)
        {
            if (_isAtEof)
            {
                return(0);
            }
            int returnValue = await base.ReadAsync(buffer, offset, count, cancellationToken);

            if (returnValue == 0)
            {
                ReceivedEof();
            }
            return(returnValue);
        }
예제 #12
0
        /// <summary>
        /// Sends the async.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        protected internal override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, Threading.CancellationToken cancellationToken)
        {
            TaskCompletionSource <HttpResponseMessage> tcs = new TaskCompletionSource <HttpResponseMessage>();

            if (cancellationToken.IsCancellationRequested)
            {
                tcs.SetCanceled();
            }
            else
            {
                HttpWebRequest webRequest = null;
                if (this.AutomaticDecompression == DecompressionMethods.GZip)
                {
                    webRequest = new GZipHttpWebRequest(request.RequestUri);
                }
                else
                {
                    webRequest = WebRequest.CreateHttp(request.RequestUri);
                }
                webRequest.Method = request.Method.Method;
                if (webRequest.SupportsCookieContainer)
                {
                    webRequest.CookieContainer = this.CookieContainer;
                }
                webRequest.AllowAutoRedirect     = this.AllowAutoRedirect;
                webRequest.Credentials           = this.Credentials;
                webRequest.UseDefaultCredentials = this.UseDefaultCredentials;
                Action <IEnumerable <KeyValuePair <string, string> > > addHeaders = (headers) =>
                {
                    if (headers == null)
                    {
                        return;
                    }
                    foreach (var header in headers)
                    {
                        switch (header.Key)
                        {
                        case "Accept":
                            webRequest.Accept = header.Value;
                            break;

                        case "Content-Type":
                            webRequest.ContentType = header.Value;
                            break;

                        case "UserAgent":
                            webRequest.UserAgent = header.Value;
                            break;

                        default:
                            webRequest.Headers[header.Key] = header.Value;
                            break;
                        }
                    }
                };
                addHeaders(request.Headers.InternalHeaders);
                addHeaders(request.Content.Headers.InternalHeaders);

                var beginGetResponseDelegate = new AsyncCallback(delegate(IAsyncResult asynchronousResult2)
                {
                    HttpWebRequest req2 = (HttpWebRequest)asynchronousResult2.AsyncState;

                    if (req2.HaveResponse)
                    {
                        try
                        {
                            WebResponse response = req2.EndGetResponse(asynchronousResult2);
                            tcs.SetResult(new HttpResponseMessage(response, request));
                        }
                        catch (Exception exception)
                        {
                            tcs.SetException(exception);
                        }
                    }
                });

                if (request.Method == HttpMethod.Get || request.Method == HttpMethod.Head)
                {
                    webRequest.BeginGetResponse(beginGetResponseDelegate, webRequest);
                }
                else
                {
#if !WP7
                    long length = -1;
                    if (request.Content.TryComputeLength(out length))
                    {
                        webRequest.ContentLength = length;
                    }
#endif
                    webRequest.BeginGetRequestStream(new AsyncCallback(async delegate(IAsyncResult asynchronousResult)
                    {
                        HttpWebRequest req = (HttpWebRequest)asynchronousResult.AsyncState;

                        if (cancellationToken.IsCancellationRequested)
                        {
                            tcs.SetCanceled();
                        }
                        else
                        {
                            if (request.Content != null)
                            {
                                Stream postStream = null;
                                try
                                {
                                    postStream = req.EndGetRequestStream(asynchronousResult);
                                }
                                catch (Exception ex)
                                {
                                    tcs.SetException(ex);
                                    return;
                                }
                                await request.Content.CopyToAsync(postStream);
                                if (cancellationToken.IsCancellationRequested)
                                {
                                    tcs.SetCanceled();
                                    return;
                                }
                                postStream.Close();
                            }

                            req.BeginGetResponse(beginGetResponseDelegate, req);
                        }
                    }), webRequest);
                }
            }
            return(tcs.Task);
        }
예제 #13
0
        /// <summary>
        /// Handles service start event.
        /// </summary>
        /// <param name="args">Service start arguments.</param>
        public virtual void Start(string[] args)
        {
            string    userInput = string.Empty;
            Arguments arguments = new Arguments(string.Join(" ", Arguments.ToArgs(Environment.CommandLine).Where(arg => !arg.StartsWith("--filter=", StringComparison.OrdinalIgnoreCase)).Skip(1)));

            // Handle external service restart requests
            if (arguments.Exists("OrderedArg1") && arguments.Exists("restart"))
            {
                string serviceName = arguments["OrderedArg1"];

                if (GSF.Common.IsPosixEnvironment)
                {
                    string serviceCommand = FilePath.GetAbsolutePath(serviceName);

                    try
                    {
                        Command.Execute(serviceCommand, "stop");
                    }
                    catch (Exception ex)
                    {
                        string errorMessage = $"Failed to stop the {serviceName} daemon: {ex.Message}\r\n";
                        WriteLine(errorMessage);
                        Logger.SwallowException(ex, errorMessage);
                    }

                    try
                    {
                        Command.Execute(serviceCommand, "start");
                    }
                    catch (Exception ex)
                    {
                        string errorMessage = $"Failed to restart the {serviceName} daemon: {ex.Message}\r\n";
                        WriteLine(errorMessage);
                        Logger.SwallowException(ex, errorMessage);
                    }
                }
                else
                {
                    // Attempt to access service controller for the specified Windows service
                    ServiceController serviceController = ServiceController.GetServices().SingleOrDefault(svc => string.Compare(svc.ServiceName, serviceName, StringComparison.OrdinalIgnoreCase) == 0);

                    if (serviceController != null)
                    {
                        try
                        {
                            if (serviceController.Status == ServiceControllerStatus.Running)
                            {
                                WriteLine("Attempting to stop the {0} Windows service...", serviceName);

                                serviceController.Stop();

                                // Can't wait forever for service to stop, so we time-out after 20 seconds
                                serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(20.0D));

                                if (serviceController.Status == ServiceControllerStatus.Stopped)
                                {
                                    WriteLine("Successfully stopped the {0} Windows service.", serviceName);
                                }
                                else
                                {
                                    WriteLine("Failed to stop the {0} Windows service after trying for 20 seconds...", serviceName);
                                }

                                // Add an extra line for visual separation of service termination status
                                WriteLine("");
                            }
                        }
                        catch (Exception ex)
                        {
                            string errorMessage = $"Failed to stop the {serviceName} Windows service: {ex.Message}\r\n";
                            WriteLine(errorMessage);
                            Logger.SwallowException(ex, errorMessage);
                        }
                    }

                    // If the service failed to stop or it is installed as stand-alone debug application, we try to forcibly stop any remaining running instances
                    try
                    {
                        Process[] instances = Process.GetProcessesByName(serviceName);

                        if (instances.Length > 0)
                        {
                            int total = 0;
                            WriteLine("Attempting to stop running instances of the {0}...", serviceName);

                            // Terminate all instances of service running on the local computer
                            foreach (Process process in instances)
                            {
                                process.Kill();
                                total++;
                            }

                            if (total > 0)
                            {
                                WriteLine("Stopped {0} {1} instance{2}.", total, serviceName, total > 1 ? "s" : "");
                            }

                            // Add an extra line for visual separation of process termination status
                            WriteLine("");
                        }
                    }
                    catch (Exception ex)
                    {
                        string errorMessage = $"Failed to terminate running instances of the {serviceName}: {ex.Message}\r\n";
                        WriteLine(errorMessage);
                        Logger.SwallowException(ex, errorMessage);
                    }

                    // Attempt to restart Windows service...
                    if (serviceController != null)
                    {
                        try
                        {
                            // Refresh state in case service process was forcibly stopped
                            serviceController.Refresh();

                            if (serviceController.Status != ServiceControllerStatus.Running)
                            {
                                serviceController.Start();
                            }
                        }
                        catch (Exception ex)
                        {
                            string errorMessage = $"Failed to restart the {serviceName} Windows service: {ex.Message}\r\n";
                            WriteLine(errorMessage);
                            Logger.SwallowException(ex, errorMessage);
                        }
                    }
                }

                return;
            }

            // Handle clearing of dynanmic RazorEngine assemblies
            if (arguments.Exists("clearCache"))
            {
                string assemblyDirectory = FilePath.GetAbsolutePath(Common.DynamicAssembliesFolderName);

                if (!Directory.Exists(assemblyDirectory))
                {
                    return;
                }

                string[] razorFolders = Directory.EnumerateDirectories(assemblyDirectory, "RazorEngine_*", SearchOption.TopDirectoryOnly).ToArray();

                foreach (string razorFolder in razorFolders)
                {
                    try
                    {
                        Directory.Delete(razorFolder, true);
                    }
                    catch (Exception ex)
                    {
                        string errorMessage = $"Failed to remove temporary dynamic assembly folder: {razorFolder}";
                        WriteLine(errorMessage);
                        Logger.SwallowException(ex, errorMessage);
                    }
                }

                return;
            }

            // Handle normal remote console operations
            if (arguments.Exists("server"))
            {
                // Override default settings with user provided input.
                m_clientHelper.PersistSettings    = false;
                m_remotingClient.PersistSettings  = false;
                m_remotingClient.ConnectionString = $"Server={arguments["server"]}";
            }

            long lastConnectAttempt = 0;

            // Connect to service and send commands.
            while ((object)userInput != null && !string.Equals(userInput, "Exit", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    // Do not reattempt connection too quickly
                    while (DateTime.UtcNow.Ticks - lastConnectAttempt < Ticks.PerSecond)
                    {
                        Thread.Sleep(200);
                    }

                    lastConnectAttempt = DateTime.UtcNow.Ticks;

                    ICancellationToken timeoutCancellationToken = new Threading.CancellationToken();

                    if (System.Console.IsInputRedirected)
                    {
                        // If the client is invoked as part of a command line script,
                        // implement a 5-second timeout in case of connectivity issues
                        Action timeoutAction = () =>
                        {
                            if (!timeoutCancellationToken.IsCancelled)
                            {
                                Environment.Exit(1);
                            }
                        };

                        timeoutAction.DelayAndExecute(5000);
                    }

                    if (!m_authenticationFailure)
                    {
                        // If there has been no authentication
                        // failure, connect normally
                        Connect();
                    }
                    else
                    {
                        StringBuilder username = new StringBuilder();
                        StringBuilder password = new StringBuilder();

                        // If there has been an authentication failure,
                        // prompt the user for new credentials
                        PromptForCredentials(username, password);

                        try
                        {
                            // Attempt to set network credentials used when attempting AD authentication
                            using (UserInfo userInfo = new UserInfo(username.ToString()))
                            {
                                userInfo.Initialize();
                                SetNetworkCredential(new NetworkCredential(userInfo.LoginID, password.ToString()));
                            }
                        }
                        catch (Exception ex)
                        {
                            // Even if this fails, we can still pass along default credentials
                            SetNetworkCredential(null);
                            Logger.SwallowException(ex);
                        }

                        Connect(username.ToString(), password.ToString());
                    }

                    timeoutCancellationToken.Cancel();

                    while (m_authenticated && m_clientHelper.Enabled && (object)userInput != null && !string.Equals(userInput, "Exit", StringComparison.OrdinalIgnoreCase))
                    {
                        // Wait for a command from the user.
                        userInput = System.Console.ReadLine()?.Trim();

                        // Write a blank line to the console.
                        WriteLine();

                        if (string.IsNullOrWhiteSpace(userInput))
                        {
                            continue;
                        }

                        // The user typed in a command and didn't just hit <ENTER>.
                        switch (userInput.ToUpper())
                        {
                        case "CLS":
                            // User wants to clear the console window.
                            System.Console.Clear();
                            break;

                        case "EXIT":
                            // User wants to exit the telnet session with the service.
                            if (m_telnetActive)
                            {
                                userInput = string.Empty;
                                m_clientHelper.SendRequest("Telnet -disconnect");
                            }

                            break;

                        case "LOGIN":
                            m_authenticated         = false;
                            m_authenticationFailure = true;
                            break;

                        default:
                            // User wants to send a request to the service.
                            m_clientHelper.SendRequest(userInput);

                            if (string.Compare(userInput, "Help", StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                DisplayHelp();
                            }

                            break;
                        }
                    }

                    m_clientHelper.Disconnect();
                }
                catch (Exception ex)
                {
                    // Errors during the outer connection loop
                    // should simply force an attempt to reconnect
                    m_clientHelper.Disconnect();

                    Logger.SwallowException(ex);
                }
            }
        }