Ejemplo n.º 1
0
        private PnPConnection(ClientContext context,
                              ConnectionType connectionType,
                              PSCredential credential,
                              string url,
                              string tenantAdminUrl,
                              string pnpVersionTag,
                              InitializationType initializationType)
        {
            InitializeTelemetry(context, initializationType);
            var coreAssembly = Assembly.GetExecutingAssembly();

            UserAgent = $"NONISV|SharePointPnP|PnPPS/{((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version}";
            //if (context == null)
            //    throw new ArgumentNullException(nameof(context));
            if (context != null)
            {
                Context = context;
                Context.ExecutingWebRequest += Context_ExecutingWebRequest;
            }
            ConnectionType = connectionType;
            TenantAdminUrl = tenantAdminUrl;

            PSCredential  = credential;
            PnPVersionTag = pnpVersionTag;
            ContextCache  = new List <ClientContext> {
                context
            };
            if (!string.IsNullOrEmpty(url))
            {
                Url = (new Uri(url)).AbsoluteUri;
            }
            ConnectionMethod = ConnectionMethod.Credentials;
            ClientId         = PnPManagementShellClientId;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Returns a PnPConnection based on connecting using an existing token
        /// </summary>
        /// <param name="token">Token to connect with</param>
        /// <param name="tokenAudience">Indicator of <see cref="TokenAudience"/> indicating for which API this token is meant to be used</param>
        /// <param name="host">PowerShell Host environment in which the commands are being run</param>
        /// <param name="initializationType">Indicator of type <see cref="InitializationType"/> which indicates the method used to set up the connection. Used for gathering usage analytics.</param>
        /// <param name="url">Url of the SharePoint environment to connect to, if applicable. Leave NULL not to connect to a SharePoint environment.</param>
        /// <param name="clientContext">A SharePoint ClientContext to make available within this connection. Leave NULL to not connect to a SharePoint environment.</param>
        /// <param name="minimalHealthScore">Minimum health score that the SharePoint server should report before allowing requests to be executed on it. Scale of 0 to 10 where 0 is healthiest and 10 is least healthy. Leave NULL not to perform health checks on SharePoint.</param>
        /// <param name="pnpVersionTag">Identifier set on the SharePoint ClientContext as the ClientTag to identify the source of the requests to SharePoint. Leave NULL not to set it.</param>
        /// <param name="disableTelemetry">Boolean indicating if telemetry on the commands being executed should be disabled. Telemetry is enabled by default.</param>
        /// <returns><see cref="PnPConnection"/ instance which can be used to communicate with one of the supported APIs</returns>
        public static PnPConnection GetConnectionWithToken(GenericToken token,
                                                           TokenAudience tokenAudience,
                                                           PSHost host,
                                                           InitializationType initializationType,
                                                           PSCredential credentials,
                                                           string url = null,
                                                           ClientContext clientContext       = null,
                                                           int?minimalHealthScore            = null,
                                                           string pnpVersionTag              = null,
                                                           bool disableTelemetry             = false,
                                                           AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            var connection = new PnPConnection(host, initializationType, url, clientContext, new Dictionary <TokenAudience, GenericToken>(1)
            {
                { tokenAudience, token }
            }, minimalHealthScore, pnpVersionTag, disableTelemetry)
            {
                ConnectionMethod = ConnectionMethod.AccessToken,
                Tenant           = token.ParsedToken.Claims.FirstOrDefault(c => c.Type.Equals("tid", StringComparison.InvariantCultureIgnoreCase))?.Value,
                ClientId         = token.ParsedToken.Claims.FirstOrDefault(c => c.Type.Equals("appid", StringComparison.InvariantCultureIgnoreCase))?.Value,
                AzureEnvironment = azureEnvironment
            };

            connection.PSCredential = credentials;
            return(connection);
        }
Ejemplo n.º 3
0
        private PnPConnection(ClientContext context,
                              ConnectionType connectionType,
                              PSCredential credential,
                              string url,
                              string tenantAdminUrl,
                              string pnpVersionTag,
                              InitializationType initializationType)
        {
            InitializeTelemetry(context, initializationType);
            var coreAssembly = Assembly.GetExecutingAssembly();

            if (context != null)
            {
                Context = context;
            }
            ConnectionType = connectionType;
            TenantAdminUrl = tenantAdminUrl;

            PSCredential  = credential;
            PnPVersionTag = pnpVersionTag;
            ContextCache  = new List <ClientContext> {
                context
            };
            if (!string.IsNullOrEmpty(url))
            {
                Url = (new Uri(url)).AbsoluteUri;
            }
            ConnectionMethod = ConnectionMethod.Credentials;
            ClientId         = PnPManagementShellClientId;
        }
Ejemplo n.º 4
0
        public static TBuilder Initialize <TBuilder>(this TBuilder systemBuilder, InitializationType initializationType)
            where TBuilder : SystemBuilder
        {
            systemBuilder.OnBuild(context =>
            {
                var mediator = context.Resolve <IMediator>();
                return(mediator.Publish(new InitializeNotification(initializationType)));
            });

            return(systemBuilder);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Instantiates a basic new PnP Connection. Use one of the static methods to retrieve a PnPConnection for a specific purpose.
        /// </summary>
        /// <param name="host">PowerShell Host environment in which the commands are being run</param>
        /// <param name="initializationType">Indicator of type <see cref="InitializationType"/> which indicates the method used to set up the connection. Used for gathering usage analytics.</param>
        /// <param name="url">Url of the SharePoint environment to connect to, if applicable. Leave NULL not to connect to a SharePoint environment.</param>
        /// <param name="clientContext">A SharePoint ClientContext to make available within this connection. Leave NULL to not connect to a SharePoint environment.</param>
        /// <param name="minimalHealthScore">Minimum health score that the SharePoint server should report before allowing requests to be executed on it. Scale of 0 to 10 where 0 is healthiest and 10 is least healthy. Leave NULL not to perform health checks on SharePoint.</param>
        /// <param name="pnpVersionTag">Identifier set on the SharePoint ClientContext as the ClientTag to identify the source of the requests to SharePoint. Leave NULL not to set it.</param>
        /// <param name="disableTelemetry">Boolean indicating if telemetry on the commands being executed should be disabled. Telemetry is enabled by default.</param>
        private PnPConnection(PSHost host,
                              InitializationType initializationType,
                              string url = null,
                              ClientContext clientContext = null,
                              Dictionary <TokenAudience, GenericToken> tokens = null,
                              int?minimalHealthScore = null,
                              string pnpVersionTag   = null,
                              bool disableTelemetry  = false)
        {
            if (!disableTelemetry)
            {
                InitializeTelemetry(clientContext, host, initializationType);
            }

            UserAgent = $"NONISV|SharePointPnP|PnPPS/{((AssemblyFileVersionAttribute)Assembly.GetExecutingAssembly().GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version}";
            Context   = clientContext;

            // Enrich the AccessTokens collection with the token(s) passed in
            if (tokens != null)
            {
                AccessTokens.AddRange(tokens);
            }

            // Validate if we have a SharePoint Context
            if (Context != null)
            {
                // We have a SharePoint Context, configure the context
                ContextCache = new List <ClientContext> {
                    Context
                };

#if !ONPREMISES
                // If we have a SharePoint or a Graph Access Token, use it for the SharePoint connection
                var accessToken = AccessTokens.ContainsKey(TokenAudience.SharePointOnline) ? TryGetAccessToken(TokenAudience.SharePointOnline) : TryGetAccessToken(TokenAudience.MicrosoftGraph);
                if (accessToken != null)
                {
                    Context.ExecutingWebRequest += (sender, args) =>
                    {
                        args.WebRequestExecutor.WebRequest.UserAgent            = UserAgent;
                        args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken;
                    };
                }
#endif
            }
            else
            {
                // We do not have a SharePoint Context
                ContextCache = null;
            }

            PnPVersionTag      = pnpVersionTag;
            MinimalHealthScore = minimalHealthScore;
            Url = url;
        }
Ejemplo n.º 6
0
        private PnPConnection(string pnpVersionTag, InitializationType initializationType, string tenantAdminUrl)
        {
            InitializeTelemetry(null, initializationType);
            var coreAssembly = Assembly.GetExecutingAssembly();

            ConnectionType   = ConnectionType.O365;
            PnPVersionTag    = pnpVersionTag;
            TenantAdminUrl   = tenantAdminUrl;
            ConnectionMethod = ConnectionMethod.ManagedIdentity;
            ManagedIdentity  = true;
        }
        public SafeUnmanagedMemoryHandle(int numberOfBytes, InitializationType initializationType = InitializationType.ZeroOutMemory)
            : base(true)
        {
            SetHandle(Marshal.AllocHGlobal(numberOfBytes));

            if (initializationType == InitializationType.ZeroOutMemory)
            {
                unsafe
                {
                    UnsafeUtils.ClearMemory((byte *)handle, numberOfBytes);
                }
            }
        }
Ejemplo n.º 8
0
        internal void InitializeTelemetry(ClientContext context, InitializationType initializationType)
        {
            var enableTelemetry = false;
            var userProfile     = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            var telemetryFile   = System.IO.Path.Combine(userProfile, ".pnppowershelltelemetry");

            if (Environment.GetEnvironmentVariable("PNPPOWERSHELL_DISABLETELEMETRY") != null)
            {
                enableTelemetry = Environment.GetEnvironmentVariable("PNPPOWERSHELL_DISABLETELEMETRY").ToLower().Equals("false");
            }

            if (!System.IO.File.Exists(telemetryFile))
            {
                enableTelemetry = true;
            }
            else
            {
                if (System.IO.File.ReadAllText(telemetryFile).ToLower() == "allow")
                {
                    enableTelemetry = true;
                }
            }

            if (enableTelemetry)
            {
                var serverLibraryVersion = "";
                var serverVersion        = "";
                if (context != null)
                {
                    try
                    {
                        if (context.ServerLibraryVersion != null)
                        {
                            serverLibraryVersion = context.ServerLibraryVersion.ToString();
                        }
                        if (context.ServerVersion != null)
                        {
                            serverVersion = context.ServerVersion.ToString();
                        }
                    }
                    catch { }
                }

                ApplicationInsights = new ApplicationInsights();
                var coreAssembly    = Assembly.GetExecutingAssembly();
                var operatingSystem = Utilities.OperatingSystem.GetOSString();

                ApplicationInsights.Initialize(serverLibraryVersion, serverVersion, initializationType.ToString(), ((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version.ToString(), operatingSystem);
                ApplicationInsights.TrackEvent("Connect-PnPOnline");
            }
        }
Ejemplo n.º 9
0
        private PnPConnection(string pnpVersionTag, InitializationType initializationType, string tenantAdminUrl)
        {
            InitializeTelemetry(null, initializationType);
            var coreAssembly = Assembly.GetExecutingAssembly();

            UserAgent = $"NONISV|SharePointPnP|PnPPS/{((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version}";
            //if (context == null)
            //    throw new ArgumentNullException(nameof(context));
            ConnectionType   = ConnectionType.O365;
            PnPVersionTag    = pnpVersionTag;
            TenantAdminUrl   = tenantAdminUrl;
            ConnectionMethod = ConnectionMethod.ManagedIdentity;
            ManagedIdentity  = true;
        }
Ejemplo n.º 10
0
    public NeuralNetwork(
        int[] layerLengths,
        float learnRate,
        int batchSize,
        float dropoutKeepRate,
        float weightDecayRate,
        ActivisionFunctionType activisionType,
        ActivisionFunctionType activisionTypeOutput,
        CostFunctionType costType,
        InitializationType initializationType,
        int initializationSeed,
        float activisionCoeffitient,
        int dropoutSeed
        )
    {
        m_layerLengths          = layerLengths;
        m_layerCount            = m_layerLengths.Length;
        m_learnRate             = learnRate;
        m_activisionCoeffitient = activisionCoeffitient;
        m_dropoutKeepRate       = dropoutKeepRate;
        m_weightDecayRate       = weightDecayRate;
        m_initDropoutSeed       = dropoutSeed;
        m_currentDropoutSeed    = dropoutSeed;

        if (batchSize <= 0)
        {
            Debug.Log("Info: batch size was <= 0 (" + batchSize + "). It was set to a default value of 1!");
            m_batchSize = 1;
        }
        m_batchSize = batchSize;

        m_activisionFunctionType       = activisionType;
        m_activisionFunctionTypeOutput = activisionTypeOutput;
        m_costFunctionType             = costType;
        m_initializationType           = initializationType;

        SetActivisionFunction(activisionType);

        InitializeBiases(null, initializationSeed);
        for (int i = 1; i < m_layerCount; i++)
        {
            initializationSeed += m_layerLengths[i];
        }
        InitializeWeights(null, initializationSeed);
        InitializeBatch();

        InitializeBackPropagation();

        //m_activisionFunctionType = ActivisionFunctionType.Sigmoid;
    }
Ejemplo n.º 11
0
 /// <summary>
 /// Returns a PnPConnection based on connecting using an username and password
 /// </summary>
 /// <param name="credential">Credential set to connect with</param>
 /// <param name="host">PowerShell Host environment in which the commands are being run</param>
 /// <param name="initializationType">Indicator of type <see cref="InitializationType"/> which indicates the method used to set up the connection. Used for gathering usage analytics.</param>
 /// <param name="url">Url of the SharePoint environment to connect to, if applicable. Leave NULL not to connect to a SharePoint environment.</param>
 /// <param name="clientContext">A SharePoint ClientContext to make available within this connection. Leave NULL to not connect to a SharePoint environment.</param>
 /// <param name="minimalHealthScore">Minimum health score that the SharePoint server should report before allowing requests to be executed on it. Scale of 0 to 10 where 0 is healthiest and 10 is least healthy. Leave NULL not to perform health checks on SharePoint.</param>
 /// <param name="pnpVersionTag">Identifier set on the SharePoint ClientContext as the ClientTag to identify the source of the requests to SharePoint. Leave NULL not to set it.</param>
 /// <param name="disableTelemetry">Boolean indicating if telemetry on the commands being executed should be disabled. Telemetry is enabled by default.</param>
 /// <returns><see cref="PnPConnection"/ instance which can be used to communicate with one of the supported APIs</returns>
 public static PnPConnection GetConnectionWithPsCredential(PSCredential credential,
                                                           PSHost host,
                                                           InitializationType initializationType,
                                                           string url = null,
                                                           ClientContext clientContext = null,
                                                           int?minimalHealthScore      = null,
                                                           string pnpVersionTag        = null,
                                                           bool disableTelemetry       = false)
 {
     return(new PnPConnection(host, initializationType, url, clientContext, null, minimalHealthScore, pnpVersionTag, disableTelemetry)
     {
         PSCredential = credential,
         ConnectionMethod = ConnectionMethod.Credentials
     });
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Returns a PnPConnection based on connecting using a ClientId and Certificate
 /// </summary>
 /// <param name="clientId">ClientId to connect with</param>
 /// <param name="certificate">Certificate to connect with</param>
 /// <param name="aadDomain">The Azure Active Directory tenant name (i.e. contoso.onmicrosoft.com) or the tenant identifier to which to connect</param>
 /// <param name="host">PowerShell Host environment in which the commands are being run</param>
 /// <param name="initializationType">Indicator of type <see cref="InitializationType"/> which indicates the method used to set up the connection. Used for gathering usage analytics.</param>
 /// <param name="url">Url of the SharePoint environment to connect to, if applicable. Leave NULL not to connect to a SharePoint environment.</param>
 /// <param name="clientContext">A SharePoint ClientContext to make available within this connection. Leave NULL to not connect to a SharePoint environment.</param>
 /// <param name="pnpVersionTag">Identifier set on the SharePoint ClientContext as the ClientTag to identify the source of the requests to SharePoint. Leave NULL not to set it.</param>
 /// <param name="disableTelemetry">Boolean indicating if telemetry on the commands being executed should be disabled. Telemetry is enabled by default.</param>
 /// <returns><see cref="PnPConnection"/ instance which can be used to communicate with one of the supported APIs</returns>
 public static PnPConnection GetConnectionWithClientIdAndCertificate(string clientId,
                                                                     X509Certificate2 certificate,
                                                                     InitializationType initializationType,
                                                                     string url                  = null,
                                                                     string aadDomain            = null,
                                                                     ClientContext clientContext = null,
                                                                     string pnpVersionTag        = null,
                                                                     bool disableTelemetry       = false)
 {
     return(new PnPConnection(initializationType, url, clientContext, null, pnpVersionTag, disableTelemetry)
     {
         ClientId = clientId,
         Certificate = certificate,
         ConnectionMethod = ConnectionMethod.AzureADAppOnly,
         Tenant = aadDomain
     });
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Returns a PnPConnection based on connecting using a ClientId and ClientSecret
 /// </summary>
 /// <param name="clientId">ClientId to connect with</param>
 /// <param name="clientSecret">ClientSecret to connect with</param>
 /// <param name="aadDomain">The Azure Active Directory tenant name (i.e. contoso.onmicrosoft.com) or the tenant identifier to which to connect</param>
 /// <param name="host">PowerShell Host environment in which the commands are being run</param>
 /// <param name="initializationType">Indicator of type <see cref="InitializationType"/> which indicates the method used to set up the connection. Used for gathering usage analytics.</param>
 /// <param name="url">Url of the SharePoint environment to connect to, if applicable. Leave NULL not to connect to a SharePoint environment.</param>
 /// <param name="clientContext">A SharePoint ClientContext to make available within this connection. Leave NULL to not connect to a SharePoint environment.</param>
 /// <param name="minimalHealthScore">Minimum health score that the SharePoint server should report before allowing requests to be executed on it. Scale of 0 to 10 where 0 is healthiest and 10 is least healthy. Leave NULL not to perform health checks on SharePoint.</param>
 /// <param name="pnpVersionTag">Identifier set on the SharePoint ClientContext as the ClientTag to identify the source of the requests to SharePoint. Leave NULL not to set it.</param>
 /// <param name="disableTelemetry">Boolean indicating if telemetry on the commands being executed should be disabled. Telemetry is enabled by default.</param>
 /// <returns><see cref="PnPConnection"/ instance which can be used to communicate with one of the supported APIs</returns>
 public static PnPConnection GetConnectionWithClientIdAndClientSecret(string clientId,
                                                                      string clientSecret,
                                                                      PSHost host,
                                                                      InitializationType initializationType,
                                                                      string url                  = null,
                                                                      string aadDomain            = null,
                                                                      ClientContext clientContext = null,
                                                                      int?minimalHealthScore      = null,
                                                                      string pnpVersionTag        = null,
                                                                      bool disableTelemetry       = false)
 {
     return(new PnPConnection(host, initializationType, url, clientContext, null, minimalHealthScore, pnpVersionTag, disableTelemetry)
     {
         ClientId = clientId,
         ClientSecret = clientSecret,
         ConnectionMethod = ConnectionMethod.AzureADAppOnly,
         Tenant = aadDomain
     });
 }
Ejemplo n.º 14
0
        internal PnPConnection(ClientContext context,
                               ConnectionType connectionType,
                               int minimalHealthScore,
                               int retryCount,
                               int retryWait,
                               PSCredential credential,
                               string url,
                               string tenantAdminUrl,
                               string pnpVersionTag,
                               PSHost host,
                               bool disableTelemetry,
                               InitializationType initializationType)
        {
            if (!disableTelemetry)
            {
                InitializeTelemetry(context, host, initializationType);
            }
            var coreAssembly = Assembly.GetExecutingAssembly();

            UserAgent = $"NONISV|SharePointPnP|PnPPS/{((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version}";
            //if (context == null)
            //    throw new ArgumentNullException(nameof(context));
            Context = context;
            Context.ExecutingWebRequest += Context_ExecutingWebRequest;

            ConnectionType     = connectionType;
            MinimalHealthScore = minimalHealthScore;
            RetryCount         = retryCount;
            RetryWait          = retryWait;
            TenantAdminUrl     = tenantAdminUrl;

            PSCredential  = credential;
            PnPVersionTag = pnpVersionTag;
            ContextCache  = new List <ClientContext> {
                context
            };
            Url = (new Uri(url)).AbsoluteUri;
            ConnectionMethod = ConnectionMethod.Credentials;
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Connect using provided credentials or the current credentials
        /// </summary>
        /// <returns>PnPConnection based on credentials authentication</returns>
        private PnPConnection ConnectCredentials(PSCredential credentials, InitializationType initializationType = InitializationType.Credentials)
        {
            if (!CurrentCredentials && credentials == null)
            {
                credentials = GetCredentials();
                if (credentials == null)
                {
                    credentials = Host.UI.PromptForCredential(Resources.EnterYourCredentials, "", "", "");

                    // Ensure credentials have been entered
                    if (credentials == null)
                    {
                        // No credentials have been provided
                        return(null);
                    }
                }
            }
            if (ClientId == null)
            {
                ClientId = PnPConnection.PnPManagementShellClientId;
            }

            if (PnPConnection.Current?.ClientId == ClientId)
            {
                if (credentials != null && PnPConnection.Current?.PSCredential?.UserName == credentials.UserName &&
                    PnPConnection.Current?.PSCredential.GetNetworkCredential().Password == credentials.GetNetworkCredential().Password)
                {
                    ReuseAuthenticationManager();
                }
            }

            return(PnPConnection.CreateWithCredentials(this, new Uri(Url),
                                                       credentials,
                                                       CurrentCredentials,
                                                       TenantAdminUrl,
                                                       AzureEnvironment,
                                                       ClientId,
                                                       RedirectUri, TransformationOnPrem, initializationType));
        }
Ejemplo n.º 16
0
 internal PnPConnection(ClientContext context, ConnectionType connectionType, int minimalHealthScore, int retryCount, int retryWait, PSCredential credential, string clientId, string clientSecret, string url, string tenantAdminUrl, string pnpVersionTag, PSHost host, bool disableTelemetry, InitializationType initializationType)
     : this(context, connectionType, minimalHealthScore, retryCount, retryWait, credential, url, tenantAdminUrl, pnpVersionTag, host, disableTelemetry, initializationType)
 {
     ClientId     = clientId;
     ClientSecret = clientSecret;
 }
Ejemplo n.º 17
0
 internal PnPConnection(ClientContext context, ConnectionType connectionType, PSCredential credential, string clientId, string clientSecret, string url, string tenantAdminUrl, string pnpVersionTag, bool disableTelemetry, InitializationType initializationType)
     : this(context, connectionType, credential, url, tenantAdminUrl, pnpVersionTag, disableTelemetry, initializationType)
 {
     ClientId     = clientId;
     ClientSecret = clientSecret;
 }
Ejemplo n.º 18
0
 internal SPOnlineConnection(ClientContext context, ConnectionType connectionType, int minimalHealthScore, int retryCount, int retryWait, PSCredential credential, string clientId, string clientSecret, string url, string tenantAdminUrl, string pnpVersionTag, System.Management.Automation.Host.PSHost host, bool disableTelemetry, InitializationType initializationType)
     : this(context, connectionType, minimalHealthScore, retryCount, retryWait, credential, url, tenantAdminUrl, pnpVersionTag, host, disableTelemetry, initializationType)
 {
     this.ClientId     = clientId;
     this.ClientSecret = clientSecret;
 }
Ejemplo n.º 19
0
        internal void InitializeTelemetry(ClientContext context, PSHost host, InitializationType initializationType)
        {
            var enableTelemetry = false;
            var userProfile     = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            var telemetryFile   = System.IO.Path.Combine(userProfile, ".pnppowershelltelemetry");

            if (!System.IO.File.Exists(telemetryFile))
            {
#if ONPREMISES
                if (Environment.UserInteractive && Environment.GetCommandLineArgs().FirstOrDefault(a => a.ToLower().StartsWith("-noni")) == null)
                {
                    var choices = new System.Collections.ObjectModel.Collection <ChoiceDescription>();
                    choices.Add(new ChoiceDescription("&Allow", "You will allow us to transmit anonymous data"));
                    choices.Add(new ChoiceDescription("&Do not allow", "You do not allow us to transmit anonymous data"));
                    if (host.UI.PromptForChoice("PnP PowerShell Telemetry", $"Please allow us to transmit anonymous metrics in order to make PnP PowerShell even better.{Environment.NewLine}We transmit the version of PnP PowerShell you are using, the version of SharePoint you are connecting to and which cmdlet you are executing. We do not transmit tenant/server URLs nor parameter values and content.{Environment.NewLine}{Environment.NewLine}Your decision will be recorded in a file a called .pnppowershelltelemetry which will be located in your profile folder ({userProfile}).{Environment.NewLine}{Environment.NewLine}You can choose to disable and/or enable telemetry at a later stage by using Enable-PnPPowerShellTelemetry or Disable-PnPPowerShellTelemetry. Get-PnPPowerShellTelemetryEnabled will provide you with your current setting.", choices, 0) == 0)
                    {
                        enableTelemetry = true;
                        System.IO.File.WriteAllText(telemetryFile, "allow");
                    }
                    else
                    {
                        System.IO.File.WriteAllText(telemetryFile, "disallow");
                    }
                }
#else
                enableTelemetry = true;
#endif
            }
            else
            {
                if (System.IO.File.ReadAllText(telemetryFile).ToLower() == "allow")
                {
                    enableTelemetry = true;
                }
            }
            if (enableTelemetry)
            {
                var serverLibraryVersion = "";
                var serverVersion        = "";
                if (context != null)
                {
                    try
                    {
                        if (context.ServerLibraryVersion != null)
                        {
                            serverLibraryVersion = context.ServerLibraryVersion.ToString();
                        }
                        if (context.ServerVersion != null)
                        {
                            serverVersion = context.ServerVersion.ToString();
                        }
                    }
                    catch { }
                }
                TelemetryClient = new TelemetryClient();
                TelemetryClient.InstrumentationKey             = "a301024a-9e21-4273-aca5-18d0ef5d80fb";
                TelemetryClient.Context.Session.Id             = Guid.NewGuid().ToString();
                TelemetryClient.Context.Cloud.RoleInstance     = "PnPPowerShell";
                TelemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
#if !PNPPSCORE
                TelemetryClient.Context.GlobalProperties.Add("ServerLibraryVersion", serverLibraryVersion);
                TelemetryClient.Context.GlobalProperties.Add("ServerVersion", serverVersion);
                TelemetryClient.Context.GlobalProperties.Add("ConnectionMethod", initializationType.ToString());
#else
                TelemetryClient.Context.Properties.Add("ServerLibraryVersion", serverLibraryVersion);
                TelemetryClient.Context.Properties.Add("ServerVersion", serverVersion);
                TelemetryClient.Context.Properties.Add("ConnectionMethod", initializationType.ToString());
#endif
                var coreAssembly = Assembly.GetExecutingAssembly();
#if !PNPPSCORE
                TelemetryClient.Context.GlobalProperties.Add("Version", ((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version.ToString());
#else
                TelemetryClient.Context.Properties.Add("Version", ((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version.ToString());
#endif

#if SP2013
                TelemetryClient.Context.GlobalProperties.Add("Platform", "SP2013");
#elif SP2016
                TelemetryClient.Context.GlobalProperties.Add("Platform", "SP2016");
#elif SP2019
                TelemetryClient.Context.GlobalProperties.Add("Platform", "SP2019");
#else
#if !PNPPSCORE
                TelemetryClient.Context.GlobalProperties.Add("Platform", "SPO");
#else
                TelemetryClient.Context.Properties.Add("Platform", "SPO");
#endif
#endif
                TelemetryClient.TrackEvent("Connect-PnPOnline");
            }
        }
Ejemplo n.º 20
0
        internal PnPConnection(GenericToken tokenResult, ConnectionMethod connectionMethod, ConnectionType connectionType, string pnpVersionTag, bool disableTelemetry, InitializationType initializationType)
        {
            if (!disableTelemetry)
            {
                InitializeTelemetry(null, initializationType);
            }
            var coreAssembly = Assembly.GetExecutingAssembly();

            UserAgent        = $"NONISV|SharePointPnP|PnPPS/{((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version}";
            ConnectionType   = connectionType;
            PnPVersionTag    = pnpVersionTag;
            ConnectionMethod = connectionMethod;
        }
Ejemplo n.º 21
0
 public InitializerAttribute(InitializationType type) : this(type, DEFAULT_NAME)
 {
 }
Ejemplo n.º 22
0
 private PnPConnection(ClientContext context, ConnectionType connectionType, PSCredential credential, string clientId, string clientSecret, string url, string tenantAdminUrl, string pnpVersionTag, InitializationType initializationType)
     : this(context, connectionType, credential, url, tenantAdminUrl, pnpVersionTag, initializationType)
 {
     ClientId     = clientId;
     ClientSecret = clientSecret;
 }
Ejemplo n.º 23
0
        internal static PnPConnection CreateWithCredentials(Cmdlet cmdlet, Uri url, PSCredential credentials, bool currentCredentials, string tenantAdminUrl, AzureEnvironment azureEnvironment = AzureEnvironment.Production, string clientId = null, string redirectUrl = null, bool onPrem = false, InitializationType initializationType = InitializationType.Credentials)
        {
            var context = new PnPClientContext(url.AbsoluteUri)
            {
                ApplicationName         = Resources.ApplicationName,
                DisableReturnValueCache = true
            };
            PnPConnection spoConnection = null;

            if (!onPrem)
            {
                var tenantId = string.Empty;
                try
                {
                    if (!string.IsNullOrWhiteSpace(clientId))
                    {
                        PnP.Framework.AuthenticationManager authManager = null;
                        if (PnPConnection.CachedAuthenticationManager != null)
                        {
                            authManager = PnPConnection.CachedAuthenticationManager;
                            PnPConnection.CachedAuthenticationManager = null;
                        }
                        else
                        {
                            authManager = PnP.Framework.AuthenticationManager.CreateWithCredentials(clientId, credentials.UserName, credentials.Password, redirectUrl, azureEnvironment);
                        }
                        using (authManager)
                        {
                            context = PnPClientContext.ConvertFrom(authManager.GetContext(url.ToString()));
                            context.ExecuteQueryRetry();
                            cmdlet.WriteVerbose("Acquiring token");
                            var accesstoken = authManager.GetAccessTokenAsync(url.ToString()).GetAwaiter().GetResult();
                            cmdlet.WriteVerbose("Token acquired");
                            var parsedToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(accesstoken);
                            tenantId = parsedToken.Claims.FirstOrDefault(c => c.Type == "tid").Value;
                        }
                    }
                    else
                    {
                        PnP.Framework.AuthenticationManager authManager = null;
                        if (PnPConnection.CachedAuthenticationManager != null)
                        {
                            authManager = PnPConnection.CachedAuthenticationManager;
                        }
                        else
                        {
                            authManager = PnP.Framework.AuthenticationManager.CreateWithCredentials(credentials.UserName, credentials.Password, azureEnvironment);
                        }
                        using (authManager)
                        {
                            context = PnPClientContext.ConvertFrom(authManager.GetContext(url.ToString()));
                            context.ExecuteQueryRetry();

                            var accessToken = authManager.GetAccessTokenAsync(url.ToString()).GetAwaiter().GetResult();
                            var parsedToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(accessToken);
                            tenantId = parsedToken.Claims.FirstOrDefault(c => c.Type == "tid").Value;
                        }
                    }
                }
                catch (ClientRequestException)
                {
                    context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                }
                catch (ServerException)
                {
                    context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                }
                var connectionType = ConnectionType.O365;
                if (url.Host.ToLowerInvariant().EndsWith($"sharepoint.{PnP.Framework.AuthenticationManager.GetSharePointDomainSuffix(azureEnvironment)}"))
                {
                    connectionType = ConnectionType.O365;
                }

                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }

                spoConnection = new PnPConnection(context, connectionType, credentials, url.ToString(), tenantAdminUrl, PnPPSVersionTag, initializationType)
                {
                    ConnectionMethod = Model.ConnectionMethod.Credentials,
                    AzureEnvironment = azureEnvironment,
                    Tenant           = tenantId
                };
            }
            else
            {
                PnP.Framework.AuthenticationManager authManager = null;
                if (PnPConnection.CachedAuthenticationManager != null)
                {
                    authManager = PnPConnection.CachedAuthenticationManager;
                }
                else
                {
                    authManager = new PnP.Framework.AuthenticationManager();
                }
                using (authManager)
                {
                    if (currentCredentials)
                    {
                        context = PnPClientContext.ConvertFrom(authManager.GetOnPremisesContext(url.ToString()));
                    }
                    else
                    {
                        context = PnPClientContext.ConvertFrom(authManager.GetOnPremisesContext(url.ToString(), credentials.UserName, credentials.Password));
                    }
                }

                spoConnection = new PnPConnection(context, ConnectionType.O365, credentials, url.ToString(), tenantAdminUrl, PnPPSVersionTag, initializationType)
                {
                    ConnectionMethod = Model.ConnectionMethod.Credentials,
                    AzureEnvironment = azureEnvironment,
                };
            }

            return(spoConnection);
        }
Ejemplo n.º 24
0
        internal PnPConnection(ClientContext context, GenericToken tokenResult, ConnectionType connectionType, int minimalHealthScore, int retryCount, int retryWait, PSCredential credential, string url, string tenantAdminUrl, string pnpVersionTag, PSHost host, bool disableTelemetry, InitializationType initializationType)
        {
            if (!disableTelemetry)
            {
                InitializeTelemetry(context, host, initializationType);
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            var coreAssembly = Assembly.GetExecutingAssembly();

            UserAgent          = $"NONISV|SharePointPnP|PnPPS/{((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version}";
            Context            = context;
            ConnectionType     = connectionType;
            MinimalHealthScore = minimalHealthScore;
            RetryCount         = retryCount;
            RetryWait          = retryWait;
            PSCredential       = credential;
            TenantAdminUrl     = tenantAdminUrl;
            ContextCache       = new List <ClientContext> {
                context
            };
            PnPVersionTag                = pnpVersionTag;
            Url                          = (new Uri(url)).AbsoluteUri;
            ConnectionMethod             = ConnectionMethod.AccessToken;
            ClientId                     = PnPManagementShellClientId;
            Tenant                       = tokenResult.ParsedToken.Claims.FirstOrDefault(c => c.Type == "tid").Value;
            context.ExecutingWebRequest += (sender, args) =>
            {
                args.WebRequestExecutor.WebRequest.UserAgent            = UserAgent;
                args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + tokenResult.AccessToken;
            };
        }
Ejemplo n.º 25
0
        internal PnPConnection(ConnectionMethod connectionMethod, ConnectionType connectionType, int minimalHealthScore, int retryCount, int retryWait, string pnpVersionTag, PSHost host, bool disableTelemetry, InitializationType initializationType)
        {
            if (!disableTelemetry)
            {
                InitializeTelemetry(null, host, initializationType);
            }
            var coreAssembly = Assembly.GetExecutingAssembly();

            UserAgent          = $"NONISV|SharePointPnP|PnPPS/{((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version}";
            ConnectionType     = connectionType;
            MinimalHealthScore = minimalHealthScore;
            RetryCount         = retryCount;
            RetryWait          = retryWait;
            PnPVersionTag      = pnpVersionTag;
            ConnectionMethod   = connectionMethod;
        }
Ejemplo n.º 26
0
        //internal static ClientContext GetCachedContext(string url)
        //{
        //    return ContextCache.FirstOrDefault(c => System.Net.WebUtility.UrlEncode(c.Url) == System.Net.WebUtility.UrlEncode(url));
        //}

        //internal static void ClearContextCache()
        //{
        //    ContextCache.Clear();
        //}

        internal void InitializeTelemetry(ClientContext context, InitializationType initializationType)
        {
            var enableTelemetry = false;
            var userProfile     = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            var telemetryFile   = System.IO.Path.Combine(userProfile, ".pnppowershelltelemetry");

            if (!System.IO.File.Exists(telemetryFile))
            {
                enableTelemetry = true;
            }
            else
            {
                if (System.IO.File.ReadAllText(telemetryFile).ToLower() == "allow")
                {
                    enableTelemetry = true;
                }
            }
            if (enableTelemetry)
            {
                var serverLibraryVersion = "";
                var serverVersion        = "";
                if (context != null)
                {
                    try
                    {
                        if (context.ServerLibraryVersion != null)
                        {
                            serverLibraryVersion = context.ServerLibraryVersion.ToString();
                        }
                        if (context.ServerVersion != null)
                        {
                            serverVersion = context.ServerVersion.ToString();
                        }
                    }
                    catch { }
                }

                ApplicationInsights = new ApplicationInsights();
                var coreAssembly = Assembly.GetExecutingAssembly();
                ApplicationInsights.Initialize(serverLibraryVersion, serverVersion, initializationType.ToString(), ((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version.ToString());
                ApplicationInsights.TrackEvent("Connect-PnPOnline");

                //TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();
                //TelemetryClient = new TelemetryClient(config);
                //config.InstrumentationKey = "a301024a-9e21-4273-aca5-18d0ef5d80fb";
                ////config..Context.Session.Id = Guid.NewGuid().ToString();
                //TelemetryClient.Context.Cloud.RoleInstance = "PnPPowerShell";
                //TelemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString();

                //TelemetryProperties = new Dictionary<string, string>(10);
                //TelemetryProperties.Add("ServerLibraryVersion", serverLibraryVersion);
                //TelemetryProperties.Add("ServerVersion", serverVersion);
                //TelemetryProperties.Add("ConnectionMethod", initializationType.ToString());
                //var coreAssembly = Assembly.GetExecutingAssembly();
                //TelemetryProperties.Add("Version", ((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version.ToString());
                //TelemetryProperties.Add("Platform", "SPO");
                //TelemetryClient.TrackEvent("Connect-PnPOnline", TelemetryProperties);


                //TelemetryClient = new TelemetryClient(;
                //TelemetryClient.InstrumentationKey = "a301024a-9e21-4273-aca5-18d0ef5d80fb";
                //TelemetryClient.Context.Session.Id = Guid.NewGuid().ToString();
                //TelemetryClient.Context.Cloud.RoleInstance = "PnPPowerShell";
                //TelemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
                //TelemetryClient.Context.Properties.Add("ServerLibraryVersion", serverLibraryVersion);
                //TelemetryClient.Context.Properties.Add("ServerVersion", serverVersion);
                //TelemetryClient.Context.Properties.Add("ConnectionMethod", initializationType.ToString());
                //var coreAssembly = Assembly.GetExecutingAssembly();
                //TelemetryClient.Context.Properties.Add("Version", ((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version.ToString());
                //TelemetryClient.Context.Properties.Add("Platform", "SPO");
                //TelemetryClient.TrackEvent("Connect-PnPOnline");
            }
        }
Ejemplo n.º 27
0
 public InitializeNotification(InitializationType initializationType)
 {
     InitializationType = initializationType;
 }
Ejemplo n.º 28
0
 public InitializerAttribute(InitializationType type, string secondaryInitializerName)
 {
     m_type = type;
     m_secondaryInitializerName = secondaryInitializerName;
 }