This manager class can be used to obtain a SharePointContext object
Exemplo n.º 1
1
     protected static void UsingTenantContext(Action<ClientContext> action)
     {
         var auth = new OfficeDevPnP.Core.AuthenticationManager();
         var tenenatUrl = ConfigurationManager.AppSettings["TenantAdminUrl"];
         var realm = ConfigurationManager.AppSettings["Realm"];
         var appId = ConfigurationManager.AppSettings["ClientId"];
         var appSecret = ConfigurationManager.AppSettings["ClientSecret"];
 
         using (var context = auth.GetAppOnlyAuthenticatedContext(tenenatUrl, realm, appId, appSecret))
         {
             action(context);
         }
     }
 public ClientContext GetContext(string url)
 {
     var authenticationManager = new AuthenticationManager();
     var username = ConfigurationManager.AppSettings["SiteCollectionRequests_UserName"];
     var password = ConfigurationManager.AppSettings["SiteCollectionRequests_Password"];
     return authenticationManager.GetSharePointOnlineAuthenticatedContextTenant(url, username, password);
 }
        internal static SPOnlineConnection InitiateAzureADAppOnlyConnection(Uri url, string clientId, string tenant, string certificatePEM, string privateKeyPEM, SecureString certificatePassword, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, PSHost host, bool disableTelemetry, bool skipAdminCheck = false, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            string           password    = new System.Net.NetworkCredential(string.Empty, certificatePassword).Password;
            X509Certificate2 certificate = CertificateHelper.GetCertificateFromPEMstring(certificatePEM, privateKeyPEM, password);

            var authManager    = new OfficeDevPnP.Core.AuthenticationManager();
            var clientContext  = authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificate, azureEnvironment);
            var context        = PnPClientContext.ConvertFrom(clientContext, retryCount, retryWait * 1000);
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }

            CleanupCryptoMachineKey(certificate);

            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.AADAppOnly));
        }
        internal static SPOnlineConnection InstantiateHighTrustConnection(string url, string clientId, string hightrustCertificatePath, string hightrustCertificatePassword, string hightrustCertificateIssuerId, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, PSHost host, bool disableTelemetry, bool skipAdminCheck, string loginName)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();
            var context     = authManager.GetHighTrustCertificateAppAuthenticatedContext(url, clientId, hightrustCertificatePath, hightrustCertificatePassword, hightrustCertificateIssuerId, loginName);

            return(InstantiateHighTrustConnection(context, url, minimalHealthScore, retryCount, retryWait, requestTimeout, tenantAdminUrl, host, disableTelemetry, skipAdminCheck));
        }
        internal static SPOnlineConnection InstantiateHighTrustConnection(string url, string clientId, System.Security.Cryptography.X509Certificates.X509Certificate2 hightrustCertificate, string hightrustCertificateIssuerId, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();
            var context     = authManager.GetHighTrustCertificateAppOnlyAuthenticatedContext(url, clientId, hightrustCertificate, hightrustCertificateIssuerId);

            return(InstantiateHighTrustConnection(context, url, minimalHealthScore, retryCount, retryWait, requestTimeout, tenantAdminUrl, skipAdminCheck));
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {

            AuthenticationManager am = new AuthenticationManager();
            ClientContext cc = am.GetSharePointOnlineAuthenticatedContextTenant("https://bertonline.sharepoint.com/sites/dev", "*****@*****.**", GetPassWord());

            cc.Load(cc.Web.EventReceivers);
            cc.ExecuteQuery();

            List<EventReceiverDefinition> rerToDelete = new List<EventReceiverDefinition>();

            foreach (EventReceiverDefinition rer in cc.Web.EventReceivers)
            {
                Console.WriteLine(string.Format("Type:{0}, Url:{1}, Assembly:{2}, Class:{3}", rer.EventType, rer.ReceiverUrl, rer.ReceiverAssembly, rer.ReceiverClass));
                if (rer.EventType == EventReceiverType.ListAdded && !String.IsNullOrEmpty(rer.ReceiverUrl))
                {
                    rerToDelete.Add(rer);
                }
            }

            Console.WriteLine("Cleanup old ListAdded event receivers");
            foreach(EventReceiverDefinition rer in rerToDelete)
            {
                // this might fail for side loaded apps
                rer.DeleteObject();
            }

            cc.ExecuteQuery();

        }
Exemplo n.º 7
0
        internal static SPOnlineConnection InstantiateWebloginConnection(Uri url, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();

            var context = PnPClientContext.ConvertFrom(authManager.GetWebLoginClientContext(url.ToString()), retryCount, retryWait * 1000);

            if (context != null)
            {
                context.RetryCount      = retryCount;
                context.Delay           = retryWait * 1000;
                context.ApplicationName = Properties.Resources.ApplicationName;
                context.RequestTimeout  = requestTimeout;
#if !ONPREMISES
                context.DisableReturnValueCache = true;
#elif SP2016
                context.DisableReturnValueCache = true;
#endif
                var connectionType = ConnectionType.OnPrem;
                if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
                {
                    connectionType = ConnectionType.O365;
                }
                if (skipAdminCheck == false)
                {
                    if (IsTenantAdminSite(context))
                    {
                        connectionType = ConnectionType.TenantAdmin;
                    }
                }

                return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString()));
            }
            throw new Exception("Error establishing a connection, context is null");
        }
Exemplo n.º 8
0
        private static SPOnlineConnection InitiateAzureAdAppOnlyConnectionWithCert(Uri url, string clientId, string tenant,
                                                                                   int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, PSHost host, bool disableTelemetry,
                                                                                   bool skipAdminCheck, AzureEnvironment azureEnvironment, X509Certificate2 certificate)
        {
            var authManager   = new OfficeDevPnP.Core.AuthenticationManager();
            var clientContext =
                authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificate,
                                                                  azureEnvironment);
            var context = PnPClientContext.ConvertFrom(clientContext, retryCount, retryWait * 1000);

            context.RequestTimeout = requestTimeout;
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }

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

            CleanupCryptoMachineKey(certificate);

            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null,
                                                       url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.AADAppOnly);

            spoConnection.ConnectionMethod = ConnectionMethod.AzureADAppOnly;
            return(spoConnection);
        }
Exemplo n.º 9
0
        //internal static Uri RedirectUri;
        //internal static string ClientId;

        internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, string realm, string clientId, string clientSecret, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();

            if (realm == null)
            {
                realm = GetRealmFromTargetUrl(url);
            }

            var context = PnPClientContext.ConvertFrom(authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret), retryCount, retryWait * 1000);

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;
#if !ONPREMISES
            context.DisableReturnValueCache = true;
#elif SP2016
            context.DisableReturnValueCache = true;
#endif
            var connectionType = ConnectionType.OnPrem;
            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString()));
        }
Exemplo n.º 10
0
        internal static SPOnlineConnection InitiateAzureADNativeApplicationConnection(Uri url, string clientId, Uri redirectUri, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();


            string         appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string         configFile    = Path.Combine(appDataFolder, "SharePointPnP.PowerShell\\tokencache.dat");
            FileTokenCache cache         = new FileTokenCache(configFile);

            var context = PnPClientContext.ConvertFrom(authManager.GetAzureADNativeApplicationAuthenticatedContext(url.ToString(), clientId, redirectUri, cache), retryCount, retryWait * 10000);

            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString()));
        }
Exemplo n.º 11
0
        public static void ProvisionArtifactsByTemplate()
        {
            // Create a PnP AuthenticationManager object
            AuthenticationManager am = new AuthenticationManager();

            // Authenticate against SPO with an App-Only access token
            using (ClientContext context = am.GetAzureADAppOnlyAuthenticatedContext(
                O365ProjectsAppContext.CurrentSiteUrl, O365ProjectsAppSettings.ClientId,
                O365ProjectsAppSettings.TenantId, O365ProjectsAppSettings.AppOnlyCertificate))
            {
                Web web = context.Web;

                // Load the template from the file system
                XMLTemplateProvider provider =
                new XMLFileSystemTemplateProvider(
                    String.Format(HttpContext.Current.Server.MapPath(".")),
                    "ProvisioningTemplates");

                ProvisioningTemplate template = provider.GetTemplate("O365ProjectsAppSite.xml");

                // Configure the AppSiteUrl parameter
                template.Parameters["AppSiteUrl"] = O365ProjectsAppContext.CurrentAppSiteUrl;

                // Apply the template to the target site
                template.Connector = provider.Connector;
                web.ApplyProvisioningTemplate(template);
            }
        }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            OfficeDevPnP.Core.Utilities.LoggingUtility.Internal.Source.Switch.Level = SourceLevels.Information;
            OfficeDevPnP.Core.Utilities.LoggingUtility.Internal.Source.Listeners.Add(new ConsoleTraceListener() { Name = "Console" });

            // Create a context to work with
            // Office 365 Multi-tenant sample - TODO Change your URL and username
            ClientContext cc = new AuthenticationManager().GetSharePointOnlineAuthenticatedContextTenant("https://bertonline.sharepoint.com", "*****@*****.**", GetPassWord());

            // Office 365 Dedicated sample - On-Premises sample
            //ClientContext cc = new AuthenticationManager().GetNetworkCredentialAuthenticatedContext("https://sp2013.bertonline.info", "administrator", GetPassWord(), "set1");

            // Get a list of sites: search is one way to obtain this list, alternative can be a site directory 
            List<SiteEntity> sites = cc.Web.SiteSearchScopedByUrl("https://bertonline.sharepoint.com");

            // Generic settings (apply changes on all webs or just root web
            bool applyChangesToAllWebs = true;

            // Settings for branding specific changes
            // Version of the new theme, if the site has a lower version it will be upgraded
            int currentBrandingVersion = 2;
            // Name of the theme that will be applied
            string currentThemeName = "SPCTheme";
            // Turn forceBranding to true to apply branding in case the site was not branded before
            bool forceBranding = false;

            // Optionally further refine the list of returned site collections by inspecting the url here we are looking for a specific value that is contained in the url
        
            var filteredSites = from p in sites
                                where p.Url.Contains("13003")
                                select p;

            List<SiteEntity> sitesAndSubSites = new List<SiteEntity>();
            if (applyChangesToAllWebs)
            {
                // we want to update all webs, so the list of sites is extended with all sub sites
                foreach (SiteEntity site in filteredSites)
                {
                    sitesAndSubSites.Add(new SiteEntity() { Url = site.Url, Title = site.Title, Template = site.Template });
                    GetSubSites(cc, site.Url, ref sitesAndSubSites);
                }
                sites = sitesAndSubSites;
            }

            // iterate the list of sites and perform the wanted updates
            foreach (SiteEntity site in sites)
            {
                //Create a clientcontext for the site we're inspecting
                using (ClientContext siteContext = new ClientContext(site.Url))
                {
                    siteContext.Credentials = cc.Credentials;
                    //Process the branding updates for the site
                    ProcessBrandingUpdate(siteContext, site, currentThemeName, currentBrandingVersion, forceBranding);
                }
            }

            Console.WriteLine("----------------------------------------------------------------------");
            Console.ReadLine();
        }
Exemplo n.º 13
0
        public static void ProvisionArtifactsByCode()
        {
            // Create a PnP AuthenticationManager object
            AuthenticationManager am = new AuthenticationManager();

            // Authenticate against SPO with an App-Only access token
            using (ClientContext context = am.GetAzureADAppOnlyAuthenticatedContext(
                O365ProjectsAppContext.CurrentSiteUrl, O365ProjectsAppSettings.ClientId,
                O365ProjectsAppSettings.TenantId, O365ProjectsAppSettings.AppOnlyCertificate))
            {
                Web web = context.Web;
                List targetLibrary = null;

                // If the target library does not exist (PnP extension method)
                if (!web.ListExists(O365ProjectsAppSettings.LibraryTitle))
                {
                    // Create it using another PnP extension method
                    targetLibrary = web.CreateList(ListTemplateType.DocumentLibrary,
                        O365ProjectsAppSettings.LibraryTitle, true, true);
                }
                else
                {
                    targetLibrary = web.GetListByTitle(O365ProjectsAppSettings.LibraryTitle);
                }

                // If the target library exists
                if (targetLibrary != null)
                {
                    // Try to get the user's custom action
                    UserCustomAction customAction = targetLibrary.GetCustomAction(O365ProjectsAppConstants.ECB_Menu_Name);

                    // If it doesn't exist
                    if (customAction == null)
                    {
                        // Add the user custom action to the list
                        customAction = targetLibrary.UserCustomActions.Add();
                        customAction.Name = O365ProjectsAppConstants.ECB_Menu_Name;
                        customAction.Location = "EditControlBlock";
                        customAction.Sequence = 100;
                        customAction.Title = "Manage Business Project";
                        customAction.Url = $"{O365ProjectsAppContext.CurrentAppSiteUrl}Project/?SiteUrl={{SiteUrl}}&ListId={{ListId}}&ItemId={{ItemId}}&ItemUrl={{ItemUrl}}";
                    }
                    else
                    {
                        // Update the already existing Custom Action
                        customAction.Name = O365ProjectsAppConstants.ECB_Menu_Name;
                        customAction.Location = "EditControlBlock";
                        customAction.Sequence = 100;
                        customAction.Title = "Manage Business Project";
                        customAction.Url = $"{O365ProjectsAppContext.CurrentAppSiteUrl}Project/?SiteUrl={{SiteUrl}}&ListId={{ListId}}&ItemId={{ItemId}}&ItemUrl={{ItemUrl}}";
                    }

                    customAction.Update();
                    context.ExecuteQueryRetry();

                }
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// REtrieve an authenticated ClientContext using AppOnly auth
        /// </summary>
        /// <param name="Url">The SharePoint Online site Url</param>
        /// <param name="AppID">The App id</param>
        /// <param name="AppSecret">The App secret</param>
        /// <returns>A tested authenticated ClientContext</returns>
        public static ClientContext GetAuthenticatedContext(string Url, string AppID, string AppSecret)
        {
            var am      = new OfficeDevPnP.Core.AuthenticationManager();
            var context = am.GetAppOnlyAuthenticatedContext(Url, AppID, AppSecret);

            // We try to call for the SPO site title
            validateAuthentication(context);
            return(context);
        }
Exemplo n.º 15
0
        protected static void UsingTenantContext(Action <ClientContext> action)
        {
            var auth       = new OfficeDevPnP.Core.AuthenticationManager();
            var tenenatUrl = ConfigurationManager.AppSettings["TenantAdminUrl"];
            var realm      = ConfigurationManager.AppSettings["Realm"];
            var appId      = ConfigurationManager.AppSettings["ClientId"];
            var appSecret  = ConfigurationManager.AppSettings["ClientSecret"];

            using (var context = auth.GetAppOnlyAuthenticatedContext(tenenatUrl, realm, appId, appSecret))
            {
                action(context);
            }
        }
Exemplo n.º 16
0
        private ClientContext GetClientContext()
        {
            AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();

            if (clientContext == null)
            {
                return(authManager.GetWebLoginClientContext(SITE_URL));
            }
            else
            {
                return(clientContext);
            }
        }
        internal static SPOnlineConnection InitiateAccessTokenConnection(Uri url, string accessToken, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            var authManager    = new OfficeDevPnP.Core.AuthenticationManager();
            var context        = PnPClientContext.ConvertFrom(authManager.GetAzureADAccessTokenAuthenticatedContext(url.ToString(), accessToken), retryCount, retryWait);
            var connectionType = ConnectionType.O365;

            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag));
        }
        public static ClientContext GetAppOnlyClientContext(String siteUrl)
        {
            string tenantID = ClaimsPrincipal.Current.HasClaim(c => c.Type == "http://schemas.microsoft.com/identity/claims/tenantid") ?
                ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value :
                PnPPartnerPackSettings.Tenant;

            AuthenticationManager authManager = new AuthenticationManager();
            ClientContext context = authManager.GetAzureADAppOnlyAuthenticatedContext(
                siteUrl,
                PnPPartnerPackSettings.ClientId,
                tenantID,
                PnPPartnerPackSettings.AppOnlyCertificate);

            return (context);
        }
Exemplo n.º 19
0
        private static ClientContext CreateContext(string contextUrl, ICredentials credentials)
        {
            ClientContext context = null;

            if (!String.IsNullOrEmpty(AppId) && !String.IsNullOrEmpty(AppSecret))
            {
                OfficeDevPnP.Core.AuthenticationManager am = new OfficeDevPnP.Core.AuthenticationManager();
                context = am.GetAppOnlyAuthenticatedContext(contextUrl, AppId, AppSecret);
            }
            else
            {
                context             = new ClientContext(contextUrl);
                context.Credentials = credentials;
            }

            context.RequestTimeout = 1000 * 60 * 15;
            return(context);
        }
Exemplo n.º 20
0
        // This function will get triggered/executed when a new message is written
        // on an Azure Queue called queue.

        public static void ExecuteTimer([TimerTrigger("0 */5 * * * *", RunOnStartup = true)] TimerInfo timer, TextWriter log)
        {
            OfficeDevPnP.Core.AuthenticationManager authMan = new OfficeDevPnP.Core.AuthenticationManager();
            using (ClientContext ctx = authMan.GetAppOnlyAuthenticatedContext(ConfigurationManager.AppSettings["PiwikAdminSiteUrl"], ConfigurationManager.AppSettings["PiwikAzureAppKey"], ConfigurationManager.AppSettings["PiwikAzureAppSecret"]))
            {
                Functions f = new Functions();

                AzureLogger splogger = new AzureLogger();
                splogger.WriteLog(Category.Information, "Piwik PRO Job", "Started");
                Configuration         cfg  = new Configuration(splogger, ctx);
                PiwikPROJobOperations pbjo = new PiwikPROJobOperations(cfg, splogger);

                pbjo.GetAllNewSitesAndOperate(ctx, ConfigurationManager.AppSettings["PiwikAzureAppKey"], ConfigurationManager.AppSettings["PiwikAzureAppSecret"], ConfigurationManager.AppSettings["PiwikAdminTenantSiteUrl"]);
                pbjo.GetAllDeactivatingSitesAndOperate(ctx, ConfigurationManager.AppSettings["PiwikAzureAppKey"], ConfigurationManager.AppSettings["PiwikAzureAppSecret"], ConfigurationManager.AppSettings["PiwikAdminTenantSiteUrl"]);

                splogger.WriteLog(Category.Information, "Piwik PRO Job", "Finished");
            }
        }
Exemplo n.º 21
0
        internal static SPOnlineConnection InitiateAzureADAppOnlyConnection(Uri url, string clientId, string tenant, string certificatePath, SecureString certificatePassword, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false)
        {
            var authManager    = new OfficeDevPnP.Core.AuthenticationManager();
            var context        = PnPClientContext.ConvertFrom(authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificatePath, certificatePassword), retryCount, retryWait * 1000);
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString()));
        }
        internal static SPOnlineConnection InstantiateAdfsConnection(Uri url, PSCredential credentials, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();

            var networkCredentials = credentials.GetNetworkCredential();

            string adfsHost;
            string adfsRelyingParty;

            GetAdfsConfigurationFromTargetUri(url, out adfsHost, out adfsRelyingParty);

            if (string.IsNullOrEmpty(adfsHost) || string.IsNullOrEmpty(adfsRelyingParty))
            {
                throw new Exception("Cannot retrieve ADFS settings.");
            }

            var context = PnPClientContext.ConvertFrom(authManager.GetADFSUserNameMixedAuthenticatedContext(url.ToString(), networkCredentials.UserName, networkCredentials.Password, networkCredentials.Domain, adfsHost, adfsRelyingParty), retryCount, retryWait * 1000);

            context.RetryCount = retryCount;
            context.Delay      = retryWait * 1000;

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;
#if !ONPREMISES
            context.DisableReturnValueCache = true;
#elif SP2016
            context.DisableReturnValueCache = true;
#endif

            var connectionType = ConnectionType.OnPrem;

            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag);
            spoConnection.ConnectionMethod = Model.ConnectionMethod.ADFS;
            return(spoConnection);
        }
        internal static SPOnlineConnection InstantiateHighTrustConnection(string url, string clientId, string hightrustCertificatePath, string hightrustCertificatePassword, string hightrustCertificateIssuerId, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();
            var context     = authManager.GetHighTrustCertificateAppOnlyAuthenticatedContext(url, clientId, hightrustCertificatePath, hightrustCertificatePassword, hightrustCertificateIssuerId);

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;
#if SP2016
            context.DisableReturnValueCache = true;
#endif
            var connectionType = ConnectionType.OnPrem;
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag));
        }
        internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, string realm, string clientId, string clientSecret, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool disableTelemetry, bool skipAdminCheck = false, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();

            if (realm == null)
            {
                realm = GetRealmFromTargetUrl(url);
            }

            PnPClientContext context;

            if (url.DnsSafeHost.Contains("spoppe.com"))
            {
                context = PnPClientContext.ConvertFrom(authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret, acsHostUrl: "windows-ppe.net", globalEndPointPrefix: "login"), retryCount, retryWait * 1000);
            }
            else
            {
                context = PnPClientContext.ConvertFrom(authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret, acsHostUrl: authManager.GetAzureADACSEndPoint(azureEnvironment), globalEndPointPrefix: authManager.GetAzureADACSEndPointPrefix(azureEnvironment)), retryCount, retryWait * 1000);
            }

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;
#if !ONPREMISES
            context.DisableReturnValueCache = true;
#elif SP2016 || SP2019
            context.DisableReturnValueCache = true;
#endif
            var connectionType = ConnectionType.OnPrem;
            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, clientId, clientSecret, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.SPClientSecret));
        }
Exemplo n.º 25
0
        static void Main(string[] args)
        {

            // Office 365 Multi-tenant sample
            ClientContext cc = new AuthenticationManager().GetSharePointOnlineAuthenticatedContextTenant("https://yourtenant-my.sharepoint.com", "*****@*****.**", GetPassWord());

            // Office 365 Dedicated sample - On-Premises sample
            //ClientContext cc = new AuthenticationManager().GetNetworkCredentialAuthenticatedContext("https://my.contoso.com", "keyzersoze", GetPassWord(), "contoso");
            
            Console.WriteLine("----------------------------------------------------------------------");

            // Only lists the my sites
            List<SiteEntity> sites = cc.Web.MySiteSearch();

            // List all site collections
            //List<SiteEntity> sites = cc.Web.SiteSearch();

            // Lists site collections scoped to an URL
            //List<SiteEntity> sites = cc.Web.SiteSearchScopedByUrl("https://yourtenant.sharepoint.com");
            // List site collections scoped by title
            //List<SiteEntity> sites = cc.Web.SiteSearchScopedByTitle("test");

            // if needed furhter refine the returned set of site collections
            var filteredSites = from p in sites
                                where p.Url.Contains("my")
                                select p;

            foreach (var site in filteredSites)
            {
                Console.WriteLine("Title: {0}", site.Title);
                Console.WriteLine("Path: {0}", site.Url);
                Console.WriteLine("Description: {0}", site.Description);
                Console.WriteLine("Template: {0}", site.Template);
                Console.WriteLine("----------------------------------------------------------------------");
            }

            Console.WriteLine();
            Console.WriteLine("Press a key to continue...");
            Console.ReadKey();
        }
        internal static SPOnlineConnection InitiateAzureADAppOnlyConnection(Uri url, string clientId, string tenant, string certificatePath, SecureString certificatePassword, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, PSHost host, bool disableTelemetry, bool skipAdminCheck = false, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            var authManager    = new OfficeDevPnP.Core.AuthenticationManager();
            var context        = PnPClientContext.ConvertFrom(authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificatePath, certificatePassword, azureEnvironment), retryCount, retryWait * 1000);
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.AADAppOnly);

            spoConnection.ConnectionMethod = Model.ConnectionMethod.AzureADAppOnly;
            return(spoConnection);
        }
        internal static SPOnlineConnection InitiateAzureADAppOnlyConnection(Uri url, string clientId, string tenant, string certificatePEM, string privateKeyPEM, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            X509Certificate2 certificate = CertificateHelper.GetCertificateFromPEMstring(certificatePEM, privateKeyPEM);

            var authManager    = new OfficeDevPnP.Core.AuthenticationManager();
            var clientContext  = authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificate, azureEnvironment);
            var context        = PnPClientContext.ConvertFrom(clientContext, retryCount, retryWait * 1000);
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag));
        }
        internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, string realm, string clientId, string clientSecret, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();
            if (realm == null)
            {
                realm = GetRealmFromTargetUrl(url);
            }

            PnPClientContext context = null;
            if (url.DnsSafeHost.Contains("spoppe.com"))
            {
                context = PnPClientContext.ConvertFrom(authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret, acsHostUrl: "windows-ppe.net", globalEndPointPrefix: "login"), retryCount, retryWait * 1000);
            }
            else
            {
                context = PnPClientContext.ConvertFrom(authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret), retryCount, retryWait * 1000);
            }

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout = requestTimeout;
#if !ONPREMISES
            context.DisableReturnValueCache = true;
#elif SP2016
            context.DisableReturnValueCache = true;
#endif
            var connectionType = ConnectionType.OnPrem;
            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag);
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Admin, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            dynamic data = await req.Content.ReadAsAsync <object>();

            string SPParentSiteUrl   = data["SPParentSiteUrl"];
            string SPWebTemplate     = data["SPWebTemplate"];
            string SPSiteTitle       = data["SPSiteTitle"];
            string SPSiteDescription = data["SPSiteDescription"];
            string SPSiteURL         = data["SPSiteURL"];
            int    SPSiteLanguage    = data["SPSiteLanguage"];

            log.Info($"SPParentSiteUrl = '{SPParentSiteUrl}'");
            log.Info($"SPWebTemplate = '{SPWebTemplate}'");
            log.Info($"SPSiteTitle = '{SPSiteTitle}'");
            log.Info($"SPSiteDescription = '{SPSiteDescription}'");
            log.Info($"SPSiteURL = '{SPSiteURL}'");
            log.Info($"SPSiteLanguage = '{SPSiteLanguage}'");

            string userName = System.Environment.GetEnvironmentVariable("SPUser", EnvironmentVariableTarget.Process);
            string password = System.Environment.GetEnvironmentVariable("SPPwd", EnvironmentVariableTarget.Process);

            var authenticationManager = new PnPAuthenticationManager();
            var clientContext         = authenticationManager.GetSharePointOnlineAuthenticatedContextTenant(SPParentSiteUrl, userName, password);
            var pnpClientContext      = PnPClientContext.ConvertFrom(clientContext);

            var webCreationInfo = new Microsoft.SharePoint.Client.WebCreationInformation();

            webCreationInfo.WebTemplate = SPWebTemplate;
            webCreationInfo.Title       = SPSiteTitle;
            webCreationInfo.Description = SPSiteDescription;
            webCreationInfo.Url         = SPSiteURL;
            webCreationInfo.Language    = SPSiteLanguage;

            pnpClientContext.Web.Webs.Add(webCreationInfo);
            pnpClientContext.ExecuteQuery();

            return(req.CreateResponse(HttpStatusCode.OK, "request done"));
        }
        internal static SPOnlineConnection InitiateAzureADNativeApplicationConnection(Uri url, string clientId, Uri redirectUri, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();


            string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string configFile = Path.Combine(appDataFolder, "SharePointPnP.PowerShell\\tokencache.dat");
            FileTokenCache cache = new FileTokenCache(configFile);

            var context = PnPClientContext.ConvertFrom(authManager.GetAzureADNativeApplicationAuthenticatedContext(url.ToString(), clientId, redirectUri, cache), retryCount, retryWait * 10000);
            var connectionType = ConnectionType.OnPrem;
            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag);
        }
Exemplo n.º 31
0
 private bool TrySharePointConnection(string url, string clientId, string clientSecret)
 {
     try
     {
         using (var Context = new AuthenticationManager().GetAppOnlyAuthenticatedContext(url, clientId, clientSecret))
         {
             var web = Context.Web;
             try
             {
                 Context.Load(web);
                 Context.ExecuteQuery();
                 return(true);
             }
             catch (Exception)
             {
                 return(false);
             }
         };
     }
     catch (Exception e)
     {
         return(false);
     }
 }
        internal static SPOnlineConnection InstantiateAdfsCertificateConnection(Uri url, string serialNumber, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool disableTelemetry, bool skipAdminCheck = false, string loginProviderName = null)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();

            string adfsHost;
            string adfsRelyingParty;

            OfficeDevPnP.Core.AuthenticationManager.GetAdfsConfigurationFromTargetUri(url, loginProviderName, out adfsHost, out adfsRelyingParty);

            if (string.IsNullOrEmpty(adfsHost) || string.IsNullOrEmpty(adfsRelyingParty))
            {
                throw new Exception("Cannot retrieve ADFS settings.");
            }

            var context = authManager.GetADFSCertificateMixedAuthenticationContext(url.ToString(), serialNumber, adfsHost, adfsRelyingParty);

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;
#if !ONPREMISES
            context.DisableReturnValueCache = true;
#elif SP2016 || SP2019
            context.DisableReturnValueCache = true;
#endif
            var connectionType = ConnectionType.OnPrem;

            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.ADFS);
            spoConnection.ConnectionMethod = ConnectionMethod.ADFS;
            return(spoConnection);
        }
        public string Get(string title, string description)
        {
            String result = "";

            string siteUrl = "https://xxxxx.sharepoint.com/sites/xxxxx";                                                                 // Sharepoint URL where you have administrative permisions

            using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, "xxxxxxx", "xxxxxxx")) //put the client id and secret generate in sharepoint app registration site
            {
                cc.Load(cc.Web, p => p.Title);
                cc.ExecuteQuery();
                Console.WriteLine(cc.Web.Title);
                Web web = cc.Web;

                if (ProvisionSubSite(title, description, cc))
                {
                    result = "Hola el Site group fue creado satisfactoriamente: " + title + " Descripción: " + description;
                }
                else
                {
                    result = "Algo salio mal";
                }
            };
            return(result);
        }
Exemplo n.º 34
0
        internal ClientContext CloneContext(string url)
        {
            var context = ContextCache.FirstOrDefault(c => new Uri(c.Url).AbsoluteUri == new Uri(url).AbsoluteUri);

            if (context == null)
            {
                context = Context.Clone(url);
                try
                {
                    context.ExecuteQueryRetry();
                }
                catch (Exception ex)
                {
#if !ONPREMISES && !PNPPSCORE
                    if ((ex is WebException || ex is NotSupportedException) && CurrentConnection.PSCredential != null)
                    {
                        // legacy auth?
                        using (var authManager = new OfficeDevPnP.Core.AuthenticationManager())
                        {
                            context = authManager.GetAzureADCredentialsContext(url.ToString(), CurrentConnection.PSCredential.UserName, CurrentConnection.PSCredential.Password);
                        }
                        context.ExecuteQueryRetry();
                    }
                    else
                    {
#endif
                    throw;
#if !ONPREMISES && !PNPPSCORE
                }
#endif
                }
                ContextCache.Add(context);
            }
            Context = context;
            return(context);
        }
Exemplo n.º 35
0
        public static void BrowseFilesLibrary()
        {
            // Create a PnP AuthenticationManager object
            AuthenticationManager am = new AuthenticationManager();

            // Authenticate against SPO with a delegated access token
            using (ClientContext context = am.GetAzureADWebApplicationAuthenticatedContext(
                O365ProjectsAppContext.CurrentSiteUrl, (url) => {
                    return (MicrosoftGraphHelper.GetAccessTokenForCurrentUser(url));
                }))
            {
                Web web = context.Web;
                var targetLibrary = web.GetListByTitle(O365ProjectsAppSettings.LibraryTitle);

                context.Load(targetLibrary.RootFolder, 
                    fld => fld.ServerRelativeUrl,
                    fld => fld.Files.Include(f => f.Title, f => f.ServerRelativeUrl));
                context.ExecuteQueryRetry();

                foreach (var file in targetLibrary.RootFolder.Files)
                {
                    // Handle each file object ... this is just a sample ...
                }
            }
        }
        internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, PSCredential credentials, PSHost host, bool currentCredentials, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool disableTelemetry, bool skipAdminCheck = false, ClientAuthenticationMode authenticationMode = ClientAuthenticationMode.Default)
        {
            var context = new PnPClientContext(url.AbsoluteUri);

            context.RetryCount      = retryCount;
            context.Delay           = retryWait * 1000;
            context.ApplicationName = Properties.Resources.ApplicationName;
#if !ONPREMISES
            context.DisableReturnValueCache = true;
#elif SP2016 || SP2019
            context.DisableReturnValueCache = true;
#endif
            context.RequestTimeout = requestTimeout;

            context.AuthenticationMode = authenticationMode;

            if (authenticationMode == ClientAuthenticationMode.FormsAuthentication)
            {
                var formsAuthInfo = new FormsAuthenticationLoginInfo(credentials.UserName, EncryptionUtility.ToInsecureString(credentials.Password));
                context.FormsAuthenticationLoginInfo = formsAuthInfo;
            }

            if (!currentCredentials)
            {
                try
                {
                    SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(credentials.UserName, credentials.Password);
                    context.Credentials = onlineCredentials;
                    try
                    {
                        context.ExecuteQueryRetry();
                    }
#if !ONPREMISES
                    catch (NotSupportedException nox)
                    {
#if NETSTANDARD2_1
                        // Legacy auth is not supported with .NET Standard
                        throw nox;
#else
                        // legacy auth?
                        var authManager = new OfficeDevPnP.Core.AuthenticationManager();
                        context = PnPClientContext.ConvertFrom(authManager.GetAzureADCredentialsContext(url.ToString(), credentials.UserName, credentials.Password));
                        context.ExecuteQueryRetry();
#endif
                    }
#endif
                    catch (ClientRequestException)
                    {
                        context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    }
                    catch (ServerException)
                    {
                        context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    }
                }
                catch (ArgumentException)
                {
                    // OnPrem?
                    context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    try
                    {
                        context.ExecuteQueryRetry();
                    }
                    catch (ClientRequestException ex)
                    {
                        throw new Exception("Error establishing a connection", ex);
                    }
                    catch (ServerException ex)
                    {
                        throw new Exception("Error establishing a connection", ex);
                    }
                }
            }
            else
            {
                if (credentials != null)
                {
                    context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                }
                else
                {
                    // If current credentials should be used, use the DefaultNetworkCredentials of the CredentialCache. This has the same effect
                    // as using "UseDefaultCredentials" in a HttpClient.
                    context.Credentials = CredentialCache.DefaultNetworkCredentials;
                }
            }
#if SP2013 || SP2016 || SP2019
            var connectionType = ConnectionType.OnPrem;
#else
            var connectionType = ConnectionType.O365;
#endif
            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }

            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, credentials, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.Credentials);
            spoConnection.ConnectionMethod = Model.ConnectionMethod.Credentials;
            return(spoConnection);
        }
Exemplo n.º 37
0
        static void Main(string[] args)
        {
            // Office 365 Multi-tenant sample
            // For a console application you need to create a context: this can be done by creating a context based on a user and password. 
            // Using this approach you can add administrators to site collections for which the user used to create the context is already an 
            // admin.
            Console.Write("Tenant name (e.g. ams if your SharePoint url is https://");
            ConsoleWriteColor("ams", ConsoleColor.Green);
            Console.WriteLine(".sharepoint.com) :");
            string tenantName = Console.ReadLine();

            Console.Write("Name of site collection to target permissions (siteName)\r\n(https://" + tenantName + ".sharepoint.com/sites/");
            ConsoleWriteColor("<siteName>", ConsoleColor.Green);
            Console.WriteLine(") :");
            string siteName = Console.ReadLine();
            
            Console.Write("Tenant admin name (");
            ConsoleWriteColor("<tenantAdminName>", ConsoleColor.Green);
            Console.WriteLine("@" + tenantName + ".onmicrosoft.com) :");
            string tenantAdminUserName = Console.ReadLine();

            Console.WriteLine("Create SharePoint ClientContext object for the web");
            string tenantAdminPassword = GetPassword();
            AuthenticationManager authManager = new AuthenticationManager();

            string targetSiteUrl = String.Format("https://{0}.sharepoint.com/sites/{1}", tenantName, siteName);
            string tenantAdmin = String.Format("{0}@{1}.onmicrosoft.com", tenantAdminUserName, tenantName);
            ClientContext cc = authManager.GetSharePointOnlineAuthenticatedContextTenant(targetSiteUrl, tenantAdmin, tenantAdminPassword);
            
            // Alternative approach is via an AppOnly app that has been registered via AppRegNew/AppInv. Good thing with this approach is
            // that you registered app can have tenant level permissions which makes that you can use below code to for example set the 
            // additional site collection administrators to site collections where you today are not listed as site collection admin. A 
            // typical example would be adding additional admins to OneDrive site collections to enable eDiscovery
            //ClientContext cc = authManager.GetAppOnlyAuthenticatedContext("https://tenantname-my.sharepoint.com/personal/user2", "<your tenant realm>", "<appID>", "<appsecret>");

            // Tenant admin site context
            Console.WriteLine("Create SharePoint ClientContext object for the tenant administration web");
            string tenantAdminUrl = String.Format("https://{0}-admin.sharepoint.com/", tenantName);
            ClientContext ccTenant = authManager.GetSharePointOnlineAuthenticatedContextTenant(tenantAdminUrl, tenantAdmin, tenantAdminPassword);

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("----------------------------------------------------------------------");
            Console.WriteLine("Admins for site collection {0}:", targetSiteUrl);
            // Get a list of current admins
            List<UserEntity> admins = cc.Web.GetAdministrators();
            foreach (var admin in admins)
            {
                Console.WriteLine("{0} ({1})", admin.Title, admin.LoginName);
            }

            Console.WriteLine("----------------------------------------------------------------------");
            Console.WriteLine("Add administrators to the current site collection:");

            // Prepare a list of admins to add: below sample shows how to do this for Office 365 Multi-Tenant
            // NOTE: This is a sample of the code that must be implemented and WILL NOT EXECUTE since the user

            List<UserEntity> adminsToAdd = new List<UserEntity>();
            adminsToAdd.Add(new UserEntity() { LoginName = SAMPLE_USER_ACCOUNTNAME });

            cc.Web.AddAdministrators(adminsToAdd);
            foreach (var admin in adminsToAdd)
            {
                Console.WriteLine("Add: {0}", admin.LoginName);
            }

            Console.WriteLine("----------------------------------------------------------------------");
            Console.WriteLine("Remove administrators from the current site collection:");
            UserEntity adminToRemove = new UserEntity() { LoginName = SAMPLE_USER_ACCOUNTNAME };
            cc.Web.RemoveAdministrator(adminToRemove);
            Console.WriteLine("Removed: {0}", adminToRemove.LoginName);

            Console.WriteLine("----------------------------------------------------------------------");
            Console.WriteLine("External sharing settings for current site collection:");
            Console.WriteLine(ccTenant.Web.GetSharingCapabilitiesTenant(new Uri(targetSiteUrl)));

            Console.WriteLine("----------------------------------------------------------------------");
            Console.WriteLine("External users for current site collection:");
            List<ExternalUserEntity> externalUsers = ccTenant.Web.GetExternalUsersForSiteTenant(new Uri(targetSiteUrl));
            //List<ExternalUserEntity> externalUsers = ccTenant.Web.GetExternalUsersTenant();"
            foreach (var externalUser in externalUsers)
            {
                Console.WriteLine("{0} ({1})", externalUser.DisplayName, externalUser.AcceptedAs);
            }

            Console.WriteLine("Press enter to continue...");
            Console.ReadLine();
        }
        internal static SPOnlineConnection InstantiateWebloginConnection(Uri url, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();

            var context = PnPClientContext.ConvertFrom(authManager.GetWebLoginClientContext(url.ToString()), retryCount, retryWait * 1000);

            if (context != null)
            {
                context.RetryCount = retryCount;
                context.Delay = retryWait * 1000;
                context.ApplicationName = Properties.Resources.ApplicationName;
                context.RequestTimeout = requestTimeout;
#if !ONPREMISES
                context.DisableReturnValueCache = true;
#elif SP2016
            context.DisableReturnValueCache = true;
#endif
                var connectionType = ConnectionType.OnPrem;
                if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
                {
                    connectionType = ConnectionType.O365;
                }
                if (skipAdminCheck == false)
                {
                    if (IsTenantAdminSite(context))
                    {
                        connectionType = ConnectionType.TenantAdmin;
                    }
                }

                return new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag);
            }
            throw new Exception("Error establishing a connection, context is null");
        }
        /// <summary>
        /// Clones a ClientContext object while "taking over" the security context of the existing ClientContext instance
        /// </summary>
        /// <param name="clientContext">ClientContext to be cloned</param>
        /// <param name="siteUrl">Site URL to be used for cloned ClientContext</param>
        /// <param name="accessTokens">Dictionary of access tokens for sites URLs</param>
        /// <returns>A ClientContext object created for the passed site URL</returns>
        public static ClientContext Clone(this ClientRuntimeContext clientContext, Uri siteUrl, Dictionary <String, String> accessTokens = null)
        {
            if (siteUrl == null)
            {
                throw new ArgumentException(CoreResources.ClientContextExtensions_Clone_Url_of_the_site_is_required_, nameof(siteUrl));
            }

            ClientContext clonedClientContext = new ClientContext(siteUrl);

            clonedClientContext.AuthenticationMode = clientContext.AuthenticationMode;
            clonedClientContext.ClientTag          = clientContext.ClientTag;
#if !ONPREMISES || SP2016 || SP2019
            clonedClientContext.DisableReturnValueCache = clientContext.DisableReturnValueCache;
#endif


            // In case of using networkcredentials in on premises or SharePointOnlineCredentials in Office 365
            if (clientContext.Credentials != null)
            {
                clonedClientContext.Credentials = clientContext.Credentials;
            }
            else
            {
                // Check if we do have context settings
                var contextSettings = clientContext.GetContextSettings();

                if (contextSettings != null) // We do have more information about this client context, so let's use it to do a more intelligent clone
                {
                    string newSiteUrl = siteUrl.ToString();

                    // A diffent host = different audience ==> new access token is needed
                    if (contextSettings.UsesDifferentAudience(newSiteUrl))
                    {
                        // We need to create a new context using a new authentication manager as the token expiration is handled in there
                        OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();

                        ClientContext newClientContext = null;
                        if (contextSettings.Type == ClientContextType.SharePointACSAppOnly)
                        {
                            newClientContext = authManager.GetAppOnlyAuthenticatedContext(newSiteUrl, TokenHelper.GetRealmFromTargetUrl(new Uri(newSiteUrl)), contextSettings.ClientId, contextSettings.ClientSecret, contextSettings.AcsHostUrl, contextSettings.GlobalEndPointPrefix);
                        }
#if !ONPREMISES && !NETSTANDARD2_0
                        else if (contextSettings.Type == ClientContextType.AzureADCredentials)
                        {
                            newClientContext = authManager.GetAzureADCredentialsContext(newSiteUrl, contextSettings.UserName, contextSettings.Password);
                        }
                        else if (contextSettings.Type == ClientContextType.AzureADCertificate)
                        {
                            newClientContext = authManager.GetAzureADAppOnlyAuthenticatedContext(newSiteUrl, contextSettings.ClientId, contextSettings.Tenant, contextSettings.Certificate, contextSettings.Environment);
                        }
#endif

                        if (newClientContext != null)
                        {
                            //Take over the form digest handling setting
                            newClientContext.FormDigestHandlingEnabled = (clientContext as ClientContext).FormDigestHandlingEnabled;
                            newClientContext.ClientTag = clientContext.ClientTag;
#if !ONPREMISES || SP2016 || SP2019
                            newClientContext.DisableReturnValueCache = clientContext.DisableReturnValueCache;
#endif
                            return(newClientContext);
                        }
                        else
                        {
                            throw new Exception($"Cloning for context setting type {contextSettings.Type} was not yet implemented");
                        }
                    }
                    else
                    {
                        // Take over the context settings, this is needed if we later on want to clone this context to a different audience
                        contextSettings.SiteUrl = newSiteUrl;
                        clonedClientContext.AddContextSettings(contextSettings);

                        clonedClientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
                        {
                            // Call the ExecutingWebRequest delegate method from the original ClientContext object, but pass along the webRequestEventArgs of
                            // the new delegate method
                            MethodInfo methodInfo      = clientContext.GetType().GetMethod("OnExecutingWebRequest", BindingFlags.Instance | BindingFlags.NonPublic);
                            object[]   parametersArray = new object[] { webRequestEventArgs };
                            methodInfo.Invoke(clientContext, parametersArray);
                        };
                    }
                }
                else // Fallback the default cloning logic if there were not context settings available
                {
                    //Take over the form digest handling setting
                    clonedClientContext.FormDigestHandlingEnabled = (clientContext as ClientContext).FormDigestHandlingEnabled;

                    var originalUri = new Uri(clientContext.Url);
                    // If the cloned host is not the same as the original one
                    // and if there is an active PnPProvisioningContext
                    if (originalUri.Host != siteUrl.Host &&
                        PnPProvisioningContext.Current != null)
                    {
                        // Let's apply that specific Access Token
                        clonedClientContext.ExecutingWebRequest += (sender, args) =>
                        {
                            // We get a fresh new Access Token for every request, to avoid using an expired one
                            var accessToken = PnPProvisioningContext.Current.AcquireToken(siteUrl.Authority, null);
                            args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken;
                        };
                    }
                    // Else if the cloned host is not the same as the original one
                    // and if there is a custom Access Token for it in the input arguments
                    else if (originalUri.Host != siteUrl.Host &&
                             accessTokens != null && accessTokens.Count > 0 &&
                             accessTokens.ContainsKey(siteUrl.Authority))
                    {
                        // Let's apply that specific Access Token
                        clonedClientContext.ExecutingWebRequest += (sender, args) =>
                        {
                            args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessTokens[siteUrl.Authority];
                        };
                    }
                    // Else if the cloned host is not the same as the original one
                    // and if the client context is a PnPClientContext with custom access tokens in its property bag
                    else if (originalUri.Host != siteUrl.Host &&
                             accessTokens == null && clientContext is PnPClientContext &&
                             ((PnPClientContext)clientContext).PropertyBag.ContainsKey("AccessTokens") &&
                             ((Dictionary <string, string>)((PnPClientContext)clientContext).PropertyBag["AccessTokens"]).ContainsKey(siteUrl.Authority))
                    {
                        // Let's apply that specific Access Token
                        clonedClientContext.ExecutingWebRequest += (sender, args) =>
                        {
                            args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + ((Dictionary <string, string>)((PnPClientContext)clientContext).PropertyBag["AccessTokens"])[siteUrl.Authority];
                        };
                    }
                    else
                    {
                        // In case of app only or SAML
                        clonedClientContext.ExecutingWebRequest += (sender, webRequestEventArgs) =>
                        {
                            // Call the ExecutingWebRequest delegate method from the original ClientContext object, but pass along the webRequestEventArgs of
                            // the new delegate method
                            MethodInfo methodInfo      = clientContext.GetType().GetMethod("OnExecutingWebRequest", BindingFlags.Instance | BindingFlags.NonPublic);
                            object[]   parametersArray = new object[] { webRequestEventArgs };
                            methodInfo.Invoke(clientContext, parametersArray);
                        };
                    }
                }
            }

            return(clonedClientContext);
        }
Exemplo n.º 40
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            if (adminPassword == null)
            {
                // This is the part where I grab the secret.
                var azureServiceTokenProvider = new AzureServiceTokenProvider();
                log.Info("Getting the secret.");
                var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
                log.Info("KeyVaultSecret: " + Environment.GetEnvironmentVariable("KeyVaultSecret"));
                adminPassword = (await kvClient.GetSecretAsync(Environment.GetEnvironmentVariable("KeyVaultSecret"))).Value;
            }

            // parse query parameter
            string name = req.GetQueryNameValuePairs()
                          .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
                          .Value;

            // Get request body
            dynamic data = await req.Content.ReadAsAsync <object>();

            // Set name to query string or body data
            name = name ?? data?.name;
            string title = data?.title;

            string siteUrl   = string.Empty;
            string adminUser = Environment.GetEnvironmentVariable("spAdminUser");

            log.Info("adminUser: "******"spSite");

            log.Info("spSite: " + adminUser);
            System.Security.SecureString secureString = new System.Security.SecureString();
            foreach (char ch in adminPassword)
            {
                secureString.AppendChar(ch);
            }
            string sitesRequest = Environment.GetEnvironmentVariable("listName");

            log.Info("listName: " + sitesRequest);
            Dictionary <string, string> siteInfo = new Dictionary <string, string>();

            OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
            string camlQuery =
                "<View>" +
                "<Query>" +
                "<Where>" +
                "<Eq>" +
                "<FieldRef Name='Status' />" +
                "<Value Type='Choice'>Approved</Value>" +
                "</Eq>" +
                "</Where>" +
                "</Query>" +
                "<RowLimit>1</RowLimit>" +
                "</View>";
            CamlQuery cq = new CamlQuery();

            cq.ViewXml = camlQuery;
            using (var context = authManager.GetSharePointOnlineAuthenticatedContextTenant(spSite, adminUser, secureString))
            {
                List list = context.Web.Lists.GetByTitle(sitesRequest);
                ListItemCollection lic = list.GetItems(cq);
                context.Load(lic);
                context.ExecuteQuery();
                foreach (ListItem item in lic)
                {
                    siteInfo.Add("Id", item["ID"].ToString());
                    siteInfo.Add("title", item["Title"].ToString());
                    siteInfo.Add("owner", item["Owner"].ToString());
                    siteInfo.Add("description", item["Description"] == null ? "" : item["Description"].ToString());
                    siteInfo.Add("type", item["SiteType"].ToString());
                    siteInfo.Add("alias", item["Alias"].ToString());
                    log.Info("Processing: " + item["Title"].ToString());
                    var siteType = siteInfo["type"];
                    switch (siteType.ToLower())
                    {
                    case "communicationsite":
                        var ctx = context.CreateSiteAsync(new CommunicationSiteCollectionCreationInformation
                        {
                            Title       = siteInfo["title"].ToString(),
                            Owner       = siteInfo["owner"].ToString(),
                            Lcid        = 1033,
                            Description = siteInfo["description"].ToString(),
                            Url         = spSite + "/sites/" + siteInfo["alias"].ToString(),
                        }).GetAwaiter().GetResult();
                        // Add OWner
                        User user = ctx.Web.EnsureUser(siteInfo["owner"].ToString());
                        ctx.Web.Context.Load(user);
                        ctx.Web.Context.ExecuteQueryRetry();
                        ctx.Web.AssociatedOwnerGroup.Users.AddUser(user);
                        ctx.Web.AssociatedOwnerGroup.Update();
                        ctx.Web.Context.ExecuteQueryRetry();
                        break;

                    case "teamsite":
                        var ctxTeamsite = context.CreateSiteAsync(new TeamSiteCollectionCreationInformation
                        {
                            DisplayName = siteInfo["title"].ToString(),
                            Description = siteInfo["description"].ToString(),
                            Alias       = siteInfo["alias"].ToString(),
                            IsPublic    = false,
                        }).GetAwaiter().GetResult();
                        siteUrl = ctxTeamsite.Url;
                        // Add OWner
                        User userTeamSite = ctxTeamsite.Web.EnsureUser(siteInfo["owner"].ToString());
                        ctxTeamsite.Web.Context.Load(userTeamSite);
                        ctxTeamsite.Web.Context.ExecuteQueryRetry();
                        ctxTeamsite.Web.AssociatedOwnerGroup.Users.AddUser(userTeamSite);
                        ctxTeamsite.Web.AssociatedOwnerGroup.Update();
                        ctxTeamsite.Web.Context.ExecuteQueryRetry();
                        break;

                    case "teams":
                        string token = Graph.getToken();
                        log.Info("Access Token: " + token);
                        string userId  = string.Empty;
                        string groupId = string.Empty;
                        if (string.IsNullOrEmpty(token) == false)
                        {
                            userId = Graph.getUser(token, siteInfo["owner"].ToString());
                            log.Info("userId: " + userId);
                        }
                        if (string.IsNullOrEmpty(userId) == false)
                        {
                            string dataPost =
                                "{ 'displayName': '" + siteInfo["title"].ToString() + "', 'groupTypes': ['Unified'], 'mailEnabled': true, 'mailNickname': '" + siteInfo["alias"].ToString().Replace("\r\n", "").Replace(" ", "") + "', 'securityEnabled': false, '*****@*****.**': ['https://graph.microsoft.com/v1.0/users/" + userId + "'], 'visibility': 'Private' }";
                            groupId = Graph.createUnifiedGroup(token, dataPost);
                            log.Info("groupId: " + groupId);
                            log.Info("Creating team......");
                            string teamData = "{ \"memberSettings\": { \"allowCreateUpdateChannels\": true }, \"messagingSettings\": { \"allowUserEditMessages\": true, \"allowUserDeleteMessages\": true }, \"funSettings\": { \"allowGiphy\": true, \"giphyContentRating\": \"strict\" } }";
                            string team     = Graph.createTeamFromUnifiedGroup(token, teamData, groupId);
                            log.Info("team: " + team);
                            //Graph.addOwnerToUnifiedGroup(token, groupId, userId);
                            //removeOwnerToUnifiedGroup(token, groupId, userId);
                        }
                        siteUrl = siteInfo["title"].ToString();
                        log.Info("Teams ready: " + siteUrl);
                        break;
                    }
                    // When the site or Teams has been created the status of the list item will change in ready
                    if (siteUrl != string.Empty)
                    {
                        item["Status"] = "Ready";
                        item.Update();

                        context.ExecuteQuery();
                    }
                }
            }

            return(siteUrl == null
                ? req.CreateResponse(HttpStatusCode.InternalServerError, "Something went wrong!")
                : req.CreateResponse(HttpStatusCode.OK, siteUrl));
        }
        internal static SPOnlineConnection InstantiateAdfsConnection(Uri url, PSCredential credentials, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false)
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();

            var networkCredentials = credentials.GetNetworkCredential();

            string adfsHost;
            string adfsRelyingParty;
            GetAdfsConfigurationFromTargetUri(url, out adfsHost, out adfsRelyingParty);

            if (string.IsNullOrEmpty(adfsHost) || string.IsNullOrEmpty(adfsRelyingParty))
            {
                throw new Exception("Cannot retrieve ADFS settings.");
            }

            var context = PnPClientContext.ConvertFrom(authManager.GetADFSUserNameMixedAuthenticatedContext(url.ToString(), networkCredentials.UserName, networkCredentials.Password, networkCredentials.Domain, adfsHost, adfsRelyingParty), retryCount, retryWait * 1000);

            context.RetryCount = retryCount;
            context.Delay = retryWait * 1000;

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout = requestTimeout;
#if !ONPREMISES
            context.DisableReturnValueCache = true;
#elif SP2016
            context.DisableReturnValueCache = true;
#endif

            var connectionType = ConnectionType.OnPrem;

            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag);
        }
Exemplo n.º 42
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function BetterCopyFunction processed a request.");

            string errorMsg = "";

            try
            {
                dynamic data = await req.Content.ReadAsAsync <object>();

                string targetUrl     = data?.targetUrl;
                string sourceUrl     = data?.sourceUrl;
                Uri    targetSiteUri = new Uri(targetUrl);
                Uri    sourceSiteUri = new Uri(sourceUrl);
                string pageLayout    = data?.pageLayout;

                string fileName = ""; // we get this from the source item

                int sourceId;

                try
                {
                    string strSourceId = data?.sourceId;
                    sourceId = int.Parse(strSourceId);
                }
                catch (Exception)
                {
                    log.Error("Setting up variables failed.");
                    errorMsg += "Setting up variables failed.";
                    throw;
                }

                log.Info("Got the variables! Now connecting to SharePoint...");

                // Get the realm for the URL
                var realm = TokenHelper.GetRealmFromTargetUrl(targetSiteUri);
                // parse tenant admin url from the sourceUrl (there's probably a cuter way to do this but this is simple :])
                string tenantAdminUrl = sourceUrl.Substring(0, sourceUrl.IndexOf(".com") + 4).TrimEnd(new[] { '/' }).Replace(".sharepoint", "-admin.sharepoint");
                // parse tenant url from the admin url
                var tenantUrl        = tenantAdminUrl.Substring(0, tenantAdminUrl.IndexOf(".com") + 4).Replace("-admin", "");
                AzureEnvironment env = TokenHelper.getAzureEnvironment(tenantAdminUrl);

                using (var ctx_target = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(targetSiteUri.ToString(), clientId, clientSecret, env))
                {
                    log.Info("Target site context built successfully!");

                    using (var ctx_source = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(sourceSiteUri.ToString(), clientId, clientSecret, env))
                    {
                        log.Info("Source site context built successfully!");

                        var exists = ctx_target.WebExistsFullUrl(targetUrl);

                        string targetWebUrl = targetUrl.Replace(tenantUrl, "");
                        var    targetWeb    = ctx_target.Site.OpenWeb(targetWebUrl);

                        ctx_target.Load(ctx_target.Site);
                        ctx_target.Load(targetWeb);
                        ctx_target.ExecuteQuery();

                        var sourceWeb = ctx_source.Site.OpenWeb(sourceUrl.Replace(tenantUrl, ""));
                        ctx_source.Load(sourceWeb);
                        ctx_source.ExecuteQuery();

                        log.Info("SharePoint connection fine! Connected to: " + targetWeb.Title);

                        pageLayout = ctx_target.Site.Url + pageLayout.Substring(pageLayout.IndexOf("/_catalogs"));

                        var sourceList = sourceWeb.Lists.GetByTitle("Pages");
                        ctx_source.Load(sourceList);
                        ctx_source.ExecuteQuery();

                        var targetList = targetWeb.Lists.GetByTitle("Pages");
                        ctx_target.Load(targetList);
                        ctx_target.ExecuteQuery();

                        log.Info("... and: " + targetList.Title + " " + targetList.ItemCount);

                        string publishingPageContent = "";

                        ListItem sourceItem = null;
                        try
                        {
                            sourceItem = sourceList.GetItemById(sourceId);

                            if (sourceItem == null)
                            {
                                string    qs    = String.Format("<View><Query><Where><Eq><FieldRef Name=\"ID\"></FieldRef><Value Type=\"Number\">{0}</Value></Eq></Where></Query></View>", sourceId);
                                CamlQuery query = new CamlQuery();
                                query.ViewXml = qs;
                                var items = sourceList.GetItems(query);

                                ctx_source.Load(items);
                                ctx_source.ExecuteQuery();

                                sourceItem = items.First();
                            }
                        }
                        catch (Exception ex)
                        {
                            sourceItem = sourceWeb.GetListItem("/Pages/Forms/DispForm.aspx?ID=" + sourceId);
                            errorMsg  += ex.Message + " ";
                        }
                        finally
                        {
                            ctx_source.Load(sourceItem);
                            ctx_source.Load(sourceItem.File);
                            ctx_source.Load(sourceItem, r => r.Client_Title, r => r.Properties);
                            ctx_source.ExecuteQueryRetry();

                            log.Info("Got source item! Title: " + sourceItem.Client_Title);

                            if (sourceItem["PublishingPageContent"] != null)
                            {
                                publishingPageContent = sourceItem["PublishingPageContent"].ToString();
                            }
                        }

                        fileName = sourceItem.File.Name;

                        // at this point, we've fetched all the info we needed. On to getting the target item, and then updating the fields there.
                        ListItem targetItem = null;
                        try
                        {
                            targetItem = targetList.GetItemById(sourceId);

                            if (targetItem == null)
                            {
                                string    qs1    = String.Format("<View><Query><Where><Eq><FieldRef Name=\"ID\"></FieldRef><Value Type=\"Number\">{0}</Value></Eq></Where></Query></View>", sourceId);
                                CamlQuery query1 = new CamlQuery();
                                query1.ViewXml = qs1;
                                var items1 = targetList.GetItems(query1);

                                ctx_target.Load(items1);
                                ctx_target.ExecuteQuery();

                                targetItem = items1.First();
                            }
                        }
                        catch (Exception ex)
                        {
                            log.Warning("Getting source item via conventional ways failed. Trying the unorthodox ones...");

                            targetItem = targetWeb.GetListItem("/Pages/Forms/DispForm.aspx?ID=" + sourceId);

                            var items = targetList.GetItems(CamlQuery.CreateAllItemsQuery());
                            ctx_target.Load(items);
                            ctx_target.ExecuteQueryRetry();

                            for (int i = 0; i < items.Count; i++)
                            {
                                if (items[i].Id == sourceId)
                                {
                                    targetItem = items[i];
                                }
                            }
                        }
                        finally
                        {
                            try
                            {
                                string str = "Published automatically by an Azure Function (BetterCopyFunction).";
                                targetItem.File.CheckIn(str, CheckinType.MajorCheckIn);
                                targetItem.File.Publish(str);

                                ctx_target.Load(targetItem);

                                ctx_target.ExecuteQueryRetry();
                            }
                            catch (Exception ex)
                            {
                                log.Info("Error: " + ex.Message);
                            }

                            ctx_target.Load(targetItem);
                            ctx_target.Load(targetItem, r => r.Client_Title, r => r.Properties);
                            ctx_target.ExecuteQueryRetry();
                        }

                        log.Info("Target item title: " + targetItem.Client_Title);

                        try
                        {
                            targetItem["PublishingPageLayout"]  = pageLayout;
                            targetItem["PublishingPageContent"] = publishingPageContent;
                            targetItem.SystemUpdate();

                            ctx_target.ExecuteQuery();
                        }
                        catch (Exception ex)
                        {
                            log.Warning("There was an error in saving target item values. Values were: " + pageLayout + " " + publishingPageContent);
                            log.Warning("Error was: " + ex.Message);
                        }
                        finally
                        {
                            log.Info("Target item updated!");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errorMsg += ex.Message;
                errorMsg += "\r\n " + ex.StackTrace;

                throw;
            }

            return(String.IsNullOrEmpty(errorMsg)
                ? req.CreateResponse(HttpStatusCode.OK, "Function run was a success.")
                : req.CreateResponse(HttpStatusCode.InternalServerError, errorMsg));
        }
Exemplo n.º 43
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");


            // string appOnlyId = ConfigurationManager.AppSettings["AppOnlyID"];
            // string appOnlySecret = ConfigurationManager.AppSettings["AppOnlySecret"];

            // parse query parameter
            log.LogInformation("C# HTTP trigger function processed a request.");

            // // parse query parameter
            string title           = req.Query["title"];
            string nameFR          = req.Query["spacenamefr"];
            string owner1          = req.Query["owner1"];
            string owner2          = req.Query["owner2"];
            string owner3          = req.Query["owner3"];
            string description     = req.Query["description"];
            string template        = req.Query["template"];
            string descriptionFr   = req.Query["descriptionFr"];
            string business        = req.Query["business"];
            string requester_name  = req.Query["requester_name"];
            string requester_email = req.Query["requester_email"];

            // // Get request body
            //dynamic data = await req.Content.ReadAsAsync<object>();
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            dynamic data = JsonConvert.DeserializeObject(requestBody);

            // // Set name to query string or body data
            title           = title ?? data?.name.title;
            nameFR          = nameFR ?? data?.name.nameFR;
            owner1          = owner1 ?? data?.name.owner1;
            owner2          = owner2 ?? data?.name.owner2;
            owner3          = owner3 ?? data?.name.owner3;
            description     = description ?? data?.name.description;
            template        = template ?? data?.name.template;
            descriptionFr   = descriptionFr ?? data?.name.descriptionFr;
            business        = business ?? data?.name.business;
            requester_name  = requester_name ?? data?.name.requester_name;
            requester_email = requester_email ?? data?.name.requester_email;

            log.LogInformation("get info" + title);

            //  string name = req.Query["name"];

            // string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            // dynamic data = JsonConvert.DeserializeObject(requestBody);
            //name = name ?? data?.name;


            //using (var cc = new AuthenticationManager().GetAzureADAppOnlyAuthenticatedContext(siteUrl, "1d4139b1-fd16-4f06-8ac6-7b9ac7b58864", "tbssctdev.onmicrosoft.com", @"C:\test.pfx", "password123"))

            using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAzureADAppOnlyAuthenticatedContext(siteURL, "", "", KeyVaultAccess.GetKeyVaultCertificate("", "")))
            {
                cc.Load(cc.Web, p => p.Title);
                cc.Load(cc.Web, p => p.Description);

                cc.ExecuteQuery();
                Console.WriteLine(cc.Web.Title);
                Console.WriteLine(cc.Web.Description);



                //ClientContext ctx = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(siteURL, appOnlyId, appOnlySecret);
                log.LogInformation("get context");

                Web  web  = cc.Web;
                List list = cc.Web.Lists.GetByTitle("Space Requests");
                log.LogInformation("get list");

                ListItemCreationInformation oListItemCreationInformation = new ListItemCreationInformation();
                ListItem oItem = list.AddItem(oListItemCreationInformation);

                User userTest  = web.EnsureUser(owner1);
                User userTest2 = web.EnsureUser(owner2);


                cc.Load(userTest);
                cc.ExecuteQuery();
                log.LogInformation("get user");
                owner1 = userTest.Id.ToString() + ";#" + userTest.LoginName.ToString();
                cc.Load(userTest2);
                cc.ExecuteQuery();
                owner2 = userTest2.Id.ToString() + ";#" + userTest2.LoginName.ToString();
                if (owner3 != "")
                {
                    User userTest3 = web.EnsureUser(owner3);
                    cc.Load(userTest3);
                    cc.ExecuteQuery();
                    owner3 = userTest3.Id.ToString() + ";#" + userTest3.LoginName.ToString();
                }

                oItem["Space_x0020_Name"]          = title;
                oItem["Space_x0020_Name_x0020_FR"] = nameFR;
                oItem["Owner1"] = owner1 + ";#" + owner2 + ";#" + owner3;
                oItem["Space_x0020_Description_x0020__x"]  = description;
                oItem["Template_x0020_Title"]              = template;
                oItem["Space_x0020_Description_x0020__x0"] = descriptionFr;
                oItem["Team_x0020_Purpose_x0020_and_x00"]  = business;
                oItem["Business_x0020_Justification"]      = business;
                oItem["Requester_x0020_Name"]              = requester_name;
                oItem["Requester_x0020_email"]             = requester_email;
                oItem["_Status"] = "Submitted";
                oItem.Update();
                cc.ExecuteQuery();

                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = string.Format(@"
                <View>
                    <Query>
                        <Where>
                            <Eq>
                                <FieldRef Name='Space_x0020_Name' />
                                <Value Type='Text'>{0}</Value>
                            </Eq>
                        </Where>
                    </Query>
                    <ViewFields>
                        <FieldRef Name='ID'/>
                        <FieldRef Name='Space_x0020_Name'/>
                    </ViewFields>
                    <RowLimit>1</RowLimit>
                </View>", title);

                ListItemCollection collListItemID = list.GetItems(camlQuery);
                cc.Load(collListItemID);
                cc.ExecuteQuery();

                int requestID = 0;

                foreach (ListItem oListItem in collListItemID)
                {
                    log.LogInformation(oListItem["Space_x0020_Name"].ToString());
                    requestID = oListItem.Id;
                }
                ListItem collListItem = list.GetItemById(requestID);
                // changes some fields
                collListItem["SharePoint_x0020_Site_x0020_URL"] = "https://.sharepoint.com/teams/1000" + requestID;
                collListItem.Update();
                // executes the update of the list item on SharePoint
                cc.ExecuteQuery();

                //req.CreateResponse(HttpStatusCode.InternalServerError, "Create item successfully ");

                //  }
                //return null;

                string responseMessage = "Create item successfully ";

                return(new OkObjectResult(responseMessage));
            }
        }
Exemplo n.º 44
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            string message = "";

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

            string description = "";

            // Get request body
            dynamic data = await req.Content.ReadAsAsync <object>();

            string id = data.ID;

            log.Info("Document id: " + id);
            message += "Document id: " + id;

            OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
            try
            {
                // Connects to SharePoint online site
                using (var ctx = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
                {
                    // List Name input
                    // Retrieves list object using title
                    List list = ctx.Site.RootWeb.GetListByTitle(listName);
                    if (list != null)
                    {
                        // Returns required result
                        ListItem li = list.GetItemById(id);

                        ctx.Load(li);
                        ctx.Load(li.File);
                        ctx.ExecuteQuery();

                        ctx.ExecuteQuery();

                        // We CAN extract text out of most documents with the library, but for this demo I'm limiting our options to these 2 that I know to be working :)
                        if (li.File.Name.IndexOf(".pdf") >= 0 || li.File.Name.IndexOf(".doc") >= 0)
                        {
                            li.File.OpenBinaryStream();

                            ctx.Load(li.File);
                            ctx.ExecuteQuery();

                            log.Info("It was a valid file! Continuing into handling...");


                            try
                            {
                                log.Info("Got a file! Name: " + li.File.Name);


                                var fileRef  = li.File.ServerRelativeUrl;
                                var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileRef);
                                fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileRef);

                                using (var ms = new MemoryStream())
                                {
                                    log.Info("Extracting text..");

                                    fileInfo.Stream.CopyTo(ms);
                                    byte[] fileContents = ms.ToArray();

                                    var    extractor        = new TikaOnDotNet.TextExtraction.TextExtractor();
                                    var    extractionResult = extractor.Extract(fileContents);
                                    string text             = extractionResult.Text;

                                    List <MultiLanguageInput> analyzable = FormatAnalyzableText(ref text);

                                    log.Info("Formed altogether " + analyzable.Count + " sentences to analyze!");

                                    int snippetEnd = 500 < text.Length ? 500 : text.Length;
                                    log.Info("Extracted text! First few rows here.. \r\n " + text.Substring(0, snippetEnd));


                                    RunTextAnalysis(ref keyPhrases, analyzable, log);
                                }

                                log.Info("Found " + keyPhrases.Count + " key phrases! First 20 are here: ");
                                foreach (var kp in keyPhrases.Take(20))
                                {
                                    log.Info(kp);
                                }


                                try
                                {
                                    log.Info("Saving to SharePoint..");
                                    TextInfo ti = new CultureInfo("en-US", false).TextInfo;

                                    li["Title"] = ti.ToTitleCase(li.File.Name);

                                    // then write the most important keyphrases back
                                    foreach (var s in keyPhrases.Take(keywordCount))
                                    {
                                        description += s + "\r\n";
                                    }

                                    li.Update();

                                    try
                                    {
                                        ctx.Load(list.Fields);
                                        ctx.ExecuteQuery();

                                        log.Info("Updating Managed Metadata...");

                                        var fieldnames = new string[] { "Keywords" };
                                        var field      = list.GetFields(fieldnames).First();

                                        // setting managed metadata
                                        log.Info("Updating keywords to taxonomy! Taking: " + keywordCount);
                                        UpdateManagedMetadata(keyPhrases.Take(keywordCount).ToArray(), log, ctx, li, field, wantedGuid);

                                        ctx.ExecuteQuery();
                                    }
                                    catch (Exception ex)
                                    {
                                        log.Error(ex.Message);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    log.Error(ex.Message);
                                }
                            }
                            catch (Exception ex)
                            {
                                log.Error(ex.Message);
                                return(req.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
                            }
                        }
                        else
                        {
                            return(req.CreateResponse(HttpStatusCode.OK, "File was not pdf or doc"));
                        }

                        return(req.CreateResponse(HttpStatusCode.OK, list.Id));
                    }
                    else
                    {
                        log.Info("List is not available on the site");
                        return(req.CreateResponse(HttpStatusCode.NotFound, "List is not available on the site"));
                    }
                }
            }
            catch (Exception ex)
            {
                log.Info("Error Message: " + ex.Message);
                message += "Error Message: " + ex.Message;
            }

            log.Info("");

            var returnable = JsonConvert.SerializeObject(keyPhrases);

            return(keyPhrases.Count <= 0
                ? req.CreateResponse(HttpStatusCode.BadRequest, "Couldn't analyze file. Please verify the POST payload!")
                : req.CreateResponse(HttpStatusCode.OK, returnable));
        }
Exemplo n.º 45
0
        static void Main(string[] args)
        {
            // Office 365 Multi-tenant sample
            ClientContext cc = new AuthenticationManager().GetSharePointOnlineAuthenticatedContextTenant("https://bertonline.sharepoint.com/sites/130020", "*****@*****.**", GetPassWord());
            
            //if (!cc.Site.IsInPlaceRecordsManagementActive())
            //{
            //    cc.Site.EnableSiteForInPlaceRecordsManagement();
            //}
            
            FileStream ostrm;
            StreamWriter writer = null;
            TextWriter oldOut = Console.Out;
            string fileName = @"c:\temp\recordsmanagement.txt";

            //Redirect console to file if needed
            if (!toConsole)
            {
                try
                {
                    if (System.IO.File.Exists(fileName))
                    {
                        System.IO.File.Delete(fileName);
                    }
                    ostrm = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
                    writer = new StreamWriter(ostrm);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Cannot open recordsmanagement.txt for writing");
                    Console.WriteLine(e.Message);
                    return;
                }
                Console.SetOut(writer);
            }

            List ecm = cc.Web.GetListByTitle("Documents");

            //List ecm = cc.Web.GetListByTitle("ECMTest");
            cc.Load(ecm.RootFolder, p => p.Properties);
            cc.Load(ecm.EventReceivers);
            cc.Load(cc.Web, t => t.AllProperties);
            cc.ExecuteQuery();

            Console.WriteLine("Web properties:");
            foreach(var prop in cc.Web.AllProperties.FieldValues)
            {
                Console.WriteLine(String.Format("{0} : {1}", prop.Key, prop.Value != null ? prop.Value.ToString() : ""));
            }

            Console.WriteLine("=======================================================");
            Console.WriteLine("Rootfolder props = list props:");
            foreach(var prop in ecm.RootFolder.Properties.FieldValues)
            {
                Console.WriteLine(String.Format("{0} : {1}", prop.Key, prop.Value != null ? prop.Value.ToString() : ""));
            }
            Console.WriteLine("=======================================================");
            Console.WriteLine("List event receivers:");
            foreach (var eventReceiver in ecm.EventReceivers)
            {
                Console.WriteLine(String.Format("Name: {0}", eventReceiver.ReceiverName));
                Console.WriteLine(String.Format("Type: {0}", eventReceiver.EventType));
                Console.WriteLine(String.Format("Assembly: {0}", eventReceiver.ReceiverAssembly));
                Console.WriteLine(String.Format("Class: {0}", eventReceiver.ReceiverClass));
                Console.WriteLine(String.Format("Url: {0}", eventReceiver.ReceiverUrl));
                Console.WriteLine(String.Format("Sequence: {0}", eventReceiver.SequenceNumber));
                Console.WriteLine(String.Format("Synchronisation: {0}", eventReceiver.Synchronization));
            }

            Console.WriteLine("=======================================================");
            Console.WriteLine("List items:");
            CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
            ListItemCollection items = ecm.GetItems(query);

            cc.Load(items);
            cc.ExecuteQuery();
            foreach (ListItem listItem in items)
            {
                foreach (var field in listItem.FieldValues)
                {
                    Console.WriteLine("{0} : {1}", field.Key, field.Value);
                }
                Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++++++++");
            }

            if (!toConsole)
            {
                writer.Flush();
                Console.Out.Close();
                Console.SetOut(oldOut);
            }
            Console.WriteLine("Press enter to continue...");
            Console.ReadLine();

        }
 internal static SPOnlineConnection InitiateAzureADAppOnlyConnection(Uri url, string clientId, string tenant, string certificatePath, SecureString certificatePassword, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false)
 {
     var authManager = new OfficeDevPnP.Core.AuthenticationManager();
     var context = PnPClientContext.ConvertFrom(authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificatePath, certificatePassword), retryCount, retryWait * 1000);
     var connectionType = ConnectionType.OnPrem;
     if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
     {
         connectionType = ConnectionType.O365;
     }
     if (skipAdminCheck == false)
     {
         if (IsTenantAdminSite(context))
         {
             connectionType = ConnectionType.TenantAdmin;
         }
     }
     return new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag);
 }
Exemplo n.º 47
0
        /// <summary>
        /// Processes a message from the oauth queue
        /// </summary>
        /// <param name="message">Message retrieved from the queue</param>
        /// <returns>true if ok</returns>
        private bool ProcessMessageOAuth(string message)
        {
            bool processed = true;

            // first part contains the title, second the site to apply the title on
            string[] messageParts = message.Split(new string[] { "|" }, StringSplitOptions.None);
            if (messageParts[0].Length > 0)
            {
                ClientContext cc = new AuthenticationManager().GetAppOnlyAuthenticatedContext(messageParts[1],
                                                                                              RoleEnvironment.GetConfigurationSettingValue("Realm"),
                                                                                              RoleEnvironment.GetConfigurationSettingValue("AppId"),
                                                                                              EncryptionUtility.Decrypt(RoleEnvironment.GetConfigurationSettingValue("AppSecret"),RoleEnvironment.GetConfigurationSettingValue("ThumbPrint")));
                //Update the site title
                cc.Web.Title = messageParts[0];
                cc.Web.Update();
                cc.ExecuteQuery();
            }
            return processed;
        }