I am trying to enable View toolbar on my list views. But it seems not to be working. How can I get the code right?
/// <summary>
/// Handles the Click event of the btnEnable control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void btnEnable_Click(object sender, EventArgs e)
{
using (SPWeb spWeb = new SPSite(tbSiteUrl.Text).OpenWeb())
{
SPList spList = spWeb.Lists[lbLists.SelectedItem.ToString()];
foreach (SPView spView in spList.Views)
{
EnableToolbar(spView.Title, spList.Title, spWeb.Url);
}
}
}
/// <summary>
/// Enables the toolbar.
/// </summary>
/// <param name="viewName">Name of the view.</param>
/// <param name="listName">Name of the list.</param>
/// <param name="webUrl">The web URL.</param>
private void EnableToolbar(string viewName, string listName, string webUrl)
{
SPSecurity.RunWithElevatedPrivileges(() =>
{
using (var spSite = new SPSite(webUrl))
{
using (SPWeb web = spSite.OpenWeb())
{
spSite.AllowUnsafeUpdates = true;
SPList spList = web.Lists[listName];
SPView spView = spList.Views[viewName];
XDocument xDocument =
XDocument.Parse(spView.GetViewXml());
XElement xElement =
xDocument.Element("View").Element("Toolbar");
xElement.RemoveAttributes();
xElement.SetAttributeValue("Type", "Standard");
xElement.SetAttributeValue("ShowAlways", "TRUE");
spView.SetViewXml(xDocument.ToString());
spView.Update();
spSite.AllowUnsafeUpdates = false;
}
}
});
}
UPDATE:
using (var spSite = new SPSite(webUrl))
{
using (SPWeb web = spSite.OpenWeb())
{
spSite.AllowUnsafeUpdates = true;
SPList spList = web.Lists[listName];
SPView spView = spList.Views[viewName];
spView.Toolbar =
#"<Toolbar Type=""Standard"" ShowAlways=""TRUE""/>";
spView.Update();
spSite.AllowUnsafeUpdates = false;
}
}
Closer, but still not good.
This time, it did modified the view. I know it because, the second time I run the debugger, I did noticed the value of the SPView.Toolbar property changed.
But when I open the same page in the SharePoint designer, I do not see <Toolbar Type="Standard" ShowAlways="TRUE"/> but I see the default value as: <Toolbar Type="Standard"/>.
In addition to that, I do not see the toolbar on the list view page when I open the list view in the browser.
This is what I had to do to make it work.
/// <summary>
/// Enables the toolbar.
/// </summary>
/// <param name="viewName">Name of the view.</param>
/// <param name="listName">Name of the list.</param>
/// <param name="webUrl">The web URL.</param>
private void EnableToolbar(string viewName, string listName, string webUrl)
{
using (var spSite = new SPSite(webUrl))
{
using (SPWeb web = spSite.OpenWeb())
{
spSite.AllowUnsafeUpdates = true;
SPList spList = web.Lists[listName];
SPView spView = spList.Views[viewName];
SPLimitedWebPartManager spLimitedWebPartManager =
web.GetLimitedWebPartManager(spView.Url, PersonalizationScope.Shared);
foreach (WebPart webPart in spLimitedWebPartManager.WebParts)
{
if (webPart.GetType().Name.Equals("XsltListViewWebPart"))
{
try
{
MethodInfo ensureViewMethod = webPart.GetType().GetMethod("EnsureView",
BindingFlags.Instance |
BindingFlags.NonPublic);
object[] ensureViewParams = {};
ensureViewMethod.Invoke(webPart, ensureViewParams);
FieldInfo viewFieldInfo = webPart.GetType().GetField("view",
BindingFlags.NonPublic |
BindingFlags.Instance);
var view = viewFieldInfo.GetValue(webPart) as SPView;
Type[] toolbarMethodParamTypes = {Type.GetType("System.String")};
MethodInfo setToolbarTypeMethod = view.GetType().GetMethod("SetToolbarType",
BindingFlags.Instance |
BindingFlags.NonPublic, null,
toolbarMethodParamTypes, null);
object[] setToolbarParam = {"ShowToolbar"};
setToolbarTypeMethod.Invoke(view, setToolbarParam);
view.Update();
}
catch { }
}
}
spSite.AllowUnsafeUpdates = false;
}
}
}
Use the SPView.Toolbar property instead. The property expects the <Toolbar/> CAML element and replaces the particular XML node in the underlying CAML fragment.
Related
I have a fresh web application already created.
Now I just want to Programmatically add Site Collections and Subsites to the Web Application using the console application.
Any Help appreciated.
Regards,
Navish
You can use next class for your needs. Please adapt it and fill exceptions handling blocks.
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
namespace TestApp
{
/// <summary>
/// Allows to create site collections and web sites.
/// </summary>
public class SiteCreation
{
/// <summary>
/// Creates new site collection.
/// </summary>
/// <param name="webApplicationsUrl">Web application url, which will host new site collection.</param>
/// <param name="siteUrl">Created site collection URL.</param>
/// <param name="siteTitle">Created site collection title.</param>
/// <param name="siteDescription">Created site collection description.</param>
/// <param name="siteTemplateName">Template name (STS#0 for example).</param>
/// <param name="lcid">LCID (1033 for English).</param>
/// <param name="ownerLogin">Owner login name.</param>
/// <returns>
/// Created site collection.
/// </returns>
public SPSite CreateSiteUnderWebApplication(string webApplicationsUrl, string siteUrl, string siteTitle, string siteDescription, string siteTemplateName, uint lcid, string ownerLogin)
{
var webApp = SPWebApplication.Lookup(new Uri(webApplicationsUrl));
if (webApp != null)
{
using (var site = webApp.Sites[siteUrl])
{
if (site == null)
{
try
{
var siteNew = webApp.Sites.Add(siteUrl, siteTitle, siteDescription, lcid, siteTemplateName, ownerLogin, ownerLogin, string.Empty);
return siteNew;
}
catch (Exception exc)
{
//error can't create site
//if (Properties.Settings.Default.logErrorMessages)
// eventLog.WriteEntry(exc.Message, EventLogEntryType.Error);
return null;
}
}
else
{
// warning site already exist
//if (Properties.Settings.Default.logWarningMessages)
// eventLog.WriteEntry("Site: " + strSiteUrl + " under webapp: " + strWebApplicationsUrl + " alredy exist.", EventLogEntryType.Warning);
return null;
}
}
}
else
{
// error can't access webapp
//if (Properties.Settings.Default.logErrorMessages)
// eventLog.WriteEntry("Can't access " + strWebApplicationsUrl + " webapp", EventLogEntryType.Error);
return null;
}
}
/// <summary>
/// Create web site under site collection.
/// </summary>
/// <param name="siteCollectionUrl">URL of parent site collection.</param>
/// <param name="webSiteUrl">Url of created web site.</param>
/// <param name="webSiteTitle">Title of created web site.</param>
/// <param name="webSiteDescription">Description of created web site.</param>
/// <param name="webSiteTemplateName">Name of web site template.</param>
/// <param name="lcid">LCID of web site.</param>
/// <param name="isCustomTemplate">True if webSiteTemplateName is name of custom template.</param>
/// <returns>Created web site.</returns>
public SPWeb CreateWebSiteUnderSiteCollection(string siteCollectionUrl, string webSiteUrl, string webSiteTitle, string webSiteDescription, string webSiteTemplateName, uint lcid, bool isCustomTemplate)
{
SPSite siteCollection = null;
SPWeb web = null;
try
{
siteCollection = new SPSite(siteCollectionUrl);
web = siteCollection.AllWebs[webSiteUrl];
if (web.Exists)
{
// warning site already exist
//if (Properties.Settings.Default.logWarningMessages)
// eventLog.WriteEntry("Site: " + strSiteUrl + " under site collection: " + strSiteCollectionUrl + " alredy exist.", EventLogEntryType.Warning);
return null;
}
else
{
web.Dispose();
web = siteCollection.OpenWeb();
siteCollection.AllowUnsafeUpdates = true;
SPWeb webNew = null;
if (isCustomTemplate)
{
var siteTemplate = siteCollection.GetCustomWebTemplates(lcid)[webSiteTemplateName];
webNew = web.Webs.Add(webSiteUrl, webSiteTitle, webSiteDescription, lcid, siteTemplate, false, false);
}
else
{
webNew = web.Webs.Add(webSiteUrl, webSiteTitle, webSiteDescription, lcid, webSiteTemplateName, false, false);
}
siteCollection.AllowUnsafeUpdates = false;
return webNew;
}
}
catch (Exception exc)
{
//error can't create site
//if (Properties.Settings.Default.logErrorMessages)
// eventLog.WriteEntry(exc.Message, EventLogEntryType.Error);
return null;
}
finally
{
if (web != null)
web.Dispose();
if (siteCollection != null)
siteCollection.Dispose();
}
}
}
}
this is like an interview question given to me by someone, can you tell me whats wrong with it or if there is a better way of doing this. this will be run in a large enterprise. NOTE : Demo.Tasks.Task is a custom object whose deninition is not shown in this code.
using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.WebControls;
using System.Collections;
namespace Demo.WebParts
{
/// <summary>
/// Description for MyTasks.
/// </summary>
[DefaultProperty("Text"),
ToolboxData("<{0}:WebPart1 runat=server></{0}:WebPart1>"),
XmlRoot(Namespace="Demo.Tasks")]
public class MyTasks : Microsoft.SharePoint.WebPartPages.WebPart
{
private const string defaultListName = "";
private string listName = defaultListName;
private ArrayList alTasks;
[Browsable(true),
Category("Miscellaneous"),
DefaultValue(defaultListName),
WebPartStorage(Storage.None),
FriendlyName("List Name Filter"),
Description("The name of sps lists to gather tasks from")]
public string ListName
{
get
{
return listName;
}
set
{
listName = value;
}
}
protected override void CreateChildControls()
{
alTasks = new ArrayList();
try
{
SPWeb myWeb = SPControl.GetContextWeb(this.Context);
foreach(SPList list in myWeb.Lists)
{
if(list.BaseTemplate == SPListTemplateType.Tasks)
{
if(list.Title == listName)
{
getTasksFromList(list);
}
}
}
foreach(SPWeb subWeb in myWeb.Webs)
foreach(SPList list in subWeb.Lists)
if(list.BaseTemplate == SPListTemplateType.Tasks)
getTasksFromList(list);
}
catch
{}
}
private void getTasksFromList(SPList list)
{
for(int i=0;i<list.ItemCount;i++)
{
if(list.Items[i]["AssignedTo"].ToString() == this.Context.User.Identity.Name)
{
Demo.Tasks.Task tsk = Tasks.Task.CreateTask();
tsk.Title = list.Items[i]["Title"].ToString();
tsk.DueDate = (DateTime)list.Items[i]["DueDate"];
tsk.Description = list.Items[i]["Description"].ToString();
tsk.Priority = (int)list.Items[i]["Priority"];
alTasks.Add(tsk);
//now update the item
list.Items[i]["LastViewed"] = DateTime.Now;
}
}
}
/// <summary>
/// Render this Web Part to the output parameter specified.
/// </summary>
/// <param name="output"> The HTML writer to write out to </param>
protected override void RenderWebPart(HtmlTextWriter output)
{
try
{
string strHTML = "";
for(int i=0;i<alTasks.Count;i++)
{
Demo.Tasks.Task tsk = (Demo.Tasks.Task)alTasks[i];
strHTML = strHTML + "The task " + tsk.Title + " is due on " + tsk.DueDate + "<BR>" + tsk.Description + "<BR><BR>";
}
output.Write(strHTML);
}
catch
{}
}
}
}
It would be better if you'll give us more info (what doesn't work, etc.).
But in my opinion you should use 'using' when you're working with SPWeb or SPSite. Not doing this sometimes causes strange errors:
using (SPWeb myWeb = SPControl.GetContextWeb(this.Context))
{
foreach (SPList list in myWeb.Lists)
{
if (list.BaseTemplate == SPListTemplateType.Tasks)
{
if (list.Title == listName)
getTasksFromList(list);
}
}
}
using (SPSite site = new SPSite(SiteUrl))
{
foreach (SPWeb subWeb in site.AllWebs)
{
try //should be 1st statement after foreach
{
foreach (SPList list in subWeb.Lists)
{
if (list.BaseTemplate == SPListTemplateType.Tasks)
getTasksFromList(list);
}
}
finally
{
if (subWeb != null)
subWeb.Dispose();
}
}
}
Here you can read about this:
http://blogs.msdn.com/b/rogerla/archive/2009/01/14/try-finally-using-sharepoint-dispose.aspx
I am in the process of upgrading our custom solutions to Sharepoint 2010. I wanted to utilize the WorkflowCompleted event handler but I don't seem to be able to get the relevant SPListItem from the event properties.
I tried using SPWorkflowEventProperties.ActivationProperties but this always returns null (even in the WorkflowStarted event handler).
How do I get the context from workflow event handlers (SPListItem, SPWeb, SPSite etc)?
I've found the same thing. SPWorkflowEventProperties is practically useless since just about everything is null. It doesn't tell status (Approved, Rejected, etc). And, most importantly, it doesn't (directly) tell what item was completed. Hopefully this will be addressed in future versions. In the meantime, I used the following:
public override void WorkflowCompleted(SPWorkflowEventProperties properties)
{
using (SPSite site = new SPSite(properties.WebUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPListItem task = GetApprovedTask(properties, web);
SPListItem item = GetApprovedItem(web, task);
if (null != item)
{
// TODO : process approved item
}
}
}
}
private SPListItem GetApprovedItem(SPWeb web, SPListItem task)
{
SPListItem item = null;
if (null != task)
{
SPList list = web.Lists[new Guid(task[SPBuiltInFieldId.WorkflowListId].ToString())];
item = list.GetItemById((int)task[SPBuiltInFieldId.WorkflowItemId]);
}
return item;
}
private SPListItem GetApprovedTask(SPWorkflowEventProperties properties, SPWeb web)
{
SPListItem item = null;
string caml = #"<Where><And><And><And><Eq><FieldRef Name='WorkflowOutcome' /><Value Type='Text'>Approved</Value></Eq><Eq><FieldRef Name='WorkflowInstanceID' /><Value Type='Guid'>{0}</Value></Eq></And><IsNotNull><FieldRef Name='WorkflowListId' /></IsNotNull></And><IsNotNull><FieldRef Name='WorkflowItemId' /></IsNotNull></And></Where>";
SPQuery query = new SPQuery();
query.Query = string.Format(caml, properties.InstanceId);
query.RowLimit = 1;
SPList list = web.Lists["Tasks"];
SPListItemCollection items = list.GetItems(query);
if (items.Count > 0)
{
item = items[0];
}
return item;
}
You can use the InstanceId property to retrieve the SPListItem from the workflow task list as shown in this post
http://blog.symprogress.com/2011/09/sp-2010-get-workflow-status-workflowcompleted-event/
If you can be more generous with details I can be more specific with answer.
But this is generally what you need to do:
Set context specific properties
public static DependencyProperty _ContextProperty
= System.Workflow.ComponentModel.DependencyProperty.Register("_Context",
typeof(WorkflowContext), typeof(MyCustomActivity));
[Description("Site Context")]
[Category("User")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public WorkflowContext __Context
{
get
{
return ((WorkflowContext)(base.GetValue(MyCustomActivity.__ContextProperty)));
}
set
{
base.SetValue(MyCustomActivity.__ContextProperty, value);
}
}
public static DependencyProperty __ListIdProperty
= System.Workflow.ComponentModel.DependencyProperty.Register("__ListId",
typeof(string), typeof(MyCustomActivity));
[ValidationOption(ValidationOption.Required)]
public string __ListId
{
get
{
return ((string)(base.GetValue(MyCustomActivity.__ListIdProperty)));
}
set
{
base.SetValue(MyCustomActivity.__ListIdProperty, value);
}
}
public static DependencyProperty __ListItemProperty
= System.Workflow.ComponentModel.DependencyProperty.Register("__ListItem",
typeof(int), typeof(MyCustomActivity));
[ValidationOption(ValidationOption.Required)]
public int __ListItem
{
get
{
return ((int)(base.GetValue(MyCustomActivity.__ListItemProperty)));
}
set
{
base.SetValue(MyCustomActivity.__ListItemProperty, value);
}
}
public static DependencyProperty __ActivationPropertiesProperty
= DependencyProperty.Register("__ActivationProperties",
typeof(Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties), typeof(MyCustomActivity));
[ValidationOption(ValidationOption.Required)]
public Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties __ActivationProperties
{
get
{
return (Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties)base.GetValue(MyCustomActivity.__ActivationPropertiesProperty);
}
set
{
base.SetValue(MyCustomActivity.__ActivationPropertiesProperty, value);
}
}
You will get context in __Context and everything else from __Context like this:
protected override ActivityExecutionStatus
Execute(ActivityExecutionContext executionContext) {
// Raise Invoke Event to execute custom code in the workflow.
this.RaiseEvent(MyCustomActivity.InvokeEvent,
this, EventArgs.Empty);
SPWeb _cxtWeb = null;
String _strLinfo = "Dll;";
String _strTo = String.Empty;
// Set Context
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (_cxtWeb = __Context.Web)
{
//_cxtWeb = __Context.Web;
Guid _cListId = new Guid(__ListId);
SPList _cSPList = _cxtWeb.Lists[_cListId]; // TimeLog
SPListItem _cListItem = _cSPList.GetItemById(__ListItem);
SMTPSERVER = _cxtWeb.Site.WebApplication
.OutboundMailServiceInstance.Server.Address;
}
});
}
catch { /**/ }
}
I wanted to programmatically start workflow when itemAdded in Pages Library.
I do as following :
public override void ItemAdded(SPItemEventProperties properties)
{
SPListItem listItem = properties.ListItem;
StartWF(listItem);
}
public void StartWF(SPListItem listItem)
{
using(SPWeb web = listItem.Web) {
using(SPSite site = web.Site) {
SPWorkflowManager manager = site.WorkflowManager;
SPList parentList = listItem.ParentList;
SPWorkflowAssociationCollection associationCollection =
parentList.WorkflowAssociations;
foreach(SPWorkflowAssociation association in
associationCollection) {
if (association.Name == "APWFAnn2010") {
string data =
association.AssociationData;
SPWorkflow wf =
manager.StartWorkflow(listItem,
association,
association.
AssociationData);
}
}
}
}
}
then I hit this error "The system cannot find the file specified. (Exception from HRESULT: 0x80070002)"
"APWFAnn2010" is the workflow name I wanted to start. It is SP default Approval Workflow created in Pages Library.
Please help, thank you in advance.
You can also pass in the name into the function above by doing it this way, and then you'd have a function that can start any workflow on any item:
public void StartWF(SPListItem listItem, SPSite spSite, string wfName)
{
SPList parentList = listItem.ParentList;
SPWorkflowAssociationCollection associationCollection = parentList.WorkflowAssociations;
foreach (SPWorkflowAssociation association in associationCollection)
{
if (association.Name == wfName)
{
association.AutoStartChange = true;
association.AutoStartCreate = false;
association.AssociationData = string.Empty;
spSite.WorkflowManager.StartWorkflow(listItem, association, association.AssociationData);
}
}
}
First of you have your using site within the using web it should be the other way around - on the other hand I don't even see you using the SPWeb, so why have it in there?. And secondly I would rewrite the code a bit:
public override void ItemAdded(SPItemEventProperties properties)
{
SPListItem listItem = properties.ListItem;
spSite = properties.OpenWeb().Site;
spWeb = properties.Web;
using(spSite) {
StartWF(listItem, spSite);
}
}
public void StartWF(SPListItem listItem, SPSite spSite)
{
SPList parentList = listItem.ParentList;
SPWorkflowAssociationCollection associationCollection =
parentList.WorkflowAssociations;
foreach(SPWorkflowAssociation association in associationCollection) {
if (association.Name == "APWFAnn2010") {
association.AutoStartChange = true;
association.AutoStartCreate = false;
association.AssociationData = string.Empty;
spSite.WorkflowManager.StartWorkflow(listItem,
association,
association.AssociationData);
}
}
}
I need to add custom handling to a lists' adding event. However, the event does not appear to be firing. I would like my custom handler defined in EventReceivers to fire anytime a new item of the custom type is added to the list.
I would appreciate any suggestions.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace MyTestGroupListFeature
{
class MyTestGroupListFeature : SPFeatureReceiver
{
private const string LISTNAME = "Acquisition Groups";
private const string CONTENTTYPE_LISTNAME = "Contenttype List";
private const string FOO = "FOO";
private const string SITE_TEMPLATE_EXTENSION = ".stp";
public override void FeatureInstalled
(SPFeatureReceiverProperties properties)
{
}
public override void FeatureUninstalling
(SPFeatureReceiverProperties properties)
{
FeatureDeactivating(properties);
}
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
try
{
SPWeb web = properties.Feature.Parent as SPWeb;
SPList list = GetList(web, LISTNAME);
SPSite site = web.Site;
site.AllowUnsafeUpdates = true;
SPContentType newCType = CreateSourceSystemContentType(web);
SPList listct = web.Lists[CONTENTTYPE_LISTNAME];
AddEventReceiverToList(listct);
AddContentTypeToList(web, listct, newCType);
}
catch { }
}
/// <summary>
/// Creates a content type for Source System
/// </summary>
private SPContentType CreateSourceSystemContentType(SPWeb site)
{
//Create site columns
string acronymFieldName = site.Fields.Add("Acronym", SPFieldType.Text, true);
SPFieldText acronymField = (SPFieldText)site.Fields.GetFieldByInternalName(acronymFieldName);
acronymField.Group = "AQSIDM Columns";
acronymField.Update();
string nameFieldName = site.Fields.Add("Name", SPFieldType.Text, true);
SPFieldText nameField = (SPFieldText)site.Fields.GetFieldByInternalName(nameFieldName);
acronymField.Group = "AQSIDM Columns";
acronymField.Update();
string descriptionFieldName = site.Fields.Add("Description", SPFieldType.Text, true);
SPFieldText descriptionField = (SPFieldText)site.Fields.GetFieldByInternalName(descriptionFieldName);
descriptionField.Group = "AQSIDM Columns";
descriptionField.Update();
// Get the parent content type.
SPContentTypeId itemCTID = new SPContentTypeId("0x01");
SPContentType itemCT = site.AvailableContentTypes[itemCTID];
//Create SourceSystem content type:
SPContentType sourceSystemCT = new SPContentType(itemCT, site.ContentTypes, "Source System");
sourceSystemCT.Group = "Source System Content Types";
//Add columns to content type
sourceSystemCT = site.ContentTypes[sourceSystemCT.Id];
SPFieldLink acronymLink = new SPFieldLink(acronymField);
sourceSystemCT.FieldLinks.Add(acronymLink);
//
SPFieldLink nameLink = new SPFieldLink(nameField);
sourceSystemCT.FieldLinks.Add(nameLink);
//
SPFieldLink descriptionLink = new SPFieldLink(descriptionField);
sourceSystemCT.FieldLinks.Add(descriptionLink);
//
//sourceSystemCT.Update();
string assemblyName = System.Reflection.Assembly.GetEntryAssembly().FullName;
string ctReceiverName = "MyTestGroupListFeature.EventReceivers";
sourceSystemCT.EventReceivers.Add(SPEventReceiverType.ItemAdding, assemblyName, ctReceiverName);
sourceSystemCT.Update(true);
site.ContentTypes.Add(sourceSystemCT);
return sourceSystemCT;
}
/// <summary>
/// Adds a custom content type to site's list
/// </summary>
private void AddContentTypeToList(SPWeb web, SPList list, SPContentType ct)
{
list.ContentTypesEnabled = true;
list.ContentTypes.Add(ct);
list.Update();
// Add the item:
SPListItem newItem = list.Items.Add();
newItem["Acronym"] = "Acronym Field Added";
newItem.Update();
}
/// <summary>
/// Programmatically add new event receivers
/// </summary>
private void AddEventReceiverToList(SPList list)
{
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
SPEventReceiverDefinition eventReceiver = list.EventReceivers.Add();
eventReceiver.Name = "On Updating";
eventReceiver.Type = SPEventReceiverType.ItemAdding;
eventReceiver.SequenceNumber = 200;
eventReceiver.Assembly = assembly.FullName;
eventReceiver.Class = "MyTestGroupListFeature.EventReceivers";
eventReceiver.Update();
}
}
class EventReceivers : SPItemEventReceiver
{
/// <summary>
/// Test behavior when adding an item
/// </summary>
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
SourceSystem ss = new SourceSystem();
ss.Name = "sharepointss";
ss.Acronym = "sharepoint acronym";
ss.Description = "desc";
ss.EndPoint = new Uri(#"\testURI");
ss.Update("foo");
ss.Create(String.Format("SourceSystem_Create_SP_{0:o}", DateTime.Now));
}
}
}
After you activated the feature, did you verify whether or not the event receiver was attached to the list? This can be done programatically or using tools such as SharePoint Manager.