<commit_before>﻿// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Management.Automation;
using System.Net.Http.Headers;
using System.Reflection;
using Microsoft.Azure.Common.Authentication;
using Microsoft.Azure.Common.Authentication.Models;
using Microsoft.WindowsAzure.Commands.Common;
using Newtonsoft.Json;
using System.IO;
using System.Management.Automation.Host;
using System.Text;
using System.Threading;

namespace Microsoft.WindowsAzure.Commands.Utilities.Common
{
    /// <summary>
    /// Represents base class for all Azure cmdlets.
    /// </summary>
    public abstract class AzurePSCmdlet : PSCmdlet, IDisposable
    {
        protected readonly ConcurrentQueue<string> _debugMessages;

        private RecordingTracingInterceptor _httpTracingInterceptor;

        private DebugStreamTraceListener _adalListener;
        protected static AzurePSDataCollectionProfile _dataCollectionProfile = null;
        protected static string _errorRecordFolderPath = null;
        protected const string _fileTimeStampSuffixFormat = "yyyy-MM-dd-THH-mm-ss-fff";

        protected AzurePSQoSEvent QosEvent;

        protected virtual bool IsUsageMetricEnabled {
            get { return false; }
        }

        protected virtual bool IsErrorMetricEnabled
        {
            get { return true; }
        }

        /// <summary>
        /// Gets the PowerShell module name used for user agent header.
        /// By default uses "Azurepowershell"
        /// </summary>
        protected virtual string ModuleName { get { return "AzurePowershell"; } }

        /// <summary>
        /// Gets PowerShell module version used for user agent header.
        /// </summary>
        protected string ModuleVersion { get { return Assembly.GetCallingAssembly().GetName().Version.ToString(); } }

        /// <summary>
        /// Gets the default Azure context.
        /// </summary>
        protected abstract AzureContext DefaultContext { get; }

        /// <summary>
        /// Initializes AzurePSCmdlet properties.
        /// </summary>
        public AzurePSCmdlet()
        {
            _debugMessages = new ConcurrentQueue<string>();
        }

        /// <summary>
        /// Initialize the data collection profile
        /// </summary>
        protected static void InitializeDataCollectionProfile()
        {
            if (_dataCollectionProfile != null && _dataCollectionProfile.EnableAzureDataCollection.HasValue)
            {
                return;
            }

            // Get the value of the environment variable for Azure PS data collection setting.
            string value = Environment.GetEnvironmentVariable(AzurePSDataCollectionProfile.EnvironmentVariableName);
            if (!string.IsNullOrWhiteSpace(value))
            {
                if (string.Equals(value, bool.FalseString, StringComparison.OrdinalIgnoreCase))
                {
                    // Disable data collection only if it is explictly set to 'false'.
                    _dataCollectionProfile = new AzurePSDataCollectionProfile(true);
                }
                else if (string.Equals(value, bool.TrueString, StringComparison.OrdinalIgnoreCase))
                {
                    // Enable data collection only if it is explictly set to 'true'.
                    _dataCollectionProfile = new AzurePSDataCollectionProfile(false);
                }
            }

            // If the environment value is null or empty, or not correctly set, try to read the setting from default file location.
            if (_dataCollectionProfile == null)
            {
                string fileFullPath = Path.Combine(AzureSession.ProfileDirectory, AzurePSDataCollectionProfile.DefaultFileName);
                if (File.Exists(fileFullPath))
                {
                    string contents = File.ReadAllText(fileFullPath);
                    _dataCollectionProfile = JsonConvert.DeserializeObject<AzurePSDataCollectionProfile>(contents);
                }
            }

            // If the environment variable or file content is not set, create a new profile object.
            if (_dataCollectionProfile == null)
            {
                _dataCollectionProfile = new AzurePSDataCollectionProfile();
            }
        }

        /// <summary>
        /// Get the data collection profile
        /// </summary>
        protected static AzurePSDataCollectionProfile GetDataCollectionProfile()
        {
            if (_dataCollectionProfile == null)
            {
                InitializeDataCollectionProfile();
            }

            return _dataCollectionProfile;
        }

        /// <summary>
        /// Check whether the data collection is opted in from user
        /// </summary>
        /// <returns>true if allowed</returns>
        public static bool IsDataCollectionAllowed()
        {
            if (_dataCollectionProfile != null &&
                _dataCollectionProfile.EnableAzureDataCollection.HasValue &&
                _dataCollectionProfile.EnableAzureDataCollection.Value)
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// Save the current data collection profile Json data into the default file path
        /// </summary>
        /// <param name="profile"></param>
        protected abstract void SaveDataCollectionProfile();

        protected bool CheckIfInteractive()
        {
            bool interactive = true;
            if (this.Host == null || this.Host.UI == null || this.Host.UI.RawUI == null)
            {
                interactive = false;
            }
            else
            {
                try
                {
                    var test = this.Host.UI.RawUI.KeyAvailable;
                }
                catch
                {
                    interactive = false;
                }
            }

            if (!interactive && !_dataCollectionProfile.EnableAzureDataCollection.HasValue)
            {
                _dataCollectionProfile.EnableAzureDataCollection = false;
            }
            return interactive;
        }<commit_msg>Disable-azuredatacollection prompts if you want to disable azure data collection in non-interactive session (#103424390)<commit_after>﻿// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Management.Automation;
using System.Net.Http.Headers;
using System.Reflection;
using Microsoft.Azure.Common.Authentication;
using Microsoft.Azure.Common.Authentication.Models;
using Microsoft.WindowsAzure.Commands.Common;
using Newtonsoft.Json;
using System.IO;
using System.Management.Automation.Host;
using System.Text;
using System.Linq;
using System.Threading;

namespace Microsoft.WindowsAzure.Commands.Utilities.Common
{
    /// <summary>
    /// Represents base class for all Azure cmdlets.
    /// </summary>
    public abstract class AzurePSCmdlet : PSCmdlet, IDisposable
    {
        protected readonly ConcurrentQueue<string> _debugMessages;

        private RecordingTracingInterceptor _httpTracingInterceptor;

        private DebugStreamTraceListener _adalListener;
        protected static AzurePSDataCollectionProfile _dataCollectionProfile = null;
        protected static string _errorRecordFolderPath = null;
        protected const string _fileTimeStampSuffixFormat = "yyyy-MM-dd-THH-mm-ss-fff";

        protected AzurePSQoSEvent QosEvent;

        protected virtual bool IsUsageMetricEnabled {
            get { return false; }
        }

        protected virtual bool IsErrorMetricEnabled
        {
            get { return true; }
        }

        /// <summary>
        /// Gets the PowerShell module name used for user agent header.
        /// By default uses "Azurepowershell"
        /// </summary>
        protected virtual string ModuleName { get { return "AzurePowershell"; } }

        /// <summary>
        /// Gets PowerShell module version used for user agent header.
        /// </summary>
        protected string ModuleVersion { get { return Assembly.GetCallingAssembly().GetName().Version.ToString(); } }

        /// <summary>
        /// Gets the default Azure context.
        /// </summary>
        protected abstract AzureContext DefaultContext { get; }

        /// <summary>
        /// Initializes AzurePSCmdlet properties.
        /// </summary>
        public AzurePSCmdlet()
        {
            _debugMessages = new ConcurrentQueue<string>();
        }

        /// <summary>
        /// Initialize the data collection profile
        /// </summary>
        protected static void InitializeDataCollectionProfile()
        {
            if (_dataCollectionProfile != null && _dataCollectionProfile.EnableAzureDataCollection.HasValue)
            {
                return;
            }

            // Get the value of the environment variable for Azure PS data collection setting.
            string value = Environment.GetEnvironmentVariable(AzurePSDataCollectionProfile.EnvironmentVariableName);
            if (!string.IsNullOrWhiteSpace(value))
            {
                if (string.Equals(value, bool.FalseString, StringComparison.OrdinalIgnoreCase))
                {
                    // Disable data collection only if it is explictly set to 'false'.
                    _dataCollectionProfile = new AzurePSDataCollectionProfile(true);
                }
                else if (string.Equals(value, bool.TrueString, StringComparison.OrdinalIgnoreCase))
                {
                    // Enable data collection only if it is explictly set to 'true'.
                    _dataCollectionProfile = new AzurePSDataCollectionProfile(false);
                }
            }

            // If the environment value is null or empty, or not correctly set, try to read the setting from default file location.
            if (_dataCollectionProfile == null)
            {
                string fileFullPath = Path.Combine(AzureSession.ProfileDirectory, AzurePSDataCollectionProfile.DefaultFileName);
                if (File.Exists(fileFullPath))
                {
                    string contents = File.ReadAllText(fileFullPath);
                    _dataCollectionProfile = JsonConvert.DeserializeObject<AzurePSDataCollectionProfile>(contents);
                }
            }

            // If the environment variable or file content is not set, create a new profile object.
            if (_dataCollectionProfile == null)
            {
                _dataCollectionProfile = new AzurePSDataCollectionProfile();
            }
        }

        /// <summary>
        /// Get the data collection profile
        /// </summary>
        protected static AzurePSDataCollectionProfile GetDataCollectionProfile()
        {
            if (_dataCollectionProfile == null)
            {
                InitializeDataCollectionProfile();
            }

            return _dataCollectionProfile;
        }

        /// <summary>
        /// Check whether the data collection is opted in from user
        /// </summary>
        /// <returns>true if allowed</returns>
        public static bool IsDataCollectionAllowed()
        {
            if (_dataCollectionProfile != null &&
                _dataCollectionProfile.EnableAzureDataCollection.HasValue &&
                _dataCollectionProfile.EnableAzureDataCollection.Value)
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// Save the current data collection profile Json data into the default file path
        /// </summary>
        /// <param name="profile"></param>
        protected abstract void SaveDataCollectionProfile();

        protected bool CheckIfInteractive()
        {
            bool interactive = true;
            if (this.Host == null || 
                this.Host.UI == null || 
                this.Host.UI.RawUI == null ||
                Environment.GetCommandLineArgs().Any(s => s.Equals("-NonInteractive", StringComparison.OrdinalIgnoreCase)))
            {
                interactive = false;
            }
            else
            {
                try
                {
                    var test = this.Host.UI.RawUI.KeyAvailable;
                }
                catch
                {
                    interactive = false;
                }
            }

            if (!interactive && !_dataCollectionProfile.EnableAzureDataCollection.HasValue)
            {
                _dataCollectionProfile.EnableAzureDataCollection = false;
            }
            return interactive;
        }
{'fraction_non_alphanumeric': 0.10108787793161911, 'fraction_numerical': 0.0012009042102288782, 'mean_word_length': 1.7939609236234457, 'pattern_counts': {'":': 0, '<': 53, '<?xml version=': 0, '>': 54, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6949919', 'n_tokens_mistral': 3175, 'n_tokens_neox': 3058, 'n_words': 926}