Wrapper over the settings files created by the Google Cloud SDK. No data is cached, so it is possible to have race conditions between gcloud and PowerShell. This is by design. gcloud is the source of truth for data.
        /// <summary>
        /// Given a settingName (e.g. Project) and a settingValue (e.g. "gcloud-testing" or $project),
        /// this function will try to first resolve the settingValue to a string. If it fails to do so,
        /// then the function will look into the Cloud SDK Settings to get the default value.
        /// </summary>
        protected string GetCloudSdkSettingValue(string settingName, string settingValue)
        {
            if (settingValue != null)
            {
                // If the cmdlet is not executing and the user is only using tab completion, the string parameterValue
                // will have double quotes at the start and end so we have to trim that.
                settingValue = settingValue.Trim('"');

                // If the parameterValue is a variable, then we have to extract out the variable name.
                if (settingValue.StartsWith("$"))
                {
                    // Try to resolve the variable parameterValue, if unsuccessful, set it to an empty string.
                    settingValue = ResolveVariable(settingValue, string.Empty).ToString();
                }
            }

            // If we cannot resolve the variable or the user has not entered parameter yet, parameterValue is null here.
            // So we will get the value from Cloud SDK Settings.
            if (string.IsNullOrWhiteSpace(settingValue))
            {
                settingValue = CloudSdkSettings.GetSettingsValue(settingName);
            }

            return(settingValue);
        }
예제 #2
0
        /// <summary>
        /// Gives the property a default value from the gcould config. This sets the property regardless of its
        /// current value.
        /// </summary>
        /// <param name="property">The property to set.</param>
        /// <param name="instance">The instance that contains the property to set.</param>
        public void SetObjectConfigDefault(PropertyInfo property, object instance)
        {
            string settingsValue = CloudSdkSettings.GetSettingsValue(Property);

            if (string.IsNullOrEmpty(settingsValue))
            {
                throw new PSInvalidOperationException(
                          $"Parameter {property.Name} was not set and does not have a default value.");
            }

            property.SetValue(instance, settingsValue);
        }
예제 #3
0
        /// <summary>
        /// Returns the access token of the current active config.
        /// </summary>
        public static async Task <ActiveUserToken> GetAccessToken(CancellationToken cancellationToken)
        {
            // We get the issued time before the command so we won't be too late
            // when it comes to token expiry.
            DateTime issuedTime = DateTime.Now;

            string userCredentialJson = await GetGCloudCommandOutput("auth print-access-token");

            cancellationToken.ThrowIfCancellationRequested();
            string currentUser = CloudSdkSettings.GetSettingsValue("account");

            return(new ActiveUserToken(userCredentialJson, currentUser));
        }
예제 #4
0
        /// <summary>
        /// Gives the field a default value from the gcould config.
        /// </summary>
        /// <param name="field">
        /// The field info.
        /// </param>
        /// <param name="instance">
        /// The instance the field is a member of.
        /// </param>
        public void SetConfigDefault(FieldInfo field, object instance)
        {
            if (field.GetValue(instance) == null)
            {
                string settingsValue = CloudSdkSettings.GetSettingsValue(Property);
                if (string.IsNullOrEmpty(settingsValue))
                {
                    throw new PSInvalidOperationException(
                              $"Parameter {field.Name} was not set and does not have a default value.");
                }

                field.SetValue(instance, settingsValue);
            }
        }
        public GCloudCmdlet()
        {
            if (CloudSdkSettings.GetOptIntoUsageReporting())
            {
                string clientID = CloudSdkSettings.GetAnoymousClientID();
                _telemetryReporter = new GoogleAnalyticsCmdletReporter(clientID, AnalyticsEventCategory.CmdletInvocation);
            }
            else
            {
                _telemetryReporter = new InMemoryCmdletResultReporter();
            }

            // Only set upon successful completion of EndProcessing.
            _cmdletInvocationSuccessful = false;
        }
예제 #6
0
        /// <summary>
        /// Gives the field a default value from the gcould config.
        /// </summary>
        /// <param name="field">
        /// The field info.
        /// </param>
        /// <param name="instance">
        /// The instance the field is a member of.
        /// </param>
        public void SetConfigDefault(FieldInfo field, GCloudCmdlet instance)
        {
            bool isBoundParameter = instance.MyInvocation.BoundParameters.ContainsKey(field.Name);

            if (!isBoundParameter)
            {
                string settingsValue = CloudSdkSettings.GetSettingsValue(Property);
                if (string.IsNullOrEmpty(settingsValue))
                {
                    throw new PSInvalidOperationException(
                              $"Parameter {field.Name} was not set and does not have a default value.");
                }

                field.SetValue(instance, settingsValue);
            }
        }
        public void Dispose()
        {
            string cmdletName   = GetCmdletName();
            string parameterSet = ParameterSetName;

            // "__AllParameterSets" isn't super-useful in reports.
            if (String.IsNullOrWhiteSpace(parameterSet) ||
                ParameterSetName == ParameterAttribute.AllParameterSets)
            {
                parameterSet = "Default";
            }

            string projectNumber = null;

            // Try to convert the project ID into project number.
            // Swallow the error if we fail to do so and proceed to reporting.
            try
            {
                if (string.IsNullOrWhiteSpace(Project))
                {
                    Project = CloudSdkSettings.GetDefaultProject();
                }

                projectNumber = GetProjectNumber(Project);
            }
            catch { }

            if (_cmdletInvocationSuccessful)
            {
                _telemetryReporter.ReportSuccess(cmdletName, parameterSet, projectNumber);
            }
            else
            {
                // TODO(chrsmith): Is it possible to get ahold of any exceptions the
                // cmdlet threw? If so, use that to determine a more appropriate error code.
                // We report 1 instead of 0 so that the data can be see in Google Analytics.
                // (null vs. 0 is ambiguous in the UI.)
                _telemetryReporter.ReportFailure(cmdletName, parameterSet, Project, 1);
            }
        }
        public virtual async Task <string> GetAccessTokenForRequestAsync(string authUri = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (s_token == null)
            {
                await RefreshTokenAsync(cancellationToken).ConfigureAwait(false);

                return(s_token.AccessToken);
            }

            string currentCloudSdkUser = CloudSdkSettings.GetSettingsValue("account");

            if (s_token.IsExpired || s_token.User != currentCloudSdkUser)
            {
                if (!await RefreshTokenAsync(cancellationToken).ConfigureAwait(false))
                {
                    throw new InvalidOperationException(
                              "The access token has expired or the user has changed, but we can't refresh it.");
                }
            }

            return(s_token.AccessToken);
        }