static void Main(string[] args) { var branding = XDocument.Load("settings.xml").Element("branding"); var url = branding.Attribute("url").Value; var username = GetUserName(); var password = GetPassword(); var credentials = new SharePointOnlineCredentials(username, password); foreach (var site in branding.Element("sites").Descendants("site")) { var siteUrl = url.TrimEnd(trimChars) + "/" + site.Attribute("url").Value.TrimEnd(trimChars); using (ClientContext clientContext = new ClientContext(siteUrl)) { clientContext.Credentials = credentials; clientContext.Load(clientContext.Web); clientContext.ExecuteQuery(); UploadFiles(clientContext, branding); UploadMasterPages(clientContext, branding); UploadPageLayouts(clientContext, branding); } } Console.WriteLine("Done!"); Console.ReadLine(); }
public SPClientContext(Uri webFullUrl, AuthType authType = AuthType.Default, string userName = null, string password = null) : this(webFullUrl) { Authentication = authType; UserName = userName; switch (Authentication) { case AuthType.Default: AuthenticationMode = ClientAuthenticationMode.Default; Credentials = string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(password) ? CredentialCache.DefaultNetworkCredentials : new NetworkCredential(UserName, password); break; case AuthType.SharePointOnline: AuthenticationMode = ClientAuthenticationMode.Default; Credentials = new SharePointOnlineCredentials(UserName, Utility.GetSecureString(password)); break; case AuthType.Anonymous: AuthenticationMode = ClientAuthenticationMode.Anonymous; break; case AuthType.Forms: AuthenticationMode = ClientAuthenticationMode.FormsAuthentication; FormsAuthenticationLoginInfo = new FormsAuthenticationLoginInfo(UserName, password); break; } }
static TestCommon() { // Read configuration data TenantUrl = ConfigurationManager.AppSettings["SPOTenantUrl"]; DevSiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"]; if (string.IsNullOrEmpty(TenantUrl) || string.IsNullOrEmpty(DevSiteUrl)) { throw new ConfigurationErrorsException("Tenant site Url or Dev site url in App.config are not set up."); } // Trim trailing slashes TenantUrl = TenantUrl.TrimEnd(new[] { '/' }); DevSiteUrl = DevSiteUrl.TrimEnd(new[] { '/' }); if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["SPOCredentialManagerLabel"])) { var tempCred = Core.Utilities.CredentialManager.GetCredential(ConfigurationManager.AppSettings["SPOCredentialManagerLabel"]); // username in format domain\user means we're testing in on-premises if (tempCred.UserName.IndexOf("\\") > 0) { string[] userParts = tempCred.UserName.Split('\\'); Credentials = new NetworkCredential(userParts[1], tempCred.SecurePassword, userParts[0]); } else { Credentials = new SharePointOnlineCredentials(tempCred.UserName, tempCred.SecurePassword); } } else { if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["SPOUserName"]) && !String.IsNullOrEmpty(ConfigurationManager.AppSettings["SPOPassword"])) { UserName = ConfigurationManager.AppSettings["SPOUserName"]; var password = ConfigurationManager.AppSettings["SPOPassword"]; Password = GetSecureString(password); Credentials = new SharePointOnlineCredentials(UserName, Password); } else if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["OnPremUserName"]) && !String.IsNullOrEmpty(ConfigurationManager.AppSettings["OnPremDomain"]) && !String.IsNullOrEmpty(ConfigurationManager.AppSettings["OnPremPassword"])) { Password = GetSecureString(ConfigurationManager.AppSettings["OnPremPassword"]); Credentials = new NetworkCredential(ConfigurationManager.AppSettings["OnPremUserName"], Password, ConfigurationManager.AppSettings["OnPremDomain"]); } else if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["AppId"]) && !String.IsNullOrEmpty(ConfigurationManager.AppSettings["AppSecret"])) { AppId = ConfigurationManager.AppSettings["AppId"]; AppSecret = ConfigurationManager.AppSettings["AppSecret"]; } else { throw new ConfigurationErrorsException("Tenant credentials in App.config are not set up."); } } }
public SPService(string username, string password, string url) { using (ClientContext ctx = new ClientContext(url)) { var securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } var onlineCredentials = new SharePointOnlineCredentials(username, securePassword); ctx.Credentials = onlineCredentials; web = ctx.Web; ctx.Load(web); ctx.ExecuteQuery(); //ctx.GetFormDigestDirect().DigestValue var authCookie = onlineCredentials.GetAuthenticationCookie(new Uri(url)); //var fedAuthString = authCookie.TrimStart("SPOIDCRL=".ToCharArray()); webinfo = new WebInfo { Title = web.Title, ErrorMessage = "", DigestInfo = authCookie.ToString() }; context = ctx; } }
public ActionResult Index() { User spUser = null; var url = "https://website/"; var accountName = "accountName"; var password = "******"; var securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } var onlineCredentials = new SharePointOnlineCredentials(accountName, securePassword); using (var clientContext = new ClientContext(url)) { if (clientContext != null) { clientContext.Credentials = onlineCredentials; spUser = clientContext.Web.CurrentUser; clientContext.Load(spUser, user => user.Title); clientContext.ExecuteQuery(); ViewBag.UserName = spUser.Title; } } return View(); }
/// <summary> /// Returns a SharePoint Online Credential given a certain name. Add the credential in the Windows Credential Manager and create a new Windows Credential. Then add a new GENERIC Credential. The name parameter in the method maps to the Internet or network address field. /// </summary> /// <param name="name"></param> /// <returns>Microsoft.SharePoint.Client.SharePointOnlineCredentials</returns> public static SharePointOnlineCredentials GetSharePointOnlineCredential(string name) { var networkCredential = GetCredential(name); var credential = new SharePointOnlineCredentials(networkCredential.UserName, networkCredential.SecurePassword); return credential; }
public SPMarketSyncManager(string siteUrl, string login, string password) { var creds = new SharePointOnlineCredentials(login, password); var auth = creds.AuthenticateAsync(new Uri(siteUrl), true); _siteUrl = siteUrl; _cookieContainer = auth.Result.CookieContainer; }
/// <summary> /// Returns a SharePointOnline ClientContext object /// </summary> /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param> /// <param name="tenantUser">User to be used to instantiate the ClientContext object</param> /// <param name="tenantUserPassword">Password of the user used to instantiate the ClientContext object</param> /// <returns>ClientContext to be used by CSOM code</returns> public ClientContext GetSharePointOnlineAuthenticatedContextTenant(string siteUrl, string tenantUser, string tenantUserPassword) { var spoPassword = GetSecureString(tenantUserPassword); SharePointOnlineCredentials sharepointOnlineCredentials = new SharePointOnlineCredentials(tenantUser, spoPassword); var ctx = new ClientContext(siteUrl); ctx.Credentials = sharepointOnlineCredentials; return ctx; }
static ClientContext SetupContext(Uri siteCollection, string username, string password) { if (string.IsNullOrEmpty(username) && string.IsNullOrEmpty(password)) { return new ClientContext(siteCollection); } else { var securePassword = new SecureString(); password.ToCharArray().ToList().ForEach(securePassword.AppendChar); var credentials = new SharePointOnlineCredentials(username, securePassword); return new ClientContext(siteCollection) { Credentials = credentials }; } }
public TestListService() { const string userName = "******"; const string password = "******"; var securePassword = new SecureString(); foreach (var c in password) { securePassword.AppendChar(c); } credentials = new SharePointOnlineCredentials(userName, securePassword); }
private Cookie GetFedAuthCookie(SharePointOnlineCredentials credentials) { string authCookie = credentials.GetAuthenticationCookie(new Uri(this.TenantUrl)); if (authCookie.Length > 0) { return new Cookie("SPOIDCRL", authCookie.TrimStart("SPOIDCRL=".ToCharArray()), String.Empty, new Uri(this.TenantUrl).Authority); } else { return null; } }
public SharepointClient(SharepointClientParameters parameters) { _parameters = parameters; var credentials = new SharePointOnlineCredentials(parameters.User, parameters.Password.ToSecureString()); _context = new ClientContext(parameters.Url) { RequestTimeout = parameters.RequestTimeout, Credentials = credentials }; _context.ExecuteQuery(); }
public WebListClientContext() { CredentialsAttribute attr = typeof(SharePointArticleRepository) .GetCustomAttributes(false) .FirstOrDefault(a => a.GetType() == typeof(CredentialsAttribute)) as CredentialsAttribute; WebUri = attr.WebUri; credentials = attr.Credentials; client = new WebClient().Create() .WithCredentials(credentials) .WhereHeader.AcceptIs("application/json;odata=verbose") .ContentTypeIs("application/json;odata=verbose") .UsesWindowsAuthentification(); }
/// <summary> /// Returns a SharePointOnline ClientContext object /// </summary> /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param> /// <param name="tenantUser">User to be used to instantiate the ClientContext object</param> /// <param name="tenantUserPassword">Password (SecureString) of the user used to instantiate the ClientContext object</param> /// <returns>ClientContext to be used by CSOM code</returns> public ClientContext GetSharePointOnlineAuthenticatedContextTenant(string siteUrl, string tenantUser, SecureString tenantUserPassword) { Log.Info(Constants.LOGGING_SOURCE, CoreResources.AuthenticationManager_GetContext, siteUrl); Log.Debug(Constants.LOGGING_SOURCE, CoreResources.AuthenticationManager_TenantUser, tenantUser); if (sharepointOnlineCredentials == null) { sharepointOnlineCredentials = new SharePointOnlineCredentials(tenantUser, tenantUserPassword); } var ctx = new ClientContext(siteUrl); ctx.Credentials = sharepointOnlineCredentials; return ctx; }
/// <summary> /// Get csom ProjectContext by letting user type in username and password /// </summary> /// <param name="url">pwa website url string</param> /// <returns></returns> private static csom.ProjectContext GetContext(string url) { csom.ProjectContext context = new csom.ProjectContext(url); string userName, passWord; Console.WriteLine("Please enter your username for PWA"); userName = Console.ReadLine(); Console.WriteLine("Please enter your password for PWA"); passWord = Console.ReadLine(); NetworkCredential netcred = new NetworkCredential(userName, passWord); SharePointOnlineCredentials orgIDCredential = new SharePointOnlineCredentials(netcred.UserName, netcred.SecurePassword); context.Credentials = orgIDCredential; return context; }
/// <summary> /// Returns a SharePointOnline ClientContext object /// </summary> /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param> /// <param name="tenantUser">User to be used to instantiate the ClientContext object</param> /// <param name="tenantUserPassword">Password of the user used to instantiate the ClientContext object</param> /// <returns>ClientContext to be used by CSOM code</returns> public ClientContext GetSharePointOnlineAuthenticatedContextTenant(string siteUrl, string tenantUser, string tenantUserPassword) { LoggingUtility.Internal.TraceInformation((int)EventId.AuthenticationContext, CoreResources.AuthenticationManager_GetContext, siteUrl); LoggingUtility.Internal.TraceVerbose(CoreResources.AuthenticationManager_TenantUser, tenantUser); if (sharepointOnlineCredentials == null) { var spoPassword = tenantUserPassword.ToSecureString(); sharepointOnlineCredentials = new SharePointOnlineCredentials(tenantUser, spoPassword); } var ctx = new ClientContext(siteUrl); ctx.Credentials = sharepointOnlineCredentials; return ctx; }
static TestCommon() { // Read configuration data TenantUrl = ConfigurationManager.AppSettings["SPOTenantUrl"]; DevSiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"]; if (string.IsNullOrEmpty(TenantUrl) || string.IsNullOrEmpty(DevSiteUrl)) { throw new ConfigurationErrorsException("Tenant credentials in App.config are not set up."); } if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["SPOCredentialManagerLabel"])) { Credentials = Core.Utilities.CredentialManager.GetSharePointOnlineCredential(ConfigurationManager.AppSettings["SPOCredentialManagerLabel"]); } else { if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["SPOUserName"]) && !String.IsNullOrEmpty(ConfigurationManager.AppSettings["SPOPassword"])) { UserName = ConfigurationManager.AppSettings["SPOUserName"]; var password = ConfigurationManager.AppSettings["SPOPassword"]; Password = GetSecureString(password); Credentials = new SharePointOnlineCredentials(UserName, Password); } else if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["OnPremUserName"]) && !String.IsNullOrEmpty(ConfigurationManager.AppSettings["OnPremDomain"]) && !String.IsNullOrEmpty(ConfigurationManager.AppSettings["OnPremPassword"])) { Password = GetSecureString(ConfigurationManager.AppSettings["OnPremPassword"]); Credentials = new NetworkCredential(ConfigurationManager.AppSettings["OnPremUserName"], Password, ConfigurationManager.AppSettings["OnPremDomain"]); } else if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["Realm"]) && !String.IsNullOrEmpty(ConfigurationManager.AppSettings["AppId"]) && !String.IsNullOrEmpty(ConfigurationManager.AppSettings["AppSecret"])) { Realm = ConfigurationManager.AppSettings["Realm"]; AppId = ConfigurationManager.AppSettings["AppId"]; AppSecret = ConfigurationManager.AppSettings["AppSecret"]; } else { throw new ConfigurationErrorsException("Tenant credentials in App.config are not set up."); } } }
/// <summary> /// Returns a SharePointOnline ClientContext object /// </summary> /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param> /// <param name="tenantUser">User to be used to instantiate the ClientContext object</param> /// <param name="tenantUserPassword">Password of the user used to instantiate the ClientContext object</param> /// <returns>ClientContext to be used by CSOM code</returns> public ClientContext GetSharePointOnlineAuthenticatedContextTenant(string siteUrl, string tenantUser, string tenantUserPassword) { if (sharepointOnlineCredentials == null) { var spoPassword = new SecureString(); foreach (char c in tenantUserPassword) { spoPassword.AppendChar(c); } sharepointOnlineCredentials = new SharePointOnlineCredentials(tenantUser, spoPassword); } var ctx = new ClientContext(siteUrl); ctx.Credentials = sharepointOnlineCredentials; return ctx; }
public async void LoadResults(string siteUrl, string keywords, string login, string mdp) { ObservableCollection<CortanaItem> cortanaResults = new ObservableCollection<CortanaItem>(); keywords = keywords.Trim('.').ToLower(); try { using (ClientContext context = new ClientContext(siteUrl)) { SharePointOnlineCredentials credentials = new SharePointOnlineCredentials(login, mdp); context.Credentials = credentials; KeywordQuery keywordQuery = new KeywordQuery(context); keywordQuery.QueryText = keywords; keywordQuery.SourceId = new Guid(SettingsValues.SourceId); keywordQuery.EnablePhonetic = true; keywordQuery.EnableStemming = true; keywordQuery.RowLimit = 100; SearchExecutor searchExecutor = new SearchExecutor(context); ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery); context.ExecuteQueryAsync().Wait(); foreach (var item in results.Value[0].ResultRows) { CortanaItem ci = new CortanaItem(); ci.Id = item["ID"] != null ? item["ID"].ToString() : string.Empty; ci.Title = item["Title"] != null ? item["Title"].ToString() : string.Empty; ci.LastModifiedDate = item["Modified"] != null ? item["Modified"].ToString() : string.Empty; ci.Url = item["Path"] != null ? item["Path"].ToString() : string.Empty; cortanaResults.Add(ci); } } LoadDataCompleted(cortanaResults); // Fire event DataLoadCompleted } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Erreur : " + ex.Message); LoadDataCompleted(null); } }
/// <summary> /// Activates SharePoint feature /// </summary> /// <param name="clientUrl">Client Url</param> /// <param name="credentials">SharePoint Credentials</param> /// <returns>Flag if feature activated</returns> public static bool ActivateFeature(string clientUrl, SharePointOnlineCredentials credentials) { try { using (ClientContext clientContext = new ClientContext(clientUrl)) { clientContext.Credentials = credentials; Guid featureId = new Guid(ConfigurationManager.AppSettings["DocumentFeatureID"]); FeatureCollection features = clientContext.Site.Features; clientContext.Load(features); clientContext.ExecuteQuery(); var isFeatureActivated = (from feature in features where feature.DefinitionId == featureId select feature).FirstOrDefault(); if (null != isFeatureActivated) { // Feature Activated return false; } else { // Activate the feature features.Add(featureId, false, FeatureDefinitionScope.Farm); clientContext.ExecuteQuery(); return true; } } } // SharePoint Specific Exception catch (ClientRequestException clientRequestException) { ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: " + clientRequestException.Message + "\nStacktrace: " + clientRequestException.StackTrace); } // SharePoint Specific Exception catch (ServerException serverException) { ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: " + serverException.Message + "\nStacktrace: " + serverException.StackTrace); } catch (Exception exception) { ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace); } return false; }
/// <summary> /// Sample Member that provisions personal sites leveraging CSOM /// You dont want to do provision more than 200 users during a single request. If you have a large amount of users consider // waiting for the last users site to be provisioned. The reason behind this is not to bombard the service with requests. /// </summary> /// <param name="tenantAdminUrl">The Tenanat Admin URL for your SharePoint Online Subscription</param> /// <param name="spoCredentials">The Credentials of the user who has tenant admin permission.</param> /// <param name="emailIDs">The email ids for users whos personal site you want to create.</param> public static void CreatePersonalSiteUsingCSOM(SharePointOnlineCredentials spoCredentials, string tenantAdminUrl, string[] emailIDs) { using (ClientContext _context = new ClientContext(tenantAdminUrl)) { try { _context.AuthenticationMode = ClientAuthenticationMode.Default; _context.Credentials = spoCredentials; ProfileLoader _profileLoader = ProfileLoader.GetProfileLoader(_context); _profileLoader.CreatePersonalSiteEnqueueBulk(emailIDs); _profileLoader.Context.ExecuteQuery(); } catch (Exception _ex) { Console.WriteLine(string.Format("Opps, something went wrong and we need to work on it. The error message is {0}", _ex.Message)); } } }
static void Main(string[] args) { string siteUrl = GetAdminURL(); /* Prompt for Credentials */ Console.WriteLine("Enter Credentials for {0}", siteUrl); string userName = GetUserName(); SecureString pwd = GetPassword(); string[] emailIds = GetEmailId(); /* End Program if no Credentials */ if (string.IsNullOrEmpty(userName) || (pwd == null) || emailIds == null || string.IsNullOrEmpty(siteUrl)) return; SharePointOnlineCredentials _creds = new SharePointOnlineCredentials(userName, pwd); CreatePersonalSiteUsingCSOM(_creds, siteUrl, emailIds); Console.WriteLine("Working on it. Press any key to continue"); Console.Read(); }
private static void DeployNewSite(string newSiteUrl, Tuple<string, string> creds) { using (ClientContext context = new ClientContext(AdminUrl)) { SharePointOnlineCredentials adminCredentials = new SharePointOnlineCredentials(creds.Item1, creds.Item2.ToSecureString()); context.Credentials = adminCredentials; var tenant = new Tenant(context); // Create new site collection with storage limits and settings from the form tenant.CreateSiteCollection(newSiteUrl, "Outlook Meeting Workspace", creds.Item1, "STS#0", (int) 20, (int) 10, 3, // 3 is the timezone for Stockholm 0, 0, 1033); } }
/// <summary> /// Creating client context along with authentication /// </summary> /// <param name="url">Site URL</param> /// <param name="userId">User id</param> /// <param name="password">Password to authenticate</param> /// <returns>Client context</returns> public static ClientContext ConfigureClientContext(string url, string userId, string password) { using (var securePassword = new SecureString()) { if (!string.IsNullOrWhiteSpace(userId) && !string.IsNullOrWhiteSpace(password) && !string.IsNullOrWhiteSpace(url)) { foreach (char character in password) { securePassword.AppendChar(character); } using (ClientContext clientContext = new ClientContext(url)) { object onlineCredentials; onlineCredentials = new SharePointOnlineCredentials(userId, securePassword); clientContext.Credentials = (SharePointOnlineCredentials)onlineCredentials; // Secure the credentials and generate the SharePoint Online Credentials clientContext.ExecuteQuery(); return clientContext; } } return null; } }
public ICredentials GetCredentialsForSharePoint(string userName, Uri urlToSite, bool isSharePointOnline) { var credentials = GetCredentialsFromWindowsCredentialManager(urlToSite, isSharePointOnline); //If there is no creds specified in the credential manager and no username is set, we want to use default credentials if (credentials == null && !string.IsNullOrEmpty(userName)) { var password = PromptForPassword(userName); if (password != null && password.Length > 0) { if (isSharePointOnline) { Log.Debug("Attempting to authenticate with SharePointOnlineCredentials"); credentials = new SharePointOnlineCredentials(userName, password); if (!AuthenticateUser((SharePointOnlineCredentials) credentials, urlToSite)) { Log.Error("There is a problem authenticating with the provided credentials"); GetCredentialsForSharePoint(userName, urlToSite, false); } } else { try { Log.Debug("Attempting to authenticate with NetworkCredentials"); credentials = new NetworkCredential(userName, password); } catch { Log.Error("There is a problem with the provided credentials"); GetCredentialsForSharePoint(userName, urlToSite, false); } } } } return credentials; }
public async void LoadItems(string siteUrl, string listName, string login, string mdp) { ObservableCollection<CortanaItem> cortanaItems = new ObservableCollection<CortanaItem>(); try { using (ClientContext context = new ClientContext(siteUrl)) { SharePointOnlineCredentials credentials = new SharePointOnlineCredentials(login, mdp); context.Credentials = credentials; Web web = context.Web; ListItemCollection listItemCollection = web.Lists.GetByTitle(listName).GetItems(CamlQuery.CreateAllItemsQuery()); context.Load(listItemCollection); await context.ExecuteQueryAsync().ContinueWith((t) => { foreach (var item in listItemCollection) { CortanaItem ci = new CortanaItem(); ci.Id = item.FieldValues["ID"] != null ? item.FieldValues["ID"].ToString() : string.Empty; ci.Title = item.FieldValues["Title"] != null ? item.FieldValues["Title"].ToString() : string.Empty; ci.LastModifiedDate = item.FieldValues["Modified"] != null ? item.FieldValues["Modified"].ToString() : string.Empty; ci.Url = item.FieldValues["FileRef"] != null ? item.FieldValues["FileRef"].ToString() : string.Empty; cortanaItems.Add(ci); } }); } LoadDataCompleted(cortanaItems); // Fire event DataLoadCompleted } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Erreur : " + ex.Message); LoadDataCompleted(null); } }
public async void LoadAppointments(string siteUrl, string calendarName, string login, string mdp) { ObservableCollection<CortanaAppointment> cortanaAppointments = new ObservableCollection<CortanaAppointment>(); try { using (ClientContext context = new ClientContext(siteUrl)) { SharePointOnlineCredentials credentials = new SharePointOnlineCredentials(login, mdp); context.Credentials = credentials; Web web = context.Web; ListItemCollection calendarAppointmentsCollection = web.Lists.GetByTitle(calendarName).GetItems(CamlQuery.CreateAllItemsQuery()); context.Load(calendarAppointmentsCollection); await context.ExecuteQueryAsync().ContinueWith((t) => { foreach (var item in calendarAppointmentsCollection) { CortanaAppointment ci = new CortanaAppointment(); ci.Id = item.FieldValues["ID"] != null ? item.FieldValues["ID"].ToString() : string.Empty; ci.Subject = item.FieldValues["Title"] != null ? item.FieldValues["Title"].ToString() : string.Empty; ci.StartDate = item.FieldValues["EventDate"] != null ? DateTime.Parse(item.FieldValues["EventDate"].ToString()) : new DateTime(); cortanaAppointments.Add(ci); } }); } LoadDataCompleted(cortanaAppointments); // Fire event DataLoadCompleted } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Erreur : " + ex.Message); LoadDataCompleted(null); } }
static TestCommon() { TenantUrl = ConfigurationManager.AppSettings["SPOTenantUrl"]; DevSiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"]; if (string.IsNullOrEmpty(TenantUrl) || string.IsNullOrEmpty(DevSiteUrl)) { throw new ConfigurationErrorsException("Tenant credentials in App.config are not set up."); } if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["SPOCredentialManagerLabel"])) { Credentials = CredentialManager.GetCredential(ConfigurationManager.AppSettings["SPOCredentialManagerLabel"]); } else { UserName = ConfigurationManager.AppSettings["SPOUserName"]; var password = ConfigurationManager.AppSettings["SPOPassword"]; Password = password.ToSecureString(); Credentials = new SharePointOnlineCredentials(UserName, Password); } }
static TestCommon() { // Read configuration data TenantUrl = AppSetting("SPOTenantUrl"); DevSiteUrl = AppSetting("SPODevSiteUrl"); #if !ONPREMISES if (string.IsNullOrEmpty(TenantUrl)) { throw new ConfigurationErrorsException("Tenant site Url in App.config are not set up."); } #endif if (string.IsNullOrEmpty(DevSiteUrl)) { throw new ConfigurationErrorsException("Dev site url in App.config are not set up."); } // Trim trailing slashes TenantUrl = TenantUrl.TrimEnd(new[] { '/' }); DevSiteUrl = DevSiteUrl.TrimEnd(new[] { '/' }); if (!string.IsNullOrEmpty(AppSetting("SPOCredentialManagerLabel"))) { var tempCred = OfficeDevPnP.Core.Utilities.CredentialManager.GetCredential(AppSetting("SPOCredentialManagerLabel")); // username in format domain\user means we're testing in on-premises if (tempCred.UserName.IndexOf("\\") > 0) { string[] userParts = tempCred.UserName.Split('\\'); Credentials = new NetworkCredential(userParts[1], tempCred.SecurePassword, userParts[0]); } else { Credentials = new SharePointOnlineCredentials(tempCred.UserName, tempCred.SecurePassword); } } else { if (!String.IsNullOrEmpty(AppSetting("SPOUserName")) && !String.IsNullOrEmpty(AppSetting("SPOPassword"))) { UserName = AppSetting("SPOUserName"); var password = AppSetting("SPOPassword"); Password = GetSecureString(password); Credentials = new SharePointOnlineCredentials(UserName, Password); } else if (!String.IsNullOrEmpty(AppSetting("AppId")) && !String.IsNullOrEmpty(AppSetting("AppSecret"))) { AppId = AppSetting("AppId"); AppSecret = AppSetting("AppSecret"); } else { throw new ConfigurationErrorsException("Tenant credentials in App.config are not set up."); } } }
/// <summary> /// Fetches On-Prem documents and their folder structure /// Uploads them to SharePoint Online to respective folders. /// </summary> /// <param name="spoCredentials">SharePointOnlineCredetials</param> /// <param name="tenantAdminUrl">Url to tenant admin site</param> /// <param name="folders">List of folders to be created</param> /// <param name="userName">On-prem username as in mysite url</param> /// <param name="sourceLibraryName">source library name</param> /// <param name="onPremMysiteUrl">Onpremises mysite url for the users</param> /// <param name="onpremCreds">Onprem credentials</param> /// <param name="overwrite">Overwrite existing files</param> public static void UploadDocuments(SharePointOnlineCredentials spoCredentials, string tenantAdminUrl, List <string> folders, string userName, string sourceLibraryName, string onPremMysiteUrl, NetworkCredential onpremCreds, bool overwrite) { using (ClientContext context = new ClientContext(tenantAdminUrl)) { try { context.AuthenticationMode = ClientAuthenticationMode.Default; context.Credentials = spoCredentials; context.ExecuteQuery(); List docs = context.Web.Lists.GetByTitle(SPODocumentsName); context.ExecuteQuery(); var folder = docs.RootFolder; context.Load(folder); context.ExecuteQuery(); context.Load(context.Web); context.ExecuteQuery(); string SPOUrl = context.Web.ServerRelativeUrl; // Create onprem folder structure to SPO foreach (string f in folders) { // Shared documents name is different in SPO if (f.Contains(SharedDocumentsName)) { EnsureFolder(context, folder, SPOSharedDocumentsName); } else { EnsureFolder(context, folder, f); } } onPremMysiteUrl = string.Format(onPremMysiteUrl, userName); using (ClientContext opContext = new ClientContext(onPremMysiteUrl)) { opContext.Credentials = onpremCreds; opContext.Load(opContext.Web); opContext.ExecuteQuery(); List documentsList = opContext.Web.Lists.GetByTitle(sourceLibraryName); opContext.Load(documentsList); opContext.ExecuteQuery(); CamlQuery query = CamlQuery.CreateAllItemsQuery(); ListItemCollection items = documentsList.GetItems(query); opContext.Load(items, items2 => items2.IncludeWithDefaultProperties (item => item.DisplayName, item => item.File)); opContext.ExecuteQuery(); foreach (ListItem item in items) { if (item.FileSystemObjectType != FileSystemObjectType.Folder) { string itemUrl = item.File.ServerRelativeUrl; itemUrl = itemUrl.Substring(itemUrl.IndexOf(sourceLibraryName)); // Library names are different in SPO (2013) than in 2010 mysite if (sourceLibraryName == PicturesName) { itemUrl = "/" + itemUrl; } else if (sourceLibraryName == SharedDocumentsName) { itemUrl = "/" + itemUrl.Replace(SharedDocumentsName, SPOSharedDocumentsName); } else { itemUrl = itemUrl.Substring(itemUrl.IndexOf("/")); } try { // Get the file from mysite and upload the file to spo string SPOLocation = SPOUrl + "/" + SPODocumentsName + itemUrl; FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(opContext, item.File.ServerRelativeUrl); Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, SPOLocation, fileInfo.Stream, overwrite); } catch (ClientRequestException crex) { if (crex.Message.ToLower().Contains("exists")) { Console.WriteLine(crex.Message); } else { throw crex; } } } } } } catch (Exception ex) { Console.WriteLine(string.Format("Opps, something went wrong and we need to work on it. The error message is {0}", ex.Message)); } } }
/// <summary> /// Main function /// /// Parameters /// 0 - Sharepoint Online Admin Url ("https://poc-admin.sharepoint.com") /// 1 - Sharepoint Online Onedrive url with placeholder ("https://poc-my.sharepoint.com/personal/{0}_poc_onmicrosoft_com") /// 2 - Sharepoint Online Admin name ("*****@*****.**") /// 3 - Sharepoint Online Admin password ("pass@word1") /// 4 - path to CSV File (C:\temp\users.csv) /// 5 - Onprem mysite url with placeholder ("http://mysite/personal/{0}") /// 6 - Onprem admin name (admin) /// 7 - Onprem admin password (pass@word1) /// 8 - Overwrite files in SPO /// </summary> /// <param name="args"></param> static void Main(string[] args) { string spoSiteUrl = string.Empty; string spoMysiteUrl = string.Empty; string adminUserName = string.Empty; SecureString adminPwd = ToSecureString(string.Empty); string csvLocation = string.Empty; string onPremMysiteUrl = string.Empty; string onPremAdmin = string.Empty; SecureString onPremAdminPWD = ToSecureString(string.Empty); bool overwrite = true; try { spoSiteUrl = args[0]; spoMysiteUrl = args[1]; adminUserName = args[2]; adminPwd = ToSecureString(args[3]); csvLocation = args[4]; onPremMysiteUrl = args[5]; onPremAdmin = args[6]; onPremAdminPWD = ToSecureString(args[7]); overwrite = Convert.ToBoolean(args[8]); } catch (Exception) { Console.WriteLine("Something was wrong with the parameters!"); Console.WriteLine(); Console.WriteLine("Parameters:"); Console.WriteLine(@"0 - Sharepoint Online Admin Url ('https://poc-admin.sharepoint.com')"); Console.WriteLine(@"1 - Sharepoint Online Onedrive url with placeholder ('https://poc-my.sharepoint.com/personal/{0}_poc_onmicrosoft_com')"); Console.WriteLine(@"2 - Sharepoint Online Admin name ('*****@*****.**')"); Console.WriteLine(@"3 - Sharepoint Online Admin password ('pass@word1')"); Console.WriteLine(@"4 - path to CSV File ('C:\temp\users.csv')"); Console.WriteLine(@"5 - Onprem mysite url with placeholder ('http://mysite/personal/{0}')"); Console.WriteLine(@"6 - Onprem admin name ('admin')"); Console.WriteLine(@"7 - Onprem admin password ('password')"); Console.WriteLine(@"8 - Overwrite files in SPO (true/false)"); Console.WriteLine(); Console.WriteLine("Press any key to continue..."); Console.Read(); return; } List <User> users = ReadUsersFromCSV(csvLocation); foreach (User user in users) { string spoMysiteUrlNew = string.Format(spoMysiteUrl, user.SpoOneDriveUserName); List <string> folders = new List <string>(); SharePointOnlineCredentials creds = new SharePointOnlineCredentials(adminUserName, adminPwd); NetworkCredential onpremCreds = new NetworkCredential(onPremAdmin, onPremAdminPWD); folders = GetOnPremFolderStructure(user.OnPremUserName, PersonalDocumentsName, onPremMysiteUrl, onpremCreds); UploadDocuments(creds, spoMysiteUrlNew, folders, user.OnPremUserName, PersonalDocumentsName, onPremMysiteUrl, onpremCreds, overwrite); folders = GetOnPremFolderStructure(user.OnPremUserName, PicturesName, onPremMysiteUrl, onpremCreds); UploadDocuments(creds, spoMysiteUrlNew, folders, user.OnPremUserName, PicturesName, onPremMysiteUrl, onpremCreds, overwrite); folders = GetOnPremFolderStructure(user.OnPremUserName, SharedDocumentsName, onPremMysiteUrl, onpremCreds); UploadDocuments(creds, spoMysiteUrlNew, folders, user.OnPremUserName, SharedDocumentsName, onPremMysiteUrl, onpremCreds, overwrite); } }
/// <summary> /// Executes the business logic /// </summary> /// <param name="logger">The logger.</param> public override void Run(BaseAction parentAction, DateTime CurrentTime, LogHelper logger) { if (parentAction != null) { this.Properties = parentAction.Properties; } CsvProcessor csvProcessor = new CsvProcessor(); string[] csvFiles = Directory.GetFiles(this.CSVDirectoryLocation, "*.csv", SearchOption.TopDirectoryOnly); logger.LogVerbose(string.Format("Attempting to get files from directory 'location' {0}. Number of files found {1}", this.CSVDirectoryLocation, csvFiles.Length)); foreach (string csvFile in csvFiles) { logger.LogVerbose(string.Format("Attempting to read CSV file '{0}' from location {1}", csvFile, this.CSVDirectoryLocation)); logger.LogVerbose(string.Format("Pausing the utility for '{0}' seconds so ASMX service is not overloaded", this.SleepPeriod)); Thread.Sleep(this.SleepPeriod * 1000); using (StreamReader reader = new StreamReader(csvFile)) { logger.LogVerbose(string.Format("Establishing connection with tenant at '{0}'", this.TenantSiteUrl)); using (ClientContext context = new ClientContext(this.TenantSiteUrl)) { Uri site = new Uri(this.TenantSiteUrl); try { UserProfileService.UserProfileService profileService = new UserProfileService.UserProfileService(site.ToString() + ProfileService); this.profileService = profileService; profileService.UseDefaultCredentials = false; using (SecureString password = new SecureString()) { foreach (char c in this.TenantAdminPassword.ToCharArray()) { password.AppendChar(c); } logger.LogVerbose(string.Format("Attempting to authenticate against tenant with user name '{1}'", this.TenantSiteUrl, this.TenantAdminUserName)); var crudentials = new SharePointOnlineCredentials(this.TenantAdminUserName, password); string cookie = crudentials.GetAuthenticationCookie(site); profileService.CookieContainer = new CookieContainer(); profileService.CookieContainer.Add(new Cookie(FedAuthCookieName, cookie.TrimStart(SPOIDCookieValue.ToCharArray()), string.Empty, site.Authority)); csvProcessor.Execute(reader, (entries, y) => { IterateCollection(context, entries, logger); }, logger); } } finally { if (this.profileService != null) { this.profileService.Dispose(); } } } } // Clean up current CSV file System.IO.File.Delete(csvFile); } }
public void sentdatatoSPLIst() { string careeractivities = ""; string otheractivities = ""; string k = ""; for (int i = 0; i < chk_CareerActivities.Items.Count; i++) { if (chk_CareerActivities.Items[i].Selected) { k = k + chk_CareerActivities.Items[i].Value + ";"; } } careeractivities = k; string j = ""; for (int n = 0; n < chk_OtherActivities.Items.Count; n++) { if (chk_OtherActivities.Items[n].Selected) { j = j + chk_OtherActivities.Items[n].Value + ";"; } } otheractivities = j; int sem = 0; int Year = LibraryMOD.SeperateTerm(LibraryMOD.GetCurrentTerm(), out sem); int iYear = Year; int iSem = sem; string sSemester = LibraryMOD.GetSemesterString(iSem); string languageoption = ""; if (Session["LanguageOption"].ToString() == "True") { languageoption = "<b>Language:</b> " + ddlLanguage.SelectedItem.Text + ""; } string login = "******"; //give your username here string password = "******"; //give your password var securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } string siteUrl = "https://ectacae.sharepoint.com/sites/ECTPortal/eservices/studentservices"; ClientContext clientContext = new ClientContext(siteUrl); Microsoft.SharePoint.Client.List myList = clientContext.Web.Lists.GetByTitle("Students_Requests"); ListItemCreationInformation itemInfo = new ListItemCreationInformation(); Microsoft.SharePoint.Client.ListItem myItem = myList.AddItem(itemInfo); string refno = Create16DigitString(); myItem["Title"] = refno; //myItem["RequestID"] = refno; myItem["Year"] = iYear; myItem["Semester"] = iSem; myItem["Request"] = "<b>Service ID:</b> " + lbl_ServiceID.Text + "<br/> <b>Service Name:</b> " + lbl_ServiceNameEn.Text + " (" + lbl_ServiceNameAr.Text + " )<br/><b>Date of Birth:</b> " + lbl_DOB.Text + "<br/><b>Graduation Semester:</b> " + lbl_GraduationSemester.Text + "<br/><b>Graduation Year:</b> " + lbl_GraduationYear.Text + "<br/><b>Major:</b> " + lbl_Major.Text + "<br/><b>Address:</b> " + txt_Address.Text + "<br/><b>Mobile #1:</b> " + txt_StudentContact1.Text + "<br/><b>Mobile #2:</b> " + txt_StudentContact2.Text + "<br/><b>Email:</b> " + txt_Email.Text + "<br/><b>Work Place:</b> " + txt_WorkPlace.Text + "<br/><b>Job Title:</b> " + txt_JobTitle.Text + "<br/><b>Direct Supervisor Name:</b> " + txt_DirSupName.Text + "<br/><b>Direct Supervisor Job Title:</b> " + txt_DirSupJobtitle.Text + "<br/><b>Contact Details:</b> " + txt_ContactDetails.Text + "<br/><b>Career Development Activities (Workshop/Seminar):</b> " + careeractivities + "<br/><b>Other Activities:</b> " + otheractivities + "<br/><b>Other Suggestion for Alumni services & Activities:</b> " + txt_Remarks.Text + "<br/>" + languageoption + "<br/>"; myItem["RequestNote"] = txt_Remarks.Text.Trim(); myItem["ServiceID"] = lbl_ServiceID.Text; myItem["Fees"] = hdf_Price.Value; myItem["Requester"] = clientContext.Web.EnsureUser(hdf_StudentEmail.Value); //myItem["Requester"] = clientContext.Web.EnsureUser("*****@*****.**"); myItem["StudentID"] = lbl_StudentID.Text; myItem["StudentName"] = lbl_StudentName.Text; myItem["Contact"] = txt_StudentContact1.Text; myItem["Finance"] = clientContext.Web.EnsureUser(Session["FinanceEmail"].ToString()); myItem["FinanceAction"] = "Initiate"; myItem["FinanceNote"] = ""; myItem["Host"] = clientContext.Web.EnsureUser(Session["HostEmail"].ToString());//Session["HostEmail"].ToString(); myItem["HostAction"] = "Initiate"; myItem["HostNote"] = ""; //myItem["Provider"] = ""; myItem["ProviderAction"] = "Initiate"; myItem["ProviderNote"] = ""; myItem["Status"] = "Finance Approval Needed"; //myItem["Modified"] = DateTime.Now; //myItem["Created"] = DateTime.Now; //myItem["Created By"] = hdf_StudentEmail.Value; //myItem["Modified By"] = hdf_StudentEmail.Value; try { myItem.Update(); //if (flp_Upload.HasFile) //{ // var attachment = new AttachmentCreationInformation(); // flp_Upload.SaveAs(Server.MapPath("~/Upload/" + flp_Upload.FileName)); // string FileUrl = Server.MapPath("~/Upload/" + flp_Upload.FileName); // string filePath = FileUrl; // attachment.FileName = Path.GetFileName(filePath); // attachment.ContentStream = new MemoryStream(System.IO.File.ReadAllBytes(filePath)); // Attachment att = myItem.AttachmentFiles.Add(attachment); //} var onlineCredentials = new SharePointOnlineCredentials(login, securePassword); clientContext.Credentials = onlineCredentials; clientContext.ExecuteQuery(); //string FileUrls = Server.MapPath("~/Upload/" + flp_Upload.FileName); //System.IO.File.Delete(FileUrls); lbl_Msg.Text = "Request (ID# " + refno + ") Generated Successfully"; lbl_Msg.Visible = true; div_msg.Visible = true; lnk_Generate.Enabled = false; } catch (Exception e) { Console.WriteLine(e.Message); } //Console.ReadLine(); }
static void Main(string[] args) { // Environment variables var siteUrl = ConfigurationManager.AppSettings["pwa:SiteUrl"]; var login = ConfigurationManager.AppSettings["pwa:Login"]; var password = ConfigurationManager.AppSettings["pwa:Password"]; var fieldId = new Guid(ConfigurationManager.AppSettings["pwa:FieldId"]); var resourceId = new Guid(ConfigurationManager.AppSettings["pwa:ResourceId"]); // Store password in secure string var securePassword = new SecureString(); foreach (var c in password) { securePassword.AppendChar(c); } // Project instance credentials var creds = new SharePointOnlineCredentials(login, securePassword); // Initiation of the client context using (var ctx = new ProjectContext(siteUrl)) { ctx.Credentials = creds; // Retrieve Enterprise Custom Field var field = ctx.CustomFields.GetByGuid(fieldId); // Load InernalName property, we will use it to get the value ctx.Load(field, x => x.InternalName); // Execture prepared query on server side ctx.ExecuteQuery(); var fieldInternalName = field.InternalName; // Retrieve recource by its Id var resource = ctx.EnterpriseResources.GetByGuid(resourceId); // ! // Load custom field value ctx.Load(resource, x => x[fieldInternalName]); ctx.ExecuteQuery(); // Update ECF value resource[fieldInternalName] = "Vitaly Zhukov"; ctx.EnterpriseResources.Update(); ctx.ExecuteQuery(); // Get ECF value from server ctx.Load(resource, x => x[fieldInternalName]); ctx.ExecuteQuery(); Console.WriteLine("ECF value: " + resource[fieldInternalName]); Console.ReadLine(); } }
internal static SPIaCConnection InstantiateSPOnlineConnection(Uri url, PSCredential credentials, PSHost host, bool currentCredentials, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false) { ClientContext context = new ClientContext(url.AbsoluteUri) { ApplicationName = Resources.ApplicationName, RequestTimeout = requestTimeout }; if (!currentCredentials) { try { SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(credentials.UserName, credentials.Password); context.Credentials = onlineCredentials; try { context.ExecuteQueryRetry(); } catch (IdcrlException iex) { System.Diagnostics.Trace.TraceError("Authentication Exception {0}", iex.Message); return(null); } catch (WebException wex) { System.Diagnostics.Trace.TraceError("Authentication Exception {0}", wex.Message); return(null); } 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); } } 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 SPIaCConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, credentials, url.ToString())); }
internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, PSCredential credentials, PSHost host, bool currentCredentials, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, 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 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(); } catch (ClientRequestException) { context.ExecutingWebRequest += Ctx_ExecutingWebRequest; context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password); } catch (ServerException) { context.ExecutingWebRequest += Ctx_ExecutingWebRequest; context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password); } } catch (ArgumentException) { // OnPrem? context.ExecutingWebRequest += Ctx_ExecutingWebRequest; 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.ExecutingWebRequest += Ctx_ExecutingWebRequest; context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password); } } 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, credentials, url.ToString(), tenantAdminUrl, PnPPSVersionTag)); }
static TestCommon() { #if NETSTANDARD2_0 // Load configuration in a way that's compatible with a .Net Core test project as well ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap { ExeConfigFilename = @"..\..\App.config" //Path to your config file }; configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); #endif // Read configuration data TenantUrl = AppSetting("SPOTenantUrl"); DevSiteUrl = AppSetting("SPODevSiteUrl"); O365AccountDomain = AppSetting("O365AccountDomain"); DefaultSiteOwner = AppSetting("DefaultSiteOwner"); if (string.IsNullOrEmpty(DefaultSiteOwner)) { #if !ONPREMISES DefaultSiteOwner = AppSetting("SPOUserName"); #else DefaultSiteOwner = $"{AppSetting("OnPremDomain")}\\{AppSetting("OnPremUserName")}"; #endif } #if !ONPREMISES if (string.IsNullOrEmpty(TenantUrl)) { throw new ConfigurationErrorsException("Tenant site Url in App.config are not set up."); } #endif if (string.IsNullOrEmpty(DevSiteUrl)) { throw new ConfigurationErrorsException("Dev site url in App.config are not set up."); } // Trim trailing slashes TenantUrl = TenantUrl.TrimEnd(new[] { '/' }); DevSiteUrl = DevSiteUrl.TrimEnd(new[] { '/' }); if (!string.IsNullOrEmpty(AppSetting("SPOCredentialManagerLabel"))) { var tempCred = Core.Utilities.CredentialManager.GetCredential(AppSetting("SPOCredentialManagerLabel")); UserName = tempCred.UserName; Password = tempCred.SecurePassword; // username in format domain\user means we're testing in on-premises if (tempCred.UserName.IndexOf("\\") > 0) { string[] userParts = tempCred.UserName.Split('\\'); Credentials = new NetworkCredential(userParts[1], tempCred.SecurePassword, userParts[0]); } #if !NETSTANDARD2_0 else { Credentials = new SharePointOnlineCredentials(tempCred.UserName, tempCred.SecurePassword); } #endif } else { #if !NETSTANDARD2_0 if (!String.IsNullOrEmpty(AppSetting("SPOUserName")) && !String.IsNullOrEmpty(AppSetting("SPOPassword"))) { UserName = AppSetting("SPOUserName"); var password = AppSetting("SPOPassword"); Password = EncryptionUtility.ToSecureString(password); Credentials = new SharePointOnlineCredentials(UserName, Password); } else #endif if (!String.IsNullOrEmpty(AppSetting("OnPremUserName")) && !String.IsNullOrEmpty(AppSetting("OnPremDomain")) && !String.IsNullOrEmpty(AppSetting("OnPremPassword"))) { Password = EncryptionUtility.ToSecureString(AppSetting("OnPremPassword")); Credentials = new NetworkCredential(AppSetting("OnPremUserName"), Password, AppSetting("OnPremDomain")); } else if (!String.IsNullOrEmpty(AppSetting("AppId")) && !String.IsNullOrEmpty(AppSetting("AppSecret"))) { AppId = AppSetting("AppId"); AppSecret = AppSetting("AppSecret"); } else if (!String.IsNullOrEmpty(AppSetting("AppId")) && !String.IsNullOrEmpty(AppSetting("HighTrustIssuerId"))) { AppId = AppSetting("AppId"); HighTrustCertificatePassword = AppSetting("HighTrustCertificatePassword"); HighTrustCertificatePath = AppSetting("HighTrustCertificatePath"); HighTrustIssuerId = AppSetting("HighTrustIssuerId"); if (!String.IsNullOrEmpty(AppSetting("HighTrustCertificateStoreName"))) { StoreName result; if (Enum.TryParse(AppSetting("HighTrustCertificateStoreName"), out result)) { HighTrustCertificateStoreName = result; } } if (!String.IsNullOrEmpty(AppSetting("HighTrustCertificateStoreLocation"))) { StoreLocation result; if (Enum.TryParse(AppSetting("HighTrustCertificateStoreLocation"), out result)) { HighTrustCertificateStoreLocation = result; } } HighTrustCertificateStoreThumbprint = AppSetting("HighTrustCertificateStoreThumbprint").Replace(" ", string.Empty); } else { throw new ConfigurationErrorsException("Tenant credentials in App.config are not set up."); } } }
//public async Task writeFile(string text) //{ // string sharePointXmlPath1 = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory.ToString(), "Sharepoint_Gaurav.xml"); // System.IO.File.WriteAllText(sharePointXmlPath1, text); //} public async Task <List <string> > SharepointSearchEng(string searchstr, string docType) { try { string userName = "******"; string password = "******"; //string[] searchString = searchstr.Split(','); //string docType = searchString[1]; //docType = docType.Replace(" ", String.Empty); //string searchStrFinal = searchString[0].Replace("&", "And"); //string searchWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(searchstr); string apiUrl = "https://murphyoil.sharepoint.com/_api/search/query?querytext=" + "\'" + searchstr + "\'"; var securePassword = new SecureString(); foreach (char c in password.ToCharArray()) { securePassword.AppendChar(c); } var credential = new SharePointOnlineCredentials(userName, securePassword); Uri uri = new Uri(apiUrl); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Method = "GET"; request.Credentials = credential; request.Headers[HttpRequestHeader.Cookie] = credential.GetAuthenticationCookie(new Uri(apiUrl), true); // SPO requires cookie authentication request.Headers["X-FORMS_BASED_AUTH_ACCEPTED"] = "f"; HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse(); Stream webStream = webResponse.GetResponseStream(); StreamReader responseReader = new StreamReader(webStream); string response = responseReader.ReadToEnd(); string xmlFilePath = Directory.GetCurrentDirectory(); string xmlFile = xmlFilePath + "SharePoint.xml"; string sharePointXmlPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory.ToString(), "Sharepoint.xml"); System.IO.File.WriteAllText(sharePointXmlPath, response); Console.WriteLine(response); // Console.WriteLine(response); XmlDocument xDoc = new XmlDocument(); xDoc.Load(sharePointXmlPath); // XmlNodeList str = xDoc.GetElementsByTagName("d:Cells"); // XmlNodeList str = xDoc.SelectNodes($"//d:Key[.='indexSystem']"); foreach (XmlNode node in xDoc.DocumentElement.ChildNodes) { if (KEYFOUND == 1) { break; } getChildNodes(node); } Console.WriteLine(OPATH); Console.WriteLine(KEYFOUND); OPATH = OPATH.Distinct().ToList(); if (KEYFOUND == 0) { return(OPATH); } //get the pattern from user and match if (searchstr.Equals("All", comparisonType: StringComparison.OrdinalIgnoreCase)) { patternMatch = 1; return(OPATH); } else { foreach (var oPath in OPATH) { Match m = Regex.Match(oPath, docType, RegexOptions.IgnoreCase); if (m.Success) { Console.WriteLine("Found '{0}' at position {1}.", m.Value, m.Index); finalPathList.Add(oPath); patternMatch = 1; } } } if (patternMatch == 0) { finalPathList.Add("Not Found"); return(finalPathList); } else { return(finalPathList); } } catch { Console.WriteLine("Exceptions"); finalPathList.Add("Not Found"); return(finalPathList); } }
private static void GetFicheiro() { var url = "https://mpcjellycode.sharepoint.com/sites/Site"; var username = "******"; var password = "******"; var securedPassword = new SecureString(); password.ToList().ForEach(securedPassword.AppendChar); var credentials = new SharePointOnlineCredentials(username, securedPassword); using (var clientContext = new ClientContext(url)) { clientContext.Credentials = credentials; var web = clientContext.Web; clientContext.Load(web, website => website.ServerRelativeUrl); clientContext.ExecuteQuery(); Console.WriteLine(clientContext.ServerVersion.ToString(4)); clientContext.Load(web.Lists, GetListQuery()); clientContext.ExecuteQuery(); foreach (List list in web.Lists) { if (list.Title != "Documents") { continue; } Console.WriteLine("List title is: " + list.Title); Console.WriteLine(list.Id); Console.WriteLine("RootFolder: " + list.RootFolder.ServerRelativePath.DecodedUrl); //Console.WriteLine(string.Join(", ", list.Fields.Select(x => x.InternalName))); var ids = list.RootFolder.Files.Select(x => x.UniqueId).ToList(); Console.WriteLine("Files: " + string.Join(Environment.NewLine, list.RootFolder.Files.Select(x => x.ServerRelativePath.DecodedUrl + " " + x.UniqueId))); Console.WriteLine("Subfolders: " + string.Join(", ", list.RootFolder.Folders.Select(x => x.ServerRelativePath.DecodedUrl))); Console.WriteLine(list.EnableAttachments); foreach (var id in ids) { var file = web.GetFileById(id); clientContext.Load(file); clientContext.ExecuteQuery(); var fullPath = $"{file.ServerRelativeUrl}"; var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fullPath); var memoryStream = new MemoryStream(); fileInfo.Stream.CopyTo(memoryStream); var bytes = memoryStream.ToArray(); } Console.WriteLine(Environment.NewLine); } Console.ReadLine(); } }
public static void getProjects() { // start by requesting the first page int currentPage = 1; var url = "https://rest.tsheets.com/api/v1/reports/project"; var tsheetsApi = new RestClient(_connection, _authProvider); var filters = new Dictionary <string, string>(); filters.Add("start_date", ConfigurationManager.AppSettings.Get("start_date")); filters.Add("end_date", ConfigurationManager.AppSettings.Get("end_date")); //filters.Add("end_date", DateTime.Now.ToString("yyyy-MM-dd")); filters["per_page"] = "50"; List <AllTimeSheetData> allTimeSheetData = new List <AllTimeSheetData>(); List <SupplementalData> supplementalData = new List <SupplementalData>(); bool moreData = true; while (moreData) { filters["page"] = currentPage.ToString(); var timesheetData = tsheetsApi.Get(ObjectType.Timesheets, filters); var timesheetsObject = JObject.Parse(timesheetData); var allTimeSheets = timesheetsObject.SelectTokens("results.timesheets.*"); var supplemental_data = timesheetsObject.SelectTokens("supplemental_data.jobcodes.*"); // see if we have more pages to retrieve moreData = bool.Parse(timesheetsObject.SelectToken("more").ToString()); // increment to the next page currentPage++; //NOTE: Fetch all timesheet data foreach (var timesheet in allTimeSheets) { try { allTimeSheetData.Add(JsonConvert.DeserializeObject <AllTimeSheetData>(timesheet.ToString())); int cs = 0; foreach (var item in timesheet["customfields"]) { if (cs == 0) { allTimeSheetData[count].customfields.FirstColumn = item.First.ToString(); } if (cs == 1) { allTimeSheetData[count].customfields.SecondColumn = item.First.ToString(); } if (cs == 2) { allTimeSheetData[count].customfields.ThirdColumn = item.First.ToString(); } if (cs == 3) { allTimeSheetData[count].customfields.FourthColumn = item.First.ToString(); } if (cs == 4) { allTimeSheetData[count].customfields.FifthColumn = item.First.ToString(); } cs++; } } catch (Exception ex) { } count++; } //NOTE: Fetch all supplement data foreach (var supplemental in supplemental_data) { supplementalData.Add(JsonConvert.DeserializeObject <SupplementalData>(supplemental.ToString())); } } List <string> projectNames = new List <string>(); foreach (var sd in supplementalData) { if (sd.parent_id == 0) { #region "Updating Project ID in LL Internal Tasks List" if (sd.name.Substring(0, 5).StartsWith("LL")) { string name = sd.name.Substring(0, 5); if (!projectNames.Contains(name)) { projectNames.Add(name); string PMPSiteUrl = "https://leonlebeniste.sharepoint.com/sites/PMP"; ClientContext clientContext = new ClientContext(PMPSiteUrl); List oList = clientContext.Web.Lists.GetByTitle("LL Projects List"); CamlQuery camlQuery = new CamlQuery(); ListItemCollection collListItem = oList.GetItems(camlQuery); clientContext.Load(collListItem); string sharepoint_Login = ConfigurationManager.AppSettings.Get("sharepoint_Login_PMP"); string sharepoint_Password = ConfigurationManager.AppSettings.Get("sharepoint_Password_PMP"); var securePassword = new SecureString(); foreach (char c in sharepoint_Password) { securePassword.AppendChar(c); } var onlineCredentials = new SharePointOnlineCredentials(sharepoint_Login, securePassword); clientContext.Credentials = onlineCredentials; clientContext.ExecuteQuery(); foreach (ListItem oListItem in collListItem) { if (name == Convert.ToString(oListItem["ProjectNumber"])) { //NOTE: Update Project ID in list. ListItem myItem = oList.GetItemById(Convert.ToString(oListItem["ID"])); myItem["ProjID"] = sd.id; try { myItem.Update(); clientContext.Credentials = onlineCredentials; clientContext.ExecuteQuery(); Console.WriteLine("Project ID Successfully Update on: " + name); } catch (Exception e) { Console.WriteLine(e.Message); } } } } } #endregion List <SupplementalData> spChildItems = supplementalData.Where(x => x.parent_id == sd.id).ToList(); foreach (var spChildItem in spChildItems) { List <AllTimeSheetData> allMilestoneItems = allTimeSheetData.Where(x => x.jobcode_id == spChildItem.id).ToList(); long project_id = sd.id; string taskName = spChildItem.name; //NOTE: Logic for upating PMP sites milestones. GetPMPSitesAndSubSiteTasks(project_id, taskName, allMilestoneItems, sd); } } } //foreach (var td in allTimeSheetData) //{ // List<SupplementalData> spItem = supplementalData.Where(x => x.id == td.jobcode_id).ToList(); // if (spItem.Count > 0) // { // long project_id = supplementalData.Where(x => x.id == td.jobcode_id).Select(x => x.project_id).FirstOrDefault(); // if (project_id > 0) // { #region trial tenant list //string sharepoint_Login = ConfigurationManager.AppSettings.Get("sharepoint_Login"); //string sharepoint_Password = ConfigurationManager.AppSettings.Get("sharepoint_Password"); //var securePassword = new SecureString(); //foreach (char c in sharepoint_Password) //{ // securePassword.AppendChar(c); //} //string siteUrl = ConfigurationManager.AppSettings.Get("sharepoint_SiteUrl"); //ClientContext clientContext = new ClientContext(siteUrl); //List myList = clientContext.Web.Lists.GetByTitle(ConfigurationManager.AppSettings.Get("sharepoint_ListName")); //NOTE: Check if project id is available in list //TimeSpan duration = new TimeSpan(); //if (!string.IsNullOrWhiteSpace(sd.duration)) //{ // duration = TimeSpan.FromSeconds(Convert.ToInt64(sd.duration)); // string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", // duration.Hours, // duration.Minutes, // duration.Seconds, // duration.Milliseconds); //} //long ID = CheckItemAlreadyExists(clientContext, sharepoint_Login, securePassword, project_id); //if (ID > 0) //{ // ListItem myItem = myList.GetItemById(ID.ToString()); // myItem["Title"] = sd.id; // myItem["user_id"] = sd.user_id; // myItem["jobcode_id"] = sd.jobcode_id; // myItem["project_id"] = project_id; // myItem["Duration"] = duration; // myItem.Update(); // clientContext.ExecuteQuery(); //} //else //{ // ListItemCreationInformation itemInfo = new ListItemCreationInformation(); // ListItem myItem = myList.AddItem(itemInfo); // myItem["Title"] = sd.id; // myItem["user_id"] = sd.user_id; // myItem["jobcode_id"] = sd.jobcode_id; // myItem["project_id"] = project_id; // myItem["Duration"] = duration; // try // { // myItem.Update(); // var onlineCredentials = new SharePointOnlineCredentials(sharepoint_Login, securePassword); // clientContext.Credentials = onlineCredentials; // clientContext.ExecuteQuery(); // Console.WriteLine("Item Inserted Successfully project_id: " + project_id); // } // catch (Exception e) // { // Console.WriteLine(e.Message); // } //} #endregion // string taskName = spItem.Select(x => x.name).FirstOrDefault(); // //NOTE: Logic for upating PMP sites milestones. // GetPMPSitesAndSubSiteTasks(project_id, taskName, allTimeSheetData, spItem); // } // } //} }
public static void GetPMPSubSiteTaskLists(string siteUrl, string sharepoint_Login, SecureString securePassword, string taskName, List <AllTimeSheetData> allMilestoneItems, SupplementalData sd) { ClientContext clientContext = new ClientContext(siteUrl); List oList = clientContext.Web.Lists.GetByTitle("Schedule"); CamlQuery camlQuery = new CamlQuery(); ListItemCollection collListItem = oList.GetItems(camlQuery); clientContext.Load(collListItem); var onlineCredentials = new SharePointOnlineCredentials(sharepoint_Login, securePassword); clientContext.Credentials = onlineCredentials; clientContext.ExecuteQuery(); //var groupItem = allTimeSheetData.Where(x => x.jobcode_id == spItem.Select(y => y.id).FirstOrDefault()).GroupBy(x => x.id); long installation = 0; long projectManagement = 0; long fabrication = 0; long preProduction = 0; string installationVal = string.Empty; string projectManagementVal = string.Empty; string fabricationVal = string.Empty; string preProductionVal = string.Empty; foreach (var item in allMilestoneItems) { if (item.customfields.SecondColumn == "Installation") { installation = installation + Convert.ToInt64(item.duration); } else if (item.customfields.SecondColumn == "Project Management") { projectManagement = projectManagement + Convert.ToInt64(item.duration); } else if (item.customfields.SecondColumn == "Fabrication") { fabrication = fabrication + Convert.ToInt64(item.duration); } else if (item.customfields.SecondColumn == "Pre Production") { preProduction = preProduction + Convert.ToInt64(item.duration); } } TimeSpan duration = new TimeSpan(); duration = TimeSpan.FromSeconds(Convert.ToInt64(installation)); installationVal = string.Format("{0:D2}.{1:D2}", duration.Hours, duration.Minutes, duration.Seconds, duration.Milliseconds); duration = new TimeSpan(); duration = TimeSpan.FromSeconds(Convert.ToInt64(projectManagement)); projectManagementVal = string.Format("{0:D2}.{1:D2}", duration.Hours, duration.Minutes, duration.Seconds, duration.Milliseconds); duration = new TimeSpan(); duration = TimeSpan.FromSeconds(Convert.ToInt64(fabrication)); fabricationVal = string.Format("{0:D2}.{1:D2}", duration.Hours, duration.Minutes, duration.Seconds, duration.Milliseconds); duration = new TimeSpan(); duration = TimeSpan.FromSeconds(Convert.ToInt64(preProduction)); preProductionVal = string.Format("{0:D2}.{1:D2}", duration.Hours, duration.Minutes, duration.Seconds, duration.Milliseconds); foreach (ListItem oListItem in collListItem) { if (Convert.ToString(oListItem["Title"]) == taskName) { ListItemCreationInformation itemInfo = new ListItemCreationInformation(); ListItem myItem = oList.GetItemById(Convert.ToString(oListItem["ID"])); myItem["Actual_x0020_Install"] = installationVal; myItem["Actual_x0020_Project_x0020_Manag"] = projectManagementVal; myItem["Actual_x0020_Fabrication"] = fabricationVal; myItem["Actual_x0020_Pre_x0020_Productio"] = preProductionVal; try { myItem.Update(); clientContext.Credentials = onlineCredentials; clientContext.ExecuteQuery(); Console.WriteLine("Item Updated Successfully name: " + taskName); } catch (Exception e) { Console.WriteLine(e.Message); } } } }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req, TraceWriter log) { log.Info($"Webhook was triggered!"); try { var jsonContent = await req.Content.ReadAsStringAsync(); log.Info(jsonContent); dynamic data = JsonConvert.DeserializeObject(jsonContent); // TODO: Rather than using web application settings, we should be using the Azure Key Vault for // credentials var connectionString = WebUtility.UrlDecode(WebUtility.UrlDecode(data.SpoSiteName.ToString())); var documentSetUrl = string.Empty; var applicationFolder = data.ApplicationFolder.ToString(); var permitFolderName = data.PermitFolder.ToString(); using (ClientContext clientContext = new ClientContext(connectionString)) { var dummy = new TaxonomyItem(clientContext, null); var username = ConfigurationManager.ConnectionStrings["UserName"].ConnectionString; var password = ConfigurationManager.ConnectionStrings["Password"].ConnectionString; var securePassword = new SecureString(); foreach (char p in password) { securePassword.AppendChar(p); } var credentials = new SharePointOnlineCredentials(username, securePassword); clientContext.Credentials = credentials; log.Info("Got client context and set credentials"); log.Info(string.Format("ListName is {0}", data.ListName.ToString())); var list = clientContext.Web.Lists.GetByTitle(data.ListName.ToString()); var rootFolder = list.RootFolder; var permitFolderUrl = String.Format("{0}/{1}", data.ListName.ToString(), permitFolderName); var applicationFolderUrl = String.Format("{0}/{1}", permitFolderUrl, applicationFolder); // Get the Permit folder content type var ctPermit = GetByName(list.ContentTypes, data.PermitContentType.ToString()); log.Info(string.Format("Permit Content Type Id is {0}", ctPermit.Id.StringValue)); // Create permit sub folder inside list root folder if it doesn't exist var permitFolder = CreateSubFolderIfDoesntExist(clientContext, permitFolderName, rootFolder, ctPermit, data.PermitFolder.ToString()); log.Info(string.Format("Folder is {0}", permitFolder.Name)); // Get the Application document set content type var ctApplication = GetByName(list.ContentTypes, data.ApplicationContentType.ToString()); log.Info(string.Format("Applicaction Content Type Id is {0}", ctApplication.Id.StringValue)); // Create the Document Set try { var ds = DocumentSet.Create(clientContext, permitFolder, applicationFolder, ctApplication.Id); clientContext.ExecuteQuery(); documentSetUrl = ds.Value; log.Info(string.Format("Document Set Id is {0}", documentSetUrl)); } catch (ServerException ex) when(ex.Message.StartsWith("A document, folder or document set with the name") && ex.Message.EndsWith("already exists.")) { documentSetUrl = "Document set exists already"; log.Info(string.Format("Handling {0} - {1}", ex.Source, ex.Message)); } } return(req.CreateResponse(HttpStatusCode.OK, "{ \"DocumentSetUrl\" : \"" + documentSetUrl + "\" }")); } catch (Exception ex) { log.Info(string.Format("{0} Exception {1}", ex.Source, ex.ToString())); return(req.CreateResponse(HttpStatusCode.InternalServerError, "Critial error creating SharePoint DocumentSet: " + ex.Message)); } }
static void Main(string[] args) { #region Authentication string username = "******"; string password = "******"; SecureString securepassword = new SecureString(); foreach (char c in password.ToCharArray()) { securepassword.AppendChar(c); } var onlineCredentials = new SharePointOnlineCredentials(username, securepassword); #endregion #region Index for columns /* * (1) Number -- SR_x0020_Number -- SR_x0020_Number * (2) Number -- Age -- Age * (3) Number -- Total_x0020_SR_x0020_Labor_x0020 -- Total_x0020_SR_x0020_Labor_x0020 * (4) Person or Group -- SR_x0020_Owner -- SR_x0020_Owner * (5) Single line of text -- Support_x0020_Topic -- Support_x0020_Topic * (6) Person or Group -- SME_x0020_Reviewer -- SME_x0020_Reviewer * (7) Single line of text -- Comments -- Comments * (8) Single line of text -- Opportunities -- Opportunities * (9) Person or Group -- Last_x0020_week_x0020_SME_x0020_ -- Last_x0020_week_x0020_SME_x0020_ * (10)Single line of text -- Last_x0020_week_x0020_Comments -- Last_x0020_week_x0020_Comments * (11)Single line of text -- Last_x0020_week_x0020_Opportunit -- Last_x0020_week_x0020_Opportunit * */ #endregion string siteurl = "<<SPO Url>>"; string xlsfile = @"C:\Desktop\<<Excel file name>>.xls"; string listname = "Cust List"; #region Opening the Excel file and defining the columns Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(xlsfile); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Excel.Range xlRange = xlWorksheet.UsedRange; int rowCount = xlRange.Rows.Count; int colCount = xlRange.Columns.Count; List <string> colList = new List <string>(); for (int j = 1; j <= colCount; j++) { // Adjusting the Internal name for certain columns which has a longer name if (xlRange.Cells[1, j].Value2.ToString() == "Total SR Labor (Mins)") { colList.Add("Total_x0020_SR_x0020_Labor_x0020"); } else if (xlRange.Cells[1, j].Value2.ToString() == "Last week SME Reviewer") { colList.Add("Last_x0020_week_x0020_SME_x0020_"); } else if (xlRange.Cells[1, j].Value2.ToString() == "Last week Opportunities") { colList.Add("Last_x0020_week_x0020_Opportunit"); } else { colList.Add(xlRange.Cells[1, j].Value2.ToString().Replace(" ", "_x0020_")); // Converting all spaces to it's hexadecimal value, _x0020_ } } Console.WriteLine("Opened the Excel file successfully....."); try { using (ClientContext context = new ClientContext(siteurl)) { context.Credentials = onlineCredentials; Web oweb = context.Web; context.Load(oweb); context.ExecuteQuery(); Console.WriteLine("Successfully connected to the SPO site....."); List olist = oweb.Lists.GetByTitle(listname); ListItemCreationInformation lici = new ListItemCreationInformation(); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "<View><RowLimit>200</RowLimit></View>"; ListItemCollection allitems = olist.GetItems(camlQuery); context.Load(allitems); context.ExecuteQuery(); #region Iterting the field names within the list //FieldCollection flc = olist.Fields; //context.Load(flc); //context.ExecuteQuery(); //foreach (Field f in flc) //{ // Console.WriteLine(f.TypeDisplayName + " -- " + f.InternalName + " -- " + f.StaticName); //} #endregion #endregion #region Add a single list item //ListItem olistitem = olist.AddItem(lici); //for (int j = 1; j <= colCount; j++) //{ // if (xlRange.Cells[2, j].Value2 == null) // continue; // else if (j == 4 || j == 6 || j == 9) // olistitem[colList[j - 1]] = oweb.EnsureUser(xlRange.Cells[2, j].Value2.ToString() + "@microsoft.com"); // else // olistitem[colList[j - 1]] = xlRange.Cells[2, j].Value2.ToString(); //} //olistitem.Update(); //context.ExecuteQuery(); #endregion for (int i = 2; i <= rowCount; i++) { ListItem olistitem = olist.AddItem(lici); ListItem existing = null; if (allitems.Count > 0) { existing = CheckSR(allitems, xlRange.Cells[i, 1].Value2.ToString()); } if (existing != null) { existing["Age"] = xlRange.Cells[i, 2].Value2.ToString(); existing["Total_x0020_SR_x0020_Labor_x0020"] = xlRange.Cells[i, 3].Value2.ToString(); existing["SR_x0020_Owner"] = oweb.EnsureUser(xlRange.Cells[i, 4].Value2.ToString() + "@<<email-domain>>"); existing["Support_x0020_Topic"] = xlRange.Cells[i, 5].Value2.ToString(); ClientResult <PrincipalInfo> persons = Utility.ResolvePrincipal(context, oweb, ((Microsoft.SharePoint.Client.FieldLookupValue)(existing["SME_x0020_Reviewer"])).LookupValue, PrincipalType.User, PrincipalSource.All, null, false); context.ExecuteQuery(); PrincipalInfo person = persons.Value; existing["Last_x0020_week_x0020_SME_x0020_"] = oweb.EnsureUser(person.Email); existing["Last_x0020_week_x0020_Comments"] = existing["Comments"]; existing["Last_x0020_week_x0020_Opportunit"] = existing["Opportunities"]; if (xlRange.Cells[i, 6].Value2 != null) { existing["SME_x0020_Reviewer"] = oweb.EnsureUser(xlRange.Cells[i, 6].Value2.ToString() + "@<<email-domain>>"); } if (xlRange.Cells[i, 7].Value2 != null) { existing["Comments"] = xlRange.Cells[i, 7].Value2.ToString(); } if (xlRange.Cells[i, 8].Value2 != null) { existing["Opportunities"] = xlRange.Cells[i, 8].Value2.ToString(); } existing.Update(); context.ExecuteQuery(); continue; } for (int j = 1; j <= colCount; j++) { if (xlRange.Cells[i, j].Value2 == null) { continue; } else if (j == 4 || j == 6 || j == 9) { olistitem[colList[j - 1]] = oweb.EnsureUser(xlRange.Cells[i, j].Value2.ToString() + "@microsoft.com"); } else { olistitem[colList[j - 1]] = xlRange.Cells[i, j].Value2.ToString(); } } olistitem.Update(); context.ExecuteQuery(); lici = null; } } Console.WriteLine("Done!!"); Console.ReadKey(); } catch (Exception ex) { Console.WriteLine("ERROR:- " + ex.Message); Console.ReadKey(); } #region Closing the Excel connections finally { xlWorkbook.Close(true, null, null); xlApp.Quit(); releaseObject(xlWorksheet); releaseObject(xlWorkbook); releaseObject(xlApp); Console.WriteLine("Excel file closed properly....."); } #endregion }
/// <summary> /// Registra un nuevo archivo en el servidor de SharePoint /// </summary> /// <param name="hayError">variable que contiene el mensaje de error al registrar</param> /// <param name="listName">biblioteca de donde se encontrará el archivo</param> /// <param name="folderName">nombre de carpeta del archivo</param> /// <param name="fileName">nombre del archivo</param> /// <param name="myFile">stream del archivo</param> /// <param name="prmSiteURL">URL del servidor SharePoint</param> /// <param name="prmCredenciales">Credenciales de acceso al servidor SharePoint</param> /// <returns>Indicador con el resultado de la operación</returns> public ProcessResult <Object> RegistraArchivoSharePoint(ref string hayError, string listName, string folderName, string fileName, MemoryStream myFile, string prmSiteURL = null, SharePointOnlineCredentials prmCredenciales = null) { ProcessResult <Object> resultado = new ProcessResult <Object>(); string siteUrl = string.Empty; if (string.IsNullOrEmpty(prmSiteURL)) { siteUrl = RetornaSiteUrlSharePoint(); } else { siteUrl = prmSiteURL; } try { using (ClientContext clientContext = new ClientContext(siteUrl)) { Web webSite = clientContext.Web; if (prmCredenciales == null) { clientContext.Credentials = RetornaCredencialesServer(); } else { clientContext.Credentials = prmCredenciales; } #region CreacionListaPrincipal en caso no exista List existeLista = null; ListCollection lstCollection = clientContext.Web.Lists; IEnumerable <List> misLitas = clientContext.LoadQuery(lstCollection.Include(list => list.Title)); clientContext.ExecuteQuery(); existeLista = misLitas.FirstOrDefault(lista => lista.Title.ToLower() == listName.ToLower()); if (existeLista == null) { ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = listName; creationInfo.TemplateType = (int)ListTemplateType.DocumentLibrary; List listGeneral = webSite.Lists.Add(creationInfo); listGeneral.Description = Pe.Stracon.SGC.Infraestructura.Core.Context.DatosConstantes.ArchivosContrato.DescripcionBibliotecaSHP; listGeneral.Update(); clientContext.ExecuteQuery(); } #endregion #region crearDirectorio var folder = CreateCarpeta(clientContext.Web, listName, folderName); #endregion #region listaDirectorio List listaSitio = clientContext.Web.Lists.GetByTitle(listName); clientContext.Load(listaSitio); clientContext.Load(listaSitio.RootFolder); clientContext.ExecuteQuery(); var serverRelativeURLFile = listaSitio.RootFolder.ServerRelativeUrl.ToString() + (string.IsNullOrEmpty(folderName) ? "" : "/" + folderName) + "/" + fileName; #endregion #region GenerarBytesSHP Stream stmMyFile; byte[] newFile = myFile.ToArray(); stmMyFile = new MemoryStream(newFile); #endregion #region CopiarStreamArchivo Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, serverRelativeURLFile, stmMyFile, true); #endregion #region Leer Nuevo Archivo clientContext.Load(webSite); clientContext.ExecuteQuery(); Microsoft.SharePoint.Client.File getNewFile = webSite.GetFileByServerRelativeUrl(serverRelativeURLFile); clientContext.Load(getNewFile); #endregion #region Cargar Datos ListItem myItem = getNewFile.ListItemAllFields; clientContext.Load(myItem); clientContext.Load(myItem.File); clientContext.ExecuteQuery(); resultado.Result = myItem.Id; #endregion } } catch (Exception ex) { hayError = ex.Message; RegistrarLogErrores(siteUrl, "SGC - Registrar Archivo", ex.Message); resultado.Result = -1; resultado.IsSuccess = false; resultado.Exception = new ApplicationLayerException <SharePointService>(ex); } return(resultado); }
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) { // legacy auth? var authManager = new OfficeDevPnP.Core.AuthenticationManager(); context = PnPClientContext.ConvertFrom(authManager.GetAzureADCredentialsContext(url.ToString(), credentials.UserName, credentials.Password)); context.ExecuteQueryRetry(); } #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); }
public void sentdatatoSPLIst() { int sem = 0; int Year = LibraryMOD.SeperateTerm(LibraryMOD.GetCurrentTerm(), out sem); int iYear = Year; int iSem = sem; string sSemester = LibraryMOD.GetSemesterString(iSem); string login = "******"; //give your username here string password = "******"; //give your password var securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } string siteUrl = "https://ectacae.sharepoint.com/sites/ECTPortal/eservices/studentservices"; ClientContext clientContext = new ClientContext(siteUrl); Microsoft.SharePoint.Client.List myList = clientContext.Web.Lists.GetByTitle("Students_Requests"); ListItemCreationInformation itemInfo = new ListItemCreationInformation(); Microsoft.SharePoint.Client.ListItem myItem = myList.AddItem(itemInfo); string refno = Create16DigitString(); myItem["Title"] = refno; //myItem["RequestID"] = refno; myItem["Year"] = iYear; myItem["Semester"] = iSem; myItem["Request"] = "<b>Service ID:</b> " + lbl_ServiceID.Text + "<br/> <b>Service Name:</b> " + lbl_ServiceNameEn.Text + " (" + lbl_ServiceNameAr.Text + " )"; myItem["RequestNote"] = txt_Remarks.Text.Trim(); myItem["ServiceID"] = lbl_ServiceID.Text; myItem["Fees"] = hdf_Price.Value; //myItem["Requester"] = clientContext.Web.EnsureUser(hdf_StudentEmail.Value); myItem["Requester"] = clientContext.Web.EnsureUser("*****@*****.**"); myItem["StudentID"] = lbl_StudentID.Text; myItem["StudentName"] = lbl_StudentName.Text; myItem["Contact"] = lbl_StudentContact.Text; myItem["Finance"] = clientContext.Web.EnsureUser("*****@*****.**"); myItem["FinanceAction"] = "Initiate"; myItem["FinanceNote"] = ""; myItem["Host"] = clientContext.Web.EnsureUser("*****@*****.**");//Session["HostEmail"].ToString(); myItem["HostAction"] = "Initiate"; myItem["HostNote"] = ""; //myItem["Provider"] = ""; myItem["ProviderAction"] = "Initiate"; myItem["ProviderNote"] = ""; myItem["Status"] = "Finance Approval Needed"; //myItem["Modified"] = DateTime.Now; //myItem["Created"] = DateTime.Now; //myItem["Created By"] = hdf_StudentEmail.Value; //myItem["Modified By"] = hdf_StudentEmail.Value; try { myItem.Update(); //if (flp_Upload.HasFile) //{ // var attachment = new AttachmentCreationInformation(); // flp_Upload.SaveAs(Server.MapPath("~/Upload/" + flp_Upload.FileName)); // string FileUrl = Server.MapPath("~/Upload/" + flp_Upload.FileName); // string filePath = FileUrl; // attachment.FileName = Path.GetFileName(filePath); // attachment.ContentStream = new MemoryStream(System.IO.File.ReadAllBytes(filePath)); // Attachment att = myItem.AttachmentFiles.Add(attachment); //} var onlineCredentials = new SharePointOnlineCredentials(login, securePassword); clientContext.Credentials = onlineCredentials; clientContext.ExecuteQuery(); //string FileUrls = Server.MapPath("~/Upload/" + flp_Upload.FileName); //System.IO.File.Delete(FileUrls); lbl_Msg.Text = "Request (ID# " + refno + ") Generated Successfully"; lbl_Msg.Visible = true; div_msg.Visible = true; lnk_Generate.Enabled = false; } catch (Exception e) { Console.WriteLine(e.Message); } //Console.ReadLine(); }
public void LeerlingBewarenInSharepointList(Leerling teBewarenLeerling, String schooljaar) { var securePassword = new SecureString(); foreach (var c in paswoord) { securePassword.AppendChar(c); } credentials = new SharePointOnlineCredentials(userName, securePassword); //context = new ClientContext("https://technischescholenmechel.sharepoint.com/TSM ICT/"); context = new ClientContext("https://technischescholenmechel.sharepoint.com/TSM Globaal/"); context.Credentials = credentials; // Het sharepoint web binnenhalen. Web web = context.Web; // De bestaande lijst die we nodig hebben binnenhalen "Testlijst - Inschrijvingen eID". //List announcementsList = context.Web.Lists.GetByTitle("Testlijst - Inschrijvingen eID"); List announcementsList = context.Web.Lists.GetByTitle("MS Inschrijvingen - TEST"); // List item aanmaken op basis van de leerling die we willen aanmaken in sharepoint //standaard aanmaak info gegevens aanmaken. indien nodig kan je hier bepaalde gegevens specifieren ListItemCreationInformation itemAanmaakInfo = new ListItemCreationInformation(); //list item aanmaken en linken met opgevraagde lijst ListItem nieuwItem = announcementsList.AddItem(itemAanmaakInfo); //NAAM nieuwItem["Title"] = teBewarenLeerling.naam; //VOORNAAM nieuwItem["_x006c_a76"] = teBewarenLeerling.voornaam; //NATIONAALNUMMER nieuwItem["mofc"] = teBewarenLeerling.nationaalnummer; //GEBOORTEPLAATS nieuwItem["_x0071_py8"] = teBewarenLeerling.geboorteplaats; //GEBOORTEDATUM nieuwItem["lpcu"] = teBewarenLeerling.geboorteDatumOmzetenDateTime(); //STRAAT nieuwItem["leerling_adres_straat"] = teBewarenLeerling.straatZonderNr; //NR nieuwItem["leerling_adres_nummer"] = teBewarenLeerling.huisNr; //BUS nieuwItem["leerling_adres_bus"] = teBewarenLeerling.bus; //POSTCODE nieuwItem["leerling_adres_postcode"] = teBewarenLeerling.postcode; //GEMEENTE nieuwItem["leerling_adres_gemeente"] = teBewarenLeerling.gemeente; //LAND nieuwItem["leerling_adres_land"] = teBewarenLeerling.land; //NATIONALITEIT nieuwItem["eo9y"] = teBewarenLeerling.nationaliteit; //SCHOOLJAAR nieuwItem["ins_schooljaar"] = schooljaar; //GESLACHT if (teBewarenLeerling.geslacht == "M") { nieuwItem["leerling_geslacht"] = "Man"; } else { nieuwItem["leerling_geslacht"] = "Vrouw"; } //nieuwe gegevens updaten in item lijst nieuwItem.Update(); //de aanmaak query uitvoeren tegenover de sharepoint server. context.ExecuteQuery(); //laten weten dat leerling aangemaakt is DialogResult dResult = MessageBox.Show("Leerling is aangemaakt. Verder gaan op inschrijvingssite ?", "Inschrijving resultaat", MessageBoxButtons.OKCancel); if (dResult == DialogResult.OK) { if (!(VraagContentId(teBewarenLeerling) == "Leerling niet gevonden")) { String url = "https://technischescholenmechel.sharepoint.com/TSM%20Globaal/Lists/MS%20Inschrijvingen%20%20TEST/Item/editifs.aspx?List=fac6218d%2D5da6%2D4dd4%2D9f27%2Dd51e2306b156&ID=" + VraagContentId(teBewarenLeerling) + "&Source=https%3A%2F%2Ftechnischescholenmechel%2Esharepoint%2Ecom%2FTSM%2520Globaal%2FLists%2FMS%2520Inschrijvingen%2520%2520TEST%2FOverzicht%2Easpx&ContentTypeId=0x0100F6FB02CA6D57EC41B63B32BBDE8F5824"; Process.Start(url); } else { MessageBox.Show("Leerling niet gevonden om Sharepoint te openen.", "Melding"); } } }
/// <summary> /// Creating client context along with authentication /// </summary> /// <param name="url">Site URL</param> /// <param name="userId">User id</param> /// <param name="password">Password to authenticate</param> /// <param name="isDeployedOnAzure">To resolve what kind of credentials are to be use</param> /// <returns>Client context</returns> public static ClientContext ConfigureClientContext(string url, string userId, string password, bool isDeployedOnAzure) { using (var securePassword = new SecureString()) { if (!string.IsNullOrWhiteSpace(userId) && !string.IsNullOrWhiteSpace(password) && !string.IsNullOrWhiteSpace(url)) { foreach (char character in password) { securePassword.AppendChar(character); } using (ClientContext clientContext = new ClientContext(url)) { object onlineCredentials; if (isDeployedOnAzure) { onlineCredentials = new SharePointOnlineCredentials(userId, securePassword); clientContext.Credentials = (SharePointOnlineCredentials)onlineCredentials; // Secure the credentials and generate the SharePoint Online Credentials } else { onlineCredentials = new NetworkCredential(userId, securePassword); clientContext.Credentials = (NetworkCredential)onlineCredentials; // Assign On Premise credentials to the Client Context } clientContext.ExecuteQuery(); return clientContext; } } return null; } }
static void Main(string[] args) { ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true; FiddlerApplication.AfterSessionComplete += FiddlerApplication_AfterSessionComplete; FiddlerApplication.BeforeRequest += FiddlerApplication_BeforeRequest; FiddlerApplication.BeforeResponse += FiddlerApplication_BeforeResponse; FiddlerApplication.Startup(9898, FiddlerCoreStartupFlags.Default); try { ClientContext context = new ClientContext("https://victorvv.sharepoint.com"); SecureString se = new SecureString(); foreach (var cc in "1qaz2wsxE") { se.AppendChar(cc); } var cre = new SharePointOnlineCredentials("*****@*****.**", se); var cookie = cre.GetAuthenticationCookie(new Uri("https://victorvv.sharepoint.com")); } catch (Exception e) { } FiddlerApplication.Shutdown(); Console.ReadLine(); }