private void AsJwtToken(string key, ConnectionType type)
 {
     ConnectionType = type;
     CustomHeaders.Add("Authorization", "Bearer " + key);
     _isConfigured   = true;
     IsAuthenticated = true;
 }
Exemple #2
0
 /// <summary>
 /// Adds an custom header to the MailMessage.
 ///	NOTE: some SMTP servers will reject improper custom headers
 ///</summary>
 /// <param name="mailheader">MailHeader instance</param>
 /// <example>
 /// <code>
 ///     MailMessage msg = new MailMessage("*****@*****.**", "*****@*****.**");
 ///		MailHeader header = new MailHeader("X-Something", "HeaderValue");
 ///		msg.AddCustomHeader(header);
 /// </code>
 /// </example>
 public void AddCustomHeader(MailHeader mailheader)
 {
     if (mailheader.Name != null && mailheader.Body != null)
     {
         CustomHeaders.Add(mailheader);
     }
 }
Exemple #3
0
        /// <inheritdoc/>
        public async Task CallAsync <TService>(
            CustomHeaders customHeaders,
            Uri uri,
            Expression <Func <TService, Task> > callMethod) where TService : IService
        {
            var proxyFactory = new ServiceProxyFactory(c => new ExtendedServiceRemotingClientFactory(new FabricTransportServiceRemotingClientFactory(remotingCallbackMessageHandler: c), customHeaders));
            var service      = proxyFactory.CreateServiceProxy <TService>(uri);
            var success      = true;

            var stopwatch = Stopwatch.StartNew();
            var started   = DateTime.Now;

            try
            {
                await callMethod.Compile().Invoke(service);
            }
            catch (Exception exception)
            {
                success = false;
                _logger.LogError(ServiceFabricEvent.Exception, exception, exception.Message);
                throw;
            }
            finally
            {
                stopwatch.Stop();
                _logger.LogDependency(callMethod, started, stopwatch.Elapsed, success);
            }
        }
Exemple #4
0
 /// <summary>
 /// Creates an <see cref="ServiceProxy"/>
 /// </summary>
 /// <typeparam name="TServiceInterface">The type of service to create</typeparam>
 /// <param name="serviceUri">The uri of the service</param>
 /// <param name="customHeaders">A <see cref="CustomHeaders"/> instance with data passed to the service</param>
 /// <param name="partitionKey"></param>
 /// <param name="targetReplicaSelector"></param>
 /// <param name="listenerName"></param>
 /// <returns>A service proxy object that implements IServiceProxy and TServiceInterface.</returns>
 public static TServiceInterface Create <TServiceInterface>(Uri serviceUri, CustomHeaders customHeaders = null,
                                                            ServicePartitionKey partitionKey            = null,
                                                            TargetReplicaSelector targetReplicaSelector = TargetReplicaSelector.Default, string listenerName = null)
     where TServiceInterface : IService
 {
     return(Create <TServiceInterface>(serviceUri, () => customHeaders, partitionKey, targetReplicaSelector, listenerName));
 }
 private void Remove_Click(object sender, RoutedEventArgs e)
 {
     if (SelectedCustomHeader != null && CustomHeaders.Contains(SelectedCustomHeader))
     {
         CustomHeaders.Remove(SelectedCustomHeader);
     }
 }
Exemple #6
0
        protected virtual HttpWebRequest GetRequest(string uri, HttpVerbs verb)
        {
            HttpWebRequest request = null;

            try
            {
                request = (HttpWebRequest)WebRequest.Create(uri);

                if (RequestTimeoutInMilliseconds.HasValue)
                {
                    request.Timeout = RequestTimeoutInMilliseconds.Value;
                }

                request.Headers.Clear();
                Headers?.ToList().ForEach(h => request.Headers.Add(h.Key, h.Value));
                CustomHeaders?.ToList().ForEach(h => request.Headers.Add(h.Key, h.Value));

                request.Referer = BaseUrl;
                request.Method  = verb.ToString().ToUpper();

                request.ContentType = ContentType;
                request.Accept      = ContentType;

                return(request);
            }
            catch (Exception ex)
            {
                request?.Abort();

                log.Error(ex.Message, ex);
                throw;
            }
        }
Exemple #7
0
 public ApiRequestClient(string baseUrl, string apiKey, int?requestTimeoutInSeconds = null)  : base(baseUrl, requestTimeoutInSeconds)
 {
     if (apiKey != null)
     {
         CustomHeaders.Add("apikey", apiKey);
     }
 }
Exemple #8
0
        public void AddCustomHeader(string key, string value)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                return;
            }

            CustomHeaders.Add(key, value);
        }
Exemple #9
0
        public CustomHeadersResponse Any(CustomHeaders c)
        {
            var response = new CustomHeadersResponse
            {
                Foo = Request.Headers["Foo"],
                Bar = Request.Headers["Bar"]
            };

            return(response);
        }
 public void AsStaticHeaderUserViaProxy(string userId, string headerName, bool certificateValidation)
 {
     ConnectionType        = ConnectionType.StaticHeaderUserViaProxy;
     CertificateValidation = certificateValidation;
     UserId           = userId;
     UserDirectory    = Environment.UserDomainName;
     StaticHeaderName = headerName;
     CustomHeaders.Add(headerName, userId);
     _isConfigured = true;
 }
Exemple #11
0
        internal void SetRequestHeaders(HttpRequestMessage request)
        {
            request.Headers.Clear();

            Accept.ForEach(x => request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(x)));
            AcceptEncoding.ForEach(x => request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue(x)));
            CustomHeaders.ToList().ForEach(x => request.Headers.Add(x.Key, x.Value));
            if (request.Content != null)
            {
                request.Content.Headers.ContentType = new MediaTypeHeaderValue(ContentType);
            }
        }
Exemple #12
0
 /// <summary>
 /// Sets custom headers from an array of lines.
 /// </summary>
 /// <param name="lines">The lines containing the colon-separated name and value of the headers</param>
 public void SetCustomHeaders(string[] lines)
 {
     CustomHeaders.Clear();
     foreach (var line in lines)
     {
         if (line.Contains(':'))
         {
             var split = line.Split(new[] { ':' }, 2);
             CustomHeaders[split[0].Trim()] = split[1].Trim();
         }
     }
 }
Exemple #13
0
        /// <summary>
        /// Make the http request. This method does not handle any exceptions thrown by making the http request.
        /// </summary>
        private string PerformHttpRequest(ServiceName serviceName, string requestBody)
        {
            // We have done the login now we can actually do a query on Neolane
            var reqData = (HttpWebRequest)WebRequest.Create(Uri);

            reqData.Method      = "POST";
            reqData.ContentType = "text/xml; charset=utf-8";

            // Add to the headers the requested service action that we want to call
            reqData.Headers.Add("SOAPAction", serviceName.ToString());

            // Add to the headers the security and session token
            // Tokens should be provided except for the login request
            if (AuthenticationTokens != null)
            {
                reqData.Headers.Add("X-Security-Token", AuthenticationTokens.SecurityToken);

                // The session token can be added either in the request body or in header as a cookie.
                // We add it as a header, to make it easier to deal with queuing requests for later processing.
                reqData.Headers.Add("cookie", $"__sessiontoken={AuthenticationTokens.SessionToken}");
            }

            foreach (var header in CustomHeaders.Where(i => Regex.IsMatch(i, @"^[a-z_-]+:", RegexOptions.Compiled | RegexOptions.IgnoreCase)))
            {
                reqData.Headers.Add(header);
            }

            // Write the body to a byteArray to be passed with the Request Stream
            var byteArrayData = Encoding.UTF8.GetBytes(requestBody);

            // Set the ContentLength property of the WebRequest.
            reqData.ContentLength = byteArrayData.Length;

            // Write the data to the request stream.
            using (var dataStreamInputData = reqData.GetRequestStream())
            {
                dataStreamInputData.Write(byteArrayData, 0, byteArrayData.Length);
            }

            // Get the response stream and open the stream using a StreamReader for easy access.
            string responseFromServer;

            using (var response = reqData.GetResponse())
                using (var dataStream = response.GetResponseStream())
                    using (var reader = new StreamReader(dataStream))
                    {
                        // Read the content.
                        responseFromServer = reader.ReadToEnd();
                    }

            return(responseFromServer);
        }
 public void AsNtlmUserViaProxy(NetworkCredential credential, bool certificateValidation = true)
 {
     ConnectionType        = ConnectionType.NtlmUserViaProxy;
     CertificateValidation = certificateValidation;
     if (credential != null)
     {
         var credentialCache = new CredentialCache();
         credentialCache.Add(this.BaseUri, "ntlm", credential);
         CustomCredential = credentialCache;
     }
     CustomHeaders.Add("User-Agent", "Windows");
     _isConfigured = true;
 }
Exemple #15
0
        /// <summary>
        /// Builds a string containing custom headers.
        /// </summary>
        /// <returns>One header per line, with name and value separated by a colon</returns>
        public string GetCustomHeaders()
        {
            StringBuilder sb = new StringBuilder();

            foreach (var pair in CustomHeaders)
            {
                sb.Append($"{pair.Key}: {pair.Value}");
                if (!pair.Equals(CustomHeaders.Last()))
                {
                    sb.Append(Environment.NewLine);
                }
            }
            return(sb.ToString());
        }
        public async Task <int> Get(int a, int b)
        {
            var uri = new Uri($"{FabricRuntime.GetActivationContext().ApplicationName}/MyStateless");

            var customheaders = new CustomHeaders
            {
                { HeaderIdentifiers.TraceId, HttpContext.TraceIdentifier }
            };

            var sum = await _serviceRemoting.CallAsync <IMyService, int>(customheaders, uri, service => service.CalculateSumAsync(a, b));

            await new HttpClient().GetAsync("http://www.google.nl");

            var actor = ActorProxy.Create <IMyActor>(ActorId.CreateRandom());
            await actor.GetCountAsync(CancellationToken.None);

            return(sum);
        }
Exemple #17
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(Via.ToString());
            sb.Append(From.ToString());
            sb.Append($"To: <sip:{To.ToString()}>").AppendLine();
            sb.Append(CallId.ToString());
            sb.Append(CSeq.ToString());
            if (!string.IsNullOrEmpty(UserAgent))
            {
                sb.Append($"User-Agent: {UserAgent}").AppendLine();
            }
            if (Expires > 0)
            {
                sb.Append($"Expires: {Expires.ToString()}").AppendLine();
            }
            if (!string.IsNullOrEmpty(Accept))
            {
                sb.Append($"Accept: {Accept}").AppendLine();
            }
            if (!string.IsNullOrEmpty(ContentType))
            {
                sb.Append($"Content-Type: {ContentType}").AppendLine();
            }
            if (ContentLength > 0)
            {
                sb.Append($"Content-Length: {ContentLength.ToString()}").AppendLine();
            }
            sb.Append($"Max-Forwards: {MaxForwards}").AppendLine();
            if (Allow != null && Allow.Count > 0)
            {
                sb.Append($"Allow: {string.Join(",",Allow)}").AppendLine();
            }
            if (CustomHeaders.Count() > 0)
            {
                foreach (KeyValuePair <string, string> Header in CustomHeaders)
                {
                    sb.Append($"X-{Header.Key}: {Header.Value}").AppendLine();
                }
            }

            return(sb.ToString());
        }
        public void AsDirectConnection(string userDirectory, string userId, int port    = 4242, bool certificateValidation = true,
                                       X509Certificate2Collection certificateCollection = null)
        {
            ConnectionType = ConnectionType.DirectConnection;
            var uriBuilder = new UriBuilder(BaseUri)
            {
                Port = port
            };

            BaseUri               = uriBuilder.Uri;
            UserId                = userId;
            UserDirectory         = userDirectory;
            CertificateValidation = certificateValidation;
            Certificates          = certificateCollection;
            var userHeaderValue = string.Format("UserDirectory={0};UserId={1}", UserDirectory, UserId);

            CustomHeaders.Add("X-Qlik-User", userHeaderValue);
            _isConfigured = true;
        }
        static void FixedHeaderValues()
        {
            Console.WriteLine("Press any key to start .... ");
            Console.ReadLine();

            // Create a new instance of CustomHeaders that is passed on each call.
            var customHeaders = new CustomHeaders
            {
                { "Header1", DateTime.Now },
                { "Header2", Guid.NewGuid() }
            };

            var serviceUri = new Uri("fabric:/ServiceFabric.Remoting.CustomHeaders.DemoApplication/DemoService");

            var proxyFactory = new ServiceProxyFactory(handler =>
                                                       new ExtendedServiceRemotingClientFactory(
                                                           new FabricTransportServiceRemotingClientFactory(remotingCallbackMessageHandler: handler), customHeaders));
            var proxy         = proxyFactory.CreateServiceProxy <IDemoService>(serviceUri);
            var actorResponse = proxy.SayHelloToActor().GetAwaiter().GetResult();

            Console.WriteLine($"Actor said '{actorResponse}'");
            Console.WriteLine("Press any key to stop. ");
            Console.ReadLine();
        }
        static void NonReusedProxy()
        {
            // Create a new instance of CustomHeaders that is passed on each call.
            var customHeaders = new CustomHeaders
            {
                { "Header1", DateTime.Now.ToString(CultureInfo.InvariantCulture) },
                { "Header2", Guid.NewGuid().ToString() }
            };

            while (true)
            {
                var serviceUri   = new Uri("fabric:/ServiceFabric.Remoting.CustomHeaders.DemoApplication/DemoService");
                var proxy        = ExtendedServiceProxy.Create <IDemoService>(serviceUri, customHeaders);
                var actorMessage = proxy.SayHelloToActor().GetAwaiter().GetResult();

                Console.WriteLine($"Actor said '{actorMessage}'");
                Console.WriteLine("Press any key to restart (q to quit).... ");
                var key = Console.ReadLine();
                if (key.ToLowerInvariant() == "q")
                {
                    break;
                }
            }
        }
        internal static CustomHeaders GetCustomHeaders(this IServiceRemotingRequestMessageHeader header)
        {
            var customHeaders = new CustomHeaders();

            if (header.TryGetHeaderValue(CustomHeaders.CustomHeader, out byte[] headerValue))
Exemple #22
0
        /// <inheritdoc />
        public override BlockBase FromLS(string line)
        {
            // Trim the line
            var input = line.Trim();

            // Parse the label
            if (input.StartsWith("#"))
            {
                Label = LineParser.ParseLabel(ref input);
            }

            Method = (HttpMethod)LineParser.ParseEnum(ref input, "METHOD", typeof(HttpMethod));
            Url    = LineParser.ParseLiteral(ref input, "URL");

            while (LineParser.Lookahead(ref input) == TokenType.Boolean)
            {
                LineParser.SetBool(ref input, this);
            }

            CustomHeaders.Clear(); // Remove the default headers

            while (input != "" && !input.StartsWith("->"))
            {
                var parsed = LineParser.ParseToken(ref input, TokenType.Parameter, true).ToUpper();
                switch (parsed)
                {
                case "MULTIPART":
                    RequestType = RequestType.Multipart;
                    break;

                case "BASICAUTH":
                    RequestType = RequestType.BasicAuth;
                    break;

                case "STANDARD":
                    RequestType = RequestType.Standard;
                    break;

                case "CONTENT":
                    PostData = LineParser.ParseLiteral(ref input, "POST DATA");
                    break;

                case "STRINGCONTENT":
                    var sCont  = LineParser.ParseLiteral(ref input, "STRING CONTENT");
                    var sSplit = sCont.Split(new char[] { ':' }, 2);
                    MultipartContents.Add(new MultipartContent()
                    {
                        Type = MultipartContentType.String, Name = sSplit[0].Trim(), Value = sSplit[1].Trim()
                    });
                    break;

                case "FILECONTENT":
                    var fCont  = LineParser.ParseLiteral(ref input, "FILE CONTENT");
                    var fSplit = fCont.Split(new char[] { ':' }, 2);
                    MultipartContents.Add(new MultipartContent()
                    {
                        Type = MultipartContentType.File, Name = fSplit[0].Trim(), Value = fSplit[1].Trim()
                    });
                    break;

                case "COOKIE":
                    var cookiePair = ParsePair(LineParser.ParseLiteral(ref input, "COOKIE VALUE"));
                    CustomCookies[cookiePair.Key] = cookiePair.Value;
                    break;

                case "HEADER":
                    var headerPair = ParsePair(LineParser.ParseLiteral(ref input, "HEADER VALUE"));
                    CustomHeaders[headerPair.Key] = headerPair.Value;
                    break;

                case "CONTENTTYPE":
                    ContentType = LineParser.ParseLiteral(ref input, "CONTENT TYPE");
                    break;

                case "USERNAME":
                    AuthUser = LineParser.ParseLiteral(ref input, "USERNAME");
                    break;

                case "PASSWORD":
                    AuthPass = LineParser.ParseLiteral(ref input, "PASSWORD");
                    break;

                case "BOUNDARY":
                    MultipartBoundary = LineParser.ParseLiteral(ref input, "BOUNDARY");
                    break;

                default:
                    break;
                }
            }

            if (input.StartsWith("->"))
            {
                LineParser.EnsureIdentifier(ref input, "->");
                var outType = LineParser.ParseToken(ref input, TokenType.Parameter, true);
                if (outType.ToUpper() == "STRING")
                {
                    ResponseType = ResponseType.String;
                }
                else if (outType.ToUpper() == "FILE")
                {
                    ResponseType = ResponseType.File;
                    DownloadPath = LineParser.ParseLiteral(ref input, "DOWNLOAD PATH");
                }
            }

            return(this);
        }
 /// <summary>
 /// Creates an <see cref="ActorProxy"/>
 /// </summary>
 /// <typeparam name="TActorInterface">The type of the actor to create</typeparam>
 /// <param name="actorId">The id of the actor to address</param>
 /// <param name="customHeaders">A <see cref="CustomHeaders"/> instance with data passed to the actor</param>
 /// <param name="applicationName"></param>
 /// <param name="serviceName"></param>
 /// <param name="listenerName"></param>
 /// <returns>An actor proxy object that implements IActorProxy and TActorInterface.</returns>
 public static TActorInterface Create <TActorInterface>(ActorId actorId, CustomHeaders customHeaders = null, string applicationName = null, string serviceName = null, string listenerName = null) where TActorInterface : IActor
 {
     return(Create <TActorInterface>(actorId, () => customHeaders, applicationName, serviceName, listenerName));
 }
Exemple #24
0
        /// <inheritdoc />
        public override BlockBase FromLS(string line)
        {
            // Trim the line
            var input = line.Trim();

            // Parse the label
            if (input.StartsWith("#"))
            {
                Label = LineParser.ParseLabel(ref input);
            }

            Method = (HttpMethod)LineParser.ParseEnum(ref input, "METHOD", typeof(HttpMethod));
            Url    = LineParser.ParseLiteral(ref input, "URL");

            while (LineParser.Lookahead(ref input) == TokenType.Boolean)
            {
                LineParser.SetBool(ref input, this);
            }

            CustomHeaders.Clear(); // Remove the default headers

            while (input != string.Empty && !input.StartsWith("->"))
            {
                var parsed = LineParser.ParseToken(ref input, TokenType.Parameter, true).ToUpper();
                switch (parsed)
                {
                case "MULTIPART":
                    RequestType = RequestType.Multipart;
                    break;

                case "BASICAUTH":
                    RequestType = RequestType.BasicAuth;
                    break;

                case "STANDARD":
                    RequestType = RequestType.Standard;
                    break;

                case "RAW":
                    RequestType = RequestType.Raw;
                    break;

                case "CONTENT":
                    PostData = LineParser.ParseLiteral(ref input, "POST DATA");
                    break;

                case "RAWDATA":
                    RawData = LineParser.ParseLiteral(ref input, "RAW DATA");
                    break;

                case "STRINGCONTENT":
                    var stringContentPair = ParseString(LineParser.ParseLiteral(ref input, "STRING CONTENT"), ':', 2);
                    MultipartContents.Add(new MultipartContent()
                    {
                        Type = MultipartContentType.String, Name = stringContentPair[0], Value = stringContentPair[1]
                    });
                    break;

                case "FILECONTENT":
                    var fileContentTriplet = ParseString(LineParser.ParseLiteral(ref input, "FILE CONTENT"), ':', 3);
                    MultipartContents.Add(new MultipartContent()
                    {
                        Type = MultipartContentType.File, Name = fileContentTriplet[0], Value = fileContentTriplet[1], ContentType = fileContentTriplet[2]
                    });
                    break;

                case "COOKIE":
                    var cookiePair = ParseString(LineParser.ParseLiteral(ref input, "COOKIE VALUE"), ':', 2);
                    CustomCookies[cookiePair[0]] = cookiePair[1];
                    break;

                case "HEADER":
                    var headerPair = ParseString(LineParser.ParseLiteral(ref input, "HEADER VALUE"), ':', 2);
                    CustomHeaders[headerPair[0]] = headerPair[1];
                    break;

                case "CONTENTTYPE":
                    ContentType = LineParser.ParseLiteral(ref input, "CONTENT TYPE");
                    break;

                case "USERNAME":
                    AuthUser = LineParser.ParseLiteral(ref input, "USERNAME");
                    break;

                case "PASSWORD":
                    AuthPass = LineParser.ParseLiteral(ref input, "PASSWORD");
                    break;

                case "BOUNDARY":
                    MultipartBoundary = LineParser.ParseLiteral(ref input, "BOUNDARY");
                    break;

                case "SECPROTO":
                    SecurityProtocol = LineParser.ParseEnum(ref input, "Security Protocol", typeof(SecurityProtocol));
                    break;

                default:
                    break;
                }
            }

            if (input.StartsWith("->"))
            {
                LineParser.EnsureIdentifier(ref input, "->");
                var outType = LineParser.ParseToken(ref input, TokenType.Parameter, true);
                if (outType.ToUpper() == "STRING")
                {
                    ResponseType = ResponseType.String;
                }
                else if (outType.ToUpper() == "FILE")
                {
                    ResponseType = ResponseType.File;
                    DownloadPath = LineParser.ParseLiteral(ref input, "DOWNLOAD PATH");
                    while (LineParser.Lookahead(ref input) == TokenType.Boolean)
                    {
                        LineParser.SetBool(ref input, this);
                    }
                }
                else if (outType.ToUpper() == "BASE64")
                {
                    ResponseType   = ResponseType.Base64String;
                    OutputVariable = LineParser.ParseLiteral(ref input, "OUTPUT VARIABLE");
                }
            }

            return(this);
        }
Exemple #25
0
        public void Open(string url, string method, string data, dynamic callback = null)
        {
            WebBrowserNavigateErrorEventHandler     fail      = null;
            WebBrowserDocumentCompletedEventHandler completed = null;
            WebBrowserNavigatedEventHandler         navigated = null;

            navigationType = "Other";
            var frameCount = 0;
            var done       = false;

            navigated = delegate(object sender, WebBrowserNavigatedEventArgs e)
            {
                browser.Document.Window.Error += delegate(object sender2, HtmlElementErrorEventArgs e2)
                {
                    e2.Handled = true;

                    if (OnError != null)
                    {
                        dynamic err = new ExpandoObject();
                        err.file = e2.Url.AbsoluteUri;
                        err.line = e2.LineNumber;

                        ObjectHelpers.DynamicInvoke(OnError, e2.Description, new dynamic[] { err });
                    }
                };
            };

            fail = new WebBrowserNavigateErrorEventHandler(delegate(object s, WebBrowserNavigateErrorEventArgs e)
            {
                browser.NavigateError     -= fail;
                browser.DocumentCompleted -= completed;
                browser.Navigated         -= navigated;

                if (callback != null)
                {
                    ObjectHelpers.DynamicInvoke(callback, "fail");
                }

                done = true;

                if (OnLoadFinished != null)
                {
                    ObjectHelpers.DynamicInvoke(OnLoadFinished, "fail");
                }
                navigationType = "Unknown";
            });



            completed = new WebBrowserDocumentCompletedEventHandler(delegate(object s, WebBrowserDocumentCompletedEventArgs e)
            {
                frameCount++;

                var complete = false;

                if (browser.Document != null)
                {
                    HtmlWindow win = browser.Document.Window;
                    if (!(win.Frames.Count > frameCount && win.Frames.Count > 0))
                    {
                        complete = true;
                    }
                }
                else
                {
                    complete = true;
                }


                if (complete)
                {
                    EvaluateAsync(ResourceHelpers.ReadResource("browser/bootstrap.js"));
                    browser.NavigateError     -= fail;
                    browser.DocumentCompleted -= completed;
                    frame              = browser.Document.Window;
                    browser.Navigated -= navigated;

                    var width    = browser.Document.Body.ScrollRectangle.Width;
                    var height   = browser.Document.Body.ScrollRectangle.Height;
                    browser.Size = new Size(width, height);

                    if (callback != null)
                    {
                        ObjectHelpers.DynamicInvoke(callback, "success");
                    }

                    done = true;

                    if (OnLoadFinished != null)
                    {
                        ObjectHelpers.DynamicInvoke(OnLoadFinished, "success");
                    }
                    navigationType = "Unknown";
                }
            });

            var headers = string.Empty;

            if (CustomHeaders != null)
            {
                foreach (var name in CustomHeaders.GetDynamicMemberNames())
                {
                    headers += string.Format("{0}: {1}\r\n", (string)name, CustomHeaders[name]);
                }
            }

            switch (method)
            {
            case "GET":
                browser.NavigateError     += fail;
                browser.DocumentCompleted += completed;
                browser.Navigated         += navigated;
                browser.Navigate(url, "", null, headers);
                break;

            case "POST":
                if (string.IsNullOrEmpty(data))
                {
                    data = " ";
                }
                browser.NavigateError     += fail;
                browser.DocumentCompleted += completed;
                browser.Navigated         += navigated;
                browser.Navigate(url, "", global::System.Text.Encoding.UTF8.GetBytes(data), headers);
                break;

            default:
                throw new Exception();
            }

            while (callback == null && !done)
            {
                Thread.Sleep(10);
                Application.DoEvents();
            }
        }
Exemple #26
0
        public HttpRequest WithHeader(string name, object value)
        {
            CustomHeaders.Add(name, value);

            return(this);
        }
Exemple #27
0
        public async Task <IActionResult> GetSubGridPatches(string ecSerial,
                                                            double machineLatitude, double machineLongitude,
                                                            double bottomLeftX, double bottomLeftY, double topRightX, double topRightY)
        {
            var patchesRequest = new PatchesRequest(ecSerial, machineLatitude, machineLongitude,
                                                    new BoundingBox2DGrid(bottomLeftX, bottomLeftY, topRightX, topRightY));

            Log.LogInformation($"{nameof(GetSubGridPatches)}: {JsonConvert.SerializeObject(patchesRequest)}");

            // todoJeannie temporary to look into the DID info available.
            Log.LogDebug($"{nameof(GetSubGridPatches)}: customHeaders {CustomHeaders.LogHeaders()}");

            try
            {
                patchesRequest.Validate();

                // identify VSS projectUid and CustomerUid
                var tfaHelper = new TagFileAuthHelper(LoggerFactory, ConfigStore, TagFileAuthProjectV5Proxy);
                var tfaResult = await tfaHelper.GetProjectUid(patchesRequest.ECSerial, patchesRequest.MachineLatitude, patchesRequest.MachineLongitude);

                if (tfaResult.Code != 0 || string.IsNullOrEmpty(tfaResult.ProjectUid) || string.IsNullOrEmpty(tfaResult.CustomerUid))
                {
                    var errorMessage = $"Unable to identify a unique project or customer. Result: {JsonConvert.SerializeObject(tfaResult)}";
                    Log.LogInformation(errorMessage);
                    return(BadRequest(new PatchSubgridsProtobufResult(tfaResult.Code, tfaResult.Message)));
                }

                Log.LogInformation($"{nameof(GetSubGridPatches)}: tfaResult {JsonConvert.SerializeObject(tfaResult)}");

                // Set customerUid for downstream service calls e.g. ProjectSvc
                Log.LogInformation($"{nameof(GetSubGridPatches)}: requestHeaders {JsonConvert.SerializeObject(Request.Headers)} PrincipalCustomerUID {((RaptorPrincipal) User).CustomerUid} authNContext {JsonConvert.SerializeObject(((RaptorPrincipal) User).GetAuthNContext())}");
                if (((RaptorPrincipal)User).SetCustomerUid(tfaResult.CustomerUid))
                {
                    Request.Headers[HeaderConstants.X_VISION_LINK_CUSTOMER_UID] = tfaResult.CustomerUid;
                }

                // this endpoint has no UserId so excludedSSs and targets are not relevant
                var filter = SetupCompactionFilter(Guid.Parse(tfaResult.ProjectUid), patchesRequest.BoundingBox);

                var liftSettings = SettingsManager.CompactionLiftBuildSettings(CompactionProjectSettings.DefaultSettings);
                Log.LogDebug($"{nameof(GetSubGridPatches)}: filter: {JsonConvert.SerializeObject(filter)} liftSettings: {JsonConvert.SerializeObject(liftSettings)}");

                var requestPatchId            = 0;
                var requestPatchSize          = 1000; // max # sub-grids to scan
                var requestIncludeTimeOffsets = true;
                var patchRequest = new PatchRequest(
                    null, // obsolete
                    Guid.Parse(tfaResult.ProjectUid),
                    new Guid(),
                    DisplayMode.Height,
                    null,
                    liftSettings,
                    false,
                    VolumesType.None,
                    VelociraptorConstants.VOLUME_CHANGE_TOLERANCE,
                    null, filter, null, FilterLayerMethod.AutoMapReset,
                    requestPatchId, requestPatchSize, requestIncludeTimeOffsets);

                patchRequest.Validate();

                var v2PatchRequestResponse = await WithServiceExceptionTryExecuteAsync(() => RequestExecutorContainerFactory
                                                                                       .Build <CompactionSinglePatchExecutor>(LoggerFactory, ConfigStore, trexCompactionDataProxy : TRexCompactionDataProxy,
                                                                                                                              customHeaders : CustomHeaders, userId : GetUserId(), fileImportProxy : FileImportProxy)
                                                                                       .ProcessAsync(patchRequest));

                var v2PatchRequestFinalResponse = AutoMapperUtility.Automapper.Map <PatchSubgridsProtobufResult>(v2PatchRequestResponse);
                return(Ok(v2PatchRequestFinalResponse));
            }
            catch (ServiceException se)
            {
                Log.LogError(se, $"{nameof(GetSubGridPatches)} Exception thrown: ");
                var actionResult = StatusCode((int)se.Code, new PatchSubgridsProtobufResult(se.GetResult.Code, se.GetResult.Message));
                return(actionResult);
            }
        }
Exemple #28
0
        /// <summary>
        ///     Parses a single header and sets member variables according to it.
        /// </summary>
        /// <param name="headerName">The name of the header</param>
        /// <param name="headerValue">The value of the header in unfolded state (only one line)</param>
        /// <exception cref="ArgumentNullException">
        ///     If <paramref name="headerName" /> or <paramref name="headerValue" /> is
        ///     <see langword="null" />
        /// </exception>
        private void ParseHeader(string headerName, string headerValue)
        {
            if (headerName == null)
            {
                throw new ArgumentNullException(nameof(headerName));
            }

            if (headerValue == null)
            {
                throw new ArgumentNullException(nameof(headerValue));
            }

            switch (headerName.ToUpperInvariant())
            {
            // See http://tools.ietf.org/html/rfc5322#section-3.6.3
            case "TO":
                To = RfcMailAddress.ParseMailAddresses(headerValue);
                break;

            // See http://tools.ietf.org/html/rfc5322#section-3.6.3
            case "CC":
                Cc = RfcMailAddress.ParseMailAddresses(headerValue);
                break;

            // See http://tools.ietf.org/html/rfc5322#section-3.6.3
            case "BCC":
                Bcc = RfcMailAddress.ParseMailAddresses(headerValue);
                break;

            // See http://tools.ietf.org/html/rfc5322#section-3.6.2
            case "FROM":
                // There is only one MailAddress in the from field
                From = RfcMailAddress.ParseMailAddress(headerValue);
                break;

            // http://tools.ietf.org/html/rfc5322#section-3.6.2
            // The implementation here might be wrong
            case "REPLY-TO":
                // This field may actually be a list of addresses, but no
                // such case has been encountered
                ReplyTo = RfcMailAddress.ParseMailAddress(headerValue);
                break;

            // http://tools.ietf.org/html/rfc5322#section-3.6.2
            case "SENDER":
                Sender = RfcMailAddress.ParseMailAddress(headerValue);
                break;

            // See http://tools.ietf.org/html/rfc5322#section-3.6.5
            // RFC 5322:
            // The "Keywords:" field contains a comma-separated list of one or more
            // words or quoted-strings.
            // The field are intended to have only human-readable content
            // with information about the message
            case "KEYWORDS":
                var keywordsTemp = headerValue.Split(',');
                foreach (var keyword in keywordsTemp)
                {
                    Keywords.Add(Utility.RemoveQuotesIfAny(keyword.Trim()));
                }
                break;

            // See http://tools.ietf.org/html/rfc5322#section-3.6.7
            case "RECEIVED":
                // Simply add the value to the list
                Received.Add(new Received(headerValue.Trim()));
                break;

            case "IMPORTANCE":
                Importance = HeaderFieldParser.ParseImportance(headerValue.Trim());
                break;

            // See http://tools.ietf.org/html/rfc3798#section-2.1
            case "DISPOSITION-NOTIFICATION-TO":
                DispositionNotificationTo = RfcMailAddress.ParseMailAddresses(headerValue);
                break;

            case "MIME-VERSION":
                MimeVersion = headerValue.Trim();
                break;

            // See http://tools.ietf.org/html/rfc5322#section-3.6.5
            case "SUBJECT":
                Subject = EncodedWord.Decode(headerValue);
                break;

            // See http://tools.ietf.org/html/rfc5322#section-3.6.7
            case "RETURN-PATH":
                // Return-paths does not include a username, but we
                // may still use the address parser
                ReturnPath = RfcMailAddress.ParseMailAddress(headerValue);
                break;

            // See http://tools.ietf.org/html/rfc5322#section-3.6.4
            // Example Message-ID
            // <*****@*****.**>
            case "MESSAGE-ID":
                MessageId = HeaderFieldParser.ParseId(headerValue);
                break;

            // See http://tools.ietf.org/html/rfc5322#section-3.6.4
            case "IN-REPLY-TO":
                InReplyTo = HeaderFieldParser.ParseMultipleIDs(headerValue);
                break;

            // See http://tools.ietf.org/html/rfc5322#section-3.6.4
            case "REFERENCES":
                References = HeaderFieldParser.ParseMultipleIDs(headerValue);
                break;

            // See http://tools.ietf.org/html/rfc5322#section-3.6.1))
            case "DATE":
                Date     = headerValue.Trim();
                DateSent = Rfc2822DateTime.StringToDate(headerValue);
                break;

            // See http://tools.ietf.org/html/rfc2045#section-6
            // See ContentTransferEncoding class for more details
            case "CONTENT-TRANSFER-ENCODING":
                ContentTransferEncoding = HeaderFieldParser.ParseContentTransferEncoding(headerValue.Trim());
                break;

            // See http://tools.ietf.org/html/rfc2045#section-8
            case "CONTENT-DESCRIPTION":
                // Human description of for example a file. Can be encoded
                ContentDescription = EncodedWord.Decode(headerValue.Trim());
                break;

            // See http://tools.ietf.org/html/rfc2045#section-5.1
            // Example: Content-type: text/plain; charset="us-ascii"
            case "CONTENT-TYPE":
                ContentType = HeaderFieldParser.ParseContentType(headerValue);
                break;

            // See http://tools.ietf.org/html/rfc2183
            case "CONTENT-DISPOSITION":
                ContentDisposition = HeaderFieldParser.ParseContentDisposition(headerValue);
                break;

            // See http://tools.ietf.org/html/rfc2045#section-7
            // Example: <foo4*[email protected]>
            case "CONTENT-ID":
                ContentId = HeaderFieldParser.ParseId(headerValue);
                break;

            default:
                // This is an unknown header

                // Custom headers are allowed. That means headers
                // that are not mentionen in the RFC.
                // Such headers start with the letter "X"
                // We do not have any special parsing of such

                // Add it to custom headers
                if (CustomHeaders.ContainsKey(headerName))
                {
                    CustomHeaders[headerName].Add(headerValue);
                }
                else
                {
                    CustomHeaders.Add(headerName, new List <string> {
                        headerValue
                    });
                }

                break;
            }
        }
        public async Task StartDownload()
        {
            try
            {
                ProgressBar.Tag       = this;
                ProgressLabel.Text    = "";
                ProgressLabel.Visible = true;
                Directory.CreateDirectory(Path.GetDirectoryName(SavePath));
                FileInfo     file          = new FileInfo(SavePath);
                DialogResult overwriteFile = DialogResult.Yes;
                if (file.Exists)
                {
                    switch (ParentDownload.OverwriteMode)
                    {
                    case 0:
                        overwriteFile = DialogResult.No;
                        break;

                    case 1:
                        overwriteFile = DialogResult.Yes;
                        break;

                    case 2:
                        if (FileInfo.Modified > file.CreationTime)
                        {
                            overwriteFile = DialogResult.Yes;
                        }
                        else
                        {
                            overwriteFile = DialogResult.No;
                        }
                        break;

                    case 3:
                        overwriteFile = MessageBox.Show($"File [{file.Name}] already exists. Overwrite?", "", MessageBoxButtons.YesNo);
                        break;
                    }
                    if (overwriteFile == DialogResult.Yes)
                    {
                        file.Delete();
                    }
                }

                if (overwriteFile == DialogResult.Yes)
                {
                    CustomHeaders.Add("X-Requested-With", "XMLHttpRequest");
                    string downloadPath = EncodeWebUrl(FileInfo.PublicUrl.OriginalString);
                    if (ParentDownload.CloudService == CloudServiceType.Allsync)
                    {
                        var encodedUrl = new Uri(downloadPath);
                        var host       = encodedUrl.Host;
                        downloadPath = $"https://{host}/public.php/webdav{EncodeAllsyncUrl(FileInfo.Path)}";
                    }

                    //var logFileName = $"download-log-{DateTime.Now.ToString("MM-dd-yyyy")}.txt";
                    //string log = $"{DateTime.Now}\ndownloadPath: {downloadPath}\nSavePath: {SavePath}\n";
                    //File.AppendAllText(logFileName, log);

                    DownloadTask = DownloadFileAsync(downloadPath, SavePath, Progress, ParentDownload.cancellationTokenSource.Token, _networkCredential);
                    await DownloadTask;
                }
                ParentDownload.UpdateQueue(this);
            }
            catch (Exception ex)
            {
                if (DownloadTask.IsCanceled)
                {
                    DownloadTask.Dispose();
                }
                //MessageBox.Show(ex.Message);
            }
        }
Exemple #30
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            // Setup
            var request = new Request();

            request.Setup(data.GlobalSettings, securityProtocol, AutoRedirect, data.ConfigSettings.MaxRedirects, AcceptEncoding);

            var localUrl = ReplaceValues(Url, data);

            data.Log(new LogEntry($"Calling URL: {localUrl}", Colors.MediumTurquoise));

            // Set content
            switch (RequestType)
            {
            case RequestType.Standard:
                request.SetStandardContent(ReplaceValues(PostData, data), ReplaceValues(ContentType, data), Method, EncodeContent, GetLogBuffer(data));
                break;

            case RequestType.BasicAuth:
                request.SetBasicAuth(ReplaceValues(AuthUser, data), ReplaceValues(AuthPass, data));
                break;

            case RequestType.Multipart:
                var contents = MultipartContents.Select(m =>
                                                        new MultipartContent()
                {
                    Name        = ReplaceValues(m.Name, data),
                    Value       = ReplaceValues(m.Value, data),
                    ContentType = ReplaceValues(m.Value, data),
                    Type        = m.Type
                });
                request.SetMultipartContent(contents, ReplaceValues(MultipartBoundary, data), GetLogBuffer(data));
                break;

            case RequestType.Raw:
                request.SetRawContent(ReplaceValues(RawData, data), ReplaceValues(ContentType, data), Method, GetLogBuffer(data));
                break;
            }

            // Set proxy
            if (data.UseProxies)
            {
                request.SetProxy(data.Proxy);
            }

            // Set headers
            data.Log(new LogEntry("Sent Headers:", Colors.DarkTurquoise));
            var headers = CustomHeaders.Select(h =>
                                               new KeyValuePair <string, string>(ReplaceValues(h.Key, data), ReplaceValues(h.Value, data))
                                               ).ToDictionary(h => h.Key, h => h.Value);

            request.SetHeaders(headers, AcceptEncoding, GetLogBuffer(data));

            // Set cookies
            data.Log(new LogEntry("Sent Cookies:", Colors.MediumTurquoise));

            foreach (var cookie in CustomCookies) // Add new user-defined custom cookies to the bot's cookie jar
            {
                data.Cookies[ReplaceValues(cookie.Key, data)] = ReplaceValues(cookie.Value, data);
            }

            request.SetCookies(data.Cookies, GetLogBuffer(data));

            // End the request part
            data.LogNewLine();

            // Perform the request
            try
            {
                (data.Address, data.ResponseCode, data.ResponseHeaders, data.Cookies) = request.Perform(localUrl, Method, GetLogBuffer(data));
            }
            catch (Exception ex)
            {
                if (data.ConfigSettings.IgnoreResponseErrors)
                {
                    data.Log(new LogEntry(ex.Message, Colors.Tomato));
                    data.ResponseSource = ex.Message;
                    return;
                }
                throw;
            }

            // Save the response content
            switch (ResponseType)
            {
            case ResponseType.String:
                data.ResponseSource = request.SaveString(ReadResponseSource, data.ResponseHeaders, GetLogBuffer(data));
                break;

            case ResponseType.File:
                if (SaveAsScreenshot)
                {
                    Files.SaveScreenshot(request.GetResponseStream(), data);     // Read the stream
                    data.Log(new LogEntry("File saved as screenshot", Colors.Green));
                }
                else
                {
                    request.SaveFile(ReplaceValues(DownloadPath, data), GetLogBuffer(data));
                }
                break;

            case ResponseType.Base64String:
                var base64 = Convert.ToBase64String(request.GetResponseStream().ToArray());
                InsertVariable(data, false, base64, OutputVariable);
                break;

            default:
                break;
            }
        }