public bool AddDeptCal(SharePointContext spContext, string Title, string StartDates, string EndDates) { // using (var clientContext = TokenHelper.GetClientContextWithContextToken(sharepointUrl, contextToken, hostUrl)) if (spContext == null) spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current); using (var clientContext = spContext.CreateAppOnlyClientContextForSPHost()) //CreateAppOnlyClientContextForSPAppWeb { try { ListCollection lists = clientContext.Web.Lists; List selectedList = lists.GetByTitle("Department Calendar"); // Getting Listname from ConfigList ListItemCreationInformation itemCreateInfo; Microsoft.SharePoint.Client.ListItem newItem; itemCreateInfo = new ListItemCreationInformation(); newItem = selectedList.AddItem(itemCreateInfo); newItem["Title"] = Title; newItem["EventDate"] = Convert.ToDateTime(StartDates); newItem["EndDate"] = Convert.ToDateTime(EndDates); newItem["Description"] = ""; newItem.Update(); clientContext.ExecuteQuery(); return true; } catch (Exception ex) { Microsoft.SharePoint.Client.Utilities.Utility.LogCustomRemoteAppError(clientContext, Global.ProductId, ex.Message); clientContext.ExecuteQuery(); return false; } } }
//public TValue ErrorHandler<TValue>(Func<TValue> action) //{ // try // { // return action(); // } // catch (Exception ex) // { // DumpErrorIntoAppLog(DateTime.Now.ToString(CultureInfo.InvariantCulture), ex.Message); // return default(TValue); // } //} //public void ErrorHandler(Action action) //{ // try // { // action(); // } // catch (Exception ex) // { // DumpErrorIntoAppLog(DateTime.Now.ToString(CultureInfo.InvariantCulture), ex.Message); // } //} public void DumpErrorIntoAppLog(string time, string message) { ContextUtility utility = new ContextUtility(HttpContext.Current.Request); using (ClientContext context = TokenHelper.GetClientContextWithContextToken(utility.ContextDetails.AppWebUrl, utility.ContextDetails.ContextTokenString, HttpContext.Current.Request.Url.Authority)) { try { List list = context.Web.Lists.GetByTitle("Errors"); context.Load(list); context.ExecuteQuery(); if (list == null) { return; } CamlQuery query = CamlQuery.CreateAllItemsQuery(); ListItemCollection items = list.GetItems(query); context.Load(items); context.ExecuteQuery(); Microsoft.SharePoint.Client.ListItem newItem; ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); newItem = list.AddItem(itemCreateInfo); newItem["Errors"] = string.Format("Time: {0} Message: {1}", time, message); newItem.Update(); context.ExecuteQuery(); } catch (Exception ex) { Microsoft.SharePoint.Client.Utilities.Utility.LogCustomRemoteAppError(context, Global.ProductId, ex.Message); context.ExecuteQuery(); } } }
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) { if (data is LogEntity) { using (DocLibContext clientContext = new DocLibContext()) { MossServerInfoConfigurationSettings section = MossServerInfoConfigurationSettings.GetConfig(); MossServerInfoConfigurationElement document = section.Servers["documentServer"]; if (document != null) { ListCollection lists = clientContext.Web.Lists; clientContext.Load(lists); List logList = lists.GetByTitle(document.LogListName); clientContext.Load(logList); clientContext.ExecuteQuery(); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem oListItem = logList.AddItem(itemCreateInfo); oListItem["Title"] = ((LogEntity)data).Title; oListItem["operationInfo"] = ((LogEntity)data).Message; oListItem.Update(); //clientContext.Load(itemCreateInfo); clientContext.ExecuteQuery(); } } } else { base.TraceData(eventCache, source, eventType, id, data); } }
/// <summary> /// /// </summary> /// <param name="args"></param> static void Main(string[] args) { Uri siteUri = new Uri(ConfigurationManager.AppSettings["url"]); //Get the realm for the URL string realm = TokenHelper.GetRealmFromTargetUrl(siteUri); //Get the access token for the URL. // Requires this app to be registered with the tenant string accessToken = TokenHelper.GetAppOnlyAccessToken( TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken; //Get client context with access token using (var ctx = TokenHelper.GetClientContextWithAccessToken( siteUri.ToString(), accessToken)) { // Let's create a list to the host web and add a new entry for each execution if (!ListExists(ctx.Web, "RemoteOperation")) { AddList(ctx.Web, ListTemplateType.GenericList, "RemoteOperation"); } // Add new execution entry to the list time stamp // Assume that the web has a list named "Announcements". List list = ctx.Web.Lists.GetByTitle("RemoteOperation"); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem newItem = list.AddItem(itemCreateInfo); newItem["Title"] = string.Format("New {0}", DateTime.Now.ToLongTimeString()); newItem.Update(); ctx.ExecuteQuery(); } }
public void SendMonitoringData(int UniqueID, string type, double value) { // Get access to source site using (var ctx = new ClientContext(tenant)) { //Provide count and pwd for connecting to the source var passWord = new SecureString(); foreach (char c in passwordString.ToCharArray()) passWord.AppendChar(c); ctx.Credentials = new SharePointOnlineCredentials(userName, passWord); // Actual code for operations Web web = ctx.Web; ctx.Load(web); ctx.ExecuteQuery(); List myList = web.Lists.GetByTitle("MonitorLiveData"); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem newItem = myList.AddItem(itemCreateInfo); newItem["AlertID"] = UniqueID.ToString(); newItem["DataType"] = type.ToString(); newItem["DataValue"] = value; newItem.Update(); ctx.ExecuteQuery(); } }
public string FillAppWebNotesListToThreshold() { using (var clientContext = SharePointContext.CreateUserClientContextForSPAppWeb()) { List notesList = clientContext.Web.Lists.GetByTitle("Notes"); var itemCreateInfo = new ListItemCreationInformation(); for (int i = 0; i < 500; i++) { ListItem newItem = notesList.AddItem(itemCreateInfo); newItem["Title"] = "Notes Title." + i.ToString(); newItem["FTCAM_Description"] = "Notes description"; newItem.Update(); if (i % 100 == 0) clientContext.ExecuteQuery(); } clientContext.ExecuteQuery(); clientContext.Load(notesList, l => l.ItemCount); clientContext.ExecuteQuery(); if (notesList.ItemCount >= 5000) return "The App Web Notes List has " + notesList.ItemCount + " items, and exceeds the threshold."; else return 500 + " items have been added to the App Web Notes List. " + "There are " + (5000-notesList.ItemCount) + " items left to add."; } }
public string FillHostWebSupportCasesToThreshold() { using (var clientContext = SharePointContext.CreateUserClientContextForSPHost()) { List supportCasesList = clientContext.Web.Lists.GetByTitle("Support Cases"); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); for (int i = 0; i < 500; i++) { ListItem newItem = supportCasesList.AddItem(itemCreateInfo); newItem["Title"] = "Wrong product received." + i.ToString(); newItem["FTCAM_Status"] = "Open"; newItem["FTCAM_CSR"] = "bjones"; newItem["FTCAM_CustomerID"] = "thresholds test"; newItem.Update(); if (i % 100 == 0) clientContext.ExecuteQuery(); } clientContext.ExecuteQuery(); clientContext.Load(supportCasesList, l => l.ItemCount); clientContext.ExecuteQuery(); if(supportCasesList.ItemCount>=5000) return "The Host Web Support Cases List has " + supportCasesList.ItemCount + " items, and exceeds the threshold."; else return 500 + " items have been added to the Host Web Support Cases List. " + "There are " + (5000 - supportCasesList.ItemCount) + " items left to add."; } }
private int CreateNewRequest(string siteName, string siteTitle, string siteDescription, string[] owners, string[] members, string[] visitors) { // Get the term foeld for the Reasearch taxonomy var termfield = _siteRequestList.Fields.GetByInternalNameOrTitle("InstitutionalSiteClassification"); _sharePoint.ClientContext.Load(termfield); _sharePoint.ClientContext.ExecuteQuery(); const string term = "Research"; string hiddentextFieldId = string.Empty; string termId = SharePointTaxonomyHelper.GetTermInfo(_sharePoint.Root, termfield, term, ref hiddentextFieldId); Field hiddenTextField = _siteRequestList.Fields.GetById(new Guid(hiddentextFieldId)); _sharePoint.ClientContext.Load(hiddenTextField); _sharePoint.ClientContext.ExecuteQuery(); var itemCreateInfo = new ListItemCreationInformation(); var listItem = _siteRequestList.AddItem(itemCreateInfo); listItem["UrdmsSiteTitle"] = siteTitle; listItem["UrdmsSiteId"] = siteName; listItem["Body"] = siteDescription; listItem["UrdmsSiteProvisioningRequestStatus"] = "Approved"; listItem["UrdmsClassification"] = String.Format("-1;#{0}|{1}", term, termId); listItem[hiddenTextField.InternalName] = String.Format("-1;#{0}|{1}", term, termId); // Set Site Users listItem["UrdmsSiteOwners"] = SetUserValues(owners); listItem["UrdmsSiteMembers"] = SetUserValues(members); listItem["UrdmsSiteVisitors"] = SetUserValues(visitors); listItem.Update(); _sharePoint.ClientContext.ExecuteQuery(); return listItem.Id; }
/// <summary> /// Adds a new entry to the site directory list /// </summary> /// <param name="siteDirectoryHost">Url to the site directory site collection</param> /// <param name="siteDirectoryProvisioningPage">Path to a page used as url when the site collection is not yet provisioned</param> /// <param name="listName">Name of the site directory list</param> /// <param name="title">Title of the site collection</param> /// <param name="siteUrl">Url of the site collection</param> /// <param name="template">Template used to provision this site collection</param> /// <param name="requestor">Person that requested the provisioning</param> /// <param name="owner">Person that will be the primary owner of the site collection</param> /// <param name="backupOwners">Person(s) that will be the backup owner(s) of the site collection</param> /// <param name="permissions">Chosen permission model</param> public void AddSiteDirectoryEntry(ClientContext cc, Web web, string siteDirectoryHost, string siteDirectoryProvisioningPage, string listName, string title, string siteUrl, string template, string[] ownerLogins) { List listToInsertTo = web.Lists.GetByTitle(listName); ListItemCreationInformation lici = new ListItemCreationInformation(); ListItem listItem = listToInsertTo.AddItem(lici); listItem["Title"] = title; //URL = hyperlink field FieldUrlValue url = new FieldUrlValue(); url.Description = title; url.Url = String.Format("{0}/{1}", siteDirectoryHost, siteDirectoryProvisioningPage); listItem["SiteTitle"] = url; // store url also as text field to facilitate easy CAML querying afterwards listItem["UrlText"] = siteUrl; // Owners = Person field with multiple values FieldUserValue[] users = new FieldUserValue[ownerLogins.Length]; int i = 0; foreach (string ownerLogin in ownerLogins) { FieldUserValue ownersField = FieldUserValue.FromUser(ownerLogin); users[i] = ownersField; i++; } listItem["Owners"] = users; listItem["Template"] = template; listItem["Status"] = "Requested"; listItem.Update(); cc.ExecuteQuery(); }
public static bool AddProduct(SharePointContext spContext, Product product) { using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { if (clientContext != null) { try { List lstProducts = clientContext.Web.Lists.GetByTitle("Products"); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem newProduct = lstProducts.AddItem(itemCreateInfo); newProduct["Title"] = product.Title; newProduct["ProductDescription"] = product.Description; newProduct["Price"] = product.Price; newProduct.Update(); clientContext.ExecuteQuery(); return true; } catch (ServerException ex) { return false; } } } return false; }
protected void CreateSiteButton_Click(object sender, EventArgs e) { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); //using (var clientContext = spContext.CreateAppOnlyClientContextForSPAppWeb()) using ( var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { var web = clientContext.Web; clientContext.Load(web); var list = web.Lists.GetByTitle("SiteCreationRequests"); clientContext.Load(list); clientContext.ExecuteQuery(); //var roleassignments = list.RoleAssignments; //clientContext.Load(roleassignments); //clientContext.ExecuteQuery(); //clientContext.Load(roleassignments.Groups.GetById(3)); //clientContext.Load(clientContext.Web.CurrentUser); //clientContext.ExecuteQuery(); //var ownerGroup = roleassignments.Groups.GetById(3); //clientContext.Load(ownerGroup.Users); //clientContext.ExecuteQuery(); //ownerGroup.Users.AddUser(clientContext.Web.CurrentUser); //ownerGroup.Update(); //clientContext.ExecuteQuery(); var newItemCreator = new ListItemCreationInformation(); var newItem = list.AddItem(newItemCreator); newItem["Title"] = SiteName.Text; newItem["Approver"] = clientContext.Web.GetUserById(11); //newItem["Approver"] = clientContext.Web.CurrentUser; newItem["Approved"] = false; newItem.Update(); clientContext.ExecuteQuery(); } }
void SPtimer_Elapsed(object sender, ElapsedEventArgs e) { //Comment out either of the below based on On Premise server or Online // Uri hostWeb = new Uri("http://tenant/sites/DevCenter"); //Below line works with On line Uri hostWeb = new Uri("https://sweethome03.sharepoint.com"); string realm = TokenHelper.GetRealmFromTargetUrl(hostWeb); string appOnlyAccessToken = TokenHelper.GetAppOnlyAccessToken(SharePointPrincipal, hostWeb.Authority, realm).AccessToken; using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(hostWeb.ToString(), appOnlyAccessToken)) { if (clientContext != null) { var myList = clientContext.Web.Lists.GetByTitle("WindowsTimerJob"); ListItemCreationInformation listItemCreate = new ListItemCreationInformation(); Microsoft.SharePoint.Client.ListItem newItem = myList.AddItem(listItemCreate); newItem["Title"] = "Added from Timer Job"; newItem.Update(); clientContext.ExecuteQuery(); } } }
protected void cmdCreateCustomersList_Click(object sender, EventArgs e) { SharePointContext spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (ClientContext clientContext = spContext.CreateUserClientContextForSPHost()) { clientContext.Load(clientContext.Web); clientContext.ExecuteQuery(); string listTitle = "Customers"; // delete list if it exists ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { clientContext.Web.Lists.GetByTitle(listTitle).DeleteObject(); } using (scope.StartCatch()) { } } // create and initialize ListCreationInformation object ListCreationInformation listInformation = new ListCreationInformation(); listInformation.Title = listTitle; listInformation.Url = "Lists/Customers"; listInformation.QuickLaunchOption = QuickLaunchOptions.On; listInformation.TemplateType = (int)ListTemplateType.Contacts; // Add ListCreationInformation to lists collection and return list object List list = clientContext.Web.Lists.Add(listInformation); // modify additional list properties and update list.OnQuickLaunch = true; list.EnableAttachments = false; list.Update(); // send command to server to create list clientContext.ExecuteQuery(); // add an item to the list ListItemCreationInformation lici1 = new ListItemCreationInformation(); var item1 = list.AddItem(lici1); item1["Title"] = "Lennon"; item1["FirstName"] = "John"; item1.Update(); // add a second item ListItemCreationInformation lici2 = new ListItemCreationInformation(); var item2 = list.AddItem(lici2); item2["Title"] = "McCartney"; item2["FirstName"] = "Paul"; item2.Update(); // send add commands to server clientContext.ExecuteQuery(); // add message to app’s start page placeholderMainContent.Text = "New list created"; } }
protected void btnSave_Click(object sender, EventArgs e) { string errMsg = string.Empty; try { using (var clientContext = GetClientContext()) { var web = GetClientContextWeb(clientContext); var lstEmployee = web.Lists.GetByTitle("Employees"); var itemCreateInfo = new ListItemCreationInformation(); var listItem = lstEmployee.AddItem(itemCreateInfo); listItem["EmpNumber"] = txtEmpNumber.Text; listItem["UserID"] = txtUserID.Text; listItem["Title"] = txtName.Text; listItem["EmpManager"] = txtManager.Text; listItem["Designation"] = ddlDesignation.SelectedValue; listItem["Location"] = ddlCity.Text; StringBuilder sbSkills = new StringBuilder(); RepeaterItemCollection skills = rptSkills.Items; foreach (RepeaterItem skill in skills) { TextBox tbTech = (TextBox)skill.FindControl("rptTxtTechnology"); TextBox tbSkill = (TextBox)skill.FindControl("rptTxtExperience"); sbSkills.Append(tbTech.Text).Append(",").Append(tbSkill.Text).Append(";"); } listItem["Skills"] = sbSkills.ToString(); if (rptUploadedFiles.Items.Count > 0) { listItem["AttachmentID"] = hdnAttachmentID.Value; } listItem.Update(); clientContext.ExecuteQuery(); } } catch (Exception ex) { errMsg = ex.Message; } if (errMsg.Length > 0) { ClientScript.RegisterStartupScript(this.GetType(), "errorMessage", "alert('" + errMsg + "');", true); } else { string url = HttpContext.Current.Request.Url.AbsoluteUri; url = url.Replace("Default.aspx", "Thanks.aspx"); Response.Redirect(url); } }
private static void AddListItem(ClientContext clientContext, string listName) { Web currentWeb = clientContext.Web; var myList = clientContext.Web.Lists.GetByTitle(listName); ListItemCreationInformation listItemCreate = new ListItemCreationInformation(); Microsoft.SharePoint.Client.ListItem newItem = myList.AddItem(listItemCreate); newItem["Title"] = "Item added by Job at " + DateTime.Now; newItem.Update(); clientContext.ExecuteQuery(); }
public ActionResult Index() { var requestClient = new HttpRequestClient(); var resultsFromApi = requestClient.GetFixtureTable(); var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { List teamsList = clientContext.Web.Lists.GetByTitle("Teams"); var itemCreateInfo = new ListItemCreationInformation(); ListItem newTeam = null; //Here we store the results in a sharepoint List foreach (var team in resultsFromApi) { newTeam = teamsList.AddItem(itemCreateInfo); newTeam["Title"] = team.Name; newTeam["Position"] = team.Position; newTeam["Points"] = team.Points; newTeam["Played"] = team.Played; newTeam.Update(); } clientContext.ExecuteQuery(); //Here is an example of how to get the information from the list List list = clientContext.Web.Lists.GetByTitle("Teams"); ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(listItems); clientContext.ExecuteQuery(); var resultsFromSharepoint = listItems.Select(x => new Team() { Name = x["Title"] + string.Empty, Points = Convert.ToInt32(x["Points"]), Played = Convert.ToInt32(x["Played"]), Position = Convert.ToInt32(x["Position"]) }); var model = new Results() { ResultsFromAPI = resultsFromApi, ResultsFromSharePoint = resultsFromSharepoint }; return View(model); } }
protected override void ExecuteCmdlet() { List list = null; if (List != null) { list = SelectedWeb.GetList(List); } if (list != null) { ListItemCreationInformation liCI = new ListItemCreationInformation(); var item = list.AddItem(liCI); if (ContentType != null) { ContentType ct = null; if (ContentType.ContentType == null) { if (ContentType.Id != null) { ct = SelectedWeb.GetContentTypeById(ContentType.Id, true); } else if (ContentType.Name != null) { ct = SelectedWeb.GetContentTypeByName(ContentType.Name, true); } } else { ct = ContentType.ContentType; } if (ct != null) { if (!ct.IsPropertyAvailable("StringId")) { ClientContext.Load(ct, c => c.StringId); ClientContext.ExecuteQueryRetry(); } item["ContentTypeId"] = ct.StringId; item.Update(); ClientContext.ExecuteQueryRetry(); } } foreach (var key in Values.Keys) { item[key as string] = Values[key]; } item.Update(); ClientContext.Load(item); ClientContext.ExecuteQueryRetry(); WriteObject(item); } }
public bool LoadTimeOffTypes() { Microsoft.SharePoint.Client.ListItemCollection listItems; //using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken)) var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current); using (var clientContext = spContext.CreateAppOnlyClientContextForSPAppWeb()) { try { Web web = clientContext.Web; ListCollection lists = web.Lists; List selectedList = lists.GetByTitle(WebConfigurationManager.AppSettings["TimeOffTypes"]); clientContext.Load<ListCollection>(lists); // this lists object is loaded successfully clientContext.Load<List>(selectedList); // this list object is loaded successfully clientContext.ExecuteQuery(); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = @"<View><Query><Where><IsNotNull><FieldRef Name='ID' /></IsNotNull></Where></Query><FieldRef Name='Title' /><FieldRef Name='Description' /><FieldRef Name='ApprovalRequired' /></View>"; listItems = selectedList.GetItems(camlQuery); clientContext.Load<Microsoft.SharePoint.Client.ListItemCollection>(listItems); clientContext.ExecuteQuery(); StringBuilder timeofftypes = new StringBuilder(); timeofftypes.Append("OTP Overtime Pay,LVC Vacation Pay,LSK Sick Leave Pay,LCL Consulting,LFN Funeral Leave,LJD Jury Duty,LJR Jury Duty Reversal,"); timeofftypes.Append("LML Military Leave ,LUB Union Business,LPR Person Leave,LPS Personal Leave Charge to Sick,LCE Compensation Hours Earned,"); timeofftypes.Append("LCU Compensation Hours Used,LST Short Term Disability,LWP Leave Without Pay,LMW FMLA Leave Without Pay,LMV FMLA Vacation"); timeofftypes.Append("LMS FMLA Sick,LMC FMLA Comp,LMB FMLA Leave w/o Pay w/Benefits,LMN FMLA Leave w/o Pay w/o Benefits,LMR FMLA Personal,"); timeofftypes.Append("LMP FMLA Personal Charge to Sick,LMD FMLA Short Term Disability,FST Substitute Teaching,FTV Travel Increment,PAD Additional Compensation"); if (listItems == null || listItems.Count == 0) { ListItemCreationInformation itemCreateInfo; Microsoft.SharePoint.Client.ListItem newItem; foreach (string item in timeofftypes.ToString().Split(',')) { itemCreateInfo = new ListItemCreationInformation(); newItem = selectedList.AddItem(itemCreateInfo); newItem["Title"] = item.Trim(); newItem["Description"] = item.Trim(); newItem["ApprovalRequired"] = true; newItem.Update(); } clientContext.ExecuteQuery(); return true; } return false; } catch (Exception ex) { Microsoft.SharePoint.Client.Utilities.Utility.LogCustomRemoteAppError(clientContext, Global.ProductId, ex.Message); clientContext.ExecuteQuery(); return false; } } }
private ListItem GenerateSystemLogListItem(ClientContext clientContext) { Microsoft.SharePoint.Client.Web oWebsite = clientContext.Web; clientContext.Load(oWebsite); List SystemLogList = oWebsite.Lists.GetByTitle(LOG_TITLE); var ListItemCreateInfo = new ListItemCreationInformation(); ListItem SystemLogListItem = SystemLogList.AddItem(ListItemCreateInfo); return SystemLogListItem; }
/// <summary> /// Inserts an item to the promoted links list /// </summary> /// <param name="listName">List to operate on</param> /// <param name="title">Title of the promoted link</param> /// <param name="url">Url of the promoted link</param> public void AddPromotedSiteLink(ClientContext cc, Web web, string listName, string title, string url) { List listToInsertTo = web.Lists.GetByTitle(listName); ListItemCreationInformation lici = new ListItemCreationInformation(); ListItem listItem = listToInsertTo.AddItem(lici); listItem["Title"] = title; listItem["LinkLocation"] = url; listItem["LaunchBehavior"] = "New tab"; listItem["TileOrder"] = 1; listItem.Update(); cc.ExecuteQuery(); }
/// <summary> /// /// </summary> /// <param name="clientContext"></param> public void AddComposedLooksAndSetDefaultTheme(ClientContext clientContext) { List designCatalogList = clientContext.Web.GetCatalog(124); Web web = clientContext.Web; clientContext.Load(web); clientContext.ExecuteQuery(); string masterPageUrl = string.Format("{0}/_catalogs/masterpage/oslo.master", web.ServerRelativeUrl); int displayOrder = 1; //if it is newly created sub web get the theme properites from the root web. if (themeProperties != null) { themeProperties = GetThemeListItems(clientContext); } // create items in composed looks foreach (ThemeProperties theme in themeProperties) { ListItemCreationInformation itemInfo = new ListItemCreationInformation(); ListItem item = designCatalogList.AddItem(itemInfo); item["DisplayOrder"] = displayOrder; item["Name"] = theme.ThemeName; item["Title"] = theme.ThemeName; item["ThemeUrl"] = theme.SPColorUrl; item["FontSchemeUrl"] = theme.ImageUrl; item["ImageUrl"] = theme.ImageUrl; item["MasterPageUrl"] = masterPageUrl; displayOrder++; item.Update(); } clientContext.ExecuteQuery(); var defaultTheme = themeProperties.FirstOrDefault(i => i.ThemeName == "CustomDefaultTheme"); if (defaultTheme != null) { ListItemCreationInformation itemInfo = new ListItemCreationInformation(); ListItem item = designCatalogList.AddItem(itemInfo); item["DisplayOrder"] = 0; item["Name"] = "Current"; item["Title"] = "Current"; item["ThemeUrl"] = defaultTheme.SPColorUrl; item["FontSchemeUrl"] = defaultTheme.ImageUrl; item["ImageUrl"] = defaultTheme.ImageUrl; item["MasterPageUrl"] = masterPageUrl; item.Update(); designCatalogList.Update(); //applying the theme clientContext.Web.ApplyTheme(defaultTheme.SPColorUrl, defaultTheme.FontUrl, defaultTheme.ImageUrl, true); clientContext.ExecuteQuery(); } // throw new NotImplementedException(); }
public void AddTrip([FromBody] TripEntity trip) { using (var ctx = SharePointContextHelper.GetClientContextForCurrentPrincipal()) { var tripList= ctx.Web.Lists.GetByTitle(Constants.SPLISTE); var lici = new ListItemCreationInformation(); var newItem = tripList.AddItem(lici); newItem[Constants.FELD_TITLE] = trip.Title; newItem[Constants.FELD_START] = trip.Start; newItem[Constants.FELD_END] = trip.End; newItem[Constants.FELD_CITY] = trip.City; newItem.Update(); ctx.ExecuteQuery(); } }
/// <summary> /// Adds a new request to the SharePoint site. /// </summary> /// <param name="input">A VpnRequest model</param> public void addRequest(VpnRequest input) { List spList = clientContext.Web.Lists.GetByTitle(requestNames.ListName); clientContext.Load(spList); var itemCreateInfo = new ListItemCreationInformation(); var listItem = spList.AddItem(itemCreateInfo); //pulling up the current user information User user = clientContext.Web.EnsureUser(HttpContext.Current.User.Identity.Name); clientContext.Load(user); clientContext.ExecuteQuery(); FieldUserValue userValue = new FieldUserValue(); userValue.LookupId = user.Id; //pulling up the manager information var manager = clientContext.Web.EnsureUser(input.Manager); clientContext.Load(manager); clientContext.ExecuteQuery(); FieldUserValue userValue2 = new FieldUserValue(); userValue2.LookupId = manager.Id; listItem[requestNames.internalCreatedBy] = userValue; listItem[requestNames.internalVpnRecipientFirst] = input.VPN_recipientFirst; listItem[requestNames.internalVpnRecipientLast] = input.VPN_recipientLast; listItem[requestNames.internalWorkPhone] = input.Work_Phone; listItem[requestNames.internalEmail] = input.VPN_recipientEmail; listItem[requestNames.internalUserCode] = input.VPN_userCode; listItem[requestNames.internalManager] = userValue2; listItem[requestNames.internalUserDept] = input.VPN_userDept; listItem[requestNames.internalUserStatus] = input.VPN_userStatus; listItem[requestNames.internalSystemsList] = input.Systems_List; listItem[requestNames.internalJustification] = input.VPN_justification; listItem[requestNames.internalAccessStart] = input.VPN_accessStart; listItem[requestNames.internalAccessEnd] = input.VPN_accessEnd; listItem[requestNames.internalCompanyName] = input.Company_Name; listItem[requestNames.internalCompanyOther] = input.Company_Other; listItem[requestNames.internalOfficeLocation] = input.Office_Location; listItem[requestNames.internalOfficeAddress] = input.Office_Address; listItem[requestNames.internalMachineOwner] = input.Machine_Owner; listItem[requestNames.internalExtCode] = input.Ext_code; listItem[requestNames.internalAgency] = input.Agency; listItem.Update(); clientContext.ExecuteQuery(); }
static void Main(string[] args) { string siteUrl = "http://hydpcnew00123:44393"; ClientContext clientContext = new ClientContext(siteUrl); List oList = clientContext.Web.Lists.GetByTitle("SCHOOL"); ListItemCreationInformation listCreationInformation = new ListItemCreationInformation(); ListItem oListItem = oList.AddItem(listCreationInformation); oListItem["Title"] = "Client Item"; oListItem.Update(); clientContext.ExecuteQuery(); Console.WriteLine("Success..."); Console.ReadKey(false); }
public void Create_new_list_item_in_site_creation_request_list_with_status_set_to_in_progress() { var siteRequestList = _rootWeb.Lists.GetByTitle("URDMS - Site Creation Request"); var itemCreateInfo = new ListItemCreationInformation(); var listItem = siteRequestList.AddItem(itemCreateInfo); listItem["Title"] = _siteName; listItem["UrdmsSiteTitle"] = _projectTitle; listItem["UrdmsClassification"] = null; listItem["Body"] = "This is a description of the site."; listItem["UrdmsSiteProvisioningRequestStatus"] = "In Progress"; listItem.Update(); _clientContext.ExecuteQuery(); Console.WriteLine("Created list item with ID: {0}", listItem.Id); }
public void CreateDocLibrary(ClientContext ctx, string libraryName, string requestor) { // Create new list to the host web ListCreationInformation newList = new ListCreationInformation(); newList.Title = libraryName; newList.TemplateType = (int)ListTemplateType.GenericList; newList.Description = requestor; newList.Url = libraryName; List list = ctx.Web.Lists.Add(newList); ListItemCreationInformation newItem = new ListItemCreationInformation(); ListItem item = list.AddItem(newItem); item["Title"] = requestor; item.Update(); ctx.ExecuteQuery(); }
public void AddDeaultData(ClientContext context, List list) { for (int i = 1; i <= 5; i++) { // Add a list item var itemInfo = new ListItemCreationInformation { LeafName = string.Format("List Item {0}", i) }; var item = list.AddItem(itemInfo); item["My_x0020_Number1"] = 100 + i; item["My_x0020_Number2"] = i; item.Update(); } context.ExecuteQuery(); }
/// <summary> /// Writes the log entry - asynchronous. /// </summary> /// <param name="entry">The entry.</param> private void WriteLogEntryAsync(object entry) { var logEntry = (LogEntry)entry; try { // create the context using (var clientContext = new ClientContext(SiteUrl)) { // get the site var site = clientContext.Web; if (site == null) return; // get the event log list var list = site.Lists.GetByTitle(ListName); clientContext.Load(list); clientContext.ExecuteQuery(); if (list == null) return; // add item to the list var itemCreationInfo = new ListItemCreationInformation(); var listItem = list.AddItem(itemCreationInfo); listItem[DiagnosticsFieldNames.Message] = logEntry.Message; listItem[DiagnosticsFieldNames.EventTime] = logEntry.EventTime; listItem[DiagnosticsFieldNames.HostName] = logEntry.HostName; listItem[DiagnosticsFieldNames.Login] = logEntry.CurrentUserLogin; listItem[DiagnosticsFieldNames.Source] = logEntry.Source; listItem[DiagnosticsFieldNames.StackTrace] = logEntry.StackTrace; listItem[DiagnosticsFieldNames.Type] = logEntry.Type.ToString(); listItem[DiagnosticsFieldNames.ExceptionType] = logEntry.ExceptionType; listItem.Update(); clientContext.ExecuteQuery(); } } catch (Exception ex) { Logger.Instance.Log(ex, LogType.Internal); } }
/// <summary> /// Handles events that occur after an action occurs, such as after a user adds an item to a list or deletes an item from a list. /// </summary> /// <param name="properties">Holds information about the remote event.</param> public void ProcessOneWayEvent(SPRemoteEventProperties properties) { using (ClientContext clientContext = TokenHelper.CreateRemoteEventReceiverClientContext(properties)) { if (clientContext != null) { List lstExternalEvents = clientContext.Web.Lists.GetByTitle(properties.ItemEventProperties.ListTitle); ListItem itemEvent = lstExternalEvents.GetItemById(properties.ItemEventProperties.ListItemId); clientContext.Load(itemEvent); clientContext.ExecuteQuery(); clientContext.Load(clientContext.Web); clientContext.ExecuteQuery(); try { string rerListname = ConfigurationManager.AppSettings["RERListName"].ToString(); List DemoList = clientContext.Web.Lists.GetByTitle(rerListname); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem newItem = DemoList.AddItem(itemCreateInfo); switch (properties.EventType) { case SPRemoteEventType.ItemAdded: newItem["Title"] = "Updated by RER added an item calendar : " + itemEvent["Title"]; newItem.Update(); clientContext.ExecuteQuery(); break; case SPRemoteEventType.ItemUpdated: newItem["Title"] = "Updated by RER updated an item calendar : " + itemEvent["Title"] + " " + DateTime.Now.ToShortDateString(); newItem.Update(); clientContext.ExecuteQuery(); break; } } catch(Exception ex) { Console.Write(ex.Message); } } } }
public override int Perform(OptionSet optionSet) { using (var clientContext = new ClientContext(site)) { var list = clientContext.Web.Lists.GetByTitle(listName); var itemCreateInfo = new ListItemCreationInformation(); var item = list.AddItem(itemCreateInfo); item["Title"] = title; item["PackageVersion"] = version; item.Update(); clientContext.ExecuteQuery(); var fileName = Path.GetFileName(triggerScript); AddAttachment(item.Id.ToString(), fileName, System.IO.File.ReadAllBytes(triggerScript)); } return 0; }
public void CreateListItem(Ticket ticket, string listTitle) { var context = SPClientContext.Instance.GetContext(); Web site = context.Web; List serviceTeam = site.Lists.GetByTitle(listTitle); ListItemCreationInformation listItemInfo = new ListItemCreationInformation(); ListItem teamListItem = serviceTeam.AddItem(listItemInfo); teamListItem["TicketID"] = ticket.Id; switch (listTitle) { case "Development team": teamListItem["Error"] = ticket.Body; break; case "Marketing team": teamListItem["Error"] = ticket.Body; break; } teamListItem["Status"] = AllStatus.New; teamListItem["Priority"] = Priority.Low; teamListItem.Update(); context.ExecuteQuery(); }
public ActionResult Add(Pedidos model) { var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { Web web = clientContext.Web; clientContext.Load(web); clientContext.ExecuteQuery(); ListCollection lists = web.Lists; clientContext.Load <ListCollection>(lists); clientContext.ExecuteQuery(); var pedidos = lists.GetByTitle("Pedidos"); clientContext.Load(pedidos); ListItemCreationInformation listCreationInformation = new ListItemCreationInformation(); ListItem oListItem = pedidos.AddItem(listCreationInformation); oListItem["Title"] = model.Cliente; oListItem["Unidades"] = model.Unidades; oListItem["Fecha"] = DateTime.Now; var lv = new FieldLookupValue { LookupId = model.idProducto }; oListItem["Producto"] = lv; oListItem.Update(); clientContext.ExecuteQuery(); } return(RedirectToAction("Index", new { SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri }));; } }
public void ItemAddedToListEventHandler(ClientContext clientContext, Guid listId, int listItemId) { try { Helper.AddLog("ItemAddedToListEventHandler", "Creating Record"); var testList = clientContext.Web.Lists.GetByTitle("TestList"); clientContext.Load(clientContext.Web); clientContext.Load(testList); clientContext.ExecuteQuery(); ListItemCreationInformation newItemInfo = new ListItemCreationInformation(); var newItem = testList.AddItem(newItemInfo); newItem["Title"] = DateTime.Now.ToString(); newItem["TaskDetails"] = "Item Added"; newItem["DocDetails"] = ""; newItem.Update(); clientContext.ExecuteQuery(); Helper.AddLog("ItemAddedToListEventHandler", "Created Record"); } catch (Exception oops) { Helper.AddLog("ItemAddedToListEventHandler-Error", oops.ToString()); System.Diagnostics.Trace.WriteLine(oops.Message); } }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnUpdateItem_Click(object sender, RoutedEventArgs e) { try { SPClient.List announcementsList = ctx.SPContext.Web.Lists.GetByTitle("MyFirstList"); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem listItem = announcementsList.GetItemById(this.txtBoxId.Text); listItem["Description"] = this.txtBoxDescriptionUpdate.Text; listItem.Update(); ctx.SPContext.ExecuteQuery(); MessageBox.Show("Item inserted"); this.txtBoxId.Text = ""; this.txtBoxDescriptionUpdate.Text = ""; } catch (Exception ex) { RaiseException(ex); } }
/// <summary> /// Saves the questionnaire. /// </summary> /// <param name="questions">The questions.</param> /// <param name="meetingId">The meeting identifier.</param> public static void SaveQuestionnaire(IList <Questionnaire> questions, string meetingId) { var list = Context.Web.Lists.GetByTitle("QuestionnairResponses"); foreach (var qu in questions) { var itemCreateInfo = new ListItemCreationInformation(); var listItem = list.AddItem(itemCreateInfo); listItem["Title"] = qu.Question; listItem["MeetingIdLookUp"] = new FieldLookupValue() { LookupId = Convert.ToInt32(qu.MeetingId) }; listItem["QuestionId"] = new FieldLookupValue() { LookupId = qu.QuestionnaireId }; listItem["Response"] = qu.SelectedOptions; listItem.Update(); } Context.ExecuteQuery(); UpdateQuestionCategoryOnlineMeeting(meetingId); }
public static Folder CreateFolder(ClientContext cc, List list, string sitecontent, string documentSetName) { try { ContentTypeCollection listContentTypes = list.ContentTypes; cc.Load(listContentTypes, types => types.Include(type => type.Id, type => type.Name, type => type.Parent)); //var result = cc.LoadQuery(listContentTypes.Where(c => c.Name == "document set 2")); string SiteContentName = sitecontent; var result = cc.LoadQuery(listContentTypes.Where(c => c.Name == SiteContentName)); cc.ExecuteQuery(); ContentType targetDocumentSetContentType = result.FirstOrDefault(); ListItemCreationInformation newItemInfo = new ListItemCreationInformation(); newItemInfo.UnderlyingObjectType = FileSystemObjectType.Folder; //newItemInfo.LeafName = "Document Set Kien2"; newItemInfo.LeafName = documentSetName; //newItemInfo.FolderUrl = list.RootFolder.ServerRelativeUrl.ToString(); ListItem newListItem = list.AddItem(newItemInfo); newListItem["ContentTypeId"] = targetDocumentSetContentType.Id.ToString(); newListItem.Update(); Folder folder = newListItem.Folder; return(folder); } catch (Exception ex) { Console.WriteLine("Unable to create document set"); Console.WriteLine(ex); throw; } }
public RedirectResult NewItem(string details, DateTime dueDate) { ClientContext clientContext = new ClientContext(SiteUrl); var user = clientContext.Web.EnsureUser(User.Identity.Name); clientContext.Load(user); clientContext.ExecuteQuery(); FieldUserValue userValue = new FieldUserValue(); userValue.LookupId = user.Id; List spList = clientContext.Web.Lists.GetByTitle(ListName); var info = new ListItemCreationInformation(); var item = spList.AddItem(info); item[FieldDetails] = details; item[FieldDueDate] = dueDate; item[FieldAuthor] = userValue; item.Update(); clientContext.ExecuteQuery(); return(Redirect("Items")); }
public static SharePointList CreateCustomersList() { ClientContext ctx = GetClientContext(); ctx.Load(ctx.Web); ctx.ExecuteQuery(); string listTitle = "Customers"; // delete list if it exists ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx); using (scope.StartScope()) { using (scope.StartTry()) { ctx.Web.Lists.GetByTitle(listTitle).DeleteObject(); } using (scope.StartCatch()) { } } // create and initialize ListCreationInformation object ListCreationInformation listInformation = new ListCreationInformation(); listInformation.Title = listTitle; listInformation.Url = "Lists/Customers"; listInformation.QuickLaunchOption = QuickLaunchOptions.On; listInformation.TemplateType = (int)ListTemplateType.Contacts; // Add ListCreationInformation to lists collection and return list object List list = ctx.Web.Lists.Add(listInformation); // modify additional list properties and update list.OnQuickLaunch = true; list.EnableAttachments = false; list.Update(); // send command to server to create list ctx.Load(list, l => l.Id, l => l.Title, l => l.DefaultViewUrl); ctx.ExecuteQuery(); // add an item to the list ListItemCreationInformation lici1 = new ListItemCreationInformation(); var item1 = list.AddItem(lici1); item1["Title"] = "Lennon"; item1["FirstName"] = "John"; item1.Update(); // add a second item ListItemCreationInformation lici2 = new ListItemCreationInformation(); var item2 = list.AddItem(lici2); item2["Title"] = "McCartney"; item2["FirstName"] = "Paul"; item2.Update(); // send add commands to server ctx.ExecuteQuery(); string urlAuthority = "https://" + (new Uri(siteUrl)).Authority; SharePointList newList = new SharePointList { Id = list.Id.ToString(), Title = list.Title, DefaultViewUrl = urlAuthority + list.DefaultViewUrl }; ctx.Dispose(); return(newList); }
public void CreateNewSiteRequest(SiteInformation siteRequest) { Log.Info("SPSiteRequestManager.CreateNewSiteRequest", "Entering CreateNewSiteRequest requested url {0}", siteRequest.Url); UsingContext(ctx => { Stopwatch _timespan = Stopwatch.StartNew(); var _web = ctx.Web; ctx.Load(_web); if (!_web.ListExists(SiteRequestList.TITLE)) { var _message = String.Format("The List {0} does not exist in Site {1}", SiteRequestList.TITLE, _web.Url); Log.Fatal("SPSiteRequestManager.CreateNewSiteRequest", _message); throw new DataStoreException(_message); } List list = _web.Lists.GetByTitle(SiteRequestList.TITLE); ListItemCreationInformation _listItemCreation = new ListItemCreationInformation(); ListItem _record = list.AddItem(_listItemCreation); _record[SiteRequestFields.TITLE] = siteRequest.Title; _record[SiteRequestFields.DESCRIPTION_NAME] = siteRequest.Description; _record[SiteRequestFields.TEMPLATE_NAME] = siteRequest.Template; _record[SiteRequestFields.URL_NAME] = siteRequest.Url; _record[SiteRequestFields.LCID_NAME] = siteRequest.Lcid; _record[SiteRequestFields.TIMEZONE_NAME] = siteRequest.TimeZoneId; _record[SiteRequestFields.POLICY_NAME] = siteRequest.SitePolicy; _record[SiteRequestFields.EXTERNALSHARING_NAME] = siteRequest.EnableExternalSharing; _record[SiteRequestFields.ONPREM_REQUEST_NAME] = siteRequest.SharePointOnPremises; _record[SiteRequestFields.BC_NAME] = siteRequest.BusinessCase; _record[SiteRequestFields.PROPS_NAME] = siteRequest.SiteMetadataJson; //If Settings are set to autoapprove then automatically approve the requests if (_manager.GetAppSettings().AutoApprove) { _record[SiteRequestFields.PROVISIONING_STATUS_NAME] = SiteRequestStatus.Approved.ToString(); _record[SiteRequestFields.APPROVEDDATE_NAME] = DateTime.Now; } else { _record[SiteRequestFields.PROVISIONING_STATUS_NAME] = SiteRequestStatus.New.ToString(); } FieldUserValue _siteOwner = FieldUserValue.FromUser(siteRequest.SiteOwner.Name); _record[SiteRequestFields.OWNER_NAME] = _siteOwner; //Additional Admins if (siteRequest.AdditionalAdministrators != null) { if (siteRequest.AdditionalAdministrators.Count > 0) { FieldUserValue[] _additionalAdmins = new FieldUserValue[siteRequest.AdditionalAdministrators.Count]; int _index = 0; foreach (SiteUser _user in siteRequest.AdditionalAdministrators) { FieldUserValue _adminFieldUser = FieldUserValue.FromUser(_user.Name); _additionalAdmins[_index] = _adminFieldUser; _index++; } _record[SiteRequestFields.ADD_ADMINS_NAME] = _additionalAdmins; } } _record.Update(); ctx.ExecuteQuery(); _timespan.Stop(); Log.TraceApi("SharePoint", "SPSiteRequestManager.CreateNewSiteRequest", _timespan.Elapsed); Log.Info("SPSiteRequestManager.CreateNewSiteRequest", PCResources.SiteRequestNew_Successful, siteRequest.Url); } ); }
static void Main(string[] args) { //tempFunc(); //Environment.Exit(0); Console.Title = "Uploading Blog"; Console.WriteLine(string.Format("Start {0}", DateTime.Now)); //Get Collection List <KeyArea_Channel> keyAreaChannelColl = db.getKeyArea_Channel(); List <Common.ContentType> contentTypeColl = db.getContentType(); //args.[0] = "News"; //if (args.Length == 0) //{ // Console.WriteLine("Site parameter missing..."); // Environment.Exit(100); //} // List<Blog> blogUploadCollection = db.getBlogsToUpload(args[0].ToString(),args[1].ToString()); List <Blog> blogUploadCollection = db.getBlogsToUpload("Learnet", "V"); ClientContext ctx; Web oWeb; foreach (Blog b in blogUploadCollection) { //if (b.subSite == "Learnet")//|| b.ID !=15) //{ // continue; // setSiteUrlForLearnet(b); // if (siteUrl == "Not mapped to any site") // continue; //} //else //{ // siteUrl = ConfigurationManager.AppSettings["SiteUrl"]; //} string p = (string.IsNullOrEmpty(b.project) ? "" : b.project).ToLower(); //if (p == "retail" || p == "jio") // if (p != "retail") // continue; setSiteUrlForLearnet(b, "http://digitalj3.ril.com"); if (siteUrl == "Not mapped to any site") { continue; } //set Learnet site url //ONly video // if (b.categoryType.ToString() != "V") { continue; } b.project = "Hydrocarbon"; Console.WriteLine(string.Format("Uploading Blog ID {0}", b.ID)); prepareWebContext(out ctx, out oWeb); // Console.WriteLine(formatBody(b.body,ctx)); List olist = null; if (b.categoryType.ToLower() == "t") { if ((b.siteCollection.ToLower() == "hr social" && b.subSite.ToLower() == "blogs")) { olist = oWeb.Lists.GetByTitle("MyCorner"); continue; // for mycorner blog } else { if (b.siteCollection.ToLower() == "" && b.subSite.ToLower() == "fc&a") { if (b.categories.ToLower() == "mycorner") { olist = oWeb.Lists.GetByTitle("MyCorner"); continue; // for mycorner blog } } olist = oWeb.Lists.GetByTitle("DiscussionText"); } } else { olist = oWeb.Lists.GetByTitle("Discussions List"); } ListItemCreationInformation createItem = new ListItemCreationInformation(); ListItem oItem = olist.AddItem(createItem); // parse keyArea and contenttype b.keyArea = formatKeyArea(b, ref keyAreaChannelColl, ctx); b.contentType = formatContentType(b, ref contentTypeColl); //get blogComment if exist List <Blog> blogCommentCollection = null; int blogCommentCount = 0; if (b.hasComment) { blogCommentCollection = getBlogComments(b); blogCommentCount = blogCommentCollection.Count; } Console.WriteLine("Uploading blog on site"); try { insertBlogItem(blogCommentCount, b, ctx, oItem, b.typeOfContent); } catch (Exception ex) { rollbackTransaction(oItem, ctx, ex.Message, b.rowID); continue; } if (b.hasComment) { Console.WriteLine("Uploading blog comment on site"); try { insertBlogComments(blogCommentCollection, ctx, oItem, b); } catch (Exception ex) { continue; } } if (b.likeCount > 0) { Console.WriteLine("Uploading blog like on site"); foreach (string user in b.likedBy.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)) { User likedUser = resolveUser(user, ctx); db.blogAnalyticsCommentLike((string.IsNullOrEmpty(b.project) ? b.channel : b.project), ctx.Web.Title, Convert.ToInt16(oItem["ID"]), "LIKE", likedUser.Title, likedUser.Email, (b.published.ToString() == "01-01-0001 00:00:00" ? b.modified : b.published), b.categoryType); } } if (b.hasAttachement) { Console.WriteLine("Uploading attachment on site"); ctx.Load(oItem); ctx.ExecuteQuery(); DataRowCollection dataRows = db.getBlogAttachments(b.siteCollection, b.subSite, b.ID).Rows; foreach (DataRow dr in dataRows) { string filePath = dr["DownloadPath"].ToString();// System.Web.HttpUtility.UrlDecode(dr["DownloadPath"].ToString()); if (filePath == "") { if (dataRows.Count == 0) { Console.WriteLine("Cannot access blank path"); rollbackTransaction(oItem, ctx, "Cannot access blank path", b.rowID); return; } else { continue; } } else if (filePath.ToLower() == "na") { continue; } FileInfo temp = new FileInfo(filePath); if (isImage(temp) && (dr["AttachmentType"].ToString().ToLower().Trim() == "normal" || dr["AttachmentType"].ToString().ToLower().Trim() == "thumbnail")) { uploadImagesForTextBlog(ctx, filePath, temp, b.categoryType); continue; } using (System.IO.FileStream fileStream = new System.IO.FileInfo(filePath).Open(System.IO.FileMode.Open)) { try { var attachment = new AttachmentCreationInformation(); attachment.FileName = System.Web.HttpUtility.UrlDecode(temp.Name.Substring(temp.Name.IndexOf("_") + 1)); attachment.ContentStream = fileStream; // My file stream Attachment att = oItem.AttachmentFiles.Add(attachment); ctx.Load(att); ctx.ExecuteQuery(); } catch (Exception ex) { //string targetFileUrl = string.Format("{0}/Lists/DiscussionsList/Attachments/{1}/{2}", ctx.Web.ServerRelativeUrl, oItem["ID"], System.Web.HttpUtility.UrlDecode(temp.Name.Substring(temp.Name.IndexOf("_") + 1)),fileStream,true); //Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, targetFileUrl, fileStream, true); Console.WriteLine(ex.Message); if (!ex.Message.Contains("The specified name is already in use.")) { rollbackTransaction(oItem, ctx, ex.Message, b.rowID); } } } } } } // UPDATE MIGRATED SITE STATUS Console.WriteLine("Updatint Migrated Site Status"); var siteName = (from site in blogUploadCollection select new { siteColl = site.siteCollection, subWeb = site.subSite }).Distinct().ToList(); foreach (var obj in siteName) { db.completeMigratedStatusForSite(obj.siteColl, obj.subWeb); } Console.WriteLine(string.Format("End {0}", DateTime.Now)); }
public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation) { using (var scope = new PnPMonitoredScope(this.Name)) { if (template.Lists.Any()) { var rootWeb = (web.Context as ClientContext).Site.RootWeb; web.EnsureProperties(w => w.ServerRelativeUrl); web.Context.Load(web.Lists, lc => lc.IncludeWithDefaultProperties(l => l.RootFolder.ServerRelativeUrl)); web.Context.ExecuteQueryRetry(); var existingLists = web.Lists.AsEnumerable <List>().Select(existingList => existingList.RootFolder.ServerRelativeUrl).ToList(); var serverRelativeUrl = web.ServerRelativeUrl; #region DataRows foreach (var listInstance in template.Lists) { if (listInstance.DataRows != null && listInstance.DataRows.Any()) { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Processing_data_rows_for__0_, listInstance.Title); // Retrieve the target list var list = web.Lists.GetByTitle(parser.ParseString(listInstance.Title)); web.Context.Load(list); // Retrieve the fields' types from the list Microsoft.SharePoint.Client.FieldCollection fields = list.Fields; web.Context.Load(fields, fs => fs.Include(f => f.InternalName, f => f.FieldTypeKind, f => f.TypeAsString)); web.Context.ExecuteQueryRetry(); var keyColumnType = "Text"; var parsedKeyColumn = parser.ParseString(listInstance.DataRows.KeyColumn); if (!string.IsNullOrEmpty(parsedKeyColumn)) { var keyColumn = fields.FirstOrDefault(f => f.InternalName.Equals(parsedKeyColumn, StringComparison.InvariantCultureIgnoreCase)); if (keyColumn != null) { switch (keyColumn.FieldTypeKind) { case FieldType.User: case FieldType.Lookup: keyColumnType = "Lookup"; break; case FieldType.URL: keyColumnType = "Url"; break; case FieldType.DateTime: keyColumnType = "DateTime"; break; case FieldType.Number: case FieldType.Counter: keyColumnType = "Number"; break; } } } foreach (var dataRow in listInstance.DataRows) { try { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_list_item__0_, listInstance.DataRows.IndexOf(dataRow) + 1); bool create = true; ListItem listitem = null; if (!string.IsNullOrEmpty(listInstance.DataRows.KeyColumn)) { // Get value from key column var dataRowValues = dataRow.Values.Where(v => v.Key == listInstance.DataRows.KeyColumn); // if it is empty, skip the check if (dataRowValues.Any()) { var query = $@"<View><Query><Where><Eq><FieldRef Name=""{parsedKeyColumn}""/><Value Type=""{keyColumnType}"">{dataRowValues.FirstOrDefault().Value}</Value></Eq></Where></Query><RowLimit>1</RowLimit></View>"; var camlQuery = new CamlQuery() { ViewXml = query }; var existingItems = list.GetItems(camlQuery); list.Context.Load(existingItems); list.Context.ExecuteQueryRetry(); if (existingItems.Count > 0) { if (listInstance.DataRows.UpdateBehavior == UpdateBehavior.Skip) { create = false; } else { listitem = existingItems[0]; create = true; } } } } if (create) { if (listitem == null) { var listitemCI = new ListItemCreationInformation(); listitem = list.AddItem(listitemCI); } foreach (var dataValue in dataRow.Values) { Field dataField = fields.FirstOrDefault( f => f.InternalName == parser.ParseString(dataValue.Key)); if (dataField != null) { String fieldValue = parser.ParseString(dataValue.Value); switch (dataField.FieldTypeKind) { case FieldType.Geolocation: // FieldGeolocationValue - Expected format: Altitude,Latitude,Longitude,Measure var geolocationArray = fieldValue.Split(','); if (geolocationArray.Length == 4) { var geolocationValue = new FieldGeolocationValue { Altitude = Double.Parse(geolocationArray[0]), Latitude = Double.Parse(geolocationArray[1]), Longitude = Double.Parse(geolocationArray[2]), Measure = Double.Parse(geolocationArray[3]), }; listitem[parser.ParseString(dataValue.Key)] = geolocationValue; } else { listitem[parser.ParseString(dataValue.Key)] = fieldValue; } break; case FieldType.Lookup: // FieldLookupValue - Expected format: LookupID or LookupID,LookupID,LookupID... if (fieldValue.Contains(",")) { var lookupValues = new List <FieldLookupValue>(); fieldValue.Split(',').All(value => { lookupValues.Add(new FieldLookupValue { LookupId = int.Parse(value), }); return(true); }); listitem[parser.ParseString(dataValue.Key)] = lookupValues.ToArray(); } else { var lookupValue = new FieldLookupValue { LookupId = int.Parse(fieldValue), }; listitem[parser.ParseString(dataValue.Key)] = lookupValue; } break; case FieldType.URL: // FieldUrlValue - Expected format: URL,Description var urlArray = fieldValue.Split(','); var linkValue = new FieldUrlValue(); if (urlArray.Length == 2) { linkValue.Url = urlArray[0]; linkValue.Description = urlArray[1]; } else { linkValue.Url = urlArray[0]; linkValue.Description = urlArray[0]; } listitem[parser.ParseString(dataValue.Key)] = linkValue; break; case FieldType.User: // FieldUserValue - Expected format: loginName or loginName,loginName,loginName... if (fieldValue.Contains(",")) { var userValues = new List <FieldUserValue>(); fieldValue.Split(',').All(value => { var user = web.EnsureUser(value); web.Context.Load(user); web.Context.ExecuteQueryRetry(); if (user != null) { userValues.Add(new FieldUserValue { LookupId = user.Id, });; } return(true); }); listitem[parser.ParseString(dataValue.Key)] = userValues.ToArray(); } else { var user = web.EnsureUser(fieldValue); web.Context.Load(user); web.Context.ExecuteQueryRetry(); if (user != null) { var userValue = new FieldUserValue { LookupId = user.Id, }; listitem[parser.ParseString(dataValue.Key)] = userValue; } else { listitem[parser.ParseString(dataValue.Key)] = fieldValue; } } break; case FieldType.DateTime: var dateTime = DateTime.MinValue; if (DateTime.TryParse(fieldValue, out dateTime)) { listitem[parser.ParseString(dataValue.Key)] = dateTime; } break; default: listitem[parser.ParseString(dataValue.Key)] = fieldValue; break; } listitem.Update(); } } web.Context.ExecuteQueryRetry(); // TODO: Run in batches? if (dataRow.Security != null && (dataRow.Security.ClearSubscopes == true || dataRow.Security.CopyRoleAssignments == true || dataRow.Security.RoleAssignments.Count > 0)) { listitem.SetSecurity(parser, dataRow.Security); } } } catch (Exception ex) { if (ex.GetType().Equals(typeof(ServerException)) && (ex as ServerException).ServerErrorTypeName.Equals("Microsoft.SharePoint.SPDuplicateValuesFoundException", StringComparison.InvariantCultureIgnoreCase) && applyingInformation.IgnoreDuplicateDataRowErrors) { scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_listitem_duplicate); continue; } else { scope.LogError(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_listitem_failed___0_____1_, ex.Message, ex.StackTrace); throw; } } } } } #endregion } } return(parser); }
protected override void ExecuteCmdlet() { List list = null; if (List != null) { list = List.GetList(SelectedWeb); } if (list != null) { ListItemCreationInformation liCI = new ListItemCreationInformation(); if (Folder != null) { // Create the folder if it doesn't exist var rootFolder = list.EnsureProperty(l => l.RootFolder); var targetFolder = SelectedWeb.EnsureFolder(rootFolder, Folder); liCI.FolderUrl = targetFolder.ServerRelativeUrl; } var item = list.AddItem(liCI); if (ContentType != null) { ContentType ct = null; if (ContentType.ContentType == null) { if (ContentType.Id != null) { ct = SelectedWeb.GetContentTypeById(ContentType.Id, true); } else if (ContentType.Name != null) { ct = SelectedWeb.GetContentTypeByName(ContentType.Name, true); } } else { ct = ContentType.ContentType; } if (ct != null) { ct.EnsureProperty(w => w.StringId); item["ContentTypeId"] = ct.StringId; item.Update(); ClientContext.ExecuteQueryRetry(); } } if (Values != null) { item = ListItemHelper.UpdateListItem(item, Values, false, (warning) => { WriteWarning(warning); }, (terminatingErrorMessage, terminatingErrorCode) => { ThrowTerminatingError(new ErrorRecord(new Exception(terminatingErrorMessage), terminatingErrorCode, ErrorCategory.InvalidData, this)); }); } item.Update(); ClientContext.Load(item); ClientContext.ExecuteQueryRetry(); WriteObject(item); } }
static void Main(string[] args) { //configure log file var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "log.txt" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); // Rules for mapping loggers to targets config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); // Apply config LogManager.Configuration = config; Logger _log_ = NLog.LogManager.GetCurrentClassLogger(); //connect var siteUrl = ConfigurationManager.AppSettings["siteUrl"]; using (ClientContext clientContext = new ClientContext(siteUrl)) { Console.WriteLine("Enter username:"******"Enter password:"******""; //mask the password with * in console do { ConsoleKeyInfo key = Console.ReadKey(true); if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter) { password += key.KeyChar; Console.Write("*"); } else { if (key.Key == ConsoleKey.Backspace && password.Length > 0) { password = password.Substring(0, (password.Length - 1)); Console.Write("\b \b"); } else if (key.Key == ConsoleKey.Enter) { break; } } } while (true); try { NetworkCredential _myCredentials = new NetworkCredential(username, password); clientContext.Credentials = _myCredentials; clientContext.ExecuteQuery(); Console.WriteLine("Connected to {0}", siteUrl); _log_.Info("Connected to {0}", siteUrl); } catch (Exception ex) { Console.WriteLine("Couldn't connect to {0} with your credentials!", siteUrl); _log_.Error("Couldn't connect to {0} with your credentials!: {1}", siteUrl, ex); Environment.Exit(-1); } try { var site = clientContext.Site; var web = clientContext.Site.RootWeb; clientContext.Load(web, w => w.ServerRelativeUrl); clientContext.ExecuteQuery(); } catch (Exception ex) { _log_.Error("Couldn't load site: {0}", ex); } //read the csv files //BANKS List <string> Codes = new List <string>(); List <string> Names = new List <string>(); List <string> Regions = new List <string>(); List <string> Bics = new List <string>(); List <string> Tels = new List <string>(); List <string> Faxes = new List <string>(); List <string> WebSites = new List <string>(); try { Console.WriteLine("Reading banks Csv..."); using (var reader = new StreamReader(ConfigurationManager.AppSettings["bankCSV"], Encoding.Default)) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { csv.Configuration.Delimiter = ";"; csv.Configuration.HasHeaderRecord = true; csv.Read(); csv.ReadHeader(); while (csv.Read()) { string code = csv.GetField <string>("ΑΡΙΘΜΗΤΙΚΟΣ ΚΩΔΙΚΟΣ ΤΗΣ ΤΡΑΠΕΖΑΣ"); if (code == "") { code = "-"; } else if (code.Length == 2) { code = "0" + code; } Codes.Add(code); string name = csv.GetField <string>("ΕΠΙΣΗΜΗ ΟΝΟΜΑΣΙΑ ΤΗΣ ΤΡΑΠΕΖΑΣ (ΕΛΛΗΝΙΚΑ)"); if (name == "") { name = "-"; } Names.Add(name); string region = csv.GetField <string>("ΔΙΕΥΘΥΝΣΗ ΕΔΡΑΣ ΤΗΣ ΤΡΑΠΕΖΑΣ (ΕΛΛΗΝΙΚΑ)"); if (region == "") { region = "-"; } Regions.Add(region); string bic = csv.GetField <string>("SWIFT BIC"); if (bic == "") { bic = "-"; } Bics.Add(bic); string tel = csv.GetField <string>("ΤΗΛΕΦΩΝΙΚΟ ΚΕΝΤΡΟ"); if (tel == "") { tel = "-"; } Tels.Add(tel); string fax = csv.GetField <string>("ΚΕΝΤΡΙΚΟFAX"); if (fax == "") { fax = "-"; } Faxes.Add(fax); string webSite = csv.GetField <string>("ΗΛΕΚΤΡΟΝΙΚΗ ΔΙΕΥΘΥΝΣΗ-URL"); if (webSite == "") { webSite = "-"; } WebSites.Add(webSite); } } _log_.Info("Banks csv read"); } catch (Exception ex) { Console.WriteLine("Couldn't read {0}!", ConfigurationManager.AppSettings["bankCSV"]); _log_.Error("Couldn't read {0}: {1}", ConfigurationManager.AppSettings["bankCSV"], ex); } //BRANCHES List <string> Hebics = new List <string>(); List <string> BranchNames = new List <string>(); List <string> BranchRegions = new List <string>(); List <string> Addresses = new List <string>(); List <string> BranchTels = new List <string>(); List <string> Communities = new List <string>(); List <string> Municipalities = new List <string>(); List <string> ZipCodes = new List <string>(); try { Console.WriteLine("Reading branches Csv..."); using (var reader = new StreamReader(ConfigurationManager.AppSettings["branchCSV"], Encoding.Default)) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { csv.Configuration.Delimiter = ";"; csv.Configuration.HasHeaderRecord = true; csv.Read(); csv.ReadHeader(); while (csv.Read()) { string hebic = csv.GetField <string>("ΚΩΔΙΚΟΣ HEBIC"); if (hebic == "") { hebic = "-"; } else if (hebic.Length == 6) { hebic = "0" + hebic; } Hebics.Add(hebic); string name = csv.GetField <string>("ΟΝΟΜΑΣΙΑ ΚΑΤΑΣΤΗΜΑΤΟΣ (ΕΛΛΗΝΙΚΑ)"); if (name == "") { name = "-"; } BranchNames.Add(name); string region = csv.GetField <string>("ΟΝΟΜΑΣΙΑ ΤΟΠΟΘΕΣΙΑΣ ΚΑΤΑΣΤΗΜΑΤΟΣ (ΕΛΛΗΝΙΚΑ)"); if (region == "") { region = "-"; } BranchRegions.Add(region); string address = csv.GetField <string>("Διεύθυνση ΕΛΛΗΝΙΚΑ"); if (address == "") { address = "-"; } Addresses.Add(address); string tel = csv.GetField <string>("ΑΡΙΘΜΟΣ ΤΗΛΕΦΩΝΟΥ"); if (tel == "") { tel = "-"; } BranchTels.Add(tel); string community = csv.GetField <string>("ΤΑΧΥΔΡΟΜΙΚΗ ΠΕΡΙΟΧΗ (ΕΛΛΗΝΙΚΑ)"); if (community == "") { community = "-"; } Communities.Add(community); string municipality = csv.GetField <string>("ΔΗΜΟΣ/ ΚΟΙΝΟΤΗΤΑ"); if (municipality == "") { municipality = "-"; } Municipalities.Add(municipality); string zipcode = ""; string temp1 = csv.GetField <string>("ΓΡΑΦΕΙΟ ΤΑΧΥΔΡΟΜΙΚΟΥ ΚΩΔΙΚΑ"); string temp2 = csv.GetField <string>("ΔΙΑΔΡΟΜΗ ΤΑΧΥΔΡΟΜΙΚΟΥ ΚΩΔΙΚΑ"); if (temp1.Length == 1) { temp1 = "00" + temp1; } else if (temp1.Length == 2) { temp1 = "0" + temp1; } if (temp2.Length == 1) { temp2 = "0" + temp2; } if (temp1 == "" && temp2 == "") { zipcode = "-"; } else { zipcode = temp1 + temp2; } ZipCodes.Add(zipcode); } } _log_.Info("Branches csv read"); } catch (Exception ex) { Console.WriteLine("Couldn't read {0}!", ConfigurationManager.AppSettings["bankCSV"]); _log_.Error("Couldn't read {0}: {1}", ConfigurationManager.AppSettings["bankCSV"], ex); } //read BANKS list List listBanks = clientContext.Web.Lists.GetByTitle("BANKS"); try { clientContext.Load(listBanks); clientContext.ExecuteQuery(); } catch (Exception ex) { Console.WriteLine("Couldn't load list Banks!"); _log_.Error("Couldn't load list Banks: {0}", ex); } if (listBanks != null) { CamlQuery query = new CamlQuery(); query.ViewXml = "<View><Query><OrderBy><FieldRef Name='bankCode' Ascending='True' /></OrderBy></Query></View>"; ListItemCollection collListItem = listBanks.GetItems(query); try { clientContext.Load(collListItem); clientContext.ExecuteQuery(); } catch (Exception ex) { _log_.Error("Couldn't get list items of list Banks: {0}", ex); } int l = 0; int c = 0; int lstop = collListItem.Count; int cstop = Codes.Count; Console.WriteLine("Updating Banks..."); while (c < cstop) { string sharepointCode = collListItem[l]["bankCode"].ToString(); bool flag = false; if (Codes[c] == sharepointCode) { string sharepointName = collListItem[l]["bankName"].ToString(); string csvName = Names[c]; if (!(collListItem[l]["bankName"].ToString().Equals(Names[c]))) { collListItem[l]["bankName"] = Names[c]; flag = true; } if (!(collListItem[l]["bankRegion"].ToString().Equals(Regions[c]))) { collListItem[l]["bankRegion"] = Regions[c]; flag = true; } if (!(collListItem[l]["bankBic"].ToString().Equals(Bics[c]))) { collListItem[l]["bankBic"] = Bics[c]; flag = true; } if (!(collListItem[l]["bankTel"].ToString().Equals(Tels[c]))) { collListItem[l]["bankTel"] = Tels[c]; flag = true; } if (!(collListItem[l]["bankFax"].ToString().Equals(Faxes[c]))) { collListItem[l]["bankFax"] = Faxes[c]; flag = true; } if (!(collListItem[l]["bankWebSite"].ToString().Equals(WebSites[c]))) { collListItem[l]["bankWebSite"] = WebSites[c]; flag = true; } if (flag) { try { collListItem[l].Update(); clientContext.ExecuteQuery(); } catch (Exception ex) { _log_.Error("Couldn't update bank item, c={0}, l={1}: {2}", c, l, ex); } } l++; c++; } else if (Codes[c].CompareTo(sharepointCode) > 0) { try { collListItem[l].DeleteObject(); clientContext.ExecuteQuery(); } catch (Exception ex) { _log_.Error("Couldn't delete bank item, c={0}, l={1}: {2}", c, l, ex); } lstop--; } else { ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem newListItem = listBanks.AddItem(itemCreateInfo); newListItem["bankCode"] = Codes[c]; newListItem["bankName"] = Names[c]; newListItem["bankRegion"] = Regions[c]; newListItem["bankBic"] = Bics[c]; newListItem["bankTel"] = Tels[c]; newListItem["bankFax"] = Faxes[c]; newListItem["bankWebSite"] = WebSites[c]; try { newListItem.Update(); clientContext.ExecuteQuery(); } catch (Exception ex) { _log_.Error("Couldn't add new bank item, c={0}, l={1}: {2}", c, l, ex); } c++; } if (l == lstop) { break; } } if (c == cstop) { for (int i = l; i < lstop; i++) { try { collListItem[l].DeleteObject(); clientContext.ExecuteQuery(); } catch (Exception ex) { _log_.Error("Couldn't delete bank item (c==cstop), c={0} l={1} {2}", c, l, ex); } } } if (l == lstop) { for (int i = c; i < cstop; i++) { ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem newListItem = listBanks.AddItem(itemCreateInfo); newListItem["bankCode"] = Codes[i]; newListItem["bankName"] = Names[i]; newListItem["bankRegion"] = Regions[i]; newListItem["bankBic"] = Bics[i]; newListItem["bankTel"] = Tels[i]; newListItem["bankFax"] = Faxes[i]; newListItem["bankWebSite"] = WebSites[i]; try { newListItem.Update(); clientContext.ExecuteQuery(); } catch (Exception ex) { _log_.Error("Couldn't add new bank item (l==lstop), c={0}, l={1}: {2}", c, l, ex); } } } _log_.Info("Banks List Updated"); } //read BRANCHES list List listBranches = clientContext.Web.Lists.GetByTitle("BRANCHES"); try { clientContext.Load(listBranches); clientContext.ExecuteQuery(); } catch (Exception ex) { Console.WriteLine("Couldn't load list Branches!"); _log_.Error("Couldn't load list Branches: {0}", ex); } if (listBranches != null) { CamlQuery query = new CamlQuery(); query.ViewXml = "<View><Query><OrderBy><FieldRef Name='branchHebic' Ascending='True' /></OrderBy></Query></View>"; ListItemCollection collListItem = listBranches.GetItems(query); try { clientContext.Load(collListItem); clientContext.ExecuteQuery(); } catch (Exception ex) { _log_.Error("Couldn't get list items of list Branches: {0}", ex); } int l = 0; int c = 0; int lstop = collListItem.Count; int cstop = Hebics.Count; int mycount = 100; Console.WriteLine("Updating Branches..."); while (c < cstop) { if (c % 100 == 99) { Console.WriteLine(" {0} items processed", mycount); mycount += 100; } string sharepointHebic = collListItem[l]["branchHebic"].ToString(); if (Hebics[c] == sharepointHebic) { bool flag = false; string sharepointName = collListItem[l]["branchName"].ToString(); string csvName = BranchNames[c]; if (!(collListItem[l]["branchName"].ToString().Equals(BranchNames[c]))) { collListItem[l]["branchName"] = BranchNames[c]; flag = true; } if (!(collListItem[l]["branchRegion"].ToString().Equals(BranchRegions[c]))) { collListItem[l]["branchRegion"] = BranchRegions[c]; flag = true; } if (!(collListItem[l]["branchAddress"].ToString().Equals(Addresses[c]))) { collListItem[l]["branchAddress"] = Addresses[c]; flag = true; } if (!(collListItem[l]["branchTel"].ToString().Equals(BranchTels[c]))) { collListItem[l]["branchTel"] = BranchTels[c]; flag = true; } if (!(collListItem[l]["branchCommunity"].ToString().Equals(Communities[c]))) { collListItem[l]["branchCommunity"] = Communities[c]; flag = true; } if (!(collListItem[l]["branchMunicipality"].ToString().Equals(Municipalities[c]))) { collListItem[l]["branchMunicipality"] = Municipalities[c]; flag = true; } if (!(collListItem[l]["branchZipCode"].ToString().Equals(ZipCodes[c]))) { collListItem[l]["branchZipCode"] = ZipCodes[c]; flag = true; } if (flag) { try { collListItem[l].Update(); clientContext.ExecuteQuery(); } catch (Exception ex) { _log_.Error("Couldn't update branch item, c={0}, l={1}: {2}", c, l, ex); } } l++; c++; } else if (Hebics[c].CompareTo(sharepointHebic) > 0) { try { collListItem[l].DeleteObject(); clientContext.ExecuteQuery(); } catch (Exception ex) { _log_.Error("Couldn't delete branch item, c={0}, l={1}: {2}", c, l, ex); } lstop--; } else { ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem newListItem = listBranches.AddItem(itemCreateInfo); newListItem["branchHebic"] = Hebics[c]; newListItem["branchName"] = BranchNames[c]; newListItem["branchRegion"] = BranchRegions[c]; newListItem["branchAddress"] = Addresses[c]; newListItem["branchTel"] = BranchTels[c]; newListItem["branchCommunity"] = Communities[c]; newListItem["branchMunicipality"] = Municipalities[c]; newListItem["branchZipCode"] = ZipCodes[c]; try { newListItem.Update(); clientContext.ExecuteQuery(); } catch (Exception ex) { _log_.Error("Couldn't add new branch item, c={0}, l={1}: {2}", c, l, ex); } c++; } if (l == lstop) { break; } } if (c == cstop) { for (int i = l; i < lstop; i++) { try { collListItem[l].DeleteObject(); clientContext.ExecuteQuery(); } catch (Exception ex) { _log_.Error("Couldn't delete branch item (c==cstop), c={0}, l={1}: {2}", c, l, ex); } } } if (l == lstop) { for (int i = c; i < cstop; i++) { ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem newListItem = listBranches.AddItem(itemCreateInfo); newListItem["branchHebic"] = Hebics[i]; newListItem["branchName"] = BranchNames[i]; newListItem["branchRegion"] = BranchRegions[i]; newListItem["branchAddress"] = Addresses[i]; newListItem["branchTel"] = BranchTels[i]; newListItem["branchCommunity"] = Communities[i]; newListItem["branchMunicipality"] = Municipalities[i]; newListItem["branchZipCode"] = ZipCodes[i]; try { newListItem.Update(); clientContext.ExecuteQuery(); } catch (Exception ex) { _log_.Error("Couldn't add new branch item (l==lstop), c={0}, l={1}: {2}", c, l, ex); } } } _log_.Info("Branches List Updated"); } } }
public void SetBlankTaxonomyFieldValueTest() { var fieldName = "Test2_" + DateTime.Now.ToFileTime(); var fieldId = Guid.NewGuid(); using (var clientContext = TestCommon.CreateClientContext()) { // Retrieve list var list = clientContext.Web.Lists.GetById(_listId); clientContext.Load(list); clientContext.ExecuteQueryRetry(); // Retrieve Termset TaxonomySession session = TaxonomySession.GetTaxonomySession(clientContext); var termSet = session.GetDefaultSiteCollectionTermStore().GetTermSet(_termSetId); clientContext.Load(termSet); clientContext.ExecuteQueryRetry(); // Create taxonomyfield first TaxonomyFieldCreationInformation fieldCI = new TaxonomyFieldCreationInformation() { Id = fieldId, DisplayName = fieldName, InternalName = fieldName, Group = "Test Fields Group", TaxonomyItem = termSet }; //Add Enterprise keywords field so that we have at least two taxonomy fields in the list var keyworkdField = clientContext.Web.Fields.GetByInternalNameOrTitle("TaxKeyword"); clientContext.Load(keyworkdField, f => f.Id); list.Fields.Add(keyworkdField); var field = list.CreateTaxonomyField(fieldCI); // Create Item ListItemCreationInformation itemCi = new ListItemCreationInformation(); var item = list.AddItem(itemCi); item.Update(); clientContext.Load(item); clientContext.ExecuteQueryRetry(); //First set a valid value in at least two taxonomy fields (same term can be used if one field is the keyword field) item.SetTaxonomyFieldValue(fieldId, _termName, _termId); item.SetTaxonomyFieldValue(keyworkdField.Id, _termName, _termId); clientContext.Load(item, i => i[fieldName], i => i["TaxCatchAll"]); clientContext.ExecuteQueryRetry(); Assert.AreEqual(2, (item["TaxCatchAll"] as FieldLookupValue[]).Length, "TaxCatchAll does not have 2 entries"); var value = item[fieldName] as TaxonomyFieldValue; Assert.AreEqual(_termId.ToString(), value.TermGuid, "Term not set correctly"); //Set a blank value in one of the taxonomy fields. item.SetTaxonomyFieldValue(fieldId, string.Empty, Guid.Empty); var taxonomyField = clientContext.CastTo <TaxonomyField>(field); clientContext.Load(taxonomyField, t => t.TextField); clientContext.Load(item, i => i[fieldName], i => i["TaxCatchAll"]); clientContext.ExecuteQueryRetry(); var hiddenField = list.Fields.GetById(taxonomyField.TextField); clientContext.Load(hiddenField, f => f.InternalName); clientContext.ExecuteQueryRetry(); Assert.AreEqual(1, (item["TaxCatchAll"] as FieldLookupValue[]).Length, "TaxCatchAll does not have 1 entry"); object taxonomyFieldValue = item[fieldName]; object hiddenFieldValue = item[hiddenField.InternalName]; Assert.IsNull(taxonomyFieldValue, "taxonomyFieldValue is not null"); Assert.IsNull(hiddenFieldValue, "hiddenFieldValue is not null"); } }
/// <summary> /// Add list items to a list. /// </summary> /// <param name="web">Web where the list exists.</param> /// <param name="list">List to add items to.</param> /// <param name="dataRows">XML configration for items to add.</param> /// <param name="tokenParser"></param> private static void AddItemsToList(this Web web, List list, IEnumerable <XElement> dataRows, TokenParser tokenParser) { // Retrieve the fields' types from the list FieldCollection fields = list.Fields; web.Context.Load(fields, fs => fs.Include(f => f.InternalName, f => f.FieldTypeKind)); web.Context.ExecuteQueryRetry(); foreach (var dataRow in dataRows) { try { var listitemCI = new ListItemCreationInformation(); var listitem = list.AddItem(listitemCI); foreach (var dataValue in dataRow.Attributes()) { Field dataField = fields.FirstOrDefault( f => f.InternalName == dataValue.Name.LocalName); if (dataField != null) { String fieldValue = tokenParser.ParseString(dataValue.Value); switch (dataField.FieldTypeKind) { case FieldType.Geolocation: // FieldGeolocationValue - Expected format: Altitude,Latitude,Longitude,Measure var geolocationArray = fieldValue.Split(','); if (geolocationArray.Length == 4) { var geolocationValue = new FieldGeolocationValue { Altitude = Double.Parse(geolocationArray[0]), Latitude = Double.Parse(geolocationArray[1]), Longitude = Double.Parse(geolocationArray[2]), Measure = Double.Parse(geolocationArray[3]), }; listitem[dataValue.Name.LocalName] = geolocationValue; } else { listitem[dataValue.Name.LocalName] = fieldValue; } break; case FieldType.Lookup: // FieldLookupValue - Expected format: LookupID var lookupValue = new FieldLookupValue { LookupId = Int32.Parse(fieldValue), }; listitem[dataValue.Name.LocalName] = lookupValue; break; case FieldType.URL: // FieldUrlValue - Expected format: URL,Description var urlArray = fieldValue.Split(','); var linkValue = new FieldUrlValue(); if (urlArray.Length == 2) { linkValue.Url = urlArray[0]; linkValue.Description = urlArray[1]; } else { linkValue.Url = urlArray[0]; linkValue.Description = urlArray[0]; } listitem[dataValue.Name.LocalName] = linkValue; break; case FieldType.User: // FieldUserValue - Expected format: loginName var user = web.EnsureUser(fieldValue); web.Context.Load(user); web.Context.ExecuteQueryRetry(); if (user != null) { var userValue = new FieldUserValue { LookupId = user.Id, }; listitem[dataValue.Name.LocalName] = userValue; } else { listitem[dataValue.Name.LocalName] = fieldValue; } break; case FieldType.Invalid: if (dataField.GetType() == typeof(Microsoft.SharePoint.Client.Taxonomy.TaxonomyField)) { var txField = web.Context.CastTo <TaxonomyField>(dataField); web.Context.Load(txField, tx => tx.TermSetId); web.Context.ExecuteQueryRetry(); var ts = TaxonomySession.GetTaxonomySession(web.Context); var termSet = ts.GetDefaultSiteCollectionTermStore().GetTermSet(txField.TermSetId); var term = termSet.Terms.GetByName(fieldValue); web.Context.Load(term, t => t.Id); web.Context.ExecuteQueryRetry(); var termValue = new TaxonomyFieldValue(); termValue.TermGuid = term.Id.ToString(); txField.SetFieldValueByValue(listitem, termValue); } else { listitem[dataValue.Name.LocalName] = fieldValue; } break; default: listitem[dataValue.Name.LocalName] = fieldValue; break; } } listitem.Update(); } web.Context.ExecuteQueryRetry(); // TODO: Run in batches? } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
public static void addNewRecord(DataRow dr, List targetList, ClientContext ctx) { //Instantiate dictionary to temporarily store field values Dictionary <string, object> itemFieldValues = new Dictionary <string, object>(); foreach (DataColumn dc in dr.Table.Columns) { //Get site column that matches the property name //ASSUMPTION: Your property names match the internal names of the corresponding site columns Microsoft.SharePoint.Client.Field matchingField = targetList.Fields.GetByInternalNameOrTitle(dc.ColumnName); ctx.Load(matchingField); ctx.ExecuteQuery(); //Switch on the field type switch (matchingField.FieldTypeKind) { case FieldType.DateTime: try { DateTime date = DateTime.Parse(dr[dc].ToString()); itemFieldValues.Add(matchingField.InternalName, date); } catch (Exception ex) { } break; case FieldType.User: FieldUserValue userFieldValue = GetUserFieldValue(dr[dc].ToString(), ctx); if (userFieldValue != null) { itemFieldValues.Add(matchingField.InternalName, userFieldValue); } else { throw new Exception("User field value could not be added: " + dr[dc].ToString()); } break; case FieldType.Lookup: var lookupField = ctx.CastTo <FieldLookup>(matchingField); ctx.Load(lookupField); ctx.ExecuteQuery(); FieldLookupValue lookupFieldValue = GetLookupFieldValue(dr[dc].ToString(), lookupField.LookupList, lookupField.LookupField, ctx); if (lookupFieldValue != null) { itemFieldValues.Add(matchingField.InternalName, lookupFieldValue); } else { throw new Exception("Lookup field value could not be added: " + dr[dc].ToString()); } break; case FieldType.Invalid: switch (matchingField.TypeAsString) { case "TaxonomyFieldType": TaxonomyFieldValue taxFieldValue = GetTaxonomyFieldValue(dr[dc].ToString(), matchingField, ctx); if (taxFieldValue != null) { itemFieldValues.Add(matchingField.InternalName, taxFieldValue); } else { throw new Exception("Taxonomy field value could not be added: " + dr[dc].ToString()); } break; default: //Code for publishing site columns not implemented continue; } break; default: itemFieldValues.Add(matchingField.InternalName, dr[dc]); break; } } //Add new item to list ListItemCreationInformation creationInfo = new ListItemCreationInformation(); ListItem oListItem = targetList.AddItem(creationInfo); foreach (KeyValuePair <string, object> itemFieldValue in itemFieldValues) { //Set each field value oListItem[itemFieldValue.Key] = itemFieldValue.Value; } //Persist changes oListItem.Update(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(oListItem["Title"].ToString() + " : Inserted!!"); ctx.ExecuteQuery(); }
private static void ImportRow(ClientContext ctx, TermGroup termGroup, string listName, DataRow row, string[] columnNames, int rowIndex, ref List <LogItem> logs) { var web = ctx.Web; ctx.Load(web); ctx.ExecuteQuery(); ctx.Load(web.Lists); ctx.ExecuteQuery(); var list = web.Lists.FirstOrDefault(r => Regex.IsMatch(r.Title, listName, RegexOptions.IgnoreCase | RegexOptions.Compiled)); ctx.Load(list); var fields = list.Fields; ctx.Load(fields); ctx.ExecuteQuery(); var data = new List <DataFieldItem>(); foreach (var name in columnNames) { if (WorksheetToListMap.FirstOrDefault(x => x.ListName == listName && x.ListColumnName == name).Ignore) { continue; } var field = fields.FirstOrDefault(x => x.InternalName == name); var mappedProperty = WorksheetToListMap.FirstOrDefault(x => x.ListName == listName && x.ListColumnName == name); var value = row[mappedProperty.ColumnCode].ToString().Trim(); if (string.IsNullOrEmpty(value)) { continue; } switch (field.TypeAsString) { case "TaxonomyFieldTypeMulti": { // log if term isnt found var excelTerms = value.Split(new char[] { ',', ';' }); var f = field as TaxonomyField; var terms = new List <string>(); for (int i = 0; i < excelTerms.Length; i++) { if (string.IsNullOrEmpty(excelTerms[i])) { continue; } Term term = null; try { term = GetTermByLabel(termGroup, excelTerms[i], mappedProperty.TermSetName); } catch { if (!logs.Exists(x => x.Category == LogCategory.MissingTerm && x.LogValue.ToString() == excelTerms[i].ToString())) { logs.Add(new LogItem(LogCategory.MissingTerm, value, name, rowIndex)); } } /* * if (term == null) * { * if (!logs.Exists(x => x.Category == LogCategory.MissingTerm && x.LogValue.ToString() == value.ToString())) * logs.Add(new LogItem(LogCategory.MissingTerm, value, name, rowIndex)); * continue; * } */ if (term != null) { terms.Add($"-1;#{excelTerms[i]}|{term.Id}"); } } var termString = string.Join(";#", terms.ToArray()); if (!string.IsNullOrEmpty(termString)) { var o = new DataFieldItem { Name = name, SPField = field, FieldValue = termString }; data.Add(o); } } break; case "TaxonomyFieldType": { // log if term isnt found var f = field as TaxonomyField; //var term = GetTermByLabel(ctx, value, mappedProperty.TermGroup, mappedProperty.TermSetName); var term = GetTermByLabel(termGroup, value, mappedProperty.TermSetName); if (term == null) { if (!logs.Exists(x => x.Category == LogCategory.MissingTerm && x.LogValue.ToString() == value.ToString())) { logs.Add(new LogItem(LogCategory.MissingTerm, value, name, rowIndex)); } break; } TaxonomyFieldValue taxValue = new TaxonomyFieldValue(); taxValue.TermGuid = term.Id.ToString(); taxValue.Label = term.Name; taxValue.WssId = -1; data.Add(new DataFieldItem { Name = name, SPField = field, FieldValue = term }); } break; case "User": var user = ctx.Web.SiteUsers.GetByEmail(value); ctx.Load(user); try { ctx.ExecuteQuery(); } catch { if (!logs.Exists(x => x.Category == LogCategory.UserNotFound && x.LogValue.ToString() == value.ToString())) { logs.Add(new LogItem(LogCategory.UserNotFound, value, name, rowIndex)); } continue; } var userValue = new FieldUserValue(); userValue.LookupId = user.Id; data.Add(new DataFieldItem { Name = name, SPField = field, FieldValue = userValue }); break; case "DateTime": DateTime d; if (DateTime.TryParse(value, out d)) { data.Add(new DataFieldItem { Name = name, SPField = field, FieldValue = d.ToShortDateString() }); } else { continue; } break; case "Boolean": data.Add(new DataFieldItem { Name = name, SPField = field, FieldValue = (value == "Yes" ? true : false) }); break; default: data.Add(new DataFieldItem { Name = name, SPField = field, FieldValue = value }); break; } } var itemCreateInfo = new ListItemCreationInformation(); var newItem = list.AddItem(itemCreateInfo); foreach (var d in data) { var field = d.SPField; switch (field.TypeAsString) { case "TaxonomyFieldTypeMulti": { var f = field as TaxonomyField; f.SetFieldValueByValueCollection(newItem, new TaxonomyFieldValueCollection(ctx, d.FieldValue.ToString(), f)); } break; case "TaxonomyFieldType": { var f = field as TaxonomyField; f.SetFieldValueByValue(newItem, d.FieldValue as TaxonomyFieldValue); } break; case "User": newItem[field.InternalName] = d.FieldValue; break; case "DateTime": newItem[field.InternalName] = d.FieldValue; break; case "Boolean": newItem[field.InternalName] = d.FieldValue; break; default: newItem[field.InternalName] = d.FieldValue; break; } } newItem["CEN_ClinicalReviewPhase"] = "Complete"; newItem["CEN_ProgressStatus"] = "Final"; newItem.Update(); try { ctx.ExecuteQuery(); } catch (Exception ex) { //if (Debugger.IsAttached) Debugger.Break(); logs.Add(new LogItem(LogCategory.Exceptions, newItem.Id, newItem["Title"].ToString(), rowIndex)); } }
public ActionResult tosharepoint() { //FUNCIONA //using (ClientContext clientContext = new ClientContext("https://limenainc.sharepoint.com/sites/comercia")) //{ // var passWord = new SecureString(); // foreach (char c in "Fr@Nc!sC0@2018".ToCharArray()) passWord.AppendChar(c); // clientContext.Credentials = new SharePointOnlineCredentials("*****@*****.**", passWord); // Web web = clientContext.Web; // clientContext.Load(web); // try // { // clientContext.ExecuteQuery(); // ViewBag.hola = web.Title; // } // catch (Exception e) // { // Console.WriteLine(e.Message); // ViewBag.hola = e.Message; // } //} //Nos conectamos al sitio de sharepoint using (ClientContext clientContext = new ClientContext("https://limenainc.sharepoint.com/sites/comercia")) { var passWord = new SecureString(); foreach (char c in "Fr@Nc!sC0@2018".ToCharArray()) { passWord.AppendChar(c); } clientContext.Credentials = new SharePointOnlineCredentials("*****@*****.**", passWord); //Web web = clientContext.Web; //ListCollection collList = web.Lists; //clientContext.Load(collList); try { // Seleccionamos la lista especifica. List customerdataList = clientContext.Web.Lists.GetByTitle("Customer Data"); ////PARA CONSULTAS [SELECT] //// Luego hacemos una consulta limitando los resultados a 100 //CamlQuery query = CamlQuery.CreateAllItemsQuery(100); //ListItemCollection items = customerdataList.GetItems(query); //// Retornamos la lista de items en un ListItemCollection hacia un List.GetItems(Query). //clientContext.Load(items); //clientContext.ExecuteQuery(); //foreach (ListItem listItem in items) //{ // // We have all the list item data. For example, Title. // ViewBag.hola = ViewBag.hola + ", " + listItem["Title"]; //} // We are just creating a regular list item, so we don't need to // set any properties. If we wanted to create a new folder, for // example, we would have to set properties such as // UnderlyingObjectType to FileSystemObjectType.Folder. ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem newItem = customerdataList.AddItem(itemCreateInfo); newItem["Title"] = "TIENDA DE PRUEBA FRAN"; newItem.Update(); clientContext.ExecuteQuery(); ViewBag.hola = "Tienda ingresada correctamente"; //clientContext.ExecuteQuery(); //foreach (List oList in collList) //{ // if (oList.Title == "Customer Data") { // ViewBag.hola = oList.Id + ", " + oList.Title + "" + oList.Created.ToString(); // } // //Console.WriteLine("Title: {0} Created: {1}", oList.Title, oList.Created.ToString()); //} //ViewBag.hola = web.Title; } catch (Exception e) { Console.WriteLine(e.Message); ViewBag.hola = e.Message; } } return(View()); }
public static void SyncList(this List srcList, ClientContext ctxTarget, string cListName, string cSyncFields, DateTime dtLastRun) { try { List tgtList = ctxTarget.Web.Lists.GetByTitle(cListName); ctxTarget.Load(tgtList, l => l.ItemCount); ctxTarget.ExecuteQuery(); srcList.Context.Load(srcList, s => s.ItemCount, s => s.HasUniqueRoleAssignments); srcList.Context.ExecuteQuery(); ListItemCollection workItems = null; if (srcList.ItemCount != tgtList.ItemCount) { workItems = srcList.GetAllItems(); } else { workItems = srcList.GetModifiedItems(dtLastRun); } foreach (ListItem item in workItems) { try { srcList.Context.Load(item); srcList.Context.ExecuteQueryRetry(); ListItem tgtItem = tgtList.GetListItemByTitle(item["Title"].ToString()); if (tgtItem == null) { ListItemCreationInformation lici = new ListItemCreationInformation(); tgtItem = tgtList.AddItem(lici); tgtItem["Title"] = item["Title"]; tgtItem.Update(); } string[] aFields = cSyncFields.Split(';'); foreach (string cField in aFields) { try { if (cField.Contains("`")) { string[] cFieldInfo = cField.Split('`'); if (item[cFieldInfo[1]] != null) { string cText = item[cFieldInfo[1]].ToString(); if (cText.Contains("/Departments/Marketing/MarketingStore")) { if (cFieldInfo[0].ToLower().Contains("image")) { cText = cText.Replace("/Departments/Marketing/MarketingStore", ""); string cUrl = cText.Substring(cText.IndexOf("<img")); cUrl = cUrl.Substring(cUrl.IndexOf("src") + 5); Int32 iEnd = cUrl.IndexOf("\""); cUrl = cUrl.Substring(0, iEnd); cUrl = cUrl.Replace("/Catalog%20Images/", "https://sandbox.rammware.net/sites/Sebia/BrochureImages/"); tgtItem[cFieldInfo[0]] = cUrl; } else { cText = cText.Replace("/Departments/Marketing/MarketingStore", ""); string cUrl = cText.Substring(cText.IndexOf("href") + 6); Int32 iEnd = cUrl.IndexOf("\""); cUrl = cUrl.Substring(0, iEnd); tgtItem[cFieldInfo[0]] = cUrl; } } else { tgtItem[cFieldInfo[0]] = item[cFieldInfo[1]]; } } } else { tgtItem[cField.Trim()] = item[cField.Trim()]; } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } tgtItem.Update(); ctxTarget.ExecuteQuery(); } tgtItem.Update(); srcList.Context.Load(item, i => i.HasUniqueRoleAssignments, i => i.RoleAssignments); srcList.Context.ExecuteQuery(); if (item.HasUniqueRoleAssignments) { tgtItem.BreakRoleInheritance(false, true); tgtItem.Update(); ctxTarget.ExecuteQuery(); SyncPemrissions(ctxTarget, tgtItem, item); } } catch (Exception ex) { throw new Exception("An error occured in SyncList for (Inside): " + srcList.Title + " " + ex.Message); } } } catch (Exception ex) { throw new Exception("An error occured in SyncList for: " + srcList.Title + " " + ex.Message); } }
static void Main(string[] args) { const string _tenant = "<Your Tenant Name>"; //e.g. 'contoso' const string _username = "******"; SecureString _password = null; //The password for _username var user = "******"; //e.g. 'test_contoso_com' var socialSite = $"https://{_tenant}-my.sharepoint.com/personal/{user}"; var socialPartial = $"/personal/{user}"; var followSite = $"https://{_tenant}.sharepoint.com/sites/MySite"; Guid webId = new Guid("<Web Id for followSite root web>"); string webTitle = "<Title of followSite>"; Guid siteId = new Guid("<Site Id for followSite>"); using (ClientContext ctx = new ClientContext(socialSite)) { ctx.Credentials = new SharePointOnlineCredentials(_username, _password); try { //Hidden list that contains followed sites, documents, and items var list = ctx.Web.Lists.GetByTitle("Social"); ctx.Load(list); //Validate the 'Private' folder exists -- for a user who hasn't followed anything it will not be there. var folderPrivate = ctx.Web.GetFolderByServerRelativeUrl($"{socialPartial}/Social/Private"); ctx.Load(folderPrivate); try { ctx.ExecuteQuery(); } catch (Exception ex) { //Create private and Followed site var info = new ListItemCreationInformation(); info.UnderlyingObjectType = FileSystemObjectType.Folder; info.LeafName = "Private"; ListItem newFolder = list.AddItem(info); newFolder["Title"] = "Private"; newFolder["ContentTypeId"] = "0x01200029E1F7200C2F49D9A9C5FA014063F220006553A43C7080C04AA5273E7978D8913D"; newFolder.Update(); ctx.ExecuteQuery(); } //Validate the 'FollowedSites' folder exists -- for a user who hasn't followed anything it will not be there. var folderFollowed = ctx.Web.GetFolderByServerRelativeUrl($"{socialPartial}/Social/Private/FollowedSites"); ctx.Load(folderFollowed); try { ctx.ExecuteQuery(); } catch (Exception ex) { //Create private and Followed site var info = new ListItemCreationInformation(); info.UnderlyingObjectType = FileSystemObjectType.Folder; info.FolderUrl = $"{socialPartial}/Social/Private"; info.LeafName = "FollowedSites"; ListItem newFolder = list.AddItem(info); newFolder["Title"] = "FollowedSites"; newFolder["ContentTypeId"] = "0x0120001F6E5E1DE9E5447195CFF4F4FC5DDF5B00545FD50747B4D748AA2F22CD9D0BCB5E"; newFolder.Update(); ctx.ExecuteQuery(); } //Create the new follow item for the site, in the FollowedSites folder. var infoItem = new ListItemCreationInformation(); infoItem.FolderUrl = $"{socialPartial}/Social/Private/FollowedSites"; var newFollowedSite = list.AddItem(infoItem); newFollowedSite["Title"] = webTitle; newFollowedSite["ContentTypeId"] = "0x01FC00533CDB8F4EAE447D941948EFAE32BFD500D2687BB5643C16498964AD0C58FBA2F3"; newFollowedSite["Url"] = followSite; newFollowedSite["SiteId"] = siteId; newFollowedSite["WebId"] = webId; newFollowedSite.Update(); ctx.ExecuteQuery(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
public void addAllData(string listTitle) { Web web = mClientContext.Web; SP.List projList = mClientContext.Web.Lists.GetByTitle(listTitle); Dictionary <int, Milestone> milestoneDict = mProg.getMilestoneObjMap(); bool isOrdered = false; Console.WriteLine("the error code is: " + this.mEmailError.getErrorCode()); if (this.mIsNewList == false) { readData(listTitle); isOrdered = milestonesAreOrdered(milestoneDict, false); inputMilestoneAddCommands(milestoneDict); } else { isOrdered = milestonesAreOrdered(milestoneDict, true); inputMilestoneAddCommands(milestoneDict); } if ((this.mEmailError.getErrorCode() == 0 || this.mEmailError.getErrorCode() == -1) && isOrdered == true) { ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem oListItem = projList.AddItem(itemCreateInfo); Console.WriteLine("milestone size is: " + mProg.getMMilestoneSize()); oListItem["Estimated_x0020_Start_x0020_Time"] = mProg.getMEstStartTime(); oListItem["Estimated_x0020_Start_x0020_Date"] = mProg.getMEstStartDate(); oListItem["Estimated_x0020_End_x0020_Time"] = mProg.getMEstEndTime(); oListItem["Estimated_x0020_End_x0020_Date"] = mProg.getMEstEndDate(); oListItem["Actual_x0020_Start_x0020_Time"] = mProg.getMActualStartTime(); oListItem["Actual_x0020_Start_x0020_Date"] = mProg.getMActualStartDate(); oListItem["Time_x0020_Spent"] = mProg.getMTimeSpent(); oListItem["Resources"] = mProg.getMResources(); oListItem["Current_x0020_Status"] = mProg.getMCurrentStatus(); oListItem["Current_x0020_Status_x0020_Reaso"] = mProg.getMStatusReason(); List <int> addCommand = new List <int>(); List <int> updateCommand = new List <int>(); List <int> removeCommand = new List <int>(); //if(this.mIsNewList == true) //{ // foreach (var pair in mProg.getMilestoneObjMap().OrderBy(i => i.Key)) // { // Milestone milestone = pair.Value; // Console.WriteLine("the milestone command is: " + milestone.getCommand().Trim()); // if (milestone.getCommand().Trim() == "Add") // { // milestoneAddHandler(projList, oListItem, milestone); // } // } //} if (this.milestonesWithAddCommands.Count > 0) { for (int i = 0; i < this.milestonesWithAddCommands.Count; i++) { milestoneDict.TryGetValue(this.milestonesWithAddCommands[i], out Milestone milestone); if (milestone != null) { milestoneAddHandler(projList, oListItem, milestone); //if (milestone.getCommand().Trim() == "Update") //{ // updateCommand.Add(milestone.getNumber()); //} //if (milestone.getCommand().Trim() == "Remove") //{ // removeCommand.Add(milestone.getNumber()); //} } } } //foreach (var pair in mProg.getMilestoneObjMap().OrderBy(i => i.Key)) //{ // Milestone milestone = pair.Value; // Console.WriteLine("the milestone command is: " + milestone.getCommand().Trim()); // if (milestone.getCommand().Trim() == "Add") // { // addCommand.Add(milestone.getNumber()); // milestoneCommandHandler(projList, oListItem, milestone); // } // else if (milestone.getCommand().Trim() == "Update") // { // updateCommand.Add(milestone.getNumber()); // } // else if (milestone.getCommand().Trim() == "Remove") // { // removeCommand.Add(milestone.getNumber()); // } //} //updateMilestones(projList, updateCommand, removeCommand, addCommand); //Console.WriteLine("the milestone number is: " + mProg.getMMilestoneNum(pair.Key)); //} //}else if(milestone.getCommand().Trim() == "Update" || milestone.getCommand().Trim() == "Remove") //{s // milestoneCommandHandler(projList, oListItem, milestone); //} //oListItem.Update(); //mClientContext.ExecuteQuery(); //oListItem.Update(); //SP.CamlQuery myQuery = new SP.CamlQuery(); //myQuery.ViewXml = " < Where > < Eq > < FieldRef Name = 'Milestone_x0020_Number' /> <Value Type = 'Text'> 2 </Value> </ Eq > </ Where ></ View >"; //SP.ListItemCollection collectItems = projList.GetItems(myQuery); //mClientContext.Load(collectItems); Console.WriteLine("MUST UPDATE"); this.mInitialMilestoneRowCount = 0; oListItem.Update(); mClientContext.ExecuteQuery(); } else { this.mEmailError.setErrorCheck(true); if (isOrdered == false) { string mailboxAddress = mProg.getMailItem().mMailboxAddress; mEmailError.sendMilestoneTooLargeErrorEmail(mailboxAddress); this.mEmailError.setErrorCode(3); } } }
public void SetTaxonomyFieldMultiValueTest() { var fieldName = "TaxKeyword"; using (var clientContext = TestCommon.CreateClientContext()) { // Retrieve list var list = clientContext.Web.Lists.GetById(_listId); clientContext.Load(list); clientContext.ExecuteQueryRetry(); // Retrieve Termset TaxonomySession session = TaxonomySession.GetTaxonomySession(clientContext); var termSet = session.GetDefaultSiteCollectionTermStore().GetTermSet(_termSetId); clientContext.Load(termSet); clientContext.ExecuteQueryRetry(); //Add Enterprise keywords field var keyworkdField = clientContext.Web.Fields.GetByInternalNameOrTitle(fieldName); clientContext.Load(keyworkdField, f => f.Id); list.Fields.Add(keyworkdField); //Create second term var taxSession = TaxonomySession.GetTaxonomySession(clientContext); var termStore = taxSession.GetDefaultSiteCollectionTermStore(); Guid term2Id = Guid.NewGuid(); string term2Name = "Test_Term_" + DateTime.Now.ToFileTime(); var term2 = termStore.GetTerm(term2Id); clientContext.Load(term2, t => t.Id); clientContext.ExecuteQueryRetry(); // Create if non existant if (term2.ServerObjectIsNull.Value) { term2 = termSet.CreateTerm(term2Name, 1033, term2Id); clientContext.ExecuteQueryRetry(); } else { var label2 = term2.GetDefaultLabel(1033); clientContext.ExecuteQueryRetry(); term2Name = label2.Value; } // Create Item ListItemCreationInformation itemCi = new ListItemCreationInformation(); var item = list.AddItem(itemCi); item.Update(); clientContext.Load(item); clientContext.ExecuteQueryRetry(); item.SetTaxonomyFieldValues(keyworkdField.Id, new List <KeyValuePair <Guid, string> > { new KeyValuePair <Guid, string>(_termId, _termName), new KeyValuePair <Guid, string>(term2Id, term2Name) }); clientContext.Load(item, i => i[fieldName]); clientContext.ExecuteQueryRetry(); var value = item[fieldName] as TaxonomyFieldValueCollection; Assert.IsNotNull(value); Assert.AreEqual(2, value.Count, "Taxonomy value count mismatch"); Assert.IsTrue(value[0].WssId > 0, "Term WSS ID not set correctly"); Assert.IsTrue(value[1].WssId > 0, "Term2 WSS ID not set correctly"); Assert.AreEqual(_termName, value[0].Label, "Term label not set correctly"); Assert.AreEqual(term2Name, value[1].Label, "Term2 label not set correctly"); Assert.AreEqual(_termId.ToString(), value[0].TermGuid, "Term GUID not set correctly"); Assert.AreEqual(term2Id.ToString(), value[1].TermGuid, "Term2 GUID not set correctly"); } }
public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation) { using (var scope = new PnPMonitoredScope(this.Name)) { if (!template.Lists.Any()) { return(parser); } web.EnsureProperties(w => w.ServerRelativeUrl); web.Context.Load(web.Lists, lc => lc.IncludeWithDefaultProperties(l => l.RootFolder.ServerRelativeUrl)); web.Context.ExecuteQueryRetry(); #region DataRows foreach (var listInstance in template.Lists) { if (listInstance.DataRows != null && listInstance.DataRows.Any()) { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Processing_data_rows_for__0_, listInstance.Title); // Retrieve the target list var list = web.Lists.GetByTitle(parser.ParseString(listInstance.Title)); web.Context.Load(list); // Retrieve the fields' types from the list Microsoft.SharePoint.Client.FieldCollection fields = list.Fields; web.Context.Load(fields, fs => fs.Include(f => f.InternalName, f => f.FieldTypeKind, f => f.TypeAsString, f => f.ReadOnlyField, f => f.Title)); web.Context.ExecuteQueryRetry(); var keyColumnType = "Text"; var parsedKeyColumn = parser.ParseString(listInstance.DataRows.KeyColumn); if (!string.IsNullOrEmpty(parsedKeyColumn)) { var keyColumn = fields.FirstOrDefault(f => f.InternalName.Equals(parsedKeyColumn, StringComparison.InvariantCultureIgnoreCase)); if (keyColumn != null) { switch (keyColumn.FieldTypeKind) { case FieldType.User: case FieldType.Lookup: keyColumnType = "Lookup"; break; case FieldType.URL: keyColumnType = "Url"; break; case FieldType.DateTime: keyColumnType = "DateTime"; break; case FieldType.Number: case FieldType.Counter: keyColumnType = "Number"; break; } } } foreach (var dataRow in listInstance.DataRows) { try { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_list_item__0_, listInstance.DataRows.IndexOf(dataRow) + 1); bool processItem = true; ListItem listitem = null; if (!string.IsNullOrEmpty(listInstance.DataRows.KeyColumn)) { // Get value from key column var dataRowValues = dataRow.Values.Where(v => v.Key == listInstance.DataRows.KeyColumn).ToList(); // if it is empty, skip the check if (dataRowValues.Any()) { var query = $@"<View><Query><Where><Eq><FieldRef Name=""{parsedKeyColumn}""/><Value Type=""{keyColumnType}"">{parser.ParseString(dataRowValues.FirstOrDefault().Value)}</Value></Eq></Where></Query><RowLimit>1</RowLimit></View>"; var camlQuery = new CamlQuery() { ViewXml = query }; var existingItems = list.GetItems(camlQuery); list.Context.Load(existingItems); list.Context.ExecuteQueryRetry(); if (existingItems.Count > 0) { if (listInstance.DataRows.UpdateBehavior == UpdateBehavior.Skip) { processItem = false; } else { listitem = existingItems[0]; processItem = true; } } } } if (processItem) { if (listitem == null) { var listitemCI = new ListItemCreationInformation(); listitem = list.AddItem(listitemCI); } ListItemUtilities.UpdateListItem(listitem, parser, dataRow.Values, ListItemUtilities.ListItemUpdateType.UpdateOverwriteVersion); if (dataRow.Security != null && (dataRow.Security.ClearSubscopes || dataRow.Security.CopyRoleAssignments || dataRow.Security.RoleAssignments.Count > 0)) { listitem.SetSecurity(parser, dataRow.Security); } } } catch (ServerException ex) { if (ex.ServerErrorTypeName.Equals("Microsoft.SharePoint.SPDuplicateValuesFoundException", StringComparison.InvariantCultureIgnoreCase) && applyingInformation.IgnoreDuplicateDataRowErrors) { scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_listitem_duplicate); continue; } } catch (Exception ex) { scope.LogError(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_listitem_failed___0_____1_, ex.Message, ex.StackTrace); throw; } } } } #endregion DataRows } return(parser); }
public UpdatePipelineList(string clientContextWeb, string backupListTarget, string excelIndexTarget, string sharepointIndexTarget) { System.IO.Directory.CreateDirectory(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"\Export\"); string folder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"\Export\"; string filter = "*.xlsx"; string[] files = Directory.GetFiles(folder, filter); string pipelinefile = "Pipeline.xlsx"; string dhcfile = "DHCUpdate.xlsx"; Regex regexPipeline = FindFilesPatternToRegex.Convert("*pipeline*.xlsx"); Regex regexDHC = FindFilesPatternToRegex.Convert("*dhc*.xlsx"); foreach (string file in files) { //Console.WriteLine("Inside File check: {0}", file); if (regexPipeline.IsMatch(file.ToLower())) { pipelinefile = file; } else if (regexDHC.IsMatch(file.ToLower())) { dhcfile = file; } } Console.WriteLine("------Update Pipeline ----------------"); //Console.WriteLine("Folder : {0}", folder); Console.WriteLine("Pipelinefile: {0}", pipelinefile); Console.WriteLine("DHCfile : {0}", dhcfile); Console.WriteLine("--------------------------------------"); log.Debug(string.Format("------ Update Pipeline Files ------")); log.Debug(string.Format("Pipelinefile: {0}", pipelinefile)); log.Debug(string.Format("DHCfile : {0}", dhcfile)); log.Debug(string.Format("---------------------------------------")); FileStream stream, streamDHC; try { //update for reading files stream = System.IO.File.Open(pipelinefile, FileMode.Open, FileAccess.Read); //update for reading files streamDHC = System.IO.File.Open(dhcfile, FileMode.Open, FileAccess.Read); } catch (Exception ex) { Console.WriteLine("Please close the excel file and press enter"); Console.ReadLine(); //update for reading files stream = System.IO.File.Open(pipelinefile, FileMode.Open, FileAccess.Read); //update for reading files streamDHC = System.IO.File.Open(dhcfile, FileMode.Open, FileAccess.Read); } IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(stream); reader.IsFirstRowAsColumnNames = true; DataSet ds = reader.AsDataSet(); IExcelDataReader readerDHC = ExcelReaderFactory.CreateOpenXmlReader(streamDHC); readerDHC.IsFirstRowAsColumnNames = true; DataSet dsDHC = readerDHC.AsDataSet(); DataRowSharepointMappingCollection mapping = MyRetriever.GetTheCollection(); DataRowSharepointMappingCollection mappingDHC = MyRetriever.GetTheCollection("DataRowDHCMappingsSection"); DataTable dt = ds.Tables[0]; DataColumn dcParent = dt.Columns["Opportunity Name"]; using (var clientContext = new ClientContext(clientContextWeb)) { Web web = clientContext.Web; //------------------------------------ // GetItems for PipeLine list //------------------------------------ List oldList = web.Lists.GetByTitle(backupListTarget); CamlQuery query = CamlQuery.CreateAllItemsQuery(2000); ListItemCollection oldItems = oldList.GetItems(query); clientContext.Load(oldItems); var listFields = oldList.Fields; clientContext.Load(listFields, fields => fields.Include(field => field.Title, field => field.InternalName, field => field.ReadOnlyField, field => field.StaticName)); clientContext.ExecuteQuery(); //-------------------------------------------------- // GetItems from LOB (LineOfBusiness list here..... //-------------------------------------------------- List LOBList = web.Lists.GetByTitle("LOB-MPP-Map"); CamlQuery LOBquery = CamlQuery.CreateAllItemsQuery(1000); ListItemCollection LOBitems = LOBList.GetItems(LOBquery); clientContext.Load(LOBitems); var LOBFields = LOBList.Fields; clientContext.Load(LOBFields, fields => fields.Include(field => field.Title, field => field.InternalName)); clientContext.ExecuteQuery(); //UpdateLOBFields( clientContext, oldList, oldItems, LOBitems); // Console.WriteLine("Finished return from LOB update"); //oldList.Update(); //Console.WriteLine("Finished return from oldList update"); //clientContext.ExecuteQuery(); //------------------------- //Stop here for now. //------------------------- // Console.ReadLine(); // System.Environment.Exit(0); //log.Debug(string.Format("Opening List: {0}", backupListTarget)); //log.Debug("Internal fields"); //log.Debug("-------------------------"); // foreach (Field f in listFields) // { // log.Debug(string.Format("Title: {0}, Internal Name: {1}", f.Title, f.InternalName)); // log.Debug(string.Format("Static Name: {0}", f.StaticName)); // log.Debug("-----------------"); // //log.Debug(f.InternalName); // } foreach (DataRow dr in ds.Tables[0].Rows) { //log.Debug("------- Inside For -----------------"); //log.Debug(dr["HPE Opportunity Id"].ToString()); var my_itemlist = oldItems.ToList(); // ---------------BEGIN MY COMMENT SECTION -------------------------- //Console.WriteLine("Sales Opportunity Id: {0}", dr["Sales Opportunity Id"].ToString()); //Console.WriteLine(" My_itemlist count: {0}", my_itemlist.Count); ////---------MAT ----DEBUG TEST-------------------- ////-- List out item list for verification --- //// --------------------------------------------- //if (my_itemlist.Count() == 0 ) //{ // Console.WriteLine("My List count in 0"); //} //else //{ // log.Debug("-- Item List ------"); // foreach (ListItem targetListItem in my_itemlist) // { // log.Debug(string.Format("Title: {0}, HPEOppID: {1}", targetListItem["Title"], targetListItem["HPOppID"].ToString())); // Console.WriteLine(targetListItem["Title"]); // } //} //Console.WriteLine(" -------- MAT list completed here ---------------"); // ---------------END MY COMMENT SECTION -------------------------- var page = from ListItem itemlist in oldItems.ToList() // var page = from ListItem itemlist in my_itemlist //where itemlist["HPOppID"].ToString() == dr["Sales Opportunity Id"].ToString() where itemlist["HPOppID"].ToString() == dr[excelIndexTarget.ToString()].ToString() select itemlist; //Console.WriteLine("Page Count is: {0}", page.Count()); //this is an update if (page.Count() == 1) { Console.ForegroundColor = ConsoleColor.Blue; //Console.WriteLine(string.Format("UPDATE RECORD: Name:{0} ID:{1}", dr["Opportunity Name"].ToString(), dr["Sales Opportunity Id"].ToString())); //log.Debug(string.Format("UPDATE: Name:{0} ID:{1}", dr["Opportunity Name"].ToString(), dr["Sales Opportunity Id"].ToString())); Console.WriteLine(string.Format("UPDATE RECORD: Name:{0} ID:{1}", dr["Opportunity Name"].ToString(), dr[excelIndexTarget.ToString()].ToString())); log.Debug(string.Format("UPDATE: Name:{0} ID:{1}", dr["Opportunity Name"].ToString(), dr[excelIndexTarget.ToString()].ToString())); ListItem item = page.FirstOrDefault(); //iterate the mapping between sharepoint list items and excel spreadsheet items foreach (DataRowSharepointMapping map in mapping) { UpdateField(item, map.SharePointColumn, map.DataRowColumn, dr, sharepointIndexTarget); } CompareSalesStage(item, dsDHC, mappingDHC, excelIndexTarget, sharepointIndexTarget); //Console.WriteLine("- Before Item update."); // just update the item item.Update(); //Console.WriteLine("- Before List update."); //update the list oldList.Update(); countupdate++; } // This is a new record //else if (page.Count() == 0 && !string.IsNullOrEmpty(dr["Sales Opportunity Id"].ToString())) ----MAT else if (page.Count() == 0 && !string.IsNullOrEmpty(dr[excelIndexTarget.ToString()].ToString())) { Console.ForegroundColor = ConsoleColor.Yellow; //Console.WriteLine(string.Format("------- Inside ELSE NEW RECORD-----------------")); //Console.WriteLine(string.Format("NEW RECORD: Name:{0} ID:{1}", dr["Opportunity Name"].ToString(), dr["Sales Opportunity Id"].ToString())); Console.WriteLine(string.Format("NEW RECORD: Name:{0} ID:{1}", dr["Opportunity Name"].ToString(), dr[excelIndexTarget.ToString()].ToString())); //log.Debug("------- Inside ELSE NEW RECORD-----------------"); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem oListItem = oldList.AddItem(itemCreateInfo); // -- iterate the mapping between sharepoint list items and excel spreadsheet items foreach (DataRowSharepointMapping map in mapping) { UpdateField(oListItem, map.SharePointColumn, map.DataRowColumn, dr, sharepointIndexTarget); } CompareSalesStage(oListItem, dsDHC, mappingDHC, excelIndexTarget, sharepointIndexTarget); // -- just update the item //Console.WriteLine("- Before Item update."); oListItem.Update(); // -- update the list //Console.WriteLine("- Before List update."); oldList.Update(); countnew++; } else { //Console.ForegroundColor = ConsoleColor.Red; //Console.WriteLine("ERROR"); } // Not sure about this one. (MAT) clientContext.ExecuteQuery(); } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(string.Format("We updated: {0} records and we added {1} records", countupdate.ToString(), countnew.ToString())); log.Debug(string.Format("------------------------------------------------------------")); log.Debug(string.Format("We updated: {0} records and we added {1} records", countupdate.ToString(), countnew.ToString())); Console.WriteLine("Completed first set of updates. \n"); Console.WriteLine("Starting LOB checks........ \n"); log.Debug(string.Format("------------------------------------------------------------")); log.Debug(string.Format("Starting LOB Checks........")); UpdateLOBFields(clientContext, oldList, oldItems, LOBitems, sharepointIndexTarget); //Console.WriteLine("Finished return from LOB update..."); //oldList.Update(); clientContext.ExecuteQuery(); Console.WriteLine("Finished Line Of Business updates... \n"); } }
private void import_excel_to_sharepoint_list(Object stateInfo) { try { string[] ui_selections = stateInfo.ToString().Split(';'); _clientContext.Load(_site); _list = _site.Lists.GetByTitle(ui_selections[0]); _clientContext.ExecuteQuery(); Folder root_folder = _list.RootFolder; _clientContext.Load(root_folder); _clientContext.ExecuteQuery(); string root_folder_url = root_folder.ServerRelativeUrl; string commandStr = "select * from [" + ui_selections[1] + "]"; OleDbDataAdapter command = new OleDbDataAdapter(commandStr, get_conn_string()); DataTable data = new DataTable(); command.Fill(data); this.Invoke( _update_counter, new object[] { _count + " / " + data.Rows.Count } ); // prepar for the loop DataTable table = new DataTable(); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); if (_folder_tree == null) { _folder_tree = new Tree(); _folder_tree.URL = String.Format("{0}", root_folder_url); _folder_tree.Name = "ROOT"; _folder_tree.Children = new List <Tree>(); } int record_number = 0; _count = int.Parse(numericUpDown1.Value.ToString()); foreach (DataRow row in data.Rows) { if (!_is_running) { return; } record_number++; if (record_number <= _count) { continue; } // check if need to created Folders for imported items string new_folder_relative_url = ""; Tree new_folder = null; Tree parent_folder = _folder_tree; _message = _folder_tree.URL; foreach (DataGridViewRow mapping_row in dgMapping.Rows) { // if the Folder Level column is not null, then, put item into this folder // the folder level will depends on the sequence of the folder columns apprea in the Mapping GridView. TODO: maybe improved in the future. if (mapping_row.Cells[3].Value != null) { string folder_name = format_folder_name(row[mapping_row.Cells[0].Value.ToString()].ToString()); _message += "\n folder:" + folder_name; new_folder = create_folder_if_not_exists(parent_folder, folder_name); new_folder_relative_url += folder_name + "/"; parent_folder = new_folder; } } if (new_folder != null) { itemCreateInfo.FolderUrl = new_folder.URL; _message += "\nnew_folder: " + new_folder.URL; } Microsoft.SharePoint.Client.ListItem listItem = _list.AddItem(itemCreateInfo); // Item Value foreach (DataGridViewRow mapping_row in dgMapping.Rows) { if (mapping_row.Cells[1].Value != null) { if (mapping_row.Cells[2].Value != null) { if (string.IsNullOrEmpty(table.TableName)) { table.TableName = mapping_row.Cells[2].Value.ToString(); } else { if (table.TableName != mapping_row.Cells[2].Value.ToString()) { listItem[table.TableName] = this.ToHtmlTable(table); table.TableName = null; table.Clear(); table.Columns.Clear(); table.TableName = mapping_row.Cells[2].Value.ToString(); } } DataColumn tcol = new DataColumn(mapping_row.Cells[0].Value.ToString()); table.Columns.Add(tcol); if (row[mapping_row.Cells[0].Value.ToString()] != null) // The column must have value, or, it will be ignored. { if (!string.IsNullOrEmpty(row[mapping_row.Cells[0].Value.ToString()].ToString())) { string[] col_values = row[mapping_row.Cells[0].Value.ToString()].ToString().Split(_separator); if (table.Rows.Count == 0) { for (int i = 0; i < col_values.Length; i++) { table.Rows.Add(new object[] { col_values[i] }); } } else { int i = 0; for (i = 0; i < Math.Min(col_values.Length, table.Rows.Count); i++) { table.Rows[i][tcol] = col_values[i]; } if (col_values.Length > table.Rows.Count) { for (int j = i; j < col_values.Length; j++) { DataRow new_row = table.Rows.Add(); new_row[tcol] = col_values[j]; } } } } } } else { string value = row[mapping_row.Cells[0].Value.ToString()].ToString(); if (!string.IsNullOrEmpty(value)) { // Check the Date-Time format, for some date column will have time in it, we must remove the time first before we can put it into SharePoint. Regex reg = new Regex(@" [0-9]+:[0-9]+[AP]M$", RegexOptions.Multiline | RegexOptions.IgnoreCase); if (reg.IsMatch(value)) { value = reg.Replace(value, ""); } listItem[mapping_row.Cells[1].Value.ToString()] = value; } } } } if (table.Columns.Count > 0) { listItem[table.TableName] = this.ToHtmlTable(table); table.TableName = null; table.Clear(); table.Columns.Clear(); } listItem.Update(); _count++; this.Invoke( _update_counter, new object[] { _count + " / " + data.Rows.Count } ); if (_count % 20 == 0) { _clientContext.ExecuteQuery(); // TODO: Is there any other way to improve this? } } _clientContext.ExecuteQuery(); // for the last item } catch (Exception ex) { MessageBox.Show(_message + "\n" + ex.ToString() + "\n" + ex.Source + "\n" + ex.StackTrace); } }
public void CreateNewSiteRequest(SiteRequestInformation siteRequest) { UsingContext(ctx => { var web = ctx.Web; if (!web.ListExists(SiteRequestList.TITLE)) { this.HandleSiteRequestList(ctx); } List list = web.Lists.GetByTitle(SiteRequestList.TITLE); ListItemCreationInformation _listItemCreation = new ListItemCreationInformation(); ListItem _record = list.AddItem(_listItemCreation); _record[SiteRequestFields.TITLE] = siteRequest.Title; _record[SiteRequestFields.DESCRIPTION_NAME] = siteRequest.Description; _record[SiteRequestFields.TEMPLATE_NAME] = siteRequest.Template; _record[SiteRequestFields.URL_NAME] = siteRequest.Url; _record[SiteRequestFields.LCID_NAME] = siteRequest.Lcid; _record[SiteRequestFields.TIMEZONE_NAME] = siteRequest.TimeZoneId; _record[SiteRequestFields.POLICY_NAME] = siteRequest.SitePolicy; _record[SiteRequestFields.EXTERNALSHARING_NAME] = siteRequest.EnableExternalSharing; _record[SiteRequestFields.ONPREM_REQUEST_NAME] = siteRequest.SharePointOnPremises; _record[SiteRequestFields.BC_NAME] = siteRequest.BusinessCase; _record[SiteRequestFields.PROPS_NAME] = siteRequest.PropertiesJSON; //If Settings are set to autoapprove then automatically approve the requests if (_manager.GetAppSettings().AutoApprove) { _record[SiteRequestFields.PROVISIONING_STATUS_NAME] = SiteRequestStatus.Approved.ToString(); _record[SiteRequestFields.APPROVEDDATE_NAME] = DateTime.Now; } else { _record[SiteRequestFields.PROVISIONING_STATUS_NAME] = SiteRequestStatus.New.ToString(); } FieldUserValue _siteOwner = FieldUserValue.FromUser(siteRequest.SiteOwner.Name); _record[SiteRequestFields.OWNER_NAME] = _siteOwner; //Additional Admins if (siteRequest.AdditionalAdministrators != null) { if (siteRequest.AdditionalAdministrators.Count > 0) { FieldUserValue[] _additionalAdmins = new FieldUserValue[siteRequest.AdditionalAdministrators.Count]; int _index = 0; foreach (SiteUser _user in siteRequest.AdditionalAdministrators) { FieldUserValue _adminFieldUser = FieldUserValue.FromUser(_user.Name); _additionalAdmins[_index] = _adminFieldUser; _index++; } _record[SiteRequestFields.ADD_ADMINS_NAME] = _additionalAdmins; } } _record.Update(); ctx.ExecuteQuery(); Log.Info("Provisioning.Common.Data.Impl.UpdateRequestStatus", PCResources.SiteRequestNew_Successfull, siteRequest.Url); } ); }
public static void ProvisionLists(ClientContext ctx) { //Create country list Console.WriteLine("Provisioning lists:"); List countryList = null; if (!ctx.Web.ListExists("EmpCountry")) { Console.WriteLine("Country list..."); countryList = ctx.Web.CreateList(ListTemplateType.GenericList, "EmpCountry", false, false, "Lists/EmpCountry", false); //Provision country list items ListItemCreationInformation newCountryCreationInfomation; newCountryCreationInfomation = new ListItemCreationInformation(); ListItem newCountry = countryList.AddItem(newCountryCreationInfomation); newCountry["Title"] = "Belgium"; newCountry.Update(); newCountry = countryList.AddItem(newCountryCreationInfomation); newCountry["Title"] = "United States of America"; newCountry.Update(); newCountry = countryList.AddItem(newCountryCreationInfomation); newCountry["Title"] = "India"; newCountry.Update(); ctx.Load(countryList); ctx.ExecuteQueryRetry(); } else { countryList = ctx.Web.GetListByUrl("Lists/EmpCountry"); Console.WriteLine("Country list was already available"); } List stateList = null; if (!ctx.Web.ListExists("EmpState")) { Console.WriteLine("State list..."); stateList = ctx.Web.CreateList(ListTemplateType.GenericList, "EmpState", false, false, "Lists/EmpState", false); Field countryLookup = stateList.CreateField(@"<Field Type=""Lookup"" DisplayName=""Country"" ID=""{BDEF775C-AB4B-4E86-9FB8-0A2DE40FE832}"" Name=""Country""></Field>", false); ctx.Load(stateList); ctx.Load(countryLookup); ctx.Load(stateList.DefaultView, p => p.ViewFields); ctx.ExecuteQueryRetry(); // Add field to default view stateList.DefaultView.ViewFields.Add("Country"); stateList.DefaultView.Update(); ctx.ExecuteQueryRetry(); // configure country lookup field FieldLookup countryField = ctx.CastTo <FieldLookup>(countryLookup); countryField.LookupList = countryList.Id.ToString(); countryField.LookupField = "Title"; countryField.Indexed = true; countryField.IsRelationship = true; countryField.RelationshipDeleteBehavior = RelationshipDeleteBehaviorType.Restrict; countryField.Update(); ctx.ExecuteQueryRetry(); //Provision state list items ListItemCreationInformation newStateCreationInfomation; newStateCreationInfomation = new ListItemCreationInformation(); ListItem newState = stateList.AddItem(newStateCreationInfomation); newState["Title"] = "Washington"; newState["Country"] = "2;#United States of America"; newState.Update(); newState = stateList.AddItem(newStateCreationInfomation); newState["Title"] = "Limburg"; newState["Country"] = "1;#Belgium"; newState.Update(); newState = stateList.AddItem(newStateCreationInfomation); newState["Title"] = "Tennessee"; newState["Country"] = "2;#United States of America"; newState.Update(); newState = stateList.AddItem(newStateCreationInfomation); newState["Title"] = "Karnataka"; newState["Country"] = "3;#India"; newState.Update(); ctx.ExecuteQueryRetry(); } else { countryList = ctx.Web.GetListByUrl("Lists/EmpState"); Console.WriteLine("State list was already available"); } List cityList = null; if (!ctx.Web.ListExists("EmpCity")) { Console.WriteLine("City list..."); cityList = ctx.Web.CreateList(ListTemplateType.GenericList, "EmpCity", false, false, "Lists/EmpCity", false); Field stateLookup = cityList.CreateField(@"<Field Type=""Lookup"" DisplayName=""State"" ID=""{F55BED78-CAF9-4EDF-92B9-C46BDC032DD5}"" Name=""State""></Field>", false); ctx.Load(cityList); ctx.Load(stateLookup); ctx.Load(cityList.DefaultView, p => p.ViewFields); ctx.ExecuteQueryRetry(); // Add field to default view cityList.DefaultView.ViewFields.Add("State"); cityList.DefaultView.Update(); ctx.ExecuteQueryRetry(); // configure state lookup field FieldLookup stateField = ctx.CastTo <FieldLookup>(stateLookup); stateField.LookupList = stateList.Id.ToString(); stateField.LookupField = "Title"; stateField.Indexed = true; stateField.IsRelationship = true; stateField.RelationshipDeleteBehavior = RelationshipDeleteBehaviorType.Restrict; stateField.Update(); ctx.ExecuteQueryRetry(); //Provision city list items ListItemCreationInformation newCityCreationInfomation; newCityCreationInfomation = new ListItemCreationInformation(); ListItem newCity = cityList.AddItem(newCityCreationInfomation); newCity["Title"] = "Bree"; newCity["State"] = "2;#Limburg"; newCity.Update(); newCity = cityList.AddItem(newCityCreationInfomation); newCity["Title"] = "Redmond"; newCity["State"] = "1;#Washington"; newCity.Update(); newCity = cityList.AddItem(newCityCreationInfomation); newCity["Title"] = "Franklin"; newCity["State"] = "3;#Tennessee"; newCity.Update(); newCity = cityList.AddItem(newCityCreationInfomation); newCity["Title"] = "Bangalore"; newCity["State"] = "4;#Karnataka"; newCity.Update(); ctx.ExecuteQueryRetry(); } else { cityList = ctx.Web.GetListByUrl("Lists/EmpCity"); Console.WriteLine("City list was already available"); } List designationList = null; if (!ctx.Web.ListExists("EmpDesignation")) { Console.WriteLine("Designation list..."); designationList = ctx.Web.CreateList(ListTemplateType.GenericList, "EmpDesignation", false, false, "Lists/EmpDesignation", false); ctx.Load(designationList); ctx.ExecuteQueryRetry(); //Provision designation list items ListItemCreationInformation newDesignationCreationInfomation; newDesignationCreationInfomation = new ListItemCreationInformation(); ListItem newDesignation = designationList.AddItem(newDesignationCreationInfomation); newDesignation["Title"] = "Service Engineer"; newDesignation.Update(); newDesignation = designationList.AddItem(newDesignationCreationInfomation); newDesignation["Title"] = "Service Engineer II"; newDesignation.Update(); newDesignation = designationList.AddItem(newDesignationCreationInfomation); newDesignation["Title"] = "Senior Service Engineer"; newDesignation.Update(); newDesignation = designationList.AddItem(newDesignationCreationInfomation); newDesignation["Title"] = "Principal Service Engineer"; newDesignation.Update(); newDesignation = designationList.AddItem(newDesignationCreationInfomation); newDesignation["Title"] = "Program Manager"; newDesignation.Update(); newDesignation = designationList.AddItem(newDesignationCreationInfomation); newDesignation["Title"] = "Senior Program Manager"; newDesignation.Update(); ctx.ExecuteQueryRetry(); } else { designationList = ctx.Web.GetListByUrl("Lists/EmpDesignation"); Console.WriteLine("Designation list was already available"); } List empAttachmentsList = null; if (!ctx.Web.ListExists("EmpAttachments")) { Console.WriteLine("EmpAttachments list..."); empAttachmentsList = ctx.Web.CreateList(ListTemplateType.DocumentLibrary, "EmpAttachments", false, false, "Lists/EmpAttachments", false); ctx.Load(empAttachmentsList); ctx.ExecuteQueryRetry(); empAttachmentsList.CreateField(@"<Field Type=""Text"" DisplayName=""AttachmentID"" ID=""{E6FAC176-F466-4174-9785-7FB9611CBC00}"" Name=""AttachmentID""></Field>", false); empAttachmentsList.Update(); ctx.Load(empAttachmentsList.DefaultView, p => p.ViewFields); ctx.ExecuteQueryRetry(); // Add fields to view empAttachmentsList.DefaultView.ViewFields.Add("AttachmentID"); empAttachmentsList.DefaultView.Update(); ctx.ExecuteQueryRetry(); } else { empAttachmentsList = ctx.Web.GetListByUrl("Lists/EmpAttachments"); Console.WriteLine("EmpAttachments list was already available"); } List employeeList = null; if (!ctx.Web.ListExists("Employees")) { Console.WriteLine("Employee list..."); employeeList = ctx.Web.CreateList(ListTemplateType.GenericList, "Employees", false, false, "Lists/Employees", false); ctx.Load(employeeList); ctx.ExecuteQueryRetry(); employeeList.CreateField(@"<Field Type=""Text"" DisplayName=""Number"" ID=""{0FFF75B6-0E57-46BE-84D7-E5225A55E914}"" Name=""EmpNumber""></Field>", false); employeeList.CreateField(@"<Field Type=""Text"" DisplayName=""UserID"" ID=""{D3199531-C091-4359-8CDE-86FB3924F65E}"" Name=""UserID""></Field>", false); employeeList.CreateField(@"<Field Type=""Text"" DisplayName=""Manager"" ID=""{B7E2F4D9-AEA2-40DB-A354-94EEDAFEF35E}"" Name=""EmpManager""></Field>", false); employeeList.CreateField(@"<Field Type=""Text"" DisplayName=""Designation"" ID=""{AB230804-C137-4ED8-A6D6-722037BDDA3D}"" Name=""Designation""></Field>", false); employeeList.CreateField(@"<Field Type=""Text"" DisplayName=""Location"" ID=""{2EE32832-5EF0-41D0-8CD3-3DE7B9616C21}"" Name=""Location""></Field>", false); employeeList.CreateField(@"<Field Type=""Text"" DisplayName=""Skills"" ID=""{89C02660-822D-4F41-881D-1D533C56017E}"" Name=""Skills""></Field>", false); employeeList.CreateField(@"<Field Type=""Text"" DisplayName=""AttachmentID"" ID=""{53A31281-1C25-4D00-B785-40C71D37AE7B}"" Name=""AttachmentID""></Field>", false); employeeList.Update(); ctx.Load(employeeList.DefaultView, p => p.ViewFields); ctx.ExecuteQueryRetry(); // Add fields to view employeeList.DefaultView.ViewFields.Add("EmpNumber"); employeeList.DefaultView.ViewFields.Add("UserID"); employeeList.DefaultView.ViewFields.Add("EmpManager"); employeeList.DefaultView.ViewFields.Add("Designation"); employeeList.DefaultView.ViewFields.Add("Location"); employeeList.DefaultView.ViewFields.Add("Skills"); employeeList.DefaultView.ViewFields.Add("AttachmentID"); employeeList.DefaultView.Update(); ctx.ExecuteQueryRetry(); } else { employeeList = ctx.Web.GetListByUrl("Lists/Employees"); Console.WriteLine("Employee list was already available"); } }
protected override void ExecuteCmdlet() { List list = null; if (List != null) { list = List.GetList(SelectedWeb); } if (list != null) { ListItemCreationInformation liCI = new ListItemCreationInformation(); if (Folder != null) { // Create the folder if it doesn't exist var rootFolder = list.EnsureProperty(l => l.RootFolder); var targetFolder = SelectedWeb.EnsureFolder(rootFolder, Folder); liCI.FolderUrl = targetFolder.ServerRelativeUrl; } var item = list.AddItem(liCI); if (ContentType != null) { ContentType ct = null; if (ContentType.ContentType == null) { if (ContentType.Id != null) { ct = SelectedWeb.GetContentTypeById(ContentType.Id, true); } else if (ContentType.Name != null) { ct = SelectedWeb.GetContentTypeByName(ContentType.Name, true); } } else { ct = ContentType.ContentType; } if (ct != null) { ct.EnsureProperty(w => w.StringId); item["ContentTypeId"] = ct.StringId; item.Update(); ClientContext.ExecuteQueryRetry(); } } if (Values != null) { Hashtable values = Values ?? new Hashtable(); // Load all list fields and their types var fields = ClientContext.LoadQuery(list.Fields.Include(f => f.Id, f => f.InternalName, f => f.Title, f => f.TypeAsString)); ClientContext.ExecuteQueryRetry(); foreach (var key in values.Keys) { var field = fields.FirstOrDefault(f => f.InternalName == key as string || f.Title == key as string); if (field != null) { switch (field.TypeAsString) { case "User": case "UserMulti": { var userValues = new List <FieldUserValue>(); var value = values[key]; if (value.GetType().IsArray) { foreach (var arrayItem in value as object[]) { int userId; if (!int.TryParse(arrayItem as string, out userId)) { var user = SelectedWeb.EnsureUser(arrayItem as string); ClientContext.Load(user); ClientContext.ExecuteQueryRetry(); userValues.Add(new FieldUserValue() { LookupId = user.Id }); } else { userValues.Add(new FieldUserValue() { LookupId = userId }); } } item[key as string] = userValues.ToArray(); } else { int userId; if (!int.TryParse(value as string, out userId)) { var user = SelectedWeb.EnsureUser(value as string); ClientContext.Load(user); ClientContext.ExecuteQueryRetry(); item[key as string] = new FieldUserValue() { LookupId = user.Id }; } else { item[key as string] = new FieldUserValue() { LookupId = userId }; } } #if !ONPREMISES item.SystemUpdate(); #else item.Update(); #endif break; } case "TaxonomyFieldType": case "TaxonomyFieldTypeMulti": { var value = values[key]; if (value.GetType().IsArray) { var taxSession = ClientContext.Site.GetTaxonomySession(); var terms = new List <KeyValuePair <Guid, string> >(); foreach (var arrayItem in value as object[]) { TaxonomyItem taxonomyItem; Guid termGuid = Guid.Empty; if (!Guid.TryParse(arrayItem as string, out termGuid)) { // Assume it's a TermPath taxonomyItem = ClientContext.Site.GetTaxonomyItemByPath(arrayItem as string); } else { taxonomyItem = taxSession.GetTerm(termGuid); ClientContext.Load(taxonomyItem); ClientContext.ExecuteQueryRetry(); } terms.Add(new KeyValuePair <Guid, string>(taxonomyItem.Id, taxonomyItem.Name)); } TaxonomyField taxField = ClientContext.CastTo <TaxonomyField>(field); taxField.EnsureProperty(tf => tf.AllowMultipleValues); if (taxField.AllowMultipleValues) { var termValuesString = String.Empty; foreach (var term in terms) { termValuesString += "-1;#" + term.Value + "|" + term.Key.ToString("D") + ";#"; } termValuesString = termValuesString.Substring(0, termValuesString.Length - 2); var newTaxFieldValue = new TaxonomyFieldValueCollection(ClientContext, termValuesString, taxField); taxField.SetFieldValueByValueCollection(item, newTaxFieldValue); #if !ONPREMISES item.SystemUpdate(); #else item.Update(); #endif ClientContext.ExecuteQueryRetry(); } else { WriteWarning($@"You are trying to set multiple values in a single value field. Skipping values for field ""{field.InternalName}"""); } } else { Guid termGuid = Guid.Empty; if (!Guid.TryParse(value as string, out termGuid)) { // Assume it's a TermPath var taxonomyItem = ClientContext.Site.GetTaxonomyItemByPath(value as string); termGuid = taxonomyItem.Id; } item[key as string] = termGuid.ToString(); } #if !ONPREMISES item.SystemUpdate(); #else item.Update(); #endif break; } case "Lookup": case "LookupMulti": { int[] multiValue; if (values[key] is Array) { var arr = (object[])values[key]; multiValue = new int[arr.Length]; for (int i = 0; i < arr.Length; i++) { multiValue[i] = int.Parse(arr[i].ToString()); } } else { string valStr = values[key].ToString(); multiValue = valStr.Split(',', ';').Select(int.Parse).ToArray(); } var newVals = multiValue.Select(id => new FieldLookupValue { LookupId = id }).ToArray(); FieldLookup lookupField = ClientContext.CastTo <FieldLookup>(field); lookupField.EnsureProperty(lf => lf.AllowMultipleValues); if (!lookupField.AllowMultipleValues && newVals.Length > 1) { WriteWarning($@"You are trying to set multiple values in a single value field. Skipping values for field ""{field.InternalName}"""); } item[key as string] = newVals; #if !ONPREMISES item.SystemUpdate(); #else item.Update(); #endif break; } default: { item[key as string] = values[key]; #if !ONPREMISES item.SystemUpdate(); #else item.Update(); #endif break; } } } else { ThrowTerminatingError(new ErrorRecord(new Exception("Field not present in list"), "FIELDNOTINLIST", ErrorCategory.InvalidData, key)); } } } item.Update(); ClientContext.Load(item); ClientContext.ExecuteQueryRetry(); WriteObject(item); } }
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("*****@*****.**"); 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(); }
private void btnStartMigration_Click(object sender, EventArgs e) { //1. Loop through sites being migrated foreach (MigrationSite ms in sitesForMig) { bool migrated = false; if (migratedSitesDict.TryGetValue(ms.OldSiteUrl, out migrated)) { if (migrated == true) { //Jumpt to next iteration in foreach loop if migrated is true continue; } } //Connect to SPO Site try { using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(ms.OldSiteUrl, tbUsername.Text, tbPassword.Text)) { using (var DestClientContent = authManager.GetSharePointOnlineAuthenticatedContextTenant(ms.NewSiteUrl, tbUsername.Text, tbPassword.Text)) { //Destination client content Web destWeb = DestClientContent.Web; DestClientContent.Load(destWeb); DestClientContent.ExecuteQuery(); //1. load lists and libraries Web web = clientContext.Web; ListCollection collectionLists = web.Lists; clientContext.Load( collectionLists, lists => lists.Include( list => list.Title, list => list.Id, List => List.Hidden, List => List.IsCatalog, List => List.IsSiteAssetsLibrary, List => List.BaseTemplate )); clientContext.ExecuteQuery(); //2. Loop lists & libraries foreach (List oList in collectionLists) { if (oList.Hidden == false && oList.IsSiteAssetsLibrary == false && oList.IsCatalog == false) { try { //The find ListMapping can generate an exception and if it does then that list is not in scope for migration ListMapping lm = listMappings.Find(list => list.ListName == oList.Title); Debug.WriteLine("========================"); Debug.WriteLine("List Name " + oList.Title); Debug.WriteLine("List Name " + lm.ListName + " " + lm.ListType + " " + lm.MappedListname); Debug.WriteLine("========================"); //3. Load the list items ListItemCollection items = oList.GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(items); clientContext.ExecuteQuery(); //4. Loop through the lists items foreach (ListItem item in items) { clientContext.Load(item); clientContext.ExecuteQuery(); //copy item - check if list or library if (oList.BaseTemplate == 100) { Debug.WriteLine("MIGRATING LIST"); List destinationList = DestClientContent.Web.Lists.GetByTitle(lm.MappedListname); DestClientContent.Load(destinationList.Fields); DestClientContent.ExecuteQuery(); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem listItem = destinationList.AddItem(itemCreateInfo); foreach (var obj in item.FieldValues) { Debug.WriteLine(" Title " + obj.Key); Debug.WriteLine(" Value " + obj.Value); //check if field in scope for migration string fieldName; if (metadataMappingsDict.TryGetValue(obj.Key, out fieldName)) { Debug.WriteLine("=========================="); Debug.WriteLine(obj.Key + " mapped to " + metadataMappingsDict[fieldName]); Debug.WriteLine("========================"); listItem[metadataMappingsDict[fieldName]] = obj.Value; } listItem["Created"] = item["Created"]; listItem.Update(); DestClientContent.ExecuteQuery(); }//end foreach (var obj in item.FieldValues) } else if (oList.BaseTemplate == 101) { Debug.WriteLine("MIGRATING LIBRARY"); try { Microsoft.SharePoint.Client.File file = item.File; clientContext.Load(file); clientContext.ExecuteQuery(); string destination = destWeb.ServerRelativeUrl.TrimEnd('/') + "/" + lm.MappedListname + "/" + file.Name; Debug.WriteLine("DESTINATION " + destination); FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, file.ServerRelativeUrl); Microsoft.SharePoint.Client.File.SaveBinaryDirect(DestClientContent, destination, fileInfo.Stream, true); var uploadedFile = DestClientContent.Web.GetFileByServerRelativeUrl(destination); var listItem = uploadedFile.ListItemAllFields; //set properties //5. Loop the fields foreach (var obj in item.FieldValues) { Debug.WriteLine(" textField " + obj.Key); Debug.WriteLine(" Value " + obj.Value); //check if field in scope for migration string fieldName; if (metadataMappingsDict.TryGetValue(obj.Key, out fieldName)) { Debug.WriteLine("========================"); Debug.WriteLine(obj.Key + " mapped to " + metadataMappingsDict[fieldName]); Debug.WriteLine("========================"); listItem[metadataMappingsDict[fieldName]] = obj.Value; } }//end foreach (var obj in item.FieldValues) listItem["Created"] = item["Created"]; listItem.Update(); DestClientContent.ExecuteQuery(); //update created date & metadata fields } catch (Exception ex) { Debug.WriteLine(ex.Message); } } } } catch (Exception ex) { Debug.WriteLine("========================"); Debug.WriteLine("NOT IN SCOPE " + oList.Title); Debug.WriteLine("========================"); } } } migrated = true; } //End destination client context } //end using clientContent } catch (Exception ex) { } //End Connect to SPO Site //update Excel Report Sheet Excel.Range last = xlMigrationReportSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing); Excel.Range range = xlMigrationReportSheet.get_Range("A1", last); int lastUsedRow = last.Row + 1; xlMigrationReportSheet.Cells[lastUsedRow, 1] = ms.OldSiteUrl; xlMigrationReportSheet.Cells[lastUsedRow, 2] = migrated.ToString(); xlSettingsFile.Save(); } }