'激活功能':对象引用未设置为对象的实例

时间:2013-06-04 14:35:58

标签: c# sharepoint-2010 object-reference sharepoint-feature feature-activation

我有以下激活码:

    public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        // Create a new list and populate it.
        using (SPWeb web = properties.Feature.Parent as SPWeb)
        {
            web.Lists.Add("Projects", "Projects That are currently being worked on.", SPListTemplateType.GenericList);
            web.Update();

            // Add the new list and the new content.
            SPList projectList = web.Lists["Projects"];
            projectList.Fields.Add("Name", SPFieldType.Text, false);
            projectList.Fields.Add("Description", SPFieldType.Text, false);
            projectList.Update();

            //Create the view? - Possibly remove me.
            System.Collections.Specialized.StringCollection stringCollection = 
                new System.Collections.Specialized.StringCollection();
            stringCollection.Add("Name");
            stringCollection.Add("Description");

            //Add the list.
            projectList.Views.Add("Project Summary", stringCollection, @"", 100, 
                true, true, Microsoft.SharePoint.SPViewCollection.SPViewType.Html, false);
            projectList.Update();
        }
    }

应该检查并添加一个名为project及其关联视图的新列表。在运行应用程序时我得到了什么:

  

'激活功能':对象引用未设置为实例   对象

我的问题是:

  • 为什么会这样?激活发生在站点级别。我是“开发”网站的管理员
  • 我应该每次检查以确保此列表尚不存在吗? (每次,每次我点击部署时)

1 个答案:

答案 0 :(得分:1)

我将假设您有一个网站范围功能,并且您NullReferenceException是由您尝试投射properties.Feature.Parent as SPWeb造成的。

如果我对您的网站作用域功能的假设是正确的,则无法以您尝试的方式访问SPWeb。试试这个:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    SPSite siteCollection = properties.Feature.Parent as SPSite;
    if (siteCollection != null) 
    {
        SPWeb web = siteCollection.RootWeb;
        // Rest of your code here.
    }
}