private async Task GetDataByEventIdAsync(ClientContext clientContext, string idEvent) { List list = clientContext.Web.Lists.GetByTitle("Event List"); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='EventTitle'/>" + "<Value Type='Text'>" + idEvent + "</Value></Eq></Where></Query><RowLimit>1</RowLimit></View>"; ListItemCollection collListItem = list.GetItems(camlQuery); clientContext.Load(collListItem); clientContext.ExecuteQuery(); var users = Regex.Split(collListItem.FirstOrDefault()["EventParticipants"].ToString(), ";#"); emailTemplate.UsersEmail = users.Select(u => new Model.Domain.User() { mail = u }).ToList(); string userId = collListItem.FirstOrDefault()["EventHostId"].ToString(); var user = await _sPUserService.GetUserById(userId); emailTemplate.HostUserEmail = user; emailTemplate.EventTitle = collListItem.FirstOrDefault()["EventTitle"].ToString(); emailTemplate.Subject = "subject"; emailTemplate.EventRestaurant = collListItem.FirstOrDefault()["EventRestaurant"].ToString(); }
public void SetResultNews(string library, string idItem, string categoria) { using (ClientContext client = new ClientContext(siteUrl)) { client.Credentials = new SharePointOnlineCredentials(userName, GetPassword(passWord)); var list = client.Web.Lists.GetByTitle(library); client.Load(list); client.ExecuteQuery(); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "<View><Query><Where><Geq><FieldRef Name='ID'/>" + "<Value Type='Number'>" + idItem + "</Value></Geq></Where></Query><RowLimit>100</RowLimit></View>"; ListItemCollection collListItem = list.GetItems(camlQuery); client.Load(collListItem); client.ExecuteQuery(); if (collListItem != null) { var item = collListItem.FirstOrDefault(); item["Categoria"] = categoria; item.Update(); client.ExecuteQuery(); } } }
/// <summary> /// Checks if item is modified after it is loaded on the client side /// </summary> /// <param name="collection">List item collection</param> /// <param name="cachedItemModifiedDate">Date time when current user loaded the page to see/update configuration values.</param> /// <returns>Success flag</returns> public static bool CheckItemModified(ListItemCollection collection, string cachedItemModifiedDate) { bool response = false; int errorModifiedDate = 0; // If there is new list item being created then 'cachedItemModifiedDate' will be 0 if (null != collection && !string.IsNullOrWhiteSpace(cachedItemModifiedDate)) { if (String.Equals(Convert.ToString(errorModifiedDate, CultureInfo.InvariantCulture), cachedItemModifiedDate) && collection.Count.Equals(0)) // Verify if new item flag is true and no list item is present in the Matter Configuration list { response = true; } else if (0 < collection.Count) { ListItem settingsListItem = collection.FirstOrDefault(); DateTime cachedDate; if (DateTime.TryParse(cachedItemModifiedDate, out cachedDate)) { DateTime itemModifiedDate = Convert.ToDateTime(settingsListItem[Constants.MODIFIED_DATE_COLUMN], CultureInfo.InvariantCulture); if (0 == DateTime.Compare(cachedDate, itemModifiedDate)) { response = true; } } } } return(response); }
public void UpdateRequestStatus(string url, SiteRequestStatus status, string statusMessage) { UsingContext(ctx => { Log.Info("Provisioning.Common.Data.Impl.UpdateRequestStatus", PCResources.SiteRequestUpdate_Successfull, url, status.ToString()); var web = ctx.Web; if (!web.ListExists(SiteRequestList.TITLE)) { this.HandleSiteRequestList(ctx); } var _list = ctx.Web.Lists.GetByTitle(SiteRequestList.TITLE); var _query = new CamlQuery(); _query.ViewXml = string.Format(CAML_GETREQUEST_BY_URL, url); ListItemCollection _itemCollection = _list.GetItems(_query); ctx.Load(_itemCollection); ctx.ExecuteQuery(); if (_itemCollection.Count != 0) { ListItem _item = _itemCollection.FirstOrDefault(); _item[SiteRequestFields.PROVISIONING_STATUS_NAME] = status.ToString(); if (!string.IsNullOrEmpty(statusMessage)) { _item[SiteRequestFields.STATUSMESSAGE_NAME] = statusMessage; } _item.Update(); ctx.ExecuteQuery(); } }); }
/// <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); }
public void DeleteItem(int rowPos) { if (currentList == null) { currentList = Context.Web.Lists.GetByTitle(ViewTitle); } // Option 1: Get Item by ID ListItem oItem = currentList.GetItemById(11); // Option 2: Get Item using CAML Query CamlQuery oQuery = new CamlQuery(); oQuery.ViewXml = $@"<View><Query><Where> <Eq> <FieldRef Name='{Title}' /> <Value Type='Text'>New List Item</Value> </Eq> </Where></Query></View>"; ListItemCollection oItems = currentList.GetItems(oQuery); Context.Load(oItems); Context.ExecuteQuery(); oItem = oItems.FirstOrDefault(); // Option 2: Ends Here(Above line) oItem.DeleteObject(); Context.ExecuteQuery(); }
private void button9_Click(object sender, EventArgs e) { using (var context = new ClientContext("https://thethread-qa.carpetright.co.uk/Facilities/")) { try { var web = context.Web; List list = null; ListItemCollection items = null; var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { list = web.Lists.GetByTitle("Test Tasks"); var query = new CamlQuery(); query.ViewXml = "<View><RowLimit>1</RowLimit></View>"; items = list.GetItems(query); context.Load(items); } using (scope.StartCatch()) { var lci = new ListCreationInformation(); lci.Title = "Test Tasks"; lci.QuickLaunchOption = QuickLaunchOptions.On; lci.TemplateType = (int)ListTemplateType.Tasks; list = web.Lists.Add(lci); } using (scope.StartFinally()) { // list = web.Lists.GetByTitle("Test Tasks"); // context.Load(list); } } //context.Load(web); context.ExecuteQuery(); var item = items.FirstOrDefault(); if (item != null) { item["Status"] = "In Progress"; item["PercentComplete"] = 0.1; item.Update(); } context.ExecuteQuery(); // var status = scope.HasException ? "Not Created" : "Created"; ResultsListBox.Items.Add("Item updated"); } catch (Exception ex) { ResultsListBox.Items.Add(ex.Message); } } }
/// <summary> /// Create variation labels /// </summary> /// <param name="context">Context for SharePoint objects and operations</param> /// <param name="variationLabels">Variation labels</param> private static void CreateVariationLabels(this ClientContext context, List <VariationLabelEntity> variationLabels) { // Get current web Web web = context.Web; context.Load(web, w => w.ServerRelativeUrl); context.ExecuteQueryRetry(); // Try to get _VarLabelsListId property from web property bag string variationLabelsListId = web.GetPropertyBagValueString(VARIATIONLABELSLISTID, string.Empty); if (!string.IsNullOrEmpty(variationLabelsListId)) { // Load the lists var lists = web.Lists; context.Load(lists); context.ExecuteQueryRetry(); // Get the "Variation Labels" List by id Guid varRelationshipsListId = new Guid(variationLabelsListId); var variationLabelsList = lists.GetById(varRelationshipsListId); // Get the variationLabelsList list items ListItemCollection collListItems = variationLabelsList.GetItems(CamlQuery.CreateAllItemsQuery()); context.Load(collListItems); context.ExecuteQueryRetry(); if (variationLabelsList != null) { foreach (VariationLabelEntity label in variationLabels) { // Check if variation label already exists var varLabel = collListItems.FirstOrDefault(x => x["Language"].ToString() == label.Language); if (varLabel == null) { // Create the new item ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem olistItem = variationLabelsList.AddItem(itemCreateInfo); olistItem["Title"] = label.Title; olistItem["Description"] = label.Description; olistItem["Flag_x0020_Control_x0020_Display"] = label.FlagControlDisplayName; olistItem["Language"] = label.Language; olistItem["Locale"] = label.Locale; olistItem["Hierarchy_x0020_Creation_x0020_M"] = label.HierarchyCreationMode; olistItem["Is_x0020_Source"] = label.IsSource; olistItem["Hierarchy_x0020_Is_x0020_Created"] = false; olistItem.Update(); context.ExecuteQueryRetry(); } } } } }
/// <summary> /// Get Item using CamlQuery /// </summary> /// <param name="operation"></param> /// <param name="query"></param> /// <param name="retrievals"></param> /// <returns></returns> public static ListItem GetItem(this CSOMOperation operation, CamlQuery query) { ListItemCollection items = operation .LastList .GetItems(query); ListItem item = items.FirstOrDefault(); operation.Load(item); return(item); }
public void UpdateRequestStatus(string url, SiteRequestStatus status, string statusMessage) { Log.Info("SPSiteRequestManager.UpdateRequestStatus", "Entering UpdateRequestStatus url {0} status {1} status message", url, status.ToString(), statusMessage); 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.UpdateRequestStatus", _message); throw new DataStoreException(_message); } var _list = ctx.Web.Lists.GetByTitle(SiteRequestList.TITLE); var _query = new CamlQuery(); _query.ViewXml = string.Format(CAML_GETREQUEST_BY_URL, url); ListItemCollection _itemCollection = _list.GetItems(_query); ctx.Load(_itemCollection); ctx.ExecuteQuery(); if (_itemCollection.Count != 0) { ListItem _item = _itemCollection.FirstOrDefault(); _item[SiteRequestFields.PROVISIONING_STATUS_NAME] = status.ToString(); if (!string.IsNullOrEmpty(statusMessage)) { _item[SiteRequestFields.STATUSMESSAGE_NAME] = statusMessage; } _item.Update(); ctx.ExecuteQuery(); } _timespan.Stop(); Log.Info("SPSiteRequestManager.UpdateRequestStatus", PCResources.SiteRequestUpdate_Successful, url, status.ToString()); Log.TraceApi("SharePoint", "SPSiteRequestManager.UpdateRequestStatus", _timespan.Elapsed); }); }
/// <summary> /// Checks if document exists. /// </summary> /// <param name="clientContext">SP client context</param> /// <param name="fileName">Name of the file.</param> /// <param name="documentLibraryName">Name of the document library.</param> /// <param name="folderPath">Path of the folder.</param> /// <returns>Returns true in case of Document presence</returns> public static DuplicateDocument DocumentExists(ClientContext clientContext, ContentCheckDetails contentCheck, string documentLibraryName, string folderPath, bool isMail) { DuplicateDocument duplicateDocument = new DuplicateDocument(false, false); if (null != clientContext && null != contentCheck && !string.IsNullOrEmpty(documentLibraryName) && !string.IsNullOrEmpty(folderPath)) { string serverRelativePath = folderPath + ConstantStrings.ForwardSlash + contentCheck.FileName; ListItemCollection listItemCollection = null; string camlQuery = string.Format(CultureInfo.InvariantCulture, ConstantStrings.GetAllFilesInFolderQuery, serverRelativePath); listItemCollection = Lists.GetData(clientContext, documentLibraryName, camlQuery); duplicateDocument.DocumentExists = (null != listItemCollection && 0 < listItemCollection.Count) ? true : false; // Check file size, from, sent date as well. if (duplicateDocument.DocumentExists) { // check for other conditions as well. ListItem listItem = listItemCollection.FirstOrDefault(); DateTime sentDate, storedFileSentDate; long fileSize = Convert.ToInt64(listItem.FieldValues[ConstantStrings.SearchEmailFileSize], CultureInfo.InvariantCulture); if (isMail) { // check for subject, from and sent date string subject = Convert.ToString(listItem.FieldValues[ConstantStrings.SearchEmailSubject], CultureInfo.InvariantCulture); string from = Convert.ToString(listItem.FieldValues[ConstantStrings.SearchEmailFrom], CultureInfo.InvariantCulture); bool isValidDateFormat; isValidDateFormat = DateTime.TryParse(Convert.ToString(listItem.FieldValues[ConstantStrings.SearchEmailSentDate], CultureInfo.InvariantCulture), out storedFileSentDate); isValidDateFormat &= DateTime.TryParse(contentCheck.SentDate, out sentDate); if (isValidDateFormat) { TimeSpan diffrence = sentDate - storedFileSentDate; uint tolleranceMin = Convert.ToUInt16(ConstantStrings.SentDateTolerance, CultureInfo.InvariantCulture); // up to how much minutes difference between uploaded files is tolerable duplicateDocument.HasPotentialDuplicate = ((fileSize == contentCheck.FileSize) && (subject.Trim() == contentCheck.Subject.Trim()) && (from.Trim() == contentCheck.FromField.Trim()) && (diffrence.Minutes < tolleranceMin)); } } else { duplicateDocument.HasPotentialDuplicate = (fileSize == contentCheck.FileSize); } } } return(duplicateDocument); }
/// <summary> /// Checks if hierarchy is created for the variation label. /// Get the "Hierarchy_x0020_Is_x0020_Created" list item value /// </summary> /// <param name="context">Context for SharePoint objects and operations</param> /// <param name="variationLabel">Variation label</param> /// <returns>True, if hierarchy is created for the variation label</returns> private static bool CheckForHierarchyCreation(this ClientContext context, VariationLabelEntity variationLabel) { bool hierarchyIsCreated = false; // Get current web Web web = context.Web; context.Load(web, w => w.ServerRelativeUrl); context.ExecuteQueryRetry(); // Try to get _VarLabelsListId property from web property bag string variationLabelsListId = web.GetPropertyBagValueString(VARIATIONLABELSLISTID, string.Empty); if (!string.IsNullOrEmpty(variationLabelsListId)) { // Load the lists var lists = web.Lists; context.Load(lists); context.ExecuteQueryRetry(); // Get the "Variation Labels" List by id Guid varRelationshipsListId = new Guid(variationLabelsListId); var variationLabelsList = lists.GetById(varRelationshipsListId); // Get the variationLabelsList list items ListItemCollection collListItems = variationLabelsList.GetItems(CamlQuery.CreateAllItemsQuery()); context.Load(collListItems); context.ExecuteQueryRetry(); if (variationLabelsList != null) { // Check hierarchy is created ListItem varLabel = collListItems.FirstOrDefault(x => x["Language"].ToString() == variationLabel.Language); variationLabel.IsCreated = hierarchyIsCreated = (bool)varLabel["Hierarchy_x0020_Is_x0020_Created"]; } } return(hierarchyIsCreated); }
public void UpdateItem(MyTestListItem item) { CamlQuery camlQuery = new CamlQuery() { ViewXml = $"<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>{item.Id}</Value></Eq></Where></Query></View>" }; List approvedTabsList = Context.Web.Lists.GetByTitle(ListTitle); ListItemCollection approvedTabs = approvedTabsList.GetItems(camlQuery); Context.Load(approvedTabs); Context.ExecuteQuery(); ListItem approvedTabItem = approvedTabs.FirstOrDefault(); if (approvedTabItem == null) { ListItemCreationInformation approvedTabCI = new ListItemCreationInformation(); approvedTabItem = approvedTabsList.AddItem(approvedTabCI); } approvedTabItem["Title"] = item.Title; approvedTabItem.Update(); Context.ExecuteQuery(); }
public Stream GetPhotoInfo(string library, string idItem) { using (ClientContext client = new ClientContext(siteUrl)) { client.Credentials = new SharePointOnlineCredentials(userName, GetPassword(passWord)); var list = client.Web.Lists.GetByTitle(library); client.Load(list); client.ExecuteQuery(); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "<View><Query><Where><Geq><FieldRef Name='ID'/>" + "<Value Type='Number'>" + idItem + "</Value></Geq></Where></Query><RowLimit>100</RowLimit></View>"; ListItemCollection collListItem = list.GetItems(camlQuery); client.Load(collListItem); client.ExecuteQuery(); if (collListItem != null) { var item = collListItem.FirstOrDefault(); client.Load(item, i => i.File); client.Load(item, i => i.File.Length); client.ExecuteQuery(); var fileRef = item.File.ServerRelativeUrl; client.ExecuteQuery(); var fileInfo = client.Web.GetFileByServerRelativeUrl(fileRef); var clientFile = fileInfo.OpenBinaryStream(); client.Load(fileInfo); client.ExecuteQuery(); var stream = clientFile.Value; var lg = clientFile.Value.Length; return(stream); } return(null); } }
public static Complaint GetComplaint(int id, string cllistName, string seg) { try { using (var clientContext = new ClientContext("http://cmlbi.za.omlac.net/sites/gladius")) { List complaints = clientContext.Web.Lists.GetByTitle(cllistName); string query = string.Format(CamlQueryConstants.GetComplaintQuery, id); var q = new CamlQuery() { ViewXml = query }; ListItemCollection items = complaints.GetItems(q); Microsoft.SharePoint.Client.TimeZone timeZoneSP = clientContext.Web.RegionalSettings.TimeZone; clientContext.Load(timeZoneSP); clientContext.Load(items); clientContext.ExecuteQuery(); ListItem listItem = items.FirstOrDefault(x => x.Id == id); var fixedTimeZoneName = timeZoneSP.Description.Replace("and", "&"); var timeZoneInfo = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(tz => tz.DisplayName == fixedTimeZoneName); var result = new Complaint() { Reference = Convert.ToString(listItem[ListColumnConstants.CompRef]), EmsCaseReference = Convert.ToString(listItem[ListColumnConstants.EMSCaseRef]), MailboxName = Convert.ToString(listItem[ListColumnConstants.MailboxName]), MemberCode = Convert.ToString(listItem[ListColumnConstants.MemCode]), Surname = Convert.ToString(listItem[ListColumnConstants.Surname]), SchemePolicyContractNo = Convert.ToString(listItem[ListColumnConstants.SchmePlcyContractNo]), Source = Convert.ToString(listItem[ListColumnConstants.Source]), SourceType = Convert.ToString(listItem[ListColumnConstants.CompSourceType]), DepartmentInvolved = Convert.ToString(listItem[ListColumnConstants.DeptInvolved]), RelatedProcess = Convert.ToString(listItem[ListColumnConstants.ReltdProcess]), Levels = Convert.ToString(listItem[ListColumnConstants.Levels]), PreviousLevelComp = Convert.ToString(listItem[ListColumnConstants.PrevLevel1Comp]), DateReceived = TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(listItem[ListColumnConstants.DateTimeReceived]), timeZoneInfo), ExtensionRequested = Convert.ToString(listItem[ListColumnConstants.ExtnRequested]), ExtensionRequestedComment = Convert.ToString(listItem[ListColumnConstants.ExtnReqComment]), ProductType = Convert.ToString(listItem[ListColumnConstants.ProductType]), BenefitType = Convert.ToString(listItem[ListColumnConstants.BenefitType]), BenefitDetail = Convert.ToString(listItem[ListColumnConstants.BenefitDetail]), Category = Convert.ToString(listItem[ListColumnConstants.CompCategory]), TcfComplaintOutcome = Convert.ToString(listItem[ListColumnConstants.TCFCompOutcome]), TcfComplaintRelatedTo = Convert.ToString(listItem[ListColumnConstants.TCFCompReltdTo]), DepartmentAtFault = Convert.ToString(listItem[ListColumnConstants.DeptAtFault]), RelatedToFund = Convert.ToString(listItem[ListColumnConstants.ReltdToFund]), Outcome = Convert.ToString(listItem[ListColumnConstants.Outcome]), Status = Convert.ToString(listItem[ListColumnConstants.Status]), WriteOffAmount = Convert.ToString(listItem[ListColumnConstants.WriteOffAmtInRands]), RootCauseAnalysis = Convert.ToString(listItem[ListColumnConstants.RCAnalysis]), ComplaintResponder = Convert.ToString(listItem[ListColumnConstants.CompRespUser]), ClosedwithinSLA = Convert.ToString(listItem[ListColumnConstants.ClosedwithinSLA]), RCAFindings = Convert.ToString(listItem[ListColumnConstants.RCAFindings]), TlComplaintOwner = Convert.ToString(listItem[ListColumnConstants.TLComplaintOwner]), ComplaintTheme = Convert.ToString(listItem[ListColumnConstants.ComplaintTheme]), LitigationAction = Convert.ToString(listItem[ListColumnConstants.RefForLitignLegalAct]), FinancialImpact = Convert.ToString(listItem[ListColumnConstants.TypeOfFinImpact]), ReasonForSlaBreach = Convert.ToString(listItem[ListColumnConstants.ReasonSLABreach]), IdNumber = Convert.ToString(listItem[ListColumnConstants.CompIDNumber]) }; if (listItem[ListColumnConstants.RCACompletionDate] != null) { result.RcTargetCompletionDate = TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(listItem[ListColumnConstants.RCACompletionDate]), timeZoneInfo); } if (listItem[ListColumnConstants.QryClosedDateRspnd] != null) { result.QueryClosedDate = TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(listItem[ListColumnConstants.QryClosedDateRspnd]), timeZoneInfo); } if (listItem[ListColumnConstants.RenegoDueDate] != null) { result.RenegotiatedDueDate = TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(listItem[ListColumnConstants.RenegoDueDate]), timeZoneInfo); } result.SegmentName = seg; if (listItem[seg + ListColumnConstants.RCAID] != null) { FieldLookupValue lookuprca = listItem[seg + ListColumnConstants.RCAID] as FieldLookupValue; result.RcId = lookuprca.LookupId.ToString(); } if (listItem[ListColumnConstants.TLComplaintOwner] != null) { FieldLookupValue lookup = listItem[ListColumnConstants.TLComplaintOwner] as FieldLookupValue; result.TlComplaintOwner = lookup.LookupValue; } return(result); } } catch (Exception ex) { throw new ArgumentException("Something went wrong: " + ex.Message); } }
static void Main(string[] args) { var siteUrl = ConfigurationManager.AppSettings["site"]; using (var context = new ClientContext(siteUrl)) { Web site = context.Web; var pwd = ConfigurationManager.AppSettings["password"]; SecureString passWord = new SecureString(); foreach (char c in pwd) { passWord.AppendChar(c); } context.Credentials = new SharePointOnlineCredentials(ConfigurationManager.AppSettings["username"], passWord); List targetList = site.Lists.GetByTitle(ConfigurationManager.AppSettings["list"]); CamlQuery query = new CamlQuery(); query.ViewXml = @"<View><Query><OrderBy><FieldRef Name='Date' Ascending='false'/></OrderBy><Where><And><Geq><FieldRef Name='Date' /><Value IncludeTimeValue='TRUE' Type='DateTime'>" + new DateTime(DateTime.Now.AddMonths(-1).Year, DateTime.Now.AddMonths(-1).Month, 1).ToString("yyyy-MM-ddTHH:mm:ssZ") + "</Value></Geq><Leq><FieldRef Name='Date' /><Value IncludeTimeValue='TRUE' Type='DateTime'>" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ") + "</Value></Leq></And></Where></Query><RowLimit>500</RowLimit></View>"; ListItemCollection collListItem = targetList.GetItems(query); context.Load(collListItem); context.ExecuteQuery(); foreach (var v in collListItem.Reverse()) { Console.WriteLine(((FieldLookupValue)v["Project_x0020__x002d__x0020_Cust0"]).LookupValue + " --- Date:" + v["Date"] + " --- Hours: " + v["Hours"]); } //Console.WriteLine("Hours this year: " + collListItem?.Sum(x => (double)x["Hours"])); //Console.WriteLine("How many +- hours this year: " + (collListItem?.Sum(x => (double)x["Hours"]) - collListItem?.GroupBy(c => DateTime.Parse(c["Date"].ToString()).Date).Count() * 8)); var gbm = collListItem.GroupBy(v => DateTime.Parse(v["Date"].ToString()).Month); var cmg = gbm.FirstOrDefault(v => v.Key == DateTime.Now.Month); Console.WriteLine("Hours this month: " + cmg?.Sum(x => (double)x["Hours"])); Console.WriteLine("How many +- hours this month: " + (cmg?.Sum(x => (double)x["Hours"]) - cmg?.GroupBy(c => DateTime.Parse(c["Date"].ToString()).Date).Count() * 8)); var gbw = collListItem.GroupBy(v => DateTime.Parse(v["Date"].ToString()).AddDays(-(int)DateTime.Parse(v["Date"].ToString()).DayOfWeek + 1).Date); var cwg = gbw.FirstOrDefault(x => x.Key == DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek + 1).Date); Console.WriteLine("Hours this week: " + cwg?.Sum(x => (double)x["Hours"])); Console.WriteLine("How many +- hours: " + (cwg?.Sum(x => (double)x["Hours"]) - cwg?.GroupBy(c => DateTime.Parse(c["Date"].ToString()).Date).Count() * 8)); foreach (var targetListItem in collListItem.GroupBy(x => ((FieldLookupValue)x["Project_x0020__x002d__x0020_Cust0"]).LookupId)) { Console.WriteLine(((FieldLookupValue)targetListItem?.FirstOrDefault()?["Project_x0020__x002d__x0020_Cust0"])?.LookupValue + " = " + ((FieldLookupValue)targetListItem?.FirstOrDefault()?["Project_x0020__x002d__x0020_Cust0"])?.LookupId); } var ht = HoursToday(); Console.WriteLine("How many hours have you worked today?"); Console.WriteLine("From: " + ht.StartTime); Console.WriteLine("To: " + ht.EndTime); var hoursToday = ConsoleReadLineWithDefault(ht.Hours); if (hoursToday != ht.Hours) { hoursToday = hoursToday.Replace(",", "."); ht.EndTime = ht.StartTime.AddHours(double.Parse(hoursToday, CultureInfo.GetCultureInfo("en-US"))); Console.WriteLine("New To: " + ht.EndTime); } Console.WriteLine("Which project id have you worked on?"); var projectId = ConsoleReadLineWithDefault(((FieldLookupValue)collListItem?.FirstOrDefault()?["Project_x0020__x002d__x0020_Cust0"])?.LookupId.ToString()); Console.WriteLine("Write a comment for the time registration?"); var comment = Console.ReadLine(); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem newItem = targetList.AddItem(itemCreateInfo); var usaHours = 8; if (TimeZoneInfo.Local.IsDaylightSavingTime(DateTime.Now)) { usaHours = 7; } newItem["Date"] = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, usaHours, 0, 0, DateTimeKind.Utc).ToString("yyyy-MM-ddTHH:mm:ssZ"); newItem["Hours"] = hoursToday.Replace(",", "."); newItem["Project_x0020__x002d__x0020_Cust0"] = projectId; newItem["Comments"] = comment; //newItem["From"] = ht.StartTime.ToString("MM-dd-yyyy HH:mm"); Time Format is weird, maybe American //newItem["To"] = ht.EndTime.ToString("MM-dd-yyyy HH:mm"); newItem["Person2"] = ((FieldLookupValue)collListItem?.FirstOrDefault()?["Person2"])?.LookupId.ToString(); newItem.Update(); context.ExecuteQuery(); } }
/// <summary> /// Gets the email template. /// </summary> /// <param name="appContext">The application context.</param> /// <param name="appWeb">The application web.</param> /// <param name="templateName">Name of the template.</param> /// <param name="listItemDetails">The list item details.</param> /// <param name="customValues">The custom values.</param> /// <param name="role">The role.</param> /// <param name="applicationName">Name of the application.</param> /// <param name="formName">Name of the form.</param> /// <returns> /// Return Subject and Body Dictionary /// </returns> public Dictionary <string, string> GetEmailBody(ClientContext appContext, Web appWeb, string templateName, List <ListItemDetail> listItemDetails, Dictionary <string, string> customValues, string role, string applicationName = ApplicationNameConstants.LUMITEMCODECREATION, string formName = FormNameConstants.ICCPForm) { Dictionary <string, string> emailTemplate = new Dictionary <string, string>(); if (!string.IsNullOrEmpty(templateName)) { //BELDataAccessLayer helper = new BELDataAccessLayer(); //string siteURL = BELDataAccessLayer.Instance.GetConfigVariable(SiteURLs.ROOTSITEURL); string siteURL = BELDataAccessLayer.Instance.GetSiteURL(SiteURLs.ROOTSITEURL); using (ClientContext context = BELDataAccessLayer.Instance.CreateClientContext(siteURL)) { List emailTemplateList = context.Web.Lists.GetByTitle(ListNames.EmailTemplateList); CamlQuery qry = new CamlQuery(); qry.ViewXml = @"<View> <Query> <Where> <And> <And> <And> <Or> <IsNull><FieldRef Name='Role' /></IsNull> <Contains> <FieldRef Name='Role' /> <Value Type='Text'>" + role + @"</Value> </Contains> </Or> <Eq> <FieldRef Name='FormName' /> <Value Type='Text'>" + formName + @"</Value> </Eq> </And> <Eq> <FieldRef Name='ApplicationName' /> <Value Type='Text'>" + applicationName + @"</Value> </Eq> </And> <Eq> <FieldRef Name='Title' /> <Value Type='Text'>" + templateName + @"</Value> </Eq> </And> </Where> </Query> </View>"; ListItemCollection items = emailTemplateList.GetItems(qry); context.Load(items); context.ExecuteQuery(); if (items.Count > 0) { ListItem emailListItem = null; if (items.Count > 1) { emailListItem = items.FirstOrDefault(i => Convert.ToString(i["Role"]) != string.Empty); } else { emailListItem = items.FirstOrDefault(); } emailTemplate["Subject"] = Convert.ToString(emailListItem["Subject"]); emailTemplate["Body"] = Convert.ToString(emailListItem["Body"]); if (listItemDetails != null || customValues != null) { ListItemDetail listDetail = listItemDetails[0]; ListItem item = listDetail.ListItemObject; string listName = listDetail.ListName; if (item == null) { List spList = appWeb.Lists.GetByTitle(listName); item = spList.GetItemById(listDetail.ItemId); appContext.Load(item); appContext.Load(spList, p => p.DefaultDisplayFormUrl); appContext.ExecuteQuery(); listDetail.ListItemObject = item; customValues["ItemLink"] = "#URL" + spList.DefaultDisplayFormUrl + "?ID=" + listDetail.ItemId; customValues["ItemLinkClickHere"] = "<a href='#URL" + spList.DefaultDisplayFormUrl + "?ID=" + listDetail.ItemId + "' >Click Here</a>"; //if (customValues.ContainsKey("CurrentUserAlise")) //{ // customValues["UserName"] = customValues[Parameter.CURRENTUSERALISE]; //} customValues["ReceiverName"] = customValues[Parameter.MAILRECEIVERNAME]; customValues["UserName"] = customValues[Parameter.CURRENTAPPROVERNAME]; } emailTemplate = this.CreateEmailBody(appContext, appWeb, emailTemplate, listItemDetails, customValues); } } } } return(emailTemplate); }
/// <summary> /// Checks if item is modified after it is loaded on the client side /// </summary> /// <param name="collection">List item collection</param> /// <param name="cachedItemModifiedDate">Date time when current user loaded the page to see/update configuration values.</param> /// <returns>Success flag</returns> public static bool CheckItemModified(ListItemCollection collection, string cachedItemModifiedDate) { bool response = false; int errorModifiedDate = 0; // If there is new list item being created then 'cachedItemModifiedDate' will be 0 if (null != collection && !string.IsNullOrWhiteSpace(cachedItemModifiedDate)) { if (String.Equals(Convert.ToString(errorModifiedDate, CultureInfo.InvariantCulture), cachedItemModifiedDate) && collection.Count.Equals(0)) // Verify if new item flag is true and no list item is present in the Matter Configuration list { response = true; } else if (0 < collection.Count) { ListItem settingsListItem = collection.FirstOrDefault(); DateTime cachedDate; if (DateTime.TryParse(cachedItemModifiedDate, out cachedDate)) { DateTime itemModifiedDate = Convert.ToDateTime(settingsListItem[Constants.MODIFIED_DATE_COLUMN], CultureInfo.InvariantCulture); if (0 == DateTime.Compare(cachedDate, itemModifiedDate)) { response = true; } } } } return response; }