/// <summary> /// Retreive file from the specified folder /// </summary> /// <param name="onlineLibrary"></param> /// <param name="destinationFolder"></param> /// <param name="onlineFileName"></param> /// <returns></returns> public static ListItem GetFileInFolder(this List onlineLibrary, Folder destinationFolder, string onlineFileName) { destinationFolder.Context.Load(destinationFolder, afold => afold.ServerRelativeUrl); destinationFolder.Context.ExecuteQuery(); var relativeUrl = destinationFolder.ServerRelativeUrl; var context = destinationFolder.Context; try { CamlQuery camlQuery = new CamlQuery(); var camlAndValue = CAML.And( CAML.Eq(CAML.FieldValue("LinkFilename", FieldType.Text.ToString("f"), onlineFileName)), CAML.Eq(CAML.FieldValue("FileDirRef", FieldType.Text.ToString("f"), relativeUrl))); camlQuery.ViewXml = CAML.ViewQuery(ViewScope.RecursiveAll, CAML.Where(camlAndValue), string.Empty, CAML.ViewFields(CAML.FieldRef("Title")), 5); ListItemCollection listItems = onlineLibrary.GetItems(camlQuery); context.Load(listItems); context.ExecuteQuery(); if (listItems.Count() > 0) { var newItem = listItems.FirstOrDefault(); return(newItem); } } catch (Exception ex) { System.Diagnostics.Trace.TraceError("Failed to retrieve file {0} MSG:{1}", onlineFileName, ex.Message); } return(null); }
internal static void UpdateAmountOfStudents(ClientContext ctx, int schoolId) { List list = ctx.Web.GetListByTitle("Students"); List schoolList = ctx.Web.GetListByTitle("Schools"); ListItem school = schoolList.GetItemById(schoolId); CamlQuery query = new CamlQuery(); query.ViewXml = @"<View> <Query> <Where><Eq><FieldRef Name='School_School' LookupId='True' /><Value Type='Lookup'>" + schoolId.ToString() + @"</Value></Eq></Where> </Query> </View>"; // TODO get only the title viewfield as i only want the count. ListItemCollection items = list.GetItems(query); ctx.Load(items); ctx.Load(school); ctx.ExecuteQuery(); int amountOfStudents = items.Count(); school["School_StudAmt"] = amountOfStudents; school.SystemUpdate(); ctx.ExecuteQuery(); }
public void AddContact() { List list = clientContext.Web.Lists.GetByTitle("Address Book"); CamlQuery query = new CamlQuery(); query.ViewXml = "<View/>"; ListItemCollection items = list.GetItems(query); clientContext.Load(list); clientContext.Load(items); clientContext.ExecuteQuery(); ListItem lastItem = items[items.Count() - 1]; ListItemCreationInformation newItem = new ListItemCreationInformation(); ListItem newContact = list.AddItem(newItem); newContact["Title"] = (Int32.Parse(lastItem["Title"].ToString()) + 1).ToString(); newContact["ContactName"] = commonMethods.ReadString("Enter name of the contact : "); string email = commonMethods.ReadString("Enter email id of the contact : "); bool isValidEmail = commonMethods.IsValidEmail(email); while (!isValidEmail) { email = commonMethods.ReadString("Please enter a valid email : "); isValidEmail = commonMethods.IsValidEmail(email); } newContact["Email"] = email; string mobile = commonMethods.ReadString("Enter new mobile number of contact : "); bool isValidMobileNumber = commonMethods.IsValidPhoneNumber(mobile); while (!isValidMobileNumber) { mobile = commonMethods.ReadString("Please enter a valid mobile number : "); isValidMobileNumber = commonMethods.IsValidPhoneNumber(mobile); } newContact["Mobile"] = mobile; Console.Write("Enter landline number of contact : "); string landline = Console.ReadLine(); newContact["Landline"] = landline; Console.Write("Enter website of the contact : "); string website = Console.ReadLine(); newContact["Website"] = website; Console.Write("Enter address of the contact : "); string address = Console.ReadLine(); newContact["Address"] = address; newContact.Update(); clientContext.ExecuteQuery(); Console.WriteLine("Contact added successfully!!"); FurtherActions(); }
/// <summary> /// Method doing actually something with the changes obtained via the web hook notification. /// In this demo we're just logging to a list, in your implementation you do what you need to do :-) /// </summary> private static void DoWork(ClientContext approvalCC, List approvalList, ClientContext notificationCC, List notificationSourceList, Change change, NotificationModel notification, TraceWriter log) { try { log.Info("Loading source item with id: " + ((ChangeItem)change).ItemId); log.Info("Notification Source List name:" + notificationSourceList.Title + " " + notificationSourceList.ParentWebUrl); ListItem li = notificationSourceList.GetItemById(((ChangeItem)change).ItemId); notificationCC.Load(li); notificationCC.ExecuteQuery(); log.Info("Loaded source item with ID: " + ((ChangeItem)change).ItemId); // Only add approval item if in PEnding approval status if (li.FieldValues["_ModerationStatus"].ToString() == "2") { var changeItem = change as ChangeItem; CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "<View><Query><Where><And><And>"; camlQuery.ViewXml += $"<Eq><FieldRef Name='ClientState' /><Value Type='Text'>{notification.ClientState}</Value></Eq>"; camlQuery.ViewXml += $"<Eq><FieldRef Name='Resource' /><Value Type='Text'>{notification.Resource}</Value></Eq></And>"; camlQuery.ViewXml += $"<And><Eq><FieldRef Name='ItemId' /><Value Type='Text'>{changeItem.ItemId}</Value></Eq>"; camlQuery.ViewXml += $"<Eq><FieldRef Name='ActivityId' /><Value Type='Text'>{changeItem.UniqueId}</Value></Eq>"; camlQuery.ViewXml += $"</And></And></Where></Query></View>"; ListItemCollection matchingItems = approvalList.GetItems(camlQuery); approvalCC.Load(matchingItems); approvalCC.ExecuteQuery(); if (matchingItems.Count() == 0) { ListItemCreationInformation newItem = new ListItemCreationInformation(); ListItem item = approvalList.AddItem(newItem); var editor = li.FieldValues["Editor"] as FieldUserValue; item["Title"] = string.Format("List {0} had a Change of type \"{1}\" on the item with Id {2}.", notificationSourceList.Title, change.ChangeType.ToString(), (change as ChangeItem).ItemId); item["ClientState"] = notification.ClientState; item["SubscriptionId"] = notification.SubscriptionId; item["ExpirationDateTime"] = notification.ExpirationDateTime; item["Resource"] = notification.Resource; item["TenantId"] = notification.TenantId; item["SiteUrl"] = notification.SiteUrl; item["WebId"] = notification.WebId; item["ItemId"] = changeItem.ItemId; item["ActivityId"] = changeItem.UniqueId; item["EditorEmail"] = editor.Email; item["Activity"] = change.ChangeType.ToString(); item.Update(); approvalCC.ExecuteQueryRetry(); } } } catch (Exception exp) { log.Error("Unable to log approval: " + exp.Message + ":::" + exp.StackTrace); } }
public static bool AddToEmailQueue(ClientContext context, string TemplateCode, Hashtable DynamicKeyValues, string RecipientTo, string RecipientCc, Web subSite = null) { string emailSub = string.Empty; string emailBody = string.Empty; List lstDoc = null; if (subSite == null) { lstDoc = context.Web.Lists.GetByTitle(AppConstant.EmailTemplate); } else { lstDoc = subSite.Lists.GetByTitle(AppConstant.EmailTemplate); } string camlQuery = "<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + TemplateCode + "</Value></Eq></Where></Query></View>"; string emailSubjectColumnName = string.Empty; ListItemCollection lstItemsDoc = GetListItems(AppConstant.EmailTemplate, context, null, camlQuery, subSite); if (lstDoc.ContainsField("EmailSubject")) { emailSubjectColumnName = "EmailSubject"; } else { emailSubjectColumnName = "EmailSubject1"; } if (lstItemsDoc != null & lstItemsDoc.Count() > 0) { try { foreach (ListItem item in lstItemsDoc) { emailSub = Convert.ToString(item[emailSubjectColumnName]); emailBody = Convert.ToString(item["EmailBody1"]); foreach (string key in DynamicKeyValues.Keys) { emailSub = emailSub.Replace("[##" + key + "##]", Convert.ToString(DynamicKeyValues[key])); emailBody = emailBody.Replace("[##" + key + "##]", Convert.ToString(DynamicKeyValues[key])); } break; } } catch (Exception) { throw; } } bool status = false; string clientName = ConfigurationManager.AppSettings["ClientName"].ToString(); SendMailRequest objtb = new SendMailRequest(); objtb.To = RecipientTo; objtb.Cc = RecipientCc; objtb.SenderEmailId = "*****@*****.**"; objtb.SenderName = "HCL Academy"; if (!string.IsNullOrEmpty(clientName)) { objtb.SenderName = clientName + " Academy"; } objtb.Subject = emailSub; objtb.Body = emailBody; Task.Factory.StartNew(() => EmailHelper.SendEmail(objtb)); status = true; return(status); }
public static void GetFailedDocuments() { using (ClientContext ctx = new ClientContext(ConfigurationManager.AppSettings["WebUrl"].ToString())) //sharepointurl { // SecureString securePassword = GetSecureString(Utility.) ctx.ExecutingWebRequest += new EventHandler <WebRequestEventArgs>(ctx_MixedAuthRequest); //Set the Windows credentials. ctx.AuthenticationMode = ClientAuthenticationMode.Default; try { //Connect to sharepoint string username = ConfigurationManager.AppSettings["UserName"].ToString(); string password = ConfigurationManager.AppSettings["Password"].ToString(); string domain = ConfigurationManager.AppSettings["Domain"].ToString(); ctx.Credentials = new NetworkCredential(username, password, domain); Console.WriteLine("Successfully connected to Sharepoint"); //Build Query. Web web = ctx.Web; List list = web.Lists.GetByTitle(ConfigurationManager.AppSettings["Title"].ToString()); var query = new CamlQuery(); query.ViewXml = string.Format(@"<View> <Query> <Where> <Eq> <FieldRef Name='IsEnadocUploaded' /> <Value Type='Boolean'>0</Value> </Eq> </Where> </Query> </View>"); ListItemCollection listItems = list.GetItems(query); //Load List ctx.Load(listItems); ctx.ExecuteQuery(); var s = listItems.ToList().Select(i => i["MainDocumentId"]).Distinct(); //Loop No of IDs foreach (var itm in s) { if (itm != null) { Console.WriteLine(itm); int ID = int.Parse(itm.ToString()); try { var client = new RestClient(ConfigurationManager.AppSettings["ApiUrl"].ToString());//api var request = new RestRequest(ConfigurationManager.AppSettings["ApiResource"].ToString(), Method.POST); string mainDocumentID = ID.ToString(); request.AddHeader("Id", mainDocumentID); var result = client.Execute(request); if (result.StatusCode == HttpStatusCode.OK) { bool text = true; Print("GetFailedDocuments ", " Document Uploaded. Document ID : " + mainDocumentID, text); Console.WriteLine("Document Uploaded. Document ID: " + mainDocumentID); continue; } else { bool text = true; Print("GetFailedDocuments ", " Document Failed from StatusCode. Document ID : " + mainDocumentID, text); Console.WriteLine("Document Failed.Document ID: " + mainDocumentID); } } catch (Exception e) { bool text = false; string er = string.Format(" Document Failed. Documet Id : {0} Error : {1}", ID, e); Print("GetFailedDocuments", er, text); Console.WriteLine("Error : " + e); continue; } } else { bool text = true; Print("GetFailedDocuments", " Document Failed. Document ID : Null ", text); Console.WriteLine("Document Id is Null."); } Console.ReadLine(); } bool text1 = true; string logmsg = String.Format("Successfully pushed {0} Documents. ", listItems.Count()); Print("GetFailedDocuments", logmsg, text1); Console.WriteLine("Successfully pushed {0} Documents. ", listItems.Count()); //key - auto - value - no var run = ConfigurationManager.AppSettings["auto"]; Console.ReadLine(); } catch (Exception ex) { bool text = false; Print("GetFailedDocuments", "Error : " + ex, text); Console.WriteLine(ex); } } return; }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); LogVerbose("Scanning CSOM callout"); var invalidLinks = new List <CalloutLinkModel>(); var fields = new string[] { "_dlc_DocId", "_dlc_DocIdUrl", "Modified", "Editor", "ServerRedirectedEmbedUri", "FileRef", "Title" }; var fieldsXml = CAML.ViewFields(fields.Select(s => CAML.FieldRef(s)).ToArray()); var onlineLibrary = List.GetList(this.ClientContext.Web); if (!EndId.HasValue) { onlineLibrary.EnsureProperties(ol => ol.ItemCount); EndId = onlineLibrary.ItemCount; } ListItemCollectionPosition itemCollectionPosition = null; CamlQuery camlQuery = new CamlQuery(); for (var idx = 1; idx <= EndId; idx += 1000) { camlQuery.ViewXml = string.Format(@"<View Scope='RecursiveAll'><Query> <OrderBy><FieldRef Name='ID' /></OrderBy> <Where> <And> <And> {0}{1} </And> <Or> {2}{3} </Or> </And> </Where> {4} <RowLimit Paged='TRUE'>30</RowLimit> </Query></View>", CAML.Geq(CAML.FieldValue("ID", FieldType.Integer.ToString("f"), idx.ToString())), CAML.Leq(CAML.FieldValue("ID", FieldType.Integer.ToString("f"), (idx + 1000).ToString())), CAML.Eq(CAML.FieldValue("FileDirRef", FieldType.Text.ToString("f"), Path)), CAML.Contains(CAML.FieldValue("_dlc_DocIdUrl", FieldType.URL.ToString("f"), PartialUrl)), fieldsXml ); while (true) { camlQuery.ListItemCollectionPosition = itemCollectionPosition; ListItemCollection listItems = onlineLibrary.GetItems(camlQuery); this.ClientContext.Load(listItems); this.ClientContext.ExecuteQuery(); itemCollectionPosition = listItems.ListItemCollectionPosition; if (listItems.Count() > 0) { foreach (var listItem in listItems) { var item = onlineLibrary.GetItemById(listItem.Id); this.ClientContext.Load(item); this.ClientContext.ExecuteQuery(); var docId = item.RetrieveListItemValue("_dlc_DocId"); var docIdUrl = item.RetrieveListItemValueAsHyperlink("_dlc_DocIdUrl"); var modified = item.RetrieveListItemValue("Modified").ToDateTime(); var editor = item.RetrieveListItemUserValue("Editor"); var redirectEmbeddedUrl = item.RetrieveListItemValue("ServerRedirectedEmbedUri"); var fileRef = item.RetrieveListItemValue("FileRef"); var title = item.RetrieveListItemValue("Title"); invalidLinks.Add(new CalloutLinkModel() { DocId = docId, DocIdUrl = (docIdUrl == null) ? string.Empty : docIdUrl.Url, Modified = modified, EditorEmail = (editor == null) ? string.Empty : editor.ToUserEmailValue(), EmbeddedUrl = redirectEmbeddedUrl, FileUrl = fileRef, Title = title, Id = listItem.Id }); } } if (itemCollectionPosition == null) { break; } } } WriteObject(invalidLinks); }