使用Logging Service时,对象引用未设置为对象的实例

时间:2015-08-20 14:29:09

标签: c# sharepoint

在sharepoint中,我有此功能可以安装日志服务。

这是我的日志记录服务

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;

namespace MundoNetElements
{
    public enum LoggingCategory
    {
        None = 0,
        WebPart,
        AppPage,
        MasterPage,
        Control,
        Taxonomy,
        Workflow,
        EventReceiver,
        Job,
        Deployment,
        General,
        Feature,
        Database,
        Security
    }

    /// <summary>
    /// Areas
    /// </summary>
    public enum LoggingArea
    {
        MundoNet
    }

    public class LoggingService : SPDiagnosticsServiceBase
    {

        /// <summary>
        /// Gets the current logging service
        /// </summary>
        public static LoggingService Current
        {
            get { return SPFarm.Local.Services.GetValue<LoggingService>(DefaultName); }
        }

        /// <summary>
        /// Gets the AreaName of the DMS logging service
        /// </summary>
        public static string AreaName { get { return "MundoNet"; } }

        /// <summary>
        /// Gets the default name of the DMS logging service
        /// </summary>
        public static string DefaultName
        {
            get { return AreaName + " Logging Service"; }
        }


        public LoggingService() : base(DefaultName, SPFarm.Local) { }

        public LoggingService(string name, SPFarm farm) : base(name, farm) { }

        protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
        {
            List<SPDiagnosticsCategory> diagnosticCategories = new List<SPDiagnosticsCategory>();

            // ReSharper disable LoopCanBeConvertedToQuery
            foreach (string category in Enum.GetNames(typeof(LoggingCategory)))
            // ReSharper restore LoopCanBeConvertedToQuery
            {
                uint categoryId = (uint)(int)Enum.Parse(typeof(LoggingCategory), category);
                //Defined below the default TraceSeverity example: set to TraceSeverity.Verbose: log also verbose messages
                diagnosticCategories.Add(new SPDiagnosticsCategory(category, TraceSeverity.Verbose, EventSeverity.Information, 0, categoryId));
            }

            yield return new SPDiagnosticsArea(AreaName, diagnosticCategories);
        }


        /// <summary>
        /// Logs an Error message
        /// </summary>
        /// <param name="category">Category name</param>
        /// <param name="errorMessage">Error message</param>
        public static void LogError(LoggingCategory category, string errorMessage)
        {
            WriteToTraceLog(category, errorMessage, TraceSeverity.Unexpected);
        }

        /// <summary>
        /// Logs an Error message
        /// </summary>
        /// <param name="area">Area name</param>
        /// <param name="category">Category name</param>
        /// <param name="errorMessage">Error message</param>
        public static void LogError(LoggingArea area, LoggingCategory category, string errorMessage)
        {
            WriteToTraceLog(area, category, errorMessage, TraceSeverity.Unexpected);
        }

        /// <summary>
        /// Logs an Error message
        /// </summary>
        /// <param name="category"></param>
        /// <param name="exception"></param>
        public static void LogError(LoggingCategory category, Exception exception)
        {
            string error = string.Concat(" (" + exception.Message, ") ", exception.GetType(), " ", exception.StackTrace);
            Exception innerException = exception.InnerException;
            while (innerException != null)
            {
                error += string.Concat("Inner Error: ", innerException.Message, " ", innerException.StackTrace);
                innerException = innerException.InnerException;
            }

            WriteToTraceLog(category, error, TraceSeverity.Unexpected);
        }

        /// <summary>
        /// Logs an Error message
        /// </summary>
        /// <param name="area"></param>
        /// <param name="category"></param>
        /// <param name="exception"></param>
        public static void LogError(LoggingArea area, LoggingCategory category, Exception exception)
        {
            string error = string.Concat(" (" + exception.Message, ") ", exception.GetType(), " ", exception.StackTrace);
            Exception innerException = exception.InnerException;
            while (innerException != null)
            {
                error += string.Concat("Inner Error: ", innerException.Message, " ", innerException.StackTrace);
                innerException = innerException.InnerException;
            }

            WriteToTraceLog(area, category, error, TraceSeverity.Unexpected);
        }

        /// <summary>
        /// Logs an Error message
        /// </summary>
        /// <param name="category"></param>
        /// <param name="exception"></param>
        /// <param name="errorMessage"></param>
        public static void LogError(LoggingCategory category, Exception exception, string errorMessage)
        {
            string error = string.Concat(errorMessage, " (" + exception.Message, ") ", exception.GetType(), " ", exception.StackTrace);
            Exception innerException = exception.InnerException;
            while (innerException != null)
            {
                error += string.Concat("Inner Error: ", innerException.Message, " ", innerException.StackTrace);
                innerException = innerException.InnerException;
            }

            WriteToTraceLog(category, error, TraceSeverity.Unexpected);
        }

        /// <summary>
        /// Logs an Error message
        /// </summary>
        /// <param name="area"></param>
        /// <param name="category"></param>
        /// <param name="exception"></param>
        /// <param name="errorMessage"></param>
        public static void LogError(LoggingArea area, LoggingCategory category, Exception exception, string errorMessage)
        {
            string error = string.Concat(errorMessage, " (" + exception.Message, ") ", exception.GetType(), " ", exception.StackTrace);
            Exception innerException = exception.InnerException;
            while (innerException != null)
            {
                error += string.Concat("Inner Error: ", innerException.Message, " ", innerException.StackTrace);
                innerException = innerException.InnerException;
            }

            WriteToTraceLog(area, category, error, TraceSeverity.Unexpected);
        }

        /// <summary>
        /// Logs an informational message 
        /// </summary>
        /// <param name="category"></param>
        /// <param name="infoMessage"></param>
        public static void LogInfo(LoggingCategory category, string infoMessage)
        {
            WriteToTraceLog(category, infoMessage, TraceSeverity.Medium);
        }

        /// <summary>
        /// Log a verbose Message
        /// </summary>
        /// <param name="area"></param>
        /// <param name="category"></param>
        /// <param name="verboseMessage"></param>
        public static void LogInfo(LoggingArea area, LoggingCategory category, string verboseMessage)
        {
            WriteToTraceLog(area, category, verboseMessage, TraceSeverity.Medium);
        }

        /// <summary>
        /// Log a warning Message
        /// </summary>
        public static void LogWarning(LoggingCategory category, string warningMessage)
        {
            WriteToTraceLog(category, warningMessage, TraceSeverity.High);
        }

        /// <summary>
        /// Log a verbose Message
        /// </summary>
        /// <param name="area"></param>
        /// <param name="category"></param>
        /// <param name="verboseMessage"></param>
        public static void LogWarning(LoggingArea area, LoggingCategory category, string verboseMessage)
        {
            WriteToTraceLog(area, category, verboseMessage, TraceSeverity.High);
        }

        /// <summary>
        /// Log a verbose Message
        /// </summary>
        /// <param name="category"></param>
        /// <param name="verboseMessage"></param>
        public static void LogVerbose(LoggingCategory category, string verboseMessage)
        {
            WriteToTraceLog(category, verboseMessage, TraceSeverity.Verbose);
        }

        /// <summary>
        /// Log a verbose Message
        /// </summary>
        /// <param name="area"></param>
        /// <param name="category"></param>
        /// <param name="verboseMessage"></param>
        public static void LogVerbose(LoggingArea area, LoggingCategory category, string verboseMessage)
        {
            WriteToTraceLog(area, category, verboseMessage, TraceSeverity.Verbose);
        }

        private static void WriteToTraceLog(LoggingCategory category, string message, TraceSeverity severity)
        {
            SPDiagnosticsCategory diagnosticCategory = Current.Areas[AreaName].Categories[category.ToString()];
            Current.WriteTrace(0, diagnosticCategory, severity, message);
        }

        private static void WriteToTraceLog(LoggingArea area, LoggingCategory category, string message, TraceSeverity severity)
        {
            string areaName = Enum.GetName(typeof(LoggingArea), area);
            SPDiagnosticsCategory diagnosticCategory = Current.Areas[areaName].Categories[category.ToString()];
            Current.WriteTrace(0, diagnosticCategory, severity, message);
        }
    }

}

这是我的功能激活和停用

using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;
using Microsoft.Win32;

namespace MundoNetElements.Features.LogginService
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("4ecdaf73-b83d-42dc-a08a-953f90676187")]
    public class LogginServiceEventReceiver : SPFeatureReceiver
    {
        const string EventLogApplicationRegistryKeyPath =
           @"SYSTEM\CurrentControlSet\services\eventlog\Application";
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            RegisterLoggingService(properties);
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            UnRegisterLoggingService(properties);
        }

        static void RegisterLoggingService(SPFeatureReceiverProperties properties)
        {
            if (properties.Definition.Farm != null)
            {
                MundoNetElements.LoggingService service = new LoggingService();

                if (service == null)
                {
                    service = new MundoNetElements.LoggingService();
                    service.Update();

                    if (service.Status != SPObjectStatus.Online)
                        service.Provision();
                }

                foreach (SPServer server in properties.Definition.Farm.Servers)
                {
                    if (server.Role != SPServerRole.Invalid)
                    {
                        RegistryKey baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, server.Address);

                        RegistryKey eventLogKey = baseKey.OpenSubKey(EventLogApplicationRegistryKeyPath, true);

                        if (eventLogKey != null)
                        {
                            RegistryKey loggingServiceKey = eventLogKey.OpenSubKey(MundoNetElements.LoggingService.AreaName);

                            if (loggingServiceKey == null)
                            {
                                loggingServiceKey = eventLogKey.CreateSubKey(MundoNetElements.LoggingService.AreaName, RegistryKeyPermissionCheck.ReadWriteSubTree);
                                // ReSharper disable PossibleNullReferenceException
                                loggingServiceKey.SetValue("EventMessageFile",
                                    // ReSharper restore PossibleNullReferenceException
                                    @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\EventLogMessages.dll",
                                    RegistryValueKind.String);
                            }
                        }

                    }
                }
            }
        }

        static void UnRegisterLoggingService(SPFeatureReceiverProperties properties)
        {
            #region Unregister Logging Service for DMS
            if (properties.Definition.Farm != null)
            {
                MundoNetElements.LoggingService service = MundoNetElements.LoggingService.Current;

                if (service != null)
                    service.Delete();

                foreach (SPServer server in properties.Definition.Farm.Servers)
                {
                    if (server.Role != SPServerRole.Invalid)
                    {
                        RegistryKey baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, server.Address);

                        RegistryKey eventLogKey = baseKey.OpenSubKey(EventLogApplicationRegistryKeyPath, true);

                        if (eventLogKey != null)
                        {
                            RegistryKey loggingServiceKey = eventLogKey.OpenSubKey(MundoNetElements.LoggingService.AreaName);

                            if (loggingServiceKey != null)
                                eventLogKey.DeleteSubKey(MundoNetElements.LoggingService.AreaName);
                        }

                    }
                }
            }
            #endregion

        }
    }
}

这是我用来使用记录器服务的一行代码。

 public class NotificacionesContratosJobEventReceiver : SPFeatureReceiver
    {
        const string List_JOB_NAME = "Notificaciones Contratos Job";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                LoggingService.LogInfo(LoggingCategory.Job, "Installing Job");
                SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;

但是,我没有将Object引用设置为对象的实例。挖掘深度我们发现null在这个强制服务方法的Current属性上

  private static void WriteToTraceLog(LoggingCategory category, string message, TraceSeverity severity)
        {
            SPDiagnosticsCategory diagnosticCategory = Current.Areas[AreaName].Categories[category.ToString()];
            Current.WriteTrace(0, diagnosticCategory, severity, message);
        }

然而,我对正在发生的事情一无所知

1 个答案:

答案 0 :(得分:3)

所以你的服务没有注册。但你在哪里注册呢?这段代码:

MundoNetElements.LoggingService service = new LoggingService();

            if (service == null)
            {
                service = new MundoNetElements.LoggingService();
                service.Update();

                if (service.Status != SPObjectStatus.Online)
                    service.Provision();
            }

永远不会在内部执行&#34;如果&#34;,因为您首先创建服务实例,然后将其检查为空。