예제 #1
0
        /// <summary>
        /// Sends individual document to OneDrive
        /// </summary>
        /// <param name="clientContext">SP client context</param>
        /// <param name="collectionOfAttachments">Dictionary object containing attachment URLs and their stream data</param>
        /// <param name="listItemsColl">List item collection of Legal Briefcase folder</param>
        /// <param name="allAttachmentUrl">A string array containing all the attachment URLs</param>
        /// <param name="web">Object of site</param>
        /// <param name="usersMySite">My Site URL of the user</param>
        /// <param name="collectionOfOriginalAttachments">Dictionary object containing attachment URLs</param>
        /// <param name="defaultContentTypeId">Default content type Id</param>
        /// <param name="status">Status of documents sent to OneDrive</param>
        /// <returns>Status of documents sent to OneDrive</returns>
        internal static string SendIndividualDocument(ClientContext clientContext, Dictionary <string, Stream> collectionOfAttachments, ListItemCollection listItemsColl, string[] allAttachmentUrl, Microsoft.SharePoint.Client.Web web, string usersMySite, Dictionary <string, string> collectionOfOriginalAttachments, string defaultContentTypeId, string status)
        {
            int    documentCount = 0, count = 0;
            string fileNameKey           = string.Empty;
            string overwriteDocumentURLs = string.Empty;

            foreach (string key in collectionOfAttachments.Keys)
            {
                fileNameKey = key.Split(new string[] { ConstantStrings.DOLLAR }, StringSplitOptions.RemoveEmptyEntries)[0];
                var selectedItems = from li in listItemsColl.Cast <ListItem>()
                                    from files in li.Folder.Files
                                    where files.Name.ToUpperInvariant() == fileNameKey.ToUpperInvariant()
                                    select files;
                if (selectedItems.FirstOrDefault() != null)
                {
                    overwriteDocumentURLs += allAttachmentUrl[count] + ConstantStrings.Semicolon;
                }
                else
                {
                    SendDocumentToOneDrive(web, usersMySite, fileNameKey, collectionOfAttachments[key], collectionOfOriginalAttachments[key], defaultContentTypeId);
                    documentCount++;
                }
                count++;
                web.Update();
                clientContext.ExecuteQuery();
                MailAttachmentDetails.CheckoutFailedPosition++;
                status = string.Concat(usersMySite, ServiceConstantStrings.OneDriveDocumentLibraryTitle, ConstantStrings.Semicolon, documentCount, ConstantStrings.Semicolon, collectionOfAttachments.Count, ConstantStrings.Semicolon, overwriteDocumentURLs);
            }
            return(status);
        }
        /// <summary>
        /// Returns the ListItems from the ListItemCollection that aren't selected.
        /// </summary>
        public static IEnumerable <ListItem> NonSelectedItems(this ListItemCollection value)
        {
            if (value.Count == 0)
            {
                return(new Collection <ListItem>());
            }

            return(value.Cast <ListItem>().Where(x => !x.Selected));
        }
예제 #3
0
        public async Task <List <KeyValuePair <string, string> > > GetLookupItems(Model.FieldLookup lookup)
        {
            if (lookup.LookupWebId == Guid.Empty || string.IsNullOrEmpty(lookup.LookupList))
            {
                return(null);
            }

            using (var context = CreateContext(lookup.List.Web.Url))
            {
                var lookupField = string.IsNullOrEmpty(lookup.LookupField) ? "Title" : lookup.LookupField;
                var caml        = $@"
                    <Query>
                        <Where />
                    </Query>";

                ListItemCollection pageItems = null;
                var pageSize = 2000;
                var items    = new List <KeyValuePair <string, string> >();

                var web  = context.Site.OpenWebById(lookup.LookupWebId);
                var list = web.Lists.GetById(Guid.Parse(lookup.LookupList));

                do
                {
                    var rowLimit  = $"<RowLimit>{pageSize}</RowLimit>";
                    var listQuery = new CamlQuery
                    {
                        ViewXml = $"<View Scope='RecursiveAll'>{caml}{rowLimit}</View>",
                        ListItemCollectionPosition = pageItems?.ListItemCollectionPosition
                    };

                    pageItems = list.GetItems(listQuery);
                    context.Load(pageItems,
                                 elements => elements.Include(
                                     i => i.Id,
                                     i => i[lookupField]
                                     ),
                                 elements => elements.ListItemCollectionPosition);

                    await Task.Factory.StartNew(() => context.ExecuteQuery());

                    items.AddRange(
                        pageItems
                        .Cast <ListItem>()
                        .Select(i => new KeyValuePair <string, string>(
                                    i.Id.ToString(),
                                    i[lookupField] != null ? i[lookupField].ToString() : string.Empty
                                    )
                                )
                        );
                }while (pageItems?.ListItemCollectionPosition != null);

                return(items
                       .OrderBy(i => i.Value)
                       .ToList());
            }
        }
예제 #4
0
    private DataTable GetSelectedItems(ListItemCollection list)
    {
        var dt = new DataTable();

        dt.Columns.Add("ID");

        list.Cast <ListItem>().Where(item => item.Selected == true).Select(item => Int32.Parse(item.Value)).ToList().ForEach(id => {
            var row   = dt.NewRow();
            row["ID"] = id;
            dt.Rows.Add(row);
        });

        return(dt);
    }
예제 #5
0
        public async Task <List <Model.ListItem> > ExecuteQuery(Model.ListQuery query, int?pageSize)
        {
            using (var context = CreateContext(query.List.Web.Url))
            {
                var queryString = query.Query.StartsWith("<Query>", StringComparison.OrdinalIgnoreCase)
                    ? query.Query
                    : $"<Query>{query.Query}</Query>";

                var serverList = context.Web.Lists.GetById(query.List.Id);
                ListItemCollection pageItems = null;
                var items = new List <Model.ListItem>();

                do
                {
                    var rowLimit  = pageSize.HasValue ? $"<RowLimit>{pageSize}</RowLimit>" : string.Empty;
                    var listQuery = new CamlQuery {
                        ViewXml = $"<View Scope='RecursiveAll'>{queryString}{rowLimit}</View>",
                        ListItemCollectionPosition = pageItems?.ListItemCollectionPosition
                    };

                    pageItems = serverList.GetItems(listQuery);
                    context.Load(pageItems);

                    await Task.Factory.StartNew(() => context.ExecuteQuery());

                    items.AddRange(
                        pageItems
                        .Cast <ListItem>()
                        .Select(i => new Model.ListItem(query.List)
                    {
                        Id      = i.Id,
                        Columns =
                            query.List
                            .Fields
                            .ToDictionary(
                                f => f.InternalName,
                                f => ElementSelector(f, i)
                                )
                    })
                        );
                }while (pageItems?.ListItemCollectionPosition != null);

                return(items);
            }
        }
예제 #6
0
        /// <summary>
        /// Retrieves the list item ID.
        /// </summary>
        /// <param name="clientContext">Client context object</param>
        /// <param name="libraryName">Library name</param>
        /// <param name="pageName">Page name</param>
        /// <returns>List item id</returns>
        public static int RetrieveItemId(ClientContext clientContext, string libraryName, string pageName)
        {
            int listItemId = -1;

            if (null != clientContext && !string.IsNullOrWhiteSpace(libraryName) && !string.IsNullOrWhiteSpace(pageName))
            {
                ListItemCollection listItemCollection = GetData(clientContext, libraryName);
                clientContext.Load(listItemCollection, listItemCollectionProperties => listItemCollectionProperties.Include(listItemProperties => listItemProperties.Id, listItemProperties => listItemProperties.DisplayName));
                clientContext.ExecuteQuery();

                ListItem listItem = listItemCollection.Cast <ListItem>().FirstOrDefault(listItemProperties => listItemProperties.DisplayName.ToUpper(CultureInfo.InvariantCulture).Equals(pageName.ToUpper(CultureInfo.InvariantCulture)));

                if (null != listItem)
                {
                    listItemId = listItem.Id;
                }
            }
            return(listItemId);
        }
        /// <summary>
        /// A small helper method to create the basic merge varibles from a person (FNAME, LNAME, BIRTHDATE, GENDER).
        /// </summary>
        /// <param name="person"></param>
        /// <param name="merges"></param>
        private static void BuildMergeVars(Person person, MCMergeVar[] merges, ListItemCollection listItemCollection)
        {
            merges[0].tag = "FNAME";
            merges[0].val = person.FirstName;
            merges[1].tag = "LNAME";
            merges[1].val = person.LastName;

            if (person.BirthDate != Constants.NULL_DATE)
            {
                merges[2].tag = "BIRTHDATE";
                merges[2].val = person.BirthDate.ToShortDateString();
            }
            merges[3].tag = "GENDER";
            merges[3].val = person.Gender.ToString();

            merges[4].tag = "INTERESTS";

            // Turn the selected items in the checkbox into a comma delimited list of interests (ex: "A,B,C")
            var values = listItemCollection.Cast <ListItem>().Where(n => n.Selected).Select(n => n.Value).ToArray();

            merges[4].val = string.Join(",", values);
        }
예제 #8
0
        /// <summary>
        /// 拼接Excel标题
        /// </summary>
        protected override void HideExcelGridViewColumn()
        {
            var items = new ListItemCollection();

            if (SelectList != null)
            {
                foreach (ListItem item in SelectList.Items)
                {
                    items.Add(item);
                }
            }
            if (DimensionCheckList != null)
            {
                foreach (ListItem item in DimensionCheckList.Items)
                {
                    items.Add(item);
                }
            }
            if (TypeRadioButtonList != null)
            {
                foreach (ListItem item in TypeRadioButtonList.Items)
                {
                    items.Add(item);
                }
            }
            for (int i = 0; i < GridView.Columns.Count; i++)
            {
                GridView.Columns[i].Visible = true;
                if (items.Cast <ListItem>().Any(item => GridView.Columns[i].HeaderText.Equals(item.Text) && !item.Selected))
                {
                    GridView.Columns[i].Visible = false;
                }
                if (GridView.Columns[i].Visible)
                {
                    SetExcelGridViewColumnItemStyle(GridView.Columns[i]);
                }
            }
        }
예제 #9
0
        private IDictionary <string, string> AtualizarListaCamposVisiveis()
        {
            var temp = new ListItemCollection();

            foreach (ListItem item in chkListaCamposVisiveis.Items)
            {
                temp.Add(item);
            }
            //pegar lista já marcada nos checkbox
            var manterModulosProgramas = new ManterModulo();
            IList <Dominio.Classes.Modulo> ls;
            var resultado  = new Dictionary <string, string>();
            var idPrograma = string.IsNullOrEmpty(txtPrograma.Text) ? 0 : int.Parse(txtPrograma.Text);
            var idOferta   = string.IsNullOrWhiteSpace(cbxOfertas.SelectedValue) ? 0 : int.Parse(cbxOfertas.SelectedValue);
            var idModulo   = string.IsNullOrWhiteSpace(cbxModulos.SelectedValue) ? 0 : int.Parse(cbxModulos.SelectedValue);

            if (idModulo != 0)
            {
                ls = new List <Modulo>
                {
                    manterModulosProgramas.ObterPorId(idModulo)
                };
            }
            else if (idOferta != 0)
            {
                ls = manterModulosProgramas.ObterPorCapacitacao(idOferta);

                WebFormHelper.PreencherLista(ls, cbxModulos, true);
            }
            else if (idPrograma != 0)
            {
                ls = manterModulosProgramas.ObterPorPrograma(idPrograma);
            }
            else
            {
                ls = manterModulosProgramas.ObterTodos();
            }

            foreach (var item in ls)
            {
                var itemPrazo = new ListItem
                {
                    Selected = true,
                    Text     = item.Nome + " - Prazo",
                    Value    = "MD__" + RemoveExtraChars(item.Nome) + "__prazo__" + item.ID + "__"
                };
                var itemSolucoesInscritas = new ListItem
                {
                    Selected = true,
                    Text     = item.Nome + " - Soluções Inscritas",
                    Value    = "MD__" + RemoveExtraChars(item.Nome) + "__SolucoesInscritas__" + item.ID + "__"
                };
                var itemSolucoesConcluidas = new ListItem
                {
                    Selected = true,
                    Text     = item.Nome + " - Soluções Concluídas",
                    Value    = "MD__" + RemoveExtraChars(item.Nome) + "__SolucoesConcluidas__" + item.ID + "__"
                };
                _lsItens.Add(itemPrazo);
                _lsItens.Add(itemSolucoesInscritas);
                _lsItens.Add(itemSolucoesConcluidas);

                resultado.Add(itemPrazo.Value, item.Nome);
                resultado.Add(itemSolucoesInscritas.Value, item.Nome);
                resultado.Add(itemSolucoesConcluidas.Value, item.Nome);
            }

            WebFormHelper.PreencherLista(_lsItens, chkListaCamposVisiveis);

            foreach (ListItem item in chkListaCamposVisiveis.Items)
            {
                var valor = true;
                if (temp.Count > 0)
                {
                    var item1 = item;
                    foreach (var tmp in temp.Cast <ListItem>().Where(tmp => tmp.Value == item1.Value))
                    {
                        valor = tmp.Selected;
                        break;
                    }
                }
                item.Selected = valor;
            }

            foreach (var item in ls)
            {
                foreach (var item2 in _lsItens.Cast <ListItem>().Where(item2 => item2.Text.IndexOf(item.Nome) >= 0))
                {
                    item2.Text = item2.Text.Replace(item.Nome + " - ", "");
                }
            }

            dgRelatorio.Columns.Clear();
            foreach (ListItem item in _lsItens)
            {
                dgRelatorio.Columns.Add(new BoundField
                {
                    HeaderText     = item.Text,
                    DataField      = item.Value,
                    SortExpression = item.Value
                });
            }

            return(resultado);
        }
예제 #10
0
 /// <summary>
 /// Use this method instead of ListItemCollection.FindBValue to find the specific item with case-insensitive.
 /// </summary>
 /// <param name="listItems">the items.</param>
 /// <param name="value">the item with this value want to find.</param>
 /// <returns>the specific item or null if didn't match the value with any item.</returns>
 public static ListItem FindByValueWithIgnoreCase(this ListItemCollection listItems, string value)
 {
     return(listItems.Cast <ListItem>().FirstOrDefault(item => item.Value.Equals(value, StringComparison.InvariantCultureIgnoreCase)));
 }
예제 #11
0
 /// <summary>
 /// Use this method instead of ListItemCollection.FindByText to find the specific item with case-insensitive.
 /// </summary>
 /// <param name="listItems">the items.</param>
 /// <param name="text">the item with this text want to find.</param>
 /// <returns>the specific item or null if didn't match the text with any item.</returns>
 public static ListItem FindByTextWithIgnoreCase(this ListItemCollection listItems, string text)
 {
     return(listItems.Cast <ListItem>().FirstOrDefault(item => item.Text.Equals(text, StringComparison.InvariantCultureIgnoreCase)));
 }
 /// <summary>
 /// Sends individual document to OneDrive
 /// </summary>
 /// <param name="clientContext">SP client context</param>
 /// <param name="collectionOfAttachments">Dictionary object containing attachment URLs and their stream data</param>
 /// <param name="listItemsColl">List item collection of Legal Briefcase folder</param>
 /// <param name="allAttachmentUrl">A string array containing all the attachment URLs</param>
 /// <param name="web">Object of site</param>
 /// <param name="usersMySite">My Site URL of the user</param>
 /// <param name="collectionOfOriginalAttachments">Dictionary object containing attachment URLs</param>
 /// <param name="defaultContentTypeId">Default content type Id</param>
 /// <param name="status">Status of documents sent to OneDrive</param>
 /// <returns>Status of documents sent to OneDrive</returns>
 internal static string SendIndividualDocument(ClientContext clientContext, Dictionary<string, Stream> collectionOfAttachments, ListItemCollection listItemsColl, string[] allAttachmentUrl, Microsoft.SharePoint.Client.Web web, string usersMySite, Dictionary<string, string> collectionOfOriginalAttachments, string defaultContentTypeId, string status)
 {
     int documentCount = 0, count = 0;
     string fileNameKey = string.Empty;
     string overwriteDocumentURLs = string.Empty;
     foreach (string key in collectionOfAttachments.Keys)
     {
         fileNameKey = key.Split(new string[] { ConstantStrings.DOLLAR }, StringSplitOptions.RemoveEmptyEntries)[0];
         var selectedItems = from li in listItemsColl.Cast<ListItem>()
                             from files in li.Folder.Files
                             where files.Name.ToUpperInvariant() == fileNameKey.ToUpperInvariant()
                             select files;
         if (selectedItems.FirstOrDefault() != null)
         {
             overwriteDocumentURLs += allAttachmentUrl[count] + ConstantStrings.Semicolon;
         }
         else
         {
             SendDocumentToOneDrive(web, usersMySite, fileNameKey, collectionOfAttachments[key], collectionOfOriginalAttachments[key], defaultContentTypeId);
             documentCount++;
         }
         count++;
         web.Update();
         clientContext.ExecuteQuery();
         MailAttachmentDetails.CheckoutFailedPosition++;
         status = string.Concat(usersMySite, ServiceConstantStrings.OneDriveDocumentLibraryTitle, ConstantStrings.Semicolon, documentCount, ConstantStrings.Semicolon, collectionOfAttachments.Count, ConstantStrings.Semicolon, overwriteDocumentURLs);
     }
     return status;
 }
예제 #13
0
 public IEnumerable <TEntity> ToEntities(ListItemCollection items)
 {
     return(ToEntities(items.Cast <ListItem>()));
 }
예제 #14
0
        //public static void Add(this ControlCollection controlCollection, IFrontendComponent frontendComponent)
        //{
        //    controlCollection.Add((Control)frontendComponent);
        //}

        public static bool ContainsValue(this ListItemCollection collection, string value)
        {
            return(collection.Cast <ListItem>().Any(x => string.Equals(value, x.Value)));
        }
        static void processRegistrations(ClientContext clientContext)
        {
            // get Registrations data from sql db into data table
            registrationsTableAdapter rda = new registrationsTableAdapter();
            registrationsDataTable    rdt = new registrationsDataTable();

            _ = rda.Fill(rdt);

            strLogItem += "Registrations table rows read: " + rdt.Rows.Count + "\r\n";
            int rowsProcessed = 0;

            // get list to sync
            List      oList = clientContext.Web.Lists.GetByTitle("Registrations");
            CamlQuery cq    = new CamlQuery();

            cq.ViewXml = "<View/>";

            // get list item collection
            ListItemCollection items = oList.GetItems(cq);

            clientContext.Load(items);
            clientContext.ExecuteQuery();

            // cast list item collection to dictionary for fast finding
            Dictionary <string, ListItem> RegistrationItems = items.Cast <ListItem>().ToDictionary(i => (string)i["RegistrationID"], i => i);

            // get Company list to find SP lookup ID
            List      oListCo = clientContext.Web.Lists.GetByTitle("Company");
            CamlQuery cqCo    = new CamlQuery();

            cqCo.ViewXml = "<View/>";

            // get Company list item collection to find SP lookup ID
            ListItemCollection itemsCo = oListCo.GetItems(cqCo);

            clientContext.Load(itemsCo);
            clientContext.ExecuteQuery();

            // cast Company list item collection to dictionary for fast finding of SP lookup ID
            Dictionary <string, ListItem> CompanyItems = itemsCo.Cast <ListItem>().ToDictionary(i => (string)i["CompanyID"], i => i);

            // loop through db rows
            foreach (DataRow row in rdt.Rows)
            {
                try
                {
                    // check if the row is already a list item in sp list
                    if (RegistrationItems.TryGetValue(row["id"].ToString(), out ListItem item))
                    {
                        // if there are changes in sp list item then apply to row
                        if (
                            row["personalEmail"].ToString() != item["Title"].ToString() ||
                            row["lastName"].ToString() != item["lastName"].ToString() ||
                            row["firstName"].ToString() != item["firstName"].ToString() ||
                            row["MI"].ToString() != (item["MI"] == null ? "" : item["MI"].ToString()) ||
                            row["birthDate"].ToString() != item["birthDate"].ToString() ||
                            row["gender"].ToString() != item["gender"].ToString() ||
                            row["address1"].ToString() != item["address1"].ToString() ||
                            row["address2"].ToString() != (item["address2"] == null ? "" : item["address2"].ToString()) ||
                            row["city"].ToString() != item["city"].ToString() ||
                            row["state"].ToString() != item["state"].ToString() ||
                            row["zip"].ToString() != item["zip"].ToString() ||
                            row["suffix"].ToString() != (item["suffix"] == null ? "" : item["suffix"].ToString()) ||
                            row["primaryPhone"].ToString() != item["primaryPhone"].ToString() ||
                            row["phoneType"].ToString() != item["phoneType"].ToString() ||
                            row["language"].ToString() != item["language"].ToString() ||
                            row["studentSignature"].ToString() != (item["studentSignature"] == null ? "" : item["studentSignature"].ToString()) ||
                            row["registeredDate"].ToString() != item["registeredDate"].ToString()
                            )
                        {
                            row["Title"]            = item["personalEmail"].ToString();
                            row["lastName"]         = item["lastName"].ToString();
                            row["firstName"]        = item["firstName"].ToString();
                            row["MI"]               = item["MI"] == null ? "" : item["MI"].ToString();
                            row["birthDate"]        = item["birthDate"].ToString();
                            row["gender"]           = item["gender"].ToString();
                            row["address1"]         = item["address1"].ToString();
                            row["address2"]         = item["address2"] == null ? "" : item["address2"].ToString();
                            row["city"]             = item["city"].ToString();
                            row["state"]            = item["state"].ToString();
                            row["zip"]              = item["zip"].ToString();
                            row["suffix"]           = item["suffix"].ToString();
                            row["primaryPhone"]     = item["primaryPhone"].ToString();
                            row["phoneType"]        = item["phoneType"].ToString();
                            row["language"]         = item["language"].ToString();
                            row["studentSignature"] = item["studentSignature"] == null ? "" : item["studentSignature"].ToString();
                            row["registeredDate"]   = item["registeredDate"].ToString();
                        }
                    }
                    // if the row is not a list item in sp list, add it
                    else
                    {
                        CompanyItems.TryGetValue(row["employer"].ToString(), out ListItem itemCo);

                        ListItem nitem = oList.AddItem(new ListItemCreationInformation());

                        nitem["employer"]         = itemCo["ID"];
                        nitem["Title"]            = row["personalEmail"].ToString();
                        nitem["RegistrationID"]   = row["id"].ToString();
                        nitem["lastName"]         = row["lastName"].ToString();
                        nitem["firstName"]        = row["firstName"].ToString();
                        nitem["MI"]               = row["MI"].ToString();
                        nitem["birthDate"]        = row["birthDate"].ToString();
                        nitem["gender"]           = row["gender"].ToString();
                        nitem["address1"]         = row["address1"].ToString();
                        nitem["address2"]         = row["address2"].ToString();
                        nitem["city"]             = row["city"].ToString();
                        nitem["state"]            = row["state"].ToString();
                        nitem["zip"]              = row["zip"].ToString();
                        nitem["suffix"]           = row["suffix"].ToString();
                        nitem["primaryPhone"]     = row["primaryPhone"].ToString();
                        nitem["phoneType"]        = row["phoneType"].ToString();
                        nitem["language"]         = row["language"].ToString();
                        nitem["studentSignature"] = row["studentSignature"].ToString();
                        nitem["registeredDate"]   = row["registeredDate"].ToString();
                        nitem["copiedfromdb"]     = DateTime.Now.AddHours(-5);

                        nitem.Update();
                        clientContext.Load(nitem);
                        clientContext.ExecuteQuery();
                    }

                    rowsProcessed++;
                }
                catch (Exception ex)
                {
                    strLogItem += "Error: " + ex.Message + "\r\n";
                }
            }

            strLogItem += "Registrations table rows processed: " + rowsProcessed + "\r\n";
        }
 // This method is intended to be in conjunction with the Items property of a DropDownList, CheckBoxList, etc...
 public static IEnumerable <ListItem> ToEnumerable(this ListItemCollection item) => item.Cast <ListItem>();
예제 #17
0
 public IEnumerable <TEntity> MapEntities(ListItemCollection items, Type type)
 {
     return(MapEntities(items.Cast <ListItem>(), type));
 }
        static void processCompany(ClientContext clientContext)
        {
            // get Company data from sql db into data table
            companyTableAdapter cda = new companyTableAdapter();
            companyDataTable    cdt = new companyDataTable();

            _ = cda.Fill(cdt);

            strLogItem += "Company table rows read: " + cdt.Rows.Count + "\r\n";
            int rowsProcessed = 0;

            // get list to sync
            List      oList = clientContext.Web.Lists.GetByTitle("Company");
            CamlQuery cq    = new CamlQuery();

            cq.ViewXml = "<View/>";

            // get list item collection
            ListItemCollection items = oList.GetItems(cq);

            clientContext.Load(items);
            clientContext.ExecuteQuery();

            // cast list item collection to dictionary for fast finding
            Dictionary <string, ListItem> CompanyItems = items.Cast <ListItem>().ToDictionary(i => (string)i["CompanyID"], i => i);

            // loop through db rows
            foreach (DataRow row in cdt.Rows)
            {
                try
                {
                    // check if the row is already a list item in sp list
                    if (CompanyItems.TryGetValue(row["Id"].ToString(), out ListItem item))
                    {
                        // if there are changes in sp list item then apply to row
                        if (
                            row["name"].ToString() != item["Title"].ToString() ||
                            row["contactEmail"].ToString() != item["contactEmail"].ToString() ||
                            row["contactName"].ToString() != item["contactName"].ToString()
                            )
                        {
                            row["name"]         = item["Title"].ToString();
                            row["contactEmail"] = item["contactEmail"].ToString();
                            row["contactName"]  = item["contactName"].ToString();
                        }
                    }
                    // if the row is not a list item in sp list, add it
                    else
                    {
                        ListItem nitem = oList.AddItem(new ListItemCreationInformation());

                        nitem["CompanyID"]    = row["Id"].ToString();
                        nitem["Title"]        = row["name"].ToString();
                        nitem["contactEmail"] = row["contactEmail"].ToString();
                        nitem["contactName"]  = row["contactName"].ToString();
                        nitem["copiedfromdb"] = DateTime.Now.AddHours(-5);

                        nitem.Update();
                        clientContext.Load(nitem);
                        clientContext.ExecuteQuery();
                    }

                    rowsProcessed++;
                }
                catch (Exception ex)
                {
                    strLogItem += "Error: " + ex.Message + "\r\n";
                }
            }

            strLogItem += "Company table rows processed: " + rowsProcessed + "\r\n";
        }