How to change 'Modified By' column value when a new file is uploaded in SharePoint 2013 using Client Object Model?

I want to change 'Modified By' column value of a file that is being uploaded using Client Object Model in SharePoint 2013. The problem is that the version of the file is changing. Kindly help me. The code that I am using is:
using (System.IO.Stream fileStream = System.IO.File.OpenRead(m_strFilePath))
    Microsoft.SharePoint.Client.File.SaveBinaryDirect(m_clientContext, str_URLOfFile, fileStream, true);
    Microsoft.SharePoint.Client.File fileUploaded = m_List.RootFolder.Files.GetByUrl(str_URLOfFile);
    m_clientContext.Load(fileUploaded);
    m_clientContext.ExecuteQuery();
    User user1 = m_Web.EnsureUser("User1");
    User user2 = m_Web.EnsureUser("User2");
    ListItem item = fileUploaded.ListItemAllFields;
    fileUploaded.CheckOut();
    item["UserDefinedColumn"] = "UserDefinedValue1";
    item["Title"] = "UserDefinedValue2";
    item["Editor"] = user1;
    item["Author"] = user2;
    item.Update();
    fileUploaded.CheckIn(string.Empty, CheckinType.OverwriteCheckIn);
    m_clientContext.ExecuteQuery();

Hi talib2608,
Chris is correct for this issue, when calling update using ListItem.update method, it will increase item versions, using SystemUpdate and UpdateOverwriteVersion will update the list item overwrite version.
these two methods are not available in CSOM/REST, only server object model is available for this.
Thanks,
Qiao Wei
TechNet Community Support

Similar Messages

  • Setting the default value to taxonomy column in sharepoint 2010 using client object model

    I am creating a metadata column and I want to set its default value in sharepoint 2010 using client object model. Can anyone help me?
    My code for creating metadata column is as below:
                ClientContext clientContext = new ClientContext(siteUrl);
                Web site = clientContext.Web;
                List list = site.Lists.GetByTitle("LibraryName");
                FieldCollection collField = list.Fields;
                string fieldSchema = "<Field Type='TaxonomyFieldType' DisplayName='SoftwareColumn' Name='SoftwareColumn' />";
                collField.AddFieldAsXml(fieldSchema, true, AddFieldOptions.DefaultValue);
                //oneField.DefaultValue = "ASP.NET|4c984b91-b308-4884-b1f1-aee5d7ed58b2"; // wssId[0].ToString() + ";#" + term.Name + "|" + term.Id.ToString().ToLower();
                clientContext.Load(collField);           
                clientContext.ExecuteQuery();

    Hi,
    Please try the code like this:
    ClientContext clientContext = new ClientContext("http://yoursite/");
    List list = clientContext.Web.Lists.GetByTitle("List1_mmsfield");
    clientContext.Load(list);
    clientContext.ExecuteQuery();
    FieldCollection fields = list.Fields;
    clientContext.Load(fields);
    clientContext.ExecuteQuery();
    Field f = fields.GetByTitle("mms");
    clientContext.Load(f);
    clientContext.ExecuteQuery();
    Console.WriteLine(f.Title + "---" + f.DefaultValue);
    //2;#A2|a0a95267-b758-4e4d-8c39-067069fd2eef
    //1;#A1|641f5726-992c-41c8-9ddc-204a60b88584
    f.DefaultValue = "1;#A1|641f5726-992c-41c8-9ddc-204a60b88584";
    f.Update();
    clientContext.Load(f);
    clientContext.ExecuteQuery();
    Console.WriteLine(f.Title + "---" + f.DefaultValue);
    Best regards
    Patrick Liang
    TechNet Community Support

  • How to Enable Ratings on SharePoint List using Client Object Model for Office 365 SharePoint Site.

    How to Enable Ratings on SharePoint List using Client Object Model code for Office 365 SharePoint Site.
    Thanks in Advance
    Rajendra K

    Hi Rajendra,
    here you are the code and the blog, let me know if this helps
    using (ClientContext ctx = new ClientContext(https://yourSiteUrl))
    Web w = ctx.Web;
    List l = w.Lists.GetByTitle("yourListName");
    ctx.Load(l, info => info.Id);
    ctx.ExecuteQuery();
    string ListID = l.Id.ToString();
    Microsoft.Office.Server.ReputationModel.Reputation.SetRating(ctx, ListID, 1, 5);
    ctx.ExecuteQuery();
    http://blogs.technet.com/b/speschka/archive/2013/07/08/how-to-use-csom-with-ratings-in-sharepoint-2013.aspx
    Kind Regards, John Naguib Technical Consultant/Architect MCITP, MCPD, MCTS, MCT, TOGAF 9 Foundation

  • How to activate Custom Feature in SharePoint 2010 using Client Object model

    I am trying to Activate a custom feature using Client Object Model in SharePoint 2010. Here is the code I used. When I execute the code, I got the error "Feature with Id 'xx' is not installed in this farm, and cannot be added to this scope while
    creating site collection". Can anyone help?
    ClientContext clientContext = new ClientContext(spURL);
    //GUID of the custom feature                    
    Guid districtFeatureId = new Guid("5b3529de-5045-46da-af87-8d2e32c121a7");
    Site clientSite = clientContext.Site;
    FeatureCollection clientSiteFeatures = clientSite.Features;
    clientContext.Load(clientSiteFeatures);
    clientContext.ExecuteQuery();
    //Activate the feature
    clientSiteFeatures.Add(districtFeatureId, false, FeatureDefinitionScope.Site);
    clientContext.ExecuteQuery();

    Hi shil chan,
    When you activate a feature on the site collection, the feature should be scoped to site or farm, the error message shows it cannot find the specific feature, this will happen when you have a feature in web
    scope or the feature isn’t installed.  
    So, to troubleshooting this issue:
    Verify whether the feature is scoped to web. Please go to
    Site Setting->Site Features . If the feature is a web scope feature, then add the feature to webfeatures.
    Make sure the feature is installed correctly.
    Please inform me freely if you have any questions.
    Thanks

  • How to get list of users who all are having full access in sharepoint site using client object model c#

    Hi,
    I want to fetch the list of users who all are having full access to the sharepoint list using client object model with .Net
    Please let me know if any property for the user object or any other way to get it.
    Thanks in advance.

    Here you are complete code i created from some years it lists all groups and users, you can just add a check in the permissions loop to see if it is equal to Full Control.
    Private void GetData(object obj)
    MyArgs args = obj as MyArgs;
    try
    if (args == null)
    return; // called without parameters or invalid type
    using (ClientContext clientContext = new ClientContext(args.URL))
    // clientContext.AuthenticationMode = ClientAuthenticationMode.;
    NetworkCredential credentials = new NetworkCredential(args.UserName, args.Password, args.Domain);
    clientContext.Credentials = credentials;
    RoleAssignmentCollection roles = clientContext.Web.RoleAssignments;
    ListViewItem lvi;
    ListViewItem.ListViewSubItem lvsi;
    ListViewItem lvigroup;
    ListViewItem.ListViewSubItem lvsigroup;
    clientContext.Load(roles);
    clientContext.ExecuteQuery();
    foreach (RoleAssignment orole in roles)
    clientContext.Load(orole.Member);
    clientContext.ExecuteQuery();
    //name
    //MessageBox.Show(orole.Member.LoginName);
    lvi = new ListViewItem();
    lvi.Text = orole.Member.LoginName;
    lvsi = new ListViewItem.ListViewSubItem();
    lvsi.Text = orole.Member.PrincipalType.ToString();
    lvi.SubItems.Add(lvsi);
    //get the type group or user
    // MessageBox.Show(orole.Member.PrincipalType.ToString());
    if (orole.Member.PrincipalType.ToString() == "SharePointGroup")
    lvigroup = new ListViewItem();
    lvigroup.Text = orole.Member.LoginName;
    // args.GroupsList.Items.Add(lvigroup);
    DoUpdate1(lvigroup);
    Group group = clientContext.Web.SiteGroups.GetById(orole.Member.Id);
    UserCollection collUser = group.Users;
    clientContext.Load(collUser);
    clientContext.ExecuteQuery();
    foreach (User oUser in collUser)
    lvigroup = new ListViewItem();
    lvigroup.Text = "";
    lvsigroup = new ListViewItem.ListViewSubItem();
    lvsigroup.Text = oUser.LoginName;
    lvigroup.SubItems.Add(lvsigroup);
    //args.GroupsList.Items.Add(lvigroup);
    DoUpdate1(lvigroup);
    // MessageBox.Show(oUser.LoginName);
    RoleDefinitionBindingCollection roleDefsbindings = null;
    roleDefsbindings = orole.RoleDefinitionBindings;
    clientContext.Load(roleDefsbindings);
    clientContext.ExecuteQuery();
    //permission level
    lvsi = new ListViewItem.ListViewSubItem();
    string permissionsstr = string.Empty;
    for (int i = 0; i < roleDefsbindings.Count; i++)
    if (i == roleDefsbindings.Count - 1)
    permissionsstr = permissionsstr += roleDefsbindings[i].Name;
    else
    permissionsstr = permissionsstr += roleDefsbindings[i].Name + ", ";
    lvsi.Text = permissionsstr;
    lvi.SubItems.Add(lvsi);
    // args.PermissionsList.Items.Add(lvi);
    DoUpdate2(lvi);
    catch (Exception ex)
    MessageBox.Show(ex.Message);
    finally
    DoUpdate3();
    Kind Regards, John Naguib Technical Consultant/Architect MCITP, MCPD, MCTS, MCT, TOGAF 9 Foundation

  • How to connect sharepoint online using client object model and authentictae against window login

    Iam developing A console application where in need to connect to sharepoint online and authenticate against window login can u please suggest me the code

    Hi,
    There is couple of helper method to check and validate the SPO credentials in the same solution.
    string userName = GetUserName();
    SecureString pwd = GetPassword();
    /* End Program if no Credentials */
    if (string.IsNullOrEmpty(userName) || (pwd == null))
    return;
    // Open connection to Office365 tenant
    ClientContext cc = new ClientContext(siteUrl);
    cc.AuthenticationMode = ClientAuthenticationMode.Default;
    cc.Credentials = new SharePointOnlineCredentials(userName, pwd);
    if you give incorrect user name or password it will throws an exception in the console.
    Murugesa Pandian.,SharePoint 2010 MCPD | MCTS|Configure

  • How to update list item using client object model without changing created/modified dates?

    Hello All,
    I want to update list item using the SharePoint Client Object
    Model without updating the created / modified date. Is it possible?
    Please help.
    Thanks.

    Using the SystemUpdate method should do the trick, according
    to its literature.
    Additionally, would something like this be of any use for you?  Taken from this
    Stack Exchange thread: -
    public static class SPListItemExtensions
    /// <summary>
    /// Provides ability to update list item without firing event receiver.
    /// </summary>
    /// <param name="item"></param>
    /// <param name="doNotFireEvents">Disables firing event receiver while updating item.</param>
    public static void Update(this SPListItem item, bool doNotFireEvents)
    SPItemEventReceiverHandling rh = new SPItemEventReceiverHandling();
    if (doNotFireEvents)
    try
    rh.DisableEventFiring();
    item.Update();
    finally
    rh.EnableEventFiring();
    else
    item.Update();
    /// <summary>
    /// Provides ability to update list item without firing event receiver.
    /// </summary>
    /// <param name="item"></param>
    /// <param name="incrementListItemVersion"></param>
    /// <param name="doNotFireEvents">Disables firing event receiver while updating item.</param>
    public static void SystemUpdate(this SPListItem item, bool incrementListItemVersion, bool doNotFireEvents)
    SPItemEventReceiverHandling rh = new SPItemEventReceiverHandling();
    if (doNotFireEvents)
    try
    rh.DisableEventFiring();
    item.SystemUpdate(incrementListItemVersion);
    finally
    rh.EnableEventFiring();
    else
    item.SystemUpdate(incrementListItemVersion);
    /// <summary>
    /// Provides ability to update list item without firing event receiver.
    /// </summary>
    /// <param name="item"></param>
    /// <param name="doNotFireEvents">Disables firing event receiver while updating item.</param>
    public static void SystemUpdate(this SPListItem item, bool doNotFireEvents)
    SPItemEventReceiverHandling rh = new SPItemEventReceiverHandling();
    if (doNotFireEvents)
    try
    rh.DisableEventFiring();
    item.SystemUpdate();
    finally
    rh.EnableEventFiring();
    else
    item.SystemUpdate();
    private class SPItemEventReceiverHandling : SPItemEventReceiver
    public SPItemEventReceiverHandling() { }
    new public void DisableEventFiring()
    base.DisableEventFiring();
    new public void EnableEventFiring()
    base.EnableEventFiring();
    Steven Andrews
    SharePoint Business Analyst: LiveNation Entertainment
    Blog: baron72.wordpress.com
    Twitter: Follow @backpackerd00d
    My Wiki Articles:
    CodePlex Corner Series
    Please remember to mark your question as "answered" if this solves (or helps) your problem.

  • Assigning External content type field column value using Client Object Model

    I have a problem assinging External column value to ListItem object with client object model-based application I'm developing. To be precise, I am able to retrieve data related to external content type by reading external list created from this content type
    but I don't know how to properly use it to assign value to this field. By doing some research on my own I concluded that BDC ID column from external list is the way to go since it uniquely defines selected row from external list but that doesn't
    tell me much since I don't know what to do with it. Currently I ended up with partial solution - to assign plain string value of picker column but that makes this value visible only in "View Properties" option on Sharepoint and not in "Edit Properties"
    which pritty much makes sence since it isn't properly related to rest of the data in specific row. Does someone have a better solution for this?
    Igor S.

    I think I understand your problem.
    In my example I have an external data column "Beneficiary Name", using a Beneficiary external content type (accessing a table of beneficiaries in a SQL table).
    I want to set the "Beneficiary Name" property using the client object model. I know the name of the beneficiary but not the ID value.
    It is a fairly simple solution. You just need to identify the name of the property SharePoint assigns to the ID field, in my case it is called "Beneficiary_ID". Then set the two properties as follows:
    thisItem["Beneficiary_Name"] = "Charitable Trust";
    thisItem["Beneficiary_ID"] = -1;
    thisItem.Update();
    Setting the ID property to -1 causes the server to do an automatic lookup for the ID from the value assigned to the item.

  • What is the easy way to update Managed Metadata field multi select values using client object model C#?

    The below mentioned code works sometimes and doesn't most of the time. What is the real best way to update multi select managed metadata fields?
    Microsoft.SharePoint.Client.File file = site.GetFileByServerRelativeUrl("/sites/myspsite/Documents/Presentation2.pptx");
    clientContext.Load(file);
    clientContext.ExecuteQuery();
    ListItem currentItem = file.ListItemAllFields;
    clientContext.Load(currentItem);
    clientContext.ExecuteQuery();
    currentItem["Country"] = "-1;#India|1d13cfe9-d6f4-4bd3-a6c7-4b46a81f2a96;#-1;#China|9c1dff73-82db-44b1-8d70-f4258dd24e47;#-1;#USA|b9295c0b-67d4-4dc5-99d4-e88af888de48";
    currentItem["Title"] = "Demo Doc";
    currentItem.Update();
    clientContext.ExecuteQuery();
    file.CheckIn("test check-in", CheckinType.MajorCheckIn);
    clientContext.ExecuteQuery();
    Anuradha!!

    Hi,
    Here are two blog for your reference:
    How to Work with Managed Metadata Columns by Using the SharePoint Client Object Model
    http://blogs.msdn.com/b/sharepointdev/archive/2011/11/18/how-to-work-with-managed-metadata-columns-by-using-the-sharepoint-client-object-model-kaushalendra-kumar.aspx
    SharePoint 2010 Code Tips – Setting a Managed Metadata Field with the Client Object Model
    http://sharepointfieldnotes.blogspot.com/2011/08/sharepoint-2010-code-tips-setting.html
    Best Regards
    Dennis Guo
    TechNet Community Support

  • Is it possible to change the title of a webpart using client object model/c#/sharepoint online

    Hi folks!
    I have been busted my butt trying to Write a program changing the title of an existing webpart on on of our subsites on SharePoint online. But I keep getting an error in the very last context.executequery. Tried a bunch of different approaches, but I can't
    make it work. Before I start posting code; I Wonder if anyone have ever done this?
    Its a plain Windows form application, using Visual studio Express and the Client Object model. (Listsing the titles of the webparts Works but changing titles seem impossible. Thought it might be a checkin/out problem but it doesn't make a difference).
    Any help would be highle appreciated.
    Lars

    It depends: are you using the default style for Text Captions? In that case you can change the default style in the Object Style Manager and have it applied to all Captions.
    Or you can change one text caption, and in its Properties panel choose the option 'Save Changes to existing style' from the menu top right (see screenshot). Both methods will work if you didn't override the default Caption Style for those captions. Beware: Quizzing objects can use another style.

  • How to use impersonation in project server 2013 using csom object model

    Hi sir ,
    I have try to see only my projects.Means with project server permission with help of impersonation .
    vijay

    In addition to Lars' good advice, please find this
    blog from Paul about risks and issues reporting with OData.
    Hope this helps,
    Guillaume Rouyre, MBA, MCP, MCTS |

  • Error occur when importing web part using Client Object Model API

                    i try to update webpart properties using Client API for some view and form pages. and the following error occured:
    view: /sites/metadata des02/frank metadata library/Forms/Thumbnails.aspx
    ERROR 03-06 05:36:47,720 Microsoft.SharePoint.Client.ServerException: The specified program requires a newer version of Windows. (Exception from HRESULT: 0x8007047E)
       at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream responseStream)
       at Microsoft.SharePoint.Client.ClientRequest.ProcessResponse()
       at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb)
       at Microsoft.SharePoint.Client.ClientRequest.ExecuteQuery()
       at Microsoft.SharePoint.Client.ClientRuntimeContext.ExecuteQuery()
       at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
    /sites/metadata des02/frank metadata library/Forms/Combine.aspx, ERROR 03-06 05:36:53,235  Microsoft.SharePoint.Client.ServerException: The specified program requires a newer version of Windows. (Exception from HRESULT: 0x8007047E)
       at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream responseStream)
       at Microsoft.SharePoint.Client.ClientRequest.ProcessResponse()
       at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb)
       at Microsoft.SharePoint.Client.ClientRequest.ExecuteQuery()
       at Microsoft.SharePoint.Client.ClientRuntimeContext.ExecuteQuery()
       at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
    /sites/metadata des02/frank metadata library/Forms/Upload.aspx,
    ERROR 03-06 05:36:55,204 Microsoft.SharePoint.Client.ServerException: Exception has been thrown by the target of an invocation.
       at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream responseStream)
       at Microsoft.SharePoint.Client.ClientRequest.ProcessResponse()
       at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb)
       at Microsoft.SharePoint.Client.ClientRequest.ExecuteQuery()
       at Microsoft.SharePoint.Client.ClientRuntimeContext.ExecuteQuery()
       at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
    /sites/metadata des02/frank metadata library/Forms\EditForm.aspx ERROR 03-06 05:36:56,470 Microsoft.SharePoint.Client.ServerException: Exception from HRESULT: 0x80131904
       at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream responseStream)
       at Microsoft.SharePoint.Client.ClientRequest.ProcessResponse()
       at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb)
       at Microsoft.SharePoint.Client.ClientRequest.ExecuteQuery()
       at Microsoft.SharePoint.Client.ClientRuntimeContext.ExecuteQuery()
       at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()

    Hi Ramakrishnaraja,
    here is the code snippet:
    using (ClientContext context = new ClientContext("https://frankkk.sharepoint.com/sites/metadata des02"))
                        context.Credentials = spoc as SharePointOnlineCredentials;
                        File webPartPage = context.Web.GetFileByServerRelativeUrl("/sites/metadata des02/frank metadata library/Forms/EditForm.aspx");
                        List list = context.Web.Lists.GetByTitle("frank metadata library");
                        LimitedWebPartManager limitedWebPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
                        context.Load(webPartPage);
                        context.Load(limitedWebPartManager);
                        context.Load(limitedWebPartManager, manager => manager.WebParts);
                        if (list != null)
                            context.Load(list, l => l.Views.IncludeWithDefaultProperties(v => v.ViewFields.SchemaXml));
                        context.ExecuteQuery();                    

  • Issue in adding new items to a O365 SharePoint Online List having lookup columns (Client Object Model)

    I have two Lists i.e. Publisher and Products in my SharePoint Online site. They are having the following structures:
    1. Publisher:
    Publisher (Single line of txt)
         A1
         A2
         A3
         A4
         A5
         A6
    2. Products:
    Publisher (lookup to the above column)       
    ProductName (Single line of txt)
         A1                                                                   Apple
         A2                                                                   Samsung
         A3                                                                   Nokia
    And I have an excel file named Products.xlsx in my local machine which has the following data:
    Publisher        ProductName
         A1                   Apple
         A2                   Samsung
         A3                   Nokia
         A4                   Motorola
         A5                   LG
         A6                   HTC
    Now I have written the below client-side (CSOM) code to fetch the data from the Excel and update the corresponding fields in the Products table:
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Web;
    using System.IO;
    using System.Data;
    using System.Data.OleDb;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Text;
    using System.Xml.Linq;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Client;
    using File =
    Microsoft.SharePoint.Client.File;
    using System.Security;
    namespace ExcelToSP
        public class
    ExcelToSP
            //Main function to get the command line values and invoke the getSPList function to pull SP List data
            public
    static void Main(string[] args)
                //Instantiate Class object
                ExcelToSP p
    = new ExcelToSP();
                try
                    p.LoadExcelData();
    //Exit with Sucess code
    Environment.Exit(0);
                catch
    (Exception ex)
    //Invoke writeErrorLog function to log the exception details
    //p.WriteErrorLog(ex);
            public
    void LoadExcelData()
                try
                string fileName
    = @"E:\Products.xlsx";
                string fileExtension
    = Path.GetExtension(fileName).ToUpper();
                string connectionString
    = "";
                 if
    (fileExtension == ".XLS")
                    connectionString
    = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='"
    + fileName + "'; Extended Properties='Excel 8.0;HDR=YES;'";
                else
    if (fileExtension ==
    ".XLSX")
                    connectionString
    = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='"
    + fileName + "';Extended Properties='Excel 12.0 Xml;HDR=YES;'";
                if
    (!(string.IsNullOrEmpty(connectionString)))
    string[] sheetNames =
    GetExcelSheetNames(connectionString);
    if ((sheetNames !=
    null) &&
    (sheetNames.Length
    > 0))
    DataTable dt = null;
    OleDbConnection con =
    new OleDbConnection(connectionString);
    OleDbDataAdapter da =
    new OleDbDataAdapter("SELECT * FROM ["
    + sheetNames[0]
    + "]", con);
                        dt
    = new DataTable();
                        da.Fill(dt);
    InsertIntoList(dt,"Products");
                catch
    (Exception ex)
    throw ex;
            private
    string[] GetExcelSheetNames(string strConnection)
                var connectionString
    = strConnection;
                String[] excelSheets;
                using
    (var connection =
    new OleDbConnection(connectionString))
                    connection.Open();
    var dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
    null);
    if (dt ==
    null)
    return null;
                    excelSheets
    = new String[dt.Rows.Count];
    int i = 0;
    // Add the sheet name to the string array.
    foreach (DataRow row
    in dt.Rows)
                        excelSheets[i]
    = row["TABLE_NAME"].ToString();
                        i++;
                return excelSheets;
            private
    void InsertIntoList(DataTable listTable,
    string ListName)
                try
    string username = "[email protected]";
    string pwd = "contoso@1234";//this.Dts.Variables["password"].Value.ToString();
    ClientContext clientContext =
    new ClientContext("https://contoso.sharepoint.com/teams/myPOC/");
    SecureString password =
    new SecureString();
    char[] decryptpwd = pwd.ToCharArray();
    foreach (char c
    in decryptpwd)
                        password.AppendChar(c);
                    clientContext.Credentials
    = new SharePointOnlineCredentials(username, password);
                    clientContext.ExecuteQuery();
    //Setting SiteURL Client context
    Web web = clientContext.Web;//
                    clientContext.Load(web);
                    clientContext.ExecuteQuery();
    List lstProductFamily = web.Lists.GetByTitle("Products");
    for (int iRow
    = 0; iRow < listTable.Rows.Count; iRow++)
    ListItemCreationInformation itemCreateInfo =
    new ListItemCreationInformation();
    ListItem newItem = lstProductFamily.AddItem(itemCreateInfo);
    //FieldLookupValue flv = newItem["Publisher"] as FieldLookupValue ;
    //string lkup = flv.LookupValue;
    //int valueid = 0;
    //valueid = flv.LookupId;
                        newItem["Publisher"]
    = Convert.ToString(listTable.Rows[iRow][0]);
                        newItem["ProductName"]
    = Convert.ToString(listTable.Rows[iRow][1]);
                        newItem.Update();
                        clientContext.ExecuteQuery();
                catch
    (Exception ex)
    throw ex;
    But I'm getting the following error on running the above code "Invalid data has been used to update the list item. The field you are trying to update may be read only." 
    Can anybody please help me out?

    Hi,
    According to your description, my understanding is that you want to update data to look up field.
    I have a test about updating look up field using Client Object Model in my environment. lookup field will accept an array to set the field value.
    Here is the code snippet:
    Microsoft.SharePoint.Client.ClientContext ctx = new ClientContext("http://sp2013sps/sites/test/");
    if (ctx != null)
    List list = ctx.Web.Lists.GetByTitle("List3");
    ListItem itemToUpdate = list.GetItemById(1);
    ctx.Load(itemToUpdate);
    ctx.ExecuteQuery();
    FieldLookupValue newLookUpField = new FieldLookupValue();
    newLookUpField.LookupId = 3;
    FieldLookupValue newLookUpField1 = new FieldLookupValue();
    newLookUpField1.LookupId = 4;
    FieldLookupValue[] newarr = { newLookUpField, newLookUpField1 };
    itemToUpdate["lookup"] = newarr;
    itemToUpdate.Update();
    ctx.Load(itemToUpdate);
    ctx.ExecuteQuery();
    Best regards
    Patrick Liang
    TechNet Community Support

  • How to impersonate in client Object model?

    Hii,
    I am using client Object Model Programming in WCF service which is hosted on IIS. I have created separate APP pool in IIS which has windows authentication enabled. This App pool account will be dealing with the sharepoint server. Now I am stuck at one point.when
    I upload a file, I want to set the actual logged in user as the author or editor of the file not the app pool account. Means I want to impersonate. How can I do this?
    I have visited this link
    http://stackoverflow.com/questions/949340/getting-networkcredential-for-current-user-c but didnt work out as expected. Can any one provide some input please?
    Thanks and Regards,
    PraTech

    Hi I have tried both the options.
    The first option works fine.It impersonates all the user calls. But I wan to use serviceaccount and useraccount at times. Coule you please look in the below code and let me know why it is failing?
    teh problem is described below.
    I have an IIS app pool account to interact with the sharepoint server. but there are cases when I need to use the logged in users credentials instead of appPool account when doing some operations like uploading a document. So I decided to impersonate. I
    added the below code in the web.config file so that all  server calls are impersonated.
    <serviceBehaviors>
    <behavior name="ImpersonatedBehavior">
    <serviceMetadata httpGetEnabled="true" />
    <serviceDebug includeExceptionDetailInFaults="false" />
    <serviceAuthorization impersonateCallerForAllOperations="true"
    </behavior >
    </serviceBehaviors>
    and then i have a file uplaod method as given below
    public string UploadFile(objDocument)
    using (ClientContext clientContext = new ClientContext(objDocument.workspaceUrl))
    Site site = clientContext.Site;
    clientContext.Load(site, s => s.Url); //need url for some reasons
    clientContext.ExecuteQuery(); //Exception :UnAuthorized
    File.SaveBinaryDirect(clientContext, urlpart+ "/" + FileName, stream, true);
    clientContext.ExecuteQuery();
    the very first call to ExecuteQuery was throwing exception "UnAuthorized".actually  the user has full control on the particluar workspace.then I add the below piece of code ( just before the clientContext object initilaiztion )so that clientcontext
    object is created using the serviceAccount(appPool Account). then it was working fine. but failing at File.SaveBinaryDirect() method call.
    WindowsImpersonationContext ctx = null;
    if (!WindowsIdentity.GetCurrent().IsSystem)
          ctx = WindowsIdentity.Impersonate(System.IntPtr.Zero);
    using (ClientContext clientContext = new ClientContext(objDocument.workspaceUrl))
      Site site = clientContext.Site;
      clientContext.Load(site, s => s.Url); //need url for some reasons
      clientContext.ExecuteQuery();  //Working Fine now.
    if (ctx != null)
    ctx.Undo();// co'z while uploading the file we dont need appPool account.but need users account.
    File.SaveBinaryDirect(clientContext, urlpart+ "/" + FileName,  stream, true);
    clientContext.ExecuteQuery();//Exception
    finally
                        if (ctx != null)
                            ctx.Undo();
    Now it is throwing exception at the File.SaveBinaryDirect() saying "401:Unauthorized".

  • How to register a new docicon/progid using CSOM/SharePoint Client object model

    I know how to register a new file-type icon in SharePoint 2013 by modifying docicon.xml,
    but is it possible via any sort of web-based API? Specifically I'm trying to do it for a SharePoint Online/office 365 site.

    Hi Dylan,
    For SharePoint Online, the docicon.xml is stored in the SharePoint online Server and there is no such Web API could modify the xml file directly, so there is no easy way to achieve it.
    As a workaround, you can add some JavaScript and Jquery in the master page to modify the file type icon to the new one.
    <script>
    var IMGs = document.getElementsByTagName("IMG")
    for (var i=0; i<IMGs.length; i++)
    var alt=IMGs[i].alt;
    if (alt.substring(alt.length-4,alt.length)==".pdf")
    IMGs[i].src="/yourlibrary/yourimage.gif";
    </script>
    Here is a similar thread for your reference:
    https://social.technet.microsoft.com/forums/msonline/en-US/bf5ff648-eefb-4084-8204-9519efaf50e7/modifying-dociconxml-on-sharepoint-online
    Best Regards
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Zhengyu Guo
    TechNet Community Support

Maybe you are looking for