Пример #1
0
        public override void Specify()
        {
            var site = beforeAll(() => IISExpressDriver.StartServer());

            beforeAll(delegate() {
                var hostName = new Uri(site.UrlFor("")).Host;

                expect(() => hostName.Contains("localhost"));

                PSHostsFile.HostsFile.Set(hostName, "127.0.0.1");
            });

            describe("the web application's configuration", delegate()
            {
                var browser = beforeAll(() => new FirefoxDriver());

                it("should have a functioning database connection string", delegate() {

                    browser.Navigate().GoToUrl(site.UrlFor("/Check"));

                    var errorElement = browser.FindElement(BySizzle.CssSelector("#error"));

                    string actual = errorElement.Text.Trim();

                    Assert.That(string.IsNullOrEmpty(actual), "SQL configuration error detected.  Do you have SQL express installed and setup?  If not, you can get it here: http://www.microsoft.com/download/en/details.aspx?id=26729 \nServer reported error:\n\n" + actual);
                });
            });
        }
Пример #2
0
        /// <summary>
        /// This method tries to close all oppened explorer instanes that contain folder path
        /// </summary>
        /// <param name="folder"></param>
        /// <returns>Returns false if error occured, or true if there were no explorer instances or instanses were closed</returns>
        public static bool TryCloseExplorerInstances(string folder)
        {
            bool success = false;

            try
            {
                string       origin = new System.Uri(folder).AbsoluteUri.ToLower(); //folder must be converted to Uri
                ShellWindows sw     = new SHDocVw.ShellWindows();
                foreach (InternetExplorer ie in sw)
                {
                    if (ie == null || ie.LocationURL.IsNullOrEmpty())
                    {
                        continue;
                    }

                    string location = new System.Uri(ie.LocationURL).AbsoluteUri.ToLower(); //location must be converter to Uri in order to match origin
                    if (location.Contains(origin))                                          //type.Equals("explorer") && //checking type might be required in some cases, if at leats works for "explorer"
                    {
                        ie.Quit();
                        Thread.Sleep(200);
                    }
                }

                success = true;
            }
            catch (Exception ex)
            {
                ex.ToOutput();
                success = false;
            }

            return(success);
        }
Пример #3
0
 private string BuildHost(string website)
 {
     var host = new Uri(website, UriKind.Absolute).Host;
     if (host.Contains("www."))
     {
         host = host.Substring(4);
     }
     return host;
 }
 private string get_relative_url_to_app()
 {
     var relative_path_when_run_from_command_line = @"..\..\..\";
     var url = new Uri("file:///"+Path.Combine(Environment.CurrentDirectory, relative_path_when_run_from_command_line)).ToString();
     var still_not_up_enough_directories = url.Contains("dotNET-SpecFlow");
     if (still_not_up_enough_directories)
     {
         var relative_path_when_run_from_visual_studio = @"..\..\..\..\";
         url = new Uri("file:///" + Path.Combine(Environment.CurrentDirectory, relative_path_when_run_from_visual_studio)).ToString();
     }
     return url;
 }
Пример #5
0
        async Task <List <NSHttpCookie> > GetCookiesFromNativeStore(string url)
        {
            NSHttpCookie[] _initialCookiesLoaded = null;
            if (System.Maui.Maui.IsiOS11OrNewer)
            {
                _initialCookiesLoaded = await Configuration.WebsiteDataStore.HttpCookieStore.GetAllCookiesAsync();
            }
            else
            {
                // I haven't found a different way to get the cookies pre ios 11
                var cookieString = await WebView.EvaluateJavaScriptAsync("document.cookie");

                if (cookieString != null)
                {
                    CookieContainer extractCookies = new CookieContainer();
                    var             uri            = new Uri(url);

                    foreach (var cookie in cookieString.Split(';'))
                    {
                        extractCookies.SetCookies(uri, cookie);
                    }

                    var extracted = extractCookies.GetCookies(uri);
                    _initialCookiesLoaded = new NSHttpCookie[extracted.Count];
                    for (int i = 0; i < extracted.Count; i++)
                    {
                        _initialCookiesLoaded[i] = new NSHttpCookie(extracted[i]);
                    }
                }
            }

            _initialCookiesLoaded = _initialCookiesLoaded ?? new NSHttpCookie[0];

            List <NSHttpCookie> existingCookies = new List <NSHttpCookie>();
            string domain = new Uri(url).Host;

            foreach (var cookie in _initialCookiesLoaded)
            {
                // we don't care that much about this being accurate
                // the cookie container will split the cookies up more correctly
                if (!cookie.Domain.Contains(domain) && !domain.Contains(cookie.Domain))
                {
                    continue;
                }

                existingCookies.Add(cookie);
            }

            return(existingCookies);
        }
        /*Generic section*/
        public async Task <AzureOperationResponse <string> > BeginHttpMessagesAsyncWithFullResponse(HttpMethod method, string path, IDictionary <string, IList <string> > queries = null, string fragment = null, Object content = null, IDictionary <string, IList <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (path == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "path");
            }
            if (path.Length > 0)
            {
                if (path.StartsWith("/") && Client.EndsWithSlash)
                {
                    path = path.Substring(1);
                }
                else if (!path.StartsWith("/") && !Client.EndsWithSlash)
                {
                    path = "/" + path;
                }
            }

            if (method == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "method");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "BeginSend", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(_baseUrl + path).ToString();

            if (queries != null)
            {
                foreach (string key in queries.Keys)
                {
                    _url += (_url.Contains("?") ? "&" : "?") + key + "=" + string.Join(",", queries[key]);
                }
            }
            if (!String.IsNullOrEmpty(fragment))
            {
                _url += "#" + fragment;
            }
            // Create HTTP transport objects
            var _httpRequest = new System.Net.Http.HttpRequestMessage();

            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = method;
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }
            // Serialize Request
            if (content != null)
            {
                _httpRequest.Content = new StringContent((string)content, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();

            // Create Result
            var _result = new AzureOperationResponse <string>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }

            _result.Body = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
        /// <summary>
        /// Check file path availability
        /// </summary>
        /// <remarks>
        /// Check if a file path is available.
        /// </remarks>
        /// <param name='location'>
        /// The location
        /// </param>
        /// <param name='name'>
        /// Resource name to verify.
        /// </param>
        /// <param name='type'>
        /// Resource type used for verification. Possible values include:
        /// 'Microsoft.NetApp/netAppAccounts',
        /// 'Microsoft.NetApp/netAppAccounts/capacityPools',
        /// 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes',
        /// 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots'
        /// </param>
        /// <param name='resourceGroup'>
        /// Resource group name.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <CheckAvailabilityResponse> > CheckFilePathAvailabilityWithHttpMessagesAsync(string location, string name, string type, string resourceGroup, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            string apiVersion = "2021-02-01";

            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (location == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "location");
            }
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            if (name == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "name");
            }
            if (type == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "type");
            }
            if (resourceGroup == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroup");
            }
            ResourceNameAvailabilityRequest body = new ResourceNameAvailabilityRequest();

            if (name != null || type != null || resourceGroup != null)
            {
                body.Name          = name;
                body.Type          = type;
                body.ResourceGroup = resourceGroup;
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("location", location);
                tracingParameters.Add("body", body);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "CheckFilePathAvailability", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.NetApp/locations/{location}/checkFilePathAvailability").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
            List <string> _queryParameters = new List <string>();

            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (body != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <CheckAvailabilityResponse>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <CheckAvailabilityResponse>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Пример #8
0
        public async Task <AzureOperationResponse <string> > GetContentWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, string runbookName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (resourceGroupName != null)
            {
                if (resourceGroupName.Length > 90)
                {
                    throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
                }
                if (resourceGroupName.Length < 1)
                {
                    throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
                }
                if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
                {
                    throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
                }
            }
            if (automationAccountName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName");
            }
            if (runbookName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "runbookName");
            }
            //string apiVersion = "2015-10-31";
            string apiVersion = "2017-05-15-preview";
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("automationAccountName", automationAccountName);
                tracingParameters.Add("runbookName", runbookName);
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "GetContent", tracingParameters);
            }
            // Construct URL
            string _baseUrl = Client.BaseUri.AbsoluteUri;
            string _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/runbooks/{runbookName}/content").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName));
            _url = _url.Replace("{runbookName}", System.Uri.EscapeDataString(runbookName));
            List <string> _queryParameters = new List <string>();

            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage  _httpRequest  = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (KeyValuePair <string, List <string> > _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                CloudException ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            AzureOperationResponse <string> _result = new AzureOperationResponse <string>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    //Custom: No deserialize, just return string
                    _result.Body = _responseContent;
                    //Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<string>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Пример #9
0
    /// <summary>
    /// 执行 HttpWebRequest 请求
    /// </summary>
    /// <param name="method">协议方法的类型 WebRequestMethods.Http.XXX</param>
    private static string Request(
      string method,
      string url,
      object parameters = null,
      Encoding encode = null,
      string cookie = null,
      string referer = null,
      string userAgent = null,
      bool? allowAutoRedirect = null,
      string returnHeadersValue = null,
      bool? returnExceptionMessageIfError = null)
    {
      // 验证 URL
      if (string.IsNullOrEmpty(url) || !Regex.IsMatch(url, @"^https?\:\/\/[^/].+", RegexOptions.IgnoreCase))
      {
        return returnExceptionMessageIfError == true ? "无法识别该 URI 前缀。" : string.Empty;
      }

      try
      {
        url = new Uri(url).ToString(); // 此步会将“http://www.baidu.com”变成“http://www.baidu.com/”

        //// 配置请求

        // 拼接参数
        string ps = joinParameters(parameters);

        if (method == WebRequestMethods.Http.Get && ps.Length > 0)
        {
          url += (url.Contains("?") ? "&" : "?") + ps;
        }

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = method;
        req.Headers.Set("Cache-Control", "no-cache");
        req.Headers.Set("Pragma", "no-cache");

        if (!string.IsNullOrWhiteSpace(cookie)) { req.Headers["Cookie"] = cookie; }
        if (!string.IsNullOrWhiteSpace(referer)) { req.Referer = referer; }
        if (!string.IsNullOrWhiteSpace(userAgent)) { req.UserAgent = userAgent; }
        if (allowAutoRedirect == false) { req.AllowAutoRedirect = false; }

        if (method == WebRequestMethods.Http.Post)
        {
          // !!!写入 Post 内容必须放在所有设置之后,不然会导致设置 Referer 无效
          req.ContentLength = ps.Length;
          req.ContentType = "application/x-www-form-urlencoded";
          StreamWriter writer = new StreamWriter(req.GetRequestStream());
          writer.Write(ps);
          writer.Close();
        }

        //// 执行请求

        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

        if (!string.IsNullOrWhiteSpace(returnHeadersValue))
        {
          return resp.Headers[returnHeadersValue];
        }

        Encoding pageEncoding = encode != null ? encode : (string.IsNullOrWhiteSpace(resp.CharacterSet) ? Encoding.UTF8 : Encoding.GetEncoding(resp.CharacterSet));
        Stream receiveStream = resp.GetResponseStream();
        StreamReader readStream = new StreamReader(receiveStream, pageEncoding);
        return readStream.ReadToEnd();
      }
      catch (Exception ex)
      {
        return returnExceptionMessageIfError == true ? ex.Message : string.Empty;
      }
    }
Пример #10
0
        /// <summary>
        /// Create a system topic.
        /// </summary>
        /// <remarks>
        /// Asynchronously creates a new topic with the specified parameters.
        /// </remarks>
        /// <param name='_ResourceGroupName'>
        /// The name of the resource group within the user's subscription.
        /// </param>
        /// <param name='_SystemTopicName'>
        /// Name of the topic.
        /// </param>
        /// <param name='_SystemTopicInfo'>
        /// System Topic information.
        /// </param>
        /// <param name='_FinalTopicInfo'>
        /// The resulting System topic if successfully created.
        /// </param>
        /// <param name='_ErrorMessageAction'>
        /// Method to write exceptions to.
        /// </param>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public bool CreateOrUpdate(string _ResourceGroupName, string _SystemTopicName, SystemTopic _SystemTopicInfo, out SystemTopic _FinalTopicInfo, Action <string> _ErrorMessageAction = null)
        {
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (_ResourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (_SystemTopicName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "topicName");
            }
            if (_SystemTopicInfo == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "topicInfo");
            }
            if (_SystemTopicInfo != null)
            {
                _SystemTopicInfo.Validate();
            }
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }

            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/systemTopics/{systemTopicName}").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(_ResourceGroupName));
            _url = _url.Replace("{systemTopicName}", System.Uri.EscapeDataString(_SystemTopicName));

            List <string> _queryParameters = new List <string>();

            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(API_VERSION);
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }

            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("PUT");
            _httpRequest.RequestUri = new System.Uri(_url);

            // Serialize Request
            string _requestContent = null;

            if (_SystemTopicInfo != null)
            {
                _requestContent = JsonConvert.SerializeObject(_SystemTopicInfo, new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    Formatting        = Formatting.Indented
                });

                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            CancellationToken CancellationToken = new CancellationToken();

            CancellationToken.ThrowIfCancellationRequested();
            Client.Credentials.ProcessHttpRequestAsync(_httpRequest, CancellationToken);

            Task <HttpResponseMessage> Response = Client.HttpClient.SendAsync(_httpRequest, CancellationToken);

            Response.Wait();

            _httpResponse = Response.Result;

            Response.Dispose();

            string _responseContent;

            if (_httpResponse.StatusCode == HttpStatusCode.OK || _httpResponse.StatusCode == HttpStatusCode.Created)
            {
                Task <string> ContentReadTask = _httpResponse.Content.ReadAsStringAsync();
                ContentReadTask.Wait();

                _responseContent = ContentReadTask.Result;

                ContentReadTask.Dispose();

                try
                {
                    _FinalTopicInfo = JsonConvert.DeserializeObject <SystemTopic>(_responseContent);
                    return(true);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            else
            {
                Task <string> ContentReadTask = _httpResponse.Content.ReadAsStringAsync();
                ContentReadTask.Wait();

                _responseContent = ContentReadTask.Result;
                _ErrorMessageAction?.Invoke(_responseContent);

                ContentReadTask.Dispose();
            }

            _FinalTopicInfo = null;
            return(false);
        }
Пример #11
0
        public async Task <AzureOperationResponse <R> > SendAsync <R>(
            string requestDescription,
            string httpMethod,
            string requestSuffix,
            object requestData,
            Dictionary <string, List <string> > customHeaders = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            // Tracing
            bool   shouldTrace  = ServiceClientTracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("requestData", requestData);
                if (ApiVersion != null)
                {
                    tracingParameters.Add("apiVersion", ApiVersion);
                }
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(invocationId, this, requestDescription, tracingParameters);
            }
            // Construct URL
            var           baseUrl          = this.BaseUri.AbsoluteUri;
            var           requestUrl       = new System.Uri(new System.Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), requestSuffix).ToString();
            List <string> _queryParameters = new List <string>();

            //if (ApiVersion != null) {
            //    _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(ApiVersion)));
            //}
            if (_queryParameters.Count > 0)
            {
                requestUrl += (requestUrl.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var httpRequest = new HttpRequestMessage();
            HttpResponseMessage httpResponse = null;

            httpRequest.Method     = new HttpMethod(string.IsNullOrEmpty(httpMethod) ? "GET" : httpMethod);
            httpRequest.RequestUri = new System.Uri(requestUrl);
            // Set Headers
            if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
            {
                httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (this.AcceptLanguage != null)
            {
                if (httpRequest.Headers.Contains("accept-language"))
                {
                    httpRequest.Headers.Remove("accept-language");
                }
                httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
            }

            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (httpRequest.Headers.Contains(_header.Key))
                    {
                        httpRequest.Headers.Remove(_header.Key);
                    }
                    httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string requestContent = null;

            if (requestData != null)
            {
                requestContent      = SafeJsonConvert.SerializeObject(requestData, this.SerializationSettings);
                httpRequest.Content = new StringContent(requestContent, System.Text.Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (this.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (shouldTrace)
            {
                ServiceClientTracing.SendRequest(invocationId, httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

            if (shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
            }
            HttpStatusCode statusCode = httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string responseContent = null;

            if (statusCode != HttpStatusCode.OK)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
                try {
                    responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError errorBody = SafeJsonConvert.DeserializeObject <CloudError>(responseContent, this.DeserializationSettings);
                    if (errorBody != null)
                    {
                        ex      = new CloudException(errorBody.Message);
                        ex.Body = errorBody;
                    }
                } catch (JsonException) {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(httpRequest, requestContent);
                ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent);
                if (httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (shouldTrace)
                {
                    ServiceClientTracing.Error(invocationId, ex);
                }
                httpRequest.Dispose();
                if (httpResponse != null)
                {
                    httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var result = new AzureOperationResponse <R>();

            result.Request  = httpRequest;
            result.Response = httpResponse;
            if (httpResponse.Headers.Contains("x-ms-request-id"))
            {
                result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if (statusCode == HttpStatusCode.OK)
            {
                responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try {
                    result.Body = SafeJsonConvert.DeserializeObject <R>(responseContent, this.DeserializationSettings);
                } catch (JsonException ex) {
                    httpRequest.Dispose();
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", responseContent, ex);
                }
            }
            if (shouldTrace)
            {
                ServiceClientTracing.Exit(invocationId, result);
            }
            return(result);
        }
Пример #12
0
		private MimeType[] GetAcceptedTypes(MimeTypes registeredMimes)
		{
			var mimeTypes = new List<MimeType>();
			var originalUrl = Request.Uri.GetLeftPart(UriPartial.Authority) + Request.Url;
			var lastSegment = new Uri(originalUrl).Segments.Last();
			
			if (lastSegment.Contains(".") && (lastSegment.LastIndexOf(".") < lastSegment.Length - 1))
			{
				var extension = lastSegment.Substring(lastSegment.LastIndexOf(".") + 1);
				var mimeType = registeredMimes.GetMimeTypeForExtension(extension);

				if (mimeType != null)
					mimeTypes.Add(mimeType);
			}

			mimeTypes.AddRange(AcceptType.Parse(AcceptHeader, registeredMimes));			
			
			return mimeTypes.Distinct().ToArray();
		}
Пример #13
0
        public static async Task <AzureOperationResponse <Cluster> > BeginUpdateWithHttpMessagesAsync(this ServiceFabricManagementClient sfManagementClient, string resourceGroupName, string clusterName, dynamic parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (clusterName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "clusterName");
            }
            if (sfManagementClient.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "sfManagementClient.SubscriptionId");
            }
            if (parameters == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
            }

            string apiVersion = "2020-03-01";

            // Tracing
            bool   shouldTrace  = ServiceClientTracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("clusterName", clusterName);
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("parameters", parameters);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(invocationId, sfManagementClient, "BeginUpdate", tracingParameters);
            }

            // Construct URL
            var baseUrl = sfManagementClient.BaseUri.AbsoluteUri;
            var url     = new System.Uri(new System.Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}").ToString();

            url = url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            url = url.Replace("{clusterName}", System.Uri.EscapeDataString(clusterName));
            url = url.Replace("{subscriptionId}", System.Uri.EscapeDataString(sfManagementClient.SubscriptionId));
            List <string> _queryParameters = new List <string>();

            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }

            if (_queryParameters.Count > 0)
            {
                url += (url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }

            // Create HTTP transport objects
            var httpRequest = new HttpRequestMessage();
            HttpResponseMessage httpResponse = null;

            httpRequest.Method     = new HttpMethod("PATCH");
            httpRequest.RequestUri = new System.Uri(url);

            // Set Headers
            if (sfManagementClient.GenerateClientRequestId != null && sfManagementClient.GenerateClientRequestId.Value)
            {
                httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }

            if (sfManagementClient.AcceptLanguage != null)
            {
                if (httpRequest.Headers.Contains("accept-language"))
                {
                    httpRequest.Headers.Remove("accept-language");
                }
                httpRequest.Headers.TryAddWithoutValidation("accept-language", sfManagementClient.AcceptLanguage);
            }

            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (httpRequest.Headers.Contains(_header.Key))
                    {
                        httpRequest.Headers.Remove(_header.Key);
                    }
                    httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string requestContent = null;

            if (parameters != null)
            {
                var dynamicSerializationSettings = sfManagementClient.SerializationSettings.DeepCopy();
                dynamicSerializationSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();

                requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, dynamicSerializationSettings);
                httpRequest.Content = new StringContent(requestContent, System.Text.Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }

            // Set Credentials
            if (sfManagementClient.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await sfManagementClient.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
            }

            // Send Request
            if (shouldTrace)
            {
                ServiceClientTracing.SendRequest(invocationId, httpRequest);
            }

            cancellationToken.ThrowIfCancellationRequested();
            httpResponse = await sfManagementClient.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

            if (shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
            }

            HttpStatusCode statusCode = httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string responseContent = null;

            if ((int)statusCode != 200 && (int)statusCode != 202)
            {
                var ex = new ErrorModelException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
                try
                {
                    responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    ErrorModel _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorModel>(responseContent, sfManagementClient.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }

                ex.Request  = new HttpRequestMessageWrapper(httpRequest, requestContent);
                ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent);
                if (shouldTrace)
                {
                    ServiceClientTracing.Error(invocationId, ex);
                }

                httpRequest.Dispose();
                if (httpResponse != null)
                {
                    httpResponse.Dispose();
                }

                throw ex;
            }

            // Create Result
            var result = new AzureOperationResponse <Cluster>();

            result.Request  = httpRequest;
            result.Response = httpResponse;
            if (httpResponse.Headers.Contains("x-ms-request-id"))
            {
                result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }

            // Deserialize Response
            if ((int)statusCode == 200)
            {
                responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Cluster>(responseContent, sfManagementClient.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    httpRequest.Dispose();
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", responseContent, ex);
                }
            }

            // Deserialize Response
            if ((int)statusCode == 202)
            {
                responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Cluster>(responseContent, sfManagementClient.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    httpRequest.Dispose();
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", responseContent, ex);
                }
            }

            if (shouldTrace)
            {
                ServiceClientTracing.Exit(invocationId, result);
            }

            return(result);
        }
        public async Task <AzureOperationResponse <ResolvedSubscription> > IndexAsync(string Value)
        {
            string contenttype         = "application/json";
            string xMsMarketplaceToken = "";
            string requestId           = "";
            string correlationId       = "";
            string AcceptLanguage      = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjVPZjlQNUY5Z0NDd0NtRjJCT0hIeEREUS1EayIsImtpZCI6IjVPZjlQNUY5Z0NDd0NtRjJCT0hIeEREUS1EayJ9.eyJhdWQiOiIyMGU5NDBiMy00Yzc3LTRiMGItOWE1My05ZTE2YTFiMDEwYTciLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC82MmQxZmFlZS02NGM0LTQwMzMtYjFmZC04MzdhNTE4ZmY4OTgvIiwiaWF0IjoxNjA4OTgzMTc5LCJuYmYiOjE2MDg5ODMxNzksImV4cCI6MTYwODk4NzA3OSwiYWlvIjoiRTJKZ1lORFdZTklOME1xOTdGRFRwM3N5K3o4SEFBPT0iLCJhcHBpZCI6ImY0NWRlYTBmLWQ3NzgtNGVkOS05NDIzLTJhNDcyMjNkNmZjNSIsImFwcGlkYWNyIjoiMSIsImlkcCI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0LzYyZDFmYWVlLTY0YzQtNDAzMy1iMWZkLTgzN2E1MThmZjg5OC8iLCJvaWQiOiJjNjU5Zjc5NS03ZWNiLTRmMmEtOGY5Ny0zOThiODdhODhiNTQiLCJyaCI6IjAuQVNBQTd2clJZc1JrTTBDeF9ZTjZVWV80bUFfcVhmUjQxOWxPbENNcVJ5STliOFVnQUFBLiIsInN1YiI6ImM2NTlmNzk1LTdlY2ItNGYyYS04Zjk3LTM5OGI4N2E4OGI1NCIsInRpZCI6IjYyZDFmYWVlLTY0YzQtNDAzMy1iMWZkLTgzN2E1MThmZjg5OCIsInV0aSI6Ii1sVG9wdG1TRzB5a3Z6NUNYaHpFQUEiLCJ2ZXIiOiIxLjAifQ.1ifS_-WO3mHD4LGYjvMSvEKDODg2aSthcCc2kSAY17JMzDv_paNwoQaAue65zbX9K6G3oJ1JQScKyDZY2OlIVO1H-FoNSYhpSg8y6esmqXxwrFAF_gtW7tYAFxpPwQoEDjoxHnxHAFxJDriVirry951vBM8CVAZdYqae1BCw0iAejQj8T32ENrmTQoqYDb9mFJ1YZ_DWqzhcQ84YZ-54d0q9UXL2AV47vxCCdnvyYKgDLgtEgKfYbQU1gFwXiH8UxSyNLBVJDkGFb0gzk8B8uq-CaXcTATO_xralSfME65vF3xJ7PsHqkvIl71wX5gqTDgodSdmAfpxwl-0co4t8NQ";
            Dictionary <string, List <string> > customHeaders = null;
            CancellationToken cancellationToken = default(CancellationToken);
            bool?GenerateClientRequestId        = true;

            if (xMsMarketplaceToken == null)
            {
                throw new Microsoft.Rest.ValidationException(ValidationRules.CannotBeNull, "xMsMarketplaceToken");
            }
            string apiVersion = "2018-08-31";
            // Tracing
            bool   _shouldTrace  = true;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("requestId", "");
                tracingParameters.Add("correlationId", "");
                tracingParameters.Add("xMsMarketplaceToken", xMsMarketplaceToken);
                tracingParameters.Add("cancellationToken", "");
                ServiceClientTracing.Enter(_invocationId, this, "Resolve", tracingParameters);
            }
            // Construct URL
            var           _baseUrl         = "https://marketplaceapi.microsoft.com/api";
            var           _url             = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "saas/subscriptions/resolve").ToString();
            List <string> _queryParameters = new List <string>();

            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            SerializationSettings   = new JsonSerializerSettings
            {
                Formatting            = Newtonsoft.Json.Formatting.Indented,
                DateFormatHandling    = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
                DateTimeZoneHandling  = Newtonsoft.Json.DateTimeZoneHandling.Utc,
                NullValueHandling     = Newtonsoft.Json.NullValueHandling.Ignore,
                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
                ContractResolver      = new ReadOnlyJsonContractResolver(),
                Converters            = new List <JsonConverter>
                {
                    new Iso8601TimeSpanConverter()
                }
            };
            // Set Headers
            //if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
            //{
            //    _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            //}
            if (requestId != null)
            {
                if (_httpRequest.Headers.Contains("x-ms-requestid"))
                {
                    _httpRequest.Headers.Remove("x-ms-requestid");
                }
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-requestid", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(requestId, SerializationSettings).Trim('"'));
            }


            _httpRequest.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
            if (correlationId != null)
            {
                if (_httpRequest.Headers.Contains("x-ms-correlationid"))
                {
                    _httpRequest.Headers.Remove("x-ms-correlationid");
                }
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-correlationid", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(correlationId, SerializationSettings).Trim('"'));
            }
            if (xMsMarketplaceToken != null)
            {
                if (_httpRequest.Headers.Contains("x-ms-marketplace-token"))
                {
                    _httpRequest.Headers.Remove("x-ms-marketplace-token");
                }
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-marketplace-token", xMsMarketplaceToken);
            }
            if (AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("authorization"))
                {
                    _httpRequest.Headers.Remove("authorization");
                }
                _httpRequest.Headers.TryAddWithoutValidation("authorization", AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            //if (Client.Credentials != null)
            //{
            //    cancellationToken.ThrowIfCancellationRequested();
            //    await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            //}
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 403 && (int)_statusCode != 404 && (int)_statusCode != 500)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <ResolvedSubscription>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            DeserializationSettings = new JsonSerializerSettings
            {
                DateFormatHandling    = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
                DateTimeZoneHandling  = Newtonsoft.Json.DateTimeZoneHandling.Utc,
                NullValueHandling     = Newtonsoft.Json.NullValueHandling.Ignore,
                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
                ContractResolver      = new ReadOnlyJsonContractResolver(),
                Converters            = new List <JsonConverter>
                {
                    new Iso8601TimeSpanConverter()
                }
            };
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <ResolvedSubscription>(_responseContent, DeserializationSettings);
                    var response = _result.Body;
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Пример #15
0
 private static string RemoveDuplicateSlashes(string url)
 {
     var path = new Uri(url).AbsolutePath;
     return path.Contains("//") ? url.Replace(path, path.Replace("//", "/")) : url;
 }
        /// <summary>
        /// Stops the specified connection monitor.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group containing Network Watcher.
        /// </param>
        /// <param name='networkWatcherName'>
        /// The name of the Network Watcher resource.
        /// </param>
        /// <param name='connectionMonitorName'>
        /// The name of the connection monitor.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse> BeginStopWithHttpMessagesV1Async(string resourceGroupName, string networkWatcherName, string connectionMonitorName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (networkWatcherName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
            }
            if (connectionMonitorName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "connectionMonitorName");
            }
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            string apiVersion = "2019-06-01";
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("networkWatcherName", networkWatcherName);
                tracingParameters.Add("connectionMonitorName", connectionMonitorName);
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "BeginStop", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}/stop").ToString();

            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
            _url = _url.Replace("{connectionMonitorName}", System.Uri.EscapeDataString(connectionMonitorName));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            List <string> _queryParameters = new List <string>();

            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200 && (int)_statusCode != 202)
            {
                var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponse>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
        /// <summary>
        /// This method is used to retrieve the master key for the function app. Once this method is added in the web app OpenAPI
        /// specs, this method will call that in WebAppsOperations.cs instead.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>the master key of the function app.</returns>
        public async Task <string> GetMasterKeyAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            string apiVersion = "2016-08-01";
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                var tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", ResourceGroupName);
                tracingParameters.Add("name", Name);
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Manager.Inner.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/functions/admin/masterkey").ToString();

            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(ResourceGroupName));
            _url = _url.Replace("{name}", System.Uri.EscapeDataString(Name));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Manager.Inner.SubscriptionId));
            List <string> _queryParameters = new List <string>();

            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Manager.Inner.GenerateClientRequestId != null && Manager.Inner.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Manager.Inner.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Manager.Inner.AcceptLanguage);
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Manager.Inner.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Manager.Inner.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await((WebSiteManagementClient)Manager.Inner).HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Manager.Inner.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    var map = Rest.Serialization.SafeJsonConvert.DeserializeObject <Dictionary <string, string> >(_responseContent, Manager.Inner.DeserializationSettings);
                    return(map["masterKey"]);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            return(null);
        }
Пример #18
0
 private void btnGo_Click(object sender, EventArgs args)
 {
     btnGo.Enabled = false;
     miSettings.Enabled = false;
     txtUrl.Enabled = false;
     txtLinks.Clear();
     new Thread(delegate()
     {
         try
         {
             ArrayList<string> includeList = new ArrayList<string>();
             int i = 0;
             foreach (ToolStripMenuItem item in miInclude.DropDownItems)
             {
                 if (item.Checked) { includeList.Add(mRegexList[i]); }
                 i++;
             }
             ArrayList<string> excludeList = new ArrayList<string>();
             i = 0;
             foreach (ToolStripMenuItem item in miExclude.DropDownItems)
             {
                 if (item.Checked) { excludeList.Add(mExcludeList[i]); }
                 i++;
             }
             Set<string> links = new Set<string>();
             Uri baseUrl = new Uri(txtUrl.Text);
             string html = WebUtils.GetWebPageDetectEncoding(txtUrl.Text);
             foreach (string regex in includeList)
             {
                 Regex r = new Regex(regex, RegexOptions.IgnoreCase);
                 Match m = r.Match(html);
                 while (m.Success)
                 {
                     string message = "RSS feed NOT detected.";
                     string url = m.Result("${rssUrl}").Trim();
                     url = new Uri(baseUrl, url).ToString();
                     string urlLower = url.ToLower();
                     // test whether to include link
                     bool ok = true;
                     foreach (string substr in excludeList)
                     {
                         if (urlLower.Contains(substr)) { ok = false; break; }
                     }
                     if (ok && !links.Contains(urlLower))
                     {
                         // test RSS file
                         if (miTestLinks.Checked)
                         {
                             string xml = null;
                             try { xml = WebUtils.GetWebPageDetectEncoding(url); } catch { }
                             bool rssXmlFound = xml != null && TestRssXml(xml);
                             if (rssXmlFound) { message = "RSS feed detected."; }
                             // convert Atom to RSS
                             if (xml != null && miConvertAtomToRss.Checked && !rssXmlFound && TestAtomXml(xml))
                             {
                                 url = "http://www.devtacular.com/utilities/atomtorss/?url=" + HttpUtility.HtmlEncode(url);
                                 xml = null;
                                 try { xml = WebUtils.GetWebPageDetectEncoding(url); }
                                 catch { }
                                 rssXmlFound = xml != null && TestRssXml(xml);
                                 if (rssXmlFound) { message = "RSS feed detected after converting from Atom."; }
                             }
                             else // try the format=xml trick
                             {
                                 if (miFeedburnerFormat.Checked && !rssXmlFound)
                                 {
                                     string newUrl = url + (url.Contains("?") ? "&" : "?") + "format=xml";
                                     try { xml = WebUtils.GetWebPageDetectEncoding(newUrl); } catch { }
                                     rssXmlFound = xml != null && TestRssXml(xml);
                                     if (rssXmlFound)
                                     {
                                         message = "RSS feed detected after applying the format=xml trick.";
                                         url = newUrl;
                                     }
                                 }
                             }
                             if (miRemoveNonRss.Checked && !rssXmlFound) { Invoke(delegate() { txtLinks.Text += "#"; }); }
                             Invoke(delegate() { txtLinks.Text += url + "\r\n"; });
                             if (miOutputTestResult.Checked)
                             {
                                 Invoke(delegate() { txtLinks.Text += "# " + message + "\r\n"; });
                             }
                         }
                         else
                         {
                             Invoke(delegate() { txtLinks.Text += url + "\r\n"; });
                         }
                         links.Add(urlLower);
                     }
                     m = m.NextMatch();
                 } // m.Success
             }
         }
         catch (Exception e)
         {
             TryInvoke(delegate() { txtLinks.Text += e.Message + "\r\n" + e.StackTrace; });
         }
         finally
         {
             TryInvoke(delegate() { btnGo.Enabled = txtUrl.Enabled = miSettings.Enabled = true; });
         }
     }).Start();
 }