Exemple #1
0
 public static uint CPUSpeed()
 {
     ManagementObject mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'");
     uint sp = (uint)(mo["CurrentClockSpeed"]);
     mo.Dispose();
     return sp;
 }
Exemple #2
0
        internal static string GetHwid()
        {
            string drive = string.Empty;

            foreach (System.IO.DriveInfo compDrive in System.IO.DriveInfo.GetDrives())
            {
                if (compDrive.IsReady)
                {
                    drive = compDrive.RootDirectory.ToString();
                    break;
                }
            }
            drive = drive.EndsWith(":\\") ? drive.Substring(0, drive.Length - 2) : drive;

            string volumeSerial = string.Empty;

            System.Management.ManagementObject disk = new System.Management.ManagementObject(@"win32_logicaldisk.deviceid=""" + drive + @":""");
            disk.Get();

            volumeSerial = disk["VolumeSerialNumber"].ToString();
            disk.Dispose();

            string a = Environment.OSVersion.Version.ToString();
            string b = volumeSerial;
            string c = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].GetPhysicalAddress().ToString();

            return(a + b + c);
        }
 public string CPUSpeed()
 {
     ManagementObject Mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'");
     uint sp = (uint)(Mo["CurrentClockSpeed"]);
     Mo.Dispose();
     decimal speed = Convert.ToDecimal(sp);
     speed = Math.Round(speed / 1000, 1);
     string speedString = speed + " Ghz";
     return speedString;
 }
Exemple #4
0
        private string getVolumeSerial(string drive)
        {
            ManagementObject disk = new ManagementObject(@"win32_logicaldisk.deviceid=""" + drive + @":""");
            disk.Get();

            string volumeSerial = disk["VolumeSerialNumber"].ToString();
            disk.Dispose();

            return volumeSerial;
        }
Exemple #5
0
        private string getVolumeSerial(string drive)
        {
            ManagementObject disk = new ManagementObject(string.Format("{0}{1}{2}", @"win32_logicaldisk.deviceid=""", drive, @":"""));
            disk.Get();

            string volumeSerial = disk["VolumeSerialNumber"].ToString();
            disk.Dispose();

            return volumeSerial;
        }
Exemple #6
0
        /// <summary>
        /// Returns the HDD volume of c:
        /// </summary>
        /// <returns></returns>
        private static string CVolumeSerial()
        {
            var disk = new ManagementObject(@"win32_logicaldisk.deviceid=""c:""");
            disk.Get();

            string volumeSerial = disk["VolumeSerialNumber"].ToString();
            disk.Dispose();

            return volumeSerial;
        }
Exemple #7
0
        public static uint CpuSpeed()
        {
#if !mono
            var mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'");
            var sp = (uint) (mo["CurrentClockSpeed"]);
            mo.Dispose();
            return sp;
#else
            return 0;
#endif
        }
Exemple #8
0
        public static uint CPUSpeed()
        {
#if !mono
            ManagementObject Mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'");
            uint sp = (uint)(Mo["CurrentClockSpeed"]);
            Mo.Dispose();
            return sp;
#else
            return 0;
#endif
        }
        /// <summary>
        /// Get the data from the local machine and write it to the storage location
        /// </summary>
        public static void GetData()
        {
            int cpuSpeedMHz;
            long memoryBytes;
            string operatingSystemVersion;

            StorageManager.InitializeMachineStorage();

            string data = string.Empty;

            try
            {
                // get CPU speed in MHz
                ManagementObject moProcessor = new ManagementObject("Win32_Processor.DeviceID='CPU0'");
                cpuSpeedMHz = Convert.ToInt32(moProcessor["CurrentClockSpeed"]);
                moProcessor.Dispose();
                StorageManager.Write(SpecificationSource.LocalMachine, SpecificationType.CPU, cpuSpeedMHz.ToString());

                // get RAM size in bytes
                ManagementClass mcRAM = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection mocRAM = mcRAM.GetInstances();
                foreach (ManagementObject moRAM in mocRAM)
                {
                    memoryBytes = Convert.ToInt64(moRAM["TotalPhysicalMemory"]);
                    moRAM.Dispose();
                    StorageManager.Write(SpecificationSource.LocalMachine, SpecificationType.RAM, memoryBytes.ToString());
                }

                DriveInfo[] drives = DriveInfo.GetDrives();
                foreach (DriveInfo drive in drives)
                {
                    if (drive.Name == @"C:\")
                    {
                        StorageManager.Write(SpecificationSource.LocalMachine, SpecificationType.FreeDiskSpace, drive.AvailableFreeSpace.ToString());
                    }
                }

                // get screen resolution
                Rectangle resolution = Screen.PrimaryScreen.Bounds;
                StorageManager.Write(SpecificationSource.LocalMachine, SpecificationType.ScreenResolution, resolution.Width.ToString());
                StorageManager.Write(SpecificationSource.LocalMachine, SpecificationType.ScreenResolution, resolution.Height.ToString());

                // get OS major and minor version numbers
                operatingSystemVersion = Environment.OSVersion.Version.Major.ToString() + "." +
                    Environment.OSVersion.Version.Minor.ToString();
                StorageManager.Write(SpecificationSource.LocalMachine, SpecificationType.OSVersion, operatingSystemVersion);
            }
            catch (Exception e)
            {
                throw new ApplicationException("An error has occoured.  Error report follows:" + e.Message);
            }
        }
        public uint GetCPUSpeed()
        {
            uint result = 0;
            ManagementObject mo = null;

            try
            {
                mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'");
                result = (uint)mo["MaxClockSpeed"];
            }
            catch { }
            finally
            {
                if (mo != null)
                    mo.Dispose();
            }

            return result;
        }
Exemple #11
0
        private void serviceProcessInstaller1_Committed(object sender, InstallEventArgs e)
        {
            try
            {
                var service = new System.Management.ManagementObject(
                    String.Format("WIN32_Service.Name='{0}'", "ServiceTestAR"));
                try
                {
                    var paramList = new object[11];
                    paramList[5] = true;//We only need to set DesktopInteract parameter
                    var output = service.InvokeMethod("Change", paramList);
                    //if zero is returned then it means change is done.
                    logger(string.Format("FAILED with code {0}", output));

                    //throw new Exception(string.Format("FAILED with code {0}", output));
                }
                catch (Exception ee)
                {
                    logger(string.Format("Failed: {0}", ee.ToString()));
                }
                finally
                {
                    service.Dispose();
                }
                //////////////////////////////////////////////////////////////////////////
                //ConnectionOptions myConOptions = new ConnectionOptions();
                //myConOptions.Impersonation = ImpersonationLevel.Impersonate;
                //ManagementScope mgmtScope = new ManagementScope(@"root\CIMV2",myConOptions);

                //mgmtScope.Connect();
                //ManagementObject wmiService = new ManagementObject("Win32_Service.Name=" + serviceInstaller1.ServiceName+"");

                //ManagementBaseObject InParam = wmiService.GetMethodParameters("Change");

                //InParam["DesktopInteract"] = true;

                //ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", InParam, null);
            }
            catch (System.Exception ex)
            {
                logger(ex.ToString());
            }
        }
Exemple #12
0
        /// <summary>Generates an XML containing user hardware information.</summary>
        /// <param name="graphics">GraphicsDevice so that we can easily probe for the GPU</param>
        public void CreateHardwareProfile(GraphicsDevice graphics)
        {
            //Check to see if the Tree structure has been setup
            if (!Directory.Exists(m_Directories[ExperiaDirectories.Configs]))
            {
                Directory.CreateDirectory(m_Directories[ExperiaDirectories.Configs]);
            }

            XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true };

            //If the File Exists lets check to make sure the hardware is the same
            bool makeFile = false;
            if (File.Exists(m_Paths[ExperiaFiles.HardwareProfile]))
            {
                XmlReaderSettings readerSettings = new XmlReaderSettings { IgnoreComments = true, IgnoreWhitespace = true };
                XmlReader reader = XmlReader.Create(m_Paths[ExperiaFiles.HardwareProfile], readerSettings);

                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            switch (reader.Name)
                            {
                                case "Machine":
                                    if (reader.GetAttribute("HWGUID") != ExperiaHelper.Instance.HardwareGuidGen(graphics).ToString())
                                        makeFile = true;
                                    break;
                            }
                            break;
                    }
                }

                reader.Close();
            }

            //This takes a bit so lets make sure that we even need to make the doc
            if (!File.Exists(m_Paths[ExperiaFiles.HardwareProfile]) || makeFile)
            {

                XmlWriter writer = XmlWriter.Create(m_Paths[ExperiaFiles.HardwareProfile], settings);

                //OS Info
                XmlWriteAttributeElement(writer, "Machine", "HWGUID", ExperiaHelper.Instance.HardwareGuidGen(graphics).ToString());
                XmlWriteAttributeElement(writer, "OS", "Is64Bit", Environment.Is64BitOperatingSystem.ToString(), Environment.OSVersion.ToString());

                //Processor Write
                ManagementObject processorObject = new ManagementObject("Win32_Processor.DeviceID='CPU0'");
                Dictionary<string, string> processorInfo = new Dictionary<string, string>();
                processorInfo.Add("Count", Environment.ProcessorCount.ToString());
                processorInfo.Add("Clock", processorObject["CurrentClockSpeed"].ToString());
                processorInfo.Add("MaxClock", processorObject["MaxClockSpeed"].ToString());
                processorInfo.Add("L2", processorObject["L2CacheSize"].ToString());
                processorInfo.Add("L3", processorObject["L3CacheSize"].ToString());
                XmlWriteAttributeElement(writer, "Processor", processorInfo, processorObject["Name"].ToString());
                processorObject.Dispose();

                //Memory Info
                XmlWriteAttributeElement(writer, "RAM", "Bytes", new ComputerInfo().TotalPhysicalMemory.ToString());
                writer.WriteEndElement();

                //Network Info
                Dictionary<string, string> networkInfo = new Dictionary<string, string>();
                networkInfo.Add("ComputerName", Environment.MachineName);
                networkInfo.Add("UserName", Environment.UserName);
                XmlWriteAttributeElement(writer, "Network", networkInfo, false);
                networkInfo.Clear();
                //Network Adapter Info
                for(int i = 0; i < NetworkInterface.GetAllNetworkInterfaces().Length; i++)
                {
                    if (NetworkInterface.GetAllNetworkInterfaces()[i].OperationalStatus == OperationalStatus.Up)
                    {
                        networkInfo.Add("Name", NetworkInterface.GetAllNetworkInterfaces()[i].Description);
                        networkInfo.Add("Speed", NetworkInterface.GetAllNetworkInterfaces()[i].Speed.ToString());
                        networkInfo.Add("MAC", NetworkInterface.GetAllNetworkInterfaces()[i].GetPhysicalAddress().ToString());
                        XmlWriteAttributeElement(writer, "Adapter", networkInfo, false);
                        writer.WriteEndElement();
                        networkInfo.Clear();
                    }
                }
                writer.WriteEndElement();

                //Gpu Info
                Dictionary<string, string> gpuAttributes = new Dictionary<string, string>();
                gpuAttributes.Add("ID", graphics.Adapter.DeviceId.ToString());
                gpuAttributes.Add("VendorID", graphics.Adapter.VendorId.ToString());
                gpuAttributes.Add("SystemID", graphics.Adapter.SubSystemId.ToString());
                gpuAttributes.Add("Revision", graphics.Adapter.Revision.ToString());
                gpuAttributes.Add("HiDefCapable", graphics.Adapter.IsProfileSupported(GraphicsProfile.HiDef).ToString());
                XmlWriteAttributeElement(writer, "GPU", gpuAttributes, graphics.Adapter.Description);
                //Gpu Desktop Res
                Dictionary<string, string> gpuDesktopRes = new Dictionary<string, string>();
                gpuDesktopRes.Add("X", graphics.Adapter.CurrentDisplayMode.Width.ToString());
                gpuDesktopRes.Add("Y", graphics.Adapter.CurrentDisplayMode.Height.ToString());
                XmlWriteAttributeElement(writer, "DesktopResolution", gpuDesktopRes);

                //Close out the file
                XmlClose(writer);
                writer = null;
            }

            settings = null;
        }
        /*
        public void SetSharePermissions()
        {
        }
        */
        /// <summary>
        /// Gets the share permissions.
        /// </summary>
        /// <returns>The Names of the Trustees.</returns>
        public string[] GetSharePermissions()
        {
            ManagementObject win32LogicalSecuritySetting = null;
            ManagementBaseObject getSecurityDescriptorReturn = null;
            ManagementBaseObject securityDescriptor = null;

            try
            {
                win32LogicalSecuritySetting = new ManagementObject(@"root\cimv2:Win32_LogicalShareSecuritySetting.Name='" + this.shareName + "'");

                getSecurityDescriptorReturn = win32LogicalSecuritySetting.InvokeMethod("GetSecurityDescriptor", null, null);

                if ((uint)getSecurityDescriptorReturn["ReturnValue"] != 0)
                {
                    throw new WindowsShareException("Unable to get share permissions. Error Code: " + getSecurityDescriptorReturn["ReturnValue"]);
                }

                securityDescriptor = getSecurityDescriptorReturn["Descriptor"] as ManagementBaseObject;
                ManagementBaseObject[] dacl = securityDescriptor["DACL"] as ManagementBaseObject[];

                if (dacl == null)
                {
                    return new string[] { };
                }
                else
                {
                    return dacl.Select(ac => ((ac["Trustee"] as ManagementBaseObject)["Name"] as string)).ToArray();
                }
            }
            catch (Exception ex)
            {
                throw new WindowsShareException("Unable to get share permissions", ex);
            }
            finally
            {
                if (win32LogicalSecuritySetting != null)
                {
                    win32LogicalSecuritySetting.Dispose();
                }

                if (getSecurityDescriptorReturn != null)
                {
                    getSecurityDescriptorReturn.Dispose();
                }

                if (securityDescriptor != null)
                {
                    securityDescriptor.Dispose();
                }
            }
        }
        /// <summary>
        /// Checks if the the share has permissions.
        /// </summary>
        /// <param name="accountName">Name of the account.</param>
        /// <returns>True if the share contains the permission.</returns>
        public bool HasPermission(string accountName)
        {
            ManagementObject win32LogicalSecuritySetting = null;
            ManagementBaseObject getSecurityDescriptorReturn = null;
            ManagementBaseObject securityDescriptor = null;

            try
            {
                win32LogicalSecuritySetting = new ManagementObject(@"root\cimv2:Win32_LogicalShareSecuritySetting.Name='" + this.shareName + "'");

                getSecurityDescriptorReturn = win32LogicalSecuritySetting.InvokeMethod("GetSecurityDescriptor", null, null);

                if ((uint)getSecurityDescriptorReturn["ReturnValue"] != 0)
                {
                    throw new WindowsShareException("Unable to check share permission. Error Code: " + getSecurityDescriptorReturn["ReturnValue"]);
                }

                securityDescriptor = getSecurityDescriptorReturn["Descriptor"] as ManagementBaseObject;
                ManagementBaseObject[] dacl = securityDescriptor["DACL"] as ManagementBaseObject[];

                if (dacl == null)
                {
                    return false;
                }
                else
                {
                    foreach (var curAce in dacl)
                    {
                        string curTrustee = (curAce["Trustee"] as ManagementBaseObject)["Name"] as string;

                        // if iTrustee == accountName
                        if (curTrustee.Equals(accountName, StringComparison.OrdinalIgnoreCase))
                        {
                            return true;
                        }
                    }
                }

                return false;
            }
            catch (Exception ex)
            {
                throw new WindowsShareException("Unable to check share permission", ex);
            }
            finally
            {
                if (win32LogicalSecuritySetting != null)
                {
                    win32LogicalSecuritySetting.Dispose();
                }

                if (getSecurityDescriptorReturn != null)
                {
                    getSecurityDescriptorReturn.Dispose();
                }

                if (securityDescriptor != null)
                {
                    securityDescriptor.Dispose();
                }
            }
        }
        /// <summary>
        /// Deletes the share permission.
        /// </summary>
        /// <param name="accountName">Name of the account.</param>
        public void DeleteSharePermission(string accountName)
        {
            if (accountName == null)
            {
                throw new ArgumentNullException("accountName");
            }

            ManagementObject win32LogicalSecuritySetting = null;
            ManagementBaseObject getSecurityDescriptorReturn = null;
            ManagementBaseObject securityDescriptor = null;
            ManagementObject share = null;

            try
            {
                win32LogicalSecuritySetting = new ManagementObject(@"root\cimv2:Win32_LogicalShareSecuritySetting.Name='" + this.shareName + "'");

                getSecurityDescriptorReturn = win32LogicalSecuritySetting.InvokeMethod("GetSecurityDescriptor", null, null);

                if ((uint)getSecurityDescriptorReturn["ReturnValue"] != 0)
                {
                    throw new WindowsShareException("Unable to delete share permission. Error Code: " + getSecurityDescriptorReturn["ReturnValue"]);
                }

                securityDescriptor = getSecurityDescriptorReturn["Descriptor"] as ManagementBaseObject;
                ManagementBaseObject[] dacl = securityDescriptor["DACL"] as ManagementBaseObject[];

                if (dacl == null)
                {
                    throw new WindowsShareException("Unable to delete share permission. Access control not found");
                }
                else
                {
                    List<ManagementBaseObject> newDACL = new List<ManagementBaseObject>();
                    foreach (ManagementBaseObject ac in dacl)
                    {
                        if (((ac["Trustee"] as ManagementBaseObject)["Name"] as string).ToUpperInvariant() != accountName.ToUpperInvariant())
                        {
                            newDACL.Add(ac);
                        }
                    }

                    if (dacl.Count() == newDACL.Count())
                    {
                        throw new WindowsShareException("Unable to delete share permission. Access control not found");
                    }

                    dacl = newDACL.ToArray();
                }

                securityDescriptor["DACL"] = dacl;

                share = new ManagementObject(@"root\cimv2:Win32_Share.Name='" + this.shareName + "'");
                uint setShareInfoReturn = (uint)share.InvokeMethod("SetShareInfo", new object[] { null, null, securityDescriptor });

                if (setShareInfoReturn != 0)
                {
                    throw new WindowsShareException("Unable to delete share permission. Error code:" + setShareInfoReturn.ToString(CultureInfo.InvariantCulture));
                }
            }
            catch (Exception ex)
            {
                throw new WindowsShareException("Unable to delete share permission", ex);
            }
            finally
            {
                if (win32LogicalSecuritySetting != null)
                {
                    win32LogicalSecuritySetting.Dispose();
                }

                if (getSecurityDescriptorReturn != null)
                {
                    getSecurityDescriptorReturn.Dispose();
                }

                if (securityDescriptor != null)
                {
                    securityDescriptor.Dispose();
                }

                if (share != null)
                {
                    share.Dispose();
                }
            }
        }
        /// <summary>
        /// Test if the share exists.
        /// </summary>
        /// <returns>True if the share exists.</returns>
        public bool Exists()
        {
            // using (var shareQuery = new ManagementObjectSearcher(@"SELECT * FROM Win32_Share Where Name = '" + this.shareName + "'"))
            // {
            //     return shareQuery.Get().Count > 0;
            // }
            ManagementObject shareInstance = null;

            try
            {
                shareInstance = new ManagementObject(@"root\cimv2:Win32_Share.Name='" + this.shareName + "'");
                shareInstance.Get();
            }
            catch (ManagementException)
            {
                return false;
            }
            finally
            {
                if (shareInstance != null)
                {
                    shareInstance.Dispose();
                }
            }

            return true;
        }
Exemple #17
0
 /// <summary>
 /// Retrieve the free disk space on disk c: (in MB)
 /// </summary>
 /// <returns>An integer indicating the free HDD space in MB</returns>
 private static int FreeDiskSpace()
 {
     int retVal=0;
     ManagementObject disk = new ManagementObject("Win32_LogicalDisk.DeviceID=\"c:\"");
     disk.Get();
     string size="0";
     try
     {
         size=disk["FreeSpace"].ToString();
     }
     catch
     {}
     disk.Dispose();
     retVal=(int)(Convert.ToInt64(size)/1048576);
     return retVal;
 }
        /// <summary>
        /// Deletes the share.
        /// </summary>
        public void DeleteShare()
        {
            ManagementBaseObject outParams = null;
            ManagementObject shareInstance = null;

            try
            {
                shareInstance = new ManagementObject(@"root\cimv2:Win32_Share.Name='" + this.shareName + "'");
                outParams = shareInstance.InvokeMethod("Delete", null, null);

                if ((uint)outParams["ReturnValue"] != 0)
                {
                    throw new WindowsShareException("Unable to delete share. Win32_Share.Delete Error Code: " + outParams["ReturnValue"]);
                }
            }
            catch (Exception ex)
            {
                throw new WindowsShareException("Unable to delete share: " + this.shareName, ex);
            }
            finally
            {
                if (shareInstance != null)
                {
                    shareInstance.Dispose();
                }

                if (outParams != null)
                {
                    outParams.Dispose();
                }
            }
        }
        public void ChangeDNS(int ind)
        {
            try
            {
                ManagementObject classInstance =
                    new ManagementObject("root\\CIMV2",
                    "Win32_NetworkAdapterConfiguration.Index='" + ind + "'",
                    null);

                // Obtain in-parameters for the method
                ManagementBaseObject inParams =
                    classInstance.GetMethodParameters("SetDNSServerSearchOrder");

                // Add the input parameters.
                inParams["DNSServerSearchOrder"] = textBox3.Lines;

                // Execute the method and obtain the return values.
                ManagementBaseObject outParams =
                    classInstance.InvokeMethod("SetDNSServerSearchOrder", inParams, null);

                classInstance.Dispose();
            }
            catch (ManagementException err)
            {
                MessageBox.Show("An error occurred while trying to execute the WMI method: " + err.Message);
            }
        }
Exemple #20
0
        private void CheckFreeSpace(string drive)
        {
            bool sleep_req = false;
              do
              {
            if (sleep_req)
            {
              System.Threading.Thread.Sleep(15 * 1000);
              sleep_req = false;
            }
            try
            {
              ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"" + drive + "\"");
              disk.Get();
              if (Convert.ToInt64(disk["FreeSpace"]) < 5242880)
              {
            SendMsg(disk["FreeSpace"].ToString());
            throw new ManagementException();
              }
              disk.Dispose();
            }
            catch (ManagementException mex)
            {
              EventLog.WriteEntry("Out of disk space error: ", "CCreator Creator: " + mex.ToString(), EventLogEntryType.Warning);
              EventLog.WriteEntry("Sleeping for 15 seconds...", "CCreator Creator");
              sleep_req = true;
            }
              } while (sleep_req);

              GC.Collect();
              GC.WaitForPendingFinalizers();
              GC.Collect();
        }
Exemple #21
0
			private void CountQueueMessages(QSetQueueItem queueItem)
			{				
				//first of all, ensure we have a node to work with
				QueueItemListViewItemPair itemPair = null;
				if (_itemPairHashTable.ContainsKey(queueItem.ID))
					itemPair = (QSetMonitorWorker.QueueItemListViewItemPair)_itemPairHashTable[queueItem.ID];
				else
				{
					//TODO create icon
					itemPair = new QueueItemListViewItemPair(queueItem, new ListViewItem(queueItem.Name, (int)Images.IconType.Queue));					
					for (int subItemCounter = 0; subItemCounter < _COLUMNS; subItemCounter ++)
						itemPair.ListViewItem.SubItems.Add(string.Empty);
					_itemPairHashTable.Add(itemPair.QSetQueueItem.ID, itemPair);
					
                    Action x = delegate { _monitorListView.Items.Add(itemPair.ListViewItem); };
                    _monitorListView.Invoke(x);
				}
				
				ManagementObject counter = null;
				try
				{										
					counter = new ManagementObject(String.Format("Win32_PerfRawdata_MSMQ_MSMQQueue.name='{0}'", itemPair.QSetQueueItem.Name));
					counter.Get();			
					uint outgoingMessageCount = Convert.ToUInt32(counter.GetPropertyValue("MessagesInQueue"));
                    uint outgoingBytes = Convert.ToUInt32(counter.GetPropertyValue("BytesInQueue"));

                    Action herewegoagain = () =>
                        {
                            if (itemPair.ListViewItem.SubItems[(int)SubItemList.OutgoingMessageCount].Text != outgoingMessageCount.ToString()) //note: only do if necessary, to avoid flicker
                                itemPair.ListViewItem.SubItems[(int)SubItemList.OutgoingMessageCount].Text = outgoingMessageCount.ToString();

                            if (itemPair.ListViewItem.SubItems[(int)SubItemList.OutgoingBytes].Text != outgoingBytes.ToString()) //note: only do if necessary, to avoid flicker
                                itemPair.ListViewItem.SubItems[(int)SubItemList.OutgoingBytes].Text = outgoingBytes.ToString();
                        };


                    _monitorListView.Invoke(herewegoagain);
				}
				catch
				{
					//exception will occur when cannot get access to performance counters
				}
				finally
				{
					if (counter != null)
						counter.Dispose();
				}
			}
Exemple #22
0
 private uint CPUSpeed()
 {
     ManagementObject Mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'");
     uint sp = (uint)(Mo["CurrentClockSpeed"]);
     Mo.Dispose();
     return sp;
 }
 private void cpuSpeed()
 {
     try
     {
         ManagementObject searcher = new ManagementObject("Win32_Processor.DeviceID='CPU0'");
         currentSpeed = Convert.ToInt32((searcher["CurrentClockSpeed"]));
         cpuSpeedQ.Enqueue(currentSpeed);
         Console.WriteLine("Speed MHZ:" + currentSpeed.ToString());
         if (cpuSpeedQ.Count > 133) cpuSpeedQ.Dequeue();
         searcher.Dispose();
     }
     catch (Exception e)
     {
         throw e;
     }
 }
        internal void Refresh(object sender, ElapsedEventArgs e)
        {
            int iSpan = Properties.Settings.Default.f2TimspanCPU;
            int iIndex = 0;
            string sText = "";
               var query = (from ManagementObject p in searcher.Get()
             orderby p.Properties["Name"].Value ascending
             select p)
            .Skip(0)
            .ToList();
            foreach (var item in query)
            {
                double time = Environment.TickCount / 1000.0; //(Environment.TickCount - tCPU) / 1000.0;
                double val = Convert.ToDouble(item.Properties["PercentProcessorTime"].Value);

                if (bGraph && cpuGraphControl.GraphPane != null)
                {
                    LineItem lCurve = cpuGraphControl.GraphPane.CurveList[iIndex] as LineItem;
                    if (lCurve == null)
                        return;
                    IPointListEdit list = lCurve.Points as IPointListEdit;
                    if (list == null)
                        return;
                    list.Add(time, val);

                    Scale xScale = cpuGraphControl.GraphPane.XAxis.Scale;
                    if (time > xScale.Max)
                    {
                        xScale.Max = time;
                        xScale.Min = xScale.Max - iSpan;
                    }
                        lCurve.IsVisible = true;
                }
                if (bText)   //prepare the label string
                {
                    string name = item.Properties["Name"].Value.ToString();
                    string sCPU = "";
                    if (osInfo.Version.Major < 6)
                        sCPU = "0";
                    else
                        sCPU = name.Substring(0, 1);

                    if (osInfo.Version.Major < 6)
                    {
                        ManagementObject Mo = new ManagementObject("Win32_Processor.DeviceID='CPU" + sCPU + "'");
                        uint sp = (uint)(Mo["CurrentClockSpeed"]);
                        Mo.Dispose();
                        sText +=
                            "Core"
                            + name.ToString()
                            + "@"
                            + sp.ToString()
                            + " "
                            + val.ToString()
                            + "%" + "\n";
                    }
                    else
                    {
                        string freq = item.Properties["ProcessorFrequency"].Value.ToString();
                        if (freq != "0") //dunno...works fine on my dualcore - but my quadcore says "0" ???
                            sText +=
                                name.Substring(0, 1)
                                + ":Core"
                                + name.ToString().Substring(2, 1)
                                + "@"
                                + freq
                                + " "
                                + val.ToString().PadLeft(3, '\u2000')
                                + "%" + "\n";
                        else
                        {
                            ManagementObject Mo = new ManagementObject("Win32_Processor.DeviceID='CPU" + sCPU + "'");
                            uint sp = (uint)(Mo["CurrentClockSpeed"]);
                            Mo.Dispose();
                            sText +=
                                name.Substring(0, 1)
                                + ":Core"
                                + name.ToString().Substring(2, 1)
                                + "@"
                                + sp.ToString()
                                + " "
                                + val.ToString().PadLeft(3, '\u2000')
                                + "%" + "\n";
                        }
                    }
                }

                iIndex++;
            }
            if (bText)
                lCPU.ExecuteThreadSafe(() => lCPU.Text = sText);

            if (bGraph)
            {
                cpuGraphControl.AxisChange();
                //// Force a redraw
                cpuGraphControl.Invalidate();
            }
        }
Exemple #25
0
        private void xGetDriveInfo()
        {
            //ドライブの情報を取得する

            gDrive = driveListBox1.SelectedItem.ToString().Substring(0,2);  //ドライブ文字を取得

            System.Management.ManagementObject mo =
            new System.Management.ManagementObject("Win32_LogicalDisk=\"" + gDrive + "\"");

            //名前("C:"など)
            textBox1.AppendText("名前:{0}" +
                (string)mo.Properties["Name"].Value + "\r\n");
            //ドライブタイプ
            string typeDescription = "";
            switch ((uint)mo.Properties["DriveType"].Value)
            {
                case 5:
                    typeDescription = "光ディスクドライブ(CD-ROM,DVD-ROMなど)";
                    break;
                case 3:
                    typeDescription = "固定ディスク";
                    break;
                case 4:
                    typeDescription = "ネットワークドライブ";
                    break;
                case 1:
                    typeDescription = "ルートディレクトリがない";
                    break;
                case 6:
                    typeDescription = "RAMディスク";
                    break;
                case 2:
                    typeDescription = "リムーバブルストレージデバイス" +
                        "フロッピーディスクドライブ、USBフラッシュドライブなど";
                    break;
                case 0:
                    typeDescription = "不明";
                    break;
            }
            textBox1.AppendText("ドライブタイプ:{0}" + typeDescription + "\n");
            //ボリュームラベル
            textBox1.AppendText("ボリュームラベル:{0}" +
                (string)mo.Properties["VolumeName"].Value + "\n");
            //ボリュームシリアルナンバー
            textBox1.AppendText("ボリュームシリアルナンバー:{0}" +
                (string)mo.Properties["VolumeSerialNumber"].Value + "\n");
            gSerial = (string)mo.Properties["VolumeSerialNumber"].Value;
            //ファイルシステム(NTFS、FAT32など)
            textBox1.AppendText("ファイルシステム:{0}" +
                (string)mo.Properties["FileSystem"].Value + "\n");
            //説明(「ローカル固定ディスク」など)
            textBox1.AppendText("説明:{0}" +
                (string)mo.Properties["Description"].Value + "\n");

            //ドライブの容量を取得する
            ulong ts = (ulong)mo.Properties["Size"].Value;
            textBox1.AppendText("サイズGB" + ts / 1000000000 + "\n");
            //C:のドライブの空き容量を取得する
            ulong fs = (ulong)mo.Properties["FreeSpace"].Value;
            textBox1.AppendText("空き容量GB" + fs / 1000000000 + "\n");
            mo.Dispose();
        }
Exemple #26
0
        public override void Commit(IDictionary savedState)
        {
            MessageBox.Show("Iniciando configuración 1");
            try
            {
                var ServiceKeys = Microsoft.Win32.Registry
                                  .LocalMachine.OpenSubKey(String.Format(@"System\CurrentControlSet\Services\{0}", "DigitalSignService"), true);

                MessageBox.Show("Obteniendo la clave");

                try
                {
                    var ServiceType = (ServiceType)(int)(ServiceKeys.GetValue("type"));

                    //Service must be of type Own Process or Share Process
                    if (((ServiceType & ServiceType.Win32OwnProcess) != ServiceType.Win32OwnProcess) &&
                        ((ServiceType & ServiceType.Win32ShareProcess) != ServiceType.Win32ShareProcess))
                    {
                        throw new Exception("ServiceType must be either Own Process or Shared   Process to enable interact with desktop");
                    }

                    var AccountType = ServiceKeys.GetValue("ObjectName");
                    //Account Type must be Local System
                    if (String.Equals(AccountType, "LocalSystem") == false)
                    {
                        throw new Exception("Service account must be local system to enable interact with desktop");
                    }
                    //ORing the InteractiveProcess with the existing service type
                    ServiceType newType = ServiceType | ServiceType.InteractiveProcess;
                    ServiceKeys.SetValue("type", (int)newType);
                }
                catch (Exception exce)
                {
                    MessageBox.Show(exce.Message);
                    MessageBox.Show(exce.StackTrace);
                }
                finally
                {
                    ServiceKeys.Close();
                }

                MessageBox.Show("Iniciando configuración 2");

                var service = new System.Management.ManagementObject(
                    String.Format("WIN32_Service.Name='{0}'", "DigitalSignService"));
                try
                {
                    var paramList = new object[11];
                    paramList[5] = true;//We only need to set DesktopInteract parameter

                    var output2 = service.InvokeMethod("Change", paramList);

                    MessageBox.Show(output2 + "");
                    //if zero is returned then it means change is done.
                    if (output2.ToString() == "0")
                    {
                        MessageBox.Show(string.Format("FAILED with code {0}", output2));
                    }
                }
                finally
                {
                    service.Dispose();
                }

                MessageBox.Show("Iniciando configuración 3");

                string command     = String.Format("sc config {0} type= own type= interact", "DigitalSignService");
                var    processInfo = new System.Diagnostics.ProcessStartInfo()
                {
                    //Shell Command
                    FileName = "cmd"
                    ,
                    //pass command as argument./c means carries
                    //out the task and then terminate the shell command
                    Arguments = "/c" + command
                    ,
                    //To redirect The Shell command output to process stanadrd output
                    RedirectStandardOutput = true
                    ,
                    // Now Need to create command window.
                    //Also we want to mimic this call as normal .net call
                    UseShellExecute = false
                    ,
                    // Do not show command window
                    CreateNoWindow = true
                };

                var process = System.Diagnostics.Process.Start(processInfo);

                var output = process.StandardOutput.ReadToEnd();

                MessageBox.Show(output);

                /*if (output.Trim().EndsWith("SUCCESS") == false)
                 *  throw new Exception(output);*/


                MessageBox.Show("Finalización de la configuración");


                /*ConnectionOptions coOptions = new ConnectionOptions();
                 * coOptions.Impersonation = ImpersonationLevel.Impersonate;
                 * ManagementScope mgmtScope = new ManagementScope(@"root\CIMV2", coOptions);
                 * mgmtScope.Connect();
                 * ManagementObject wmiService;
                 * wmiService = new ManagementObject("Win32_Service.Name='DigitalSignService");
                 * ManagementBaseObject InParam = wmiService.GetMethodParameters("Change");
                 * InParam["DesktopInteract"] = true;
                 * ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", InParam, null);*/
            }
            catch (System.Exception exce)
            {
                MessageBox.Show(exce.Message);
                MessageBox.Show(exce.StackTrace);
                LogTransaction(exce.Message);
                LogTransaction(exce.StackTrace);
                throw exce;
            }
        }
        /// <summary>
        /// Adds the share permissions.
        /// </summary>
        /// <param name="accountName">Name of the account.</param>
        public void AddSharePermission(string accountName)
        {
            ManagementObject trustee = null;
            ManagementObject ace = null;
            ManagementObject win32LogicalSecuritySetting = null;
            ManagementObject share = null;
            ManagementBaseObject getSecurityDescriptorReturn = null;
            ManagementBaseObject securityDescriptor = null;

            try
            {
                //// Not necessary
                //// NTAccount ntAccount = new NTAccount(accountName);
                //// SecurityIdentifier sid = (SecurityIdentifier)ntAccount.Translate(typeof(SecurityIdentifier));
                //// byte[] sidArray = new byte[sid.BinaryLength];
                //// sid.GetBinaryForm(sidArray, 0);

                trustee = new ManagementClass(new ManagementPath("Win32_Trustee"), null);
                trustee["Name"] = accountName;
                //// trustee["SID"] = sidArray;

                ace = new ManagementClass(new ManagementPath("Win32_Ace"), null);
                //// Permissions mask http://msdn.microsoft.com/en-us/library/windows/desktop/aa394186(v=vs.85).aspx
                ace["AccessMask"] = 0x1F01FF;
                //// ace["AccessMask"] = 0x1FF;
                ace["AceFlags"] = 3;
                ace["AceType"] = 0;
                ace["Trustee"] = trustee;

                win32LogicalSecuritySetting = new ManagementObject(@"root\cimv2:Win32_LogicalShareSecuritySetting.Name='" + this.shareName + "'");

                getSecurityDescriptorReturn = win32LogicalSecuritySetting.InvokeMethod("GetSecurityDescriptor", null, null);

                if ((uint)getSecurityDescriptorReturn["ReturnValue"] != 0)
                {
                    throw new WindowsShareException("Unable to add share permission. Error Code: " + getSecurityDescriptorReturn["ReturnValue"]);
                }

                securityDescriptor = getSecurityDescriptorReturn["Descriptor"] as ManagementBaseObject;
                ManagementBaseObject[] dacl = securityDescriptor["DACL"] as ManagementBaseObject[];

                if (dacl == null)
                {
                    dacl = new ManagementBaseObject[] { ace };
                }
                else
                {
                    Array.Resize(ref dacl, dacl.Length + 1);
                    dacl[dacl.Length - 1] = ace;
                }

                securityDescriptor["DACL"] = dacl;

                share = new ManagementObject(@"root\cimv2:Win32_Share.Name='" + this.shareName + "'");
                uint setShareInfoReturn = (uint)share.InvokeMethod("SetShareInfo", new object[] { null, null, securityDescriptor });

                if (setShareInfoReturn != 0)
                {
                    throw new WindowsShareException("Unable to add share permission. Error code: " + setShareInfoReturn.ToString(CultureInfo.CurrentCulture));
                }
            }
            catch (Exception ex)
            {
                throw new WindowsShareException("Unable to add share permission", ex);
            }
            finally
            {
                if (trustee != null)
                {
                    trustee.Dispose();
                }

                if (ace != null)
                {
                    ace.Dispose();
                }

                if (win32LogicalSecuritySetting != null)
                {
                    win32LogicalSecuritySetting.Dispose();
                }

                if (getSecurityDescriptorReturn != null)
                {
                    getSecurityDescriptorReturn.Dispose();
                }

                if (securityDescriptor != null)
                {
                    securityDescriptor.Dispose();
                }

                if (share != null)
                {
                    share.Dispose();
                }
            }
        }
 private void CollectCPUSpeed()
 {
     ManagementObject Mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'");
     ProcessorSpeed = (uint)(Mo["CurrentClockSpeed"]);
     Mo.Dispose();            
 }
        /// <summary>
        /// Reverts the VM to the previous shapshop
        /// </summary>
        /// <param name="vm">The vm to apply the snapstop to</param>
        /// <param name="snapshot">The snapshot image</param>
        /// <returns>True of operation completed without error</returns>
        private bool ApplyVirtualSystemSnapshot(ManagementObject vm, ManagementObject snapshot)
        {
            var jobSuccesful = false;

            ManagementScope scope = vm.Scope;

            ManagementObject virtualSystemService = Utility.GetServiceObject(scope, "Msvm_VirtualSystemManagementService");
            ManagementBaseObject inParams = virtualSystemService.GetMethodParameters("ApplyVirtualSystemSnapshot");
            inParams["SnapshotSettingData"] = snapshot.Path.Path;

            inParams["ComputerSystem"] = vm.Path.Path;

            ManagementBaseObject outParams = virtualSystemService.InvokeMethod("ApplyVirtualSystemSnapshot", inParams, null);

            if ((uint)outParams["ReturnValue"] == ReturnCode.Started)
            {
                if (Utility.JobCompleted(outParams, scope))
                {
                    this.LogBuildMessage(string.Format(CultureInfo.InvariantCulture, "Snapshot of [{0}] was applied successfully.", this.VMName.Get(this.ActivityContext)));
                    jobSuccesful = true;
                }
                else
                {
                    this.LogBuildWarning(string.Format(CultureInfo.InvariantCulture, "Failed to apply snapshot for VM [{0}].", this.VMName.Get(this.ActivityContext)));
                }
            }
            else if ((uint)outParams["ReturnValue"] == ReturnCode.Completed)
            {
                this.LogBuildMessage(string.Format(CultureInfo.InvariantCulture, "Snapshot of [{0}] was applied successfully.", this.VMName.Get(this.ActivityContext)));
                jobSuccesful = true;
            }
            else
            {
                this.LogBuildWarning(string.Format(CultureInfo.InvariantCulture, "Snapshot of [{0}] was applied but returned error {1}", this.VMName.Get(this.ActivityContext), outParams["ReturnValue"]));
            }

            inParams.Dispose();
            outParams.Dispose();
            snapshot.Dispose();
            vm.Dispose();
            virtualSystemService.Dispose();

            return jobSuccesful;
        }
Exemple #30
0
 public static TimeSpan GetUptime()
 {
     var mo = new ManagementObject(@"\\.\root\cimv2:Win32_OperatingSystem=@");
     var lastBootUp = ManagementDateTimeConverter.ToDateTime(mo["LastBootUpTime"].ToString());
     mo.Dispose();
     return DateTime.Now.ToUniversalTime() - lastBootUp.ToUniversalTime();
 }
Exemple #31
0
 private void DesktopInteract()
 {
     ManagementObject wmiService = null;
     ManagementBaseObject InParam = null;
     string ServiceName = "usbalertSidd";
     try
     {
         wmiService = new ManagementObject(string.Format("Win32_Service.Name='{0}'",
                         ServiceName));
         InParam = wmiService.GetMethodParameters("Change");
         InParam["DesktopInteract"] = true;
         wmiService.InvokeMethod("Change", InParam, null);
     }
     finally
     {
         if (InParam != null)
             InParam.Dispose();
         if (wmiService != null)
             wmiService.Dispose();
     }
 }