Pages

Saturday, August 8, 2009

How to attach/delete/upload files to SharePoint List Item using Object Model

Hello Friends

I have one requirement in which I need to develop a web part in which users can upload multiple documents to SharePoint List Item and they can see all uploaded files into data grid control, they also need facility for user to delete selected files, add new files from same control and also they can download files.

Here in this post, I am writing code for each functionality as per my requirements.

Snippet code of deleting attachment from SharePoint list item :

private void DeleteAttachment(int NodeID, String strFileName)
    {
        try
        {
            SPContext.Current.Web.AllowUnsafeUpdates = true;

            SPListItem delItem = lstAudit.GetItemById(NodeID);
            SPAttachmentCollection atCol = delItem.Attachments;
            foreach (string strDelfileName in atCol)
            {
                if (strDelfileName == strFileName)
                {
                    atCol.Delete(strDelfileName);
                    delItem.Update();
                    lstAudit.Update();

                    return;
                }
            }

        }
        catch (Exception eDel)
        {
            string errDel = eDel.Message;
        }
    }
   

Snippet code for downloading attachment from SharePoint List Item :

 private void DownloadAttachment(string FileName)
    {
        try
        {
            string AttachmentURL = string.Empty;
            AttachmentURL = FileName;
            string strName = AttachmentURL.Substring(AttachmentURL.LastIndexOf("/") + 1);
            string sbURL = AttachmentURL.Trim();
            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
            Response.AppendHeader("Content-disposition", "attachment; filename=" + strName);
            Response.AppendHeader("Pragma", "cache");
            Response.AppendHeader("Cache-control", "private");
            Response.WriteFile(sbURL);
            Response.End();
        }
        catch (Exception eDwn)
        {
            Response.Write(eDwn.Message);
        }
    }

Snippet code of uploading document to SharePoint List Item :

 protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            string fileName = "";
            string strExtensionName = "";

            fileName = System.IO.Path.GetFileName(FileUpload.PostedFile.FileName);

            if (fileName != "")
            {
                strExtensionName = fileName.Substring(fileName.IndexOf(".") + 1);
                if (strExtensionName.Equals("webpart") || strExtensionName.Equals("dll") || strExtensionName.Equals("bat") || strExtensionName.Equals("exe"))
                {
                    lblMessage.Visible = true;
                    lblMessage.Text = "Invalid fileName!!";
                }
                else
                {
                    string _fileTime = DateTime.Now.ToFileTime().ToString();

                    string _fileorgPath = System.IO.Path.GetFullPath(FileUpload.PostedFile.FileName);

                    if (txtFileName.Text.Trim().Length > 0)
                    {
                        fileName = fileName.Replace(fileName.Substring(fileName.LastIndexOf("\\") + 1), txtFileName.Text) + "." + strExtensionName;
                    }
                    string _newfilePath = _fileTime + "~" + fileName;

                    string tempFolder = Environment.GetEnvironmentVariable("TEMP");

                   
                    string _filepath = tempFolder + _newfilePath;
                   
                    FileUpload.PostedFile.SaveAs(_filepath);

                    AddRow(fileName, _filepath, 0, true);
                }
            }
            else
            {

                lblMessage.Visible = true;
                lblMessage.Text = "Please Selct file Name";

            }

        }
        catch (Exception Ex)
        {
            Response.Write(Ex.Message);
        }

    }

   
    protected void dgdUpload_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int recordToDelete = e.RowIndex;

        //dt = (DataTable)Page.Session["Files"];
        dt = (DataTable)ViewState["Files"];

        int cn = dt.Rows.Count;

        if (Convert.ToInt32(dt.Rows[recordToDelete].ItemArray[0]) != 0)
        {
            DeleteAttachment(Convert.ToInt32(dt.Rows[recordToDelete].ItemArray[0]), dt.Rows[recordToDelete].ItemArray[1].ToString());
        }

        dt.Rows.RemoveAt(recordToDelete);

        dt.AcceptChanges();
        //Page.Session["Files"] = dt;
        ViewState["Files"] = dt;
        dgdUpload.DataSource = dt;
        dgdUpload.DataBind();
    }
    private void AddMoreColumns()
    {

        dt = new DataTable("Files");

        dc = new DataColumn("ID", Type.GetType("System.Int16"));
        dt.Columns.Add(dc);

        dc = new DataColumn("FileName", Type.GetType("System.String"));
        dt.Columns.Add(dc);

        dc = new DataColumn("FilePath", Type.GetType("System.String"));
        dt.Columns.Add(dc);

        //Page.Session["Files"] = dt;
        ViewState["Files"] = dt;

    }
    private void AddRow(string file, string path, int ID, Boolean bolCheckForfiles)
    {

        Boolean bolAddRow = true;
        //dt = (DataTable)Page.Session["Files"];
        dt = (DataTable)ViewState["Files"];
       
        if (dt == null)
        {
            AddMoreColumns();

        }
        if (bolCheckForfiles)
        {
       
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow drExistingrow in dt.Rows)
                {

                    if (drExistingrow["FileName"].ToString() == file)
                    {
                        bolAddRow = false;
                    }
                }
            }
        }
        if (bolAddRow)
        {

            dr = dt.NewRow();

 

            dr["ID"] = ID;
            dr["FileName"] = file;
            dr["FilePath"] = path;

 

            dt.Rows.Add(dr);

            //Page.Session["Files"] = dt;
            ViewState["Files"] = dt;

            dgdUpload.DataSource = dt;

            dgdUpload.DataBind();//bind in grid

        }
        else
        {
            lblMessage.Visible = true;
            lblMessage.Text = "Same File Name already exists!!!";
        }
    }

   
   

    protected void dgdUpload_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "View")
        {
            string file = e.CommandArgument.ToString();
            DownloadAttachment(file);

        }
    }

 

        if (dt != null)
        {

            int _dtcnt = dt.Rows.Count;
            foreach (DataRow dr in dt.Rows)
            {

                Boolean bolAddAttachment = true;
                fileName = dr["FileName"].ToString();
                if (itmCorrectiveActionFinding.Attachments.Count > 0)
                {
                    foreach (string strAttachedname in itmCorrectiveActionFinding.Attachments)
                    {

                        if (fileName == strAttachedname)
                        {
                            bolAddAttachment = false;

                        }
                    }
                }
                if (bolAddAttachment)
                {
                    string strFilepath = dr["FilePath"].ToString();

                    StreamReader sr = new StreamReader(strFilepath);

                    Stream fStream = sr.BaseStream;

                    contents = new byte[fStream.Length];

                    fStream.Read(contents, 0, (int)fStream.Length);

                    fStream.Close();

                    itmCorrectiveActionFinding.Attachments.Add(fileName, contents);

                    itmCorrectiveActionFinding.Update();
                    lstCorrectiveActionFinding.Update();
                    SPContext.Current.Web.Update();
                    System.IO.File.Delete(strFilepath);

                }
            }
        }

64 comments:

  1. Hi Disha

    This post is good. I'm also working in Sharepoint , I have a requiremnet, we have a webpart for slide show, this webpart takes images from an image list and shows them, now to use this webpart you need to 1> Upload all the images in the image list 2> Select the image list name from the Modify shared webpart dialouge ( we have customized it),we need to develop a sharepoint picker, from which users can upload docs to the list .

    Can you help in this regard.

    Thanks
    Arindam

    ReplyDelete
  2. Hey Arindam,

    Thank you very much for your comment.

    Please let me summarize here to see whether I am following you correctly or not for your requirements, you are saying that you need to develop functionality (SharePoint picker type of thing) from which user can upload documents to your list, and this has to be in your web part only, please correct me if I am wrong here…

    If that’s your case then you can put ASP: File Upload control into your web part and write code on clicking of save button, which will take posted file name and upload same file into document library with the help of SPFile and other classes from SharePoint object model.

    If you are looking for something else then please let me know.

    Thanks,
    Disha Shah

    ReplyDelete
  3. Hi Disha,

    I am very new to Sharepoint and ASP. I'm stuck and am looking all over the net for some help. I am using a Survey web part (I'm assuming it is a webpart that came with Sharepoint vs a web part someone in my organization created). I need functionality that allows the responder to upload an attachment to their survey response. Do you think your code will work in my case by adding it to the form "HEAD"? Or do you think I will need to use the ASP File Upload option?

    If so, I'm certain I will be able to Google it and find something, but if you have first hand experience, I would love to know your approach with specific code samples.

    Thanks in advance.

    ReplyDelete
  4. Carla,

    Thanks for the comments.

    Survey list is a special type of list, which has limited type of features into it, like we can’t add custom columns or manages content type, attach files etc.

    So I prefer to develop Custom field Type. I have developed custom field type which asks from user for country and from country it displays related state names. You can also do same thing, you can create a custom field type which asks from user to upload a document and it uploads that file to document library and stores that path as your field value and then add a new question to survey list which has type of your custom list and you can name it like "Attachment".

    This is the one way. Second way would be to create a new custom list which is not type of survey but try to make custom list same like Survey list. This is easiest way :)

    Hope it will help to you.Thanks,

    Disha Shah

    ReplyDelete
  5. Dear Disha,
    Thank you for this great post.
    I want to ask you abour the variable "txtFileName", what is it and how can I get it?

    ReplyDelete
  6. Hello Nesreen
    “txtFileName” is the Textbox that I have taken for providing the functionality to user, they can provide their own filename into “txtFileName” textbox.

    It means whatever file you have selected by File Upload Control it replaces that filename with name entered into txtFilename textbox.

    Example:
    You have selected "test.txt" from File upload control , but you want to upload that file with different name say "Real.txt" , so you need to specify "Real" in that txtFilename text box

    Hope this helps!!!

    Thanks and Regards
    Disha Shah

    ReplyDelete
  7. Thank you very for the interesting post.

    I have a similar funcationality, but how does your interface look like for add/deleting/uploading mutiple documents?
    Can i search for the documents uploaded in a list item? meaning show me all the listitem which has only this type of download?

    Please share your inputs

    Thanks

    ReplyDelete
  8. I tried your code but when i upload the documents to SP lit, i got access to filepath is denied. i don't find any file in env variable %TEMP% location. Can you point what is going wrong with me. Thanks!

    ReplyDelete
  9. Naren,

    There are many possibilities why you get error "access to file path is denied"
    May be you can try some of the below things.
    1>Check the File Size. If it is more than 50MB Please refer this link to allow users to upload more than 50MB file to SharePoint site.

    http://dishashah.wordpress.com/2009/11/04/how-to-upload-big-size-of-
    documents-to-sharepoint-site/

    2> you do not have permission for file path, may be it refers to "Double Hop" Problem.
    Double Hop -
    The double-hop issue in SharePoint occurs when IIS attempts to pass the user’s NTLM credentials to a service that is running on a server that is either not part of the requesting server’s farm, or not running directly on the web server.

    It’s my wild guess only!

    Thanks,
    Disha Shah

    ReplyDelete
  10. How Can I Upload documents into sharepoint document library with out user interaction. i mean automatically the files should get uploaded into the doc lib from a local hard disk of the server.
    As the situation is critical, Any relevent posts is encouraged.
    Thanks In Advance
    Skamuju

    ReplyDelete
  11. Skamuju

    Yeah, you can do that by creating SharePoint timer job; here are some of the steps to upload the documents from local hard drive to SharePoint document library without user interaction.

    1. Write code which will upload docs into doc lib
    2. Put your code into SharePoint timer job
    3. Configure timer job which will run on specified time
    4. Deploy timer job

    Hope this will help you!

    Disha shah

    ReplyDelete
  12. Hi Disha,

    I think this post is really very good.

    I also work in SharePoint Server and also work in Project Server, Windows Workflow Foundation and runs a SharePointKings blog entierly on SharePoint and WWF.

    I want to know if it is possible to create a custom File Upload field in sharepoint. Can you give me some highlight on this?

    the requirement is, User should be able to upload multiple files at one go in NewForm.aspx and these files should go as a multiple attachments for a single list item.

    Your thoughts appriciated.

    ReplyDelete
  13. Malay,


    Thank you for your comment. It’s good to know about your skill set.
    You can achieve your requirement in this way – you can use out of the box SharePoint Web Controls - Attachment button, Attachment Upload and Attachment field control, you need to write code which will upload all selected files from user to current or particular SharePoint list item, you can put your code into custom ASPX page or custom web part.


    Here is very good link which will explain you how to do above things - step by step.


    http://www.pointsharepoint.com/2008/12/list-attachments-in-webpart-solution.html

    Or you can create your own Custom Field type which allows you to upload multiple attachments

    http://dishashah.wordpress.com/2009/11/05/step-by-step-tutorial-for-how-to-create-and-implement-custom-field-type-in-sharepoint/

    Thanks,
    Disha

    ReplyDelete
  14. Hi,

    I tried to use the download attachment code in a custom webpart, but its throwing so many errors. Please direct me. I am using the above code for an anonmyous user......

    ReplyDelete
  15. Hi Sreeni

    Can you please let me know which kind of errors it is throwing; if it is related to "Access Denied" then you should run your code in SPSecurity.RunWithElevatedPrivileges(delegate() .

    If it is thowing other than that, provide me description of the error so I can redirect what you need to do.

    If you just get one line error message and to get detailed error message please refer this link.
    http://dishashah.wordpress.com/2009/08/08/how-to-display-detailed-error-messages-into-sharepoint-page/

    Thanks
    Disha Shah.

    ReplyDelete
  16. Awesome post..I am going to copy and paste it! Thank u so much

    ReplyDelete
  17. Hi Disha, Thanks for your reply.
    I resolved those errors. Do you have idea of downloading a listitem attachment in anonmyous mode?

    Thanks
    Sreeni

    ReplyDelete
  18. Hi Sreeni

    Yeap, you need to write your download attachment from listItem code under SPSecurity.RunWithElevatedPrivileges(delegate() block.

    This is the link you can refer for that.
    http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx

    Hope this helps!!!

    Thanks
    Disha Shah

    ReplyDelete
  19. You can also impersonate the user so that for the particular code you want to run you can give the permissions..

    Here is the code with explanation
    http://sharepointforums.blogspot.com/2008/10/impersonating-user.html

    ReplyDelete
  20. Hi,
    Thanks. I resolved that issue but another issues came up.
    I am using HTTP context to show File downlaod dialog box, after downloading button events are not working... is there any way to resolve this ...
    I am trying to refresh the page but still not working...

    thanks
    Sreeni

    ReplyDelete
  21. Srini,

    I think the problem you are facing is known issue if you are working with something related to Response or sometime HTTP context Object.

    I have alternative for this – create one separate ASPX page(child page)/web part in which write your server code which will download file on page load, and call this page from main page, I mean create one child page which will have logic for downloading file, and open child page from parent page, so in this way when user clicks on “download attachment icon”, it will open one popup window and it will open respective file and then you have all control on parent page, so all button events will work in parent page.

    Thanks!
    Disha

    ReplyDelete
  22. Hi Disha Shah

    Thank you for your useful posts, I really need your guide. I want to know can we save uploaded file in libraries or even attached files in lists of sharepoint, in a file server? I mean not in the SQL. If yes, would you plz tell me how?!


    Thank you in advanced
    Parisa

    ReplyDelete
  23. Parisa,

    Yeah, you can use WebClient Service to upload the file from SharePoint Document Library to File Server. Access all SPFiles from listitem.attachments and take its url and pass to following function.

    Sample Code:
    SaveFile(attachmentfilepath, FileserverURL);
    public bool SaveFile (string attachmentfilepath, string FileserverURL)
    {
    try
    {
    using (WebClient webclient = new WebClient())
    {
    webclient.UseDefaultCredentials = true;
    webclient.UploadFile(attachmentfilepath, "PUT", FileserverURL);
    }
    }
    catch(Exception ex)
    {
    return false;
    }
    return true;
    }

    Thanks,
    Disha

    ReplyDelete
  24. Dear Disha,
    I'm very new to sharePoint.
    Your blog helped me in create a custom webpart for uploading files in SharePoint ListItem/doc library.

    Your blogs are step by step and helped much to new learners in sharepoint.

    Thanks & Regards
    Pradeep

    ReplyDelete
  25. Hi Pradeep,

    Thanks for comment.
    If you have any questions, doubts for sharepoint development or configurations leave a comment and I will get back to you with suggestion.

    Thanks
    Disha Shah

    ReplyDelete
  26. I have a requirement that I need to write a custom web part that will display shared documents in window explorer style. So on the let side all the folders displayed in a tree view and on the right all the files for the selected folder displayed. Also we must have sharepoint default functionality like uploading, deleting and modifying, checking in and checking out files. Do you know if we can do this and how?

    ReplyDelete
  27. Hi Junaid Arif

    You can achieve your requirement by developing a customized webpart and with the use of “Object Model”.


    You can take treeview and iframe for displaying like on left had side put treeview and in treeview show folders-subfolders in explorer manner (one design functionality in treeview) and right hand side when they select a particular file write event on treenode selectednode changed , display that file on iframe which is on right hand side.

    You can put all your other functionality as buttons named as “upload”, “download” and use object model power to develop each functionality on selectednodechanged of treenode.

    Hope this helps
    Disha Shah

    ReplyDelete
  28. Thank you so much for replying this really helps. Have another question, is there a way we can add the sharepoint standard menus like New, Upload, Actions and Settings in the customized web part?

    ReplyDelete
  29. Dear Disha Shah,

    Thanks a lot for you valuable post.I have a requirment To upload ,Delete ,download files from/to document library.I followed you with the same Code.For me Upload and Delete is working fine.But download is not working properly.When i click download button ,a pop up window is opening,its asking Save,Open or Cancel.But if i click open or save its not opening the exact file which i attached.Its showing the source code for UI.When i debug the code the exception is "this is not valid virtual path".But i check the path is correct.Please help me to come out from this issue.

    (i Put ur exact code for download except the path section)

    ReplyDelete
  30. Safi

    Can you please write me back with change you made in your code for path section? That helps me out to solve your problem.

    Thanks
    Disha Shah

    ReplyDelete
  31. HI Disha,

    Would like to add multiple attachments to list item by customising the newform.aspx insteading of creaing a webpart? Is it possible?

    Regards
    Amit

    ReplyDelete
  32. Amit

    Very good question.Yes you can add multiple files via newitem but there are some disdavnatages are there too.

    For Example, If you have "title" field as compulsory , now you started to add new items and insert multiple files in that list and you did not enter value in "title" field and now when you press save all attached files gone.

    But one advantage is no need to write code and deploy webpart.

    Hope this helps.

    Thanks
    Disha Shah

    ReplyDelete
  33. Is there a way to attach file in Sharepoint survey?

    ReplyDelete
  34. Ravi

    Yes, as you know there are so many Field types are available like "Multiple Line of Text", "Person or Group".

    The same way you need to create one Custom Field type which is type of "File" and you can select that type when you add a new survey question.

    Hope this Helps
    Best Regards
    Disha Shah

    ReplyDelete
  35. Hi Disha

    A newbie to Sharepoint

    Nice post really helped to upload multiple docs .

    My question is based on project Task

    The Idea is around standard wss feature "Project Tasks Under Tracking.But its very limited as for each project and project tasks I have to crate folders. So I was thinking is it possible to do the following

    One Page that has a custom list with:

    1. Project name

    2. Project manager

    3. Project stage (initiate, proposal, in-progress, closed)

    4. Initiate date

    5. Proposal date

    6. Work start date

    7. Progress status (On-time, Delay Customer, Delay Us)

    8. Project Documents (when clicked on can attach multiple docs to this project) "Your post help me a lot in creating thing"

    9. Project plan (when clicked on – it brings up project tasks as exists project tasks under tracking)

    10. Issues ( when clicked on brings up issue tracking as under tracking - and can document multiple issues )

    11. Change Order ( when clicked on bring up a text open area to write and then can attach a document)

    12. My tasks (when clicked on displays tasks assigned to uses who signs on)

    Obviously number 1-7 is very easy. Number 8 This post helped me in creating it.But I do not know how to do number 9-12.

    Can you please help me in this

    Thanks

    Sohil Patel

    ReplyDelete
  36. Sohil

    I think whatever you had done for step 8 means custom coding the same way you need to go with for steps 9-12.
    You just need to design how the client need and put custom code into it...

    In that custom webpart you can create a table add add 12 rows as ur steps and just add controls and add logic according to that.


    Some Suggestions Like

    Fot Step 9:
    You can put one grid for displaying Project Plan.

    For Step 10
    Grid which displays existing Issues and one textbox and Submit Button where user can submit their on issues one by one and when they add a new issue it should automatically add to Grid.

    For Step 11:
    Text Box and File Input button with Submit button and grid where they can see whetever they uploaded and may be they can delete.

    For Step 12:
    grid where it shows all tasks related to that user.

    Hope this helps
    Disha Shah

    ReplyDelete
  37. Hi Disha,

    WE are creating a survey .The requirement is that whenever the user finishes the survey it should send an email notification to the author.I have tried attaching workflow to the survey,but it is throwing error!! Any idea how to implement this requirement will be of great help!!

    ReplyDelete
  38. Arvind

    Well you can do two things!!!

    You can send me workflow error and I can look into that error. For the descriptive error please check sharepoint log and give me the error description related to workflow.

    You can use eventhandler and write sendemail code in survey itemaddded or itemupdated.

    Hope this helps!!!!!
    Thanks and Reagrds
    Disha Shah

    ReplyDelete
  39. Ok..Thanks a lot..But can'w we do OOTB.I tried attaching on simple OOTB approvla workflow and it throws error!!I think we cannot attach workflow's to a survey list..What is your though on this?So customization is the last resort?

    ReplyDelete
  40. Hi Arvind

    We can attach OOTB workflow to Survey List ..Can you please let me what is the error?

    Thanks & Regards
    Disha Shah

    ReplyDelete
  41. Hi Disha

    Can you tell me if there is a relatively straightforward way to export an individual record from a list for printing - ideally in a format that can be edited to provide a corporate look and feel. I'm creating a list of project details and want to be able to generate printed case studies that incorporate output from specific fields within an individual Project Record.

    Many thanks in advance

    Jeremy

    ReplyDelete
  42. Hi Disha

    Thanks for the post just i am crawling the net i have dought i want the doucument to upload by only certain groups not all others.in sharepoint using object model if have any source plz share

    ReplyDelete
  43. Hi Nagaraj

    First create a group and add a person who has the access to upload documents to that document library. Let us say name is "Upload Group"

    Well you can write the code as below when you add a document to your SharePoint Document Library through Object Model.

    SPGroup group = SPContext.Current.Web.SiteGroups["Upload Group"];
    if(group .ContainsCurrentUser)
    {
    \\Code for add a document
    }
    else
    {
    //Write a message for "Access Denied"
    }

    Hope this helps
    Thanks & Regards
    Disha Shah

    ReplyDelete
  44. Hi Disha

    Thanxs for for useful hint!
    can u please tell me something about infopath if u know ! using custom code using VSTA

    ReplyDelete
  45. HI Disha
    I am newbie of using javascript in custom webpart development i need whenever the other group doesn't have permission of uploading the doc some javascript alert need to excute rather than error page!

    ReplyDelete
  46. Hi Disha
    I have link list and i have folder inside the link list whenever new item is added inside the folder i need to send mail how to achieve this !
    through event handler i need to do !
    But in the link list have column called Email which is having comma seperated mailid i need to pick those mailid and send mail whenever neew item is added

    ReplyDelete
  47. Hi Nagrag

    sorry for late reply!!!

    yes you need to follow these steps
    1> you need to fetch the emailid as column
    2> you need to use string array and break column value with ,
    3> Send email
    If you still not achived please let me know

    Thanks
    Disha Shah

    ReplyDelete
  48. This comment has been removed by the author.

    ReplyDelete
  49. Hi Nagraj

    The problem could be different timezone. Please check the SharePoint Server Timezone and if it is not for UK, Please follow these steps to update a new timezone.

    1> Open your web browser and access your SharePoint site.
    2> Click your Site Settings link. Under the Site Administrations section, you will find the "Regional Settings", click on that.
    3> In the "Time Zone" section change time zone to the one you want
    4> Click the "OK" button to apply the changes

    Let me know whether it solves your problem or not.

    Disha Shah

    ReplyDelete
  50. thnxs disha

    i have one more querry i want to have dedicated sql server for sharepoint web application creation while creating web application from the central admin it always take the stand alone server with sql server instance i dont want the default server instance how to achieve this one ? i need to give the external sql server instance for creation of web application in sharepoint is it possible? if yes please share your thoughts

    ReplyDelete
  51. Nagraj

    Definetly you can do that.

    1> You can always change Database Server Name and Database Name when you create a new Sharepoint Site.But the best practise is always create site on the same SQL Server Instance where your configuratation datbase resides.

    2> When you configure the SharePoint it always asks what is your database server name and you can do at that time so it becomes by default .

    Hope this helps!!!
    Disha Shah

    ReplyDelete
  52. hi disha
    I have requirement like uploading multiple files at one go in sharepoint i have done single file upload control using file upload control in sharepoint plz share some code for uploading multiple files in sharepoint using the fileupload control

    ReplyDelete
  53. Hi Disha,

    Seeing your btnUpload_Click(), the below lines of code:
    string tempFolder = Environment.GetEnvironmentVariable("TEMP");
    string _filepath = tempFolder + _newfilePath;
    FileUpload.PostedFile.SaveAs(_filepath);

    will surely give error as access denied... I agree with you on runwithelevated stuff.. But at the first instant if the above logic needs to be executed from machine which doesn't has MOSS installed then we are running into problem.

    Also in the method AddRow() this line:
    dt = (DataTable)ViewState["Files"];
    consumes to much memory do we have any alternatives....

    Was just going through the blog, looks good & explainatory... Can you help me with the above tweaks if possible..

    ReplyDelete
  54. Hi Disha,

    1)In btnUpload_Click() method,below lines
    string tempFolder = Environment.GetEnvironmentVariable("TEMP");
    string _filepath = tempFolder + _newfilePath;
    FileUpload.PostedFile.SaveAs(_filepath);

    get the attachment from local drive & save it in temp folder.

    Help me in tweaking the above lines,if the user is uploading files from his machine which doesn't has MOSS installed.

    2)Also for adding the attachment in datagrid, this line: dt = (DataTable)ViewState["Files"];
    will consume lots of memory & will slow the process of upload.

    Need help for tweaking the above points..

    Regards,
    Sidhartha

    ReplyDelete
  55. Hi there,
    I was hoping you could point me in the right direction.
    I am moving a list with attachments to a library. I was able to extract the attachments, get them all in a flat view and can move them over to library. BUT the title field in the list is not the title of the document. Is there a way I can get the title of the document to show up as a column so I can match up metadata with attachment in the library??

    SP2007
    thanks!
    Jessica

    ReplyDelete
  56. Hi Disha,
    I am uploading doucment using object model. However my 'UploadFile()' method throws exception "The request failed with HTTP status 403: Forbidden.".
    This happens if my current user is not a member of one custom group (ABCGroup). And 'ABCGroup' has all permissions. Even if I give 'Full Control' permissions to this user it doesn't work. So I am really wondering 1. Exactly which permission do we required to upload document into document library. and 2. Is it something wrong into my 'Uploadfile' method.

    --------- Here is code -------------
    public string UploadFile(string workspace, string fileName, byte[] data, string title, string comment)
    {
    string retval = "";

    SPWeb web = SPContext.Current.Web;

    SPFile newFile;
    try
    {
    SPFolder spfolder = web.GetFolder(workspace);

    if (spfolder != null)
    {
    if (data.Length == 0)
    {
    System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
    data = encoding.GetBytes(" ");
    }

    try
    {
    SPFile file = spfolder.Files[fileName];

    if (file != null)
    {
    if (file.CheckOutStatus != SPFile.SPCheckOutStatus.None)
    {
    file.UndoCheckOut();
    }
    }
    }
    catch (Exception e)
    {
    retval = e.Message;
    }

    newFile = spfolder.Files.Add(spfolder.Url + "/" + fileName, data, true, comment, false);
    newFile.Item["Title"] = title;
    newFile.Item.UpdateOverwriteVersion();
    newFile.CheckOut();
    newFile.CheckIn(comment, SPCheckinType.OverwriteCheckIn);

    }

    retval = "Uploaded successfully.";
    }
    catch (Exception e)
    {
    retval = e.Message;
    }
    return retval;
    }

    Thanks,
    Sandip

    ReplyDelete
  57. Hi Disha,

    I have similar situation, where I need to take attachments from user in itemadding eventhandler and add it to list item.

    I already raised my issue in this link, but I didn't get any useful information, if you have any ideas, plz let me know.

    http://social.msdn.microsoft.com/Forums/en-AU/sharepointdevelopment/thread/acbd19a3-368b-4ad4-ac2f-5211fc89bb93

    Thank you,
    Kishore

    ReplyDelete
  58. Hi Disha,I m new to sharepoint development. I need help from u. I want to create a sharepoint list with custom attchment option. e.g. I want to add a row like name, designation, phone, attachment(here i want to attach a doc file but file will be located into my created document library).
    /Jilani

    ReplyDelete
    Replies
    1. Hi Abdul

      You just want to give reference or attachment of document which is already uploaded inside the Document Library?

      1. Attachment: Custom lists has already attachment option.
      2. Document Library:
      Question: Is document library inside the same site?

      Respond with the which option you want to go with how it should work?I will reply you in more detail.

      Thanks
      Disha Shah


      Delete
  59. Hi Disha,I am having scenario where i need t upload documents and delete documents from Share Point list.I tried out the above code but it is not working out to me.Can u plz help me to achieve my functionality like uploading documents and deleting documents.

    ReplyDelete
    Replies
    1. Hi Vidya

      Could you please tell me which error you are getting so I could help you out?Because above code works very well.

      Thanks
      Disha Shah

      Delete
  60. Hello Disha - I am fairly new to SharePoint and want to know as to how can I get a multiple upload attachment control with delete functionality in a custom site page. Can this be done using the CSOM.

    ReplyDelete