Пример #1
10
 public static ManagementObject[] getVhdSettings(ManagementObject virtualMachine, ManagementScope Scope)
 {
     using (ManagementObject mObject = getSettingData(wmiClass.Msvm_VirtualSystemSettingData.ToString(), wmiClass.Msvm_SettingsDefineState.ToString(), virtualMachine, Scope))
     {
         return getVHDSettings(mObject);
     }
 }
Пример #2
0
        /// <summary>
        /// Gets the data for a given snapshot that belongs to the given virtual machine..
        /// </summary>
        /// <param name="virtualMachine">The virtual machine object.</param>
        /// <param name="snapshotName">The name of the snapshot that should be obtained.</param>
        /// <returns>The snapshot data object or <see langword="null" /> if no snapshot could be found.</returns>
        public static ManagementObject GetSnapshotData(ManagementObject virtualMachine, string snapshotName)
        {
            ManagementObjectCollection vmSettings = virtualMachine.GetRelated(
                "Msvm_VirtualSystemsettingData",
                "Msvm_PreviousSettingData",
                null,
                null,
                "SettingData",
                "ManagedElement",
                false,
                null);

            ManagementObject vmSetting = null;
            foreach (ManagementObject instance in vmSettings)
            {
                var name = (string)instance["ElementName"];
                if (string.Equals(snapshotName, name, StringComparison.Ordinal))
                {
                    vmSetting = instance;
                    break;
                }
            }

            return vmSetting;
        }
Пример #3
0
        public static string GetWorkGroupName()
        {
            string result = String.Empty;
            if (OSVersionPlatform.GetConcretePlatform() == PlatformID.MacOSX)
            {
                //OS X
                string configFilePath = @"/Library/Preferences/SystemConfiguration/com.apple.smb.server.plist";
                PlistParser parser = new PlistParser(configFilePath);
                result = parser["Workgroup"].ToString();
            }
            else if (OSVersionPlatform.GetGenericPlatform() == PlatformID.Unix)
            {
                //Linux
                string configFilePath = @"/etc/samba/smb.conf";
                IniFileParser parser = new IniFileParser(configFilePath);
                result = parser.GetValue("Global", "Workgroup");
            }
            else
            {
                //Windows
                using (ManagementObject managementObject = new ManagementObject(String.Format("Win32_ComputerSystem.Name='{0}'", Environment.MachineName)))
                {
                    object workgroup;
                    //Workgroup is NULL under XP
                    if (OSVersionPlatform.IsWindowsVistaOrHigher())
                        workgroup = managementObject["Workgroup"];
                    else
                        workgroup = managementObject["Domain"];

                    result = workgroup.ToString();
                }
            }
            return result;
        }
Пример #4
0
        // Expects a Win32_DiskDrive object
        // http://msdn.microsoft.com/en-us/library/aa394132%28v=VS.85%29.aspx
        internal Volume(ManagementObject o)
        {
            if (o.ClassPath.ClassName != "Win32_DiskDrive")
                throw new ArgumentException (o.ClassPath.ClassName, "o");

            Uuid = o.Str ("PNPDeviceID");
            Name = o.Str ("Caption");

            // Get USB vendor/product ids from the associated CIM_USBDevice
            // This way of associating them (via a substring of the PNPDeviceID) is quite a hack; patches welcome
            var match = regex.Match (Uuid);
            if (match.Success) {
                string query = String.Format ("SELECT * FROM CIM_USBDevice WHERE DeviceID LIKE '%{0}'", match.Groups[1].Captures[0].Value);
                UsbDevice = HardwareManager.Query (query).Select (u => new UsbDevice (u)).FirstOrDefault ();
            }

            // Get MountPoint and more from the associated LogicalDisk
            // FIXME this assumes one partition for the device
            foreach (ManagementObject partition in o.GetRelated ("Win32_DiskPartition")) {
                foreach (ManagementObject disk in partition.GetRelated ("Win32_LogicalDisk")) {
                    //IsMounted = (bool)ld.GetPropertyValue ("Automount") == true;
                    //IsReadOnly = (ushort) ld.GetPropertyValue ("Access") == 1;
                    MountPoint = disk.Str ("Name") + "/";
                    FileSystem = disk.Str ("FileSystem");
                    Capacity = (ulong) disk.GetPropertyValue ("Size");
                    Available = (long)(ulong)disk.GetPropertyValue ("FreeSpace");
                    return;
                }
            }
        }
Пример #5
0
 public RAM(CrystalFontz635 cf)
     : base(cf)
 {
     Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
     Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
     pfRAM = new PerformanceCounter("Memory", "Available MBytes");
     using (ManagementObject mo = new ManagementObject(@"Win32_ComputerSystem.Name=""" + Environment.MachineName + "\"")) {
         TotalInstalled = (ulong)mo["TotalPhysicalMemory"];
     }
     pfRAM.NextValue();
     LcdModule.ClearScreen();
     LcdModule.SetCursorPosition(0, 0);
     LcdModule.SendData(0, 0, string.Format("RAM USAGE (T:{0}Mb)", Math.Round(TotalInstalled / 1024.0 / 1024.0)).PadRight(20));
     LcdModule.SetCGRAM(0,
         new byte[] {
             0x3f,
             0x3f,
             0x3f,
             0x3f,
             0x3f,
             0x3f,
             0x3f,
             0x3f
         });
     time = new Stopwatch();
     time.Start();
 }
Пример #6
0
 public static string GetUptime()
 {
     ManagementObject mo = new ManagementObject(@"\\.\root\cimv2:Win32_OperatingSystem=@");
     DateTime lastBootUp = ManagementDateTimeConverter.ToDateTime(mo["LastBootUpTime"].ToString());
     TimeSpan temp = DateTime.Now.ToUniversalTime() - lastBootUp.ToUniversalTime();
     return temp.Days.ToString() + ":" + temp.Hours.ToString() + ":" + temp.Minutes.ToString() + ":" + temp.Seconds.ToString();
 }
Пример #7
0
 public IisAppPool(ManagementScope scope, string name)
 {
     string path = String.Format("IIsApplicationPool='W3SVC/AppPools/{0}'", name);
     this.scope = scope;
     appPool = new ManagementObject(scope, new ManagementPath(path), null);
     Name = name;
 }
Пример #8
0
        public EventRecord(ManagementObject vmi)
        {
            if (vmi == null) return; //vmi can be null eg for testing
            Category = (vmi["Category"] != null) ? vmi["Category"].ToString() : String.Empty;
            ComputerName = (vmi["ComputerName"] != null) ? vmi["ComputerName"].ToString() : String.Empty;
            EventCode = (vmi["EventCode"] != null) ? vmi["EventCode"].ToString() : String.Empty;
            EventType = (vmi["EventType"] != null) ? vmi["EventType"].ToString() : String.Empty;

            Logfile = (vmi["Logfile"] != null) ? vmi["Logfile"].ToString() : String.Empty;
            Message = (vmi["Message"] != null) ? vmi["Message"].ToString() : String.Empty;
            RecordNumber = (vmi["RecordNumber"] != null) ? vmi["RecordNumber"].ToString() : String.Empty;
            SourceName = (vmi["SourceName"] != null) ? vmi["SourceName"].ToString() : String.Empty;
            //TimeGenerated
            string timeWrittenStr = (vmi["TimeWritten"] != null) ? vmi["TimeWritten"].ToString() : String.Empty;
               // CultureInfo provider = CultureInfo.InvariantCulture;

            DateTime outDateTime = ManagementDateTimeConverter.ToDateTime(timeWrittenStr); // DateTime.ParseExact(timeWrittenStr, "yyyyMMddHHmmss.ffffff-zzz", provider);
            TimeGenerated = outDateTime;
                        // .ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK");

            //  TimeWritten = (vmi["TimeWritten"] != null) ? vmi["TimeWritten"].ToString() : String.Empty;
            Type = (vmi["Type"] != null) ? vmi["Type"].ToString() : String.Empty;
            if (vmi["InsertionStrings"] != null )
            {
                var strList = (String[]) vmi["InsertionStrings"];
                foreach (var insString in strList)
                {
                    this.InsertionStrings  += " " + insString ;
                }
            }
            else
            {
                this.InsertionStrings = String.Empty;
            }
        }
Пример #9
0
        protected override void OnCommitted(IDictionary savedState)
        {
            base.OnCommitted (savedState);

            // Setting the "Allow Interact with Desktop" option for this service.
            ConnectionOptions connOpt = new ConnectionOptions();
            connOpt.Impersonation = ImpersonationLevel.Impersonate;
            ManagementScope mgmtScope = new ManagementScope(@"root\CIMv2", connOpt);
            mgmtScope.Connect();
            ManagementObject wmiService = new ManagementObject("Win32_Service.Name='" + ReflectorMgr.ReflectorServiceName + "'");
            ManagementBaseObject inParam = wmiService.GetMethodParameters("Change");
            inParam["DesktopInteract"] = true;
            ManagementBaseObject outParam = wmiService.InvokeMethod("Change", inParam, null);

            #region Start the reflector service immediately
            try
            {
                ServiceController sc = new ServiceController("ConferenceXP Reflector Service");
                sc.Start();
            }
            catch (Exception ex)
            {
                // Don't except - that would cause a rollback.  Instead, just tell the user.
                RtlAwareMessageBox.Show(null, string.Format(CultureInfo.CurrentCulture, Strings.ServiceStartFailureText, 
                    ex.ToString()), Strings.ServiceStartFailureTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning, 
                    MessageBoxDefaultButton.Button1, (MessageBoxOptions)0);
            }
            #endregion
        }
Пример #10
0
        private void Dispose(bool disposing)
        {
            if (_disposed) return;

            if (disposing)
            {
                if(_process != null)
                {
                    try
                    {
                        _process.InvokeMethod("Terminate", new object[] { 0 });
                    }
                    catch
                    {
                        Logger.Warn("Unable to terminate remote process on [{0}].", _server);
                    }
                    finally
                    {
                        _process.Dispose();
                        _process = null;
                    }
                }
            }
            _disposed = true;
        }
Пример #11
0
 //获取硬盘卷标号
 public static string GetDiskVolumeSerialNumber()
 {
     ManagementClass mc = new ManagementClass("win32_NetworkAdapterConfiguration");
     ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
     disk.Get();
     return disk.GetPropertyValue("VolumeSerialNumber").ToString();
 }
Пример #12
0
        public float CollectMetric(PluginResource pluginResource, string option = null)
        {
            // get a handle on the service first
            var service = ServiceController.GetServices().FirstOrDefault(s => s.DisplayName == option);
            if (service == null)
            {
                throw new Exception(string.Format("Windows service by name '{0}' not found", option));
            }

            if (service.Status == ServiceControllerStatus.Stopped)
            {
                return default(float);
            }
            else if (pluginResource.ResourceTextKey == StatusResource)
            {
                return 1;
            }

            // get a handle on the process
            var serviceMgtObj = new ManagementObject(@"Win32_Service.Name='" + service.ServiceName + "'");
            var serviceProcess = Process.GetProcessById(Convert.ToInt32(serviceMgtObj["ProcessId"]));

            // return perfomance counter value for process
            var perfCounter = new PerformanceCounter("Process", pluginResource.Label, serviceProcess.ProcessName);

            var value = perfCounter.NextValue();
            if (value == 0.0)
            {
                Thread.Sleep(1000);
                value = perfCounter.NextValue();
            }

            return value;
        }
Пример #13
0
        public override void Install(System.Collections.IDictionary savedState)
        {
            try
            {
                base.Install(savedState);

                // Turn on "Allow service to interact with desktop".
                // (Note: A published technique to do this by setting a bit in the service's Type registry value (0x100) does not turn this on, so do as follows.)
                // This will let the NotifyIcon appear in the sys tray (with balloon at start-up), but not its context menu.
                ConnectionOptions options = new ConnectionOptions();
                options.Impersonation = ImpersonationLevel.Impersonate;
                ManagementScope scope = new ManagementScope(@"root\CIMv2", options); // Common Information Model, version 2.
                ManagementObject wmiService = new ManagementObject("Win32_Service.Name='" + this.serviceInstaller.ServiceName + "'");
                ManagementBaseObject inParameters = wmiService.GetMethodParameters("Change");
                inParameters["DesktopInteract"] = true;
                ManagementBaseObject outParameters = wmiService.InvokeMethod("Change", inParameters, null);
            }
            catch (Exception e)
            {
                string licenseKey = "";
                string licenseName = "";
                try
                {
                    licenseKey = Properties.Settings.Default.LicenseKey;
                    licenseName = Properties.Settings.Default.LicenseName;
                }
                catch { }

                Service.Services.LoggingService.AddLogEntry(WOSI.CallButler.ManagementInterface.LogLevel.ErrorsOnly, Utils.ErrorUtils.FormatErrorString(e), true);
                CallButler.ExceptionManagement.ErrorCaptureUtils.SendError(e, licenseKey, licenseName, "");
            }
        }
Пример #14
0
 /// <summary>
 /// <para>Create a new <see cref="StorageDisk"/> from the corresponding <see cref="ManagementObject"/></para>
 /// </summary>
 /// <param name="mo"></param>
 public StorageDisk(ManagementObject mo)
     : base(mo["DeviceID"].ToString())
 {
     this.Model = mo["Model"].ToString();
     this.Name = mo["Name"].ToString();
     this.Size = Convert.ToUInt64(mo["Size"]);
 }
Пример #15
0
 private static void Win32_SharesSearcher()
 {
     SelectQuery query = new SelectQuery("select * from Win32_Share where Name=\"" + sharename + "\"");
     using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
     {
         foreach (ManagementObject mo in searcher.Get())
         {
             foreach (PropertyData prop in mo.Properties)
             {
                 form.textBox1.AppendText(prop.Name + " = " + mo[prop.Name] + Environment.NewLine);                    }
                 //form.textBox1.AppendText(string.Format("Win32ShareName: {0} Description {1} Path {2} ", mo.Properties["Name"].Value, mo.Properties["Description"].Value, mo.Properties["Path"].Value) + Environment.NewLine);
         }
     }
     ManagementObject winShareP = new ManagementObject("root\\CIMV2", "Win32_Share.Name=\"" + sharename + "\"", null);
     ManagementBaseObject outParams = winShareP.InvokeMethod("GetAccessMask", null, null);
     form.textBox1.AppendText(String.Format("access Mask = {0:x}", outParams["ReturnValue"]) + Environment.NewLine);
     ManagementBaseObject inParams = winShareP.GetMethodParameters("SetShareInfo");
     form.textBox1.AppendText("SetShareInfor in parameters" + Environment.NewLine);
     foreach (PropertyData prop in inParams.Properties)
     {
         form.textBox1.AppendText(String.Format("PROP = {0}, TYPE = {1} ", prop.Name, prop.Type.ToString()) + Environment.NewLine);
     }
     Object access = inParams.GetPropertyValue("Access");
     //Stopped development here because ShareAFolder project exists. The rest of the development is there
     //Maybe should copy Sahare a Folder content to here at some point
 }
Пример #16
0
 public HotFixes(ManagementObject instance)
 {
     hotFixID = (instance.Properties["HotFixID"].Value != null && instance.Properties["HotFixID"].Value != null)
                    ? instance.Properties["HotFixID"].Value.ToString().Trim()
                    : string.Empty;
     description = (instance.Properties["Description"].Value != null && instance.Properties["Description"].Value != null)
                       ? instance.Properties["Description"].Value.ToString().Trim()
                       : string.Empty;
     servicePackInEffect = (instance.Properties["ServicePackInEffect"].Value != null && instance.Properties["ServicePackInEffect"].Value.ToString() != string.Empty)
                               ? instance.Properties["ServicePackInEffect"].Value.ToString().Trim()
                               : string.Empty;
     caption = (instance.Properties["Caption"].Value != null && instance.Properties["Caption"].Value.ToString() != string.Empty)
                               ? instance.Properties["Caption"].Value.ToString().Trim()
                               : string.Empty;
     cSName = (instance.Properties["CSName"].Value != null && instance.Properties["CSName"].Value.ToString() != string.Empty)
                               ? instance.Properties["CSName"].Value.ToString().Trim()
                               : string.Empty;
     installDate = (instance.Properties["InstallDate"].Value != null && instance.Properties["InstallDate"].Value != null && instance.Properties["InstallDate"].Value.ToString() != string.Empty)
                               ? instance.Properties["InstallDate"].Value.ToString().Trim()
                               : string.Empty;
     fixComments = (instance.Properties["FixComments"].Value != null && instance.Properties["FixComments"].Value.ToString() != string.Empty)
                               ? instance.Properties["FixComments"].Value.ToString().Trim()
                               : string.Empty;
     installedBy = (instance.Properties["InstalledBy"].Value != null && instance.Properties["InstalledBy"].Value.ToString() != string.Empty)
                               ? instance.Properties["InstalledBy"].Value.ToString().Trim()
                               : string.Empty;
     installedOn = (instance.Properties["InstalledOn"].Value != null && instance.Properties["InstalledOn"].Value.ToString() != string.Empty)
                               ? instance.Properties["InstalledOn"].Value.ToString().Trim()
                               : string.Empty;
     status = (instance.Properties["Status"].Value != null && instance.Properties["Status"].Value.ToString() != string.Empty)
                               ? instance.Properties["Status"].Value.ToString().Trim()
                               : string.Empty;
 }
        GetImportedPvm(
            ManagementBaseObject outputParameters)
        {
            ManagementObject pvm = null;
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            if (WmiUtilities.ValidateOutput(outputParameters, scope))
            {
                if ((uint)outputParameters["ReturnValue"] == 0)
                {
                    pvm = new ManagementObject((string)outputParameters["ImportedSystem"]);
                }
                
                if ((uint)outputParameters["ReturnValue"] == 4096)
                {
                    using (ManagementObject job = 
                        new ManagementObject((string)outputParameters["Job"]))
                    using (ManagementObjectCollection pvmCollection = 
                        job.GetRelated("Msvm_PlannedComputerSystem",
                            "Msvm_AffectedJobElement", null, null, null, null, false, null))
                    {
                        pvm = WmiUtilities.GetFirstObjectFromCollection(pvmCollection);
                    }

                }
            }

            return pvm;
        }
Пример #18
0
    private string Identifier(string wmiClass, string wmiProperty)
    {
        //Return a hardware identifier

        string Result = "";

        System.Management.ManagementClass            mc  = new System.Management.ManagementClass(wmiClass);
        System.Management.ManagementObjectCollection moc = mc.GetInstances();
        System.Management.ManagementObject           mo  = null;

        foreach (System.Management.ManagementObject mo_loopVariable in moc)
        {
            mo = mo_loopVariable;
            //Only get the first one
            if (string.IsNullOrEmpty(Result))
            {
                try {
                    Result = mo[wmiProperty].ToString();
                    break;                     // TODO: might not be correct. Was : Exit For
                }
                catch (Exception ex) {
                    //Ignore error
                }
            }
        }

        return(Result);
    }
Пример #19
0
 public Disk(ManagementObject instance)
 {
     PropertyDataCollection.PropertyDataEnumerator enumerator = instance.Properties.GetEnumerator();
     while (enumerator.MoveNext())
     {
         Console.WriteLine(enumerator.Current.Name);
     }
     manufacturer = (instance.Properties["Manufacturer"].Value != null)
                        ? instance.Properties["Manufacturer"].Value.ToString().Trim()
                        : string.Empty;
     model = (instance.Properties["Model"].Value != null)
                 ? instance.Properties["Model"].Value.ToString().Trim()
                 : string.Empty;
     description = (instance.Properties["Description"].Value != null)
                       ? instance.Properties["Description"].Value.ToString().Trim()
                       : string.Empty;
     interfaceType = (instance.Properties["InterfaceType"].Value != null)
                         ? instance.Properties["InterfaceType"].Value.ToString().Trim()
                         : string.Empty;
     size = (instance.Properties["Size"].Value != null)
                ? instance.Properties["Size"].Value.ToString().Trim()
                : string.Empty;
     partitions = (instance.Properties["Partitions"].Value != null)
                      ? instance.Properties["Partitions"].Value.ToString().Trim()
                      : string.Empty;
     scsiBus = (instance.Properties["ScsiBus"].Value != null)
                   ? instance.Properties["ScsiBus"].Value.ToString().Trim()
                   : string.Empty;
     scsiTargetID = (instance.Properties["ScsiTargetID"].Value != null)
                        ? instance.Properties["ScsiTargetID"].Value.ToString().Trim()
                        : string.Empty;
     deviceID = (instance.Properties["DeviceID"].Value != null)
                    ? instance.Properties["DeviceID"].Value.ToString().Trim()
                    : string.Empty;
 }
Пример #20
0
        static void Main()
        {
            DirectoryInfo currentDir = new DirectoryInfo(Environment.CurrentDirectory);
            string path = string.Format("win32_logicaldisk.deviceid=\"{0}\"",
                currentDir.Root.Name.Replace("\\", ""));
            ManagementObject disk = new ManagementObject(path);
            disk.Get();

            String serial = disk["VolumeSerialNumber"].ToString();
            Conexion_MSS conexion = new Conexion_MSS("null", "null", "Requerimientos", 0);
            conexion.conexion.Open();
            conexion.cmd = new System.Data.SqlClient.SqlCommand("Select usuario from Cuentas where ID='" + serial + "'", conexion.conexion);
            conexion.reader = conexion.cmd.ExecuteReader();
            List<String> cuentas = new List<string>();
            while (conexion.reader.Read())
            {
                cuentas.Add(conexion.reader[0].ToString());
            }
            conexion.reader.Close();
            conexion.conexion.Close();

            if (cuentas.Count() > 0)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Cuentas(serial,cuentas));

            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Login(serial));
            }
        }
Пример #21
0
        protected void addComputerToCollection(string resourceID, string collectionID)
        {
            /*  Set collection = SWbemServices.Get ("SMS_Collection.CollectionID=""" & CollID &"""")

                  Set CollectionRule = SWbemServices.Get("SMS_CollectionRuleDirect").SpawnInstance_()
                  CollectionRule.ResourceClassName = "SMS_R_System"
                  CollectionRule.RuleName = "Static-"&ResourceID
                  CollectionRule.ResourceID = ResourceID
                  collection.AddMembershipRule CollectionRule*/

            //o.Properties["ResourceID"].Value.ToString();

            var pathString = "\\\\srv-cm12-p01.srv.aau.dk\\ROOT\\SMS\\site_AA1" + ":SMS_Collection.CollectionID=\"" + collectionID + "\"";
            ManagementPath path = new ManagementPath(pathString);
            ManagementObject obj = new ManagementObject(path);

            ManagementClass ruleClass = new ManagementClass("\\\\srv-cm12-p01.srv.aau.dk\\ROOT\\SMS\\site_AA1" + ":SMS_CollectionRuleDirect");

            ManagementObject rule = ruleClass.CreateInstance();

            rule["RuleName"] = "Static-"+ resourceID;
            rule["ResourceClassName"] = "SMS_R_System";
            rule["ResourceID"] = resourceID;

            obj.InvokeMethod("AddMembershipRule", new object[] { rule });
        }
 internal MethodData(ManagementObject parent, string methodName)
 {
     this.parent = parent;
     this.methodName = methodName;
     this.RefreshMethodInfo();
     this.qualifiers = null;
 }
        void VolumeManager_NewSession(VolumeSession rpSession)
        {
            var rHostProcessID = Process.GetCurrentProcess().Id;
            int? rProcessID = rpSession.ProcessID;

            var rIsBrowserProcess = false;

            while (rProcessID.HasValue)
                using (var rManagementObject = new ManagementObject($"Win32_Process.Handle='{rProcessID.Value}'"))
                    try
                    {
                        rManagementObject.Get();
                        rProcessID = Convert.ToInt32(rManagementObject["ParentProcessId"]);

                        if (rProcessID == rHostProcessID)
                        {
                            rIsBrowserProcess = true;
                            break;
                        }
                    }
                    catch (ManagementException e) when (e.ErrorCode == ManagementStatus.NotFound)
                    {
                        rProcessID = null;
                    }

            if (!rIsBrowserProcess)
                return;

            Volume?.Dispose();
            Volume = new BrowserVolume(rpSession);

            VolumeManager.Instance.NewSession -= VolumeManager_NewSession;
        }
Пример #24
0
 public VideoController(ManagementObject instance)
 {
     description = (instance.Properties["Description"].Value != null)
                       ? instance.Properties["Description"].Value.ToString().Trim()
                       : string.Empty;
     currentHorizontalResolution = (instance.Properties["CurrentHorizontalResolution"].Value !=
                                    null)
                                       ?
                                   instance.Properties["CurrentHorizontalResolution"].Value.
                                       ToString().Trim()
                                       : string.Empty;
     currentVerticalResolution = (instance.Properties["CurrentVerticalResolution"].Value != null)
                                     ?
                                 instance.Properties["CurrentVerticalResolution"].Value.ToString().
                                     Trim()
                                     : string.Empty;
     currentNumberOfColors = (instance.Properties["CurrentNumberOfColors"].Value != null)
                                 ?
                             instance.Properties["CurrentNumberOfColors"].Value.ToString().Trim()
                                 : string.Empty;
     videoProcessor = (instance.Properties["VideoProcessor"].Value != null)
                          ? instance.Properties["VideoProcessor"].Value.ToString().Trim()
                          : string.Empty;
     adapterRAM = (instance.Properties["AdapterRAM"].Value != null)
                      ? instance.Properties["AdapterRAM"].Value.ToString().Trim()
                      : string.Empty;
     installedDisplayDrivers = (instance.Properties["InstalledDisplayDrivers"].Value != null)
                                   ?
                               instance.Properties["InstalledDisplayDrivers"].Value.ToString().Trim
                                   ()
                                   : string.Empty;
     driverVersion = (instance.Properties["DriverVersion"].Value != null)
                         ? instance.Properties["DriverVersion"].Value.ToString().Trim()
                         : string.Empty;
 }
Пример #25
0
 public static string DriveSN(string DriveLetter)
 {
     ManagementObject disk = new ManagementObject(String.Format("Win32_Logicaldisk='{0}'", DriveLetter));
     string VolumeName = disk.Properties["VolumeName"].Value.ToString();
     string SerialNumber = disk.Properties["VolumeSerialnumber"].Value.ToString();
     return SerialNumber.Insert(4, "-");
 }
Пример #26
0
        int wnicIndex; //the index of the wireless network interface

        #endregion Fields

        #region Constructors

        public DataStatistics(Hashtable param)
        {
            SaveResult = PublicFuns.str2Int32((String)param["SaveResult"], 1);
            FileName = (String)param["FileName"];
            StatisticLevel = PublicFuns.str2Int32((String)param["StatisticLevel"], 0);
            wnicIndex = PublicFuns.str2Int32((String)param["WNICIndex"], 0);
            tempData = new StatData(param);

            hasWNIC = false;
            sysInfo = new SystemInfo();

            win32ProcessorObj = RetrieveManagementObject("Win32_Processor");
            processor.update(win32ProcessorObj);
            sysInfo.pro = processor;

            try
            {
                getSystemInfo();
                createSystemCounters();
                initLog();
            }
            catch (MyException ex)
            {
                throw ex;
            }
        }
 public static string GetVolumeSerial(string strDriveLetter)
 {
     if (strDriveLetter == "" || strDriveLetter == null) strDriveLetter = "C";
       ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"" + strDriveLetter + ":\"");
       disk.Get();
       return disk["VolumeSerialNumber"].ToString();
 }
Пример #28
0
 private static uint DecompressFolder(string path)
 {
     using (ManagementObject obj2 = new ManagementObject("Win32_Directory.Name=\"" + path.Replace(@"\", @"\\") + "\""))
     {
         return (uint)obj2.InvokeMethod("UnCompress", null, null).Properties["ReturnValue"].Value;
     }
 }
Пример #29
0
        /// <summary>
        /// Indicates if the AppPool is running.
        /// </summary>
        /// <param name="appPoolName">The AppPool name.</param>
        /// <returns>An <see cref="bool"/>. Indicating if the AppPool is running.</returns>
        public static bool IsAppPoolRunning(string appPoolName)
        {
            string managementObjectPath = string.Format(CultureInfo.CurrentCulture, "root\\MicrosoftIISv2:IIsApplicationPoolSetting.Name=\"W3SVC/APPPOOLS/{0}\"", appPoolName);
            int state;
            using (ManagementObject managementObject = new ManagementObject(managementObjectPath))
            {
                try
                {
                    state = (int)managementObject[IisApplicationPoolSettingPropertyNames.AppPoolState];
                }
                catch (DirectoryNotFoundException e)
                {
                    if (e.Message == "Win32: The system cannot find the path specified.\r\n")
                    {
                        string exceptionMessage = string.Format(CultureInfo.CurrentCulture, "Could not find an AppPool with a name of '{0}'.", appPoolName);
                        throw new CoreException(exceptionMessage);
                    }

                    throw;
                }
            }

            switch (state)
            {
                case AppPoolStatus.Started:
                    return true;
                case AppPoolStatus.Stopped:
                    return false;
                default:
                    string exceptionMessage = string.Format(CultureInfo.CurrentCulture, "The AppPool with a name of '{0}' had an unknown status.", appPoolName);
                    throw new CoreException(exceptionMessage);
            }
        }
        public string SetHostname(string hostname)
        {
            var oldName = Environment.MachineName;
            _logger.Log("Old host name: " + oldName);
            _logger.Log("New host name: " + hostname);
            if (string.IsNullOrEmpty(hostname) || oldName.Equals(hostname, StringComparison.InvariantCultureIgnoreCase))
                return 0.ToString();

            using (var cs = new ManagementObject(@"Win32_Computersystem.Name='" + oldName + "'"))
            {
                cs.Get();
                var inParams = cs.GetMethodParameters("Rename");
                inParams.SetPropertyValue("Name", hostname);
                var methodOptions = new InvokeMethodOptions(null, TimeSpan.MaxValue);
                var outParams = cs.InvokeMethod("Rename", inParams, methodOptions);
                if (outParams == null)
                    return 1.ToString();

                var renameResult = Convert.ToString(outParams.Properties["ReturnValue"].Value);
                //Restart in 10 secs because we want finish current execution and write response back to Xenstore.
                if ("0".Equals(renameResult))
                    Process.Start(@"shutdown.exe", @"/r /t 10 /f /d p:2:4");
                return renameResult;
            }
        }
Пример #31
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);
        }
Пример #32
0
 private static double BytesToGigs(ManagementObject queryObj, string column)
 {
     var totalPhysicalMemoryString = queryObj[column];
     var totalPhysicalMemory = Convert.ToDouble(totalPhysicalMemoryString);
     var totalPhysicalGigs = Math.Round(totalPhysicalMemory / 1024 / 1024 / 1024, digits: 2);
     return totalPhysicalGigs;
 }
Пример #33
0
        public static string GetUSBdeviceID(string path)
        {
            string           drive = path.Substring(0, 2);
            string           h     = "Win32_LogicalDisk=\"" + drive + "\"";
            ManagementObject mo    = new System.Management.ManagementObject(h);

            return((string)mo.Properties["VolumeSerialNumber"].Value);
        }
Пример #34
0
        public static string GetUSBdeviceID()
        {
            Assembly         myAssembly = Assembly.GetEntryAssembly();
            string           path       = myAssembly.Location;
            string           drive      = path.Substring(0, 2);
            string           h          = "Win32_LogicalDisk=\"" + drive + "\"";
            ManagementObject mo         = new System.Management.ManagementObject(h);

            return((string)mo.Properties["VolumeSerialNumber"].Value);
        }
Пример #35
0
 private System.Management.ManagementObject FindWMIObject(string name, string propname)
 {
     System.Management.ManagementObject foundObj = null;
     foreach (System.Management.ManagementObject obj in list)
     {
         if (obj.Properties[propname].Value.ToString() == name)
         {
             foundObj = obj;
             break;
         }
     }
     return(foundObj);
 }
Пример #36
0
 public SystemAccount(System.Management.ManagementObject theObject)
 {
     Initialize();
     if ((CheckIfProperClass(theObject) == true))
     {
         PrivateLateBoundObject  = theObject;
         PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject);
         curObj = PrivateLateBoundObject;
     }
     else
     {
         throw new System.ArgumentException("类名不匹配。");
     }
 }
Пример #37
0
 public EnvironmentWmi(System.Management.ManagementObject theObject)
 {
     Initialize();
     if ((CheckIfProperClass(theObject) == true))
     {
         PrivateLateBoundObject  = theObject;
         PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject);
         curObj = PrivateLateBoundObject;
     }
     else
     {
         throw new System.ArgumentException("Class name does not match.");
     }
 }
Пример #38
0
 public EthernetSwitchPortBandwidthSettingData(System.Management.ManagementObject theObject)
 {
     Initialize();
     if ((CheckIfProperClass(theObject) == true))
     {
         PrivateLateBoundObject  = theObject;
         PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject);
         curObj = PrivateLateBoundObject;
     }
     else
     {
         throw new System.ArgumentException("Class name does not match.");
     }
 }
Пример #39
0
        private void startToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string name = this.dataGridView1.Rows[this.dataGridView1.SelectedCells[0].RowIndex].Cells["Name"].Value.ToString();

            if (name != null && name != "")
            {
                System.Management.ManagementObject obj = FindWMIObject(name, "Name");
                if (obj != null)
                {
                    obj.InvokeMethod("StartService", null);
                    LoadServices(this.wmiServerCredentials1.Username, this.wmiServerCredentials1.Password, this.wmiServerCredentials1.SelectedServer);
                }
            }
        }
Пример #40
0
 private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     Initialize();
     if ((path != null))
     {
         if ((CheckIfProperClass(mgmtScope, path, getOptions) != true))
         {
             throw new System.ArgumentException("Class name does not match.");
         }
     }
     PrivateLateBoundObject  = new System.Management.ManagementObject(mgmtScope, path, getOptions);
     PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject);
     curObj = PrivateLateBoundObject;
 }
Пример #41
0
 protected override void OnAfterInstall(IDictionary savedState)
 {
     try
     {
         System.Management.ManagementObject myService = new System.Management.ManagementObject(
             string.Format("Win32_Service.Name='{0}'", this.serviceInstaller1.ServiceName));
         System.Management.ManagementBaseObject changeMethod = myService.GetMethodParameters("Change");
         changeMethod["DesktopInteract"] = true;
         System.Management.ManagementBaseObject OutParam = myService.InvokeMethod("Change", changeMethod, null);
     }
     catch (Exception)
     {
     }
     base.OnAfterInstall(savedState);
 }
Пример #42
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());
            }
        }
 internal WmiGetEventSink GetNewGetSink(ManagementScope scope, object context, ManagementObject managementObject)
 {
     try
     {
         WmiGetEventSink sink = WmiGetEventSink.GetWmiGetEventSink(this, context, scope, managementObject);
         lock (this.m_sinkCollection)
         {
             this.m_sinkCollection.Add(sink.GetHashCode(), sink);
         }
         return(sink);
     }
     catch
     {
         return(null);
     }
 }
Пример #44
0
        } //used to lock usage of BeginMethodEnum/NextMethod

        internal MethodDataCollection(ManagementObject parent) : base()
        {
            this.parent = parent;
        }
Пример #45
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;
            }
        }