Ejemplo n.º 1
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);
    }
        public static void RemoveContent(DirectoryInfo dir)
        {
            if (!dir.Exists)
            {
                return;
            }

            LogMessage(MessageType.Info, string.Format(CultureInfo.CurrentCulture, "Removing Content from Folder: {0}", dir.FullName));
            FileSystemInfo[] infos = dir.GetFileSystemInfos("*");
            foreach (FileSystemInfo i in infos)
            {
                // Check to see if this is a DirectoryInfo object.
                if (i is DirectoryInfo)
                {
                    string dirObject = string.Format(CultureInfo.CurrentCulture, "win32_Directory.Name='{0}'", i.FullName);
                    using (ManagementObject mdir = new ManagementObject(dirObject))
                    {
                        mdir.Get();
                        ManagementBaseObject outParams = mdir.InvokeMethod("Delete", null, null);

                        // ReturnValue should be 0, else failure
                        if (outParams != null)
                        {
                            if (Convert.ToInt32(outParams.Properties["ReturnValue"].Value, CultureInfo.CurrentCulture) != 0)
                            {
                                LogMessage(MessageType.Error, string.Format(CultureInfo.CurrentCulture, "Directory deletion error: ReturnValue: {0}", outParams.Properties["ReturnValue"].Value));
                                return;
                            }
                        }
                        else
                        {
                            LogMessage(MessageType.Error, "The ManagementObject call to invoke Delete returned null.");
                            return;
                        }
                    }
                }
                else if (i is FileInfo)
                {
                    // First make sure the file is writable.
                    FileAttributes fileAttributes = System.IO.File.GetAttributes(i.FullName);

                    // If readonly attribute is set, reset it.
                    if ((fileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                    {
                        System.IO.File.SetAttributes(i.FullName, fileAttributes ^ FileAttributes.ReadOnly);
                    }

                    if (i.Exists)
                    {
                        System.IO.File.Delete(i.FullName);
                    }
                }
            }
        }
Ejemplo n.º 3
0
 internal void AddFeatureSettings(ManagementObject ethernetPortAllocationSettings, ManagementObject[] featureSettings, out ManagementObject[] resultingFeatureSettings)
 {
     using (ManagementBaseObject inputParameters = vmms.GetMethodParameters("AddFeatureSettings"))
     {
         inputParameters["AffectedConfiguration"] = ethernetPortAllocationSettings.Path.Path;
         inputParameters["FeatureSettings"]       = featureSettings.ToStringArray();
         using (ManagementBaseObject outputParameters = vmms.InvokeMethod("AddFeatureSettings", inputParameters, null))
         {
             ValidateOutput(outputParameters);
             resultingFeatureSettings = ((string[])outputParameters["ResultingFeatureSettings"]).ToObjectArray();
         }
     }
 }
        ModifySanResources(
            string poolId,
            string[] newHostResources)
        {
            if (newHostResources == null)
            {
                Console.WriteLine("Deleting all resources assigned to Virtual SAN {0} ...", poolId);
            }
            else
            {
                Console.WriteLine("Modifying resources assigned to Virtual SAN {0} ...", poolId);
            }

            ManagementScope scope = FibreChannelUtilities.GetFcScope();

            using (ManagementObject rpConfigurationService =
                       FibreChannelUtilities.GetResourcePoolConfigurationService(scope))
            {
                string poolPath = FibreChannelUtilities.GetResourcePoolPath(scope, poolId);

                string[] parentPoolPathArray = new string[1];
                parentPoolPathArray[0] = FibreChannelUtilities.GetResourcePoolPath(scope, null);

                string[] newPoolAllocationSettingsArray = new string[1];
                newPoolAllocationSettingsArray[0] =
                    FibreChannelUtilities.GetNewPoolAllocationSettings(scope, poolId, newHostResources);

                using (ManagementBaseObject inParams =
                           rpConfigurationService.GetMethodParameters("ModifyPoolResources"))
                {
                    inParams["ChildPool"]          = poolPath;
                    inParams["ParentPools"]        = parentPoolPathArray;
                    inParams["AllocationSettings"] = newPoolAllocationSettingsArray;

                    using (ManagementBaseObject outParams =
                               rpConfigurationService.InvokeMethod(
                                   "ModifyPoolResources",
                                   inParams,
                                   null))
                    {
                        WmiUtilities.ValidateOutput(outParams, scope, true, true);
                    }
                }
            }

            if (newHostResources == null)
            {
                Console.WriteLine("Successfully deleted all resources assigned to Virtual SAN {0}", poolId);
            }
            else
            {
                Console.WriteLine("Successfully modified resources assigned to Virtual SAN {0}", poolId);
            }
        }
Ejemplo n.º 5
0
        private static void DisableDHCP(ExecutionContext context, ManagementObject adapter)
        {
            string[] ipGateways  = ParseArray(context.Parameters["DefaultIPGateway"]);
            string[] ipAddresses = ParseArray(context.Parameters["IPAddress"]);
            string[] subnetMasks = ParseArray(context.Parameters["SubnetMask"]);
            if (subnetMasks.Length != ipAddresses.Length)
            {
                throw new ArgumentException("Number of Subnet Masks should be equal to IP Addresses");
            }

            ManagementBaseObject objNewIP      = null;
            ManagementBaseObject objSetIP      = null;
            ManagementBaseObject objNewGateway = null;


            objNewIP      = adapter.GetMethodParameters("EnableStatic");
            objNewGateway = adapter.GetMethodParameters("SetGateways");


            //Set DefaultGateway
            objNewGateway["DefaultIPGateway"] = ipGateways;
            int[] cost = new int[ipGateways.Length];
            for (int i = 0; i < cost.Length; i++)
            {
                cost[i] = 1;
            }
            objNewGateway["GatewayCostMetric"] = cost;


            //Set IPAddress and Subnet Mask
            objNewIP["IPAddress"]  = ipAddresses;
            objNewIP["SubnetMask"] = subnetMasks;

            Log.WriteStart("Configuring static IP...");
            objSetIP = adapter.InvokeMethod("EnableStatic", objNewIP, null);
            Log.WriteEnd("IP configured");

            Log.WriteStart("Configuring default gateway...");
            objSetIP = adapter.InvokeMethod("SetGateways", objNewGateway, null);
            Log.WriteEnd("Default gateway configured");
        }
        ModifySwitchName(
            string existingSwitchName,
            string newSwitchName,
            string newNotes)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            //
            // Get the switch we want to modify.
            //
            using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(existingSwitchName, scope))

                //
                // To make modifications to the switch, we need to modify its configuration object.
                //
                using (ManagementObject ethernetSwitchSettings = WmiUtilities.GetFirstObjectFromCollection(
                           ethernetSwitch.GetRelated("Msvm_VirtualEthernetSwitchSettingData",
                                                     "Msvm_SettingsDefineState",
                                                     null, null, null, null, false, null)))
                {
                    //
                    // Modify its properties as desired.
                    //
                    ethernetSwitchSettings["ElementName"] = newSwitchName;
                    ethernetSwitchSettings["Notes"]       = new string[] { newNotes };

                    //
                    // This is how you can modify the IOV Preferred property from its current value.
                    // We leave this commented out because it could potentially fail for a system that doesn't
                    // support IOV.
                    //
                    // ethernetSwitchSettings["IOVPreferred"] = !((bool)ethernetSwitchSettings["IOVPreferred"]);

                    //
                    // Now call the ModifySystemSettings method to apply the changes.
                    //
                    using (ManagementObject switchService = NetworkingUtilities.GetEthernetSwitchManagementService(scope))
                        using (ManagementBaseObject inParams = switchService.GetMethodParameters("ModifySystemSettings"))
                        {
                            inParams["SystemSettings"] = ethernetSwitchSettings.GetText(TextFormat.WmiDtd20);

                            using (ManagementBaseObject outParams =
                                       switchService.InvokeMethod("ModifySystemSettings", inParams, null))
                            {
                                WmiUtilities.ValidateOutput(outParams, scope);
                            }
                        }
                }

            Console.WriteLine(string.Format(CultureInfo.CurrentCulture,
                                            "The switch '{0}' was renamed to '{1}' successfully.",
                                            existingSwitchName, newSwitchName));
        }
Ejemplo n.º 7
0
        private static void SetCompressedAttribute(string directory)
        {
            DirectoryInfo di = new DirectoryInfo(directory);
            string        nameWithForwardSlashes = di.FullName.Replace('\\', '/');
            var           objPath = $"Win32_Directory.Name='{nameWithForwardSlashes}'";

            using (ManagementObject dir = new ManagementObject(objPath))
            {
                ManagementBaseObject outParams = dir.InvokeMethod("Compress", null, null);
                uint ret = (uint)(outParams.Properties["ReturnValue"].Value);
            }
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Execute a WMI Method
 /// </summary>
 /// <param name="WMIClass"></param>
 /// <param name="Method"></param>
 /// <param name="inParams"></param>
 /// <returns></returns>
 static public ManagementBaseObject ExecuteMethod(ManagementObject WMIClass, string Method, ManagementBaseObject inParams)
 {
     if (WMIClass != null)
     {
         WMIClass.Get();
         return(WMIClass.InvokeMethod(Method, inParams, new InvokeMethodOptions()));
     }
     else
     {
         return(null);
     }
 }
 public void Delete()
 {
     // ReSharper disable once StringLiteralTypo
     using (var classInstance = new ManagementObject(@"\\.\root\cimv2", $"Win32_Service.Name='{ServiceName}'", null))
         using (var outParams = classInstance.InvokeMethod("Delete", null, null))
         {
             if ((outParams == null) || (Convert.ToInt32(outParams["ReturnValue"]) != 0))
             {
                 throw new ManagementException($"Failed to delete service to {ServiceName}");
             }
         }
 }
Ejemplo n.º 10
0
    static void ObjReady(object o1, ObjectReadyEventArgs args)
    {
        Console.WriteLine(args.NewObject["name"]);
        ManagementObject o = (ManagementObject)args.NewObject;

        if ("calc.exe".Equals(o["Name"].ToString().ToLower()))
        {
            Console.WriteLine("terminating");
            o.InvokeMethod("Terminate", new object[] { 0 });
            Console.WriteLine("done");
        }
    }
Ejemplo n.º 11
0
        // 停止指定的服务
        public string StartService(string serviceName)
        {
            string           strRst = null;
            ManagementObject mo     = this.managementClass.CreateInstance();

            mo.Path = new ManagementPath(this.strPath + ".Name=\"" + serviceName + "\"");
            if ((string)mo["State"] == "Stopped")//!(bool)mo["AcceptStop"]
            {
                mo.InvokeMethod("StartService", null);
            }
            return(strRst);
        }
 /// <summary>
 /// 启用指定网卡
 /// </summary>
 /// <param name="NetworkObject">网卡对象</param>
 /// <returns>执行状态</returns>
 public bool EnableNetwork(ManagementObject NetworkObject)
 {
     try
     {
         NetworkObject.InvokeMethod("Enable", null);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Ejemplo n.º 13
0
        MigrationServiceSettings(
            string sourceHost
            )
        {
            //
            // Get the service & service setting values.
            //

            ManagementScope scope = new ManagementScope(
                @"\\" + sourceHost + @"\root\virtualization\v2", null);

            using (ManagementObject service = GetVirtualMachineMigrationService(scope))
                using (ManagementObject serviceSettings = GetMigrationServiceSettings(service))
                {
                    Console.WriteLine("Currently active VM migrations: {0}",
                                      service["ActiveVirtualSystemMigrationCount"]);

                    Console.WriteLine("Currently active storage migrations: {0}",
                                      service["ActiveStorageMigrationCount"]);

                    Console.WriteLine("Maximum allowed concurrent Storage migrations: {0}",
                                      serviceSettings["MaximumActiveStorageMigration"]);

                    Console.WriteLine("Is VM migration allowed: {0}",
                                      serviceSettings["EnableVirtualSystemMigration"]);

                    Console.WriteLine("Maximum allowed concurrent VM migrations: {0}",
                                      serviceSettings["MaximumActiveVirtualSystemMigration"]);

                    Console.WriteLine("Maximum allowed concurrent Storage migrations: {0}",
                                      serviceSettings["MaximumActiveStorageMigration"]);

                    //
                    // Set new setting values.
                    //

                    serviceSettings["EnableVirtualSystemMigration"]        = true;
                    serviceSettings["MaximumActiveVirtualSystemMigration"] = 4;
                    serviceSettings["MaximumActiveStorageMigration"]       = 5;

                    // Perform service setting change.
                    using (ManagementBaseObject inParams = service.GetMethodParameters("ModifyServiceSettings"))
                    {
                        inParams["ServiceSettingData"] = serviceSettings.GetText(TextFormat.CimDtd20);

                        using (ManagementBaseObject outParams =
                                   service.InvokeMethod("ModifyServiceSettings", inParams, null))
                        {
                            WmiUtilities.ValidateOutput(outParams, scope);
                        }
                    }
                }
        }
Ejemplo n.º 14
0
 void set(bool enable)
 {
     try {
         ManagementObject     termserv = WmiBase.Singleton.Win32_TerminalServiceSetting;
         ManagementBaseObject mb       = termserv.GetMethodParameters("SetAllowTSConnections");
         mb["AllowTSConnections"] = (uint)(enable ? 1 : 0);
         termserv.InvokeMethod("SetAllowTSConnections", mb, null);
     }
     catch {
         wmisession.Log("Terminal Services not found");
     }
 }
Ejemplo n.º 15
0
        /// <summary>
        ///   Creates new virtual machine.
        /// </summary>
        /// <param name = "machineName">Name of the virtual machine to crate.</param>
        /// <param name = "machineFolder">Full path where virtual machine will be created.</param>
        /// <param name = "diskPath">Full path and name of disk image to use.</param>
        /// <param name = "networkAdapterName">Name of the network adapter to use.</param>
        /// <param name = "macAddress">MAC address</param>
        /// <param name = "memorySize">Memory size to use for new virtual machine.</param>
        /// <returns>The task</returns>
        public IVirtualTask CreateVirtualMachine(
            string machineName, string machineFolder, string diskPath, string networkAdapterName, string macAddress, int memorySize)
        {
            if (string.IsNullOrEmpty(machineName))
            {
                throw new ArgumentNullException("machineName");
            }
            if (string.IsNullOrEmpty(machineFolder))
            {
                throw new ArgumentNullException("machineFolder");
            }
            if (string.IsNullOrEmpty(diskPath))
            {
                throw new ArgumentNullException("diskPath");
            }

            using (ManagementObject newVm = FindVirtualMachine(machineName))
            {
                if (newVm != null)
                {
                    throw new ArgumentOutOfRangeException("machineName", machineName, "Virtual machine already exists.");
                }
            }

            using (ManagementObject virtualSystemService = Utility.GetServiceObject(managementScope, "Msvm_VirtualSystemManagementService"))
                using (ManagementBaseObject inParams = virtualSystemService.GetMethodParameters("DefineVirtualSystem"))
                {
                    inParams["ResourcesettingData"] = null;
                    inParams["Sourcesetting"]       = null;
                    inParams["SystemsettingData"]   = GetVirtualSystemGlobalSettingDataInstance(managementScope, machineName);

                    using (ManagementBaseObject outParams = virtualSystemService.InvokeMethod("DefineVirtualSystem", inParams, null))
                    {
                        if (outParams == null)
                        {
                            throw new ArgumentException("Could not execute creation of new virtual machine!");
                        }

                        if ((UInt32)outParams["ReturnValue"] == ReturnCode.Started)
                        {
                            NewTask(outParams, managementScope);
                        }

                        NewTask((UInt32)outParams["ReturnValue"]);
                    }
                }

            ManagementObject vm = Utility.GetTargetComputer(machineName, managementScope);

            AddVirtualHarddrive(managementScope, vm, diskPath);
            AddVirtualNetwork(machineName, networkAdapterName, macAddress);
            return(currentTask);
        }
Ejemplo n.º 16
0
        public static string getUserInfo(ManagementObject proc)
        {
            if (proc["ExecutablePath"] != null)
            {
                string[] OwnerInfo = new string[2];
                proc.InvokeMethod("GetOwner", (object[])OwnerInfo);

                return(OwnerInfo[0]);
            }

            return(null);
        }
        public bool Commit()
        {
            object [] p = new object[1];

            if (AutostartSCService() != cbStartAtBoot.Checked)
            {
                p[0] = (cbStartAtBoot.Checked ? "Automatic" : "Manual");

                try
                {
                    ManagementPath   mp     = new ManagementPath(@"Win32_Service.Name='" + svcName + "'");
                    ManagementObject svcMgr = new ManagementObject(mp);

                    String success = svcMgr.InvokeMethod("ChangeStartMode", p).ToString();

                    if (success != @"0")
                    {
                        MessageBox.Show("Service Manager returned error code " + success, "Logitech Media Server", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
                catch {
                    MessageBox.Show("Changing startup mode failed.", "Logitech Media Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            jsonRequest(new string[] { "pref", "libraryname", musicLibraryName.Text });

            if (musicFolderInput.Text != getPref("audiodir"))
            {
                jsonRequest(new string[] { "pref", "audiodir", musicFolderInput.Text });
            }

            if (playlistFolderInput.Text != getPref("playlistdir"))
            {
                jsonRequest(new string[] { "pref", "playlistdir", playlistFolderInput.Text });
            }

            if (snUsername.Text != getPref("sn_email") || (snPassword.Text != "" && snPassword.Text != snPasswordPlaceholder && snPassword.Text != getPref("sn_password_sha")))
            {
                JsonObject result = jsonRequest(new string[] { "setsncredentials", snUsername.Text, snPassword.Text });
                if (result != null && result["validated"].ToString() != "" && result["warning"].ToString() != "")
                {
                    if (result["validated"].ToString() == "0")
                    {
                        MessageBox.Show(result["warning"].ToString(), "mysqueezebox.com", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
            }

            jsonRequest(new string[] { "pref", "sn_disable_stats", snStatsOptions.SelectedIndex.ToString() });

            return(false);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Kill a process by ProcessID
        /// </summary>
        /// <param name="ProcessID"></param>
        /// <returns></returns>
        public int KillProcess(int ProcessID)
        {
            WMIProvider oProv = new WMIProvider(oWMIProvider.mScope.Clone());

            oProv.mScope.Path.NamespacePath       = @"root\cimv2";
            oProv.mScope.Options.EnablePrivileges = true;
            ManagementObject     MO       = oProv.GetObject("Win32_Process.Handle='" + ProcessID.ToString() + "'");
            ManagementBaseObject inParams = MO.GetMethodParameters("Terminate");
            ManagementBaseObject Res      = MO.InvokeMethod("Terminate", inParams, null);

            return(int.Parse(Res.GetPropertyValue("ReturnValue").ToString()));
        }
 public static void SetEnabled(bool enabled)
 {
     try
     {
         string objPath = string.Format("Win32_Service.Name='{0}'", SERVICE_NAME);
         using (var service = new ManagementObject(new ManagementPath(objPath)))
         {
             service.InvokeMethod("ChangeStartMode", new object[] { enabled ? "Automatic" : "Disabled" });
         }
     }
     catch (Exception e) { }
 }
        /// <summary>
        /// Enables a recieve loation
        /// </summary>
        /// <param name="name"></param>
        /// <param name="portName"></param>
        private static void EnableRecieveLocation(string name, string portName)
        {
            const string scopeFormat          = "root\\MicrosoftBizTalkServer";
            const string managementPathFormat = "MSBTS_ReceiveLocation.Name='{0}',ReceivePortName='{1}'";

            Trace.WriteLine("Starting recieve location: " + name);

            var managementPath = string.Format(managementPathFormat, name, portName);
            var classInstance  = new ManagementObject(scopeFormat, managementPath, null);

            classInstance.InvokeMethod("Enable", null, null);
        }
        /// <summary>
        /// Starts a send port
        /// </summary>
        /// <param name="name"></param>
        private static void StartSendPort(string name)
        {
            const string scopeFormat          = "root\\MicrosoftBizTalkServer";
            const string managementPathFormat = "MSBTS_SendPort.Name='{0}'";

            Trace.WriteLine("Starting send port: " + name);

            var managementPath = string.Format(managementPathFormat, name);
            var classInstance  = new ManagementObject(scopeFormat, managementPath, null);

            classInstance.InvokeMethod("Start", null, null);
        }
Ejemplo n.º 22
0
 /// <summary>
 /// 禁用网卡
 /// </summary>5
 /// <param name="netWorkName">网卡名</param>
 /// <returns></returns>
 public bool DisableNetWork(ManagementObject network)
 {
     try
     {
         network.InvokeMethod("Disable", null);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Ejemplo n.º 23
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);
        }
    }
Ejemplo n.º 24
0
 private bool ReStartAdapter(ManagementObject SelectedAdpt)
 {
     try
     {
         SelectedAdpt.InvokeMethod("Disable", null);
     }
     catch (ManagementException)//me
     {
         return(false);
     }
     //Thread.Sleep(100);
     try
     {
         SelectedAdpt.InvokeMethod("Enable", null);
     }
     catch (ManagementException)//me
     {
         return(false);
     }
     return(true);
 }
        /// <summary>
        /// Changes the state of the virtual server.
        /// </summary>
        /// <param name="virtualServer">Virtual server to affect.</param>
        /// <param name="state">State to change to (e.g. Start).</param>
        public void ChangeState(
            VirtualServer virtualServer,
            VirtualServerState state)
        {
            ManagementPath path = new ManagementPath();

            path.ClassName    = "IISWebServer";
            path.RelativePath = virtualServer.Path;
            ManagementObject site = new ManagementObject(
                WmiScope, path, null);

            switch (state)
            {
            case VirtualServerState.Start:
                try
                {
                    site.InvokeMethod("Start", null);
                }
                catch (COMException ex)
                {
                    throw new Exception(
                              "Unable to start the virtual server. Another " +
                              "virtual server may already be using the port " +
                              "configured for this virtual server.", ex);
                }
                break;

            case VirtualServerState.Stop:
                site.InvokeMethod("Stop", null);
                break;

            case VirtualServerState.Pause:
                site.InvokeMethod("Pause", null);
                break;

            case VirtualServerState.Continue:
                site.InvokeMethod("Continue", null);
                break;
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Shutdown the names guest VM
        /// </summary>
        /// <returns>True if succeeds</returns>
        private bool RequestShutdown()
        {
            // based on the sample at http://blogs.msdn.com/b/taylorb/archive/2008/05/21/hyper-v-wmi-using-powershell-part-4-and-negative-1.aspx
            var jobSuccesful = false;

            // Connect to the Remote Machines Management Scope
            ManagementScope scope = this.GetScope();

            // Get the msvm_computersystem for the given VM (Vista)
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, new ObjectQuery(string.Format(CultureInfo.InvariantCulture, "SELECT * FROM Msvm_ComputerSystem WHERE ElementName = '{0}'", this.VMName.Get(this.ActivityContext)))))
            {
                try
                {
                    // Select the first object in the Searcher collection
                    var enumr = searcher.Get().GetEnumerator();
                    enumr.MoveNext();
                    ManagementObject msvm_computersystem = (ManagementObject)enumr.Current;

                    // Use the association to get the msvm_shutdowncomponent for the msvm_computersystem
                    ManagementObjectCollection collection = msvm_computersystem.GetRelated("Msvm_ShutdownComponent");
                    ManagementObjectCollection.ManagementObjectEnumerator enumerator = collection.GetEnumerator();
                    enumerator.MoveNext();
                    ManagementObject msvm_shutdowncomponent = (ManagementObject)enumerator.Current;

                    // Get the InitiateShudown Parameters
                    ManagementBaseObject inParams = msvm_shutdowncomponent.GetMethodParameters("InitiateShutdown");
                    inParams["Force"]  = true;
                    inParams["Reason"] = "Need to Shutdown";

                    // Invoke the Method
                    ManagementBaseObject outParams = msvm_shutdowncomponent.InvokeMethod("InitiateShutdown", inParams, null);
                    uint returnValue = (uint)outParams["ReturnValue"];

                    // Zero indicates success
                    if (returnValue != 0)
                    {
                        this.LogBuildWarning(string.Format(CultureInfo.InvariantCulture, "SHUTDOWN of {0} Failed", this.VMName.Get(this.ActivityContext)));
                    }
                    else
                    {
                        this.LogBuildMessage(string.Format(CultureInfo.InvariantCulture, "{0} state was shutdown successfully.", this.VMName.Get(this.ActivityContext)));
                        jobSuccesful = true;
                    }
                }
                catch (InvalidOperationException ex)
                {
                    this.LogBuildWarning(string.Format(CultureInfo.InvariantCulture, "SHUTDOWN of {0} Failed due to {1}", this.VMName.Get(this.ActivityContext), ex.Message));
                }
            }

            return(jobSuccesful);
        }
Ejemplo n.º 27
0
        public string CreateVirtualSystemSnapshot(string vmName, vm_control vmctrl)
        {
            ManagementBaseObject result = null;
            string       ret            = "";
            const string Job            = "Job";
            const string JobState       = "JobState";


            if (scope == null)
            {
                scope = getRemoteScope();
            }

            ManagementObject virtualSystemService = Utility.GetServiceObject(scope, "Msvm_VirtualSystemManagementService");

            ManagementObject vm = Utility.GetTargetComputer(vmName, scope);

            ManagementBaseObject inParams = virtualSystemService.GetMethodParameters("CreateVirtualSystemSnapshot");

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

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

            if (Utility.JobCompleted(outParams, scope, vmctrl))
            {
                if ((UInt32)outParams["ReturnValue"] == ReturnCode.Started)
                {
                    if (Utility.JobCompleted(outParams, scope, null))
                    {
                        ret = ("Snapshot was created successfully.");
                    }
                    else
                    {
                        ret = ("Failed to create snapshot VM");
                    }
                }
                else if ((UInt32)outParams["ReturnValue"] == ReturnCode.Completed)
                {
                    ret = ("Snapshot was created successfully.");
                }
                else
                {
                    ret = String.Format("Create virtual system snapshot failed with error {0}", outParams["ReturnValue"].ToString());
                }
            }
            inParams.Dispose();
            outParams.Dispose();
            vm.Dispose();
            virtualSystemService.Dispose();

            return(ret);
        }
Ejemplo n.º 28
0
        public IVirtualTask ShutdownVirtualMachine(string machineName)
        {
            if (string.IsNullOrEmpty(machineName))
            {
                throw new ArgumentNullException("machineName");
            }
            ManagementObject vm = FindVirtualMachine(machineName);

            if (vm == null)
            {
                throw new ArgumentOutOfRangeException("machineName", "Virtual machine not found.");
            }

            var guid = (string)vm["Name"];

            var query = new ObjectQuery("SELECT * FROM Msvm_ShutdownComponent WHERE SystemName='" + guid + "'");

            using (var searcher = new ManagementObjectSearcher(managementScope, query))
            {
                ManagementObject component = null;
                using (ManagementObjectCollection queryCollection = searcher.Get())
                {
                    foreach (ManagementObject m in queryCollection)
                    {
                        component = m;
                        break;
                    }

                    if (component == null)
                    {
                        throw new ArgumentOutOfRangeException("machineName", "Shutdown component not found.");
                    }

                    using (ManagementBaseObject inParams = component.GetMethodParameters("InitiateShutdown"))
                    {
                        inParams["Force"]  = true;
                        inParams["Reason"] = "test";

                        using (
                            ManagementBaseObject outParams = component.InvokeMethod("InitiateShutdown", inParams, null))
                        {
                            if (outParams == null)
                            {
                                throw new ArgumentException("Error invoking WMI RequestStateChange method.");
                            }

                            return(NewTask((UInt32)outParams["ReturnValue"]));
                        }
                    }
                }
            }
        }
Ejemplo n.º 29
0
        public virtual string CreateSite(FtpSite site)
        {
            // create folder if nessesary
            //if(!Directory.Exists(site.ContentPath))
            //	Directory.CreateDirectory(site.ContentPath);

            // create anonymous user account if required
            // blah blah blah

            // set account permissions
            // blah blah blah

            // check server bindings
            CheckFtpServerBindings(site.Bindings);

            // create FTP site
            ManagementObject objService = wmi.GetObject(String.Format("IIsFtpService='{0}'", FTP_SERVICE_ID));

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

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

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

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

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

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

            // get FTP settings
            string siteId = ((string)objSite["returnValue"]).Remove(0, "IIsFtpServer='".Length).Replace("'", "");

            // update site properties
            ManagementObject objSettings = wmi.GetObject(
                String.Format("IIsFtpServerSetting='{0}'", siteId));

            FillWmiObjectFromFtpSite(objSettings, site);

            // start FTP site
            ChangeSiteState(siteId, ServerState.Started);
            return(siteId);
        }
Ejemplo n.º 30
0
        static private Int64 CreateMBRPartition(ManagementObject DiskToMess, UInt64?Size, MBRPartType Type, FileSystem FS, bool Active, string Label, out string Letter)
        {
            Letter = "";

            ManagementBaseObject CreParMethod = DiskToMess.GetMethodParameters("CreatePartition");

            CreParMethod["Alignment"]         = 4096;
            CreParMethod["AssignDriveLetter"] = true;
            CreParMethod["IsActive"]          = Active;

            CreParMethod["MbrType"] = (UInt16)Type;
            if (Size == null)
            {
                CreParMethod["UseMaximumSize"] = true;
            }
            else
            {
                CreParMethod["Size"] = Size.Value;
            }

            ManagementBaseObject Output = DiskToMess.InvokeMethod("CreatePartition", CreParMethod, null);

            if (Convert.ToInt64(Output["ReturnValue"]) != 0)
            {
                return(Convert.ToInt64(Output["ReturnValue"]));
            }

            ManagementBaseObject Partition = Output["CreatedPartition"] as ManagementBaseObject;
            string PartitionID             = Partition["UniqueId"].ToString();

            ManagementObject Volume = GetVolume(PartitionID);

            if (Volume == null)
            {
                return(3);
            }

            Letter = Convert.ToString(Volume["DriveLetter"]);

            if (FS != FileSystem.NoFormat)
            {
                OnUpdateStatus?.Invoke("Creating filesystem (" + FS.ToString() + ")");

                Int64 res = FormatVolume(Volume, Label, FS);
                if (res != 0)
                {
                    return(res);
                }
            }

            return(0);
        }
Ejemplo n.º 31
0
        private void ExecuteMethod()
        {
            string returnString = String.Empty;

            try
            {
                this.Cursor = Cursors.WaitCursor;
                SetStatusBar("Executing method...", MessageCategory.Action);

                ManagementBaseObject inParams = _mObject.GetMethodParameters(_method.Name);

                foreach (Control control in panelInParams.Controls)
                {
                    if (control is TextBox)
                    {
                        inParams[control.Tag.ToString()] = control.Text;
                    }

                    if (control is CheckBox)
                    {
                        inParams[control.Tag.ToString()] = ((CheckBox)control).Checked.ToString();
                    }
                }

                ManagementBaseObject outParams = _mObject.InvokeMethod(_method.Name, inParams, null);

                if (outParams != null && outParams.Properties.Count > 0)
                {
                    ManagementBaseObjectW outParamsW = new ManagementBaseObjectW(outParams);
                    propertyGridOutParams.SelectedObject = outParamsW;
                    _clipboardText = outParams.GetText(TextFormat.Mof).Replace("\n", "\r\n");
                    SetStatusBar("Successfully executed method.", MessageCategory.Info);
                }
                else
                {
                    SetStatusBar("Successfully executed method. No output parameters.", MessageCategory.Info);
                }

                returnString = "Successfully executed method " + _method.Name + " of object " + _mObject.Path.RelativePath;
            }
            catch (Exception ex)
            {
                SetStatusBar("Method Execution Failed. Error: " + ex.Message, MessageCategory.Error);
                returnString = "Failed to execute method " + _method.Name + " of object " + _mObject.Path.RelativePath + ". Error: " + ex.Message;
            }
            finally
            {
                WmiExplorer parentForm = (WmiExplorer)this.Owner;
                parentForm.Log(returnString);
                this.Cursor = Cursors.Default;
            }
        }
Ejemplo n.º 32
0
        public string[] MountVHD(out bool Status, string VHD, string ProxyVM = null, string AlternateInterface = null)
        {
            if (AlternateInterface != null && AlternateInterface != this.GetType().Name)
            {
                Type Plug = PluginLoader.FindType(AlternateInterface);
                if (Plug == null)
                {
                    PluginLoader.ScanForPlugins();
                    Plug = PluginLoader.FindType(AlternateInterface);
                }
                if (Plug != null)
                {
                    dynamic Alt = Activator.CreateInstance(Plug);
                    return(Alt.MountVHD(out Status, VHD, ProxyVM));
                }
                Status = false;
                return(null);
            }

            if (ProxyVM != null)
            {
                //TODO: Mount to VM, then report location (if possible?)
                throw new NotImplementedException();
            }

            string[] drv = GetMountPoints(VHD);
            if (drv != null && drv.Length > 0)
            {
                return((Status = true) ? drv : null);
            }

            ManagementObject SvcObj = Utility.GetServiceObject(Utility.GetScope(), Utility.ServiceNames.ImageManagement);
            var inputs = SvcObj.GetMethodParameters("Mount");

            inputs["Path"] = VHD;
//            int result = Utility.WaitForJob((ManagementObject)SvcObj.InvokeMethod("Mount", new object[] { VHD }));
            var result = SvcObj.InvokeMethod("Mount", inputs, null);

            switch (Int32.Parse(result["ReturnValue"].ToString()))
            {
            case (int)Utility.ReturnCodes.OK:
                var tmp = GetMountPoints(VHD);
                return((Status = tmp.Any()) ? tmp : null);

            case (int)Utility.ReturnCodes.JobStarted:
                return((Status = (Utility.WaitForJob(Utility.GetObject(result["Job"].ToString())) == 0)) ? GetMountPoints(VHD) : null);

            default:
                Status = false;
                return(null);
            }
        }
    /// <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;
    }
Ejemplo n.º 34
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);
        }
    }