Sharepoint 2013 ItemAdded event receiver for renaming files is not working

In SP 2013 I coded an event receiver that intercepts the ItemAdded event and it just renames the file.
It is a synchronous event (I added <Synchronization>Synchronous</Synchronization> in the Elements.xml).
This is the code:
        public override void ItemAdded(SPItemEventProperties properties)
            SPSecurity.RunWithElevatedPrivileges(delegate()
                try
                    OutputDebugStringA("Inside ItemAdded");
                    string szHttpUrl = properties.WebUrl + "/" + properties.AfterUrl;
                    SPWeb openedWeb = properties.Web.Site.OpenWeb(properties.Web.ID);
                    SPFile spf = openedWeb.GetFile(szHttpUrl);
                    EventFiringEnabled = false;
                    string szUrl = properties.AfterUrl;
                    szUrl = szUrl + ".renamed";
                    string szNewFileName;
                    if (szUrl.LastIndexOf('\\') != -1) szNewFileName = szUrl.Substring(szUrl.LastIndexOf('\\') + 1);
                    else if (szUrl.LastIndexOf('/') != -1) szNewFileName = szUrl.Substring(szUrl.LastIndexOf('/') + 1);
                    else szNewFileName = szUrl;
                    if (properties.ListItem != null)
                        properties.ListItem["Title"] = szNewFileName;
                        properties.ListItem.Update();
                    spf.MoveTo(szUrl);
                    EventFiringEnabled = true;
                    base.ItemAdded(properties);
                    OutputDebugStringA("Renaming to " + szUrl);
                catch (System.Exception exception)
                    OutputDebugStringA("ItemAdded ERROR: " + exception.ToString());
The problem is that when I upload a .txt file using Internet Explorer, just after the renaming is done, IE says that something went wrong and when I inspect the log files I see:
SPRequest.GetFileAndFolderProperties: UserPrincipalName=i:0).w|s-1-5-21-4050800873-4278272723-3073177257-500, AppPrincipalName= ,bstrUrl=http://sp2013/sites/demo/subsite1 ,bstrStartUrl=Shared Documents/test2.txt ,ListDocsFlags=16400 ,bThrowException=True 0fa7689c-674b-5045-c3a2-b214a5d4cbed
01/09/2014 15:29:26.75  w3wp.exe (0x1544)                        0x16F4 SharePoint Foundation        
 General                        ai1wu Medium   System.IO.FileNotFoundException: <nativehr>0x80070002</nativehr><nativestack></nativestack>,
StackTrace:    at Microsoft.SharePoint.SPWeb.GetFileOrFolderProperties(String strUrl, ListDocsFlags listDocsFlags, Boolean throwException, SPBasePermissions& permMask)     at Microsoft.SharePoint.SPFile.PropertiesCore(Boolean
throwException)     at Microsoft.SharePoint.SPFile.get_Length()     at Microsoft.Office.RecordsManagement.PolicyFeatures.ApplicationPages.UploadPage.OnSubmit(Object o, EventArgs e)     at Microsoft.Office.RecordsManagement.PolicyFeatures.ApplicationPages.UploadExPage.OnSubmit(Object
o, EventArgs e)     at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)     at System.Web.UI.Page.ProcessRequest(Boolean includeSta... 0fa7689c-674b-5045-c3a2-b214a5d4cbed
...gesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)     at System.Web.UI.Page.ProcessRequest()     at System.Web.UI.Page.ProcessRequest(HttpContext context)     at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()    
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)     at System.Web.HttpApplication.PipelineStepManager.ResumeSteps(Exception error)     at System.Web.HttpApplication.BeginProcessRequestNotification(HttpContext
context, AsyncCallback cb)     at System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context)     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr
rootedObjectsPointer, IntPtr nativeRequestContex... 0fa7689c-674b-5045-c3a2-b214a5d4cbed
...t, IntPtr moduleData, Int32 flags)     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)     at System.Web.Hosting.UnsafeIISMethods.MgdIndicateCompletion(IntPtr
pHandler, RequestNotificationStatus& notificationStatus)     at System.Web.Hosting.UnsafeIISMethods.MgdIndicateCompletion(IntPtr pHandler, RequestNotificationStatus& notificationStatus)     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr
rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags) 
 0fa7689c-674b-5045-c3a2-b214a5d4cbed
So it is clear that the fact that I renamed the file is causing an issue in the SharePoint upload logic.
As a solution what I did was to not declare it as Synchronous, but if I do it then there is another error when Sharepoint shows the Edit Properties dialog... in this case the upload is OK but when it is time to show that Edit Property dialog IE fails and
says that the file has been already modified, or that "something went wrong".
If I use a synchronous event I get one problem. If I use the asynchronous event I get another problem... It's very frustating and I am pretty sure that a so important API like Event Receivers should have support renaming files so I hope someone can tell
me what I am doing wrong.
Thanks in advance

May be you want to consider using the following code and see if it works for you.
http://social.msdn.microsoft.com/Forums/sharepoint/en-US/40c78e03-2dca-4083-89d2-a7430099da68/how-do-i-change-the-name-property-of-a-file-in-a-document-library?forum=sharepointdevelopment
Amit

Similar Messages

  • Sharepoint 2013, event receiver to rename files not working

    I coded an event receiver (ItemAdding) that renames for example a .txt file to a .text file (it does not matter the extensions, it is just an example). In my code what I do is to an SPFile.MoveTo operation. It works fine in SP2010 but when I execute
    the same code in SP 2013, when the operation is done using IE I get the text "Sorry, something went wrong" and then "File Not Found".
    In the logs this is what I see:
    12/23/2013 15:48:49.16  w3wp.exe (0x17B0)                        0x0AC8 SharePoint Foundation        
     General                        ai1wu Medium   System.IO.FileNotFoundException: The system cannot find the file specified.
    (Exception from HRESULT: 0x80070002), StackTrace:    at Microsoft.SharePoint.SPWeb.GetFileOrFolderProperties(String strUrl, ListDocsFlags listDocsFlags, Boolean throwException, SPBasePermissions& permMask)     at Microsoft.SharePoint.SPFile.PropertiesCore(Boolean
    throwException)     at Microsoft.SharePoint.SPFile.get_Length()     at Microsoft.Office.RecordsManagement.PolicyFeatures.ApplicationPages.UploadPage.OnSubmit(Object o, EventArgs e)     at Microsoft.Office.RecordsManagement.PolicyFeatures.ApplicationPages.UploadExPage.OnSubmit(Object
    o, EventArgs e)     at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)     at System.Web.UI.Page.ProcessReque... f72b639c-77b1-5045-c3a2-b23f24ae71c0
    It's clear that the Sharepoint upload code tries to do things with the original name and it does not realize that it was renamed.
    Can I do something from my event receiver code like using the AfterProperties to bypass this error?
    Thanks

    Hi Dennis,
    The issue still persists. Here is the code:
            public override void ItemAdded(SPItemEventProperties properties)
                SPSecurity.RunWithElevatedPrivileges(delegate()
                    try
                        OutputDebugStringA("Inside ItemAdded");
                        string szHttpUrl = properties.WebUrl + "/" + properties.AfterUrl;
                        SPWeb openedWeb = properties.Web.Site.OpenWeb(properties.Web.ID);
                        SPFile spf = openedWeb.GetFile(szHttpUrl);
                        EventFiringEnabled = false;
                        string szUrl = properties.AfterUrl;
                        szUrl = szUrl + ".renamed";
                        string szNewFileName;
                        if (szUrl.LastIndexOf('\\') != -1) szNewFileName = szUrl.Substring(szUrl.LastIndexOf('\\') + 1);
                        else if (szUrl.LastIndexOf('/') != -1) szNewFileName = szUrl.Substring(szUrl.LastIndexOf('/') + 1);
                        else szNewFileName = szUrl;
                        if (properties.ListItem != null)
                            properties.ListItem["Title"] = szNewFileName;
                            properties.ListItem.Update();
                        spf.MoveTo(szUrl);
                        EventFiringEnabled = true;
                        base.ItemAdded(properties);
                        OutputDebugStringA("Renaming to " + szUrl);
                    catch (System.Exception exception)
                        OutputDebugStringA("ItemAdded ERROR: " + exception.ToString());

  • The Gmail icon for attaching files does not work in Firefox

    I have tried the config change for network.http.spdy.enabled to false, and quite a few other suggestions for this problem, some from years ago.
    Only the attach file icon is affected. Dragging files into gmail works to attach them, just the icon is not working.
    Very perplexing.

    Try allowing pop up windows
    Open Menu
    Options
    Content (on the top)
    Click Exceptions...
    Type mail.google.com in address of website area
    Click Allow
    Try to open attachment window now.
    Restart FireFox and try adding attachment again.

  • Sharepoint 2013 SP1 incoming email in load balanced farm not working on both servers

    I have 2 SharePoint 2013 WFE servers with a VIP load balancer.
    I have configured the basic scenario incoming email on both servers as per this article
    http://technet.microsoft.com/en-ca/library/cc262947(v=office.15).aspx.
    The email makes it to both WFEs in the SMTP drop folder but SharePoint picks it up always from one smtp server.
    What could go wrong?  is there any additional configuration needed so that sharepoint check both servers?

    MX records can be pointing to the IPs of your Incoming Email SharePoint servers. They should have the same weight if you want them to load balance, or different weights if you want them to be failover.
    Trevor Seward
    Follow or contact me at...
    &nbsp&nbsp
    This post is my own opinion and does not necessarily reflect the opinion or view of Microsoft, its employees, or other MVPs.

  • SharePoint 2013 site coll's created. Home page not displaying for any site collection in farm

    SharePoint 2013 site coll's created. Home page not displaying. Same issue for all site coll's in the farm. Done the basic checks. Any Ideas?

    Hi lakshita,
    Would you please check whether you can go to the page:
    http://siteurl/_layouts/settings.aspx page:
    http://siteurl/default.aspx page? If so, go to Site Features in site settings page, reactivate the Wiki Page home page feature, check the result.
    If not, please check whether there is related information in ULS log and event viewer log file? Does the page shows page not found or other errors? Check whether the site can be opened in other machine?
    Thanks,
    Qiao Wei
    TechNet Community Support

  • Calendar - How can I expand the recurrences of a recurring item in ItemAdding event receiver?

    When a user add a new recurrence event to a calendar I want to check if any of the recurrences overlap with events already in the calendar.
    I saw the property Recurrences Data and its XML but I didn't find a way to translate that value to dates I can test against the events dates on the calendar.
    So, is there a way to expand the recurrences of an event in the ItemAdding event receiver of a calendar?

    Hi,
    Per my understanding, you might want to check if there any overlapped recurring events in Event Receiver.
    You can build the query with <DateRangesOverlap> to return the recurring events with Server Object Model.
    A code demo in the thread below about how to get recurring events from Calendar for your reference:
    https://social.technet.microsoft.com/Forums/en-US/99c3ded6-a8cb-4509-9a74-e93e445d78c7/how-does-calender-list-daterangesoverlap-todaymonthyear-and-week-exactly-work?forum=sharepointdevelopmentprevious
    Thanks
    Patrick Liang
    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]

  • Event Receiver for all Page Libraries in a Site Collection

    We have a single site collection with many different page libraries.  I'd like to create a single event receiver for ALL page libraries in the site collection (850- Page Library).  Can you do this?
    The event receiver will essentially remove/expire something we have stored in the System.Web.HttpRuntime.Cache.  We are caching the content in the Page Library and would only like to expire the cache when a new page or change is performed on some
    content in the page library.

    Hi,
    We can create a new feature and add an event receiver to the feature for all Page Libraries.
    For more information, you can see the link below:
    http://msdn.microsoft.com/en-us/library/ee231604.aspx
    Here are two similar threads for you to take a look at:
    http://sharepoint.stackexchange.com/questions/37555/how-to-add-event-receivers-to-all-the-lists-in-a-site-collection
    http://social.technet.microsoft.com/Forums/en-US/f1297543-9035-49d6-9299-d82f546eeddd/event-receiver-for-specific-list-fires-for-all-lists-on-site-collection?forum=sharepointcustomizationprevious
    Thanks,
    Dennis Guo
    TechNet Community 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]
    Dennis Guo
    TechNet Community Support

  • CsrAttachmentUploadDiv part attachment is not rendered SP 2013(Attach file in not working for all the list forms)?

    csrAttachmentUploadDiv partattachment  is not rendered SP 2013(Attach file in not working for all the list forms)?
    Ravi
    function ShowPartAttachment() {
    ULSopi:
        if (document.getElementById("part1") == null || typeof document.getElementById("part1") == "undefined") {
            alert(Strings.STS.L_FormMissingPart1_Text);
            return;
        (document.getElementById("part1")).style.display = "none";
        (document.getElementById("partAttachment")).style.display = "block"; //problem here

    Am also facing the similar problem....any iputs are highly appriciated.
    Issue..
    1) Defined the attachment type in IMG.
    2) Added the attachment type "SFREEATTM" by selecting other attributes---> Attachment Types.
    3) Attached the excel file in the design.
    See the screen shot below:
    The Issue is when testing through tcode nwbc in the inbox the attachment tab is not visible after selecting the particular form.
    Please see the screen shot below:
    Did i miss any Configuration?? Please suggest...
    Regards,
    Naveen

  • How can i convert my song into .mr4 for making it my ringtone, just renaming it is not working?

    how can i convert my song into .mr4 for making it my ringtone, just renaming it is not working?

    Here's how:
    If you are using Windows, make sure you are able to view the file extension.
    http://support.microsoft.com/kb/865219
    1. Select a title (.mp3 or .m4a) in your iTunes Music Library
    2. Do File > Get Info on selected title (Windows do Edit > Get Info)
    3. In the dialog choose Options tab
    4. Set Start Time and End Time (no more than 35 secs otherwise won't work)
    5. Close dialog.
    6. Now control click the title (right click) and choose Create AAC Version
    Note: If you don't have Create AAC version, switch in menu File > Preferences...(Windows do Edit > Preferences...) > General > Import Settings... > Import Using: AAC Encoder.
    7. When it is done, drag the newly create title to the desktop.
    8. Delete the newly create title in iTunes. <-- This step is important
    9. Rename the title on your desktop from ringtone.m4a to ringtone.m4r
    10. Drag and drop it into iTunes
    Now you have a ringtone.
    Make sure it is selected in iTunes > Tones for syncing with your new iPhone.

  • I cannot update or install updates on itunes. It says that the location for that file does not exist. I cant even uninstall itunes as the same error message comes up.

    I cannot update or install updates on itunes. It says that the location for that file does not exist. I cant even uninstall itunes as the same error message comes up.

    Hi vindog60,
    Thank you for using Apple Support Communities.
    To troubleshoot this issue where you get an installation error with iTunes on your Windows PC, please follow the steps in the article linked to below.
    Issues installing iTunes for Windows - Apple Support
    Cheers,
    Alex H.

  • Adobe encore the software that's used to decode the media is not available on this system. installing the correct decoders for the file you are working with may help correct the problem

    Hi,
      I got this message after importing about ten or so H.264 files that I encoded from Adobe media encoder.  "adobe encore the software that's used to decode the media is not available on this system. installing the correct decoders for the file you are working with may help correct the problem."
    The files we're shot with HD cameras.  Edited in Premiere Pro CS3.  I installed the update 3.0.1 with still the same error.
    I also tried a brand new project and after about ten or so files being imported into a timeline, the system crash.  I tried this twice....
        Thanks in Advance

    Hi Hunt,
           Here is the skinny.  A window base PC.  footage shot with HD sony HD cameras,  Project imported to Premiere CS3.  Once completed sent file to Adobe media encoder and render them as H.264 widescreen high Quality.  Imported them to Adobe Encore CS3.  After about ten files or so.  I got the error message.  Did all the basic trouble shoot like restarting the computer, got latest patch.  Even build a new test project with the same problem.
        Something else I read in the forums, is the encore will transcoded the project to Mpeg 2 anyway, after looking at my project I realized those few files were indeed untranscoded.  So it will be a double compression and I dont want that.  So, my new question is, what is H.264 good for ?????????? I was research that Mpeg 2 is a faster render but H.264 is a slower render but better quality.....
       what do you think ????
       Peter

  • Used to convert all my videos into iPhone mp4 format using Any Video Converter - then add it to my iPhone 3GS. But last few days, I cant add video files to iTunes. and the iTunes doesnt even specify the reason except for that "files are not supported"

    Everyting was perfect earlier. Used to convert all my videos into iPhone mp4 format using Any Video Converter - then add it to my iPhone 3GS. But last few days, I cant add video files to iTunes. and the iTunes doesnt even specify the reason except for that "files are not supported"
    Everything is fine.
    -They are the right format
    -Quicktime is updated
    -I have tried simply dragging them into the 'movie' library
    -I have tried going to file<add file to library
    Nothing works, has anyone else had this problem and found a way around it?
    Any and all help appreciated.

    In addition to Mike's suggestions,  you only have 4GB of RAM and Mavericks does use more RAM than other versions. You may also want to look at the apps that startup on login and the possiblity of upgrading RAM.

  • Browse for file/img not working - Win 7

    Browse for file/img not working still - Win 7
    I have tried "run as Admin" and in "XP Compatibility mode" but still no luck fixing this issue in Win 7. Anyone have a potential fix so I can stop wasting time double checking every link/img on new work?
    Thanks!

    Are you referring to this issue?
    Problem selecting local root folder in Vista & Windows 7
    http://forums.adobe.com/thread/478327
    If so, there's no fix yet and not likely to be one.

  • Folder Specified for Temporary Files is not Available

    Whenever I start PS CS, I get a "The Folder Specified for Temporary Files is not Available" error message. How do I fix this?
    Thanks!
    JB

    >F is internal.
    Doesn't proof that it's working. Disable it (as a scratch disk). See what happens.
    Rob

  • My up to date iMac can not read the lightroom 5 installation dvd I received for christmas, the dvd player works fine with other dvd's, is there a way to download the program with the dvd's serial number?

    my up to date iMac can not read the lightroom 5 installation dvd I received for christmas, the dvd player works fine with other dvd's, is there a way to download the program with the dvd's serial number?

    No need to worry about the disk version. You would just have to install an update anyway as soon as it was installed. Download from the link provided below and use the serial number you have to activate.
    Product updates

Maybe you are looking for

  • Cannot Browse Shares on NSS326

    New device - NSS326. Setup and joined win2k3 domain no issue. I can manage it via web interface with no issue. Ping by ip and dns name on network from any device. What i cannot do is browse the device. I am using the Public share that is prebuilt int

  • HT1977 Help with app downloads

    I'm trying to download apps from itunes onto my iphone.  When I look at my itunes account in the app stoure under purchases, it shows that the apps have downloaded.  When I look at my phone, I can see them on my phone but they all say "waiting..." un

  • Workflow on Blackberry

    Hi All, I know this topic is already discussed many times before also but while going through the solutions and discussions I was not able to understand many facts. First of all I am looking for a 2 way communication between SAP workflow and Blackber

  • Group Personnel Subarea for Work Schedule

    Hi All, I am learning SAP HCM ECC 6.0 at the moment, I have created Personnel Area, Personnel Subarea however when I am trying to u201CGroup Personnel Subarea for Work Scheduleu201D the newly created Personnel Areas and Personnel Subarea are not appe

  • Reporting Studio Installation

    Hi There, We have 11.1.1.3 essbase with SmartView and Excel addin, and we want to install Report Studio, I would like to ask the group if there is anything I need to be careful when installation this to exsiting Essbase. I download the Reporting Stud