Example #1
0
        /// <summary>
        /// Updates site
        /// </summary>
        /// <param name="siteId"></param>
        /// <param name="contentPath"></param>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="host"></param>
        /// <param name="aspNet">ASP.NET version</param>
        internal static void UpdateSite(string siteId, string contentPath, string ip, string port, string host,
                                        AspNetVersion aspNet)
        {
            ManagementObject objSite    = wmi.GetObject(String.Format("IIsWebServerSetting='{0}'", siteId));
            ManagementObject objVirtDir = wmi.GetObject(
                String.Format("IIsWebVirtualDirSetting='{0}'", GetVirtualDirectoryPath(siteId, "")));

            // check if we need to add a server binding
            string existSiteId = GetSiteIdByBinding(ip, port, host);

            if (existSiteId == null)
            {
                // binding doesn't exist
                // add the binding to the web site
                ManagementBaseObject[] objProbBindings = (ManagementBaseObject[])objSite.Properties["ServerBindings"].Value;
                ManagementClass        clsBinding      = wmi.GetClass("ServerBinding");
                ManagementObject[]     newBindings     = new ManagementObject[objProbBindings.Length + 1];
                // copy existing bindings
                for (int i = 0; i < objProbBindings.Length; i++)
                {
                    newBindings[i]             = clsBinding.CreateInstance();
                    newBindings[i]["Hostname"] = (string)objProbBindings[i].Properties["Hostname"].Value;
                    newBindings[i]["IP"]       = (string)objProbBindings[i].Properties["IP"].Value;
                    newBindings[i]["Port"]     = (string)objProbBindings[i].Properties["Port"].Value;
                }
                //create new binding
                newBindings[objProbBindings.Length]             = clsBinding.CreateInstance();
                newBindings[objProbBindings.Length]["Hostname"] = host;
                newBindings[objProbBindings.Length]["IP"]       = ip;
                newBindings[objProbBindings.Length]["Port"]     = port;

                objSite.Properties["ServerBindings"].Value = newBindings;
            }
            objSite.Put();

            // set path
            if (!String.IsNullOrEmpty(contentPath))
            {
                // set content path
                objVirtDir.Properties["Path"].Value = contentPath;

                // set correct default documents
                SetVirtualDirectoryDefaultDocs(objVirtDir);
            }

            // set ASP.NET
            SetVirtualDirectoryAspNetMappings(objVirtDir, aspNet);

            // save object
            objVirtDir.Put();
        }
        /// <summary>
        /// The execute method
        /// </summary>
        /// <returns></returns>
        public override bool Execute()
        {
            try
            {
                var options = new PutOptions {
                    Type = PutType.CreateOnly
                };

                var handlerManagementClass = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_SendHandler2", null);

                foreach (var handler in
                         handlerManagementClass.GetInstances().Cast <ManagementObject>().Where(handler => (string)handler["AdapterName"] == AdapterName && (string)handler["HostName"] == HostName))
                {
                    handler.Delete();
                }

                var handlerInstance = handlerManagementClass.CreateInstance();
                if (handlerInstance != null)
                {
                    handlerInstance["AdapterName"] = AdapterName;
                    handlerInstance["HostName"]    = HostName;
                    handlerInstance.Put(options);
                }

                return(true);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(GetType().FullName, ex.ToString());
                throw;
            }
        }
Example #3
0
 /*
  * /// <summary>
  * /// Performs a network scan for BSSIDs.
  * /// </summary>
  * /// <param name="adapter">object representing</param>
  * public void ScanBssidList(NetworkInterface adapter) {
  *  IntPtr deviceHandle = OpenDevice(adapter.Id);
  *  try {
  *      // dummy reference variable
  *      int bytesReturned = new int();
  *      // tell the driver to scan the networks
  *      bool success = QueryGlobalStats(
  *                              deviceHandle,
  *                              Oid.Oid80211BssidListScan,
  *                              IntPtr.Zero,
  *                              0,
  *                              ref bytesReturned
  *                          );
  *      if (success) {
  *          // Nothing to do
  *      }
  *  }
  *  finally {
  *      CloseHandle(deviceHandle);
  *  }
  * } */
 // End ScanBssidList()
 /// <summary>
 /// Initiates a discovery scan of the available wireless networkds.
 /// </summary>
 public bool Scan(NetworkInterface adapter)
 {
     try
     {
         ManagementClass  mc = new ManagementClass("root\\WMI", "MSNDis_80211_BssIdListScan", null);
         ManagementObject mo = mc.CreateInstance();
         if (mo != null)
         {
             mo["Active"]          = true;
             mo["InstanceName"]    = adapter.Description; //.Replace(" - Packet Scheduler Miniport","");
             mo["UnusedParameter"] = 1;
             mo.Put();
         }
     }
     catch (ManagementException ex)
     {
         if (ex.ErrorCode == ManagementStatus.NotSupported)
         {
             //The operation is not supported, probably not an WiFi adapter.
             return(false);
         }
     }
     catch
     {
         // TODO: Verify root cause of exception.
         // Ignore, for now
         // there seems to be some issues with WMI on certain systems. Various exceptions have been
         // reported from this method, which relate to problems with WMI.
     }
     return(true);
 }
Example #4
0
        /// <summary>
        /// 读取权限实体
        /// </summary>
        /// <param name="name">用户/组名称</param>
        /// <param name="accessLevel">访问权限</param>
        /// <returns></returns>
        private static ManagementObject GetPermissionObject(string name, AccessLevel accessLevel)
        {
            var entryClass = new ManagementClass("root\\VisualSVN",
                                                 "VisualSVN_PermissionEntry", null);
            ManagementObject entry = entryClass.CreateInstance();
            ManagementClass  accountClass;

            if (entry != null)
            {
                try
                { // 先根据组进行权限设置
                    List <ManagementBaseObject> list = GetGroupMembersObject(name);
                    accountClass = new ManagementClass("root\\VisualSVN",
                                                       "VisualSVN_Group", null);
                }
                catch (Exception ex)
                { // 组不存在,就找用户
                    accountClass = new ManagementClass("root\\VisualSVN",
                                                       "VisualSVN_User", null);
                }
                ManagementObject account = accountClass.CreateInstance();
                if (account != null)
                {
                    account["Name"] = name;
                }
                entry["Account"]     = account;
                entry["AccessLevel"] = accessLevel;
            }
            return(entry);
        }
Example #5
0
        public static ServerHost CreateInstance(string pServer, string pUserName, string pPassword, string pDomain)
        {
            ManagementScope mgmtScope;

            if (_statMgmtScope == null)
            {
                mgmtScope = new ManagementScope
                {
                    Path    = { NamespacePath = "\\\\" + pServer + "\\" + CreatedWmiNamespace },
                    Options = new ConnectionOptions
                    {
                        Username  = pUserName,
                        Password  = pPassword,
                        Authority = "ntlmdomain:" + pDomain
                    }
                };
            }
            else
            {
                mgmtScope = _statMgmtScope;
            }
            ManagementPath mgmtPath = new ManagementPath(CreatedClassName);

            using (ManagementClass tmpMgmtClass = new ManagementClass(mgmtScope, mgmtPath, null))
            {
                return(new ServerHost(tmpMgmtClass.CreateInstance()));
            }
        }
        public async Task <object> AddCardHolder(AddCardHolder_DTO newCardHolder, string path, string user, string password)
        {
            ManagementScope cardHolderScope = _dataConduITMgr.GetManagementScope(path, user, password);

            ManagementClass cardHolderClass = new ManagementClass(cardHolderScope, new ManagementPath("Lnl_Cardholder"), null);

            ManagementObject newCardHolderInstance = cardHolderClass.CreateInstance();

            newCardHolderInstance["FIRSTNAME"] = newCardHolder.firstName;
            newCardHolderInstance["LASTNAME"]  = newCardHolder.lastName;
            newCardHolderInstance["DEPT"]      = newCardHolder.city;
            newCardHolderInstance["OPHONE"]    = newCardHolder.nroDocumento;
            newCardHolderInstance["SSNO"]      = newCardHolder.ssno;
            newCardHolderInstance["TITLE"]     = newCardHolder.empresa;
            newCardHolderInstance["BUILDING"]  = newCardHolder.instalacion;
            newCardHolderInstance["FLOOR"]     = newCardHolder.piso;
            newCardHolderInstance["DIVISION"]  = newCardHolder.area;
            newCardHolderInstance["EMAIL"]     = newCardHolder.email;


            PutOptions options = new PutOptions();

            options.Type = PutType.CreateOnly;

            //SE REALIZA COMMIT DE LA INSTANCIA
            newCardHolderInstance.Put(options);

            return(true);
        }
        CreateCopyFileToGuestSettingData(
            ManagementScope scope,
            string sourceFileNamePath,
            string destinationFileNamePath,
            bool overwriteExisting,
            bool createFullPath)
        {
            ManagementObject wmiCopyFileToGuestSettingData;

            //
            // Get an instance of the Msvm_CopyFileToGuestSettingData object.
            //

            ManagementPath settingDataPath =
                new ManagementPath("Msvm_CopyFileToGuestSettingData");

            ManagementClass copyFileToGuestSettingDataClass =
                new ManagementClass(
                    scope,
                    settingDataPath,
                    null);

            wmiCopyFileToGuestSettingData = copyFileToGuestSettingDataClass.CreateInstance();

            //
            // Set the values and return the WMI string representation.
            //

            wmiCopyFileToGuestSettingData["SourcePath"]        = sourceFileNamePath;
            wmiCopyFileToGuestSettingData["DestinationPath"]   = destinationFileNamePath;
            wmiCopyFileToGuestSettingData["OverwriteExisting"] = overwriteExisting;
            wmiCopyFileToGuestSettingData["CreateFullPath"]    = createFullPath;

            return(wmiCopyFileToGuestSettingData);
        }
Example #8
0
        public static int Main(string[] args)
        {
            try {
                ManagementClass existingClass = new ManagementClass("root/default:TestCreateInstance");
                existingClass.Delete();
            } catch {}

            ManagementClass newClass = new ManagementClass("root/default", "", null);

            newClass["__CLASS"] = "TestCreateInstance";

            newClass.Properties.Add("MyKey", CIMType.Uint32, false);
            newClass.Properties["mykey"].Qualifiers.Add("key", true);
            newClass.Put();

            ManagementObject newInstance = newClass.CreateInstance();

            newInstance["MyKey"] = 22;
            ManagementPath newPath = newInstance.Put();

            Console.WriteLine(newPath.Path);

            ManagementObject getInstance = new ManagementObject("root/default:TestCreateInstance=22");

            Console.WriteLine(getInstance["__RELPATH"]);
            return(0);
        }
Example #9
0
        public static void AddVirtualFolder(string serverName, string websiteId, string name, string path)
        {
            ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\root\MicrosoftIISV2", serverName));

            scope.Connect();

            string siteName = string.Format("W3SVC/{0}/Root/{1}", websiteId, name);

            ManagementClass  mc          = new ManagementClass(scope, new ManagementPath("IIsWebVirtualDirSetting"), null);
            ManagementObject oWebVirtDir = mc.CreateInstance();

            oWebVirtDir.Properties["Name"].Value             = siteName;
            oWebVirtDir.Properties["Path"].Value             = path;
            oWebVirtDir.Properties["AuthFlags"].Value        = 5; // Integrated Windows Auth.
            oWebVirtDir.Properties["EnableDefaultDoc"].Value = true;
            // date, time, size, extension, longdate ;
            oWebVirtDir.Properties["DirBrowseFlags"].Value = 0x4000003E;
            oWebVirtDir.Properties["AccessFlags"].Value    = 513; // read script
            oWebVirtDir.Put();

            ManagementObject mo = new ManagementObject(scope,
                                                       new System.Management.ManagementPath("IIsWebVirtualDir='" +
                                                                                            siteName + "'"), null);
            ManagementBaseObject inputParameters = mo.GetMethodParameters("AppCreate2");

            inputParameters["AppMode"] = 2;
            mo.InvokeMethod("AppCreate2", inputParameters, null);
            mo = new ManagementObject(scope, new System.Management.ManagementPath(
                                          "IIsWebVirtualDirSetting='" + siteName + "'"), null);
            mo.Properties["AppFriendlyName"].Value = name;
            mo.Put();
        }
Example #10
0
        private void CreateOrUpdate()
        {
            PutOptions options = new PutOptions {
                Type = PutType.UpdateOrCreate
            };

            using (ManagementClass instance = new ManagementClass(this.Scope, new ManagementPath("MSBTS_AdapterSetting"), null))
            {
                ManagementObject btsHostSetting = instance.CreateInstance();
                if (btsHostSetting == null)
                {
                    Log.LogError("There was a failure creating the MSBTS_AdapterSetting instance");
                    return;
                }

                btsHostSetting["Name"]      = this.AdaptorName;
                btsHostSetting["Comment"]   = this.Comment ?? string.Empty;
                btsHostSetting["MgmtCLSID"] = this.MgmtCLSID;

                if (this.Constraints > 0)
                {
                    btsHostSetting["Constraints"] = Convert.ToUInt32(this.Constraints);
                }

                btsHostSetting.Put(options);
                this.explorer.SaveChanges();
            }
        }
        private void registerAdapterInBizTalk()
        {
            try
            {
                PutOptions options = new PutOptions();
                options.Type = PutType.CreateOnly;

                //create a ManagementClass object and spawn a ManagementObject instance
                ManagementClass  newAdapterClass  = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_AdapterSetting", null);
                ManagementObject newAdapterObject = newAdapterClass.CreateInstance();

                //set the properties for the Managementobject
                newAdapterObject["Name"]        = "LoopBack";
                newAdapterObject["Comment"]     = "Bounce a message back to the message box through a solicit-response send port.";
                newAdapterObject["Constraints"] = "9482";                                   //see the registry file!!
                newAdapterObject["MgmtCLSID"]   = "{D44A2A6E-3B4F-452A-8007-CAB27D2D0B95}"; //see the registry file!!

                //create the Managementobject
                newAdapterObject.Put(options);
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("LoopBackAdapterInstaller", "Unable to register adapter in BizTalk: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }
Example #12
0
        private bool CreatePrinter()
        {
            try
            {
                var printerClass = new ManagementClass(managementScope, new ManagementPath("Win32_Printer"), new ObjectGetOptions());
                printerClass.Get();
                var printer = printerClass.CreateInstance();
                printer.SetPropertyValue("DriverName", appsettings.DriverName);
                printer.SetPropertyValue("PortName", appsettings.PrinterIP);
                //printer.SetPropertyValue("DisplayName", appsettings.PrinterName);
                printer.SetPropertyValue("Name", appsettings.PrinterName);
                printer.SetPropertyValue("DeviceID", appsettings.PrinterName);
                printer.SetPropertyValue("Location", "Office");
                printer.SetPropertyValue("Network", true);
                printer.SetPropertyValue("Shared", false);
                printer.Put();
                printer.InvokeMethod("SetDefaultPrinter", null);
                printer.InvokeMethod("PrintTestPage", null);

                ok = true;
                return(true);
            }
            catch (ManagementException ex)
            {
                return(false);
            }
        }
        private void CreateHandler(string hostName, string serverName, string adapterName, HandlerType handlerType)
        {
            string handler = handlerType == HandlerType.Receive ? "MSBTS_ReceiveHandler" : "MSBTS_SendHandler2";

            try
            {
                PutOptions options = new PutOptions();
                options.Type = PutType.CreateOnly;

                //create a ManagementClass object and spawn a ManagementObject instance
                ManagementClass  objReceiveHandlerClass = new ManagementClass(string.Format(BIZTALKSCOPE, serverName), handler, null);
                ManagementObject objReceiveHandler      = objReceiveHandlerClass.CreateInstance();

                //set the properties for the Managementobject
                objReceiveHandler["AdapterName"] = adapterName;
                objReceiveHandler["HostName"]    = hostName;

                //create the Managementobject
                objReceiveHandler.Put(options);
                System.Console.WriteLine("ReceiveHandler - " + adapterName + " " + hostName + " - has been created successfully");
            }
            catch (Exception excep)
            {
                throw new ApplicationException("Failed while creating receive handler", excep);
            }
        }
Example #14
0
        public virtual void UpdateSite(FtpSite site)
        {
            // check server bindings
            CheckFtpServerBindings(site.Bindings);

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

            FillWmiObjectFromFtpSite(objSettings, site);

            // update 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;
            }

            objSettings.Properties["ServerBindings"].Value = objBinings;

            // save object
            objSettings.Put();
        }
Example #15
0
        /// <summary>
        /// The execute method
        /// </summary>
        /// <returns></returns>
        public override bool  Execute()
        {
            try
            {
                var options = new PutOptions {
                    Type = PutType.CreateOnly
                };

                using (var recieveHandlerManagementClass = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_ReceiveHandler", null))
                {
                    foreach (var recieveHandler in
                             recieveHandlerManagementClass.GetInstances().Cast <ManagementObject>().Where(recieveHandler => (string)recieveHandler["AdapterName"] == AdapterName && (string)recieveHandler["HostName"] == HostName))
                    {
                        recieveHandler.Delete();
                    }

                    using (var recieveHandlerManager = recieveHandlerManagementClass.CreateInstance())
                    {
                        if (recieveHandlerManager != null)
                        {
                            recieveHandlerManager["AdapterName"] = AdapterName;
                            recieveHandlerManager["HostName"]    = HostName;
                            recieveHandlerManager.Put(options);
                        }
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry(GetType().FullName, ex.ToString());
                throw;
            }
        }
Example #16
0
        GetSettingsForPool(
            ManagementScope scope,
            string poolId,
            string notes
            )
        {
            using (ManagementClass rpsdClass = new ManagementClass("Msvm_ResourcePoolSettingData"))
            {
                rpsdClass.Scope = scope;
                using (ManagementObject rpsdInstance = rpsdClass.CreateInstance())
                {
                    rpsdInstance["ResourceType"]      = FcConnectionResourceType;
                    rpsdInstance["ResourceSubType"]   = FcConnectionResourceSubType;
                    rpsdInstance["OtherResourceType"] = string.Empty;
                    rpsdInstance["PoolId"]            = poolId;
                    if (notes != null)
                    {
                        rpsdInstance["Notes"] = notes;
                    }
                    rpsdInstance["ElementName"] = @"Friendly name for virtual SAN - " + poolId;

                    string rpsdString = rpsdInstance.GetText(TextFormat.WmiDtd20);
                    return(rpsdString);
                }
            }
        }
Example #17
0
        GetNewPoolAllocationSettings(
            ManagementScope scope,
            string poolId,
            string[] hostResources
            )
        {
            using (ManagementClass rasdClass = new ManagementClass("Msvm_ResourceAllocationSettingData"))
            {
                rasdClass.Scope = scope;

                using (ManagementObject rasdInstance = rasdClass.CreateInstance())
                {
                    rasdInstance["ResourceType"]      = FcConnectionResourceType;
                    rasdInstance["ResourceSubType"]   = FcConnectionResourceSubType;
                    rasdInstance["OtherResourceType"] = string.Empty;

                    rasdInstance["PoolId"]       = poolId;
                    rasdInstance["HostResource"] = hostResources;

                    string rasdString = rasdInstance.GetText(TextFormat.WmiDtd20);

                    return(rasdString);
                }
            }
        }
        /// <summary>
        /// 设置用户隶属用户组
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="groupName"></param>
        /// <returns></returns>
        public static bool AddMemberToGroup(string userName, string groupName)
        {
            try
            {
                var svn = new ManagementClass("root\\VisualSVN", "VisualSVN_Group", null);
                ManagementObject instance = svn.CreateInstance();

                instance.SetPropertyValue("Name", groupName);                                //  过滤组名
                ManagementBaseObject setMember = instance.GetMethodParameters("SetMembers"); //获取 SetMembers 方法

                List <ManagementObject> Member = GetGroupUsersArr(groupName);

                // 添加本次新用户
                Member.Add(new ManagementObject("root\\VisualSVN", string.Format("VisualSVN_User.Name='{0}'", userName), null));

                setMember["Members"] = Member.ToArray();

                instance.InvokeMethod("SetMembers", setMember, null);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        GetSettingsForPool(
            ManagementScope scope,
            string resourceType,
            string resourceSubType,
            string poolId,
            string poolName)
        {
            using (ManagementClass rpsdClass = new ManagementClass("Msvm_ResourcePoolSettingData"))
            {
                rpsdClass.Scope = scope;

                using (ManagementObject rpsdMob = rpsdClass.CreateInstance())
                {
                    rpsdMob["ResourceType"] = resourceType;

                    if (resourceType == "1")
                    {
                        rpsdMob["OtherResourceType"] = resourceSubType;
                        rpsdMob["ResourceSubType"]   = string.Empty;
                    }
                    else
                    {
                        rpsdMob["OtherResourceType"] = string.Empty;
                        rpsdMob["ResourceSubType"]   = resourceSubType;
                    }

                    rpsdMob["PoolId"]      = poolId;
                    rpsdMob["ElementName"] = poolName;

                    string rpsdString = rpsdMob.GetText(TextFormat.WmiDtd20);

                    return(rpsdString);
                }
            }
        }
Example #20
0
        private void registerAdapterInBizTalk()
        {
            try
            {
                PutOptions options = new PutOptions();
                options.Type = PutType.CreateOnly;

                //create a ManagementClass object and spawn a ManagementObject instance
                ManagementClass  newAdapterClass  = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_AdapterSetting", null);
                ManagementObject newAdapterObject = newAdapterClass.CreateInstance();

                //set the properties for the Managementobject
                newAdapterObject["Name"]        = "NULL";
                newAdapterObject["Comment"]     = "Discard BizTalk messages.";
                newAdapterObject["Constraints"] = "8210";                                   //see the registry file!!
                newAdapterObject["MgmtCLSID"]   = "{C98D3C74-F722-4F50-8AFC-4C2A9CB1D961}"; //see the registry file!!

                //create the Managementobject
                newAdapterObject.Put(options);
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("NullAdapterInstaller", "Unable to register adapter in BizTalk: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }
        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);

            obj.Scope = new ManagementScope(pathString, SCCM.GetConnectionOptions());

            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 });
        }
        GetVirtualHardDiskSettingDataEmbeddedInstance(
            string serverName,
            string namespacePath)
        {
            ManagementPath path = new ManagementPath()
            {
                Server        = serverName,
                NamespacePath = namespacePath,
                ClassName     = "Msvm_VirtualHardDiskSettingData"
            };

            using (ManagementClass settingsClass = new ManagementClass(path))
            {
                using (ManagementObject settingsInstance = settingsClass.CreateInstance())
                {
                    settingsInstance["Type"]               = m_DiskType;
                    settingsInstance["Format"]             = m_DiskFormat;
                    settingsInstance["Path"]               = m_Path;
                    settingsInstance["ParentPath"]         = m_ParentPath;
                    settingsInstance["MaxInternalSize"]    = m_MaxInternalSize;
                    settingsInstance["BlockSize"]          = m_BlockSize;
                    settingsInstance["LogicalSectorSize"]  = m_LogicalSectorSize;
                    settingsInstance["PhysicalSectorSize"] = m_PhysicalSectorSize;

                    string settingsInstanceString = settingsInstance.GetText(TextFormat.WmiDtd20);

                    return(settingsInstanceString);
                }
            }
        }
Example #23
0
        private static ManagementObject CreateEventFilter(string EventName, EventFilter EventFilter, string ProcessName)
        {
            ManagementObject _EventFilter = null;

            try
            {
                ManagementScope scope          = new ManagementScope(@"\\.\root\subscription");
                ManagementClass wmiEventFilter = new ManagementClass(scope, new ManagementPath("__EventFilter"), null);

                string query = string.Empty;
                if (EventFilter == EventFilter.ProcessStart)
                {
                    query = $@"SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName='{ProcessName}'";
                }

                WqlEventQuery wql = new WqlEventQuery(query);
                _EventFilter                   = wmiEventFilter.CreateInstance();
                _EventFilter["Name"]           = EventName;
                _EventFilter["Query"]          = wql.QueryString;
                _EventFilter["QueryLanguage"]  = wql.QueryLanguage;
                _EventFilter["EventNameSpace"] = @"root/cimv2";
                _EventFilter.Put();
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
            }
            return(_EventFilter);
        }
Example #24
0
        private bool CreatePrinterPort()
        {
            try
            {
                if (CheckPrinterPort())
                {
                    MessageBox.Show("Port already exists!");
                    return(true);
                }
                var printerPortClass = new ManagementClass(managementScope, new ManagementPath("Win32_TCPIPPrinterPort"), new ObjectGetOptions());
                printerPortClass.Get();
                var newPrinterPort = printerPortClass.CreateInstance();
                newPrinterPort.SetPropertyValue("Name", textBoxhostaddress.Text);
                if (radioraw.Checked)
                {
                    newPrinterPort.SetPropertyValue("Protocol", 1);
                }
                else if (radiolpr.Checked)
                {
                    newPrinterPort.SetPropertyValue("Protocol", 2);
                }
                newPrinterPort.SetPropertyValue("HostAddress", textBoxhostaddress.Text);
                newPrinterPort.SetPropertyValue("PortNumber", textBoxportno.Text); // default=9100
                newPrinterPort.SetPropertyValue("SNMPEnabled", false);             // true?
                newPrinterPort.SetPropertyValue("Queue", textBoxqname.Text);

                newPrinterPort.Put();
                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Create Printer Port FAILED");
                return(false);
            }
        }
Example #25
0
        private bool ActService(string name, ServiceActionType action)
        {
            var mo = _managementClass.CreateInstance();

            mo.Path = new ManagementPath(_actionPath + ".Name=\"" + name + "\"");
            mo.InvokeMethod(action.ToString(), null);
            return(true);
        }
        ///////////////////////////////////////////
        // Functions that create instances for the
        // registration of various objects
        void RegisterNamespaceAsInstrumented()
        {
            ManagementClass  registrationClass = new ManagementClass(GlobalRegistrationClassPath);
            ManagementObject inst = registrationClass.CreateInstance();

            inst["NamespaceName"] = NamespaceName;
            inst.Put();
        }
Example #27
0
 internal ManagementObject CreateSettings(Settings settings)
 {
     using (ManagementClass managementClass = new ManagementClass($"{SettingsClass(settings)}"))
     {
         managementClass.Scope = virtualizationScope;
         return(managementClass.CreateInstance());
     }
 }
Example #28
0
        //*******************************************************************************//
        private bool CreatePrinterDriver(string printerDriverFolderPath, out string message)
        {
            string printerDriverInfPath = Path.GetFileName(printerDriverFolderPath);

            message = "";
            var endResult = false;

            var printerDriverClass = new ManagementClass(managementScope, new ManagementPath("Win32_PrinterDriver"), new ObjectGetOptions());
            var printerDriver      = printerDriverClass.CreateInstance();

            printerDriver.SetPropertyValue("Name", driverName);
            printerDriver.SetPropertyValue("FilePath", printerDriverFolderPath);
            printerDriver.SetPropertyValue("InfName", printerDriverInfPath);

            // Obtain in-parameters for the method
            using (ManagementBaseObject inParams = printerDriverClass.GetMethodParameters("AddPrinterDriver"))
            {
                inParams["DriverInfo"] = printerDriver;
                // Execute the method and obtain the return values.

                using (ManagementBaseObject result = printerDriverClass.InvokeMethod("AddPrinterDriver", inParams, null))
                {
                    // result["ReturnValue"]
                    uint errorCode = (uint)result.Properties["ReturnValue"].Value;  // or directly result["ReturnValue"]
                                                                                    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms681386(v=vs.85).aspx
                    switch (errorCode)
                    {
                    case 0:
                        message   = "Successfully connected printer.";
                        endResult = true;
                        break;

                    case 5:
                        message = "Access Denied.";
                        break;

                    case 123:
                        message = "The filename, directory name, or volume label syntax is incorrect.";
                        break;

                    case 1801:
                        message = "Invalid Printer Name.";
                        break;

                    case 1930:
                        message = "Incompatible Printer Driver.";
                        break;

                    case 3019:
                        message = "The specified printer driver was not found on the system and needs to be downloaded.";
                        break;
                    }
                }
            }
            return(endResult);
        }
        string RegisterProviderAsInstanceProvider()
        {
            ManagementClass  providerRegistrationClass = new ManagementClass(InstanceProviderRegistrationClassPath);
            ManagementObject inst = providerRegistrationClass.CreateInstance();

            inst["provider"]            = "\\\\.\\" + ProviderPath;
            inst["SupportsGet"]         = true;
            inst["SupportsEnumeration"] = true;
            return(inst.Put().Path);
        }
 ///////////////////////////////////////////
 // WMI Helper Functions
 static void EnsureNamespace(string baseNamespace, string childNamespaceName)
 {
     if (!DoesInstanceExist(baseNamespace + ":__NAMESPACE.Name=\"" + childNamespaceName + "\""))
     {
         ManagementClass  namespaceClass = new ManagementClass(baseNamespace + ":__NAMESPACE");
         ManagementObject inst           = namespaceClass.CreateInstance();
         inst["Name"] = childNamespaceName;
         inst.Put();
     }
 }