0

I created a Farm Solution visual web part in a development environment (VM). I've run into issue while attempting to deploy this Visual Web Part in a test environment. I added (Add-SPSolution), installed (Install-SPSolution) and enabled the feature in our test environment. The web part is visible in the Web Part Gallery. In the development environment the web part is functioning perfectly and effectively aggregates SharePoint and AD user data.

When I go to add the web part to a site/sub site from the Web Part gallery, I receive the following error: Object reference not set to an instance of an object.

I am ripping my hair out trying to figure this out, any help would be greatly appreciated. This is my first attempt at writing a custom Web Part and it has been quite a learning experiencing putting together a dev environment, installing SharePointServer 2010 and linking this all together. Mind you the issue is not with my VM dev environment but with the corporate test environment.

ASCX.CS:

using System;
using System.Data;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.WebControls;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Collections.Generic;
using System.Diagnostics;

namespace AggregateUserData.VisualWebPart1
{
    public class DataContainer
    {
        public List<AggregateGroup> items { get; set; }
    }

    public class AggregateGroup
    {
        public string name { get; set; }
        public string perm { get; set; }
        public string user { get; set; }
        public string email { get; set; }
    }

    public class Aggregate
    {
        public List<AggregateGroup> GetGroups()
        {           
            List<AggregateGroup> list = new List<AggregateGroup>();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
                SPWeb web = SPContext.Current.Web;
                foreach (SPUser user in web.Users)
                {
                    if (user.IsDomainGroup == true)
                    {
                        SPRoleAssignment currUserRole = web.RoleAssignments.GetAssignmentByPrincipal(user);
                        foreach (SPRoleDefinition role in currUserRole.RoleDefinitionBindings)
                        {
                            GroupPrincipal adGroup = GroupPrincipal.FindByIdentity(ctx, user.Name);
                            foreach (System.DirectoryServices.AccountManagement.Principal principal in adGroup.GetMembers())
                            {
                                AggregateGroup spGroup = new AggregateGroup();
                                spGroup.name = user.LoginName;
                                spGroup.perm = role.Name;
                                spGroup.user = principal.DisplayName;

                                UserPrincipal u = UserPrincipal.FindByIdentity(ctx, principal.DistinguishedName);
                                spGroup.email = u.EmailAddress;

                                list.Add(spGroup);
                            }
                        }
                    }
                }
            });
            return list;
        }
    }
    [ToolboxItemAttribute(false)]
    public partial class VisualWebPart1 : WebPart
    {
        // Uncomment the following SecurityPermission attribute only when doing Performance Profiling using
        // the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
        // for production. Because the SecurityPermission attribute bypasses the security check for callers of
        // your constructor, it's not recommended for production purposes.
        // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
        public VisualWebPart1()
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                Aggregate aggregate = new Aggregate();
                DataContainer dataContainer = new DataContainer();
                dataContainer.items = aggregate.GetGroups();
                string returnHtml = "";
                foreach (var item in dataContainer.items)
                {
                    returnHtml += "<tr><td>" + item.name + "</td><td>" + item.perm + "</td><td>" + item.user + "</td><td>" + item.email + "</td></tr>";
                }
                userData.InnerHtml = returnHtml;
                ErrorOut.InnerText = "This is the error output label"; 
            }
            catch (Exception Exc)
            {
                ErrorOut.InnerText = Exc.ToString(); 
            }
        }
    }
}

ASCX:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %> 
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="VisualWebPart1.ascx.cs" Inherits="AggregateUserData.VisualWebPart1.VisualWebPart1" %>
<script type="text/javascript" src="SiteAssets/datatables/jQuery-1.11.3/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="SiteAssets/datatables/datatables.min.js"></script>
<link rel="stylesheet" type="text/css" href="SiteAssets/datatables/datatables.min.css">
<script>
    $(document).ready(function () {
        $('#userDataTable').DataTable();
    });
</script>
<h1>Aggregate User Data v1.1</h1>
<table id ="userDataTable">
    <thead>
        <tr>
            <th>Group Name</th>
            <th>Permission</th>
            <th>User</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody id="userData" runat="server"></tbody>
</table>
<br />
<label id="ErrorOut" runat="server"></label>

Update 08/24/2015

I am receiving the following error (permissions related?):

System.NullReferenceException: 
Object reference not set to an instance of an object. at AggregateUserData.VisualWebPart1.Aggregate.<>c__DisplayClass1.<GetGroups>b__0() at Microsoft.SharePoint.SPSecurity.<>c__DisplayClass4.<RunWithElevatedPrivileges>b__2() at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode) at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param) at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode) at AggregateUserData.VisualWebPart1.Aggregate.GetGroups() at AggregateUserData.VisualWebPart1.VisualWebPart1.Page_Load(Object sender, EventArgs e) 
  • Have you tried by again Deploying wsp by deleting the existing feature and add new feature in visual studio? – Saira Sep 8 '17 at 5:46
  • Try debugging the web part or add some debug logging in the loop to see where it may be failing. It could be 'currUserRole' or 'adGroup' that are null. Also, RunWithElevated only works if you instantiate a new SPSite and SPWeb, not by reusing context objects. But that's another matter. – Steven Van de Craen Oct 10 '17 at 9:17
2

There's a lot of locations in your code that may fail with an NRE. For instance, it could be the group that is not found, or a group with no email address...

Your only hope is to get more information on the error (like the Stack Trace).

For that purpose, you may:

  1. Add try...catch blocks in your code (a best pratice anyway), and display detailed error info in a label.
  2. Look at the ULS logs (http://samirvaidya.blogspot.fr/2012/03/where-are-sharepoint-uls-logs.html).
  3. Or edit your web.config file on the test environment, so you directly get the error message on the screen (see http://blog-sharepoint.blogspot.fr/2009/12/sharepoint-webconfig-how-to-show-full.html).
  • Thank you so much. As someone relatively new to C# and SharePoint this is really helpful. I'll be doing some research. – David Calvin Aug 24 '15 at 15:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.