In line code to upload (supportive) documents

 Recently we face a requirement from our client that one or more documents should be added against the documents already uploaded in the document library. We created a look up column (on the bases of “Title” field) and asked him to add as many documents as he wanted but he refused the solution giving two arguments. 

1-    Doesn’t have the time to go to the propertied page of each document and attach documents from there.

2-    Don’t want to fellow the process (first step was to upload the supportive document, write the name of the document in the title field and then, using properties of the target document, attach it using the look up column). 

So we have to device another solution and we decided to go in line code. For this, we added a hyperlink column and a look up column. The name of the look up column is “DocAttached”. We selected “Title” as a criteria and option for multiple values is checked. The name of the hyperlink column is “AttachDoc”. The value of the “AttachDoc” is populated by upload event handler. The code of the event handler is below: 

public override void ItemAdded(SPItemEventProperties properties)       

{           

if (properties.ListItemId.Equals(null)){   

SPListItem doc = properties.ListItem;   

doc[“AttachDoc”] = “URL of the site/Upload_file.aspx?para=” + doc[“ID”] + “, Attach File”;                doc.Update();           

}                   

} 

Above code concatenate the document ID with the URL of the page “Uploaded_file,aspx” that we have added using SharePoint Designer. Each time a document is uploaded, the value of the column “AttachDoc” is populated with a URL which has a concatenated value of the document ID. When the users click on the “Attach File” link provided in the “AttachDoc” column, the control passes to the page “Upload_file.aspx”.

The HTML and in line code for the page “Upload_file.aspx” is as under:   

<%@ Page Language=”C#” masterpagefile=”~masterurl/default.master” title=”|” inherits=”Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” meta:progid=”SharePoint.WebPartPage.Document” %>

<%@ Import Namespace=”Microsoft.SharePoint” %>

<asp:Content id=”Content1″ runat=”server” contentplaceholderid=”PlaceHolderMain”>

<head>

<META name=”WebPartPageExpansion” content=”full”>

<script runat=”server”>

SPSite sp;

            SPWeb WebSite;

            SPList DocLib;

int id = 0;

   

            string AddURL = “”;

string DocName = “”;

string DocTitle = “”;  

           

public void Page_Load(object o, EventArgs e)

{

           

            sp = new SPSite(“URL”);

            WebSite = sp.OpenWeb();

            DocLib = WebSite.Lists[“Document Library Name”];

           

            if (string.IsNullOrEmpty(Request.QueryString[“para”]))

       {

       Response.Redirect(“http://URL/Upload_error.aspx&#8221;);

       }

           

            id = Convert.ToInt32(Request.QueryString[“para”]);

}

           

   

public void UploadFile(object o, EventArgs e)

{

             if (FileUpload1.HasFile)

        {

            AttachDocument(FileUpload1);           

        }

        if (FileUpload2.HasFile)

        {

            AttachDocument(FileUpload2);

        }

        if (FileUpload3.HasFile)

        {

            AttachDocument(FileUpload3);

        }

        if (FileUpload4.HasFile)

        {

            AttachDocument(FileUpload4);

        }

        if (FileUpload5.HasFile)

        {

            AttachDocument(FileUpload5);

        }       

                       

WebSite.Close();

sp.Close();

WebSite.Dispose();

sp.Dispose(); 

      

        Response.Redirect(“Document Library URL”);

}

public void AttachDocument(FileUpload file)

{

        byte[] content = new byte[file.PostedFile.ContentLength];

        string URL = “URL of the document library/” + file.FileName;

        content = file.FileBytes;

        SPFolder DocLibFolder = WebSite.GetFolder(“DLOne”);

        SPFileCollection DocLists = DocLibFolder.Files;

        sp.AllowUnsafeUpdates = true;

        WebSite.AllowUnsafeUpdates = true;

        SPFile FileAdded = DocLists.Add(URL, content);

        SPListItem DocAdded = FileAdded.Item;

        DocName = DocAdded.Name;

        DocTitle = DocName.Substring(0, DocName.IndexOf(‘.’));

        DocAdded[“Title”] = DocTitle;

        DocAdded.Update();

        AddURL = “;#” + DocAdded.ID + “;#” + DocTitle;

        SPView DefaultView = DocLib.DefaultView;

        SPQuery SelectQuery = new SPQuery(DefaultView);

        SelectQuery.Query = “<Where><Eq><FieldRef Name=’ID’/><Value Type=’Numeric’>” + id + “</Value></Eq></Where>”;

        SPListItemCollection SelectedDoc = DocLib.GetItems(SelectQuery);

        SPListItem doc = SelectedDoc.GetItemById(id);

        doc[“DocAttached”] += AddURL;       // “;#158;#sv002”;

        doc.Update();           

}

public void button_Cancel(object o, EventArgs e)

{

  Response.Redirect(“URL of the Document Library”);

}

</script>

</head>

<body>

<div>

        <table>

            <tr>

                <td><asp:FileUpload ID=”FileUpload1″ runat=”server”/></td>

                <td> </td>

                <td> </td>

            </tr>

            <tr>

                <td><asp:FileUpload ID=”FileUpload2″ runat=”server”/></td>

                <td> </td>

                <td> </td>

            </tr>

            <tr>

                <td><asp:FileUpload ID=”FileUpload3″ runat=”server”/></td>

                <td> </td>

                <td> </td>

            </tr>

            <tr>

                <td><asp:FileUpload ID=”FileUpload4″ runat=”server”/></td>

                <td> </td>

                <td> </td>

            </tr>

            <tr>

                <td><asp:FileUpload ID=”FileUpload5″ runat=”server”/></td>

                <td> </td>

                <td> </td>

            </tr>

            <tr>

                        <td>             </td>

            </tr>

            <tr>

             <td><asp:Button ID=”Button2″ runat=”server” Text=”Upload” OnClick=”UploadFile”/>

                <asp:Button ID=”Button1″ runat=”server” Text=”Cancel” OnClick=”button_Cancel”/></td>

                <td>                   

                </td>

            </tr>

        </table>   

    </div> 

</body>                                              

</asp:Content>

 

The screen shoot of the “Upload_file.aspx” is as under: 

 

5-1.jpg

Advertisements

13 Comments »

  1. Ali said

    Hi Farhan,

    i have been trying your code for 2 days. It some how is not working. I get the error of
    “NullReferenceException was handled by user code ”
    Troulbe shooting Tips:
    Use new keyword to create an object instance.
    Check to determine if the object is null before the calling method.
    Get general help for this exception.

    Attach is an excerpt of my code that was inspired from your style of code.

    public void AttachDocument(FileUpload file)
    {

    byte[] content = new byte[file.PostedFile.ContentLength];
    string URL = “http://oss1:22222/test/” + file.FileName;

    content = file.FileBytes;
    SPFolder DocLibFolder = WebSite.GetFolder(“DLOne”);
    SPFileCollection DocLists = DocLibFolder.Files;
    sp.AllowUnsafeUpdates = true;
    WebSite.AllowUnsafeUpdates = true;
    SPFile FileAdded = DocLists.Add(URL, content); -> Get an exception at this line
    SPListItem DocAdded = FileAdded.Item;
    DocName = DocAdded.Name;
    DocTitle = DocName.Substring(0, DocName.IndexOf(‘.’));
    DocAdded[“Title”] = DocTitle;
    DocAdded.Update();
    }

  2. Farhan Faiz said

    Lets try to debug the code. Kindly do the following steps and kindly share the results:

    1 – replcae URL in DocLists.Add(URL,content) with a hard coded URL of the file.
    2 – Check the size of “content”.

    3 – Check the values of DocLibFolder and DocLists using debug.

    waiting for your reply.

  3. Ali said

    Hi Farhan,

    Sorry for the late reply. I thought if you would message me it would alert me. Anyways, was just looking at your requirements to see if i had the same requirements and saw your comment.

    The solution to the problem was the user who was trying to add the document to the document library, did not had the permissions to do so. I had to do impersonate the user and elevate the previlages.

    I was facing one more problem after impersonation. Once the file was added to the doc library, the Title was not getting updated. The Doc.Updated() thing was not working under the ElevatedPrevilages block and was giving an exception. Just have a look at my code and see if that makes sense to you, I also pasted the link while i was write the code as a comment to the site that helped me solve my problem.

    public void AttachDocument(FileUpload file, string URL, string DocumnetTitle)
    {
    SPWeb elevatedRootWeb = null;
    //Without Impersonation, the items of a list could not have been updated
    try
    {
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
    using (SPSite elevatedSite = new SPSite(sp.ID))
    {
    elevatedRootWeb = elevatedSite.RootWeb;
    }
    });
    //DocAdded.Update somehow doesn’t inside the RunWithElevatedPrivileges block
    //I instantiated the SPWeb or SPSite and call
    //updates outside the RunWithElevatedPrivileges block
    //Refer to the following code http://howtocode.blogspot.com/2007/06/moss-splistitemupdate-throws-error.html
    elevatedRootWeb.AllowUnsafeUpdates = true;
    SPUser user = elevatedRootWeb.CurrentUser;
    byte[] content = new byte[file.PostedFile.ContentLength];
    URL = URL + file.FileName;
    content = file.FileBytes;
    SPFolder DocLibFolder = elevatedRootWeb.GetFolder(“DLOne”);
    SPFileCollection DocLists = DocLibFolder.Files;
    SPFile FileAdded = DocLists.Add(URL, content, user, user, DateTime.Now.ToUniversalTime(), DateTime.Now.ToUniversalTime());
    SPListItem DocAdded = FileAdded.Item;
    DocName = DocAdded.Name;
    //DocTitle = DocName.Substring(0, DocName.IndexOf(‘.’));
    if (DocumnetTitle == “”)
    {
    DocumnetTitle = DocName.Substring(0, DocName.IndexOf(‘.’));
    }
    DocAdded[“Title”] = DocumnetTitle;
    DocAdded.Update();
    elevatedRootWeb.AllowUnsafeUpdates = false;
    }

    finally
    {
    elevatedRootWeb.Dispose();
    }
    }
    });
    return stFilename;
    }

  4. Ali said

    Farhan,

    I was wondering if you had the same issue while you were doing the same thing with your client. My client needs a document to be posted as word document and should also have the flexibility to view the content as a web page.

    My team is asking me to save the document as an MHTML document. One major problem i run into is that the size of the word documents is over 60, if i do the conversion from word to mht file, it would be very cumbersome. I was looking for an automated solution to it.

    The other problem that we run in is once the document is converted into mht file, the way mht file looks is a lot different from the original word document. Is there any code/script i could run to align the MHTML text by any chance to your knowledge that it could render it exactly as a .doc file?

    Regards,

    Ali.

  5. Farhan Faiz said

    Ali,

    If you are using MOSS 2007, then, enabling document as web page might solve this problem. If yes, then, its great. If no, then we have to find some other way.

    Do let me now in case you require further assistance in this regard.

  6. Ali said

    I tried that but that is not what we are looking for. Anyways, i guess folks at my place have figured out another way to handle it. Thanks anyways.

  7. opo Herrera said

    hi guys!! how can i add the same feature on any of my lists. What i want is to see the name of the attachments (multiple of them) and have the opportunity to upload up to to 10.

    please help me..

    Opo

    • Farhan Faiz said

      opo,

      I don’t think this is much different on sharepoint object model. Let me know if you have any issues.

      Regards,

  8. nixBS said

    hi Farhan
    my question is:how to upload an attachment in a list (not in document library) corresponding to a data record..

    I need to use some SPQuesry for getting a particular record???
    Can u help in this case..

    Thnx in advance..

    • Farhan Faiz said

      I don’t think this is much different on sharepoint object model level. Let me know if you have any issues.

  9. Wow, I was looking for something totally different when I found this. THXs

  10. Mike said

    Was this only done with front end code or did you use .net or C# in creating the solution?

    • Farhan Faiz said

      This was way back, If I remember correctly, in-line code only.

RSS feed for comments on this post · TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: