Document Library document delete using Event Receiver

Please suggest your solution for the following scenario:
A user deletes the document from document library and an e-mail has to be triggered to the admin notifying the information about the document deleted recently along with the option to Approve\Reject. If the Admin approves it, the document stays in Recycle Bin
and if Rejected, the document gets restored to the document library.
I came across some articles about 'event receiver' which can trigger an e-mail but couldn't find any coding for the recycle bin and deletion. Is there any other workaround to implement the same?

Hi,
In that case, Instead of the deleting the file through code, you can send to recycle using the SPFile.Recycle and SP.CopyTo method.
SPFile Class
Murugesa Pandian.,SharePoint 2010| MCPD | MCTS - Configure

Similar Messages

  • Can we update InfoPath field using Event Receiver ItemAdded method

    Hi,
    Can we update InfoPath browser enabled form field using Event Receiver ItemAdded method. Following is the code snippet I used to update the field but it's not updating the field.
    Please help me on this issue.
    public override void ItemAdded(SPItemEventProperties properties)
                base.ItemAdded(properties);
                try
                    //Turn off event firing so we don't end up with a conflict 
                    base.EventFiringEnabled = false;
                    //Run the code elevated so we can rename our item
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                        using (SPSite site = new SPSite(properties.Web.Site.ID))
                            using (SPWeb web = site.OpenWeb(properties.Web.ID))
                                //Grab a new copy of our list and listitem under the new security context
                                SPList list = web.Lists[properties.List.ID];
                                SPListItem item = list.Items.GetItemById(properties.ListItemId);
                                //Change name and title to match item ID
                                item.File.CheckOut();
                                string fieldInternalName = properties.List.Fields["Employee Name"].InternalName;
                                SPUser oUser = web.EnsureUser(Convert.ToString(item["Employee Entry"]).Substring(0, Convert.ToString(item["Employee Entry"]).Length - 2));
                                item[fieldInternalName] = oUser.Name;
                                item.Update();
                                item.File.CheckIn("Changed Employee Name");
                catch (Exception ex)
                    //Log an errors to the ULS
                finally
                    //Turn event firing back on
                    base.EventFiringEnabled = true;
    Srivignesh J

    When you published your infopath form, did you promote the field you are trying to update to a property, and allow updates (its one of the steps in publishing your form, where you pick which fields you want to show as fields in the list view)... 
    Otherwise, how about get the Item.SPFile object, open it as XML, find the field you want to update, and update it that way... 

  • Document Library items delete

    Hi ,
    I have a Document Library. I created one custom view through code.
    in that, i need to show a DELETE option. i already did that.
    Question is, only document owners only should have the right to delete those doc's. Others should not delete.
    For a list, we have ITEM LEVEL PERMISSION option. Like that , is there any way to achieve  that?
    How to do that.?

    Hello,
    Just create a designer workflow for  your requirement.
    Execute that workflow when an new document gets added under library.
    The functionality of the workflow is as follows
    When a new document get added, you workflow will set contribute access to the owner of that document and will set read access to rest all other users.

  • Unable to apply color formatting to document library custom view using javascript

    Hello,
    I have applied color formatting to some values in Document library at "Allitems.aspx" page.
    Created one view where record of library displaying as per sort rule and trying to apply the color formatting on that view, but its not getting apply.
    also tried to insert that list as web part in one page with the same view(created by me) and tried applying color..but not working.
    I used below script for color formatting, included in script editor web part:
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function()
    $Text = $("td.ms-cellstyle.ms-vb2:contains('Very limited risk - acceptable A')");
    $Text.css("background-color", "#7FFF00");
    $Text = $("td.ms-cellstyle.ms-vb2:contains('Measures Required (in 6 months) - M')");
    $Text.css("background-color", "#D2691E");
    $Text = $("td.ms-cellstyle.ms-vb2:contains('Immediate measures required - I')");
    $Text.css("background-color", "#6495ED");
    $Text = $("td.ms-cellstyle.ms-vb2:contains(Stop work until measures are taken - S)");
    $Text.css("background-color", "#DC143C");
    </script>
    Could please suggest a way out.
    Thanking you in advance.
    Regards,
    Jayashri

    Hi Jayashri,
    Follow the steps to debug your JS code, preferable in IE browser
    Press F12 to open your developer tool
    Select Script tab
    Search for your code, set debugger point by clicking on the left extreme position on line numbers
    Click on Start debugging at top, if its not there in your browser just refresh the page, it will hit the debug point.
    Hope it will help you in debugging your code, if you need any further details about debugging this, mail me @
    [email protected]
    Thanks
    Shakir

  • Update Sharepoint 2013 document library folder columns using document url

    Hi All,
    I have a SharePoint document library. In that library I am having folder name called Folder1. In this folder Folder1 I have 4 files in it. Now. I need to update the status column of these 4 files in Folder1 folder using the url of these 4 files.
    So can anyone help me in to solve this problem. I am using SharePoint 2013 and Visual studio 2012. I want the code in C#.
    Thanks & Regards,
    Kishore
    Kishore

    Hi,
    According to your post, my understanding is that you want to update the field within the folder.
    I have made a simple code demo below to update the field within the folder, you can have a look at it.
    using (SPSite site = new SPSite("http://YourSiteURL"))
    using (SPWeb web = site.OpenWeb())
    SPList list = web.Lists.TryGetList("Lib1");
    if (list != null)
    foreach (SPListItem folderItem in list.Folders)
    if (folderItem.Title == "Folder1")
    SPListItem item = list.GetItemById(5);
    item["Status"] = "Updated";
    item.Update();
    Console.WriteLine("Field update successfully...");
    Thanks & Regards,
    Jason
    Jason Guo
    TechNet Community Support

  • Detect what the default edit form is for a document library and list using jquery

    Hi,
    So what I have done is with some jquery made it that when a files are dragged and dropped into a document library and there is a required field such as "Metadata" the EditForm.aspx opens up for the user to fill in the required column. I am building
    the url up from what I have found in SharePoints DragDrop.js file. This is all working perfectly I just need to find a way to dynamically find what the default edit form is for that document library as I have just hardcoded like this...
    g_currentControl.strSiteUrl + "/" + this.ListName + "/Forms/EditForm.aspx?ID=" + id
    So I need a way to figure out what the default edit form is instead of hard coding like this in case someone creates a custom_editform.aspx or something for one of the lists.
    Thanks

    You can get it by hitting this REST end point via JQuery:
    http://weburl/_api/Web/Lists(guid'YOURLISTGUID')/Forms
    Chris Givens CEO, Architecting Connected Systems
    Blog Twitter

  • Get All Values From NewForm.aspx using Event Receiver Item Adding

    HI All,
             I have conditions to check before the insertion of "Calendar Event".For this I am using Item Adding Event Receiver ,When Click on Save button I need to get all the values of Items filled in NewForm.aspx and check
    the condition,If condition satisfies make them insert else show alert info  as"Not Valid",Below is code and error message
    public override void ItemAdding(SPItemEventProperties properties)
                base.ItemAdding(properties);
               string StartTime = properties.AfterProperties["Start Time"].ToString();
               string EndTime = properties.AfterProperties["End Time"].ToString();
    Error
    Object reference not set to an instance of an object.
    Use the New "Keyword to create an object instance
    Can any one help me how can I do it.
    Thanks,
    Quality Communication Provides
    Quality Work.
    http://siddiq-sharepoint2010.blogspot.in/
    Siddiqali Mohammad .

    Hi,
          Have you tried with the code snippet as mentioned below
    string EndDate = Convert.ToString(properties.AfterProperties["EndDate"]);
    string StartDate = Convert.ToString(properties.AfterProperties["EventDate"]);
    If my post is helpful - please click on the green arrow to mark it as answer

  • Add an item into announcement list in site collec. and repeat the same in all the sub webs' announcement list without using event receiver

    hi,
    I have a requirement: in my site collection i have an announcement list. and in my site collection  some 600+ sub sites exist. sharepoint admin uploads an announcement into this rootweb's announcement list. now is there any way
    i can add the same announcement -which has title, description, date time etc .- to all the 600+ sub sites' announcement list?
    i know , if i write a list item event receiver i will be able to iterate through eacha nd every subweb of my site collec and add this item into those sub web's  announcement list. But, without writing an event receiver and creating and deploying
    another wsp and avoiding all those headache, is it possible to achieve this requirement?
    any other approaches are highly appreciated!

    Hi,
    As a workaround, we can create a winform application for admin use only to add the item to all the sub web's announcement list.
    Developing Sharepoint Windows Forms
    http://www.codeproject.com/Tips/566370/Developing-Sharepoint-Windows-Forms
    Best Regards,
    Dennis Guo
    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]

  • Display notification when a document is uploaded to document library on Homepage

    How can i display notification on homepage when a document is uploaded to document library in SharePoint 2013.

    Hi,
    I think this will work for your requirement.(I am assuming Notification should be visible to all the users).
    1. Create 1 Custom List (say "Notifications").
    2. Add Event Receiver on your document Library and Whenever a new document is uploaded by using Event Receiver update the same in "Notifications" List.
    3. By using ECMA Script ,you can read the List Items and bind .
    (or)
    you can achieve the same from the document library it selft , why list is for future enhancements.
    Please share your views.
    Don't forget to mark it as an Answer if it resolves your issue and Vote Me as helpful if it useful.
    Mahesh

  • Problems with Event Receiver and SkyDrive Pro Document library

    I wrote an event Receiver that implements the ItemUpdated (but the Synchronous one) event. I basically modify docx files content. When the library has versioning enabled, I first move the SPFile to a hidden library that does not have versioning, I update
    it, and then I move back to the original library to avoid creating a new version for this file.
    This works fine in the standard case (e.g. standard Document Library), but for Document Libraries that belong to SkyDrive then when I upload files using the SkyDrive Pro utility (that is, the utility that synchronizes files from "C:\Users\Administrator\SkyDrive
    Pro\Shared with Everyone" to the server) there in an error reported by the Upload Center since it seems that as the file content is modified in the server and is different than the local copy then it does not like this situation. If you open the file
    using the Upload Center then word asks you to keep the version in the server, or the version that is local.
    Any way to bypass this?
    Thanks

    Hi,
    From the description, the issue seems to be that the event receiver fires in the SkyDrive library, but the SkyDrive folder where you met the error message isn't synchronized to the server.
    If so, this will be the default behavior, have you checked the workflow? You may consider copy the document to document library using workflow, update the document in the library using event receiver or workflow, then copy back to the SkyDrive
    library.
    If it isn't the issue, please feel free to let me know.
    Thanks,
    Qiao Wei
    TechNet Community Support

  • Change document name in event receiver

    I need to rename a document during an ItemUpdating or an ItemUpdated event. Either one would be fine. When my user changes the file name, I want my code to set it to something else. In the examples below, I am trying to set it to a silly constant value.
    If I can get this to work, I'll change it to use something meaningful.
    Is there any way to change a document's name in an event receiver? I have tried using ItemUpdated (with <Synchronization>Synchronous</Synchronization> in elements.xml). I have tried this:
    public override void ItemUpdated(SPItemEventProperties properties)
    using (DisabledEventsScope scope = new DisabledEventsScope())
    base.ItemUpdated(properties);
    try
    properties.Web.AllowUnsafeUpdates = true;
    properties.ListItem.File.Properties["FileLeafRef"] = "FOOFOO.docx";
    properties.ListItem.File.Update();
    properties.Web.AllowUnsafeUpdates = false;
    catch (Exception ex)
    properties.ErrorMessage = "Document cannot be renamed." + ex.Message;
    properties.Status = SPEventReceiverStatus.CancelWithError;
    //base.ItemUpdated(properties);
    I have also tried this:
    public override void ItemUpdated(SPItemEventProperties properties)
    using (DisabledEventsScope scope = new DisabledEventsScope())
    base.ItemUpdated(properties);
    try
    properties.Web.AllowUnsafeUpdates = true;
    properties.AfterProperties["FileLeafRef"] = "FOOFOO.docx";
    properties.ListItem.Update();
    properties.Web.AllowUnsafeUpdates = false;
    catch (Exception ex)
    properties.ErrorMessage = "Document cannot be renamed." + ex.Message;
    properties.Status = SPEventReceiverStatus.CancelWithError;
    //base.ItemUpdated(properties);
    And in that last one, I also tried setting properties.ListItem["FileLeafRef"]. I have also tried putting the base.ItemUpdated line after my logic (where you see it commented out above).
    Nothing works. No errors are thrown, but the document name stays the way the user set it.
    Leigh Webber

    There's three things you have to do in order to update the name properties:
    Assign properties.ListItem to a variable
    Update the BaseName field
    Update the Type field (if you wish to change the extension)
    public override void ItemUpdated(SPItemEventProperties properties)
    EventFiringEnabled = false;
    base.ItemUpdated(properties);
    var item = properties.ListItem; item["BaseName"] = "BarBar";
    item["Type"] = "docx"; //If you need to change the extension
    item.Update();
    EventFiringEnabled = true;
    This should fix your issue

  • Exception calling "Update" with "0" argument(s): "To add an item to a document library, use SPFileCollection.Add()"

    Hi i am trying to add a new item and update existing field value in a document library with powershell 
    but i receive below error message.
    PS C:\Users\spfarm> C:\Scripts\add.ps1
    Exception calling "Update" with "0" argument(s): "To add an item to a document
    library, use SPFileCollection.Add()"
    At C:\Scripts\add.ps1:24 char:16
    + $newItem.Update <<<< ()
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : DotNetMethodException
    #Add SharePoint PowerShell Snapin which adds SharePoint specific cmdlets
    Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue
    #Variables that we are going to use for list editing
    $webURL = "http://tspmcwfe:89"
    $listName = "test"
    #Get the SPWeb object and save it to a variable
    $web = Get-SPWeb $webURL
    #Get the SPList object to retrieve the "Demo List"
    $list = $web.Lists[$listName]
    #Create a new item
    $newItem = $list.Items.Add()
    #Add properties to this list item
    $newItem["Title"] = "My second item!"
    $newItem["Info"] = "s15"
    #Update the object so it gets saved to the list
    $newItem.Update()
    $web.Dispose()
    adil

    Hi Adil,
    Document Library is different from a normal list. The document library contains files inside it. You need to update the code to add a document to the library. Then you can get hold of the List Item represented by that file and update its properties. Here
    is an example:
    $WebURL = "http://aissp2013/sites/TestSite"
    $DocLibName = "Docs" 
    $FilePath = "c:\blogs.txt" 
    # Get a variable that points to the folder 
    $Web = Get-SPWeb $WebURL 
    $List = $Web.GetFolder($DocLibName) 
    $Files = $List.Files
    # Get just the name of the file from the whole path 
    $FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+1)
    # Load the file into a variable 
    $File= Get-ChildItem $FilePath
    # Upload it to SharePoint 
    $spFile = $Files.Add($DocLibName +"/" + $FileName,$File.OpenRead(),$false) 
    $item = $spFile.Item
    $item["Title"] = "New Title"
    $item.Update()
    $web.Dispose()
    Blog | SharePoint Learnings CodePlex Tools |
    Export Version History To Excel |
    Autocomplete Lookup Field

  • How do I change the name property of a file in a document library?

    I am trying to come up with an Event Receiver that will change the name property of an file when it is uploaded. For instance when a file is uploaded into a document Library, currently the Title is being generated (which is fine)...I want to be able to
    change the "Name" property from whatever it is, to match exactly what is in the "Title" property. Are there any sample codes/blogs out there that I can take a look at? Has anyone  had any experience doing this? It seems like something
    that should be straight forward, to change the "Name" property to match what is in the "Tilte" property.

    Hi,     
    You can try the code below which use the SPFile.MoveTo() function to change the name of the file.
    EventFiringEnabled = false;
    SPFile f = properties.ListItem.File;
    string spfileExt = new FileInfo(f.Name).Extension;
    f.MoveTo(properties.ListItem.ParentList.RootFolder.Url +
    "/" + properties.ListItem["Title"]+ "_new" + spfileExt);
    f.Update();
    EventFiringEnabled = true;
    Here is a similar thread for your reference:
    http://social.technet.microsoft.com/Forums/sharepoint/en-US/5cafb8e4-bb85-4147-9bda-4ab42a4d4817/sharepoint-2013-event-receiver-to-rename-files-not-working?forum=sharepointdevelopment
    A link about rename uploaded file using Event Receiver for your reference:
    http://paulgalvinsoldblog.wordpress.com/2008/01/25/quick-easy-rename-uploaded-file-using-sharepoint-object-model-via-an-event-receiver/
    Best regards
    Patrick Liang
    TechNet Community Support

  • Is it possible Encrypt files in document library after uploading OOB

    Is it possible Encrypt files in document library after uploading using  OOB?
    if so please share how the above can be achieved.
    V Jean

    hi
    there is no easy OTB mechanism for that. The most closer OTB functionality is Rights Management Services (see
    e.g. Plan Information Rights Management), which seems like can be used for configuring policy for data encryption, like mentioned in the following forum thread:
    How to Encrypt SharePoint data. Also you may use the following methods to make file upload safer:
    1. use https instead of http
    2. use Sharepoint rights system in order to restrict access to the uploaded documents to only allowed persons (e.g. you may use unique permissions on the doclib level or on file level)
    3. if encryption is crucial and you don't want to enable it to all doclibs via RMS, you may use custom solution via event receivers: during file upload it may encypt it by using some standard encryption algorithm (see
    Which built-in .NET cryptography algorithm is the most secure).
    Blog - http://sadomovalex.blogspot.com
    Dynamic CAML queries via C# - http://camlex.codeplex.com

  • How to move a document to a particular document library after workflow review and approval

    Hello ,
    I want to do a work flow for a document review and its approval, if the document is approved
    then it should be moved to a document library called "Approved Documents". I have done
    following steps but don't know how to move the document to another document library.
    Library > Library settings > Add a work flow
    > customized Three state work flow
    and it is generating work flow review emails but don't know how to move the document
    somebody please help how to do this????

    You can either create another SPD workflow which will run on item changed event. This workflow will check if the document status is approved and if it approved it moved document to different library. SharePoint designer does have an activity to move list
    items.
    SharePoint Designer workflow: Move a document from one library to another
    Or you can write an event receiver which will get triggered on ItemUpdated and again if the status of the document is approved it will move your document to destination library.
    Writing an event receiver will require custom coding as oppose to SPD approach.
    Amit

Maybe you are looking for

  • All Photos Missing!

    I just upgraded to a new iMac. My entire iphoto library was transfered. Initially all photos appeared but they are now missing. The photo count still shows 3748 photos but they will not open. If I click on a photo thumbnail or event all I see is a la

  • My itunes 11 keeps freexing

    hi since i have upgraded to itunes version 11 it keeps freezing on me all the time,ive un installed and reinstalled 5 times now and its still the same? it was working fine untill i got the new version i run windows 7 at the moment PLEASE HELP ME aaaa

  • Generating large amounts of XML without running out of memory

    Hi there, I need some advice from the experienced xdb users around here. I´m trying to map large amounts of data inside the DB (Oracle 11.2.0.1.0) and by large I mean files up to several GB. I compared the "low level" mapping via PL/SQL in combinatio

  • Urgent : How to manage language translation in BSP iViews

    Hi All, I am required to maintain my Poratl in bi-lingual ie (German and English) language. Now my Portal has got BSP  iViews. Through OTR I can maintain both English and German texts for translation in the BSP application. When one logs in through R

  • Wots the best method to distort text

    I have a job to do that involves touching up text on 100 shots of medicine bottles. What I need to do is replace text on the label with new text but I need to make sure the text compresses the further it wraps around the bottle and away from the came