Beispiel #1
0
        // Return management object from query
        public ManagementObject[] RunQuery(string query)
        {
            // Begin query
            ObjectQuery objectQuery                    = new ObjectQuery(query);
            ManagementObjectSearcher   searcher        = new ManagementObjectSearcher(managementScope, objectQuery);
            ManagementObjectCollection queryCollection = null;

            try
            {
                queryCollection = searcher.Get();
            }
            catch (Exception e)
            {
                throw e;
            }

            // Create a new array of management objects based on the number of items in the managementobject collection

            ManagementObject[] managementObjectArray = new ManagementObject[(queryCollection.Count)];

            // Copy each management object from the collection to the array
            if (queryCollection.Count != 0)
            {
                queryCollection.CopyTo(managementObjectArray, 0);
            }

            // Return our array of management objects regardless of number of members and process on the calling side
            // This is how we're dealing queries that return static values vs numerous members like cim_logicaldisk
            return(managementObjectArray);
        }
Beispiel #2
0
        protected ManagementBaseObject[] GetChildren(int parentProcessID)
        {
            ManagementObjectSearcher   mos            = new ManagementObjectSearcher(String.Format("Select * From Win32_Process Where ParentProcessID={0}", parentProcessID));
            ManagementObjectCollection childProcesses = mos.Get();

            ManagementBaseObject[] subProcesses = new ManagementBaseObject[childProcesses.Count + 1];
            childProcesses.CopyTo(subProcesses, 0);
            return(subProcesses);
        }
        /// <summary>
        /// Queries WMI for Bluetooth COM Ports. Provides useful information on the Console as it does.
        /// </summary>
        /// <returns></returns>
        private ManagementObject[] getWmiCOMData()
        {
            ManagementObject[]       wmiObjects  = null;
            ManagementObjectSearcher wmiSearcher = null;

            try
            {
                wmiSearcher = new ManagementObjectSearcher(@"select DeviceID,PNPDeviceID from Win32_SerialPort");

                ManagementObjectCollection tmpSearchResults = null;

                Logger.Info("Searching for Bluetooth COM devices");
                wmiSearcher      = new ManagementObjectSearcher(@"root\cimv2", "SELECT Name,DeviceID,PNPDeviceID FROM Win32_SerialPort WHERE Name LIKE \"%Bluetooth%\"");
                tmpSearchResults = wmiSearcher.Get();

                Logger.Info("Found {0} devices, verifying...", tmpSearchResults.Count);
                wmiObjects = new ManagementObject[tmpSearchResults.Count];
                tmpSearchResults.CopyTo(wmiObjects, 0);
            }
            catch (System.Management.ManagementException e)
            {
                Console.WriteLine("Query " + wmiSearcher.Query.ToString() + " threw an exception!\n");
                throw e;
            }
            try
            {
                int i = 0;
                foreach (ManagementObject obj in wmiObjects)
                {
                    if ((obj["Name"] as String).Contains("Bluetooth") == false)
                    {
                        Logger.Warning("{0} is not a Bluetooth device! Removing from search results", obj["DeviceID"] as String);
                    }
                    else
                    {
                        wmiObjects[i] = obj;
                        ++i;
                    }
                }
            }
            catch (System.Management.ManagementException e)
            {
                Console.WriteLine("Exception: Unable to read a property from wmi object!\n");
                throw e;
            }

            /* Extremeley self-referencing code to get rid of WMI-detected COM ports that
             * have a MAC address of 000000000000 */
            wmiObjects = wmiObjects.Where(obj =>
                                          (obj["PNPDeviceID"] as String).Substring(
                                              (obj["PNPDeviceID"] as String).LastIndexOf('_') - MAC_ADDRESS_LENGTH, MAC_ADDRESS_LENGTH)
                                          != "000000000000").ToArray();

            Logger.Info("Verified {0} Bluetooth COM Device(s)", wmiObjects.Length);
            return(wmiObjects);
        }
Beispiel #4
0
        public ManagementObject[] GetObjects(string queryString, bool allowQueryCaching)
        {
            ManagementObject[]         result     = new ManagementObject[0];
            ManagementObjectCollection collection = GetObjectCollection(queryString, allowQueryCaching);

            if (collection != null && collection.Count > 0)
            {
                result = new ManagementObject[collection.Count];
                collection.CopyTo(result, 0);
            }
            return(result);
        }
Beispiel #5
0
        private async Task <List <LogModel> > ExecuteQuery(ManagementScope remote, DateTime start, DateTime end, string messagequeryvalue, LogTypeEnum logType)
        {
            if (messagequeryvalue == null)
            {
                messagequeryvalue = string.Empty;
            }

            string escapedMessageQueryParameter = Regex.Replace(messagequeryvalue, "([\\\\''\"])", @"\$1");

            if (remote != null)
            {
                return(await Task.Run(() =>
                {
                    string timeBasedQuery = this.BuildTimeBasedQueryFromDates(start, end);
                    string logfileName = this.GetLogFileName(logType);

                    ObjectQuery query = new ObjectQuery($"SELECT * FROM Win32_NTLogEvent where (logfile='{logfileName}' and Message like '%{escapedMessageQueryParameter}%'{timeBasedQuery})");
                    ManagementObjectSearcher searcher = new ManagementObjectSearcher(remote, query);

                    ManagementObjectCollection querycollection = searcher.Get();

                    ConcurrentBag <LogModel> bag = new ConcurrentBag <LogModel>();

                    if (querycollection?.Count == 0)
                    {
                        return bag.ToList();
                    }

                    ManagementBaseObject[] resultarray = new ManagementBaseObject[querycollection.Count];
                    querycollection.CopyTo(resultarray, 0);

                    Parallel.ForEach(resultarray, (mbo) =>
                    {
                        bag.Add(LogModelFactory.BuildItemFromManagementBaseObject(mbo));
                    });

                    return bag.ToList();
                }));
            }
            else
            {
                return(null);
            }
        }
Beispiel #6
0
        public static int Main(string[] args)
        {
            ManagementObjectSearcher s = new ManagementObjectSearcher
                                             (new DataQuery("select * from Win32_Process"));

            ManagementObject[] processes = new ManagementObject [100];

            ManagementObjectCollection c = s.Get();

            c.CopyTo(processes, 0);

            for (int i = 0; i < processes.Length; i++)
            {
                if (null != processes[i])
                {
                    Console.WriteLine(((ManagementObject)(processes[i]))["Name"]);
                }
            }

            return(0);
        }
        public ManagementObject GetRemoteSystemDriveInfo(string remoteSytemName, string userName, string password, string driveName)
        {
            ConnectionOptions options = new ConnectionOptions();

            options.Username      = userName;
            options.Password      = password;
            options.Impersonation = System.Management.ImpersonationLevel.Impersonate;
            ManagementScope scope = null;

            scope = new ManagementScope(@"\\" + remoteSytemName + @"\root\cimv2", options);
            scope.Connect();

            //Query system for Operating System information
            SelectQuery query = new SelectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3", driveName + ":");
            ManagementObjectSearcher   searcher        = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection queryCollection = searcher.Get();

            ManagementObject[] result = null;
            queryCollection.CopyTo(result, 0);

            return(result[0]);
        }
        /* to use
         * ulong installedMemory;
         *  MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
         *  if( GlobalMemoryStatusEx( memStatus))
         *  {
         *     installedMemory = memStatus.ullTotalPhys;
         *  }
         */
        //============ borrowed END
        //==================================================
        //                Update report
        //==================================================
        static void UpdateReport()
        {
            msgStatic.msgtype = MessageTypes.MSG_UPDATEPUSH;

            msgStatic.msg_number = MessageCount();
            msgStatic.time_stamp = DateTime.Now;
#if !NDEBUG
            Console.WriteLine("#" + msgStatic.msg_number + "  " + msgStatic.time_stamp);
#endif
            //--ping
            Ping      pingSender = new Ping();
            PingReply pingReply  = pingSender.Send(srv_address);
            if (pingReply.Status == IPStatus.Success)
            {
                msgStatic.ping = pingReply.RoundtripTime;
            }
            else
            {
                msgStatic.ping = -1;
            }
            //---cpus
#if !NDEBUG
            Console.WriteLine("Getting Cpus...");
#endif
            //http://stackoverflow.com/questions/9777661/returning-cpu-usage-in-wmi-using-c-sharp
            ManagementObjectSearcher   searcher        = new ManagementObjectSearcher("select * from Win32_PerfFormattedData_PerfOS_Processor");
            ManagementObjectCollection cpus_collection = searcher.Get();
            ManagementObject[]         cpus            = new ManagementObject[cpus_collection.Count];
            cpus_collection.CopyTo(cpus, 0);
            msgStatic.cpus = new ushort[cpus.Count() - 1]; //-1 for "_total"
            for (int i = 0; i < msgStatic.cpus.Length; ++i)
            {
                msgStatic.cpus[i] = (ushort)(ulong)(cpus[i]["PercentProcessorTime"]); //raw is Int64
            }
            //---ram
#if !NDEBUG
            Console.WriteLine("Getting Memory...");
#endif
            MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
            if (GlobalMemoryStatusEx(memStatus))
            {
                msgStatic.ram_used  = memStatus.ullAvailPhys;
                msgStatic.swap_used = memStatus.ullAvailPageFile;
            }
            //---get hdds
#if !NDEBUG
            Console.WriteLine("Getting Drives...");
#endif
            DriveInfo[] drives = DriveInfo.GetDrives();
            msgStatic.drives = new DriveInfoSlim[drives.Length];
            for (int i = 0; i < drives.Length; ++i)
            {
                msgStatic.drives[i].name = drives[i].Name;
                msgStatic.drives[i].type = drives[i].DriveType;
                if (drives[i].IsReady)
                {
                    msgStatic.drives[i].free  = drives[i].TotalFreeSpace;
                    msgStatic.drives[i].total = drives[i].TotalSize;
                }
            }
            //---processes
#if !NDEBUG
            Console.WriteLine("Getting Processes...");
#endif
            msgStatic.processes_total = Process.GetProcesses().Length;

            //======get network info
#if !NDEBUG
            Console.WriteLine("Getting NICs...");
#endif
            //http://stackoverflow.com/questions/850650/reliable-method-to-get-machines-mac-address-in-c-sharp#7661829
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            msgStatic.nics = new NetworkInterfaceSlim[nics.Length];
            for (int i = 0; i < nics.Length; ++i)
            {
                msgStatic.nics[i].name        = nics[i].Name;
                msgStatic.nics[i].status      = nics[i].OperationalStatus;
                msgStatic.nics[i].speed       = nics[i].Speed;
                msgStatic.nics[i].mac_address = nics[i].GetPhysicalAddress().ToString(); //PhysicalAddress type wont serialize T_T
                                                                                         //ip complciated because multiple addresses possible
                foreach (var x in nics[i].GetIPProperties().UnicastAddresses)
                {
                    if (x.Address.AddressFamily == AddressFamily.InterNetwork && x.IsDnsEligible)
                    {
                        msgStatic.nics[i].ip = x.Address.ToString();
                    }
                }
                //msg.nics[i].type = nics[i].GetType();
            }
        }
Beispiel #9
0
        public void Execute(IJobExecutionContext context)
        {
            List <StoreModel> storeList = new List <StoreModel>();

            storeList = this._IStoreServerService.GetStoresDetails();

            List <StoreServerModel> storeServerList = new List <StoreServerModel>();

            List <StoreServerModel> storeServerStatusList = new List <StoreServerModel>();

            List <ServerServiceStatus> windowsServiceList    = new List <ServerServiceStatus>();
            List <ServerServiceStatus> windowsServiceRunList = new List <ServerServiceStatus>();


            storeServerList    = this._IStoreServerService.GetStoresServerDetails();
            windowsServiceList = this._IStoreServerService.GetWindowsServiceDetails();

            StoreServerModel storeServerDetails = new StoreServerModel();

            storeServerDetails.UserId = 1;

            Int64 batchId = this._IStoreServerService.GenerateServerServiceStatusBatch(storeServerDetails);

            Int64 windowsBatchId = this._IStoreServerService.GenerateWindowsServiceStatusBatch(storeServerDetails);

            foreach (var item in storeServerList)
            {
                StoreServerModel storeServerStatus = new StoreServerModel();
                storeServerStatus = item;
                storeServerStatus.ServerStatusBatchId = batchId;
                try
                {
                    Ping      myPing = new Ping();
                    PingReply reply  = myPing.Send(item.ISSIpAddress, 1000);

                    if (reply != null)
                    {
                        if (reply.Status == IPStatus.Success)
                        {
                            storeServerStatus.IsServerActive     = true;
                            storeServerStatus.ServerResponseTime = Convert.ToInt32(reply.RoundtripTime);
                        }
                        else
                        {
                            storeServerStatus.IsServerActive = false;
                        }
                    }
                }
                catch (Exception)
                {
                    storeServerStatus.IsServerActive = false;
                }

                List <ServerServiceStatus> windowsServiceCurrentRunList = new List <ServerServiceStatus>();

                windowsServiceCurrentRunList = windowsServiceList.Where(
                    w => w.StoreNo == item.StoreNo
                    ).ToList();

                if (storeServerStatus.IsServerActive == true &&
                    windowsServiceCurrentRunList != null &&
                    windowsServiceCurrentRunList.Count > 0
                    )
                {
                    try
                    {
                        ConnectionOptions op = new ConnectionOptions();
                        op.Username = "******";
                        op.Password = "******";
                        ManagementScope scope = new ManagementScope(@"\\" +
                                                                    item.ISSIpAddress
                                                                    + @"\root\cimv2", null);
                        scope.Connect();
                        ManagementPath  path = new ManagementPath("Win32_Service");
                        ManagementClass services;
                        services = new ManagementClass(scope, path, null);

                        ManagementObjectCollection moc         = services.GetInstances();
                        ManagementObject[]         deviceArray = new ManagementObject[moc.Count];
                        moc.CopyTo(deviceArray, 0);

                        windowsServiceCurrentRunList.ForEach(x =>
                        {
                            ServerServiceStatus serverServiceStatus = new ServerServiceStatus();
                            serverServiceStatus = x;
                            var vvv             = deviceArray.Where(w => w.GetPropertyValue("Name").ToString() == x.ServiceName);

                            if (vvv.Any(a => a.GetPropertyValue("State").ToString().ToLower().Equals("running"))
                                )
                            {
                                serverServiceStatus.IsServiceActive = true;
                            }
                            else
                            {
                                serverServiceStatus.IsServiceActive = false;
                            }
                        }
                                                             );

                        windowsServiceRunList.AddRange(windowsServiceCurrentRunList);
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                }

                lock (storeServerStatusList)
                {
                    storeServerStatusList.Add(storeServerStatus);
                }
            }



            //_heartbeat.UpdateServiceState("alive");
            var isUpdateSuccess = this._IStoreServerService.UpdateServerServiceStatusBatch(storeServerStatusList);
        }