none
Event receiver itemupdating only fires once

    Question

  • I am working with code developed by a consultant who I no longer have access to.

    Here's what's going on. I have a list that when a new item is added the event receiver creates a folder in a document library with 6 word documents in it. Each document has all the list item columns associated with it. The documents are populated with the columns from the list item. This worsk fine.

    When the list item is updated the changes are made in the documents, i.e., list item columns are changed or blank columns have data added to them.

    This work but only once. When the same item is updated a second time the changes are not carried to the document columns and because of that the documents aren't updated.

    Any idea why it would only fire on 1 change? I'm at a loss.

    The event receiver is using the itemupdating event:

    public override void ItemUpdating(SPItemEventProperties properties)
            {
                SPUserToken sysToken = null;
                string OLARuleDocuments = "";
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    using (SPSite current = properties.OpenSite())
                    {

                        sysToken = current.SystemAccount.UserToken;

                    }

                });

                string currUserDispName = properties.UserDisplayName;


                using (SPSite site = new SPSite(properties.SiteId, sysToken))
                {
                    SPContentType AdpotBriefingctype, AdpotLaunchctype, ProposalBriefingctype, ProposalLaunchctype, SubstantialChangeBriefingctype, SubstantialChangeLaunchctype;

                    OLARuleDocuments = GetAppSetting(site, "OLARuleDocuments");
                    if (OLARuleDocuments == "")
                        OLARuleDocuments = "OLARuleDocuments";
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists[OLARuleDocuments];
                        AdpotBriefingctype = web.ContentTypes["AdoptionBriefingMemorandum"];
                        AdpotLaunchctype = web.ContentTypes["AdoptionLaunchMemorandum"];
                        ProposalBriefingctype = web.ContentTypes["ProposalBriefingMemorandum"];
                        ProposalLaunchctype = web.ContentTypes["ProposalLaunchMemorandum"];
                        SubstantialChangeBriefingctype = web.ContentTypes["SubstantialChangeBriefingMemorandum"];
                        SubstantialChangeLaunchctype = web.ContentTypes["SubstantialChangeLaunchMemorandum"];

                        //ProposalBriefingMemorandum
                        //ProposalLaunchMemorandum
                        //SubstantialChangeLaunchMemorandum
                        //SubstantialChangeBriefingMemorandum

                        UpdateFolderName(list, properties);
                        //Hashtable AdpotBriefproperties = GetAdoptBriefHashTableProperites(properties, AdpotBriefingctype);
                        string filename = properties.ListItem["Title"].ToString();
                        bool ruledoc = UpdateDocuments(filename, OLARuleDocuments, properties);

     


                    }
                }

                //using (SPSite site = new SPSite(properties.SiteId, sysToken))
                //{
                //    using (SPWeb web = site.OpenWeb())
                //    {
                //        SPList list = web.Lists[OLARuleDocuments];

                //        UpdateFolderName(list, properties);


                //    }
                //}

                //using (SPSite uSite = new SPSite(properties.SiteId, properties.OriginatingUserToken))
                //{
                //    OLARuleDocuments = GetAppSetting(uSite, "OLARuleDocuments");
                //    if (OLARuleDocuments == "")
                //        OLARuleDocuments = "OLARuleDocuments";
                //    using (SPWeb uWeb = uSite.OpenWeb())
                //    {

                //        string filename = properties.ListItem["Title"].ToString();
                //        bool ruledoc = UpdateDocuments(filename, OLARuleDocuments, properties);
                //    }
                //}
            }

            /// <summary>
            /// An item was updated
            /// </summary>

            public override void ItemUpdated(SPItemEventProperties properties)
            {
                //base.ItemUpdated(properties);
                OLASetItemLevelPermission(properties);

            }

            /// <summary>
            /// An item was added
            /// </summary>

    Friday, September 13, 2013 12:16 PM

Answers

  • OK, I got the site working. Thanks for all the help. I had the server admin import the site I exported from the development server. Then I found that a site column was missing. After I re-created the column and the list and library the update seems to function properly.

    Basically I rebuilt the site. I have to have the site tested by users.

    .Net Follower I will keep this in mind if some security issues develop. There are 2 custom groups the site uses. It works for me but then I have full control.

    Thanks for all the suggestions everyone.

    • Marked as answer by wbrown2wmb Monday, October 07, 2013 12:07 PM
    Monday, October 07, 2013 12:07 PM

All replies

  • Sorry forgot to include the change code:

    protected bool UpdateDocuments(string filename, string sList, SPItemEventProperties properties)
            {
                try
                {
                    SPUserToken sysToken = null;

                    //get the system account security token 
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {

                        using (SPSite current = properties.OpenSite())
                        {

                            sysToken = current.SystemAccount.UserToken;

                        }

                    });

                    using (SPSite site = new SPSite(properties.SiteId, sysToken))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPList list = web.Lists[sList];
                            // this always uses root folder
                            SPFolder folder = web.Folders[sList];
                            SPFileCollection fcol = folder.Files;
                            //string updatetitle = filename; //properties.ListItem["Title"].ToString();
                            //<Where><And><IsNull><FieldRef Name="_vti_ItemDeclaredRecord" /></IsNull><Eq><FieldRef Name="Title" /><Value Type="Text">ttests</Value></Eq></And></Where></Query><ViewFields><FieldRef Name="Title" /><FieldRef Name="_vti_ItemDeclaredRecord" /><FieldRef Name="_UIVersionString" /></ViewFields><QueryOptions><ViewAttributes Scope="Recursive" /></QueryOptions></GetListItems>
                            SPUserCollection users = web.AllUsers;
                            SPQuery oQuery = new SPQuery(list.Views["All Documents"]);
                            oQuery.ViewAttributes = "Scope=\"Recursive\"";
                            if (list.Fields.ContainsField("_vti_ItemDeclaredRecord"))
                                oQuery.Query = "<Where><And><IsNull><FieldRef Name='_vti_ItemDeclaredRecord' /></IsNull><Eq><FieldRef Name='Title'/>" +
                                "<Value Type='Text'>" + filename + "</Value></Eq></And></Where>";
                            else
                                oQuery.Query = "<Where><Eq><FieldRef Name='Title'/>" +
                                "<Value Type='Text'>" + filename + "</Value></Eq></Where>";
                            SPListItemCollection _itemCol = list.GetItems(oQuery);

                            //SPListItemCollection _itemCol;
                            //SPQuery qry = new SPQuery(web.Lists["test"].DefaultView);               

                            //_itemCol = _web.Lists["DMSLibrary"].GetItems(qry);
                            //DataTable dtMetaData = ExecuteQuery(_web.Lists["DMSLibrary"]);
                            //int _docID = Convert.ToInt32(dtMetaData.DefaultView.ToTable().Rows[0]["ID"]);
                            web.AllowUnsafeUpdates = true;
                            if (_itemCol.Count > 0)
                            {
                                for (int iCount = 0; iCount < _itemCol.Count; iCount++)
                                {
                                    //SPDocumentLibrary docs = (SPDocumentLibrary)_web.Lists["DMSLibrary"];
                                    SPListItem _item = _itemCol[iCount];
                                    // Informal Title
                                    _item["Title"] = properties.AfterProperties["Title"];
                                    // Actual Title for displaying on Memos or Word documents.
                                   _item["RuleTitle"] = properties.AfterProperties["RuleTitle"];
                                    _item["Location"] = properties.AfterProperties["Location"];
                                    //      _item["RuleTitle"] = properties.AfterProperties["Title"];
                                    _item["NJAC"] = properties.AfterProperties["NJAC"];
                                    // _item["citation"] = properties.AfterProperties["citation"];
                                    _item["ruleaction"] = properties.AfterProperties["ruleaction"];
                                    //_item["targetdeadline"]  =  properties.AfterProperties["targetdeadline"];

                                    //if (properties.AfterProperties["targetdeadline"].ToString() != "")
                                    //  _item.TrySetValue("targetdeadline", DateTime.Parse(properties.AfterProperties["targetdeadline"].ToString(), null, DateTimeStyles.AdjustToUniversal));
                                    //if (properties.AfterProperties["registerissue"].ToString() != "")
                                    //  _item["registerissue"] = DateTime.Parse(properties.AfterProperties["registerissue"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    //properties.AfterProperties["registerissue"];
                                    _item["explanation"] = properties.AfterProperties["explanation"];
                                    _item["statuteauthority"] = properties.AfterProperties["statuteauthority"];
                                    _item["ruledescription"] = properties.AfterProperties["ruledescription"];
                                    _item["advancenotice"] = properties.AfterProperties["advancenotice"];
                                    _item["deptie"] = properties.AfterProperties["deptie"];
                                    //if (properties.AfterProperties["timeofdecision"].ToString() != "")
                                    _item["timeofdecision"] = properties.AfterProperties["timeofdecision"];
                                    _item["waivers"] = properties.AfterProperties["waivers"];
                                    _item["costbenefit"] = properties.AfterProperties["costbenefit"];
                                    _item["otherjurisdictions"] = properties.AfterProperties["otherjurisdictions"];

                                    _item["federalstandards"] = properties.AfterProperties["federalstandards"];
                                    _item["performancebased"] = properties.AfterProperties["performancebased"];
                                    //string test = properties.AfterProperties["sciencebased"].ToString(); 
                                    _item["sciencebased"] = properties.AfterProperties["sciencebased"];
                                    _item["conflicts"] = properties.AfterProperties["conflicts"];
                                    _item["alternatives"] = properties.AfterProperties["alternatives"];
                                    _item["processimprove"] = properties.AfterProperties["processimprove"];
                                    _item["unfunded"] = properties.AfterProperties["unfunded"];
                                    _item["controversy"] = properties.AfterProperties["controversy"];
                                    _item["implementation"] = properties.AfterProperties["implementation"];
                                    _item["informationtech"] = properties.AfterProperties["informationtech"];
                                    _item["enforcement"] = properties.AfterProperties["enforcement"];
                                    _item["constituentrelations"] = properties.AfterProperties["constituentrelations"];
                                    _item["proposalpubinfo"] = properties.AfterProperties["proposalpubinfo"];
                                    //if (properties.AfterProperties["proposalpubdate"].ToString() != "")
                                    //    _item["proposalpubdate"] = DateTime.Parse(properties.AfterProperties["proposalpubdate"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    //if (properties.AfterProperties["pubhearingdtandlocal"].ToString() != "")
                                    //    _item["pubhearingdtandlocal"] = DateTime.Parse(properties.AfterProperties["pubhearingdtandlocal"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    //if (properties.AfterProperties["pubcommentclosedate"].ToString() != "")
                                    //    _item["pubcommentclosedate"] = DateTime.Parse(properties.AfterProperties["pubcommentclosedate"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    _item["pubcommentreceived"] = properties.AfterProperties["pubcommentreceived"];
                                    _item["adoptionstrategy"] = properties.AfterProperties["adoptionstrategy"];
                                    _item["changesonadoption"] = properties.AfterProperties["changesonadoption"];
                                    //_item["Modified By"] = properties.
                                    //SPContext.Current.Web.CurrentUser
                                    //String[] asstcomm = properties.AfterProperties["asstcomm"].ToString().Split('/';
                                    //if (asstcomm.ToString() == "")                        
                                    //  _item["txtasstcomm"]  =  asstcomm[1];
                                    //else

                                    if (properties.AfterProperties["asstcomm"].ToString() != "")
                                        _item["txtasstcomm"] = getUserNameFromPeopleColumn(properties.AfterProperties["asstcomm"].ToString(), users);
                                    if (properties.AfterProperties["director"].ToString() != "")
                                        _item["txtdirector"] = getUserNameFromPeopleColumn(properties.AfterProperties["director"].ToString(), users);
                                    if (properties.AfterProperties["rulemanager"].ToString() != "")
                                        _item["txtrulemanager"] = getUserNameFromPeopleColumn(properties.AfterProperties["rulemanager"].ToString(), users);
                                    if (properties.AfterProperties["laffattorney"].ToString() != "")
                                        _item["txtlaffattorney"] = getUserNameFromPeopleColumn(properties.AfterProperties["laffattorney"].ToString(), users);
                                    if (properties.AfterProperties["txtdag"].ToString() != "")
                                        _item["txtdag"] = properties.AfterProperties["txtdag"].ToString();
                                    if (properties.AfterProperties["techstaff"].ToString() != "")
                                        _item["txttechstaff"] = getUserNameFromPeopleColumn(properties.AfterProperties["techstaff"].ToString(), users);

                                    // updating Adoption Dates
                                    if (properties.AfterProperties["dtAdoptionlaunch"].ToString() != "")
                                        _item["dtAdoptionlaunch"] = DateTime.Parse(properties.AfterProperties["dtAdoptionlaunch"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtAdoptionmeetwComm"].ToString() != "")
                                        _item["dtAdoptionmeetwComm"] = DateTime.Parse(properties.AfterProperties["dtAdoptionmeetwComm"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtAdoptDraftCompleteDocLglRvw"].ToString() != "")
                                        _item["dtAdoptDraftCompleteDocLglRvw"] = DateTime.Parse(properties.AfterProperties["dtAdoptDraftCompleteDocLglRvw"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtAdoptgovernoroffice"].ToString() != "")
                                        _item["dtAdoptgovernoroffice"] = DateTime.Parse(properties.AfterProperties["dtAdoptgovernoroffice"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtAdoptionFillingDeadline"].ToString() != "")
                                        _item["dtAdoptionFillingDeadline"] = DateTime.Parse(properties.AfterProperties["dtAdoptionFillingDeadline"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtAdoptionIntendedpub"].ToString() != "")
                                        _item["dtAdoptionIntendedpub"] = DateTime.Parse(properties.AfterProperties["dtAdoptionIntendedpub"].ToString(), null, DateTimeStyles.AdjustToUniversal);

                                    // updating Proposal Dates
                                    if (properties.AfterProperties["dtProposallaunch"].ToString() != "")
                                        _item["dtProposallaunch"] = DateTime.Parse(properties.AfterProperties["dtProposallaunch"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtProposalmeetwComm"].ToString() != "")
                                        _item["dtProposalmeetwComm"] = DateTime.Parse(properties.AfterProperties["dtProposalmeetwComm"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtProposalDraftCompleteDocLglRvw"].ToString() != "")
                                        _item["dtProposalDraftCompleteDocLglRvw"] = DateTime.Parse(properties.AfterProperties["dtProposalDraftCompleteDocLglRvw"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtProposalgovernorofficedate"].ToString() != "")
                                        _item["dtProposalgovernorofficedate"] = DateTime.Parse(properties.AfterProperties["dtProposalgovernorofficedate"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtProposalFillingDeadline"].ToString() != "")
                                        _item["dtProposalFillingDeadline"] = DateTime.Parse(properties.AfterProperties["dtProposalFillingDeadline"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtProposalIntendedpub"].ToString() != "")
                                        _item["dtProposalIntendedpub"] = DateTime.Parse(properties.AfterProperties["dtProposalIntendedpub"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtProposalpubhearing"].ToString() != "")
                                        _item["dtProposalpubhearing"] = DateTime.Parse(properties.AfterProperties["dtProposalpubhearing"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtProposalcommentclose"].ToString() != "")
                                        _item["dtProposalcommentclose"] = DateTime.Parse(properties.AfterProperties["dtProposalcommentclose"].ToString(), null, DateTimeStyles.AdjustToUniversal);

                                    //updating Substantial Dates
                                    if (properties.AfterProperties["dtSubstantiallaunchmeet"].ToString() != "")
                                        _item["dtSubstantiallaunchmeet"] = DateTime.Parse(properties.AfterProperties["dtSubstantiallaunchmeet"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtSubstantialmeetwComm"].ToString() != "")
                                        _item["dtSubstantialmeetwComm"] = DateTime.Parse(properties.AfterProperties["dtSubstantialmeetwComm"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtSubstantialDraftCompleteDocLglRvw"].ToString() != "")
                                        _item["dtSubstantialDraftCompleteDocLglRvw"] = DateTime.Parse(properties.AfterProperties["dtSubstantialDraftCompleteDocLglRvw"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtSubstantialgovernorofficedate"].ToString() != "")
                                        _item["dtSubstantialgovernorofficedate"] = DateTime.Parse(properties.AfterProperties["dtSubstantialgovernorofficedate"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtSubstantialFillingDeadline"].ToString() != "")
                                        _item["dtSubstantialFillingDeadline"] = DateTime.Parse(properties.AfterProperties["dtSubstantialFillingDeadline"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtSubstantialIntendedpub"].ToString() != "")
                                        _item["dtSubstantialIntendedpub"] = DateTime.Parse(properties.AfterProperties["dtSubstantialIntendedpub"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtSubstantialpubhearing"].ToString() != "")
                                        _item["dtSubstantialpubhearing"] = DateTime.Parse(properties.AfterProperties["dtSubstantialpubhearing"].ToString(), null, DateTimeStyles.AdjustToUniversal);
                                    if (properties.AfterProperties["dtSubstantialcommentclose"].ToString() != "")
                                        _item["dtSubstantialcommentclose"] = DateTime.Parse(properties.AfterProperties["dtSubstantialcommentclose"].ToString(), null, DateTimeStyles.AdjustToUniversal);

     


                                    _item.Update();

                                }

                            }
                            web.AllowUnsafeUpdates = false;

     

                            return true;
                        }
                    }
                }
                catch (SPException spEx)
                {

                    // file already exists?
                    if (spEx.ErrorCode == -2130575257)
                        return false;
                    else
                        throw spEx;
                }

            }

    Friday, September 13, 2013 12:42 PM
  • Hello

    Did you try an ItemUpdated event ?

    If not, try, and tell me if it works better.

    Saturday, September 14, 2013 7:06 AM
  • I'm not sure I can do that as I'm not sure what effect it will have on this:

    public override void ItemUpdated(SPItemEventProperties properties)
            {
                //base.ItemUpdated(properties);
                OLASetItemLevelPermission(properties);

            }

            /// <summary>
            /// An item was added
            /// </summary>

    Tuesday, September 17, 2013 6:19 PM
  • Was this code working before and the updates second time started failing recently?

    The only case I can think of when the code won't update the item is when your "_itemCol" returns 0.  Perhaps you should try looking at the SPQuery.Query property you are constructing to determine if it will (or it is) returning any items back at all.

    Have you been able to debug this in VS?


    These postings are provided "AS IS" with no warranties, and confers no rights.

    Tuesday, September 17, 2013 7:01 PM
  • OK, the problem I have is the code is deployed to a server I can't debug on. I can debug on the server/pc it was developed on, but it works on that one but not the other. I can look at the logs on the server it is deployed on but am not seeing any critical errors.
    Thursday, September 19, 2013 12:53 PM
  • When the event receiver start, and when it stops, you should see some logs... Are you ?

    In the central adminitration, is you solution deployed ?

    Saturday, October 05, 2013 6:53 AM
  • Hello!

    Probably that's not a reason of your issue, but... In the code where you get the system account token, within the SPSecurity.RunWithElevatedPrivileges, you have to create a new elevated SPSite object. Calling the properties.OpenSite() you likely use the not elevated SPSite. So, the exception seems to be here when a simple user (who is updating the item) doesn't have permissions to get the SystemAccount property of the SPSite.

    So, I recommend you to use the right method to get the system token (for details, read the blog post - How to get SystemAccount token):

    protected static SPUserToken GetSystemToken(SPSite spSite)
    {
        SPUserToken res = null;
        bool oldCatchAccessDeniedException = spSite.CatchAccessDeniedException;
        try
        {
            spSite.CatchAccessDeniedException = false;
            res = spSite.SystemAccount.UserToken;
        }
        catch (UnauthorizedAccessException)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite elevatedSPSite = new SPSite(spSite.ID))
                    res = elevatedSPSite.SystemAccount.UserToken;      // (***)
            });
        }
        finally
        {
            spSite.CatchAccessDeniedException = oldCatchAccessDeniedException;
        }
        return res;
    }

    Call the method like GetSystemToken(properties.Web.Site).

    Also I suggest to log somehow exceptions that might be thrown. Even if you don't handle them, try to catch ones, log and then rethrow. You will have much more  information about what happens inside event handlers. A simple logger I use (it logs to the EventViewer) is shown here.



    .Net Follower (http://dotnetfollower.com)


    Sunday, October 06, 2013 2:51 AM
  • Disable event firing at start of event:

    this.EventFiringEnabled = false;

    Enable event firing at end of event: 

    this.EventFiringEnabled = true 


    Tarek Yehia


    • Edited by Tarek Yehia Sunday, October 06, 2013 3:08 PM
    Sunday, October 06, 2013 3:08 PM
  • OK, I got the site working. Thanks for all the help. I had the server admin import the site I exported from the development server. Then I found that a site column was missing. After I re-created the column and the list and library the update seems to function properly.

    Basically I rebuilt the site. I have to have the site tested by users.

    .Net Follower I will keep this in mind if some security issues develop. There are 2 custom groups the site uses. It works for me but then I have full control.

    Thanks for all the suggestions everyone.

    • Marked as answer by wbrown2wmb Monday, October 07, 2013 12:07 PM
    Monday, October 07, 2013 12:07 PM
  • You could better have debugged your solution and found it out about the missing column.


    Abhijith R Shastry

    Monday, October 07, 2013 12:13 PM
  • As I stated above, I cannot debug on the server. I do not have rights to debug on the server it's supposed to run on. It does not have visual studio installed on it. Nor are the powers that be going to give me any rights on the server.

    I have access to the logs and that's it.

    If I could have run a debug then there wouldn't be an issue.

    If I do encounter any rights issues now I know where to look.

    Thank you all.

    Monday, October 07, 2013 12:20 PM