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.

Advertisements

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 (5)

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)

Older Posts »