/// <summary> /// Default Contructor /// </summary> /// <param name="webUrl">SharePoint web url</param> /// <param name="userId">userID</param> /// <param name="pwd">password</param> internal ConnectPk(string webUrl, string userId, string pwd) { this.webUrl = webUrl; SecureString password = new SecureString(); pwd.ToList().ForEach(password.AppendChar); this.credential = new SP.SharePointOnlineCredentials(userId, password); }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); var models = new List <SPUserAlertDefinition>(); try { var creds = SPIaCConnection.CurrentConnection.GetActiveCredentials(); var newcreds = new System.Net.NetworkCredential(creds.UserName, creds.Password); var spourl = new Uri(this.ClientContext.Url); var spocreds = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(creds.UserName, creds.Password); var spocookies = spocreds.GetAuthenticationCookie(spourl); var spocontainer = new System.Net.CookieContainer(); spocontainer.SetCookies(spourl, spocookies); var ws = new InfrastructureAsCode.Core.com.sharepoint.useralerts.Alerts(); ws.Url = string.Format("{0}/_vti_bin/Alerts.asmx", spourl.AbsoluteUri); ws.Credentials = newcreds; ws.CookieContainer = spocontainer; var alerts = ws.GetAlerts(); LogVerbose("User {0} webId:{1} has {2} alerts configured", alerts.CurrentUser, alerts.AlertWebId, alerts.Alerts.Count()); foreach (var alertItem in alerts.Alerts) { var model = new SPUserAlertDefinition() { CurrentUser = alerts.CurrentUser, WebId = alerts.AlertWebId, WebTitle = alerts.AlertWebTitle, AlertForTitle = alertItem.AlertForTitle, AlertForUrl = alertItem.AlertForUrl, EventType = alertItem.EventType, Id = alertItem.Id }; models.Add(model); LogVerbose("Alert {0} Active:{1} EventType:{2} Id:{3}", alertItem.AlertForUrl, alertItem.Active, alertItem.EventType, alertItem.Id); } models.ForEach(alert => WriteObject(alert)); } catch (Exception ex) { LogError(ex, "Failed in GetListItemCount for Library {0}", ListTitle); } }
protected override void ProcessRecord() { #if !NETSTANDARD2_0 var cred = Utilities.CredentialManager.GetCredential(Name); if (cred != null) { switch (Type) { case CredentialType.O365: { if (cred != null) { WriteObject(new SharePointOnlineCredentials(cred.UserName, cred.Password)); } break; } case CredentialType.OnPrem: { WriteObject(new NetworkCredential(cred.UserName, cred.Password)); break; } case CredentialType.PSCredential: { WriteObject(cred); break; } } } #else var creds = Utilities.CredentialManager.GetCredential(Name); if (creds != null) { var spoCreds = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(creds.UserName, creds.Password); WriteObject(spoCreds); } else { WriteError(new ErrorRecord(new System.Exception("Credentials not found"), "CREDSNOTFOUND", ErrorCategory.AuthenticationError, this)); } #endif }
public static MSC.ClientContext GetContext(string siteUrl) { try { AppConfiguration _AppConfiguration = GetSharepointCredentials(siteUrl); var securePassword = new SecureString(); foreach (char c in _AppConfiguration.ServicePassword) { securePassword.AppendChar(c); } var onlineCredentials = new MSC.SharePointOnlineCredentials(_AppConfiguration.ServiceUserName, securePassword); var context = new MSC.ClientContext(_AppConfiguration.ServiceSiteUrl); context.Credentials = onlineCredentials; return(context); } catch (Exception ex) { WriteLog("Error in CustomSharePointUtility.GetContext: " + ex.ToString()); return(null); } }
public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument) { var message = await argument; if (message.Attachments != null && message.Attachments.Any()) { var attachment = message.Attachments.First(); var attachmentUrl = message.Attachments[0].ContentUrl; var content = message.Attachments[0].Content; using (HttpClient httpClient = new HttpClient()) { try { var responseMessage = await httpClient.GetAsync(attachment.ContentUrl); var contentLenghtBytes = responseMessage.Content.Headers.ContentLength; var attachmentdata = await httpClient.GetByteArrayAsync(attachmentUrl); string siteUrl = Convert.ToString(ConfigurationManager.AppSettings["SiteUrl"]); string login = Convert.ToString(ConfigurationManager.AppSettings["ApplicationUserName"]); string password = Convert.ToString(ConfigurationManager.AppSettings["Password"]); string listName = Convert.ToString(ConfigurationManager.AppSettings["DocumentLib"]); var securePassword = new SecureString(); foreach (var c in password) { securePassword.AppendChar(c); } var credentials = new SP.SharePointOnlineCredentials(login, securePassword); SP.ClientContext clientContext = new SP.ClientContext(siteUrl); clientContext.Credentials = credentials; SP.List documentsList = clientContext.Web.Lists.GetByTitle(listName); var fileCreationInformation = new SP.FileCreationInformation(); //Assign to content byte[] i.e. documentStream fileCreationInformation.ContentStream = new MemoryStream(attachmentdata); //Allow owerwrite of document fileCreationInformation.Overwrite = true; //Upload URL fileCreationInformation.Url = siteUrl + "/" + listName + "/" + attachment.Name; SP.File uploadFile = documentsList.RootFolder.Files.Add( fileCreationInformation); uploadFile.ListItemAllFields.Update(); clientContext.ExecuteQuery(); SP.ListItem item = uploadFile.ListItemAllFields; string filenameWithoutExtension = Path.GetFileNameWithoutExtension(attachment.Name); item["Title"] = filenameWithoutExtension; item.Update(); clientContext.Load(item); clientContext.ExecuteQuery(); //of {attachment.ContentType} type and size of {contentLenghtBytes} bytes received await context.PostAsync($"Thanks for submitting the attachement."); } catch (Exception ex) { } } } else { await context.PostAsync("Hi there! I'm a bot created to show you how I can receive message attachments, but no attachment was sent to me. Please, try again sending a new message including an attachment."); } context.Wait(this.MessageReceivedAsync); }
/// <summary> /// Process the request /// </summary> public override void ExecuteCmdlet() { base.ExecuteCmdlet(); if (this.ClientContext == null) { LogWarning("Invalid client context, configure the service to run again"); return; } // obtain CSOM object for host web var vweb = this.ClientContext.Web; this.ClientContext.Load(vweb, hw => hw.SiteGroups, hw => hw.Title, hw => hw.ContentTypes); this.ClientContext.ExecuteQuery(); GroupCollection groups = vweb.SiteGroups; this.ClientContext.Load(groups, g => g.Include(inc => inc.Id, inc => inc.Title, igg => igg.Users)); this.ClientContext.ExecuteQuery(); var creds = SPIaCConnection.CurrentConnection.GetActiveCredentials(); var newcreds = new System.Net.NetworkCredential(creds.UserName, creds.Password); var spourl = new Uri(this.ClientContext.Url); var spocreds = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(creds.UserName, creds.Password); var spocookies = spocreds.GetAuthenticationCookie(spourl); var spocontainer = new System.Net.CookieContainer(); spocontainer.SetCookies(spourl, spocookies); var ows = new OfficeDevPnP.Core.UPAWebService.UserProfileService(); ows.Url = string.Format("{0}/_vti_bin/userprofileservice.asmx", spourl.AbsoluteUri); ows.Credentials = newcreds; ows.CookieContainer = spocontainer; var siteGroupUsers = new List <SPUserDefinitionModel>(); var filteredGroups = groups.Where(w => SiteGroups.Any(a => w.Title.Equals(a, StringComparison.CurrentCultureIgnoreCase))); foreach (var group in filteredGroups) { foreach (var user in group.Users) { if (!siteGroupUsers.Any(a => a.UserName == user.LoginName)) { var userProfile = ows.GetUserProfileByName(user.LoginName); //var userOrgs = ows.GetUserOrganizations(user.LoginName); var UserName = userProfile.RetrieveUserProperty("UserName"); var office = userProfile.RetrieveUserProperty("Department"); if (string.IsNullOrEmpty(office)) { office = userProfile.RetrieveUserProperty("SPS-Department"); } var userManager = userProfile.RetrieveUserProperty("Manager"); office = office.Replace(new char[] { '/', '\\', '-' }, ","); office = office.Replace(" ", ""); var officeSplit = office.Split(new string[] { "," }, StringSplitOptions.None); var officeAcronym = (officeSplit.Length > 0) ? officeSplit[0] : string.Empty; siteGroupUsers.Add(new SPUserDefinitionModel() { Manager = userManager, Organization = office, OrganizationAcronym = officeAcronym, UserName = user.LoginName, UserEmail = user.Email, UserDisplay = user.Title }); } } WriteObject(siteGroupUsers); } }
public void Upload() { try { using (context = new MSC.ClientContext(sharePointSite)) { SecureString s = new SecureString(); //s. MSC.SharePointOnlineCredentials cred = new MSC.SharePointOnlineCredentials(ConfigurationManager.AppSettings["UsrName"], getPassword(ConfigurationManager.AppSettings["PassWord"])); context.Credentials = cred; var list = context.Web.Lists.GetByTitle(documentLibraryName); context.Load(list); var root = list.RootFolder; context.Load(root); context.ExecuteQuery(); // ADDITION string SourceDocPath = ConfigurationManager.AppSettings["SourceDocsPath"]; DirectoryInfo dInfo = new DirectoryInfo(SourceDocPath); FileInfo[] ListofFiles = dInfo.GetFiles(); List <linkIdentifier> listofLinks = new List <linkIdentifier>(); XmlDocument doc = new XmlDocument(); doc.Load("Links.xml"); XmlNodeList listXml = doc.GetElementsByTagName("link"); foreach (XmlNode n1 in listXml) { linkIdentifier id = new linkIdentifier(); id.rowIndex = Convert.ToInt32(n1["rowIndex"].InnerText); id.colIndex = Convert.ToInt32(n1["colIndex"].InnerText); id.SheetName = n1["SheetName"].InnerText; listofLinks.Add(id); } foreach (FileInfo fileInstance in ListofFiles) { bool IsgoodLink = false; string path = fileInstance.FullName; Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); Workbook wb = excel.Workbooks.Open(path); //***********************LINK CHECK***************************************** //Read the first cell foreach (linkIdentifier identifier in listofLinks) { Worksheet excelSheet = wb.Sheets[identifier.SheetName]; string test = excelSheet.Cells[identifier.rowIndex, identifier.colIndex].Formula; test = test.Split(',')[0].TrimEnd("\"".ToCharArray()); String[] pathList = test.Split('/'); try { if (test.Contains(".aspx")) { //LinkCheck(test); IsgoodLink = CheckLink(pathList, cred); } else { IsgoodLink = CheckLink(pathList, cred); } } catch (MSC.ServerException e) { if (e.ServerErrorTypeName == "System.IO.FileNotFoundException") { IsgoodLink = false; } wb.Close(); IsgoodLink = false; } if (IsgoodLink == false) { Console.WriteLine("File {0} is having deadlinks.", fileInstance.Name); wb.Close(); return; } } wb.Close(); //***********************LINK CHECK***************************************** string tempdir = fileInstance.Name; tempdir = tempdir.Substring("2019.craft ".Length); tempdir = tempdir.Trim(' '); tempdir = tempdir.Remove((tempdir.Length - ".xlsm".Length)); String ParentDirectoryName = tempdir.Split('-')[0]; ParentDirectoryName = ParentDirectoryName.Trim(); string ChildDirectoryName = tempdir.Split('-')[1]; ChildDirectoryName = ChildDirectoryName.Trim(); try { MSC.ListItemCreationInformation information = new MSC.ListItemCreationInformation(); string targetFolder = ConfigurationManager.AppSettings["RootFolder"]; if (ConfigurationManager.AppSettings["Testing"] == "1") { targetFolder = ConfigurationManager.AppSettings["RootFolderTest"]; } ; information.FolderUrl = list.RootFolder.ServerRelativeUrl + targetFolder + ParentDirectoryName; MSC.Folder parentFolder = list.RootFolder.Folders.Add(information.FolderUrl); context.Load(parentFolder); context.ExecuteQuery(); information.FolderUrl = information.FolderUrl + "/" + ChildDirectoryName; MSC.Folder childDirectory = list.RootFolder.Folders.Add(information.FolderUrl); context.Load(childDirectory); context.ExecuteQuery(); if (IsgoodLink) { string filePath = fileInstance.FullName; FileStream documentStream = System.IO.File.OpenRead(filePath); byte[] info = new byte[documentStream.Length]; documentStream.Read(info, 0, (int)documentStream.Length); string fileURL = information.FolderUrl + "/" + fileInstance.Name; MSC.FileCreationInformation fileCreationInformation = new MSC.FileCreationInformation(); fileCreationInformation.Overwrite = true; fileCreationInformation.Content = info; fileCreationInformation.Url = fileURL; try { Microsoft.SharePoint.Client.File f = context.Web.GetFileByServerRelativeUrl(fileURL); context.Load(f); context.ExecuteQuery(); f.CheckOut(); } catch (Microsoft.SharePoint.Client.ServerException ex) { if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException") { Console.WriteLine("File is not found for Checkout"); } } Microsoft.SharePoint.Client.File uploadFile = list.RootFolder.Files.Add(fileCreationInformation); uploadFile.CheckIn("Improvement Plan", MSC.CheckinType.MajorCheckIn); context.Load(uploadFile, w => w.MajorVersion, w => w.MinorVersion); context.ExecuteQuery(); Console.WriteLine("Document {0} is uploaded and checked in into SharePoint", fileURL); } } catch (Exception e) { Console.WriteLine(e.Message); } } } } catch (Exception ex) { new EventLog().WriteEntry(ex.Message, EventLogEntryType.Error); return; } }
public bool CheckLink(String[] pathList, MSC.SharePointOnlineCredentials cred) { string baseSubPath1; string baseSubPath2; string documentLibrary; if ((pathList[3] == ":p:") || (pathList[4] == "r")) { baseSubPath1 = pathList[5]; baseSubPath2 = pathList[6]; documentLibrary = pathList[7]; } else { baseSubPath1 = pathList[3]; baseSubPath2 = pathList[4]; documentLibrary = pathList[5]; } string baseURL = pathList[0] + "//" + pathList[2] + "/" + baseSubPath1 + "/" + baseSubPath2 + "/"; bool isPathFound = false; using (ClientContext webInstance = new ClientContext(baseURL)) { if (documentLibrary == "SitePages") { documentLibrary = "Site Pages"; } documentLibrary = documentLibrary.Replace("%20", " "); webInstance.Credentials = cred; List listLink = webInstance.Web.Lists.GetByTitle(documentLibrary); webInstance.Web.Context.Load(listLink); webInstance.Web.Context.Load(listLink.RootFolder); webInstance.Web.Context.Load(listLink.RootFolder.Folders); webInstance.Web.Context.Load(listLink.RootFolder.Files); webInstance.Web.Context.ExecuteQuery(); FolderCollection fcol = listLink.RootFolder.Folders; List <string> lstFile = new List <string>(); string filetobeChecked = pathList[pathList.Count() - 1]; if (filetobeChecked.Contains('?')) { filetobeChecked = filetobeChecked.Split('?')[0]; } filetobeChecked = filetobeChecked.Replace("%20", " "); //Check in the Root Path FileCollection fileCol = listLink.RootFolder.Files; foreach (MSC.File file in fileCol) { if (file.Name == filetobeChecked) { isPathFound = true; Console.WriteLine(" expected file {0} found", filetobeChecked); break; } } if (!isPathFound) { foreach (Folder f1 in fcol) { webInstance.Web.Context.Load(f1.Files); webInstance.Web.Context.ExecuteQuery(); fileCol = f1.Files; foreach (MSC.File file in fileCol) { if (file.Name == filetobeChecked) { isPathFound = true; Console.WriteLine(" expected file {0} found", filetobeChecked); break; } } if (isPathFound) { break; } } } } return(isPathFound); }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); var models = new List <SPUserDefinitionModel>(); try { var creds = SPIaCConnection.CurrentConnection.GetActiveCredentials(); var newcreds = new System.Net.NetworkCredential(creds.UserName, creds.Password); var spourl = new Uri(this.ClientContext.Url); var spocreds = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(creds.UserName, creds.Password); var spocookies = spocreds.GetAuthenticationCookie(spourl); var spocontainer = new System.Net.CookieContainer(); spocontainer.SetCookies(spourl, spocookies); var ows = new OfficeDevPnP.Core.UPAWebService.UserProfileService(); ows.Url = string.Format("{0}/_vti_bin/userprofileservice.asmx", spourl.AbsoluteUri); ows.Credentials = newcreds; ows.CookieContainer = spocontainer; var UserProfileResult = ows.GetUserProfileByIndex(-1); var NumProfiles = ows.GetUserProfileCount(); var i = 1; var tmpCount = 0; var nextValue = UserProfileResult.NextValue; var nextValueIndex = int.Parse(nextValue); // As long as the next User profile is NOT the one we started with (at -1)... while (nextValueIndex != -1) { LogVerbose("Examining profile {0} of {1}", i, NumProfiles); // Look for the Personal Space object in the User Profile and retrieve it // (PersonalSpace is the name of the path to a user's OneDrive for Business site. Users who have not yet created a // OneDrive for Business site might not have this property set.) tmpCount++; var PersonalSpaceUrl = UserProfileResult.RetrieveUserProperty("PersonalSpace"); var UserName = UserProfileResult.RetrieveUserProperty("UserName"); if (!string.IsNullOrEmpty(UserName)) { UserName = UserName.ToString().Replace(";", ","); } var userObject = new SPUserDefinitionModel() { UserName = UserName, OD4BUrl = PersonalSpaceUrl, UserIndex = nextValueIndex }; models.Add(userObject); // And now we check the next profile the same way... UserProfileResult = ows.GetUserProfileByIndex(nextValueIndex); nextValue = UserProfileResult.NextValue; nextValueIndex = int.Parse(nextValue); i++; } models.ForEach(user => WriteObject(user)); } catch (Exception ex) { LogError(ex, "Failed to retreive user profiles"); } }
/// <summary> /// Execute the REST API querying the list with paging /// </summary> public override void ExecuteCmdlet() { base.ExecuteCmdlet(); Collection <SPListItemDefinition> results = new Collection <SPListItemDefinition>(); try { var creds = SPIaCConnection.CurrentConnection.GetActiveCredentials(); var spourl = new Uri(this.ClientContext.Url); var spocreds = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(creds.UserName, creds.Password); var spocookies = spocreds.GetAuthenticationCookie(spourl); var spocontainer = new System.Net.CookieContainer(); spocontainer.SetCookies(spourl, spocookies); // region Consume the web service var ListService = string.Format("{0}/_api/web/lists/getByTitle('{1}')/ItemCount", this.ClientContext.Url, this.ListTitle); var webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(ListService); webRequest.Credentials = new System.Net.NetworkCredential(creds.UserName, creds.Password); webRequest.Method = "GET"; webRequest.Accept = "application/json;odata=verbose"; webRequest.CookieContainer = spocontainer; var webResponse = webRequest.GetResponse(); using (Stream webStream = webResponse.GetResponseStream()) { using (StreamReader responseReader = new StreamReader(webStream)) { string response = responseReader.ReadToEnd(); var jobj = JObject.Parse(response); var itemCount = jobj["d"]["ItemCount"]; LogVerbose("ItemCount:{0}", itemCount); } } var successFlag = true; ListService = string.Format("{0}/_api/web/lists/getByTitle('{1}')/items?$top={2}", this.ClientContext.Url, this.ListTitle, this.Throttle); while (successFlag) { LogVerbose("Paging:{0}", ListService); successFlag = false; webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(ListService); webRequest.Credentials = new System.Net.NetworkCredential(creds.UserName, creds.Password); webRequest.Method = "GET"; webRequest.Accept = "application/json;odata=verbose"; webRequest.CookieContainer = spocontainer; webResponse = webRequest.GetResponse(); using (Stream webStream = webResponse.GetResponseStream()) { using (StreamReader responseReader = new StreamReader(webStream)) { string response = responseReader.ReadToEnd(); var jobj = JObject.Parse(response); var jarr = (JArray)jobj["d"]["results"]; var jnextpage = jobj["d"]["__next"]; foreach (JObject j in jarr) { LogVerbose("ItemID:{0}", j["Id"]); var newitem = new SPListItemDefinition() { Title = j["Title"].ToObject <string>(), Id = j["Id"].ToObject <int>() }; results.Add(newitem); } if (jnextpage != null && !String.IsNullOrEmpty(jnextpage.ToString())) { successFlag = true; ListService = jnextpage.ToString(); } } } } WriteObject(results, true); } catch (Exception ex) { LogError(ex, "Failed in GetListItemCount for Library {0}", ListTitle); } }