Archive for In Line Code

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”);

       }

           

            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

Comments (2)

In line code for MOSS

In line Code for MOSS

Adding in line code is tricky. Microsoft support policies recommended for inline code are as under: 

Inline code in Site Definition based ASPX pages:

Inline code is not recommended within a site definition due to the issues involved with the code no longer rendering as soon as the page is customized. 

Inline code in _layouts-based ASPX pages:

Inline code is supportable if included on a page in the _layouts directory. 

Inline code enabled through PageParserPath exclusion:

Inline code should not be allowed through the PageParserPath exclusion, except in extremely rare circumstances, because it can be modified without going through any review process. As a result, it represents a danger to the environment’s performance and security. 

So think about the pros and cons and if you are still ready to take the ride, continue reading. The first step is to open the site in Microsoft Office SharePoint Designer.  

Go from File -> New -> Page and select ASP.Net under “Page” and then select “Create from Master Page..”. You can add any page depending upon your requirements. 

This will open a blank page which will inherit master page look & feel. Now add you script under first head tag. If you don’t find it, add the head tag as well. The code written by me is as under: 

<head>

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

<script runat=”server”>        

 SPSite sp;       

SPWeb WebSite;       

SPList DocLib;       

public void Page_Load(object o, EventArgs e){                

sp = new SPSite(”Site URL”);       

WebSite = sp.OpenWeb();       

DocLib = WebSite.Lists["Doc Library Name"];       

} 

public void Hello_Click(object o, EventArgs e){       

context.Response.Write(“HELLO WORLD”);

} 

</script>  

</head>             

Add the method on the OnClick event of the button. Lastly, make changes in the web.config file. Usually present at this path C:\Inetpub\wwwroot\wss\VirtualDirectories\80.

But before making changes, save the file at some other place or you might be in big trouble. Add the following line in the PageParserPaths. Be careful.  

<PageParserPaths>       

<PageParserPath VirtualPath=”/*” CompilationMode=”Always” AllowServerSideScript=”true” IncludeSubFolders=”true” />     

</PageParserPaths>

</PageParserPaths> 

Save the changes and access the page in the browser. 

Exception: 

An error occurred during the compilation of the requested file, or one of its dependencies. The type or namespace name ‘SPSite’ could not be found (are you missing a using directive or an assembly reference?) 

Reason: 

Forget to import SharePoint namespace. 

Resolution: 

Add <%@ Import Namespace=”Microsoft.SharePoint” %> after the page directive. 

Exception: 

An error occurred during the compilation of the requested file, or one of its dependencies. Invalid token ‘=’ in class, struct, or interface member declaration 

Reason: 

Didn’t initialize variables in Page_Load method. 

Resolution: 

Initialize variables in Page_Load method.

Comments (1)

« Previous entries