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.
