Showing posts with label list items. Show all posts
Showing posts with label list items. Show all posts

Thursday, 10 October 2019

CSOM: How to copy all items from one SharePoint list to another?

using F = System.Windows.Forms;
using Microsoft.SharePoint.Client;
using PnP = OfficeDevPnP.Core;

PnP.AuthenticationManager authManagerTarget = new PnP.AuthenticationManager();
                using (ClientContext clientContextTarget = authManagerTarget.GetWebLoginClientContext(txtTargetSite.Text))
                {
                    List targetList = clientContextTarget.Web.Lists.GetByTitle(drpTargetList.SelectedItem.ToString());
                    clientContextTarget.Load(targetList);
                    clientContextTarget.ExecuteQuery();

                    PnP.AuthenticationManager authManagerSource = new PnP.AuthenticationManager();
                    using (ClientContext clientContextSource = authManagerSource.GetWebLoginClientContext(txtSourceSite.Text))
                    {
                        List sourceList = clientContextSource.Web.Lists.GetByTitle(drpSourceList.SelectedItem.ToString());
                        ListItemCollection sourceItems = sourceList.GetItems(CamlQuery.CreateAllItemsQuery());
                        clientContextSource.Load(sourceItems);
                        clientContextSource.ExecuteQuery();

                        progressBar1.Maximum = sourceItems.Count;

                        foreach (ListItem sourceItem in sourceItems)
                        {
                            ListItemCreationInformation newItem = new ListItemCreationInformation();
                            ListItem targetItem = targetList.AddItem(newItem);
                            FieldCollection sourceFields = sourceList.Fields;
                            clientContextSource.Load(sourceFields);
                            clientContextSource.ExecuteQuery();
                            foreach (Field field in sourceFields)
                            {
                                if (field.InternalName != "Attachments" && field.InternalName != "ContentType" &&
                                     !field.Hidden && !field.ReadOnlyField &&
                                     sourceItem[field.InternalName] != null &&
field.FieldTypeKind.ToString() != "URL" && field.FieldTypeKind.ToString() != "WorkflowStatus")
                                {
                                    try
                                    {
                                        targetItem[field.InternalName] = sourceItem[field.InternalName];
                                    }
                                    catch (Exception ex)
                                    {
                                        this.LogError(ex);
                                    }
                                }
                            }
                            targetItem.Update();
                            clientContextTarget.ExecuteQueryRetryAsync(10, 10000);
                            progressBar1.Value += 1;
                        }
                    }
                }

CSOM: How to delete all items in a SharePoint list?

using F = System.Windows.Forms;
using Microsoft.SharePoint.Client;
using PnP = OfficeDevPnP.Core;

try
            {
                PnP.AuthenticationManager authManager = new PnP.AuthenticationManager();
                using (ClientContext clientContext = authManager.GetWebLoginClientContext(txtSourceUrl.Text))
                {
                    List list = clientContext.Web.Lists.GetByTitle(drpLists.SelectedItem.ToString());
                    CamlQuery camlQuery = new CamlQuery();
                    camlQuery.ViewXml = "<View><Query><Where><Neq><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Neq></Where></Query></View>";
                    ListItemCollection allItems = list.GetItems(camlQuery);
                    clientContext.Load(allItems);
                    clientContext.ExecuteQuery();
                    int itemCount = allItems.Count;
                    F.MessageBox.Show("Deletion is started. Please monitor the count on SharePoint.");
                    if (itemCount > 0)
                    {
                        for (int i = itemCount - 1; i > -1; i--)
                        {
                            allItems[i].DeleteObject();
                            clientContext.ExecuteQuery();
                        }
                    }
                    F.MessageBox.Show("Items are deleted.");
                }
            }
            catch (Exception ex)
            {
                F.MessageBox.Show("Error: " + ex.Message);
            }
        }

Tuesday, 17 April 2018

[Solved] SPServices : GetListItems not returning all items from SharePoint list?


'GetListItems' will return items from default list view only.

To overcome this use the following filters:

var cmlQuery="<Query><Where><Neq><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Neq></Where></Query>";

CAMLQuery: cmlQuery,  //Include items which are filtered-out in default view
CAMLRowLimit: 0,  //Override default view row-limit

Thursday, 8 December 2016

SharePoint List Item: How to programmatically set value to a lookup column?


If you try to assign directly like below then you will get an error with message saying "Invalid data has been used to update the list item. The field you are trying to update may be read only".

newItem["Resource_x0020_ID"] = "john@company.com";

Below is the correct way to assign value to a lookup column:

SPListItem newItem = list.AddItem();

var empID = web.Lists["Resource Master"].GetItemById(Convert.ToInt32(101));

newItem["Resource_x0020_ID"] = new SPFieldLookupValue(empID.ID, empID.Title);

newItem.Update();




Friday, 2 September 2016

How to set unique permission for list items based on the users present in list columns for each item?


 static void Main(string[] args)
        {

            Console.Write("Enter list name:\r\n");
            string listTitle = Console.ReadLine();
            Console.Write("\r\nEnter column names separated by columns without space:\r\n");
            string listColumns = Console.ReadLine();
            SetItemPermissions(listTitle, listColumns);
       }


public static void SetItemPermissions(string listName, string fields)
        {
            try
            {
                int y = 0;
                ClientContext context = new ClientContext("https://domain.com/sites/siteColl/siteName/");
                string decryptedPwdt = "password";
                foreach (char c in decryptedPwdt)
                {
                    securePassword.AppendChar(c);
                }

                context.Credentials = new NetworkCredential("user", decryptedPwdt, "Domain");
                Web web = context.Web;
                context.Load(web);

                List list = web.Lists.GetByTitle(listName);
                context.Load(list);

                CamlQuery camlQuery = new CamlQuery();
                ListItemCollection itemColl = list.GetItems(camlQuery);
                string[] columnNames = fields.Split(',');

                foreach (string column in columnNames)
                {
                    context.Load(itemColl, includes => includes.Include(i => i[column]));
                }
                context.ExecuteQuery();

                foreach (ListItem item in itemColl)
                {
                    item.BreakRoleInheritance(false, false);

                    foreach (string member in columnNames)
                    {
                        try
                        {
                            if (item[member].GetType().ToString() == "Microsoft.SharePoint.Client.FieldUserValue")
                            {
                                try
                                {
                                    User user = web.EnsureUser((((Microsoft.SharePoint.Client.FieldUserValue)(item[member])).LookupValue).ToString());
                                    RoleDefinitionBindingCollection roleColl = new RoleDefinitionBindingCollection(context);
                                    roleColl.Add(context.Web.RoleDefinitions.GetByName("Custom permission level"));
                                    item.RoleAssignments.Add(user, roleColl);
                                }
                                catch
                                {
                                    User user = web.EnsureUser((((Microsoft.SharePoint.Client.FieldUserValue)(item[member])).Email).ToString());
                                    RoleDefinitionBindingCollection roleColl = new RoleDefinitionBindingCollection(context);
                                    roleColl.Add(context.Web.RoleDefinitions.GetByName("Custom permission level"));
                                    item.RoleAssignments.Add(user, roleColl);
                                }
                            }
                            else
                            {
                                User user = web.EnsureUser(item[member].ToString());
                                RoleDefinitionBindingCollection roleColl = new RoleDefinitionBindingCollection(context);
                                roleColl.Add(context.Web.RoleDefinitions.GetByName("Custom permission level"));
                                item.RoleAssignments.Add(user, roleColl);
                            }
                        }
                        catch { }
                    }

                    try
                    {

                        Group groupMember = web.SiteGroups.GetByName("Group1");
                        Group groupOwner = web.SiteGroups.GetByName("Group2");
                        Group groupTL = web.SiteGroups.GetByName("Group3");



                        RoleDefinitionBindingCollection roleCollEdit = new RoleDefinitionBindingCollection(context);
                        roleCollEdit.Add(context.Web.RoleDefinitions.GetByName("Edit"));

                        RoleDefinitionBindingCollection roleCollFull = new RoleDefinitionBindingCollection(context);

                        roleCollFull.Add(context.Web.RoleDefinitions.GetByName("Full Control"));
                        item.RoleAssignments.Add(groupMember, roleCollEdit);
                        item.RoleAssignments.Add(groupOwner, roleCollFull);
                        item.RoleAssignments.Add(groupTL, roleCollEdit);


                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }

                    try
                    {
                        item.Update();
                        context.ExecuteQuery();
                    }
                    catch (Exception ex)
                    {
                        if (ex.HResult == -2146233088)
                        {
                            Group groupMember = web.SiteGroups.GetByName("Group1");
                            Group groupOwner = web.SiteGroups.GetByName("Group2");
                            Group groupTL = web.SiteGroups.GetByName("Group3");



                            RoleDefinitionBindingCollection roleCollEdit = new RoleDefinitionBindingCollection(context);
                            roleCollEdit.Add(context.Web.RoleDefinitions.GetByName("Edit"));

                            RoleDefinitionBindingCollection roleCollFull = new RoleDefinitionBindingCollection(context);

                            roleCollFull.Add(context.Web.RoleDefinitions.GetByName("Full Control"));
                            item.RoleAssignments.Add(groupMember, roleCollEdit);
                            item.RoleAssignments.Add(groupOwner, roleCollFull);
                            item.RoleAssignments.Add(groupTL, roleCollEdit);
                            item.Update();
                            try
                            {
                                context.ExecuteQuery();
                            }
                            catch (Exception ex2)
                            {
                                Console.WriteLine(ex2.Message);
                            }
                        }
                    }

                    Console.Write(".");
                    y++;
                    if (y == 1) Console.WriteLine("\r\n1 item updated.");
                    if (y == 100) Console.WriteLine("\r\n100 items updated.");
                    if (y == 500) Console.WriteLine("\r\n500 items updated.");
                    if (y == 800) Console.WriteLine("\r\n800 items updated.");
                    if (y == 1000) Console.WriteLine("\r\n1000 items updated.");
                    if (y == 2000) Console.WriteLine("\r\n2000 items updated.");
                    if (y == 3000) Console.WriteLine("\r\n3000 items updated.");
                    if (y == 4000) Console.WriteLine("\r\n4000 items updated.");
                }
                Console.WriteLine("\r\nDone!");
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.Read();
            }

        }