Ejemplo n.º 1
1
        public bool CleanDirectory(DirectoryInfo dirInfo, string[] folderNames)
        {
            //get list of directories
            DirectoryInfo[] dirs = dirInfo.GetDirectories();

            //loop each
            foreach (DirectoryInfo dir in dirs)
            {
                bool istarget = false;
                foreach (string fname in folderNames)
                {
                    istarget = (dir.Name == fname);
                    if (istarget) break;
                }

                if (istarget)
                {
                    //dir.Attributes = FileAttributes.Normal;
                    //Directory.Delete(dir.FullName, true);
                    using (ManagementObject mo = new ManagementObject(String.Format("win32_Directory.Name='{0}'", dir.FullName)))
                    {
                        mo.Get();
                        ManagementBaseObject outParams = mo.InvokeMethod("Delete", null, null);
                        if (Convert.ToInt32(outParams.Properties["ReturnValue"].Value) != 0) return false;
                    }
                }
                else if (!CleanDirectory(dir, folderNames))
                    return false;
            }

            return true;
        }
Ejemplo n.º 2
0
        string strNS = "root\\CIMV2"; // WMI 類別 (Class)

        #endregion Fields

        #region Methods

        public void SetAuto()
        {
            // 建立 ManagementObject 物件 ( Scope , Path , options )
            objCls = new ManagementObject(strNS, strCls + ".INDEX=" + strIndex, null);
            // InvokeMethod 方法 : 在物件上叫用方法。
            objCls.InvokeMethod("EnableDHCP", null); // 設定自動取得 IP
            objCls.InvokeMethod("ReleaseDHCPLease", null); // 釋放 IP
            objCls.InvokeMethod("RenewDHCPLease", null); // 重新取得 IP
        }
 /// <summary>
 /// 设置服务与桌面交互,在serviceInstaller1的AfterInstall事件中使用
 /// </summary>
 /// <param name="serviceName">服务名称</param>
 private void SetServiceDesktopInsteract(string serviceName)
 {
     ManagementObject wmiService = new ManagementObject(string.Format("Win32_Service.Name='{0}'", serviceName));
     ManagementBaseObject changeMethod = wmiService.GetMethodParameters("Change");
     changeMethod["DesktopInteract"] = true;
     ManagementBaseObject utParam = wmiService.InvokeMethod("Change", changeMethod,null);
 }
Ejemplo n.º 4
0
        /// <summary>
        /// </summary>
        /// <param name="objz"></param>
        /// <param name="cmdTag"></param>
        /// <returns></returns>
        public static bool ChangeServiceStartMode(WmiServiceObj objz, string cmdTag)
        {
            bool bRel;
            var sc = new ServiceController(objz.Name);
            string startupType = "";

            var myPath = new ManagementPath
            {
                Server = Environment.MachineName,
                NamespacePath = @"root\CIMV2",
                RelativePath = string.Format("Win32_Service.Name='{0}'", sc.ServiceName)
            };
            switch (cmdTag)
            {
                case "41":
                    startupType = "Manual";
                    break;
                case "42":
                    startupType = "Auto";
                    break;
                case "43":
                    startupType = "Disabled";
                    break;
            }
            using (var service = new ManagementObject(myPath))
            {
                ManagementBaseObject inputArgs = service.GetMethodParameters("ChangeStartMode");
                inputArgs["startmode"] = startupType;
                service.InvokeMethod("ChangeStartMode", inputArgs, null);
                bRel = true;
            }

            sc.Refresh();
            return bRel;
        }
Ejemplo n.º 5
0
        public override void Install(System.Collections.IDictionary savedState)
        {
            try
            {
                base.Install(savedState);

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

                Service.Services.LoggingService.AddLogEntry(WOSI.CallButler.ManagementInterface.LogLevel.ErrorsOnly, Utils.ErrorUtils.FormatErrorString(e), true);
                CallButler.ExceptionManagement.ErrorCaptureUtils.SendError(e, licenseKey, licenseName, "");
            }
        }
Ejemplo n.º 6
0
        public static string DeleteAT(string srv, string JobID)
        {
            try
            {
                string strJobId = "";

                ManagementObject mo;
                ManagementPath path = ManagementPath.DefaultPath;
                path.RelativePath = "Win32_ScheduledJob.JobId=" + "\"" + JobID + "\"";
                path.Server = srv;
                mo = new ManagementObject(path);
                ManagementBaseObject inParams = null;
                // use late binding to invoke "Delete" method on "Win32_ScheduledJob" WMI class
                ManagementBaseObject outParams = mo.InvokeMethod("Delete", inParams, null);

                strJobId = outParams.Properties["ReturnValue"].Value.ToString();
                if (strJobId == "0") { return "O JobId ( " + JobID + " ) selecionado foi Apagado!"; }
                else { return "Out parameters: ReturnValue= " + strJobId; }
            }
            catch (UnauthorizedAccessException uex)
            {
                return "Ocorreu um erro: " + uex.Message;
            }
            catch (ManagementException mex)
            {
                return "Ocorreu um erro: " + mex.Message;
            }
        }
        public string SetHostname(string hostname)
        {
            var oldName = Environment.MachineName;
            _logger.Log("Old host name: " + oldName);
            _logger.Log("New host name: " + hostname);
            if (string.IsNullOrEmpty(hostname) || oldName.Equals(hostname, StringComparison.InvariantCultureIgnoreCase))
                return 0.ToString();

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

                var renameResult = Convert.ToString(outParams.Properties["ReturnValue"].Value);
                //Restart in 10 secs because we want finish current execution and write response back to Xenstore.
                if ("0".Equals(renameResult))
                    Process.Start(@"shutdown.exe", @"/r /t 10 /f /d p:2:4");
                return renameResult;
            }
        }
Ejemplo n.º 8
0
 private static void Win32_SharesSearcher()
 {
     SelectQuery query = new SelectQuery("select * from Win32_Share where Name=\"" + sharename + "\"");
     using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
     {
         foreach (ManagementObject mo in searcher.Get())
         {
             foreach (PropertyData prop in mo.Properties)
             {
                 form.textBox1.AppendText(prop.Name + " = " + mo[prop.Name] + Environment.NewLine);                    }
                 //form.textBox1.AppendText(string.Format("Win32ShareName: {0} Description {1} Path {2} ", mo.Properties["Name"].Value, mo.Properties["Description"].Value, mo.Properties["Path"].Value) + Environment.NewLine);
         }
     }
     ManagementObject winShareP = new ManagementObject("root\\CIMV2", "Win32_Share.Name=\"" + sharename + "\"", null);
     ManagementBaseObject outParams = winShareP.InvokeMethod("GetAccessMask", null, null);
     form.textBox1.AppendText(String.Format("access Mask = {0:x}", outParams["ReturnValue"]) + Environment.NewLine);
     ManagementBaseObject inParams = winShareP.GetMethodParameters("SetShareInfo");
     form.textBox1.AppendText("SetShareInfor in parameters" + Environment.NewLine);
     foreach (PropertyData prop in inParams.Properties)
     {
         form.textBox1.AppendText(String.Format("PROP = {0}, TYPE = {1} ", prop.Name, prop.Type.ToString()) + Environment.NewLine);
     }
     Object access = inParams.GetPropertyValue("Access");
     //Stopped development here because ShareAFolder project exists. The rest of the development is there
     //Maybe should copy Sahare a Folder content to here at some point
 }
Ejemplo n.º 9
0
        protected void addComputerToCollection(string resourceID, string collectionID)
        {
            /*  Set collection = SWbemServices.Get ("SMS_Collection.CollectionID=""" & CollID &"""")

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

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

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

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

            ManagementObject rule = ruleClass.CreateInstance();

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

            obj.InvokeMethod("AddMembershipRule", new object[] { rule });
        }
Ejemplo n.º 10
0
        protected override void OnCommitted(IDictionary savedState)
        {
            base.OnCommitted (savedState);

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

            #region Start the reflector service immediately
            try
            {
                ServiceController sc = new ServiceController("ConferenceXP Reflector Service");
                sc.Start();
            }
            catch (Exception ex)
            {
                // Don't except - that would cause a rollback.  Instead, just tell the user.
                RtlAwareMessageBox.Show(null, string.Format(CultureInfo.CurrentCulture, Strings.ServiceStartFailureText, 
                    ex.ToString()), Strings.ServiceStartFailureTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning, 
                    MessageBoxDefaultButton.Button1, (MessageBoxOptions)0);
            }
            #endregion
        }
Ejemplo n.º 11
0
 private static uint DecompressFolder(string path)
 {
     using (ManagementObject obj2 = new ManagementObject("Win32_Directory.Name=\"" + path.Replace(@"\", @"\\") + "\""))
     {
         return (uint)obj2.InvokeMethod("UnCompress", null, null).Properties["ReturnValue"].Value;
     }
 }
Ejemplo n.º 12
0
        public static void StartService(string service)
        {
            string msg = string.Format("starting up service begins: {0}", service);
            Singleton<ReportMediator>.UniqueInstance.ReportStatus(msg);
            string objPath = string.Format("Win32_Service.Name='{0}'", service);
            try
            {
                ConnectionOptions connectionOptions = new ConnectionOptions();
                connectionOptions.Authentication = AuthenticationLevel.Packet;
                connectionOptions.EnablePrivileges = true;
                connectionOptions.Username = Singleton<Constants>.UniqueInstance.UserName;
                connectionOptions.Password = Singleton<Constants>.UniqueInstance.PassWord;
                connectionOptions.Impersonation = ImpersonationLevel.Impersonate;

                ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", Singleton<Constants>.UniqueInstance.MachineName), connectionOptions);
                scope.Connect();
                using (ManagementObject serviceObj = new ManagementObject(scope, new ManagementPath(objPath), null))
                {
                    ManagementBaseObject outParams = serviceObj.InvokeMethod("StartService",
                        null, null);
                    uint returnValue = (uint)outParams["ReturnValue"];

                    msg = string.Format("starting up result for service {0} is {1}", service, returnValue);
                    Singleton<ReportMediator>.UniqueInstance.ReportStatus(msg, LogLevel.Warning);
                }
            }
            catch (Exception ex)
            {
                msg = string.Format("error starting up service: {0}, {1}", service, ex);
                Singleton<ReportMediator>.UniqueInstance.ReportStatus(msg, LogLevel.Warning);
            }
            msg = string.Format("starting up service ends: {0}", service);
            Singleton<ReportMediator>.UniqueInstance.ReportStatus(msg);
        }
Ejemplo n.º 13
0
 public void SetNetCfg(string strIP, string strSubmask, string strGateway, string strDNS1, string strDNS2)
 {
     // 建立 ManagementObject 物件 ( Scope , Path , options )
     objCls = new ManagementObject(strNS, strCls + ".INDEX=" + strIndex, null);
     ManagementBaseObject objInPara; // 宣告管理物件類別的基本類別
     objInPara = objCls.GetMethodParameters("EnableStatic");
     objInPara["IPAddress"] = new string[] { strIP }; // 設定 "IP" 屬性
     objInPara["SubnetMask"] = new string[] { strSubmask }; // 設定 "子網路遮罩" 屬性
     objCls.InvokeMethod("EnableStatic", objInPara, null);
     objInPara = objCls.GetMethodParameters("SetGateways");
     objInPara["DefaultIPGateway"] = new string[] { strGateway }; // 設定 "Gateway" 屬性
     objCls.InvokeMethod("SetGateways", objInPara, null);
     objInPara = objCls.GetMethodParameters("SetDNSServerSearchOrder");
     objInPara["DNSServerSearchOrder"] = new string[] { strDNS1, strDNS2 }; // 設定 "DNS" 屬性
     objCls.InvokeMethod("SetDNSServerSearchOrder", objInPara, null);
     // GetMethodParameters 方法 : 用來取得 SetDNSServerSearchOrder 參數清單。
     // InvokeMethod 方法 : 在物件上叫用方法。
 }
Ejemplo n.º 14
0
        private void SetServiceDesktopInsteract(string serviceName) {
            ConnectionOptions coOptions = new ConnectionOptions();
            coOptions.Impersonation = ImpersonationLevel.Impersonate;
            ManagementScope mgmtScope = new System.Management.ManagementScope(@"root\CIMV2", coOptions);
            mgmtScope.Connect();

            ManagementObject wmiService = new ManagementObject(string.Format("Win32_Service.Name='{0}'", serviceName));
            ManagementBaseObject changeMethod = wmiService.GetMethodParameters("Change");
            changeMethod["DesktopInteract"] = true;
            ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", changeMethod, null);
        }
Ejemplo n.º 15
0
        private void serviceInstaller1_Committed(object sender, InstallEventArgs e)
        {
            ConnectionOptions options = new ConnectionOptions();
            options.Impersonation = ImpersonationLevel.Impersonate;
            ManagementScope scope = new ManagementScope(@"root\CIMV2", options);
            scope.Connect();

            ManagementObject wmi = new ManagementObject("Win32_Service.Name='" + serviceInstaller1.ServiceName + "'");
            ManagementBaseObject inParam = wmi.GetMethodParameters("Change");
            inParam["DesktopInteract"] = true;
            ManagementBaseObject outParam = wmi.InvokeMethod("Change", inParam, null);
        }
Ejemplo n.º 16
0
        private void button2_Click(object sender, EventArgs e)
        {
            string AccountName = textBox1.Text,
                newNameForAccount = textBox2.Text;

            ManagementObject theInstance = new ManagementObject("root\\CIMv2", "Win32_UserAccount.Domain='" + Environment.MachineName + "',Name='" + AccountName + "'", null);

            ManagementBaseObject inputParams = theInstance.GetMethodParameters("Rename");
            inputParams.SetPropertyValue("Name", newNameForAccount);
            ManagementBaseObject outParams = theInstance.InvokeMethod("Rename", inputParams, null);
            button2.Hide();
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Delete the directory recursive... 
 /// 
 /// Works also if there are read-only files in the directories...
 /// </summary>
 /// <param name="currentDir"> The directory to delete. </param>
 public static void DeleteRecursive(string currentDir)
 {
     string dirName = @currentDir;
     string objPath = string.Format("Win32_Directory.Name='{0}'", dirName);
     using (ManagementObject dir = new ManagementObject(objPath))
     {
         ManagementBaseObject outParams = dir.InvokeMethod("Delete", null, null);
         uint ret = (uint)(outParams.Properties["ReturnValue"].Value);
         if (ret != 0)
             throw new IOException("DeleteRecursive failed with error code " + ret);
     }
 }
Ejemplo n.º 18
0
 private static void KillProcess(string user, ManagementObject managementObject, Func<int, bool> match) {
     var objects = new object[2];
     try {
         managementObject.InvokeMethod("GetOwner", objects);
         if (user == (string)objects[0]) {
             var pid = int.Parse(managementObject["ProcessId"].ToString());
             if (match(pid))
                 KillProcessAndChildren(pid);
         }
     }
     catch (ManagementException) {
     }
 }
        private void ResetWin32Adapter(ManagementObject win32NetworkAdapter)
        {
            try
            {
                win32NetworkAdapter.InvokeMethod("Disable", null);
                Thread.Sleep(5000);
            }
            catch (Exception e)
            {
                win32NetworkAdapter.InvokeMethod("Enable", null);
                Thread.Sleep(5000);
            }

            try
            {
                win32NetworkAdapter.InvokeMethod("Enable", null);
                Thread.Sleep(5000);
            }
            catch (Exception e)
            {

            }
        }
Ejemplo n.º 20
0
 public static void SetBrightness(int value)
 {
     ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"root\WMI", "SELECT * FROM WmiMonitorBrightness");
     string instance = "";
     foreach (ManagementObject queryObj in searcher.Get())
     {
         instance = queryObj.GetPropertyValue("InstanceName").ToString();
     }
     ManagementObject classInstance = new ManagementObject(@"root\WMI", @"WmiMonitorBrightnessMethods.InstanceName='" + instance + "'", null);
     ManagementBaseObject inParams = classInstance.GetMethodParameters("WmiSetBrightness");
     inParams["Brightness"] = value;
     inParams["Timeout"] = 5000;
     ManagementBaseObject outParams = classInstance.InvokeMethod("WmiSetBrightness", inParams, null);
 }
Ejemplo n.º 21
0
        public IisWebSite CreateWebSite(string serverComment, IEnumerable<IisWebSiteBindingDetails> bindings, string documentRoot)
        {
            var iis = new ManagementObject(scope, new ManagementPath("IIsWebService='W3SVC'"), null);

            ManagementBaseObject createNewSiteArgs = iis.GetMethodParameters("CreateNewSite");
            createNewSiteArgs["ServerComment"] = serverComment;
            createNewSiteArgs["ServerBindings"] = bindings.Select(b => CreateBinding(b)).ToArray();
            createNewSiteArgs["PathOfRootVirtualDir"] = documentRoot;

            var result = iis.InvokeMethod("CreateNewSite", createNewSiteArgs, null);

            var id = (string) result["ReturnValue"];
            return new IisWebSite(scope, id);
        }
Ejemplo n.º 22
0
        private void startToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string name = this.dataGridView1.Rows[this.dataGridView1.SelectedCells[0].RowIndex].Cells["Name"].Value.ToString();

            if (name != null && name != "")
            {
                System.Management.ManagementObject obj = FindWMIObject(name, "Name");
                if (obj != null)
                {
                    obj.InvokeMethod("StartService", null);
                    LoadServices(this.wmiServerCredentials1.Username, this.wmiServerCredentials1.Password, this.wmiServerCredentials1.SelectedServer);
                }
            }
        }
        public static uint SetComputerName(String Name)
        {
            uint ret;
            ManagementObject ob = new ManagementObject();
            using (ManagementObject wmiObject = new ManagementObject(new ManagementPath(String.Format("Win32_ComputerSystem.Name='{0}'", System.Environment.MachineName))))
            {
                ManagementBaseObject inputArgs = wmiObject.GetMethodParameters("Rename");
                inputArgs["Name"] = Name;

                ManagementBaseObject outParams = wmiObject.InvokeMethod("Rename", inputArgs, null);
                ret = (uint)(outParams.Properties["ReturnValue"].Value);
            }
            return ret;
        }
Ejemplo n.º 24
0
 protected override void OnAfterInstall(IDictionary savedState)
 {
     try
     {
         System.Management.ManagementObject myService = new System.Management.ManagementObject(
             string.Format("Win32_Service.Name='{0}'", this.serviceInstaller1.ServiceName));
         System.Management.ManagementBaseObject changeMethod = myService.GetMethodParameters("Change");
         changeMethod["DesktopInteract"] = true;
         System.Management.ManagementBaseObject OutParam = myService.InvokeMethod("Change", changeMethod, null);
     }
     catch (Exception)
     {
     }
     base.OnAfterInstall(savedState);
 }
Ejemplo n.º 25
0
 public bool AppPoolAction(string action)
 {
     bool bSuccess = false;
     _options.Authentication = AuthenticationLevel.PacketPrivacy;
     var scope = new ManagementScope(@"\\" + _sHost + "\\root\\MicrosoftIISv2", _options);
     try
     {
         scope.Connect();
         var path = new ManagementPath("IIsApplicationPool='W3SVC/AppPools/" + _sPoolName + "'");
         var pool = new ManagementObject(scope, path, null);
         switch (action.ToLower())
         {
             case "stop":
                 Console.Write("Stopping \"{0}\" on \"{1}\"...\n", _sPoolName, _sHost);
                 LogWriter.WriteLog(DateTime.Now, "Stopping " + _sPoolName + " on " + _sHost);
                 pool.InvokeMethod("Stop", new object[0]);
                 bSuccess = true;
                 Console.WriteLine("Stopping is done \n");
                 LogWriter.WriteLog(DateTime.Now, "Stopping is done on " + _sHost);
                 break;
             case "start":
                 Console.WriteLine("Starting \"{0}\" on \"{1}\"...\n", _sPoolName, _sHost);
                 LogWriter.WriteLog(DateTime.Now, "Starting " + _sPoolName + " on " + _sHost);
                 pool.InvokeMethod("Start", new object[0]);
                 bSuccess = true;
                 Console.WriteLine("Starting is done \n");
                 LogWriter.WriteLog(DateTime.Now, "Starting is done on" + _sHost);
                 break;
             case "recycle":
                 Console.WriteLine("Recycling \"{0}\" on \"{1}\"...\n", _sPoolName, _sHost);
                 LogWriter.WriteLog(DateTime.Now, "Recycling " + _sPoolName + " on " + _sHost);
                 pool.InvokeMethod("Recycle", new object[0]);
                 bSuccess = true;
                 Console.WriteLine("Recycling is done \n");
                 LogWriter.WriteLog(DateTime.Now, "Recycling is done on " + _sHost);
                 break;
             default:
                 Console.WriteLine("Incorrect operation. Operations can be start,stop,recyle");
                 LogWriter.WriteLog(DateTime.Now, "Incorrect operation. Operations can be is start,stop,recycle");
                 break;
         }
     }
     catch (Exception ex)
     {
         HostAccessExceptionHandler(ex);
     }
     return bSuccess;
 }
Ejemplo n.º 26
0
        public void AddProcess(ManagementObject mo)
        {
            string[] s = new string[2];
            mo.InvokeMethod("GetOwner", (object[])s);

            string ProcessOwner = s[0].ToString();
            string processName = (string)mo["Name"];

            //cbPsLists.Items.Add(processName + " " + ProcessOwner);
               // string s;
            processName = processName.Replace(".exe", "");
            bool added = _processList.Any(item => item.Contains(processName));
            if (!added)
            {
                _processList.Add(processName);
            }
        }
Ejemplo n.º 27
0
        private void serviceProcessInstaller1_Committed(object sender, InstallEventArgs e)
        {
            try
            {
                var service = new System.Management.ManagementObject(
                    String.Format("WIN32_Service.Name='{0}'", "ServiceTestAR"));
                try
                {
                    var paramList = new object[11];
                    paramList[5] = true;//We only need to set DesktopInteract parameter
                    var output = service.InvokeMethod("Change", paramList);
                    //if zero is returned then it means change is done.
                    logger(string.Format("FAILED with code {0}", output));

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

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

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

                //InParam["DesktopInteract"] = true;

                //ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", InParam, null);
            }
            catch (System.Exception ex)
            {
                logger(ex.ToString());
            }
        }
Ejemplo n.º 28
0
        public void AddVirtualDirectory()
        {
            var siteId = 1574596940;
            //            var siteId = 1;
            var dir = "iplayer";
            var name = String.Format(@"W3SVC/{0}/root/{1}", siteId, dir);

            var vDir = new ManagementClass(Scope, new ManagementPath("IIsWebVirtualDirSetting"), null).CreateInstance();
            vDir["Name"] = name;
            vDir["Path"] = @"C:\sites\iplayer";
            vDir.Put();

            var path = string.Format("IIsWebVirtualDir.Name='{0}'", name);
            var app = new ManagementObject(Scope, new ManagementPath(path), null);
            app.InvokeMethod("AppCreate2", new object[] { 2 });

            vDir["AppPoolId"] = "GipRegForm.Api";
            vDir["AppFriendlyName"] = "stuff";
            vDir.Put();
        }
Ejemplo n.º 29
0
 // add pc to domain
 public static bool addToDomain(string userName, string password, string domain)
 {
     using (ManagementObject wmiObject = new ManagementObject(new ManagementPath("Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'")))
     {
         try
         {
             ManagementBaseObject inParams = wmiObject.GetMethodParameters("JoinDomainorWorkgroup");
             inParams["Name"] = domain;
             inParams["Password"] = password;
             inParams["UserName"] = userName;
             inParams["FJoinOptions"] = 3;
             ManagementBaseObject outParams = wmiObject.InvokeMethod("JoinDomainOrWorkgroup", inParams, null);
             if (!outParams["ReturnValue"].ToString().Equals("0")) return false;
             return true;
         }
         catch
         {
             return false;
         }
     }
 }
Ejemplo n.º 30
0
        /// <summary>
        /// This will restart the Pocess
        /// </summary>
        /// <returns>This will return True if the Process is successfully restarted. If the Process isn't running, or if there was an error in restarting it then it will return False.</returns>
        public static bool RestartProcess(int PID)
        {
            string ProcessName = "";
            try
            {
                ManagementObject classInstance = new ManagementObject("root\\CIMV2", "Win32_Process.Handle='"+PID+"'", null);
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT Name FROM Win32_Process WHERE ProcessId =" + PID  + @"");

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    ProcessName = queryObj["Name"].ToString().Trim();
                }

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

                // Add the input parameters.

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

                // List outParams
                Console.WriteLine("Out parameters:");
                Console.WriteLine("ReturnValue: " + outParams["ReturnValue"]);
                if (int.Parse(outParams["ReturnValue"].ToString().Trim()) != 0)
                {
                    return false;
                }
                else
                {
                    return StartProcess(ProcessName);
                }
            }
            catch (ManagementException err)
            {
                Console.WriteLine("An error occurred while trying to execute the WMI method: " + err.Message);
                return false;
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// </summary>
        /// <param name="objz"></param>
        /// <param name="sMessage"></param>
        /// <returns></returns>
        public static bool DeleteService(WmiServiceObj objz, out string sMessage)
        {
            bool bRel;
            var sc = new ServiceController(objz.Name);

            var myPath = new ManagementPath
            {
                Server = Environment.MachineName,
                NamespacePath = @"root\CIMV2",
                RelativePath = string.Format("Win32_Service.Name='{0}'", sc.ServiceName)
            };

            using (var service = new ManagementObject(myPath))
            {
                ManagementBaseObject outParams = service.InvokeMethod("delete", null, null);
                sMessage = outParams["ReturnValue"].ToString();
                bRel = true;
            }

            sc.Refresh();
            return bRel;
        }
Ejemplo n.º 32
0
        public static bool SetMachineName(string Name)
        {
            String RegLocComputerName = @"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName";
            try
            {
                string compPath = "Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'";
                using (ManagementObject mo = new ManagementObject(new ManagementPath(compPath)))
                {
                    ManagementBaseObject inputArgs = mo.GetMethodParameters("Rename");
                    inputArgs["Name"] = Name;
                    ManagementBaseObject output = mo.InvokeMethod("Rename", inputArgs, null);
                    uint retValue = (uint)Convert.ChangeType(output.Properties["ReturnValue"].Value, typeof(uint));
                    if (retValue != 0)
                    {
                        LogHelper.WriteLog("Computer could not be changed due to unknown reason.");
                    }
                }

                RegistryKey ComputerName = Registry.LocalMachine.OpenSubKey(RegLocComputerName);
                if (ComputerName == null)
                {
                    LogHelper.WriteLog("Registry location '" + RegLocComputerName + "' is not readable.");
                }
                if (((String)ComputerName.GetValue("ComputerName")) != Name)
                {
                    LogHelper.WriteLog("The computer name was set by WMI but was not updated in the registry location: '" + RegLocComputerName + "'");
                }
                LogHelper.WriteLog("更改计算机名:"+Name);
                ComputerName.Close();
                ComputerName.Dispose();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("出现错误", ex);
                return false;
            }
            return true;
        }
Ejemplo n.º 33
0
        private int CancellaCartella(string path)
        {
            try
            {
                string dirObject = "Win32_Directory.Name='" + path + "'";
                using (ManagementObject managementObject = new ManagementObject(dirObject))
                {
                    managementObject.Get();
                    ManagementBaseObject outParams = managementObject.InvokeMethod("Delete", null, null);

                    // ReturnValue should be 0, else failure
                    if (Convert.ToInt32(outParams.Properties["ReturnValue"].Value) != 0)
                    {
                        Console.Write("Errore");
                    }
                }
                return 0;

            }
            catch (Exception ex)
            {
                return 1; throw ex;
            }
        }
Ejemplo n.º 34
0
        public override void Commit(IDictionary savedState)
        {
            MessageBox.Show("Iniciando configuración 1");
            try
            {
                var ServiceKeys = Microsoft.Win32.Registry
                                  .LocalMachine.OpenSubKey(String.Format(@"System\CurrentControlSet\Services\{0}", "DigitalSignService"), true);

                MessageBox.Show("Obteniendo la clave");

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

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

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

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

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

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

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

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

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

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

                var output = process.StandardOutput.ReadToEnd();

                MessageBox.Show(output);

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


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


                /*ConnectionOptions coOptions = new ConnectionOptions();
                 * coOptions.Impersonation = ImpersonationLevel.Impersonate;
                 * ManagementScope mgmtScope = new ManagementScope(@"root\CIMV2", coOptions);
                 * mgmtScope.Connect();
                 * ManagementObject wmiService;
                 * wmiService = new ManagementObject("Win32_Service.Name='DigitalSignService");
                 * ManagementBaseObject InParam = wmiService.GetMethodParameters("Change");
                 * InParam["DesktopInteract"] = true;
                 * ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", InParam, null);*/
            }
            catch (System.Exception exce)
            {
                MessageBox.Show(exce.Message);
                MessageBox.Show(exce.StackTrace);
                LogTransaction(exce.Message);
                LogTransaction(exce.StackTrace);
                throw exce;
            }
        }