Archive for January, 2008

Event Handler to Synchronize (Populate Data) List / Document Library Columns Form Other Document Library / List Columns

We have created a solution for one of our clients. The solution is based on uploading documents and attaching workflows with the documents.

Uploaded documents have different columns describing the document’s meta data. Our clients’ wants that these column in the task list.

We decide to write two event handlers. One was against the list and other was against the document library.

The event handler against list runs when a task is created in the task list. It fetches the information from the desired columns in the document library and populates the columns in the task list row.

The code is:

 public class MyClass : SPItemEventReceiver    {       

public override void ItemAdded(SPItemEventProperties properties)        {           

SPListItem item = properties.ListItem;                       

SPFieldUrlValue MyURL = null;           

SPView DefaultView = null;           

SPQuery SelectQuery = null;           

SPListItemCollection SelectedDoc = null;            

string URLText = null;           

string URL = null;                        

SPWeb site = (SPWeb)properties.OpenWeb();           

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

MyURL = new SPFieldUrlValue((string)item[“Link”]);           

URL = MyURL.Url; URLText = URL.Substring(URL.LastIndexOf(‘/’) + 1);         

DefaultView = DocLib.DefaultView;            

SelectQuery = new SPQuery(DefaultView);            

SelectQuery.Query = “<Where><Eq><FieldRef Name=’FileLeafRef’/><Value Type=’Text’>” + URLText + “</Value></Eq></Where>”           

SelectedDoc = DocLib.GetItems(SelectQuery);  

foreach (SPListItem doc in SelectedDoc) // run for once            {                  

item[“Col 1”] = doc[“Col 1”];                 

item[“Col 2”] = doc[“Col 2”];                 

item[“Col 3”] = doc[“Col 3”];                 

item.Update();           

}              

site.Dispose();                     

}

}

The second event handler was written against the document library for synchronization purpose. If user changes / update the data in the document library column, these changes must be reflected in the task list column. The event handler capture and runs against the update vent.

The code is:

 public class MYClass1 : SPItemEventReceiver    {       

public override void ItemUpdated(SPItemEventProperties properties)        {            

string DocName = null;           

string DocTitle = null;            

SPView DefaultView = null;           

SPQuery SelectQuery = null;           

SPListItemCollection SelectedDoc = null;                       

SPListItem doc = properties.ListItem;           

SPWeb site = properties.OpenWeb();           

SPList TaskList = site.Lists[“Task List Name”];            

DocName = doc[“Name”].ToString();                       

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

DefaultView = TaskList.DefaultView;            

SelectQuery = new SPQuery(DefaultView);             

SelectQuery.Query = “<Where><Eq><FieldRef Name=’LinkTitle’/><Value Type=’Text’>Please approve “ + DocTitle + “</Value></Eq></Where>”           

SelectedDoc = TaskList.GetItems(SelectQuery);            

foreach (SPListItem task in SelectedDoc)             {               

task[“Col 1”] = doc[“Col 1”];               

task[“Col 2”] = doc[“Col 2”];               

task[“Col 3”] = doc[“Col 3”];               

task.Update();           

}           

site.Dispose();       

}

}

In this way, changes in the columns of document library will be immediately visible in the columns of task list as well.  

In case you don’t know how to create and deploy event handler, follow this link.

Comments (8)

Populate / Set or Get Data / Value from / to Hyperlink Column

Data in the Hyperlink Column can be populated / set in the following manners: 

Item[“HyperLinkColumnName”] = “http://www.google.com, Google”;

Item.Update(); 

Don’t forget space after comma. 

Or 

SPFieldUrlValue MyURL = new SPFieldUrlValue();

MyURL.Description = “Google”;

MyURL.Url = http://www.google.com;

Item[“HyperLinkColumnName”] = MyURL;  

 

Data from the Hyperlink Column can be get in the following manner: 

SPFieldUrlValue MyURL = new SPFieldUrlValue(Item[“HyperLinkColumnName”].ToString()); 

string URLText = MyURL.Description;

string URL = MyURL.Url; 

Comments (3)

Adding an Event Handler to a Feature in MOSS

We will try to provide as much detail as possible while trying to explain how to write an event handler, but if you find difficulty in understanding event handler concepts, explore the this link . We will use the feature added in the previous post 

Open the project “HelloWorldFea” and rename Class1.cs to “FeatureReceiver.cs”. Add the reference of Micrososoft.SharePoint.dll. (if you don’t know how to add, click here). Write the following code in “FeatureReceiver.cs” file. 

using Microsoft.SharePoint; 

namespace HelloWorldFea{   

public class FeatureReceiver : SPFeatureReceiver    { 

public override void FeatureActivated(SPFeatureReceiverProperties properties)       

{           

SPWeb site = (SPWeb)properties.Feature.Parent;           

site.Properties[“OriginalTitle”] = site.Title;           

site.Properties.Update();            

site.Title = “HELLO WORLD”;           

site.Update();               

}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)       

{           

SPWeb site = (SPWeb)properties.Feature.Parent;           

site.Title = site.Properties[“OriginalTitle”];           

site.Update();       

} 

public override void FeatureInstalled(SPFeatureReceiverProperties properties)       

{

} 

public override void FeatureUninstalling(SPFeatureReceiverProperties properties)        

{                   

}   

}

} 

We have inherited form the class SPFeatureReceiver and override four methods which are FeatureActivated, FeatureDeactivating, FeatureInstalled and FeatureUninstalling. FeatureActivated will fire after a feature is activated and FeatureDeactivating will fire before a feature is deactivated. 

In FeatureActivated method, we did a simple trick. We store site name using persistent property bag and replace it with “HELLO WORLD” title. When the feature is deactivated, the original title of the site is restored. 

Now it’s time to deploy the assembly. First we sign the assembly. (if you don’t know how to sign, click here). The next step is to deploy the assembly into GAC. We can do that by moving to the properties of the project and then to “Build Events” tab. “Post build event command line window:” text box will already have following lines: 

cd $(ProjectDir)

Install.bat 

(For details, check this post) 

Add the following lines in the beginning. 

“%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe” /if $ “(TargetPath)” 

The last step is to add the reference in the “feature.xml” file. The updated look of the file is: 

<Feature 

Id=“” 

Title=HELLO WORLD FEATURE 

Description=This is my very first custom feature 

Version=1.0.0.0  

Scope=Web 

Hidden=FALSE 

ImageUrl=menuprofile.gif 

ReceiverAssembly=HelloWorldFea, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9136ecc8446e96dc  ReceiverClass=HelloWorldFea.FeatureReceiver  

xmlns=http://schemas.microsoft.com/sharepoint/>   

<ElementManifests>   

<ElementManifest Location=elements.xml /> 

</ElementManifests>

</Feature> 

If you don’t have the idea about the ReceiverAssembly / ReceiverClass element, click here).  Activate and deactivate the feature to test the working of the event handler. If not working, try doing the things manually.

 

Comments (2)

CREATING AND DEPLOYING FEATURE IN MOSS

Windows SharePoint Services 3.0 introduces an inherently portable and modular functionality known as feature, which provides a mechanism for defining site elements. 

 A feature is a package of Windows SharePoint Services elements that can be activated for a specific scope and that helps users accomplish a particular goal or task. 

 Features are added to a target site or site collection through a process known as feature activation. The element types that can be defined by a feature include menu commands, link commands, page templates, page instances, list definitions, list instances, event handlers, and workflows. 

 So let’s start writing a feature. The functionality of the feature which we are going to develop is that it adds a menu item “Hello World” in the “Site Actions” menu. Clicking on the menu item “Hello World” will transfer to Google. Our goal is shown in the figure below:

 

 6-3.jpg

 

 The first step is to understand the feature file structure. If you go to “C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES” directory, you will see features already existed. Each feature has a file “feature.xml” and other file usually named as “elements.xml”. 

 Now we move to VS 2005 and create a new class library DLL project and name it “HelloWorldFea. Now, it will be intelligent to create the same structure of files as that of WSS 3.0 in the VS 2005. 

 Create a directory “TEMPLATE” in the solution. Inside the “TEMPLATE” directory, create another directory “FEATURE” and lastly, in the “FEATURE” directory, create directory with the same name as that of the project which happens to be “HelloWorldFea”. 

 

6-1.jpg 

 

Now, create a xml file and name it “feature.xml” inside the directory “HelloWorldFea”. In this xml file, we will write the details that will define the high level attributes of the features itself. Add the following XML to the “feature.xml” file. 

<Feature 

Id=“” 

Title=HELLO WORLD FEATURE 

Description=This is hello world feature. 

Scope=Web 

Hidden=FALSE 

ImageUrl=menuprofile.gif 

xmlns=http://schemas.microsoft.com/sharepoint/>   

    <ElementManifests>   

         <ElementManifest Location=elements.xml /> 

    </ElementManifests>

</Feature>  

We describe the attributes of the Feature tag as under: 

Id: GUID which identifies the features uniquely. It can be created by clicking “Tools” menu of VS 2005 and then on “Create GUID”. “Create GUID” window will appear. Select “4 Registry Format (ie. (xxxx …))” option. Click on “Copy” button and paste the GUID against the Id attribute. 

Title: Specifies the title of the feature. 

Description: Specifies the description of the feature. 

Scope: Scope defines the context in which feature is activated and deactivated. It can have four values namely Web, Site, WebApplication and Farm. Web specifies that the feature can be activated and deactivated within the context of site. Site specifies that the feature can be activated and deactivated within the context of the site collection. Same stands for WebApplication and Farm. 

Hidden: Can be set to true or false. In case of true, feature is not visible in the list of available features. It can be activated or deactivated through command line, through custom code, or through an activation dependency with another feature. 

ImageUrl: The image displayed next to the feature in the use interface. The last part is ElementManifests element. The element has inner element ElementManifest which specifies the reference of other XML file. This file defines other elements that make up the feature. In our case, we have one file “elements.xml”. 

Create “elements.xml” file in the “HelloWorlFea” directory. The XML for the file is as under: 

<Elements xmlns=http://schemas.microsoft.com/sharepoint/ >  <CustomAction    Id=SiteActionsToolbar     

 

GroupId=SiteActions   

Location=Microsoft.SharePoint.StandardMenu   

Sequence=100   

Title=Hello World   

Description=A custom menu item added using a feature   

ImageUrl=_layouts/images/menuprofile.gif >   

    <UrlAction Url=http://www.google.com/>     

</CustomAction>

</Elements > 

Id has the name of the menu in which we want to add our menu item. Title and description specifies the text that will appear as title and description. UrlAction states the url of the site where user is redirected when clicked. In our case, it is http://www.google.com. 

The next step is to deploy the feature unto the “FEATURE” directory. For this purpose we create a batch file and name it “deploy.bat”. The contents of the file are: 

@SET TEMPLATEDIR=”C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE”

@SET STSADM=”C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\stsadm” 

Echo Copying filesxcopy /e /y TEMPLATE\* %TEMPLATEDIR% 

Echo Installing feature%STSADM% -o InstallFeature -filename HELLOWorldFea\feature.xml -force 

Echo Reatart IIS Worker Process

IISRESET  

In the end, go to the properties of the project and then to “Build Events” tab. Write the following lines in the “post build event command line window:”  

cd $(ProjectDir)

install.bat 

The first line is required to change the current directory to that of the project directory. The second line runs the batch file to copy the feature files to the correct location and install the feature with the InstallFeature operation of the command-line STSADM.EXE utility. Now go to the “Site Features” page by moving from “Site Actions” to “Site Settings” and clicking on “Site Features” of your site. Here, “Hello World Feature” will be available. Activate it and you will be able to see a menu item added in the “Site Actions” menu. If you fail to find the feature, check the following steps: 

  • “HelloWorldFea” directory is added in the FEATURES directory at the path “C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES”

 

  • Run the file “feature.xml” and “element.xml” to check that XML is error free.

If still unable to find the feature, try to deploy manually and see what happen. 

http://msdn2.microsoft.com/en-us/library/ms439657.aspx

Source:

http://www.microsoft.com/learning/en/us/book.aspx?ID=9692&locale=en-us

Comments (6)

Upload file in MOSS / SharePoint using code

It is easy and simple to upload a file in the document library of MOSS / SharePoint. The code for upload the file in C# is as under: 

SPSite sp = new SPSite(“URL of the site collection”);     

SPWeb site = sp.OpenWeb();      

SPFolder folder = site.GetFolder(“Document Library Name”);     

SPFileCollection files = folder.Files; FileStream fStream = File.OpenRead(“C:\\upload.doc”); //path of the file to upload     

byte[] contents = new byte[fStream.Length];     

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

fStream.Close();      

Hashtable MetaDataTable = new Hashtable();     

MetaDataTable.Add(“Comments”, “Hello World”);      

SPFile currentFile = files.Add(“URL of the document library/upload.doc”, contents, MetaDataTable, true); 

You can addd the meta data as well by using Hash Table. We have populated the “Comments” column with “Hello World”. 

With or without using the following code

 SPListItem doc = currentFile.Item;  

We can do a lot of things with the uploaded file.

For more information, visit the Microsoft link. It provides more information about the error checking and other.

Comments (20)

7 Development Projects for Microsoft Office SharePoint Server 2007 and Windows SharePoint Services (printable)

The e-book by Microsoft Press 7 Development Projects for Microsoft Office SharePoint Server 2007 and Windows SharePoint Services is an excellent resource for learning SharePoint Server and Windows Services.  

The problem with this book is that it can’t be printed if download from the Microsoft site.

But the workaround is that you can download a free pdf printing restrictions removal software which will remove the printing restrictions.

The other easy way is to download a copy of it from the following link uploaded by rosthyra

Leave a Comment

Local Copy of Document Library (Available Online Only)

Creating a local copy of document library is simple and same as adding a network place on your machine. 

The steps are very simple. Click on “My Network Place” icon on your desktop and then, click on “Add Network Place”. This will open a new wizard “Welcome to Add Network Place Wizard”. Click “Next” and it will take some seconds to download information from internet. Select “Choose another network location” and click “Next”. A text box will appear with the text caption “Internet or network address”. 

Copy the URL of the document library for which you want to create a local folder. This can be done by right click on the document library and selecting “Copy Shortcut”. 

Paste that shortcut in the “Internet or network address” and click “Next”. The wizard will ask you the name of the local folder on your machine. Type the name of your choice and click “Next”. A confirmation window will appear with the message of successful creation of the network place. Click “Finish” and folder will be created.  

You can copy and paste your documents in the local folders and documents will be automatically uploaded to the site document library. Any change that you make in the local folder will be reflected in the document library.

P.S. local folder will be available when you are online. Nothing will be availabe when offline.

Comments (3)

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

Comments (13)

Code Behind in MOSS

Code Behind in MOSS  This is great to be able to use ASP.Net code behind model for coding in MOSS. This adds great flexibility in writing customized code for MOSS. Let’s start doing this. 

The first step is to create a Web site project in Visual Studio. The details of the files are as under: Hello.aspx

 <%@ Page Language=”C#” AutoEventWireup=”true”  CodeFile=”Hello.aspx.cs” Inherits=”HelloNameSpace.HelloClass” %> 

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt; 

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >

<head runat=”server”>

<title>Code Behind Example for MOSS</title>

</head>

<body>   

<form id=”form1″ runat=”server”>   

<div>       

<asp:Button ID=”Button1″ runat=”server” Text=”Click Me” OnClick=”Button1_Click” />   

</div>   

</form>

</body>

</html>  

Hello.aspx.cs 

namespace HelloNameSpace{   

public partial class HelloClass : System.Web.UI.Page    {       

protected void Button1_Click(object sender, EventArgs e)        {           

Response.Write(“HELLO WORLD.”);       

}   

}

} 

The next step is to generate a strong name key. We can use the tool “Sn.exe”. The path, where it can be found, is “C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin”. Use the following command to generate the key. 

sn –k HelloNameSpace.snk 

The next step is to publish the site. For this, right click on the project and select “Publish Web Site”. This will generate a new window as shown in the figure below:  

4-1.jpg 

Check the option “Enable strong naming on precompiled assemblies” and gave the path of the file “HelloNameSpace.snk” that you created just before. 

Click “OK” and publishing will be succeeded.  

Go to the bin directory of the Visual Studio solution and copy the DLL file from the bin directory of the solution to the bin directory of the SharePoint site. The path of the bin directory of SharePoint can be “C:\Inetpub\wwwroot\wss\VirtualDirectories\80\bin”. Also, copy the name of the DLL file. In our case it is “App_Web_js_i-de4.dll”.

Now, its time to add the code in the MOSS site. Open the site in the SharePoint Designer and add a aspx page in the site.  

Copy and past the HTML from the file “Hello.aspx” into the aspx page added in the SharePoint Designer. Don’t forget to change the first line of the code as under: 

<%@ Page Language=”C#” AutoEventWireup=”true” Inherits=”HelloNameSpace.HelloClass, App_Web_js_i-de4″ %> 

Next step is to add two entries in the web.config file accordingly 

<SafeControl Assembly=App_Web_js_i-de4 Namespace=SPCodeBehind TypeName=* Safe=True /> 

And 

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

It is strongly recommended that you should save a copy of web.config file before making changes. The file web.config can be found at “C:\Inetpub\wwwroot\wss\VirtualDirectories\80”. 

Now access the page and hopefully it will work fine. 

The problem with this approach is that you can’t make changes in case you want to inherit master page, it will generate exception.  

For more help, follow the link below

http://blogs.vertigo.com/personal/willa/Blog/Lists/Posts/Post.aspx?ID=4

http://msdn2.microsoft.com/en-us/library/bb892187.aspx

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)

Older Posts »