Esempio n. 1
0
        /// <summary>
        /// Ctreates application pool
        /// </summary>
        /// <param name="name"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        internal static void CreateApplicationPool(string name, string username, string password)
        {
            // create pool
            ManagementObject objPool = wmi.GetClass("IIsApplicationPool").CreateInstance();

            objPool.Properties["Name"].Value = "W3SVC/AppPools/" + name;
            objPool.Put();

            // specify pool properties
            objPool = wmi.GetClass("IIsApplicationPoolSetting").CreateInstance();
            objPool.Properties["Name"].Value = "W3SVC/AppPools/" + name;
            if (!String.IsNullOrEmpty(username))
            {
                // specified account
                objPool.Properties["AppPoolIdentityType"].Value = 3;
                objPool.Properties["WAMUserName"].Value         = username;
                objPool.Properties["WAMUserPass"].Value         = password;
            }
            else
            {
                // NETWORK SERVICE
                objPool.Properties["AppPoolIdentityType"].Value = 2;
            }
            objPool.Put();
        }
        public void NotifiesIfSavedChanges()
        {
            MockNamedConfigurationSettingB setting = CreateMockNamedConfigurationSettingB("Baz", "Foo", "Bar");

            setting.Changed      += this.Changed;
            setting.SourceElement = new TestConfigurationSection();             // just so Commit works

            setting.Publish();

            using (System.Management.ManagementObjectCollection.ManagementObjectEnumerator resultEnumerator
                       = new ManagementObjectSearcher("root\\enterpriselibrary", "SELECT * FROM MockNamedConfigurationSettingB")
                         .Get().GetEnumerator())
            {
                Assert.IsTrue(resultEnumerator.MoveNext());

                ManagementObject managementObject = resultEnumerator.Current as ManagementObject;

                setting.performSave = false;
                Assert.IsNull(this.changedObject);
                managementObject.Put();
                Assert.IsNull(this.changedObject);                              // no change notified

                setting.performSave = true;
                Assert.IsNull(this.changedObject);
                managementObject.Put();
                Assert.IsNotNull(this.changedObject);                   // change notified
            }
        }
        /*
         *
         * //Report the type of the actual property value.
         * //This is important for numeric properties, where
         * //CIM Type is different than the type of value (automation layer problem).
         *
         * Object val = prop.get_Value();
         *
         * if (val.GetType() != typeof(System.DBNull) && prop.CimType != WbemCimTypeEnum.wbemCimTypeDatetime )
         * {
         *      return val.GetType();
         * }
         * else
         * {
         *      return CimTypeMapper.ToType(prop.CimType, prop.IsArray, prop);
         * }
         */



        public override void ResetValue(Object component)
        {
            try
            {
                /*
                 * Object defValue = wmiClassObj.Properties_.Item(propName, 0).get_Value();
                 * prop.set_Value(ref defValue);
                 * if (CommitImmediately)
                 * {
                 *      wmiObj.Put_((int)WbemChangeFlagEnum.wbemChangeFlagCreateOrUpdate
                 | (int)WbemFlagEnum.wbemFlagUseAmendedQualifiers,
                 |                              null);
                 | }*/

                prop.Value = classProp.Value;
                if (CommitImmediately)
                {
                    PutOptions putOpts = new PutOptions(null,
                                                        true,                                                   //use amended qualifiers
                                                        PutType.UpdateOrCreate);

                    mgmtObj.Put(putOpts);
                }
            }
            catch (Exception exc)
            {
                throw (exc);
            }
        }
Esempio n. 4
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();
        }
Esempio n. 5
0
 /// <summary>
 /// Write the bytes into WMIACPI_IO
 /// </summary>
 /// <param name="ioBytes">Raw bytes, length = 128</param>
 /// <returns>True if success</returns>
 private bool WriteWMIACPI_IO(byte[] ioBytes)
 {
     try
     {
         if (ioBytes.GetLength(0) != (int)this.IOBytesLength)
         {
             bool result = false;
             return(result);
         }
         SelectQuery              query = new SelectQuery(this.WMIACPIIOClass);
         ManagementScope          scope = new ManagementScope(this.WMIACPINamespace);
         ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(scope, query);
         using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = managementObjectSearcher.Get().GetEnumerator())
         {
             if (enumerator.MoveNext())
             {
                 ManagementObject managementObject = (ManagementObject)enumerator.Current;
                 managementObject.SetPropertyValue("IOBytes", ioBytes);
                 managementObject.Put();
                 bool result = true;
                 return(result);
             }
         }
     }
     catch (ManagementException ex)
     {
         //base.DebugInfoTrace(ex);
     }
     //catch (Exception ex2)
     //{
     //    //base.DebugInfoTrace(ex2);
     //}
     return(false);
 }
        public void SetFrameworkVersion(string version)
        {
            ManagementObject root = this.GetInstance(this.Path);

            foreach (PropertyData property in root.Properties)
            {
                if (property.Name == "ScriptMaps")
                {
                    ManagementBaseObject[] scriptMaps = (ManagementBaseObject[])property.Value;
                    foreach (ManagementBaseObject scriptMap in scriptMaps)
                    {
                        string value = (string)scriptMap["ScriptProcessor"];
                        if (value.ToLower().Contains("framework"))
                        {
                            if (!value.Contains(version))
                            {
                                string currentVersion = Regex.Match(value, @"(v\d+\.\d+\.\d+)").Value;
                                value = value.Replace(currentVersion, version);
                                scriptMap.SetPropertyValue("ScriptProcessor", value);
                            }
                            else
                            {
                                return;
                            }
                        }
                    }

                    property.Value = scriptMaps;
                    root.Put();
                    break;
                }
            }
        }
        public void CanBindObject()
        {
            MockNamedConfigurationSetting setting = CreateMockNamedConfigurationSetting("Baz", "Foo", "Bar");

            setting.Changed      += this.Changed;
            setting.SourceElement = new TestConfigurationSection();             // just so Commit works

            setting.Publish();

            using (System.Management.ManagementObjectCollection.ManagementObjectEnumerator resultEnumerator
                       = new ManagementObjectSearcher("root\\enterpriselibrary", "SELECT * FROM MockNamedConfigurationSetting")
                         .Get().GetEnumerator())
            {
                Assert.IsTrue(resultEnumerator.MoveNext());
                Assert.AreEqual("Baz", resultEnumerator.Current.Properties["Name"].Value);
                Assert.AreEqual("MockNamedConfigurationSetting", resultEnumerator.Current.SystemProperties["__CLASS"].Value);

                ManagementObject managementObject = resultEnumerator.Current as ManagementObject;
                Assert.IsNotNull(managementObject);

                Assert.IsNull(this.changedObject);
                managementObject.Put();
                Assert.IsNotNull(this.changedObject);

                Assert.IsFalse(resultEnumerator.MoveNext());
            }
        }
Esempio n. 8
0
        void SetAuthBasic(ManagementScope scope, string path)
        {
            var site = new ManagementObject(scope, new ManagementPath(path), null);

            site["AuthBasic"] = true;
            site.Put();
        }
Esempio n. 9
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);
            }
        }
Esempio n. 10
0
        private void Delete()
        {
            if (!this.CheckExists())
            {
                return;
            }

            string      queryString = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM MSBTS_SendHandler2 WHERE AdapterName = '{0}'", this.AdapterName);
            ObjectQuery query       = new ObjectQuery(queryString);

            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(this.Scope, query, null))
            {
                ManagementObjectCollection objects    = searcher.Get();
                ManagementObject           newDefault = null;
                try
                {
                    if (objects.Count > 0)
                    {
                        foreach (ManagementObject obj in objects)
                        {
                            if (!Convert.ToBoolean(obj["IsDefault"], CultureInfo.InvariantCulture))
                            {
                                newDefault = obj;
                                break;
                            }
                        }

                        foreach (ManagementObject obj in objects)
                        {
                            if (string.Compare(obj["HostName"].ToString(), this.HostName, StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                this.sendHandler = obj;
                                if (Convert.ToBoolean(this.sendHandler["IsDefault"], CultureInfo.InvariantCulture))
                                {
                                    this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Changing Default Send Handler to: {0}", newDefault["HostName"]));
                                    newDefault["IsDefault"] = true;
                                    newDefault.Put(new PutOptions {
                                        Type = PutType.UpdateOnly
                                    });
                                    this.explorer.SaveChanges();
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }

                        this.sendHandler.Delete();
                    }
                }
                finally
                {
                    if (newDefault != null)
                    {
                        newDefault.Dispose();
                    }
                }
            }
        }
Esempio n. 11
0
        /// <summary>
        /// 重命名Tap设备
        /// </summary>
        /// <param name="name">新名字</param>
        /// <param name="adapter">Tap设备</param>
        public static void RenameTapDevice(string name, NetworkInterface adapter)
        {
            if (Os.Ver == Os.V.XpOrLower)
            {
                throw new NotSupportedException("Windows Version Too Low");
            }
            if (Os.Ver == Os.V.VistaOrSeven)
            {
                // win7 or lower
                ManagementClass  nic    = new ManagementClass(@"\\.\ROOT\cimv2:Win32_NetworkAdapter");
                ManagementObject target = null;
                foreach (ManagementObject a in nic.GetInstances())
                {
                    if ((string)a["GUID"] == adapter.Id)
                    {
                        target = a;
                        break;
                    }
                }
                if (target != null)
                {
                    target.SetPropertyValue("NetConnectionID", name);
                    PutOptions po = new PutOptions {
                        Type = PutType.UpdateOnly
                    };
                    target.Put(po);
                }
            }
            else
            {
                // win8 or higher
                ManagementClass  nic    = new ManagementClass(@"\\.\ROOT\StandardCimv2:MSFT_NetAdapter");
                ManagementObject target = null;
                foreach (ManagementObject a in nic.GetInstances())
                {
                    if ((string)a["DeviceID"] == adapter.Id)
                    {
                        target = a;
                        break;
                    }
                }
                if (target != null)
                {
                    ManagementBaseObject param = target.GetMethodParameters("Rename");
                    param["NewName"] = name;
                    target.InvokeMethod("Rename", param, null);
                }
            }


            /*
             * else {
             *  // xp or lower,不确定是否有效(win7测试无效)
             *  string adapterKey = @"SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}\" + adapter.Id + @"\Connection";
             *  RegistryKey rbase = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default);
             *  RegistryKey rk = rbase.OpenSubKey(adapterKey, true);
             *  rk?.SetValue("Name", name);
             * }
             */
        }
Esempio n. 12
0
        /// <summary>
        /// Execute() implementation
        /// </summary>
        /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param>
        public override void Execute(Context context)
        {
            ManagementObject mo = GetreceiveLocationWmiObject(ReceiveLocationName);

            bool isActualEnabled;

            using (mo)
            {
                isActualEnabled = (bool)mo.GetPropertyValue("OperatingWindowEnabled");
            }

            if (Enable != isActualEnabled)
            {
                PutOptions p = new PutOptions();
                p.Type = PutType.UpdateOnly;
                mo.SetPropertyValue("OperatingWindowEnabled", Enable);
                ManagementPath result = mo.Put(p);

                context.LogInfo(string.Format("The receive location: {0} service window is {1}", ReceiveLocationName, Enable ? "enabled" : "disabled"));
            }
            else
            {
                context.LogInfo(string.Format("The receive location: {0} service windows was already in the state {1}", ReceiveLocationName, Enable ? "enabled" : "disabled"));
            }
        }
Esempio n. 13
0
        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);
        }
Esempio n. 14
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);
        }
Esempio n. 15
0
        public static void AddHostHeader(string serverName, string hostHeader,
                                         string ip, int port, string websiteID)
        {
            ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\root\MicrosoftIISV2", serverName));

            scope.Connect();

            string siteName = string.Format("'W3SVC/{0}'", websiteID);

            ManagementObject mo = new ManagementObject(scope,
                                                       new System.Management.ManagementPath("IIsWebServerSetting=" + siteName), null);

            ManagementBaseObject[] websiteBindings =
                (ManagementBaseObject[])mo.Properties["ServerBindings"].Value;

            ManagementObject mco = CreateServerBinding(scope, hostHeader, ip, port);

            ManagementBaseObject[] newWebsiteBindings =
                new ManagementBaseObject[websiteBindings.Length + 1];
            websiteBindings.CopyTo(newWebsiteBindings, 0);
            newWebsiteBindings[newWebsiteBindings.Length - 1] = mco;

            mo.Properties["ServerBindings"].Value = newWebsiteBindings;

            mo.Put();
        }
Esempio n. 16
0
 public void ApplyConfiguration(InstanceConfiguration configuration)
 {
     ManagementObject.SetPropertyValue("LogMessagesAtServiceLevel", configuration.LogMessageAtServiceLevel);
     ManagementObject.SetPropertyValue("TraceLevel", configuration.ServiceModelTraceLevel);
     ManagementObject.Put();
     Configuration = InstanceConfiguration.ReadFromWmi(ManagementObject);
 }
Esempio n. 17
0
        private static bool WriteWMIACPI_IO(WMIACPI_IO_Status status)
        {
            byte[] array = new byte[128];
            array[0]  = 1;
            array[1]  = 16;
            array[8]  = 10;
            array[9]  = 3;
            array[10] = 0;
            array[16] = (byte)status;

            SelectQuery              query = new SelectQuery("WMIACPI_IO");
            ManagementScope          scope = new ManagementScope("root\\WMI");
            ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(scope, query);

            using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = managementObjectSearcher.Get().GetEnumerator())
            {
                if (enumerator.MoveNext())
                {
                    ManagementObject managementObject = (ManagementObject)enumerator.Current;
                    managementObject.SetPropertyValue("IOBytes", array);
                    managementObject.Put();

                    return(true);
                }
            }
            if (managementObjectSearcher != null)
            {
                managementObjectSearcher.Dispose();
            }

            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);
            }
        }
Esempio n. 19
0
        private void SetAppPool(ManagementScope scope, string path, string appPoolId)
        {
            var site = new ManagementObject(scope, new ManagementPath(path), null);

            site["AppPoolId"] = appPoolId;
            site.Put();
        }
Esempio n. 20
0
        /// <summary>
        /// Set the slidebar status. Just like SetAppRegistration.
        /// This function is also written by DOSSTONED
        /// </summary>
        /// <param name="evt">Event to set.</param>
        /// <param name="enabled">Whether this event is enabled.</param>
        public byte[] SetSlideBarStatus(Event evt, bool enabled)
        {
            byte[] array = new byte[128];
            array[0]  = 1;
            array[1]  = 16;
            array[8]  = (byte)evt;
            array[9]  = 3;
            array[10] = 0;
            array[16] = (byte)(enabled ? 1 : 0);
            array[68] = (byte)(enabled ? 1 : 0);

            SelectQuery              query = new SelectQuery("WMIACPI_IO");
            ManagementScope          scope = new ManagementScope("root\\WMI");
            ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(scope, query);

            using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = managementObjectSearcher.Get().GetEnumerator())
            {
                if (enumerator.MoveNext())
                {
                    ManagementObject managementObject = (ManagementObject)enumerator.Current;
                    managementObject.SetPropertyValue("IOBytes", array);
                    managementObject.Put();
                }
            }
            if (managementObjectSearcher != null)
            {
                managementObjectSearcher.Dispose();
            }
            return(array);
        }
Esempio n. 21
0
        void SetAuth(ManagementScope scope, string path, string authSetting, bool setting)
        {
            var site = new ManagementObject(scope, new ManagementPath(path), null);

            site[authSetting] = setting;
            site.Put();
        }
Esempio n. 22
0
        private void AddDomainInternal(string domainName)
        {
            HostedSolutionLog.LogStart("AddDomainInternal");
            HostedSolutionLog.DebugInfo("Domain Name: {0}", domainName);
            try
            {
                if (string.IsNullOrEmpty(domainName))
                {
                    throw new ArgumentException("domainName");
                }

                if (GetDomain(domainName) != null)
                {
                    HostedSolutionLog.LogWarning("OCS internal domain '{0}' already exists", domainName);
                }
                else
                {
                    using (ManagementObject newDomain = Wmi.CreateInstance("MSFT_SIPFederationInternalDomainData"))
                    {
                        newDomain["SupportedInternalDomain"] = domainName;
                        newDomain.Put();
                    }
                }
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("AddDomainInternal", ex);
                throw;
            }
            HostedSolutionLog.LogEnd("AddDomainInternal");
        }
        [Ignore] // not sure why this is not working.
        public void BindOnRevokedInstanceThrows()
        {
            MockNamedConfigurationSetting setting = CreateMockNamedConfigurationSetting("Baz", "Foo", "Bar");

            setting.Changed += this.Changed;

            setting.Publish();

            using (System.Management.ManagementObjectCollection.ManagementObjectEnumerator resultEnumerator
                       = new ManagementObjectSearcher("root\\enterpriselibrary", "SELECT * FROM MockNamedConfigurationSetting")
                         .Get().GetEnumerator())
            {
                Assert.IsTrue(resultEnumerator.MoveNext());
                Assert.AreEqual("Baz", resultEnumerator.Current.Properties["Name"].Value);
                Assert.AreEqual("MockNamedConfigurationSetting", resultEnumerator.Current.SystemProperties["__CLASS"].Value);

                ManagementObject managementObject = resultEnumerator.Current as ManagementObject;
                Assert.IsNotNull(managementObject);

                Assert.IsNull(this.changedObject);
                setting.Revoke();
                try
                {
                    managementObject.Put();
                    Assert.Fail("should have thrown");
                }
                catch (ManagementException e)
                {
                    Assert.AreEqual(ManagementStatus.ProviderNotCapable, e.ErrorCode);
                }
            }
        }
Esempio n. 24
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);
        }
Esempio n. 25
0
        private static void ChangeQueuePort(string portName, string newName)
        {
            ConnectionOptions options = new ConnectionOptions();

            options.EnablePrivileges = true;

            ManagementScope mgmtScope = new ManagementScope("root\\CIMV2", options);

            mgmtScope.Connect();

            ObjectQuery objQuery = new ObjectQuery("SELECT * FROM Win32_Printer WHERE PortName = '{0}'".FormatWith(portName));

            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(mgmtScope, objQuery))
            {
                ManagementObjectCollection match = searcher.Get();
                if (match.Count != 1)
                {
                    throw new InvalidOperationException("Unexpected search result.  Returned {0} matches for PortName:{1}".FormatWith(match.Count, portName));
                }

                var enumerator = match.GetEnumerator();
                enumerator.MoveNext();
                ManagementObject printerObject = (ManagementObject)enumerator.Current;

                TraceFactory.Logger.Debug("Old Port: {0}, New Port: {1}".FormatWith(printerObject["PortName"], newName));
                printerObject["PortName"] = newName;

                PutOptions po = new PutOptions();
                po.Type = PutType.UpdateOrCreate;
                printerObject.Put(po);
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Creates a new AppPool.
        /// </summary>
        /// <param name="name">The AppPool name.</param>
        /// <param name="machineName">The server on which the AppPool will be created.</param>
        /// <param name="millisecondsTimeout">Timeout value on wait for Create to complete.</param>
        /// <returns>The Wmi ManagementPath</returns>
        public static ManagementPath Create(string name, string machineName, int millisecondsTimeout, string managedRunTimeVersion = "v4.0", int identityType = 4, string username = null, string password = null)
        {
            PutOptions options = new PutOptions();

            options.Timeout = System.TimeSpan.FromMinutes(Convert.ToDouble(millisecondsTimeout));

            IisAppPoolUtilWmiHelper helper  = new IisAppPoolUtilWmiHelper(machineName);
            ManagementObject        appPool = helper.CreateManagementObject("IIsApplicationPoolSetting");

            appPool.Properties["Name"].Value = string.Format("W3SVC/AppPools/{0}", name);
            appPool.Properties["AppPoolIdentityType"].Value   = identityType;
            appPool.Properties["ManagedRuntimeVersion"].Value = managedRunTimeVersion;

            if (identityType == 3)
            {
                if (username != null)
                {
                    appPool.Properties["WAMUserName"].Value = username;
                }
                if (password != null)
                {
                    appPool.Properties["WAMUserPass"].Value = password;
                }
            }

            return(appPool.Put(options));
        }
Esempio n. 27
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();
        }
Esempio n. 28
0
        private void SetUserGeneralSettingsInternal(string instanceId, bool enabledForFederation, bool enabledForPublicIMConectivity, bool archiveInternalCommunications, bool archiveFederatedCommunications, bool enabledForEnhancedPresence)
        {
            HostedSolutionLog.LogStart("SetUserGeneralSettingsInternal");
            try
            {
                if (string.IsNullOrEmpty(instanceId))
                {
                    throw new ArgumentException("instanceId");
                }

                using (ManagementObject userObject = GetUserByInstanceId(instanceId))
                {
                    if (userObject == null)
                    {
                        throw new Exception(string.Format("OCS user {0} not found", instanceId));
                    }

                    userObject["EnabledForFederation"]           = enabledForFederation;
                    userObject["PublicNetworkEnabled"]           = enabledForPublicIMConectivity;
                    userObject["ArchiveInternalCommunications"]  = archiveInternalCommunications;
                    userObject["ArchiveFederatedCommunications"] = archiveFederatedCommunications;
                    if (enabledForEnhancedPresence)
                    {
                        userObject["EnabledForEnhancedPresence"] = true;
                    }
                    userObject.Put();
                }
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("SetUserGeneralSettingsInternal", ex);
                throw;
            }
            HostedSolutionLog.LogEnd("SetUserGeneralSettingsInternal");
        }
Esempio n. 29
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);
 }
Esempio n. 30
0
        private void SetUserPrimaryUriInternal(string instanceId, string userUpn)
        {
            HostedSolutionLog.LogStart("SetUserPrimaryUriInternal");
            try
            {
                if (string.IsNullOrEmpty(instanceId))
                {
                    throw new ArgumentException("instanceId");
                }

                if (string.IsNullOrEmpty(userUpn))
                {
                    throw new ArgumentException("userUpn");
                }

                using (ManagementObject userObject = GetUserByInstanceId(instanceId))
                {
                    if (userObject == null)
                    {
                        throw new Exception(string.Format("OCS user {0} not found", instanceId));
                    }
                    string primaryUri = "sip:" + userUpn;
                    userObject["PrimaryURI"] = primaryUri;
                    userObject.Put();
                }
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("SetUserPrimaryUriInternal", ex);
                throw;
            }
            HostedSolutionLog.LogEnd("SetUserPrimaryUriInternal");
        }