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); }
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())); }
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); } } }
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); } } }
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; } } }
/// <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)); }
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); } }
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); } } }
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); }
public string GetCalendarTitle() { CalendarItem newCalendarItem = new CalendarItem(); string siteUrl = "https://tektaniuminc.sharepoint.com/sites/spdev"; string listName = "DemoVacationCalendar"; OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager(); using (ClientContext context = authManager.GetAppOnlyAuthenticatedContext(siteUrl, clientId, clientSecret)) { List oList = context.Web.Lists.GetByTitle(listName); context.Load(oList); context.ExecuteQuery(); return(oList.Title); } }
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); }
private void SetEnablePropertyBagChange(string adminTenantUrl, string propertyBagContextUrl, string userLogin, string userPassword, ISPLogger logger) { try { // using (ClientContext tenantCtx = new ClientContext(adminTenantUrl)) OfficeDevPnP.Core.AuthenticationManager authMan = new OfficeDevPnP.Core.AuthenticationManager(); using (ClientContext tenantCtx = authMan.GetAppOnlyAuthenticatedContext(adminTenantUrl, userLogin, userPassword)) { var tenant = new Tenant(tenantCtx); var siteProperties = tenant.GetSitePropertiesByUrl(propertyBagContextUrl, true); tenant.Context.Load(siteProperties); tenant.Context.ExecuteQueryRetry(); siteProperties.DenyAddAndCustomizePages = DenyAddAndCustomizePagesStatus.Disabled; var operation = siteProperties.Update(); tenant.Context.Load(operation, i => i.IsComplete, i => i.PollingInterval); tenant.Context.ExecuteQueryRetry(); // this is necessary, because the setting is not immediately reflected after ExecuteQuery while (!operation.IsComplete) { Thread.Sleep(operation.PollingInterval); operation.RefreshLoad(); if (!operation.IsComplete) { try { tenant.Context.ExecuteQueryRetry(); } catch (WebException webEx) { logger.WriteLog(Category.Unexpected, "Piwik Set DenyAddAndCustomizePagesStatus inside site", webEx.Message); } } } } } catch (Exception ex) { logger.WriteLog(Category.Unexpected, "Piwik Set DenyAddAndCustomizePagesStatus inside site Full method", ex.Message); } }
internal static SPIaCConnection InstantiateSPOnlineConnection(Uri url, string realm, string clientId, string clientSecret, string appDomain, string resourceUri, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false) { var authManager = new OfficeDevPnP.Core.AuthenticationManager(); if (realm == null) { realm = url.GetRealmFromTargetUrl(); } var context = authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret); context.ApplicationName = Resources.ApplicationName; 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; } } var connection = new SPIaCConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString()) { AddInCredentials = new SPOAddInKeys() { AppId = clientId, AppKey = clientSecret, Realm = realm } }; return(connection); }
public static string[] GetSharePointFile(string fileUrl, string clientSecret) { OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager(); using (ClientContext context = authManager.GetAppOnlyAuthenticatedContext(Common.GetEnvironmentVariable("SiteUrl"), Common.GetEnvironmentVariable("ClientID"), clientSecret)) { Web currentWeb = context.Web; Microsoft.SharePoint.Client.File file = currentWeb.GetFileByUrl(fileUrl); context.Load(file); context.ExecuteQuery(); ListItem item = file.ListItemAllFields; context.Load(file.ListItemAllFields); context.ExecuteQuery(); string imageField = Convert.ToString(item["OVFeatureImage"]); string articleImageUrl = string.Empty; if (!string.IsNullOrEmpty(imageField)) { //Regex to extract the src value from the img tag string imageUrl = Regex.Match(imageField, "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase).Groups[1].Value; // SharePoint image Link url articleImageUrl = Utility.GetAppSetting("SPOImageLink") + (imageUrl.Replace("/sites/intranet/PublishingImages", "")); } else { // Keep a default image articleImageUrl = Utility.GetAppSetting("SPOImageLink"); } string tnationArticleIntro = Convert.ToString(item["TNationArticleIntro"]); resultArr[0] = file.Title; resultArr[1] = articleImageUrl; resultArr[2] = tnationArticleIntro; return(resultArr); } }
static void Main(string[] args) { //https://docs.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azureacs //http://www.ktskumar.com/2016/05/authenticate-sharepoint-using-pnp-authentication-manager/ /* * https://noixno.sharepoint.com/teams/Collaborating/_layouts/15/appregnew.aspx * * Client Id: 32fb502b-37cb-4dce-bf5b-0a6e4e83a4c5 * Client Secret: 89CKbViOt4YpzK0Sx9OBIg2xAGjtCM/B6azS8v4+ZnA= * Title: SPOwithModernAuth * App Domain: www.noixno.com * Redirect URI: https://noixno.sharepoint.com/teams/Collaborating/ */ /* * https://noixno.sharepoint.com/teams/Collaborating/_layouts/15/appinv.aspx * https://noixno-admin.sharepoint.com/_layouts/15/appinv.aspx * * <AppPermissionRequests AllowAppOnlyPolicy="true"> * <AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl" /> * </AppPermissionRequests> */ string siteUrl = "https://noixno.sharepoint.com/teams/Collaborating/"; string acsAppId = "32fb502b-37cb-4dce-bf5b-0a6e4e83a4c5"; string acsSupport = "89CKbViOt4YpzK0Sx9OBIg2xAGjtCM/B6azS8v4+ZnA=";//GetString("ACS App Secret"); OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager(); using (var context = authManager.GetAppOnlyAuthenticatedContext(siteUrl, acsAppId, acsSupport)) { context.Load(context.Web); context.ExecuteQueryRetry(); System.Console.WriteLine(context.Web.Title); } System.Console.ReadLine(); }
public CalendarItem AddCalendarItem(CalendarItem calItem) { string realm = ConfigurationManager.AppSettings["ida:Audience"]; string appId = ConfigurationManager.AppSettings["ida:ClientId"]; string appSecret = ConfigurationManager.AppSettings["ida:ClientSecret"]; OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager(); var siteUrl = calItem.SiteUrl; var listName = calItem.ListName; if (listName == null || siteUrl == null) { return(null); } using (ClientContext context = authManager.GetAppOnlyAuthenticatedContext(siteUrl, appId, appSecret)) { try { List oList = context.Web.Lists.GetByTitle(listName); ListItemCreationInformation oItemCreateInfo = new ListItemCreationInformation(); ListItem oItem = oList.AddItem(oItemCreateInfo); oItem["Description"] = calItem.Description; oItem["Location"] = calItem.Location; oItem["EventDate"] = calItem.EventDate; oItem["EndDate"] = calItem.EndDate; oItem["Title"] = calItem.Title; oItem["Category"] = calItem.Category; oItem.Update(); context.ExecuteQuery(); calItem.ID = oItem.Id; return(calItem); } catch (Exception ex) { return(null); } } }
private static ClientContext InternalCreateContext(string contextUrl, SourceContextMode sourceContextMode = SourceContextMode.SPO) { string siteUrl; // Read configuration data // Trim trailing slashes siteUrl = contextUrl.TrimEnd(new[] { '/' }); if (string.IsNullOrEmpty(siteUrl)) { throw new ConfigurationErrorsException("Site Url in App.config are not set up."); } ClientContext context = new ClientContext(contextUrl); context.RequestTimeout = 1000 * 60 * 15; if (sourceContextMode == SourceContextMode.SPO) { if (!string.IsNullOrEmpty(AppSetting("SPOCredentialManagerLabel"))) { var tempCred = OfficeDevPnP.Core.Utilities.CredentialManager.GetCredential(AppSetting("SPOCredentialManagerLabel")); context.Credentials = new SharePointOnlineCredentials(tempCred.UserName, tempCred.SecurePassword); } else { if (!String.IsNullOrEmpty(AppSetting("SPOUserName")) && !String.IsNullOrEmpty(AppSetting("SPOPassword"))) { context.Credentials = new SharePointOnlineCredentials(AppSetting("SPOUserName"), GetSecureString(AppSetting("SPOPassword"))); } else if (!String.IsNullOrEmpty(AppSetting("AppId")) && !String.IsNullOrEmpty(AppSetting("AppSecret"))) { OfficeDevPnP.Core.AuthenticationManager am = new OfficeDevPnP.Core.AuthenticationManager(); context = am.GetAppOnlyAuthenticatedContext(contextUrl, AppSetting("AppId"), AppSetting("AppSecret")); } else { throw new ConfigurationErrorsException("Credentials in App.config are not set up."); } } } if (sourceContextMode == SourceContextMode.OnPremises) { if (!string.IsNullOrEmpty(AppSetting("SPOnPremCredentialManagerLabel"))) { var tempCred = OfficeDevPnP.Core.Utilities.CredentialManager.GetCredential(AppSetting("SPOnPremCredentialManagerLabel")); // username in format domain\user means we're testing in on-premises if (tempCred.UserName.IndexOf("\\") > 0) { string[] userParts = tempCred.UserName.Split('\\'); context.Credentials = new NetworkCredential(userParts[1], tempCred.SecurePassword, userParts[0]); } else { throw new ConfigurationErrorsException("Credentials in App.config are not set up for on-premises."); } } else { if (!String.IsNullOrEmpty(AppSetting("SPOnPremUserName")) && !String.IsNullOrEmpty(AppSetting("SPOnPremPassword"))) { string[] userParts = AppSetting("SPOnPremUserName").Split('\\'); context.Credentials = new NetworkCredential(userParts[1], GetSecureString(AppSetting("SPOnPremPassword")), userParts[0]); } else if (!String.IsNullOrEmpty(AppSetting("SPOnPremAppId")) && !String.IsNullOrEmpty(AppSetting("SPOnPremAppSecret"))) { OfficeDevPnP.Core.AuthenticationManager am = new OfficeDevPnP.Core.AuthenticationManager(); context = am.GetAppOnlyAuthenticatedContext(contextUrl, AppSetting("AppId"), AppSetting("AppSecret")); } else { throw new ConfigurationErrorsException("Tenant credentials in App.config are not set up."); } } } return(context); }
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; }
public IEnumerable <CalendarItem> GetCalendarItems(string siteUrl, string listName) { List <CalendarItem> calItems = new List <CalendarItem>(); DateTime todayDate = DateTime.Now; string todayString = todayDate.ToString("yyyy-MM-ddTHH:mm:ssZ"); DateTime maxDate = DateTime.Now.AddDays(30); string maxString = maxDate.ToString("yyyy-MM-ddTHH:mm:ssZ"); OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager(); try { using (ClientContext context = authManager.GetAppOnlyAuthenticatedContext(siteUrl, clientId, clientSecret)) { try { List oList = context.Web.Lists.GetByTitle(listName); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "<View><Query><Where><And><Geq><FieldRef Name='EventDate'/><Value IncludeTimeValue='False' Type='DateTime'>" + todayString + "</Value></Geq><Leq><FieldRef Name='EventDate'/><Value IncludeTimeValue='False' Type='DateTime'>" + maxString + "</Value></Leq></And></Where></Query></View>"; ListItemCollection listItems = oList.GetItems(camlQuery); context.Load(listItems); context.ExecuteQuery(); foreach (ListItem oListItem in listItems) { var fields = oListItem.FieldValues; var calItem = new CalendarItem(); foreach (var field in fields) { switch (field.Key) { case "ID": calItem.ID = Convert.ToInt32(field.Value); break; case "Title": calItem.Title = field.Value.ToString(); break; case "Description": calItem.Description = WebUtility.HtmlDecode(field.Value.ToString()); break; case "FileDirRef": calItem.FileDirRef = field.Value.ToString(); break; case "FileRef": calItem.FileRef = field.Value.ToString(); break; case "Location": calItem.Location = field.Value.ToString(); break; case "Created": calItem.Created = DateTime.Parse(field.Value.ToString()); break; case "Modified": calItem.Modified = DateTime.Parse(field.Value.ToString()); break; case "EndDate": calItem.EndDate = DateTime.Parse(field.Value.ToString()); break; case "EventDate": calItem.EventDate = DateTime.Parse(field.Value.ToString()); break; case "Author": FieldUserValue itemAuthor = field.Value as FieldUserValue; var author = new Models.UserModel(); author.Email = itemAuthor.Email; author.LookupId = itemAuthor.LookupId; author.LookupValue = itemAuthor.LookupValue; calItem.Author = author; break; case "Editor": FieldUserValue itemEditor = field.Value as FieldUserValue; var editor = new Models.UserModel(); editor.Email = itemEditor.Email; editor.LookupId = itemEditor.LookupId; editor.LookupValue = itemEditor.LookupValue; calItem.Editor = editor; break; } } calItem.ListName = listName; calItem.SiteUrl = siteUrl; calItems.Add(calItem); } return(calItems); } catch (Exception ex) { return(null); } } } catch (Exception ex1) { return(null); } }
public void GetAllNewSitesAndOperate(ClientContext clientContext, string spOnlineUserLogin, string spOnlineUserPassword, string adminTenantUrl) { try { ListProcessor sdlo = new ListProcessor(clientContext, cfg, logger); //Get all Sites with status "New" and put it to Piwik foreach (ListItem item in sdlo.GetAllNewSites()) { //connect to service and create new site PiwikPROServiceOperations pso = new PiwikPROServiceOperations(cfg.PiwikClientID, cfg.PiwikClientSecret, cfg.PiwikServiceUrl, cfg.PiwikOldApiToken, logger); FieldUrlValue valueUrl = (FieldUrlValue)(item[ConfigValues.PiwikPro_SiteDirectory_Column_Url]); string idSite = string.Empty; bool isSiteAlreadyOnPiwik = false; if (!string.IsNullOrEmpty(Convert.ToString(item[ConfigValues.PiwikPro_SiteDirectory_Column_SiteID]))) { isSiteAlreadyOnPiwik = pso.CheckIfPageIsAlreadyOnPiwik(Convert.ToString(item[ConfigValues.PiwikPro_SiteDirectory_Column_SiteID])); } if (isSiteAlreadyOnPiwik) { idSite = Convert.ToString(item[ConfigValues.PiwikPro_SiteDirectory_Column_SiteID]); pso.ChangeNameSiteInPiwik(Convert.ToString(item[ConfigValues.PiwikPro_SiteDirectory_Column_Title]), idSite); } else { idSite = pso.AddSiteToPiwik(Convert.ToString(item[ConfigValues.PiwikPro_SiteDirectory_Column_Title]), valueUrl.Url); } if (idSite.Contains("Error: ")) { item[ConfigValues.PiwikPro_SiteDirectory_Column_Status] = ConfigValues.PiwikPro_SiteDirectory_Column_Status_Error; item[ConfigValues.PiwikPro_SiteDirectory_Column_ErrorLog] = idSite; } else { try { bool? ShouldTrackDocumentAddedGoal = null; bool? ShouldTrackPageAddedGoal = null; bool? ShouldTrackPageEditedGoal = null; ClientContext contextToPropBag; if (!string.IsNullOrEmpty(spOnlineUserLogin)) { OfficeDevPnP.Core.AuthenticationManager authMan = new OfficeDevPnP.Core.AuthenticationManager(); contextToPropBag = authMan.GetAppOnlyAuthenticatedContext(valueUrl.Url, spOnlineUserLogin, spOnlineUserPassword); SetEnablePropertyBagChange(adminTenantUrl, valueUrl.Url, spOnlineUserLogin, spOnlineUserPassword, logger); } else { contextToPropBag = new ClientContext(valueUrl.Url); } if (isSiteAlreadyOnPiwik) { //operations if site was active before } else { //copy template values from piwikadmin foreach (PropertyBagEntity pbe in cfg.PropertyBagList) { if (pbe.PropertyTitle.StartsWith("Template")) { CreateOrUpdateValueInPropertyBag(pbe.PropertyValue, contextToPropBag, pbe.PropertyName.Replace("template", "")); } } } CreateOrUpdateValueInPropertyBag(idSite, contextToPropBag, ConfigValues.PiwikPro_PropertyBag_SiteId); CreateOrUpdateValueInPropertyBag("true", contextToPropBag, ConfigValues.PiwikPro_PropertyBag_PiwikIsTrackingActive); //set gdpr off pso.SetSetGdprOffInPiwik(idSite); //create/update values in propbag PropertyValues currentBag = contextToPropBag.Site.RootWeb.AllProperties; contextToPropBag.Load(currentBag); contextToPropBag.ExecuteQueryRetry(); //Prepare goals ShouldTrackDocumentAddedGoal = CheckIfValuesAreIntOrBoolAndReturn(Convert.ToString(currentBag[ConfigValues.PiwikPro_PropertyBag_ShouldTrackDocumentAddedGoal])); ShouldTrackPageAddedGoal = CheckIfValuesAreIntOrBoolAndReturn(Convert.ToString(currentBag[ConfigValues.PiwikPro_PropertyBag_ShouldTrackPageAddedGoal])); ShouldTrackPageEditedGoal = CheckIfValuesAreIntOrBoolAndReturn(Convert.ToString(currentBag[ConfigValues.PiwikPro_PropertyBag_ShouldTrackPageEditedGoal])); //Add goals to Piwik site AddGoalToPiwikAndWriteToPropertyBag(pso, ShouldTrackDocumentAddedGoal, idSite, ConfigValues.PiwikPro_PropertyBag_DocumentAddedGoalId, "Document added", currentBag, contextToPropBag); AddGoalToPiwikAndWriteToPropertyBag(pso, ShouldTrackPageAddedGoal, idSite, ConfigValues.PiwikPro_PropertyBag_PageAddedGoalId, "Page added", currentBag, contextToPropBag); AddGoalToPiwikAndWriteToPropertyBag(pso, ShouldTrackPageEditedGoal, idSite, ConfigValues.PiwikPro_PropertyBag_PageEditedGoalId, "Page edited", currentBag, contextToPropBag); AddPropBagValuesToIndexedProperties(contextToPropBag); } catch (Exception exp) { item[ConfigValues.PiwikPro_SiteDirectory_Column_ErrorLog] = exp.Message; logger.WriteLog(Category.Unexpected, "Piwik GetAllNewSitesAndOperate", exp.Message); } item[ConfigValues.PiwikPro_SiteDirectory_Column_Status] = ConfigValues.PiwikPro_SiteDirectory_Column_Status_Active; item[ConfigValues.PiwikPro_SiteDirectory_Column_SiteID] = idSite; } item.Update(); clientContext.ExecuteQueryRetry(); } } catch (Exception expcc) { logger.WriteLog(Category.Unexpected, "Piwik GetAllNewSitesAndOperateOnFinish", expcc.Message); } }
public IEnumerable <CalendarItem> GetCalendarItems(string siteUrl, string listName) { List <CalendarItem> calItems = new List <CalendarItem>(); 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); CamlQuery camlQuery = CamlQuery.CreateAllItemsQuery(100); ListItemCollection listItems = oList.GetItems(camlQuery); context.Load(listItems); context.ExecuteQuery(); foreach (ListItem oListItem in listItems) { var fields = oListItem.FieldValues; var calItem = new CalendarItem(); foreach (var field in fields) { switch (field.Key) { case "ID": calItem.ID = Convert.ToInt32(field.Value); break; case "Title": calItem.Title = field.Value.ToString(); break; case "Description": calItem.Description = WebUtility.HtmlDecode(field.Value.ToString()); break; case "FileDirRef": calItem.FileDirRef = field.Value.ToString(); break; case "FileRef": calItem.FileRef = field.Value.ToString(); break; case "Location": calItem.Location = field.Value.ToString(); break; case "Created": calItem.Created = DateTime.Parse(field.Value.ToString()); break; case "Modified": calItem.Modified = DateTime.Parse(field.Value.ToString()); break; case "EndDate": calItem.EndDate = DateTime.Parse(field.Value.ToString()); break; case "EventDate": calItem.EventDate = DateTime.Parse(field.Value.ToString()); break; case "Author": FieldUserValue itemAuthor = field.Value as FieldUserValue; var author = new Models.UserModel(); author.Email = itemAuthor.Email; author.LookupId = itemAuthor.LookupId; author.LookupValue = itemAuthor.LookupValue; calItem.Author = author; break; case "Editor": FieldUserValue itemEditor = field.Value as FieldUserValue; var editor = new Models.UserModel(); editor.Email = itemEditor.Email; editor.LookupId = itemEditor.LookupId; editor.LookupValue = itemEditor.LookupValue; calItem.Editor = editor; break; } } calItem.ListName = listName; calItem.SiteUrl = siteUrl; calItems.Add(calItem); } return(calItems); } catch (Exception ex) { return(null); } } }
public static ClientContext GetSPAuthContext(string siteUrl) { var authManager = new OfficeDevPnP.Core.AuthenticationManager(); return(authManager.GetAppOnlyAuthenticatedContext(siteUrl, clientId, clientSecret)); }