Ejemplo n.º 1
0
        public static bool ValidateSubSiteXml(string siteUrl, string domain, string userName, SecureString pwdS, string fileName)
        {
            if (!fileName.ToLower().Contains("subsite"))
            {
                return(true);
            }

            ClientContext ctx;

            if (string.IsNullOrEmpty(domain))
            {
                ctx = new OfficeDevPnP.Core.AuthenticationManager().GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, pwdS);
            }
            else
            {
                ctx = new OfficeDevPnP.Core.AuthenticationManager().GetNetworkCredentialAuthenticatedContext(siteUrl, userName, pwdS, domain);
            }

            // Just to output the site details
            Web web = ctx.Web;

            ctx.Load(web, w => w.Title, w => w.Id);
            var site = ctx.Site;

            ctx.Load(site, s => s.RootWeb, s => s.RootWeb.Id);
            ctx.ExecuteQueryRetry();
            if (ctx.Web.Id == ctx.Site.RootWeb.Id)
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 2
0
        public static void AddTaxonomyEntry()
        {
            try
            {
                OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();

                string siteUrl  = "https://sppalsmvp.sharepoint.com/sites/DeveloperSite";
                string userName = "******";
                string password = "******";

                using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
                {
                    Web web = ctx.Web;
                    ctx.Load(web);
                    ctx.Load(web.Lists);
                    ctx.ExecuteQueryRetry();
                    List list = web.Lists.GetByTitle("List1");
                    ctx.Load(list);
                    ctx.ExecuteQueryRetry();

                    var tags = new string[] { "Term1", "Term2" };

                    var tagsString = EnsureTerms(tags, siteUrl, list.Id, "MyTaxonomyField", ctx);
                }
            }
            catch (Exception ex) { }
        }
Ejemplo n.º 3
0
        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)
        {
            OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
            if (realm == null)
            {
                realm = GetRealmFromTargetUrl(url);
            }

            var context = authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret);
            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout = requestTimeout;

            var connectionType = SPOnlineConnection.ConnectionTypes.OnPrem;
            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = SPOnlineConnection.ConnectionTypes.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = SPOnlineConnection.ConnectionTypes.TenantAdmin;
                }
            }
            return new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null);
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            var mode = GetMode(args);

            try
            {
                //check to ensure there's at least one argument
                if (mode == Mode.invalid || args.Length > 2)
                {
                    DisplayUsage();
                    return;
                }

                if (mode == Mode.debug)
                {
                    //if we're in debug, to to the project directory and read the Branding files and settings.xml from there
                    var dir = System.IO.Directory.GetCurrentDirectory();
                    dir = dir.Substring(0, dir.IndexOf("\\bin"));
                    System.IO.Directory.SetCurrentDirectory(dir);
                }



                //code used to get the application to work for SP ADFS
                var siteUrl = String.Concat(GetConfigurationValue("url").TrimEnd(_TrimChars), "/", GetConfigurationValue("site").TrimEnd(_TrimChars));
                if (args.Length > 1 && args[1].Equals("online", StringComparison.OrdinalIgnoreCase))
                {
                    OfficeDevPnP.Core.AuthenticationManager am = new OfficeDevPnP.Core.AuthenticationManager();
                    using (ClientContext clientContext = am.GetADFSUserNameMixedAuthenticatedContext(siteUrl, GetConfigurationValue("username"), GetConfigurationValue("password"),
                                                                                                     GetConfigurationValue("domain"), GetConfigurationValue("adfsserver"), GetConfigurationValue("adfsurn")))
                    {
                        Execute(siteUrl, clientContext, mode);
                    }
                }
                else
                {
                    using (ClientContext clientContext = new ClientContext(siteUrl))
                    {
                        clientContext.Credentials = new NetworkCredential(GetConfigurationValue("username"), GetConfigurationValue("password"), GetConfigurationValue("domain"));
                        Execute(siteUrl, clientContext, mode);
                    }
                }

                Console.WriteLine("Done!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Critical Error: {0}", ex.Message);
            }

            if (mode != Mode.debug)
            {
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("Closing in 2 seconds...");
                System.Threading.Thread.Sleep(2000);
            }
        }
        private static async Task <int> ApplyProvisioningTemplate(string url, X509Certificate2 cert, ProvisioningTemplate template, TraceWriter log)
        {
            OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
            using (ClientContext targetCtx = authMgr.GetAzureADAppOnlyAuthenticatedContext(url, CLIENT_ID, TENANT, cert))
            {
                // Disable request timeout
                targetCtx.RequestTimeout = Timeout.Infinite;

                // Make sure our context is valid
                targetCtx.Load(targetCtx.Web, w => w.Url, w => w.Title);
                await targetCtx.ExecuteQueryRetryAsync();

                log.Info($"Connected to targetUrl: {targetCtx.Web.Url}");

                // Apply template, clear existing nav nodes
                ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation();
                ptai.ClearNavigation  = true;
                ptai.ProgressDelegate = delegate(String message, Int32 progress, Int32 total)
                {
                    log.Info(string.Format("APPLY: {0:00}/{1:00} - {2}", progress, total, message));
                };

                log.Info($"Beginning applying PnP template");
                targetCtx.Web.ApplyProvisioningTemplate(template, ptai);
                log.Info($"Finished applying PnP template");
            }
            return(await Task.FromResult(0));
        }
Ejemplo n.º 6
0
        public static ClientContext GetContext(string siteUrl)
        {
            string thumbPrint = ConfigurationManager.AppSettings["thumbPrint"];


            string tenant        = ConfigurationManager.AppSettings["tenant"];
            string applicationID = ConfigurationManager.AppSettings["applicationID"];

            X509Certificate2 cert2 = null;
            X509Store        store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            try
            {
                store.Open(OpenFlags.ReadOnly);

                var col = store.Certificates.Find(X509FindType.FindByThumbprint, thumbPrint, false);

                if (col == null || col.Count == 0)
                {
                }
                cert2 = col[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                store.Close();
            }

            OfficeDevPnP.Core.AuthenticationManager authmanager = new OfficeDevPnP.Core.AuthenticationManager();

            return(authmanager.GetAzureADAppOnlyAuthenticatedContext(siteUrl, applicationID, tenant, cert2));
        }
        private static async Task <ProvisioningTemplate> GetProvisioningTemplate(string url, X509Certificate2 cert, TraceWriter log)
        {
            ProvisioningTemplate template = null;

            OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
            using (ClientContext sourceCtx = authMgr.GetAzureADAppOnlyAuthenticatedContext(url, CLIENT_ID, TENANT, cert))
            {
                // Disable request timeout
                sourceCtx.RequestTimeout = Timeout.Infinite;

                // Make sure our context is valid
                sourceCtx.Load(sourceCtx.Web, w => w.Url, w => w.Title);
                await sourceCtx.ExecuteQueryRetryAsync();

                log.Info($"Connected to sourceUrl: {sourceCtx.Web.Url}");

                // Extract template and hold in-memory
                ProvisioningTemplateCreationInformation ptci = new ProvisioningTemplateCreationInformation(sourceCtx.Web);
                ptci.ProgressDelegate = delegate(string message, Int32 progress, Int32 total)
                {
                    log.Info(string.Format("EXTRACT: {0:00}/{1:00} - {2}", progress, total, message));
                };

                log.Info($"Beginning PnP template extraction");
                template = sourceCtx.Web.GetProvisioningTemplate(ptci);
                log.Info($"Finished PnP template extraction");
            }
            return(await Task.FromResult(template));
        }
Ejemplo n.º 8
0
        public ClientContext CloneContext(string url)
        {
            var context = ContextCache.FirstOrDefault(c => HttpUtility.UrlEncode(c.Url) == HttpUtility.UrlEncode(url));

            if (context == null)
            {
                context = Context.Clone(url);
                try
                {
                    context.ExecuteQueryRetry();
                }
                catch (Exception ex)

                {
                    if (ex is WebException || ex is NotSupportedException)
                    {
                        // legacy auth?
                        var authManager = new OfficeDevPnP.Core.AuthenticationManager();
                        context = authManager.GetAzureADCredentialsContext(url.ToString(), CurrentConnection.PSCredential.UserName, CurrentConnection.PSCredential.Password);
                        context.ExecuteQueryRetry();
                    }
                    else
                    {
                        throw;
                    }
                }
                ContextCache.Add(context);
            }
            Context = context;
            return(context);
        }
Ejemplo n.º 9
0
        public object GetSiteUsers(string siteUrl)
        {
            List <Models.User> siteUsers = new List <Models.User>();
            string             realm     = ConfigurationManager.AppSettings["ida:Audience"];
            string             appId     = ConfigurationManager.AppSettings["ida:ClientId"];
            string             appSecret = ConfigurationManager.AppSettings["ida:AppSecret"];

            OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
            using (ClientContext context = authManager.GetAppOnlyAuthenticatedContext(siteUrl, appId, appSecret))
            {
                try
                {
                    Web web   = context.Web;
                    var users = context.LoadQuery(context.Web.SiteUsers.Where(u => u.PrincipalType == PrincipalType.User && u.UserId.NameIdIssuer == "urn:federation:microsoftonline"));
                    context.ExecuteQuery();
                    foreach (Microsoft.SharePoint.Client.User user in users)
                    {
                    }

                    return(users);
                }
                catch (Exception ex)
                {
                    return(null);
                }
            }
        }
Ejemplo n.º 10
0
        public static void ActivateSiteFeature()
        {

            OfficeDevPnP.Core.AuthenticationManager authenticationManager = new OfficeDevPnP.Core.AuthenticationManager();
            using (templateSiteClientContext = authenticationManager.GetSharePointOnlineAuthenticatedContextTenant(templateSiteUrl, userName, passWord))
            {
                var features = templateSiteClientContext.Web.Features;
                templateSiteClientContext.Load(features);
                templateSiteClientContext.ExecuteQuery();
                //Feature sitePageFeature = features.Where(f => f.DisplayName == "Site Pages").FirstOrDefault();
                //foreach (Feature getfeatureName in features)
                //{
                //    //# Set the property name to retrieve the value      
                //    getfeatureName.Retrieve("DisplayName");
                //    templateSiteClientContext.Load(getfeatureName);
                //    templateSiteClientContext.ExecuteQuery();
                //    //Console.ForegroundColor = ConsoleColor.Green;
                //    Console.WriteLine("Feature Definition ID:{0}", getfeatureName.DefinitionId, getfeatureName.DisplayName);

                //}
                //Console.WriteLine(features);
                //DefinitionId = { 15a572c6e5454d32897abab6f5846e18}
                //ff48f7e6 - 2fa1 - 428d - 9a15 - ab154762043d
                Guid guidOfFeature = new Guid("3f59333f4ce1406d8a979ecb0ff0337f");
                //Feature feature = features.Where(f => f.DefinitionId == guidOfFeature).FirstOrDefault();
                //var featureId = feature.DefinitionId;
                features.Add(guidOfFeature, true, FeatureDefinitionScope.Site);
                templateSiteClientContext.ExecuteQuery();
                //label1.Text = " Operation Completed";
            }
        }
Ejemplo n.º 11
0
        public static void AddSectionAndAddWebpart()
        {
            OfficeDevPnP.Core.AuthenticationManager authenticationManager = new OfficeDevPnP.Core.AuthenticationManager();
            using (binderSiteClientContext = authenticationManager.GetSharePointOnlineAuthenticatedContextTenant(binderSiteUrl, userName, passWord))
            {
                //Create a page or get the existing page
                string pageName = "POCSiteProvisioning.aspx";
                ClientSidePage page = ClientSidePage.Load(binderSiteClientContext, pageName);
                //var page = binderSiteClientContext.Web.AddClientSidePage("POCAppProvisioning.aspx", true);

                // Add Section 
                page.AddSection(CanvasSectionTemplate.ThreeColumn, 5);

                // get the available web parts - this collection will include OOTB and custom SPFx web parts..
                page.Save();

                // Get all the available webparts
                var components = page.AvailableClientSideComponents();

                // add the named web part..
                var webPartToAdd = components.Where(wp => wp.ComponentType == 1 && wp.Name == "HeroControl").FirstOrDefault();

                if (webPartToAdd != null)
                {
                    ClientSideWebPart clientWp = new ClientSideWebPart(webPartToAdd) { Order = 1 };

                    //Add the WebPart to the page with appropriate section
                    page.AddControl(clientWp, page.Sections[1].Columns[1]);

                }

                // the save method creates the page if one doesn't exist with that name in this site..
                page.Save();
            }
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            string samlSite = "https://www.uat.com/";

            OfficeDevPnP.Core.AuthenticationManager am = new OfficeDevPnP.Core.AuthenticationManager();
            ClientContext ctx = am.GetADFSUserNameMixedAuthenticatedContext(samlSite, "username", "password", "domain", "adfs url", "adfs identifier");

            var oList = ctx.Web.Lists.GetByTitle("BusinessBytes");

            CamlQuery camlQuery = new CamlQuery();

            camlQuery.ViewXml = "<View><RowLimit>10</RowLimit></View>";

            ListItemCollection collListItem = oList.GetItems(camlQuery);

            ctx.Load(collListItem,
                     items => items.Include(
                         item => item.Id,
                         item => item["BusinessByteTitle"],
                         item => item.HasUniqueRoleAssignments));

            ctx.ExecuteQuery();

            foreach (var item in collListItem)
            {
                Console.WriteLine("{0} - {1}", item.Id, item["BusinessByteTitle"]);
            }
        }
Ejemplo n.º 13
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 && !NETSTANDARD2_0
                    if ((ex is WebException || ex is NotSupportedException) && CurrentConnection.PSCredential != null)
                    {
                        // legacy auth?
                        var authManager = new OfficeDevPnP.Core.AuthenticationManager();
                        context = authManager.GetAzureADCredentialsContext(url.ToString(), CurrentConnection.PSCredential.UserName, CurrentConnection.PSCredential.Password);
                        context.ExecuteQueryRetry();
                    }
                    else
                    {
#endif
                    throw;
#if !ONPREMISES && !NETSTANDARD2_0
                }
#endif
                }
                ContextCache.Add(context);
            }
            Context = context;
            return(context);
        }
Ejemplo n.º 14
0
        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)
        {
            OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
            if (realm == null)
            {
                realm = GetRealmFromTargetUrl(url);
            }

            var context = authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret);

            context.ApplicationName = Properties.Resources.ApplicationName;
            context.RequestTimeout  = requestTimeout;

            var connectionType = SPOnlineConnection.ConnectionTypes.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = SPOnlineConnection.ConnectionTypes.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = SPOnlineConnection.ConnectionTypes.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString()));
        }
Ejemplo n.º 15
0
        public CalendarItemModel UpdateCalendarItem(string siteUrl, string listName, CalendarItemModel calItem)
        {
            string realm     = ConfigurationManager.AppSettings["ida:Audience"];
            string appId     = ConfigurationManager.AppSettings["ida:ClientId"];
            string appSecret = ConfigurationManager.AppSettings["ida:AppSecret"];

            OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
            using (ClientContext context = authManager.GetAppOnlyAuthenticatedContext(siteUrl, appId, appSecret))
            {
                try
                {
                    List oList = context.Web.Lists.GetByTitle(listName);
                    ListItemCreationInformation oItemCreateInfo = new ListItemCreationInformation();
                    ListItem oItem = oList.GetItemById(calItem.ID);

                    oItem["Description"] = calItem.Description;
                    oItem["Location"]    = calItem.Location;
                    oItem["EventDate"]   = calItem.EventDate;
                    oItem["EndDate"]     = calItem.EndDate;
                    oItem["Author"]      = calItem.Author;
                    oItem["Editor"]      = calItem.Editor;
                    oItem.Update();
                    context.ExecuteQuery();
                    return(calItem);
                }
                catch (Exception)
                {
                    return(null);

                    throw;
                }
            }
        }
Ejemplo n.º 16
0
        public bool DeleteCalendarItemById(string siteUrl, string listName, int itemId)
        {
            string realm     = ConfigurationManager.AppSettings["ida:Audience"];
            string appId     = ConfigurationManager.AppSettings["ida:ClientId"];
            string appSecret = ConfigurationManager.AppSettings["ida:AppSecret"];
            bool   success   = false;

            OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
            using (ClientContext context = authManager.GetAppOnlyAuthenticatedContext(siteUrl, appId, appSecret))
            {
                try
                {
                    List     oList = context.Web.Lists.GetByTitle(listName);
                    ListItem oItem = oList.GetItemById(itemId);
                    oList.DeleteObject();
                    context.ExecuteQuery();
                    success = true;
                    return(success);
                }
                catch (Exception ex)
                {
                    return(success);
                }
            }
        }
Ejemplo n.º 17
0
 public string UploadDocuments(string filePath)
 {
     try
     {
         string url      = tbSharePointURL.Text;
         string username = "******";
         string password = "******";
         string docLib   = tbDocLib.Text;
         // CreateDocumentLibrary(docLib);
         //CreateFolderinDocumentLibrary(docLib, processID);
         //string serverRelativeURL = string.Format("{0}/{1}", docLib, processID);
         OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
         string fileName = Path.GetFileName(filePath);
         using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(url, username, password))
         {
             Folder folder = ctx.Web.GetFolderByServerRelativeUrl(docLib);
             folder.UploadFile(fileName, filePath, true);
         }
         return(string.Format("{0}/{1}/{2}", url, docLib, fileName));
     }
     catch (Exception ex)
     {
         return(ex.ToString());
     }
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Get the credentials from Windows Secure Store... Good, i use that often
        /// </summary>
        public static ClientContext authenticateByWindowsSecureStore()
        {
            OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();

            NetworkCredential cred = OfficeDevPnP.Core.Utilities.CredentialManager.GetCredential(securestoreid);

            return(authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteURL, cred.UserName, cred.SecurePassword));
        }
Ejemplo n.º 19
0
        public static void Session(SPDeployOptions options, Action <ClientContext> Code)
        {
            sp_deploy_settings.EchoCurrentParams(options);

            if (!String.IsNullOrEmpty(options.ADFSUrl))
            {
                OfficeDevPnP.Core.AuthenticationManager am = new OfficeDevPnP.Core.AuthenticationManager();
                using (var clientContext = am.GetADFSUserNameMixedAuthenticatedContext(options.url, options.login, options.password, options.domain, options.ADFSUrl, options.relyingParty, 600))
                {
                    //var StartedDate = DateTime.Now;
                    clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
                    {
                        foreach (Cookie Cookie in webRequestEventArgs.WebRequestExecutor.WebRequest.CookieContainer.GetCookies(new Uri(options.url)))
                        {
                            if (Cookie.Name == "FedAuth")
                            {
                                var Expires     = Cookie.Expires;
                                var CurrentTime = DateTime.Now;
                                var DateDiff    = (Expires - CurrentTime).TotalMinutes;

                                if (DateDiff < 3)
                                {
                                    am.RefreshADFSUserNameMixedAuthenticatedContext(options.url, options.login, options.password, options.domain, options.ADFSUrl, options.relyingParty);
                                }
                            }
                        }
                    };

                    Code(clientContext);
                }
            }
            else
            {
                //using (var clientContext = new ClientContext(options.url))
                //{
                var clientContext = new ClientContext(options.url);
                if (options.Credentials != null)
                {
                    clientContext.Credentials = options.Credentials;
                }

                if ((!String.IsNullOrEmpty(options.ClientId)) && (!String.IsNullOrEmpty(options.ClientSecret)))
                {
                    TokenHelper.ClientId     = options.ClientId;
                    TokenHelper.ClientSecret = options.ClientSecret;

                    var    targetWeb     = new Uri(options.url);
                    string targetRealm   = TokenHelper.GetRealmFromTargetUrl(targetWeb);
                    var    responseToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, targetWeb.Authority, targetRealm);
                    clientContext = TokenHelper.GetClientContextWithAccessToken(targetWeb.ToString(), responseToken.AccessToken);
                }

                Code(clientContext);
                clientContext.Dispose();
                //}
            }
        }
Ejemplo n.º 20
0
        private ClientContext GetClientContextWithSharePointAppIdentity(string webUrl)
        {
            string appId     = KeyVaultUtility.GetSecret(ConfigurationManager.AppSettings["sps:spGroupRequestAppIdKeyVaultSecretName"], this.TraceWriter).Result;
            string appSecret = KeyVaultUtility.GetSecret(ConfigurationManager.AppSettings["sps:spGroupRequestAppSecretKeyVaultSecretName"], this.TraceWriter).Result;

            this.TraceWriter.Info($"Creating SP Client Context with SharePoint App Identity to {webUrl} with appId { appId }");
            ClientContext clientContext = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(webUrl, appId, appSecret);

            return(clientContext);
        }
Ejemplo n.º 21
0
        public static ClientContext GetWebApplicationClientContext(TokenCache tokenCache)
        {
            string siteUrl = GetSharePointResourceID(tokenCache);

            OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
            ClientContext context = authManager.GetAzureADWebApplicationAuthenticatedContext(
                siteUrl,
                (s) => GetTokenForApplication(s, tokenCache));

            return(context);
        }
Ejemplo n.º 22
0
        public static ClientContext GetClientContext(ContentLogRequest request)
        {
            string        locationUrl   = $"{request.SiteUrl}";
            Uri           locationUri   = new Uri(locationUrl);
            ClientContext clientContext = new ClientContext(locationUri.Scheme + Uri.SchemeDelimiter + locationUri.Host);

            OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
            clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(locationUrl, request.UserId, request.Password);
            clientContext.ExecuteQuery();
            return(clientContext);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Authenticate using App Only Credentials... Good, i use that often
        /// </summary>
        public static ClientContext authenticateByAppOnlyCredentials()
        {
            // Using App Secret
            // More Info see here
            // http://www.thesharepointguide.com/access-office-365-using-a-console-application/


            OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();

            return(authMgr.GetAppOnlyAuthenticatedContext(siteURL, appId, appSecret));
        }
Ejemplo n.º 24
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.");

            // Credentials for getting authenticated context using auth manager of OfficeDevPnP Dll
            // Since its a POC, I have used direct creds.
            // You could use other authentication modes for getting the context for PRODUCTION ENV usage.
            string siteUrl  = "https://nakkeerann.sharepoint.com/sites/teamsite";
            string userName = "******";
            string password = "******";

            OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
            // parse query parameter
            string filePath = req.GetQueryNameValuePairs()
                              .FirstOrDefault(q => string.Compare(q.Key, "filePath", true) == 0)
                              .Value;

            try
            {
                // context using auth manager
                using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
                {
                    Web web = clientContext.Site.RootWeb;
                    Microsoft.SharePoint.Client.File file = web.GetFileByUrl(filePath);

                    var    data    = file.OpenBinaryStream();
                    string content = null;
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        clientContext.Load(file);
                        clientContext.ExecuteQuery();

                        if (data != null && data.Value != null)
                        {
                            data.Value.CopyTo(memoryStream);
                            memoryStream.Seek(0, SeekOrigin.Begin);

                            // Function extracts the document content
                            content = ExtractContentFromWordDocument(memoryStream);

                            // Function responds back with extracted document content
                            return(req.CreateResponse(HttpStatusCode.OK, content));
                        }
                    }
                    // Function responds back
                    return(req.CreateResponse(HttpStatusCode.BadRequest, "Unable to process file or no content present"));
                }
            }
            catch (Exception ex)
            {
                log.Info("Error Message: " + ex.Message);
                return(req.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
Ejemplo n.º 25
0
        public static ClientContext GetTenantContext()
        {
            var authManager = new OfficeDevPnP.Core.AuthenticationManager();
            var context     = authManager.GetWebLoginClientContext(adminSiteUrl);

            //ClientContext context = new ClientContext(adminSiteUrl)
            //{
            //    Credentials = new SharePointOnlineCredentials(userName, GetSecurePassword()),
            //};

            return(context);
        }
Ejemplo n.º 26
0
        //gavdcodeend 12

        //----------------------------------------------------------------------------------------
        static ClientContext LoginPnPCore()
        {
            OfficeDevPnP.Core.AuthenticationManager pnpAuthMang =
                new OfficeDevPnP.Core.AuthenticationManager();
            ClientContext rtnContext =
                pnpAuthMang.GetSharePointOnlineAuthenticatedContextTenant
                    (ConfigurationManager.AppSettings["spUrl"],
                    ConfigurationManager.AppSettings["spUserName"],
                    ConfigurationManager.AppSettings["spUserPw"]);

            return(rtnContext);
        }
Ejemplo n.º 27
0
        public static void Run([TimerTrigger("0 0 23 * * *")] TimerInfo myTimer, TraceWriter log)
        {
            string userName              = System.Environment.GetEnvironmentVariable("SPUser", EnvironmentVariableTarget.Process);
            string password              = System.Environment.GetEnvironmentVariable("SPPwd", EnvironmentVariableTarget.Process);
            string SPRootURL             = System.Environment.GetEnvironmentVariable("SPRootURL", EnvironmentVariableTarget.Process);
            string sendReportTo          = System.Environment.GetEnvironmentVariable("SendReportTo", EnvironmentVariableTarget.Process);
            var    authenticationManager = new PnPAuthenticationManager();
            var    clientContext         = authenticationManager.GetSharePointOnlineAuthenticatedContextTenant(SPRootURL, userName, password);

            try
            {
                log.Info($"SPAudit Timer trigger function executed at: {DateTime.Now}");


                var tenant         = new Tenant(clientContext);
                var siteProperties = tenant.GetSiteProperties(0, true);
                clientContext.Load(siteProperties);
                clientContext.ExecuteQuery();

                var sbOutput = new StringBuilder();
                sbOutput.AppendLine("Audit Report Results<br/>");
                sbOutput.AppendLine("---------------------<br/>");
                foreach (SiteProperties sp in siteProperties)
                {
                    //since we're iterating through the site collections we need a new context object for each site collection
                    var siteClientContext = authenticationManager.GetSharePointOnlineAuthenticatedContextTenant(sp.Url, userName, password);

                    Web             web             = siteClientContext.Web;
                    GroupCollection groupCollection = web.SiteGroups;
                    siteClientContext.Load(groupCollection, gc => gc.Include(group => group.AllowMembersEditMembership, Group => Group.Title));
                    siteClientContext.ExecuteQuery();

                    foreach (Group group in groupCollection)
                    {
                        if (group.AllowMembersEditMembership)
                        {
                            sbOutput.AppendLine($"Site Collection = {sp.Url} . Group with Edit Membership found = {group.Title}<br/>");
                        }
                    }
                }
                sbOutput.AppendLine("---------------------<br/>");
                sbOutput.AppendLine($"Audit Report Complete at {DateTime.Now}");
                OfficeDevPnP.Core.Utilities.MailUtility.SendEmail(clientContext, new string[] { sendReportTo }, null, "SharePoint Audit Report Results", sbOutput.ToString());
                log.Info($"SPAudit completed normally at: {DateTime.Now}");
            }
            catch (Exception ex)
            {
                log.Info($"SPAudit Timer Exception at: {DateTime.Now}");
                log.Info($"Message: {ex.Message}");
                log.Info($"Stack Trace: {ex.StackTrace}");
                OfficeDevPnP.Core.Utilities.MailUtility.SendEmail(clientContext, new string[] { sendReportTo }, null, "SharePoint Audit Report Has Errored", ex.Message + ex.StackTrace);
            }
        }
Ejemplo n.º 28
0
        //gavdcodeend 02

        //gavdcodebegin 06
        static void LoginPnPCoreMFA()
        {
            string        siteUrl     = ConfigurationManager.AppSettings["spUrl"];
            var           authManager = new OfficeDevPnP.Core.AuthenticationManager();
            ClientContext mfaContext  = authManager.GetWebLoginClientContext(siteUrl);

            Web myWeb = mfaContext.Web;

            mfaContext.Load(myWeb, wb => wb.Title);
            mfaContext.ExecuteQuery();

            Console.WriteLine("Connected to the site " + myWeb.Title + " using MFA");
        }
        public static void Run([QueueTrigger("ccapplication", Connection = "")] CCApplication myQueueItem, TraceWriter log, Microsoft.Azure.WebJobs.ExecutionContext functionContext)
        {
            try
            {
                log.Info($"C# Queue trigger function processed: {myQueueItem.name}");
                string TENANT_ID         = ConfigurationManager.AppSettings["TENANT_ID"];
                string TENANT_NAME       = ConfigurationManager.AppSettings["TENANT_NAME"];
                string hostname          = $"{TENANT_NAME}.sharepoint.com";
                string TEAMS_INIT_USERID = ConfigurationManager.AppSettings["TEAMS_INIT_USERID"];
                var    displayName       = myQueueItem.name;
                var    description       = myQueueItem.description;
                var    mailNickname      = myQueueItem.mailNickname;
                var    itemId            = myQueueItem.itemId;
                var    emails            = myQueueItem.emails;
                var    requesterName     = myQueueItem.requesterName;
                var    requesterEmail    = myQueueItem.requesterEmail;

                string targetSiteUrl = $"https://{TENANT_NAME}.sharepoint.com/teams/{mailNickname}";

                var authResult  = GetOneAccessToken(TENANT_ID);
                var graphClient = GetGraphClient(authResult);

                var siteId           = GetSiteId(graphClient, log, siteRelativePath, hostname).GetAwaiter().GetResult();
                var listId           = GetSiteListId(graphClient, siteId, listTitle).GetAwaiter().GetResult();
                var siteDescriptions = GetSiteDescriptions(graphClient, siteId, listId, itemId).GetAwaiter().GetResult();
                var ownerInfo        = GetOwnerInfo(graphClient, log, emails).GetAwaiter().GetResult();

                var groupId = CreateGroupAndSite(graphClient, log, description, displayName, mailNickname).GetAwaiter().GetResult();
                log.Info($"Group id is {groupId}");
                AddLicensedUserToGroup(graphClient, log, groupId, TEAMS_INIT_USERID);

                log.Info("Wait 3 minutes for site setup.");
                Thread.Sleep(3 * 60 * 1000);

                ClientContext ctx = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(targetSiteUrl, appOnlyId, appOnlySecret);
                ApplyProvisioningTemplate(ctx, log, functionContext, siteDescriptions, TENANT_ID, ownerInfo);
                UpdateStatus(graphClient, log, itemId, siteId, listId);

                //send message to create-tems queue
                var connectionString = ConfigurationManager.AppSettings["AzureWebJobsStorage"];
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
                CloudQueueClient    queueClient    = storageAccount.CreateCloudQueueClient();
                CloudQueue          queue          = queueClient.GetQueueReference("create-teams");
                InsertMessageAsync(queue, itemId, targetSiteUrl, groupId, displayName, emails, requesterName, requesterEmail, log).GetAwaiter().GetResult();
                log.Info($"Sent request to queue successful.");
            }
            catch (Exception ex)
            {
                log.Info($"error message: {ex}");
            }
        }
        public void GetAllDeactivatingSitesAndOperate(ClientContext clientContext, string spOnlineUserLogin, string spOnlineUserPassword, string adminTenantUrl)
        {
            try
            {
                ListProcessor sdlo = new ListProcessor(clientContext, cfg, logger);
                foreach (ListItem item in sdlo.GetAllDeactivatingSites())
                {
                    //connect to service and deactivate
                    PiwikPROServiceOperations pso = new PiwikPROServiceOperations(cfg.PiwikClientID, cfg.PiwikClientSecret, cfg.PiwikServiceUrl, cfg.PiwikOldApiToken, logger);
                    string        idSite          = Convert.ToString(item[ConfigValues.PiwikPro_SiteDirectory_Column_SiteID]);
                    FieldUrlValue valueUrl        = (FieldUrlValue)(item[ConfigValues.PiwikPro_SiteDirectory_Column_Url]);
                    //idSite = pso.RemoveSiteFromPiwik(Convert.ToString(item[ConfigValues.PiwikPro_SiteDirectory_Column_SiteID]));
                    pso.ChangeNameSiteInPiwik("Inactive - " + Convert.ToString(item[ConfigValues.PiwikPro_SiteDirectory_Column_Title]), idSite);
                    if (idSite.Contains("Error: "))
                    {
                        item[ConfigValues.PiwikPro_SiteDirectory_Column_Status]   = ConfigValues.PiwikPro_SiteDirectory_Column_Status_Error;
                        item[ConfigValues.PiwikPro_SiteDirectory_Column_ErrorLog] = idSite;
                    }
                    else
                    {
                        item[ConfigValues.PiwikPro_SiteDirectory_Column_Status] = ConfigValues.PiwikPro_SiteDirectory_Column_Status_NoActive;
                    }

                    item.Update();
                    clientContext.ExecuteQueryRetry();


                    if (!string.IsNullOrEmpty(spOnlineUserLogin))
                    {
                        SetEnablePropertyBagChange(adminTenantUrl, valueUrl.Url, spOnlineUserLogin, spOnlineUserPassword, logger);

                        OfficeDevPnP.Core.AuthenticationManager authMan = new OfficeDevPnP.Core.AuthenticationManager();
                        using (ClientContext contextToPropBag = authMan.GetAppOnlyAuthenticatedContext(valueUrl.Url, spOnlineUserLogin, spOnlineUserPassword))
                        {
                            CreateOrUpdateValueInPropertyBag("false", contextToPropBag, ConfigValues.PiwikPro_PropertyBag_PiwikIsTrackingActive);
                        }
                    }
                    else
                    {
                        using (ClientContext contextToPropBag = new ClientContext(valueUrl.Url))
                        {
                            CreateOrUpdateValueInPropertyBag("false", contextToPropBag, ConfigValues.PiwikPro_PropertyBag_PiwikIsTrackingActive);
                        }
                    }
                }
            }
            catch (Exception expcc)
            {
                logger.WriteLog(Category.Unexpected, "Piwik GetAllNewSitesAndOperateOnFinish", expcc.Message);
            }
        }
Ejemplo n.º 31
0
        public CalendarItem GetCalendarItemById(string siteUrl, string listName, int itemId)
        {
            string       realm     = ConfigurationManager.AppSettings["ida:Audience"];
            string       appId     = ConfigurationManager.AppSettings["ida:ClientId"];
            string       appSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
            CalendarItem calItem   = new CalendarItem();

            OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
            using (ClientContext context = authManager.GetAppOnlyAuthenticatedContext(siteUrl, appId, appSecret))
            {
                try
                {
                    List     oList = context.Web.Lists.GetByTitle(listName);
                    ListItem oItem = oList.GetItemById(itemId);
                    context.Load(oItem);
                    context.ExecuteQuery();

                    calItem.Title       = oItem["Title"].ToString();
                    calItem.ID          = oItem.Id;
                    calItem.Description = oItem["Description"].ToString();
                    calItem.Created     = DateTime.Parse(oItem["Created"].ToString());
                    calItem.EndDate     = DateTime.Parse(oItem["EndDate"].ToString());
                    calItem.EventDate   = DateTime.Parse(oItem["EventDate"].ToString());
                    calItem.FileDirRef  = oItem["FileDirRef"].ToString();
                    calItem.FileRef     = oItem["FileRef"].ToString();
                    calItem.Location    = oItem["Location"].ToString();
                    calItem.Modified    = DateTime.Parse(oItem["Modified"].ToString());
                    FieldUserValue itemAuthor = oItem["Author"] as FieldUserValue;
                    var            author     = new Models.UserModel();
                    author.Email       = itemAuthor.Email;
                    author.LookupId    = itemAuthor.LookupId;
                    author.LookupValue = itemAuthor.LookupValue;
                    calItem.Author     = author;
                    FieldUserValue itemEditor = oItem["Editor"] as FieldUserValue;
                    var            editor     = new Models.UserModel();
                    editor.Email       = itemEditor.Email;
                    editor.LookupId    = itemEditor.LookupId;
                    editor.LookupValue = itemEditor.LookupValue;
                    calItem.Editor     = editor;
                    calItem.SiteUrl    = siteUrl;
                    calItem.ListName   = listName;
                    //calItem.Category = oItem["Category"];
                    return(calItem);
                }
                catch (Exception ex)
                {
                    return(null);
                }
            }
        }
Ejemplo n.º 32
0
 private static ClientContext CreateContext(string contextUrl, ICredentials credentials)
 {
     ClientContext context;
     if (!String.IsNullOrEmpty(Realm) && !String.IsNullOrEmpty(AppId) && !String.IsNullOrEmpty(AppSecret))
     {
         var am = new OfficeDevPnP.Core.AuthenticationManager();
         context = am.GetAppOnlyAuthenticatedContext(contextUrl, Realm, AppId, AppSecret);
     }
     else
     {
         context = new ClientContext(contextUrl);
         context.Credentials = credentials;
     }
     return context;
 }