Using script to delete list item attachment

$.ajax({
url: "/_api/lists/getByTitle('Test')/getItemById(1)/AttachmentFiles/getByFileName('test.txt')",
method: 'DELETE',
headers: {
'X-RequestDigest': $('#__REQUESTDIGEST').val()
i want to delete list item attachment using script.
Above code working only in ie
in firefox and chrome it fails
Any sugestion clads

working fine when i degug the script...

Similar Messages

  • Copy List Item Attachment for archiving using SharePoint Designer 2013

    hi,
    how to Copy List Item Attachment for archiving using SharePoint Designer 2013

    1. You can use access:
    http://viziblr.com/news/2011/11/5/batch-exporting-sharepoint-2010-list-item-attachments-using.html
    Or you can try below script
    You can loop through each list item, and get each attachment.
    List<SPAttachment> attachments = new List<SPAttachment>();
    SPList list = SPContext.Current.Web.Lists["My List"];
    foreach (SPListItem item in list.Items)
    attachments.AddRange(item.Attachments.Cast<SPAttachment>());
    If this helped you resolve your issue, please mark it Answered

  • Convert list item attachment from docx to pdf using Word Automation Services

    I have been trying to convert List Item attachments from docx to pdf using word automation services, it works in a normal document library but when I use the list attachment it throws a null reference error.
    var settings = new ConversionJobSettings();
    settings.OutputFormat = Microsoft.Office.Word.Server.Conversions.SaveFormat.PDF;
    var conversion = new ConversionJob("Word Automation Services", settings);
    conversion.UserToken = SPContext.Current.Site.UserToken;
    var wordFile = SPContext.Current.Site.RootWeb.Url + "/" + wordForm.Url;
    var pdfFile = wordFile.Replace(".docx", ".pdf");
    conversion.AddFile(wordFile, pdfFile);
    conversion.Start();
    Using reflector I was able to see my problem lies in Microsoft.Office.Word.Server.FolderIterator.cs where it uses SPFile.Item which returns NULL
    internal void CheckSingleItem(SPFile inputFile, SPFile outputFile)
    Microsoft.Office.Word.Server.Log.TraceTag(0x67337931, Microsoft.Office.Word.Server.Log.Category.ObjectModel, Microsoft.Office.Word.Server.Log.Level.Verbose, "OM: FolderIterator start a single item: source='{0}'; dest='{1}'", new object[] { inputFile.Url, outputFile.Url });
    Stopwatch stopwatch = Microsoft.Office.Word.Server.Log.StartPerfStopwatch();
    try
    this.CheckInputFile(inputFile.Item);
    this.CheckOutputFile(outputFile.Url);
    Is there any way to get around this?

    Hi Qfroth,
    According to your description, my understanding is that when you use word automation service to convert Word to PDF for list item attachment, it throws the null reference error.
    I suggest you can create an event receiver and convert the word to memory stream like below:
    private byte[] ConvertWordToPDF(SPFile spFile, SPUserToken usrToken)
    byte[] result = null;
    try
    using (Stream read = spFile.OpenBinaryStream())
    using (MemoryStream write = new MemoryStream())
    // Initialise Word Automation Service
    SyncConverter sc = new SyncConverter(WORD_AUTOMATION_SERVICE);
    sc.UserToken = usrToken;
    sc.Settings.UpdateFields = true;
    sc.Settings.OutputFormat = SaveFormat.PDF;
    // Convert to PDF
    ConversionItemInfo info = sc.Convert(read, write);
    if (info.Succeeded)
    result = write.ToArray();
    catch (Exception ex)
    // Do your error management here.
    return result;
    Here is a detailed code demo for your reference:
    Word to PDF Conversion using Word Automation Service
    Best Regards
    Zhengyu Guo
    TechNet Community Support

  • Moving a List Item attachment from one list to another

    Hi,
    What are the best way of coping / moving the List Item attachment using
    jQuery / JavaScript in SharePoint 2013 from one list to another.
    Thanks
    Saroj
    Impossible is nth but good coding :-)

    For your needs better try to code your own solution. See
    SharePoint JavaScript Class Library for details. You can have two possible architectures:
    Make all work from JavaScript. And the first your step will be
    addItem method of SP.List.
    Make processing of selection on client in JavaScript and call your custom server-side component (may be an application page) for items copying (creating copies in new list of already existed items from initial list.). See
    this for example.
    Also be careful with context.load. It's recommended to write all next code in context.executeQueryAsync. Use Firebug in FF and developer tools in Chrome for debugging your code and to find what is wrong.
    Or 
    https://social.msdn.microsoft.com/Forums/sharepoint/en-US/1d01a48f-c28b-467b-acd1-22e5fb266670/how-to-retrieve-list-items-and-copy-it-to-other-list-using-javascript-object-model?forum=sharepointdevelopmentprevious
    <script type="text/javascript">
    ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
    var siteUrl = 'Site Url';
    function retrieveListItems() {
    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('List1');
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
    '<Value Type=\'Number\'>1</Value></Geq></Where></Query><RowLimit>10</RowLimit></View>');
    this.collListItem = oList.getItems(camlQuery);
    clientContext.load(collListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    function onQuerySucceeded(sender, args) {
    var listItemInfo = '';
    var listItemEnumerator = collListItem.getEnumerator();
    while (listItemEnumerator.moveNext()) {
    var objListItem = listItemEnumerator.get_current();
    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('List2');
    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);
    oListItem.set_item('Title', objListItem.get_item('Title'));
    oListItem.update();
    clientContext.load(oListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceededFinal), Function.createDelegate(this, this.onQueryFailed));
    function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    function onQuerySucceededFinal(sender, args) {
    //Do next set of operation if needed
    </script><input name="btnVarIQReject" onclick="retrieveListItems()" type="button" value="Submit"/>
    Please use my above POC code to start. This will copy all the title field value from list1 to list2
    If this helped you resolve your issue, please mark it Answered

  • Invalid data has been used to update the list item. The field you are trying to update may be read only.

    Trying to follow Serge Luca's Step by Step Tutorial. Creating Workflows for Windows Sharepoint Services and MOSS2007.  http://sergeluca.spaces.live.com/blog/cns!E8A06D5F2F585013!859.entry
    I have an onWorkflowActivated, followed by an ifElse condition and a log to history.
    In the IfElse, each branch has a code segment, that trys to update the status column in the list that the workflow is attached to.
    private void Authorize_ExecuteCode(object sender, EventArgs e)
    // tried serveral methods
    WorkflowProperties.Item["Status"] = "Automatically Approved";
    // tried all of the following (one at a time)
    item.update();
    WorkflowProperties.Item.Update();
    WorkflowProperties.Item.SystemUpdate();
    //tried this as well.
    Microsoft.SharePoint.SPListItem item = WorkflowProperties.Item;
    item["Status"] = "Automatically Approved";
    item.Update() ;
    On the update call I keep getting "Invalid data has been used to update the list item. The field you are trying to update may be read only."
    Could someone explain how to update "Status" column of the list item that the workflow is working on?
    Thank you very much.
    Bill
     

    Hi:
    you can do the following:
    add the following code to the workflow.xml file (under the MetaData section)
    Code Snippet
    <ExtendedStatusColumnValues>
    <StatusColumnValue>Branch1</StatusColumnValue>
    <StatusColumnValue>Branch2</StatusColumnValue>
    </ExtendedStatusColumnValues>
    then add 2 SetState activities one in each branch of the IfElse.
    for the code behind of setState1 (branch1) write the following code:
    Code Snippet
    state = Convert.ToInt32(SPWorkflowStatus.Max);
    for setState2 (branch2) write the following:
    Code Snippet
    state = Convert.ToInt32(SPWorkflowStatus.Max) + 1;
    where state is the variable assigned to the field State in the properties of the SetState(design lever), or instead of state u can use the following code:
    Code Snippet
    ((SetState)sender).State
    where sender is the object sent through the function parameter.
    hope this answered your question
    Best Regards

  • WebPart is raising the following error "Invalid data has been used to update the list item.The field you are trying to update may be read only"

    I have created a farm solution and then i deploy it to SharePoint server, the code looks as follow, and i use it to update a page info values (as the current page values represents old info):-
    [ToolboxItemAttribute(false)]
    public partial class VisualWebPart1 : WebPart
    // Uncomment the following SecurityPermission attribute only when doing Performance Profiling using
    // the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
    // for production. Because the SecurityPermission attribute bypasses the security check for callers of
    // your constructor, it's not recommended for production purposes.
    // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
    public VisualWebPart1()
    protected override void OnInit(EventArgs e)
    base.OnInit(e);
    InitializeControl();
    using (SPSite site = new SPSite(SPContext.Current.Site.Url))
    using (SPWeb web = site.OpenWeb())
    SPList list = web.Lists["Pages"];
    web.AllowUnsafeUpdates = true;
    foreach (SPListItem items in list.Items)
    items["Author"] = "SharePoint";
    items["Created"] = "01/08/2014 01:44 PM";
    items.Update();
    list.Update();
    web.AllowUnsafeUpdates = false;
    protected void Page_Load(object sender, EventArgs e)
    but when i try adding this web part to a page i got the following error:-
    Invalid data has been used to update the list item.The field you are trying to update may be read only
    so can anyone advice?

    i only changed lines bitween 
    web.AllowUnsafeUpdates = true;
    and
    web.AllowUnsafeUpdates = false;
    and other parts of code remains without change
    so it will updates all pages in current web
    yaşamak bir eylemdir

  • Invalid data has been used to update the list item. The field you are trying to update may be read only (Lookup Field).

    Hi.
    I am getting below error while adding value to look-up field.
    Invalid data has been used to update the list item. The field you are trying to update may be read only.
    I have tried many forums ans post but didn't come to know what's the root cause of issue. I am also posting Code for creating and adding lookup field.
    CAML to create lookup field (It works Fine)
    string lkproductNumber = "<Field Type='Lookup' DisplayName='Product Number' StaticName='ProductNumber' ReadOnly='FALSE' List='" + pNewMaster.Id + "' ShowField='Product_x0020_Number' />";
    Code to insert value to lookup field
    ClientContext client = new ClientContext(SiteUrl);
    client.Load(client.Web);
    client.Credentials = new NetworkCredential(this.UserName, this.Password, this.Domain);
    // Lookup Lists
    List pmList = client.Web.Lists.GetByTitle("Product_Master");
    //List Conatining Lookup Columns
    List piList = client.Web.Lists.GetByTitle("Product_Inventory");
    client.Load(piList);
    query.ViewXml = "<View/>";
    ListItemCollection collection = pmList.GetItems(query);
    client.Load(collection);
    client.ExecuteQuery();
    int prodid=0;
    foreach (ListItem item in collection)
    if (Convert.ToString(item["Product_x0020_Number"]) == ProductNumber)
    { prodid = Convert.ToInt32(item["ID"]); }
    ListItem piItem = piList.AddItem(new ListItemCreationInformation());
    piItem["Product_x0020_Number"] = new FieldLookupValue() { LookupId = prodid };
    piItem.Update();
    client.ExecuteQuery();
    Exception Detail
    Microsoft.SharePoint.Client.ServerException was caught
    Message=Invalid data has been used to update the list item. The field you are trying to update may be read only.
    Source=Microsoft.SharePoint.Client.Runtime
    ServerErrorCode=-2147352571
    ServerErrorTypeName=Microsoft.SharePoint.SPException
    ServerStackTrace=""
    StackTrace:
    at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream responseStream)
    at Microsoft.SharePoint.Client.ClientRequest.ProcessResponse()
    at WebServiceProviders.ClientServices.NewProductInventory() in Z:\.............ClientServices.cs:line 889
    InnerException:
    Quick response is highly appreciated.
    Thanks
    Mehar

    Try some thing like below,
    your data value that needs to be update should be in this format "ID of the lookup";#"Title of the Lookup" 
    For example,
    listItem["Product_x0020_Number"]
    = "1;#iPhone";
    listItem["Product_x0020_Number"]
    = "2;#Mobile";
    Hope this helped you....

  • How to insert sharepoint list item attachment to sql server db programatically

    Hi,
    I need to insert sharepoint list item attachments to sql server db programatically. Could some one suggest some approach and if any one work on it please provide the code. Thanks in advance

    hi,
    you can do it using powershell. Use the below script to loop through all the items attachments inside list.
    $web = $site.RootWeb<br />
    $Lists = $Web.Lists[$ListName]
    $Library = $web.Lists[$LibName]
    foreach($listItem in $Lists.Items)
    if($listItem.Attachments.Count -gt 0)
    Write-Host "**************************************************"
    Write-Host $listItem.Attachments.Count"Attachment(s) available in the ListItem:" $listItem.Title
    Write-Host "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    $i=0
    foreach($attachment in $listItem.Attachments)<br />
    $i++
    Write-Host $i".Attachment Name:" $listItem.Attachments.UrlPrefix$attachment
    $file = $web.GetFile($listItem.Attachments.UrlPrefix+$attachment)
    Write-Host "Adding Files to Library:"$Library.Title
    $bytes = $file.OpenBinary()
    Write-Host "Successfully Added"<br /> Write-Host "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    Write-Host "**************************************************"
    And use the below script to insert into SQL.
    #Connect to DB
    $DB = “server=MyInstanceName;integrated security=sspi;database=Bob”
    $conn = new-object System.Data.SqlClient.SqlConnection($DB)
    #Build the command and parameters
    $cmd = New-Object System.Data.SQLClient.SQLCommand
    $cmd.CommandType = [System.Data.CommandType]‘StoredProcedure‘
    $cmd.Parameters.Add(“@Col1″, [System.Data.SqlDbType]‘VarBinary‘)
    $cmd.Parameters[“@Col1″].Size = -1
    $cmd.Parameters[“@Col1″].Value = $bytes
    $sql = "INSERT INTO <table> (Col1) VALUES " + $cmd.Parameters[“@Col1″]
    #Execute the command
    $conn.Open()
    $cmd.ExecuteNonQuery()
    P.S. There may be some syntax error you have to make it work but the concept is right.
    Whenever you see a reply and if you think is helpful,Vote As Helpful! And whenever you see a reply being an answer to the question of the thread, click Mark As Answer

  • How to download list item attachment from display.aspx

    Im uploading documents
    to list item in list by
    using file upload control. Now I should download that file. I can able to insert documents into list item in attachment column which is predefined but am how can I download the attachments by clicking on the link in display.aspx.
    I have written this for uploadFile controller.
    SPSite site = SPContext.Current.Site;
    SPWeb web = site.OpenWeb();
    SPList list = web.Lists["list2"];
    //SPListItem itemId = list.GetItemById(5);
    int itemId=3;
    SPListItem newItem = list.GetItemById(itemId);
    byte[] contents = null;
    if (FileUpload1.PostedFile != null && FileUpload1.HasFile)
    using (Stream fileStream = FileUpload1.PostedFile.InputStream)
    contents = new byte[fileStream.Length];
    fileStream.Read(contents, 0, (int)fileStream.Length);
    fileStream.Close();
    SPAttachmentCollection attachments = newItem.Attachments;
    string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
    attachments.Add(fileName, contents);
    newItem["CLMSAttachments"] = fileName;
    newItem.Update();
    Thanks in advance.

    Hi ,
    It is your browser that decides to download/open the file.
    If you have compatible client software for the file (word for docx) your computer will by default automatically try to open it.
    But we can force the download. You have to develop a handler/aspx page that will just handle the file download and you have to override the http header "content-disposition" to "attachment;filename=yourfilename"
    Here a sample :
    var fileName = "myfile.sql";
    var r = context.Response;
    r.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
    r.ContentType = "text/plain";
    r.WriteFile(context.Server.MapPath(fileName));
    Hope that will help you
    Moudhafer

  • Error while deleting list item 0x80131904 com exception in sp 2010

    We are getting below error on production server,on development and test server its working fine.There is Application page to fill employee goals for appraisal,when user tries to save in draft they are experiencing issue that goals are deleting and not save.when
    we check in production log we are getting 'COMException'   
    ExceptionMessage: '<nativehr>0x80131904</nativehr><nativestack></nativestack>' .
    01/21/2014 18:57:05.26  w3wp.exe (0x3D98)       
    0x29FC  VFS Performance Management Syst      
    PMS Error           
    9999               
    Unexpected       Error in PMS H2 Self Evaluation  
    ExceptionType: 'SPException'   ExceptionMessage: ''  
    StackTrace: '   at Microsoft.SharePoint.SPGlobal.HandleComException(COMException comEx)      
    at Microsoft.SharePoint.Library.SPRequest.DeleteItem(String bstrUrl, String bstrListName, Int32 lID, UInt32 dwDeleteOp, Guid& pgDeleteTransactionId)      
    at Microsoft.SharePoint.SPListItem.DeleteCore(DeleteOp deleteOp)      
    at Microsoft.SharePoint.SPListItem.Delete()      
    at VFS.PMS.ApplicationPages.CommonMaster.DeleteCompetenciesDraft(Int32 appraisalPhaseId, String currentUser, String listName)      
    at VFS.PMS.ApplicationPages.Layouts.H2initial.SelfEve.SaveCompetenciesDraft(Int32 appraisalID, Int32 appraisalPhaseId, String listName)      
    at VFS.PMS.ApplicationPages.Layouts.H2initial.SelfEve.<btnSave_Click>b__0()      
    at Microsoft.SharePoint.SPSecurity.<>c__DisplayClass4.<RunWithElevatedPrivileges>b__2()      
    at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)      
    at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param)      
    at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode)      
    at VFS.PMS.ApplicationPages.Layouts.H2initial.SelfEve.btnSave_Click(Object sender, EventArgs e)'  
    Source: 'Microsoft.SharePoint'   TargetSite: 'Void HandleComException(System.Runtime.InteropServices.COMException)'  
    Inner exception:   ------------------------------------------------------------   
    ExceptionType: 'COMException'    ExceptionMessage: '<nativehr>0x80131904</nativehr><nativestack></nativestack>'   
    StackTrace: '   at Microsoft.SharePoint.Library.SPRequestInternalClass.DeleteItem(String bstrUrl, String bstrListName, Int32 lID, UInt32 dwDeleteOp, Guid& pgDeleteTransactionId)       
    at Microsoft.SharePoint.Library.SPRequest.DeleteItem(String bstrUrl, String bstrListName, Int32 lID, UInt32 dwDeleteOp, Guid& pgDeleteTransactionId)'   
    Source: ''    TargetSite: 'Void DeleteItem(System.String, System.String, Int32, UInt32, System.Guid ByRef)'   
    8f922003-389d-4edf-b75f-7e69c5818a7a              

    Hi,
    According to your post, my understanding is that you got ‘0x80131904’ error on production server.
    The issue was caused by mismatched versions between the SQL Server and SharePoint.
    In order to get the database stored procs up to the right version, the Database needs to be connected before the upgrade.
    In addtion, you can install august 2011 CU patch:
    http://support.microsoft.com/kb/2553048/en-us
    Here is a similar thread for you to take a look at:
    http://social.technet.microsoft.com/Forums/en-US/9f1349b9-d8fa-4cfd-88e5-f24d67646c4e/error-exception-from-hresult-0x80131904-when-deleting-an-item-from-a-list?forum=sharepointgeneralprevious
    Best Regards,
    Linda Li
    Linda Li
    TechNet Community Support

  • "SharePoint list itme update error : Invalid data has been used to update the list item. The field you are trying to update may be read only."

    Hi Everyone,
    i am facing one problem ...
    when i am updating an SharePoint List item, it is throwing above error....
    This is my code......
     try
                    tbl = getListDateTable("NCR");
                    DataTable dt = tbl;
                    oWebsite = mysite.OpenWeb();
                    oList = oWebsite.Lists["NCR"];
                    SPListItem itemToUpdate = null;
                    foreach (SPListItem listItem in oList.Items)
                        listItem.Update();
                        workOrderID = Convert.ToInt32(txtTitle.Text);
                        itemToUpdate = listItem;
                    //SPListItem itemToUpdate = oList.GetItemById(workOrderID);
                    //itemToUpdate.Fields["Title"].ReadOnlyField = false;
                    //string str = ddlStatus.SelectedValue;
                    itemToUpdate["Title"] = txtTitle.Text;
                    itemToUpdate["JobNumber"] = txtJobNumber.Text;
                    itemToUpdate["PartNumber"] = txtPartNumber.Text;
                    itemToUpdate["PartDescription"] = txtPartDescription.Text;
                    //itemToUpdate["RequiredBy"] = txtRequiredBy.Text;
                    itemToUpdate["ReportedBy"] = txtReportedBy.Text;
                    itemToUpdate["WrittenBy"] = txtWrittenBy.Text;
                    //itemToUpdate["DateOpened"] = txtDateOpened.SelectedDate;
                    //itemToUpdate["DateClosed"] = txtDateClosed.SelectedDate;
                    itemToUpdate.Update();
                    oList.Update();
                   // bind();
                catch (Exception ex)
                    throw ex;
    Thanks
    viswanath

    Hi Viswanath,
    If you are using People/User Type Field Column then use below code methord
    SPUser user = web.EnsureUser(loginName);
    item["UserTypeFieldName"] = user;
    Lookup Type Field Column then use below code methord
    public static SPFieldLookupValue GetLookupFieldFromValue(string lookupValue,string lookupSourceColumn, SPList lookupSourceList)
    SPFieldLookupValue value = null;
    SPQuery query = new SPQuery();
    query.Query = "<Where><Eq><FieldRef Name='" + lookupSourceColumn + "'/><Value Type='Text'>" + lookupValue + "</Value></Eq></Where>";
    SPListItemCollection listItems = lookupSourceList.GetItems(query);
    if(listItems.Count > 0 )
    value = new SPFieldLookupValue(listItems[0].ID,lookupValue);
    return value;
    item["LookupField"] = GetLookupFieldFromValue(lookupfieldValue, lookupSourceColumn, listName);
    Please mark the replies as answers if they help or unmark if not.

  • How to Copy list item attachment to document library in SharePoint 2010

    Hi,
    How to Create a folder ("List Item - Title Name") in Document library and copy list items Attachments to the same folder in SharePoint 2010,thanks in advance.
    Regards,
    Selvan.J
    Selvan J

    Hi,
    You should first check whether the folder exists in the library, if the folder not exists, then create it.
    I had modified the code, you can use the following code snippet to achieve it.
    private void EventCopyFileWhenItemCreatedOrUpdated(SPItemEventProperties properties)
    SPSite site = new SPSite(http://YourSiteName);
    SPWeb web = site.OpenWeb();
    SPList doclibList=properties.Web.Lists["YourLibName"];
    bool foundFolder = false;
    if (doclibList.Folders.Count>0)
    foreach (SPListItem fitem in doclibList.Folders)
    if (fitem.Title.Equals("FolderA"))
    foundFolder = true;
    break;
    if (foundFolder == false)
    SPListItem folder = doclibList.Folders.Add(doclibList.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder,"FolderA");
    folder.Update();
    string fUrl = doclibList.RootFolder.ServerRelativeUrl+"/FolderA";
    SPFolder myLibrary = web.GetFolder(fUrl);
    if (properties.ListTitle == "YourListName")
    SPListItem sourceItem = properties.ListItem;
    properties.Web.AllowUnsafeUpdates = true;
    //get the folder with the attachments for the source item
    SPFolder sourceItemAttachmentsFolder =
    sourceItem.Web.Folders["Lists"].SubFolders[sourceItem.ParentList.Title].SubFolders["Attachments"].SubFolders[sourceItem.ID.ToString()];
    //Loop over the attachments, and add them to the target item
    foreach (SPFile file in sourceItemAttachmentsFolder.Files)
    if (CheckFileNameExist(file.Name , properties) == false)
    byte[] binFile = file.OpenBinary();
    myLibrary.Files.Add(System.IO.Path.GetFileName(file.Url) , binFile);
    private bool CheckFileNameExist(string fileNameInFileAttach, SPItemEventProperties properties)
    bool flag = false;
    SPList myDocumentLib = properties.Web.Lists["YourLibName"];
    SPQuery spQuery = new SPQuery();
    SPListItemCollection items = myDocumentLib.GetItems(spQuery);
    foreach (SPListItem item in items)
    if (fileNameInFileAttach == item["Name"].ToString())
    flag = true;
    break;
    return flag;
    Thanks & Regards,
    Jason
    Jason Guo
    TechNet Community Support

  • Use paging in Sharepoint List items

    Hi ,
    I am having one sharepoint 2013 . I have written the code to read sharepoint custom list item using C# and Jquery both ..My List is having 5000+ items into list ,and when I am binding those records into my Gridview It is taking time to bind the data
    into Gridview. I am using Paging of 10 items per page ..still I am facing performance issues .. 
    Could any one help me on same ... 
    Thanks..

    Hi,
    For your issue, you can use SPListItemCollectionPosition in your GridView and query page by page:
    http://sharepoint.infoyen.com/2012/03/06/sharepoint-list-pagination-using-splistitemcollectionposition/
    http://www.codeproject.com/Articles/407558/SharePoint-using-SPListItemCollectionPosition
    Best Regards,
    Eric
    Eric Tao
    TechNet Community Support

  • How can I use script change long list format?

    Hi everyone
    If I have this kind of long list
    0101
    Long white radish
    Chinese Celery
    Tah tsai
    Round cucumber
    Cherry radish
    fennel
    Small-leaf arugula
    Small wax gourd
    0102
    Green-leaf Lettuce
    Broad-leaf arugula
    UFO squash
    Crystal radish
    Red wave lettuce
    Green endive
    Sponge gourd
    Rose-heart radish
    Butter head lettuce
    Radicchio
    0103
    Chinese mustard
    New Zealand spinach
    Yellow summer squash
    Turnip
    Malabar spinach
    Chinese kale
    Green bean
    Edible rape
    Begonia fimbristipulata hance
    Purple bean
    Cabbage
    Water Spinach
    Okra
    Snow peas
    How can I change the format into this:
    0101
    0101/Long white radish
    0101/Chinese Celery
    0101/Tah tsai
    0101/Round cucumber
    0101/Cherry radish
    0101/fennel
    0101/Small-leaf arugula
    0101/Small wax gourd
    0102
    0102/Green-leaf Lettuce
    0102/Broad-leaf arugula
    0102/UFO squash
    0102/Crystal radish
    0102/Red wave lettuce
    0102/Green endive
    0102/Sponge gourd
    0102/Rose-heart radish
    0102/Butter head lettuce
    0102/Radicchio
    0103
    0103/Chinese mustard
    0103/New Zealand spinach
    0103/Yellow summer squash
    0103/Turnip
    0103/Malabar spinach
    0103/Chinese kale
    0103/Green bean
    0103/Edible rape
    0103/Begonia fimbristipulata hance
    0103/Purple bean
    0103/Cabbage
    0103/Water Spinach
    0103/Okra
    0103/Snow peas
    by useing script?
    thanks
    Teetan

    Hi,
    Perhaps not a problem, try this code ...
    var myFolder=Folder("~/Documents");
    var sourceFile = new File(myFolder + "/"+"sourceFile.txt");
    var logFile = new File(myFolder + "/"+"logFile.txt");
    //var elementList = Array('0101','Long white radish','Chinese Celery','Tah tsai','Round cucumber','Cherry radish','fennel','Small-leaf arugula','Small wax gourd','0102','Green-leaf Lettuce','Broad-leaf arugula','UFO squash','Crystal radish','Red wave lettuce','Green endive','Sponge gourd','Rose-heart radish','Butter head lettuce','Radicchio','0103','Chinese mustard','New Zealand spinach','Yellow summer squash','Turnip','Malabar spinach','Chinese kale','Green bean','Edible rape','Begonia fimbristipulata hance','Purple bean','Cabbage','Water Spinach','Okra','Snow peas')
    //var newElementList = new Array;
    var myPattern = new RegExp("^\\d{4,4}$");
    var myPrefix="";
    if (sourceFile.exists){sourceFile.open( 'r' );
    while( !sourceFile.eof ) {
              var aElement  = sourceFile.readln();
              if (myPattern.test(aElement)){
                  //newElementList.push(aElement);
                  myPrefix = aElement + "/";
                  writeLogFile(aElement)
              } else {
                   //newElementList.push(myPrefix+ aElement);
                   writeLogFile(myPrefix+ aElement)
        //$.write(newElementList);
    function writeLogFile(theString) {
        logFile.open( "a" );
        logFile.writeln(theString);
        logFile.close();   

  • Not able to delete line items using BAPI_OUTB_DELIVERY_CHANGE

    Hi,
        Not able to delete line items of a delivery using BAPI 'BAPI_OUTB_DELIVERY_CHANGE', with thte below code and even return parameter has zero messages.
    I have even checked existing below posting.
    https://www.sdn.sap.com/irj/scn/logon?redirect=http%3a%2f%2fforums.sdn.sap.com%2fthread.jspa%3fthreadid%3d782509
    Below is the code that i am using.........
    *wa1-deliv_numb = wa_lips-vbeln.
    wa1-deliv_item = wa_lips-posnr.
    APPEND wa1 to item_data.
    wa-deliv_numb = vbeln_so .
    wa-deliv_item = l_item.
    wa-del_item = 'X'.
    APPEND wa TO item_control.
    w_header_data-deliv_numb = vbeln_so .
    w_header_control-deliv_numb = vbeln_so .
    w_delivery = vbeln_so .
    *w_header_control-dlv_del = 'X'. "Delete whole Delivery
    CALL FUNCTION 'BAPI_OUTB_DELIVERY_CHANGE'
      EXPORTING
        header_data    = w_header_data
        header_control = w_header_control
        delivery       = w_delivery
      TABLES
       item_data      = item_data
        item_control   = item_control
        return         = return.
      CALL FUNCTION 'BAPI_TRANSACTION_COMMIT'
        EXPORTING
          wait = 'X'.
    I have even  tried uncommenting item_data parameter but not able to delete line item.....i am able to delete whole delivery but not line items .........can any one of u help me in resolving this issiue plz ???
    Regards,
    M, Manohar

    Kindly use WS_DELIVERY_UPDATE to delete the items
    Sample code:
    L_VBKOK-VBELN_VL = vbeln_so.
    clear l_vbpok.
             refresh l_vbpok.
             l_vbpok-vbeln_vl = vbeln_so
             l_vbpok-posnr_vl = wa_deliv_item.
             l_vbpok-lips_del = c_x.
             append l_vbpok.
             set update task local.
             call function 'WS_DELIVERY_UPDATE'
               exporting
                 vbkok_wa = l_vbkok
                 commit   = ' '
                 delivery = lv_delivery
               tables
                 vbpok_tab = l_vbpok
               exceptions
                 others   = 0.
             commit work and wait.

Maybe you are looking for