Remoting PerfMon Service


//Server.cs
namespace Microshaoft.RemotingObjects.Server
{
    using System;
    using System.Threading;
    using System.Collections;
    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
    using System.Runtime.Serialization.Formatters;
    using System.ServiceProcess;
    using System.ComponentModel;
    using System.Configuration.Install;
    using System.Security.Principal;
    using Microshaoft.RemotingObjects.ServiceContracts.Share;
    using Microshaoft.Win32;
    using Microshaoft;
    public class ServiceHost : ServiceBase
    {
        ///// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        //[STAThread]
        public static readonly string serviceName = "eHome Remoting PerfMon Service";
        static void Main(string[] args)
        {
            //Microshaoft
            //Microshaoft TODO: 在此处添加代码以启动应用程序
            //Microshaoft 
            ServiceHost service = new ServiceHost();
            int l = 0;
            bool needFreeConsole = false;
            if (args != null)
            {
                l = args.Length;
            }
            if (l > 0)
            {
                if (args[0].ToLower() == "/console")
                {
                    needFreeConsole = true;
                    NativeMethods.AllocConsole();
                    Console.Title = "Server ...";
                    Console.WriteLine("Alloc Console ...");
                    Console.WriteLine("Current User Identity: {0}", WindowsIdentity.GetCurrent().Name);
                    Console.WriteLine(".Net Framework version: {0}", Environment.Version.ToString());
                }
                Console.Title = "Server"; //不能以服务运行
                Console.WriteLine("Console");
                service.OnStart(null);
                Console.ReadLine();
                return;
            }
            Console.WriteLine("Service");
            ServiceBase.Run(service);
            if (needFreeConsole)
            {
                Console.WriteLine("Free Console ...");
                NativeMethods.FreeConsole();
            }
        }
        public ServiceHost()
        {
            CanPauseAndContinue = true;
            ServiceName = ServiceHost.serviceName;
        }
        protected override void OnStart(string[] args)
        {
            Console.WriteLine(Environment.Version.ToString());
            RemotingHelper.StartRemoting<RemotingPerformanceMonitor>
                                (
                                    "perfmonurl"
                                    , 8082
                                );
        }
    }
    [RunInstallerAttribute(true)]
    public class ProjectInstaller : Installer
    {
        private ServiceInstaller serviceInstaller;
        private ServiceProcessInstaller processInstaller;
        public ProjectInstaller()
        {
            processInstaller = new ServiceProcessInstaller();
            serviceInstaller = new ServiceInstaller();
            // Service will run under system account
            processInstaller.Account = ServiceAccount.LocalSystem;
            // Service will have Start Type of Manual
            serviceInstaller.StartType = ServiceStartMode.Manual;
            serviceInstaller.ServiceName = ServiceHost.serviceName;
            Installers.Add(serviceInstaller);
            Installers.Add(processInstaller);
        }
    }
}
namespace Microshaoft.Win32
{
    using System.Runtime.InteropServices;
    public class NativeMethods
    {
        /// <summary>
        /// 启动控制台
        /// </summary>
        /// <returns></returns>
        [DllImport("kernel32.dll")]
        public static extern bool AllocConsole();
        /// <summary>
        /// 释放控制台
        /// </summary>
        /// <returns></returns>
        [DllImport("kernel32.dll")]
        public static extern bool FreeConsole();
    }
}
namespace Microshaoft.RemotingObjects
{
    using System;
    using System.IO;
    using System.Net;
    using System.Web;
    using System.Text;
    using System.Threading;
    using System.Configuration;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Globalization;
    using Microshaoft;
    using Microshaoft.RemotingObjects.Server;
    using Microshaoft.RemotingObjects.ServiceContracts.Share;
    public class RemotingPerformanceMonitor : MarshalByRefObject, IRemotingPerformanceMonitor
    {
        public string[] ReadAllInstancePerformanceCounterNextValue(string categoryName, string[] instanceNamesFilter, string[] countersName)
        {
            try
            {
                PerformanceCounterCategory pcc = new PerformanceCounterCategory(categoryName);
                string[] instances = pcc.GetInstanceNames();
                List<string> list = new List<string>();
                foreach (string instanceNameFilter in instanceNamesFilter)
                {
                    //f = instanceNameFilter.ToLower();
                    foreach (string s in instances)
                    {
                        string instance = "";
                        if (string.IsNullOrEmpty(instanceNameFilter))
                        {
                            instance = s;
                        }
                        else
                        {
                            if (s.ToLower().IndexOf(instanceNameFilter.ToLower()) >= 0)
                            {
                                instance = s;
                                Console.WriteLine(instance);
                            }
                        }
                        if (!string.IsNullOrEmpty(instance))
                        {
                            foreach (string counterName in countersName)
                            {
                                string[] l = ReadInstancePerformanceCounterNextValue(categoryName, instance, counterName);
                                if (l.Length > 0)
                                {
                                    list.AddRange(l);
                                }
                            }
                        }
                    }
                }
                return list.ToArray();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }
        }
        public string[] ReadAllInstanceAllPerformanceCounterNextValue(string categoryName, string instanceNameFilter)
        {
            try
            {
                PerformanceCounterCategory pcc = new PerformanceCounterCategory(categoryName);
                string[] instances = pcc.GetInstanceNames();
                List<string> list = new List<string>();
                instanceNameFilter = instanceNameFilter.ToLower();
                foreach (string s in instances)
                {
                    string instance = "";
                    if (string.IsNullOrEmpty(instanceNameFilter))
                    {
                        instance = s;
                    }
                    else
                    {
                        Console.WriteLine(s);
                        if (s.ToLower().IndexOf(instanceNameFilter) >= 0)
                        {
                            instance = s;
                        }
                    }
                    if (!string.IsNullOrEmpty(instance))
                    {
                        string[] l = ReadInstanceAllPerformanceCounterNextValue(categoryName, instance);
                        if (l.Length > 0)
                        {
                            list.AddRange(l);
                        }
                    }
                }
                return list.ToArray();
            }
            catch //(Exception e)
            {
                return null;
            }
        }
        public string[] ReadInstanceAllPerformanceCounterNextValue(string categoryName, string instanceName)
        {
            PerformanceCounterCategory pcc = new PerformanceCounterCategory(categoryName);
            PerformanceCounter[] counters = pcc.GetCounters(instanceName);
            List<string> list = new List<string>();
            foreach (PerformanceCounter counter in counters)
            {
                list.Add
                        (
                            string.Format
                                        (
                                            "Machine[{0}] - Category[{1}] - Instance[{2}] - Counter[{3}]: {4:dddd.dddd}"
                                            , counter.MachineName
                                            , categoryName
                                            , counter.InstanceName
                                            , counter.CounterName
                                            , counter.NextValue()
                                        )
                        );
            }
            return list.ToArray();
        }
        public string[] ReadInstancePerformanceCounterNextValue(string categoryName, string instanceName, string counterName)
        {
            PerformanceCounterCategory pcc = new PerformanceCounterCategory(categoryName);
            PerformanceCounter counter = new PerformanceCounter(categoryName,  counterName, instanceName);
            List<string> list = new List<string>();
///            foreach (PerformanceCounter counter in counters)
///            {
                //NumberFormatInfo nfi = new NumberFormatInfo();
                //nfi.NumberGroupSizes = new int[] {3,3,3,3,3,3};
                //nfi.NumberGroupSeparator = ",";
                //string nextValueString = counter.NextValue();
                list.Add
                        (
                            string.Format
                                        (
                                            "Machine[{1}] {0} DateTime[{2}] {0} Category[{3}] {0} Instance[{4}] {0} Counter[{5}]: {6:N}"
                                            , "-"
                                            , counter.MachineName
                                            , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffff")
                                            , categoryName
                                            , counter.InstanceName
                                            , counter.CounterName
                                            , counter.NextValue()
                                        )
                        );
///            }
            return list.ToArray();
        }
    }
}
//Share.cs ============================================
//Microshaoft =========================================
//Microshaoft Remoting Object Client Local Proxy
namespace Microshaoft.RemotingObjects.ServiceContracts.Share
{
    //using System;
    //using System.Collections.Generic;
    public interface IRemotingPerformanceMonitor
    {
        string[] ReadAllInstanceAllPerformanceCounterNextValue(string categoryName, string instanceNameFilter);
        string[] ReadAllInstancePerformanceCounterNextValue(string categoryName, string[] instanceNamesFilter, string[] countersName);
    }
}
namespace Microshaoft
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
    using System.Runtime.Serialization.Formatters;
    using System.Text;
    public static class RemotingHelper
    {
        public static void StartRemoting
            (
                Type RemotingType
                , string Url
                , int Port
            )
        {
            BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider();
            provider.TypeFilterLevel = TypeFilterLevel.Full;
            IDictionary ht = new Hashtable();
            ht["port"] = Port;
            TcpChannel tc = new TcpChannel(ht, null, provider);
            ChannelServices.RegisterChannel(tc, false);
            RemotingConfiguration.RegisterWellKnownServiceType(RemotingType, Url, WellKnownObjectMode.Singleton);
            Console.WriteLine("Remoting Object Started ...");
        }
        public static void StartRemoting<T>
            (
                string Url
                , int Port
            )
        {
            StartRemoting(typeof(T), Url, Port);
        }
        public static T GetRemotingLocalClientProxyObject<T>
            (
                string Url
            )
        {
            return (T) Activator.GetObject
                                    (
                                        typeof(T)
                                        , Url
                                        //, "tcp://127.0.0.1:8080/queueUrl"
                                    );
        }
    }
}
//Client.cs ============================================================================================
namespace Microshaoft.RemotingObjects.Client
{
    using System;
    using System.Collections;
    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
    using System.Runtime.Serialization.Formatters;
    using System.Threading;
    using System.Collections.Generic;
    using Microshaoft;
    using Microshaoft.RemotingObjects.ServiceContracts.Share;
    public class Class1
    {
        public static void Main()
        {
            Console.Title = "Client";
            Console.WriteLine(Environment.Version.ToString());
            Class1 a = new Class1();
            a.Run();
        }
        public void Run()
        {
                IRemotingPerformanceMonitor monitor = RemotingHelper.GetRemotingLocalClientProxyObject<IRemotingPerformanceMonitor>("tcp://127.0.0.1:8082/perfmonurl");
                string[] ss = monitor.ReadAllInstancePerformanceCounterNextValue
                                            (
                                                "Process"
                                                , new string[]
                                                    {
                                                        "devenv"
                                                    }
                                                , new string[]
                                                    {
                                                        "Working Set"
                                                    }
                                                );
            foreach (string s in ss)
            {
                Console.WriteLine(s);
            }
        }
    }
}

原文地址:https://www.cnblogs.com/Microshaoft/p/2050612.html