private ProductInfoHeaderValue(ProductInfoHeaderValue source)
        {
            Contract.Requires(source != null);

            this.product = source.product;
            this.comment = source.comment;
        }
 static CommandClient()
 {
     var type = typeof(CommandClient);
     var assemblyVersion = type.GetAssembly().GetName().Version;
     string version = "{0}.{1}".FormatWith(assemblyVersion.Major, assemblyVersion.Minor);
     UserAgent = new ProductInfoHeaderValue(type.FullName, version);
 }
        private ProductInfoHeaderValue(ProductInfoHeaderValue source)
        {
            Contract.Requires(source != null);

            this.product = source.product;
            this.comment = source.comment;
        }
        public static async Task<UpdateManager> GitHubUpdateManager(
            string repoUrl,
            string applicationName = null,
            string rootDirectory = null,
            IFileDownloader urlDownloader = null,
            bool prerelease = false)
        {
            var repoUri = new Uri(repoUrl);
            var userAgent = new ProductInfoHeaderValue("Squirrel", Assembly.GetExecutingAssembly().GetName().Version.ToString());

            if (repoUri.Segments.Count() != 3) {
                throw new Exception("Repo URL must be to the root URL of the repo e.g. https://github.com/myuser/myrepo");
            }

            using (var client = new HttpClient() { BaseAddress = new Uri(gitHubUrl) }) {
                client.DefaultRequestHeaders.UserAgent.Add(userAgent);
                var response = await client.GetAsync(String.Format("/repos{0}/releases", repoUri.PathAndQuery));
                response.EnsureSuccessStatusCode();

                var releases = SimpleJson.DeserializeObject<List<Release>>(await response.Content.ReadAsStringAsync());
                var latestRelease = releases
                    .Where(x => prerelease ? x.Prerelease : !x.Prerelease)
                    .OrderByDescending(x => x.PublishedAt)
                    .First();

                var latestReleaseUrl = latestRelease.HtmlUrl.Replace("/tag/", "/download/");

                return new UpdateManager(latestReleaseUrl, applicationName, rootDirectory, urlDownloader);
            }
        }
        private ProductInfoHeaderValue(ProductInfoHeaderValue source)
        {
            Debug.Assert(source != null);

            _product = source._product;
            _comment = source._comment;
        }
Beispiel #6
0
        private ProductInfoHeaderValue(ProductInfoHeaderValue source)
        {
            Debug.Assert(source != null);

            _product = source._product;
            _comment = source._comment;
        }
        private ProductInfoHeaderValue(ProductInfoHeaderValue source)
        {
            Contract.Requires(source != null);

            _product = source._product;
            _comment = source._comment;
        }
Beispiel #8
0
 public AsyncClient(
     string auth,
     int timeout,
     ProductInfoHeaderValue userAgent,
     HttpMessageHandler httpMessageHandler = null
     )
 {
     _httpMessageHandler = httpMessageHandler ?? new HttpClientHandler();
     try
     {
         _httpClient = new HttpClient(_httpMessageHandler)
         {
             DefaultRequestHeaders =
             {
                 Authorization = new AuthenticationHeaderValue("Basic", auth),
                 Accept = {new MediaTypeWithQualityHeaderValue("application/json")},
                 UserAgent = {userAgent}
             },
             Timeout = TimeSpan.FromMilliseconds(timeout)
         };
     }
     catch
     {
         _httpClient?.Dispose();
         _httpMessageHandler.Dispose();
         throw;
     }
 }
        private ProductInfoHeaderValue(ProductInfoHeaderValue source)
        {
            Contract.Requires(source != null);

            _product = source._product;
            _comment = source._comment;
        }
    public WebDavClient (Func<Task<HttpClient>> httpClientFactory, string productName, string productVersion)
    {
      if (httpClientFactory == null)
        throw new ArgumentNullException ("httpClientFactory");

      _productInfo = new ProductInfoHeaderValue (productName, productVersion);
      _httpClientFactory = httpClientFactory;
    }
        public void ToString_UseDifferentProductInfos_AllSerializedCorrectly()
        {
            ProductInfoHeaderValue productInfo = new ProductInfoHeaderValue("product", "1.0");
            Assert.Equal("product/1.0", productInfo.ToString());

            productInfo = new ProductInfoHeaderValue("(comment)");
            Assert.Equal("(comment)", productInfo.ToString());
        }
    public WebDavClient (Func<Task<HttpClient>> httpClientFactory, string productName, string productVersion, bool closeConnectionAfterEachRequest)
    {
      if (httpClientFactory == null)
        throw new ArgumentNullException ("httpClientFactory");

      _productInfo = new ProductInfoHeaderValue (productName, productVersion);
      _httpClientFactory = httpClientFactory;
      _closeConnectionAfterEachRequest = closeConnectionAfterEachRequest;
    }
        public void Ctor_ProductOverload_MatchExpectation()
        {
            ProductInfoHeaderValue productInfo = new ProductInfoHeaderValue(new ProductHeaderValue("product"));
            Assert.Equal(new ProductHeaderValue("product"), productInfo.Product);
            Assert.Null(productInfo.Comment);

            ProductHeaderValue input = null;
            Assert.Throws<ArgumentNullException>(() => { new ProductInfoHeaderValue(input); });
        }
 private void CheckValidParsedValue(string input, int startIndex, ProductInfoHeaderValue expectedResult,
     int expectedIndex)
 {
     ProductInfoHeaderParser parser = ProductInfoHeaderParser.MultipleValueParser;
     object result = null;
     Assert.True(parser.TryParseValue(input, null, ref startIndex, out result),
         string.Format("TryParse returned false. Input: '{0}'", input));
     Assert.Equal(expectedIndex, startIndex);
     Assert.Equal(expectedResult, result);
 }
Beispiel #15
0
 public SyncClient(
     string auth,
     int timeout,
     ProductInfoHeaderValue userAgent
     )
 {
     _auth = auth;
     _timeout = timeout;
     _userAgent = userAgent.ToString();
 }
        private static HttpRequestMessage SetUpRequest(string userAgent)
        {
            var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com/");

            if (userAgent == null) return request;

            var productInfoHeaderValue = new ProductInfoHeaderValue(new ProductHeaderValue(userAgent, "Y"));
            request.Headers.UserAgent.Add(productInfoHeaderValue);
            return request;
        }
        public void Ctor_CommentOverload_MatchExpectation()
        {
            ProductInfoHeaderValue productInfo = new ProductInfoHeaderValue("(this is a comment)");
            Assert.Null(productInfo.Product);
            Assert.Equal("(this is a comment)", productInfo.Comment);

            Assert.Throws<ArgumentException>(() => { new ProductInfoHeaderValue((string)null); });
            Assert.Throws<FormatException>(() => { new ProductInfoHeaderValue("invalid comment"); });
            Assert.Throws<FormatException>(() => { new ProductInfoHeaderValue(" (leading space)"); });
            Assert.Throws<FormatException>(() => { new ProductInfoHeaderValue("(trailing space) "); });
        }
Beispiel #18
0
        static bool TryParseElement(Lexer lexer, out ProductInfoHeaderValue parsedValue)
        {
            string comment;

            parsedValue = null;
            Token t;

            if (lexer.ScanCommentOptional(out comment, out t))
            {
                if (comment == null)
                {
                    return(false);
                }

                parsedValue         = new ProductInfoHeaderValue();
                parsedValue.Comment = comment;
                return(true);
            }

            if (t == Token.Type.End)
            {
                return(true);
            }

            if (t != Token.Type.Token)
            {
                return(false);
            }

            var value = new ProductHeaderValue();

            value.Name = lexer.GetStringValue(t);

            var pos = lexer.Position;

            t = lexer.Scan();
            if (t == Token.Type.SeparatorSlash)
            {
                t = lexer.Scan();
                if (t != Token.Type.Token)
                {
                    return(false);
                }

                value.Version = lexer.GetStringValue(t);
            }
            else
            {
                lexer.Position = pos;
            }

            parsedValue = new ProductInfoHeaderValue(value);
            return(true);
        }
        public void GetHashCode_UseSameAndDifferentProductInfos_SameOrDifferentHashCodes()
        {
            ProductInfoHeaderValue productInfo1 = new ProductInfoHeaderValue("product", "1.0");
            ProductInfoHeaderValue productInfo2 = new ProductInfoHeaderValue(new ProductHeaderValue("product", "1.0"));
            ProductInfoHeaderValue productInfo3 = new ProductInfoHeaderValue("(comment)");
            ProductInfoHeaderValue productInfo4 = new ProductInfoHeaderValue("(COMMENT)");

            Assert.Equal(productInfo1.GetHashCode(), productInfo2.GetHashCode());
            Assert.NotEqual(productInfo1.GetHashCode(), productInfo3.GetHashCode());
            Assert.NotEqual(productInfo3.GetHashCode(), productInfo4.GetHashCode());
        }
        public static async Task<UpdateManager> GitHubUpdateManager(
            string repoUrl,
            string applicationName = null,
            string rootDirectory = null,
            IFileDownloader urlDownloader = null,
            bool prerelease = false,
            string accessToken = null)
        {
            var repoUri = new Uri(repoUrl);
            var userAgent = new ProductInfoHeaderValue("Squirrel", Assembly.GetExecutingAssembly().GetName().Version.ToString());

            if (repoUri.Segments.Length != 3) {
                throw new Exception("Repo URL must be to the root URL of the repo e.g. https://github.com/myuser/myrepo");
            }

            var releasesApiBuilder = new StringBuilder("repos")
                .Append(repoUri.AbsolutePath)
                .Append("/releases");

            if (!string.IsNullOrWhiteSpace(accessToken))
                releasesApiBuilder.Append("?access_token=").Append(accessToken);
            
            Uri baseAddress;

            if (repoUri.Host.EndsWith("github.com", StringComparison.OrdinalIgnoreCase)) {
                baseAddress = new Uri("https://api.github.com/");
            } else {
                // if it's not github.com, it's probably an Enterprise server
                // now the problem with Enterprise is that the API doesn't come prefixed
                // it comes suffixed
                // so the API path of http://internal.github.server.local API location is
                // http://interal.github.server.local/api/v3. 
                baseAddress = new Uri(string.Format("{0}{1}{2}/api/v3/", repoUri.Scheme, Uri.SchemeDelimiter, repoUri.Host));
            }

            // above ^^ notice the end slashes for the baseAddress, explained here: http://stackoverflow.com/a/23438417/162694

            using (var client = new HttpClient() { BaseAddress = baseAddress }) {
                client.DefaultRequestHeaders.UserAgent.Add(userAgent);
                var response = await client.GetAsync(releasesApiBuilder.ToString());
                response.EnsureSuccessStatusCode();

                var releases = SimpleJson.DeserializeObject<List<Release>>(await response.Content.ReadAsStringAsync());
                var latestRelease = releases
                    .Where(x => prerelease || !x.Prerelease)
                    .OrderByDescending(x => x.PublishedAt)
                    .First();

                var latestReleaseUrl = latestRelease.HtmlUrl.Replace("/tag/", "/download/");

                return new UpdateManager(latestReleaseUrl, applicationName, rootDirectory, urlDownloader);
            }
        }
		public void Equals ()
		{
			var value = new ProductInfoHeaderValue ("(ab)");
			Assert.AreEqual (value, new ProductInfoHeaderValue ("(ab)"), "#1");
			Assert.AreNotEqual (value, new ProductInfoHeaderValue ("(AB)"), "#2");
			Assert.AreNotEqual (value, new ProductInfoHeaderValue ("(AA)"), "#3");

			value = new ProductInfoHeaderValue ("ab", "DD");
			Assert.AreEqual (value, new ProductInfoHeaderValue ("Ab", "DD"), "#4");
			Assert.AreNotEqual (value, new ProductInfoHeaderValue ("(AB)"), "#5");
			Assert.AreEqual (value, new ProductInfoHeaderValue ("Ab", "dd"), "#6");
		}
 public void Configuration_remains_for_DefaultRequestHeaders()
 {
     var productInfo = new ProductInfoHeaderValue("OrientDb.Http", "1.0");
     var provider = GetSimpleProvider();
     var client1 = provider.GetHttpClient(c =>
     {
         c.DefaultRequestHeaders.UserAgent.Add(productInfo);
     });
     var client2 = provider.GetHttpClient();
     var actualAgent = client2.DefaultRequestHeaders.UserAgent.First();
     Assert.Equal(productInfo.Product.Name, actualAgent.Product.Name);
     Assert.Equal(productInfo.Product.Version, actualAgent.Product.Version);
 }
Beispiel #23
0
        internal static int GetProductInfoLength(string?input, int startIndex, out ProductInfoHeaderValue?parsedValue)
        {
            Debug.Assert(startIndex >= 0);

            parsedValue = null;

            if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
            {
                return(0);
            }

            int current = startIndex;

            // Caller must remove leading whitespace.
            string?            comment = null;
            ProductHeaderValue?product = null;

            if (input[current] == '(')
            {
                int commentLength = 0;
                if (HttpRuleParser.GetCommentLength(input, current, out commentLength) != HttpParseResult.Parsed)
                {
                    return(0);
                }

                comment = input.Substring(current, commentLength);

                current = current + commentLength;
                current = current + HttpRuleParser.GetWhitespaceLength(input, current);

                parsedValue = new ProductInfoHeaderValue(comment);
            }
            else
            {
                // Trailing whitespace is removed by GetProductLength().
                int productLength = ProductHeaderValue.GetProductLength(input, current, out product);

                if (productLength == 0)
                {
                    return(0);
                }

                current = current + productLength;

                parsedValue = new ProductInfoHeaderValue(product !);
            }

            return(current - startIndex);
        }
        internal static int GetProductInfoLength(string input, int startIndex, out ProductInfoHeaderValue parsedValue)
        {
            Contract.Requires(startIndex >= 0);

            parsedValue = null;

            if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
            {
                return(0);
            }

            int current = startIndex;

            // Caller must remove leading whitespaces.
            string             comment = null;
            ProductHeaderValue product = null;

            if (input[current] == '(')
            {
                int commentLength = 0;
                if (HttpRuleParser.GetCommentLength(input, current, out commentLength) != HttpParseResult.Parsed)
                {
                    return(0);
                }

                comment = input.Substring(current, commentLength);

                current = current + commentLength;
                current = current + HttpRuleParser.GetWhitespaceLength(input, current);
            }
            else
            {
                // Trailing whitespaces are removed by GetProductLength().
                int productLength = ProductHeaderValue.GetProductLength(input, current, out product);

                if (productLength == 0)
                {
                    return(0);
                }

                current = current + productLength;
            }

            parsedValue          = new ProductInfoHeaderValue();
            parsedValue._product = product;
            parsedValue._comment = comment;
            return(current - startIndex);
        }
        /// <summary>
        /// Factory method for the benefit of platform tests that need to have finer grained control of the API version
        /// </summary>
        /// <param name="credentials">The api token and secret to use</param>
        /// <param name="baseUrl">Base URL for the host</param>
        /// <param name="apiVersion">The api version to use</param>
        /// <param name="userAgent">User-Agent details to set in the header for each request</param>
        /// <returns>Initialized instance of the Judopay api client</returns>
        internal static JudoPayApi Create(Credentials credentials, string baseUrl, string apiVersion, ProductInfoHeaderValue userAgent)
        {
            var userAgentCollection = new List<ProductInfoHeaderValue>();
            userAgentCollection.Add(new ProductInfoHeaderValue("DotNetCLR", Environment.Version.ToString()));
            userAgentCollection.Add(new ProductInfoHeaderValue(Environment.OSVersion.Platform.ToString(), Environment.OSVersion.Version.ToString()));
            if (userAgent != null) userAgentCollection.Add(userAgent);
            var httpClient = new HttpClientWrapper(
                                 userAgentCollection,
                                 new AuthorizationHandler(credentials, DotNetLoggerFactory.Create(typeof(AuthorizationHandler))),
                                 new VersioningHandler(apiVersion));

            var connection = new Connection(httpClient, DotNetLoggerFactory.Create, baseUrl);
            var client = new Client(connection);

            return new JudoPayApi(DotNetLoggerFactory.Create, client);
        }
Beispiel #26
0
        public static ProductInfoHeaderValue DefaultUserAgentFactory(string productName, string productVersion)
        {
            try
            {
                var userAgent = new ProductInfoHeaderValue(productName.Replace(' ', '-'), productVersion);

                return userAgent;
            }
            catch (FormatException ex)
            {
                Debug.WriteLine("HttpDefaults.DefaultUserAgentFactory({0}, {1}) unable to construct ProductInfoHeaderValue: {2}",
                    productName, productVersion, ex.Message);

                return null;
            }
        }
        public override bool TryParseValue(string value, object storeValue, ref int index, out object parsedValue)
        {
            parsedValue = null;

            if (string.IsNullOrEmpty(value) || (index == value.Length))
            {
                return(false);
            }

            // Skip leading whitespace
            int current = index + HttpRuleParser.GetWhitespaceLength(value, index);

            if (current == value.Length)
            {
                return(false); // whitespace-only values are not valid
            }

            ProductInfoHeaderValue result = null;
            int length = ProductInfoHeaderValue.GetProductInfoLength(value, current, out result);

            if (length == 0)
            {
                return(false);
            }

            // GetProductInfoLength() already skipped trailing whitespace. No need to do it here again.
            current = current + length;

            // If we have more values, make sure we saw a whitespace before. Values like "product/1.0(comment)" are
            // invalid since there must be a whitespace between the product and the comment value.
            if (current < value.Length)
            {
                // Note that for \r\n to be a valid whitespace, it must be followed by a space/tab. I.e. it's enough if
                // we check whether the char before the next value is space/tab.
                char lastSeparatorChar = value[current - 1];
                if ((lastSeparatorChar != ' ') && (lastSeparatorChar != '\t'))
                {
                    return(false);
                }
            }

            // Separators for "User-Agent" and "Server" headers are whitespace. This is different from most other headers
            // where comma/semicolon is used as separator.
            index       = current;
            parsedValue = result;
            return(true);
        }
    public WebDavClient (
      Func<Task<HttpClient>> httpClientFactory, 
      string productName, 
      string productVersion,
      bool closeConnectionAfterEachRequest, 
      bool acceptInvalidChars,
      bool sendEtagsWithoutQuote) 
      : base (acceptInvalidChars)
    {
      if (httpClientFactory == null)
        throw new ArgumentNullException ("httpClientFactory");

      _productInfo = new ProductInfoHeaderValue (productName, productVersion);
      _httpClientFactory = httpClientFactory;
      _closeConnectionAfterEachRequest = closeConnectionAfterEachRequest;
      _sendEtagsWithoutQuote = sendEtagsWithoutQuote;
    }
        public override bool Equals(object obj)
        {
            ProductInfoHeaderValue other = obj as ProductInfoHeaderValue;

            if (other == null)
            {
                return(false);
            }

            if (_product == null)
            {
                // We compare comments using case-sensitive comparison.
                return(string.Equals(_comment, other._comment, StringComparison.Ordinal));
            }

            return(_product.Equals(other._product));
        }
        public ProductInfoHeaderValue Create()
        {
            var productName = _userAgent.Name;
            var productVersion = _userAgent.Version;

            try
            {
                var userAgent = new ProductInfoHeaderValue(productName.Replace(' ', '-'), productVersion);

                return userAgent;
            }
            catch (FormatException ex)
            {
                Debug.WriteLine("ProductInfoHeaderValueFactory.Create({0}, {1}) unable to construct ProductInfoHeaderValue: {2}",
                    productName, productVersion, ex.Message);

                return null;
            }
        }
Beispiel #31
0
        public HttpClientFactory(IHttpClientFactoryParameters parameters, IWebReaderManagerParameters webReaderManagerParameters, IProductInfoHeaderValueFactory userAgentFactory, Func<HttpClientHandler> httpClientHandlerFactory)
        {
            if (null == parameters)
                throw new ArgumentNullException(nameof(parameters));
            if (null == webReaderManagerParameters)
                throw new ArgumentNullException(nameof(webReaderManagerParameters));
            if (null == userAgentFactory)
                throw new ArgumentNullException(nameof(userAgentFactory));
            if (null == httpClientHandlerFactory)
                throw new ArgumentNullException(nameof(httpClientHandlerFactory));

            _referrer = parameters.Referrer;
            _userAgent = userAgentFactory.Create();
            _credentials = parameters.Credentials;
            _cookieContainer = parameters.CookieContainer;

            _webReaderManagerParameters = webReaderManagerParameters;
            _httpClientHandlerFactory = httpClientHandlerFactory;
        }
        public static bool TryParse(string input, out ProductInfoHeaderValue parsedValue)
        {
            parsedValue = null;

            var lexer = new Lexer(input);

            if (!TryParseElement(lexer, out parsedValue) || parsedValue == null)
            {
                return(false);
            }

            if (lexer.Scan() != Token.Type.End)
            {
                parsedValue = null;
                return(false);
            }

            return(true);
        }
        public void ToString_Aggregate_AllSerializedCorrectly()
        {
            HttpRequestMessage request = new HttpRequestMessage();
            string input = string.Empty;

            ProductInfoHeaderValue productInfo = new ProductInfoHeaderValue("product", "1.0");
            Assert.Equal("product/1.0", productInfo.ToString());

            input += productInfo.ToString();
            request.Headers.UserAgent.Add(productInfo);

            productInfo = new ProductInfoHeaderValue("(comment)");
            Assert.Equal("(comment)", productInfo.ToString());

            input += " " + productInfo.ToString(); // Space delineated
            request.Headers.UserAgent.Add(productInfo);

            Assert.Equal(input, request.Headers.UserAgent.ToString());
        }
        public static bool TryParse(string input, out ProductInfoHeaderValue parsedValue)
        {
            int    index = 0;
            object output;

            parsedValue = null;

            if (ProductInfoHeaderParser.SingleValueParser.TryParseValue(input, null, ref index, out output))
            {
                if (index < input.Length)
                {
                    // There is some invalid leftover data. Normaly BaseHeaderParser.TryParseValue would
                    // handle this, but ProductInfoHeaderValue does not derive from BaseHeaderParser.
                    return(false);
                }
                parsedValue = (ProductInfoHeaderValue)output;
                return(true);
            }
            return(false);
        }
 internal static int GetProductInfoLength(string input, int startIndex, out ProductInfoHeaderValue parsedValue)
 {
 }
        internal static int GetProductInfoLength(string input, int startIndex, out ProductInfoHeaderValue parsedValue)
        {
            Contract.Requires(startIndex >= 0);

            parsedValue = null;

            if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
            {
                return 0;
            }

            int current = startIndex;

            // Caller must remove leading whitespaces.
            string comment = null;
            ProductHeaderValue product = null;
            if (input[current] == '(')
            {
                int commentLength = 0;
                if (HttpRuleParser.GetCommentLength(input, current, out commentLength) != HttpParseResult.Parsed)
                {
                    return 0;
                }

                comment = input.Substring(current, commentLength);

                current = current + commentLength;
                current = current + HttpRuleParser.GetWhitespaceLength(input, current);
            }
            else
            {
                // Trailing whitespaces are removed by GetProductLength().
                int productLength = ProductHeaderValue.GetProductLength(input, current, out product);

                if (productLength == 0)
                {
                    return 0;
                }

                current = current + productLength;
            }

            parsedValue = new ProductInfoHeaderValue();
            parsedValue._product = product;
            parsedValue._comment = comment;
            return current - startIndex;
        }
        public static bool TryParse(string input, out ProductInfoHeaderValue parsedValue)
        {
            int index = 0;
            object output;
            parsedValue = null;

            if (ProductInfoHeaderParser.SingleValueParser.TryParseValue(input, null, ref index, out output))
            {
                if (index < input.Length)
                {
                    // There is some invalid leftover data. Normaly BaseHeaderParser.TryParseValue would 
                    // handle this, but ProductInfoHeaderValue does not derive from BaseHeaderParser.
                    return false;
                }
                parsedValue = (ProductInfoHeaderValue)output;
                return true;
            }
            return false;
        }
 internal static void SetProductVersion(string productVersion)
 {
     UserAgentProduct = new ProductInfoHeaderValue(typeof(AdPostingApiMessageHandler).Assembly.GetName().Name, productVersion);
 }
Beispiel #39
0
 public HttpClients(Uri referrer = null, ProductInfoHeaderValue userAgent = null, ICredentials credentials = null, CookieContainer cookieContainer = null);
        public async Task<IList<AutomationAccount>> GetAutomationAccounts()
        {
            if(currSubscription == null)
                throw new Exception(Properties.Resources.SubscriptionNotSet);

            // Get the token for the tenant on this subscription.
            azureARMAuthResult = AuthenticateHelper.RefreshTokenByAuthority(currSubscription.ActiveDirectoryTenantId);
            subscriptionCreds = new TokenCloudCredentials(currSubscription.SubscriptionId, azureARMAuthResult.AccessToken);

            automationManagementClient = new AutomationManagementClient(subscriptionCreds);
            
            // Add user agent string to indicate this is coming from the ISE automation client.
            ProductInfoHeaderValue ISEClientAgent = new ProductInfoHeaderValue(Constants.ISEUserAgent, Constants.ISEVersion);
            automationManagementClient.UserAgent.Add(ISEClientAgent);

            //TODO: does this belong here?
            if (accountResourceGroups == null)
                accountResourceGroups = new Dictionary<AutomationAccount, ResourceGroupExtended>();
            else
                accountResourceGroups.Clear();
            IList<AutomationAccount> result = new List<AutomationAccount>();
            IList<ResourceGroupExtended> resourceGroups = await this.GetResourceGroups();
            foreach (ResourceGroupExtended resourceGroup in resourceGroups)
            {
                AutomationAccountListResponse accountListResponse = await automationManagementClient.AutomationAccounts.ListAsync(resourceGroup.Name);
                foreach (AutomationAccount account in accountListResponse.AutomationAccounts)
                {
                    result.Add(account);
                    accountResourceGroups.Add(account, resourceGroup);
                }
            }
            return result;
        }
        /// <summary>
        /// Refreshes the token used to access azure automation.
        /// This is currently called from a timer that runs on the Constants.tokenRefreshInterval
        /// If it is about to expire (2 minutes from the next refresh, it will renew)
        /// </summary>
        public void RefreshAutomationClientwithNewToken()
        {
            // Get the token for the tenant on this subscription and check if it is about to expire.
            // If it is, refresh it if possible.
            if (currSubscription == null) return;
            if (azureARMAuthResult.ExpiresOn.ToLocalTime() < DateTime.Now.AddMinutes(Constants.tokenRefreshInterval + 2))
            {
                azureARMAuthResult = AuthenticateHelper.RefreshTokenByAuthority(currSubscription.ActiveDirectoryTenantId);
                subscriptionCreds = new TokenCloudCredentials(currSubscription.SubscriptionId, azureARMAuthResult.AccessToken);

                automationManagementClient = new AutomationManagementClient(subscriptionCreds);

                // Add user agent string to indicate this is coming from the ISE automation client.
                ProductInfoHeaderValue ISEClientAgent = new ProductInfoHeaderValue(Constants.ISEUserAgent, Constants.ISEVersion);
                automationManagementClient.UserAgent.Add(ISEClientAgent);
            }
        }
 public static bool TryParse(string input, out ProductInfoHeaderValue parsedValue)
 {
 }