Conflict between Client object model and Item Updated Event Receiver in sharepoint 2010

Hello All,
As per my requirement I have a two custom list.
Agent Details
Port Name
Agent Details contains Agent code, Port Name,  email, address and phone of Agent. Its possible that one Agent Code is connected with multiple Port Name.
Basically what I am doing is I am getting port name connected with Agent code, using jquery and bind those values with check box(using javascript created dynamically) and bind all with Div tag.
Now when my custom edit form of Agent list open up it shows me different port name binding with checkbox group.
when user select the check box and click confirm button my clicent object model script will run and add this selected value into Port Name list. 
After confirm one more button named Save will enable asking user to edit the email, phone or address value and when I click on save my Item updated event fires which update the values of the selected port name(These port name I am getting from port
name list) to Agent Details custom list.
Now when I am trying to update the values my event receiver fires or some times it got stuck(not firing). So could you please help me the possible alternative for this requirements.
Can we user the Ecma Script(Client object model to preserve the value of selectec port) and Item updated event receiver on the same time?
Is anything am doing wrong then please guide me.

Hi,
As I understand, when you updated values in the agent details list the Item updated event receiver got stuck sometimes.
The item update event receiver will fire after the item has been saved, and the client object model script or the Ecma Script runs before the item is saved, so there is no conflict between the client object model script and item update event receiver.
You could find out the reason about the item update event receiver gets stuck by debugging the event receiver.
When you want to debug your event receivers, you have to attach to OWSTIMER.EXE and wait till they are executed. You can control this behavior using the Synchronization attribute. Also, if you’re looking for an easy way to debug an event receiver without
having to manually attach a debugger to your code, you can use the System.Diagnostics.Debugger.Launch() method.
The articles below are about how to debug in the event receiver in SharePoint 2010.
http://sharepoint-kings.blogspot.jp/2013/02/debugging-event-receivers-in-sharepoint.html
http://chakkaradeep.com/index.php/event-receivers-in-sharepoint-2010/
http://sharesaint.com/?p=77
Best regards,
Sara Fan
TechNet Community Support
Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
[email protected]

Similar Messages

  • Getting Error In Item Added Event In Event Receiver in SharePoint 2010

    Hi Guys,
    I have written Event Receiver in SharePoint 2010 On ItemAdded event of Document Library. Wants to increment a col value by reading maximum value first. I wrote below code but sometime it works correctly but some time I got below error: Document Set
    enabled on this document library and weh we added any document in any document set then this event occurred. I mentioned Code block and Error description both.
    Please see and suggest right solution.
    Code:
    public override void ItemAdded(SPItemEventProperties properties)
                    base.ItemAdded(properties);
                    SPListItem _currentItem = properties.ListItem;
                    string _QUERY = @"<Where><Eq><FieldRef Name='DocumentId'/><Value Type='Text'>21</Value></Eq></Where><OrderBy><FieldRef
    Name='RevisionReference' Ascending='False' /></OrderBy><ViewFields><FieldRef Name='RevisionReference' /></ViewFields><QueryOptions><Folder>DocumentLIBB/</Folder></QueryOptions>";
                    int maxID = 0;
                    string revisionreferencee = string.Empty;
                    using (SPWeb web = properties.OpenWeb())
                        SPList list = web.Lists["DocumentLIBB"];
                        SPQuery query = new SPQuery();
                        query.ViewAttributes = "Scope=\"Recursive\"";
                        query.Query = (_QUERY);
                        SPListItemCollection results = list.GetItems(query);
                     if (results.Count > 0)
                            SPListItem item = results[0];
                            revisionreferencee = item["RevisionReference"].ToString();
                            bool result = Int32.TryParse(revisionreferencee, out maxID);
                            _currentItem["RevisionReference"] = maxID + 1;
                            _currentItem["DocumentId"] = item["DocumentId"].ToString();
                    properties.ListItem.File.Update();
                    _currentItem.Update();
    Error Desc:
    <nativehr>0x81020015</nativehr><nativestack></nativestack>The file EKENg LIBB/QA_DOC_044/05-22 Emirates Engineering Occurrence_Error Investigation - MEDA Process - 27 AUG 2009-921.doc has been modified by SHAREPOINT\system
    on 27 Aug 2012 12:10:13 +0400.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
    Exception Details: System.Runtime.InteropServices.COMException: <nativehr>0x81020015</nativehr><nativestack></nativestack>The file EKENg LIBB/QA_DOC_044/05-22 Emirates Engineering Occurrence_Error Investigation - MEDA
    Process - 27 AUG 2009-921.doc has been modified by SHAREPOINT\system on 27 Aug 2012 12:10:13 +0400.
    Source Error:
    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. 

    Making the event synchronous (rather than the default) eliminates this error. If such a change suits your requirements you should consider it. You just have to tweak the elements.xml in your feature receiver project;
    http://blogs.msdn.com/b/unsharepoint/archive/2010/11/10/sharepoint-event-receivers-making-asynchronous-event-synchronous-to-avoid-save-conflict-error.aspx
    w: http://www.the-north.com/sharepoint | t: @JMcAllisterCH | c: http://www.b-i.com

  • 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

  • Client Object Model - Can't seem to get sites on 2010 but i can 2013

    Hi,
    So i'm trying to use the client model to get sites of a site collection and this is what I've got.
    Try
    ImportFSitesList.Clear()
    ImportFClientContext.Load(ImportFWeb, Function(website) website.Webs, Function(website) website.Title)
    ImportFClientContext.ExecuteQuery()
    For Each orWebsite As Web In ImportFWeb.Webs
    Dim newpath As String = ImportFSiteCollection + orWebsite.ServerRelativeUrl
    GetImportFSites(newpath)
    ImportFSitesList.Add(orWebsite.Title, orWebsite.ServerRelativeUrl)
    Next
    Catch ex As Exception
    Console.WriteLine(ex.Message)
    End Try
    it seems to work on 2013 but not with 2010, refs are all V16
    any help would be nice
    Ben

    > refs are all V16
    did you mean v15? SP2013 dlls have 15 version. Sharepoint uses assemblies binding redirects which allows to run code compiled against earlier version to run on higher version, but not in opposite direction. I.e. you may run the program which was compiled
    agains SP2010 for SP2013, but not vice versa.
    Check the following post: Assembly binding redirect in Sharepoint 2010: how old code for SP 2007 works in SP 2010.
    Blog - http://sadomovalex.blogspot.com
    Dynamic CAML queries via C# - http://camlex.codeplex.com

  • How to get specific folder and items in the document library sharepoint 2010

    I have a Shared library and it has Test folder and inside so many documents now i need to display the Test folder and items programmatically.
    Appreciate Help!!!!!
    Blitz

    This is how you could do it using the server object model -
    SPWeb site = SPContext.Current.Web;
    SPList list = site.Lists["listname"];
    SPQuery query = new SPQuery();
    SPFolder folder = list.RootFolder.SubFolders["FolderName"];
    query.Folder = folder;
    SPListItemCollection items = list.GetItems(query);
    foreach (SPListItem item in items)
    //do whatever you want here
    Please "Mark as Answer" if a post has answered your question or "Vote as Helpful" if it was helpful in some way. Here's
    why

  • Getting Error The trust relationship between the primary domain and the trusted domain failed in SharePoint 2010

    Hi,
    SharePoint 2010 Backup has been taken from production and restored through Semantic Tool in one of the server.The wepapplication of which the backup was taken is working fine.
    But the problem is that the SharePoint is not working correctly.We cannot create any new webapplication ,cannot navigate to the ServiceApplications.aspx page it shows error.Even the Search and UserProfile Services of the existing Web Application is not working.Checking
    the SharePoint Logs I found out the below exception
    11/30/2011 12:14:53.78  WebAnalyticsService.exe (0x06D4)         0x2D24 SharePoint Foundation          Database                     
     8u1d High     Flushing connection pool 'Data Source=urasvr139;Initial Catalog=SharePoint_Config;Integrated Security=True;Enlist=False;Connect Timeout=15' 
    11/30/2011 12:14:53.78  WebAnalyticsService.exe (0x06D4)         0x2D24 SharePoint Foundation          Topology                     
     2myf Medium   Enabling the configuration filesystem and memory caches. 
    11/30/2011 12:14:53.79  WebAnalyticsService.exe (0x06D4)         0x12AC SharePoint Foundation          Database                     
     8u1d High     Flushing connection pool 'Data Source=urasvr139;Initial Catalog=SharePoint_Config;Integrated Security=True;Enlist=False;Connect Timeout=15' 
    11/30/2011 12:14:53.79  WebAnalyticsService.exe (0x06D4)         0x12AC SharePoint Foundation          Topology                     
     2myf Medium   Enabling the configuration filesystem and memory caches. 
    11/30/2011 12:14:55.54  mssearch.exe (0x0864)                    0x2B24 SharePoint Server Search       Propagation Manager          
     fo2s Medium   [3b3-c-0 An] aborting all propagation tasks and propagation-owned transactions after waiting 300 seconds (0 indexes)  [indexpropagator.cxx:1607]  d:\office\source\search\native\ytrip\tripoli\propagation\indexpropagator.cxx 
    11/30/2011 12:14:55.99  OWSTIMER.EXE (0x1DF4)                    0x1994 SharePoint Foundation          Topology                     
     75dz High     The SPPersistedObject with
    Name User Profile Service Application, Id 9577a6aa-33ec-498e-b198-56651b53bf27, Parent 13e1ef7d-40c2-4bcb-906c-a080866ca9bd failed to initialize with the following error: System.SystemException: The trust relationship between the primary domain and the trusted
    domain failed.       at System.Security.Principal.SecurityIdentifier.TranslateToNTAccounts(IdentityReferenceCollection sourceSids, Boolean& someFailed)     at System.Security.Principal.SecurityIdentifier.Translate(IdentityReferenceCollection
    sourceSids, Type targetType, Boolean forceSuccess)     at System.Security.Principal.SecurityIdentifier.Translate(Type targetType)     at Microsoft.SharePoint.Administration.SPAce`1.get_PrincipalName()    
    at Microsoft.SharePoint.Administration.SPAcl`1.Add(String princip... 
    11/30/2011 12:14:55.99* OWSTIMER.EXE (0x1DF4)                    0x1994 SharePoint Foundation          Topology                     
     75dz High     ...alName, String displayName, Byte[] securityIdentifier, T grantRightsMask, T denyRightsMask)     at Microsoft.SharePoint.Administration.SPAcl`1..ctor(String persistedAcl)    
    at Microsoft.SharePoint.Administration.SPServiceApplication.OnDeserialization()     at Microsoft.SharePoint.Administration.SPIisWebServiceApplication.OnDeserialization()     at Microsoft.SharePoint.Administration.SPPersistedObject.Initialize(ISPPersistedStoreProvider
    persistedStoreProvider, Guid id, Guid parentId, String name, SPObjectStatus status, Int64 version, XmlDocument state) 
    11/30/2011 12:14:56.00  OWSTIMER.EXE (0x1DF4)                    0x1994 SharePoint Foundation          Topology                     
     8xqx High     Exception in RefreshCache. Exception message :The trust relationship between the primary domain and the trusted domain failed.   
    11/30/2011 12:14:56.00  OWSTIMER.EXE (0x1DF4)                    0x1994 SharePoint Foundation          Timer                        
     2n2p Monitorable The following error occured while trying to initialize the timer: System.SystemException: The trust relationship between the primary domain and the trusted domain failed.       at System.Security.Principal.SecurityIdentifier.TranslateToNTAccounts(IdentityReferenceCollection
    sourceSids, Boolean& someFailed)     at System.Security.Principal.SecurityIdentifier.Translate(IdentityReferenceCollection sourceSids, Type targetType, Boolean forceSuccess)     at System.Security.Principal.SecurityIdentifier.Translate(Type
    targetType)     at Microsoft.SharePoint.Administration.SPAce`1.get_PrincipalName()     at Microsoft.SharePoint.Administration.SPAcl`1.Add(String principalName, String displayName, Byte[] securityIdentifier, T grantRightsMask,
    T denyRightsMask)     at Microsoft.SharePoint.Administrati... 
    11/30/2011 12:14:56.00* OWSTIMER.EXE (0x1DF4)                    0x1994 SharePoint Foundation          Timer                        
     2n2p Monitorable ...on.SPAcl`1..ctor(String persistedAcl)     at Microsoft.SharePoint.Administration.SPServiceApplication.OnDeserialization()     at Microsoft.SharePoint.Administration.SPIisWebServiceApplication.OnDeserialization()    
    at Microsoft.SharePoint.Administration.SPPersistedObject.Initialize(ISPPersistedStoreProvider persistedStoreProvider, Guid id, Guid parentId, String name, SPObjectStatus status, Int64 version, XmlDocument state)     at Microsoft.SharePoint.Administration.SPConfigurationDatabase.GetObject(Guid
    id, Guid parentId, Guid type, String name, SPObjectStatus status, Byte[] versionBuffer, String xml)     at Microsoft.SharePoint.Administration.SPConfigurationDatabase.GetObject(SqlDataReader dr)     at Microsoft.SharePoint.Administration.SPConfigurationDatabase.RefreshCache(Int64
    currentVe...
    Please guide me on the above issue ,this will be of great help
    Thanks.

    I have same error. Verified for trust , ports , cleaned up cache.. nothing has helped. 
    The problem is caused by User profile Synch Service:
    UserProfileProperty_WCFLogging :: ProfilePropertyService.GetProfileProperties Exception: System.SystemException:
    The trust relationship between the primary domain and the trusted domain failed.       at System.Security.Principal.SecurityIdentifier.TranslateToNTAccounts(IdentityReferenceCollection sourceSids,
    Boolean& someFailed)     at System.Security.Principal.SecurityIdentifier.Translate(IdentityReferenceCollection sourceSids, Type targetType, Boolean forceSuccess)     at System.Security.Principal.SecurityIdentifier.Translate(Type
    targetType)     at Microsoft.SharePoint.Administration.SPAce`1.get_PrincipalName()     at Microsoft.SharePoint.Administration.SPAcl`1.Add(String principalName, String displayName, SPIdentifierType identifierType, Byte[]
    identifier, T grantRightsMask, T denyRigh...        
    08/23/2014 13:00:20.96*        w3wp.exe (0x2204)                      
            0x293C        SharePoint Portal Server              User Profiles                
            eh0u        Unexpected        ...tsMask)     at Microsoft.SharePoint.Administration.SPAcl`1..ctor(String persistedAcl)    
    at Microsoft.Office.Server.Administration.UserProfileApplication.get_SerializedAdministratorAcl()     at Microsoft.Office.Server.Administration.UserProfileApplication.GetProperties()     at Microsoft.Office.Server.UserProfiles.ProfilePropertyService.GetProfileProperties()
    Please let me know if you any solution found for this?
    Regards,
    Kunal  

  • 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

  • Client object model in SharePoint 2013

    Hi,
    I have installed .Net 2012 and want to create one client object model .But SharePoint is not installed in my system.So how i will get the SharePoint templates in the .net and how i  am able to do this.
    Please help
    Thank you

    Hi,
    Thanks for reply.
    But i am working in client machine and i have to create app using client object model and i have no access to the server.
    As per your answer, you want say i have to install SharePoint in my client system ?
    Then only i get the sharepoint templates in the .Net ?

  • Event firing at item added and item updated in event receiver?

    Hi All,
    I have created event receiver on item added & item updated on document library.
    1) On Item Added i am updating document library Title column with document Name and i have metadata for the file.
    2) On Item Updated i am move that file with metadata to another document library.
    Now the issue is the event is triggering is twice when an item is added it automatically calls the item updated event
    Need to help please...
    Thanks
    Balaji More

    Hi Thanks for reply.
    I have also write Workflow on Source doc library for document approval.
    In Source doc library i have choice column fields[Status]. Pending,Approved Default is Pending
    when approvers approve the task then i want to update Status: pending to Approved in source doc library using workflow it worked but that time i also want to update destination doc library Status column using Item updated Event receiver but not successed.
    Following is code on Item Added.
    try
    using (SPWeb oWeb = properties.OpenWeb())
    oWeb.AllowUnsafeUpdates = true;
    string UpdateStatus= string.Empty;
    UpdateStatus= properties.ListItem["Status"].ToString();
    SPFile File = properties.ListItem.File;
    SPDocumentLibrary destLib = (SPDocumentLibrary)properties.ListItem.Web.Lists["documents"];
    SPFolder mylibrary = oWeb.GetFolder("Temp");
    SPFile spfile = mylibrary.Files.Add(File, streamWriter, true);
    SPFile newfile = spfile;
    SPListItem item = file.Item;
    item["Status"] = UpdateStatus;
    item.Update();
    oWeb.AllowUnsafeUpdates = true;
    Catch()
    Item Updated when workflow is approved status is changed Pending to Approved
    then i have write a following code but status is not updated when workflow is completed
    try
    using (SPWeb oWeb = properties.OpenWeb())
    oWeb.AllowUnsafeUpdates = true;
    string UpdateStatus= string.Empty;
    SPFile File = properties.ListItem.File;
    if (properties.ListItem["Status"] != null)
    UpdateStatus = properties.ListItem["Status"].ToString();
    SPDocumentLibrary destLib = (SPDocumentLibrary)properties.ListItem.Web.Lists["documents"];
    SPFolder mylibrary = oWeb.GetFolder("Temp");
    SPFile spfile = mylibrary.Files.Add(File, streamWriter, true);
    SPFile newfile = spfile;
    SPListItem item = file.Item;
    item["Status"] = UpdateStatus;
    item.Update();
    oWeb.AllowUnsafeUpdates = true;
    Catch()
    Thanks
    Balaji More

  • Item added & item updated events fired twice.

    Hello everyone, 
    I have item added and item updated events and both sends e-mails twice cos they are fired twice. 
    I tried the below method but the problem still continues. Any suggessions?
    base.EventFiringEnabled=false;
    base.EventFiringEnabled=true;
    note: my list is custom list. (not document lib)

    If you have required checkout enabled the events can be triggered twice. See this post for more information and how to bypass it:
    Managing ItemUpdating and ItemUpdated Events Firing Twice in a SharePoint Item Event Receiver

  • How can I get an item and it's attachments from the current list using SP's JavaScript Client Object Model on newform.aspx?

    I only recently learned/read about SharePoint's JavaScript Client Object Model. I'm reading online trying to figure this out but not having much luck.
    On newform.aspx (and dispform.aspx) I want to get the
    current list,
    the last item created, and it's attachments. I now the CAML query I need to get the last item created, but first I have to get the current list and I am not sure how to do that.
    I tried this but it returns null:
    SP.ListOperation.Selection.getSelectedList()

    Hi,
    For your issue, you can get the list name from the new form url and retrieve the list last created item :
    https://social.msdn.microsoft.com/Forums/office/en-US/b90a64f8-2255-41b0-9d91-78335dd4a4cf/get-list-name-from-list-url-through-javascript?forum=sharepointdevelopmentprevious
    http://msdn.microsoft.com/en-us/library/office/hh185007(v=office.14).aspx
    Best Regards,
    Eric
    Eric Tao
    TechNet Community Support

  • 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.

  • 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

  • Add attachments to List Item using JavaScript Client object model in SP2010

    Hi All ,
    I have created custom form for submitng data in list using javascript client object model/jquery .
    Now I want to add option to uplaod multiple attachments to that list item also .
    Is there option with client object model for uplaoding attachment.
    Thanks
    M
    Manesh G

    Can you try this and let me know
    using (SPSite _site = new SPSite(SPContext.Current.Site.Url))
        using (SPWeb _web = _site.OpenWeb())
         //Let's suppose your Item Id is 1
         int ItemId = 1;
         SPList  oList = _web.Lists["EmployeeList"];
         SPListItem  _item = oList.GetItemById(ItemId);
         if (FileUpload1.HasFile)
               _web.AllowUnsafeUpdates = true;
              Stream fs = FileUpload1.PostedFile.InputStream;
              byte[] _bytes = new byte[fs.Length];
              fs.Position= 0;
              fs.Read(_bytes, 0, (int)fs.Length);
              fs.Close();
              fs.Dispose();
              _item.Attachments.Add(FileUpload1.PostedFile.FileName, _bytes);
              _item.Update();
              _web.AllowUnsafeUpdates = false;

  • Assign Group permission to list item using client object model

    Hi,
       I am trying to add the list item and assign the permission to the list item by using SP 2010 client object model. The problem which i am facing that when i assign the group as a permission to the item, by automatically the limited access permission
    is added to the group. Please find the steps which i have followed,
    Step-1: Break role inheritance.
     foreach (var item in _listItemCollection)
                            if (item["FileLeafRef"].ToString().ToLower() == "xxx")
                                item.BreakRoleInheritance(true, false);
                                _clientContext.Load(item.RoleAssignments);
                                _folderItem = item;
    _clientContext.ExecuteQuery();
    Step 2: Remove all permissions of the list item.
       foreach (var assignment in _folderItem.RoleAssignments)
                        assignment.RoleDefinitionBindings.RemoveAll();
                        assignment.Update();
    _clientContext.ExecuteQuery();
    Step 3:
        Add Group as a permission to the list item.
      var role = _web.RoleDefinitions.GetByType(RoleType.Contributor);
                    var collRdb = new RoleDefinitionBindingCollection(_clientContext) { role };
                    Principal principal = _grp;
                    _folderItem.RoleAssignments.Add(principal, collRdb);
                    _folderItem.Update();
    _clientContext.ExecuteQuery();
        After adding the group successfully to the list item, i checked the group permission and it contains the value as "Contribute,Limited Access" to the site level and "Contribute" to the list item. Please guide me how to avoid to create Contribute,Limited
    Access role.
    Balaji

    Hi Dmitry,
      When I create the group and assign contribute permission, the group has the permission at the site level(to see the permission, click group and click view Group Permission).  I have added the list item and break the role inheritance permission
    and given the unique permission by providing group as a permission to the list item. After providing the permission, the group permission at the site level changed to "Contribute, Limited Access". I dont know how contribute permission changed to contribute,
    limited access.
    I found the workaround to fix this issue. I created the group and create the folder in the shared document library by using client object model. Due to facing some issue by providing the permission using client object model, i have created the event receiver
    to the document library and using server object model, i can able to assign the approprate group permission.
    Balaji

Maybe you are looking for