Ejemplo n.º 1
0
        public void Should_pull_using_WMI()
        {
            var options = new EnumerationOptions {Rewindable = false, ReturnImmediately = true};
            var scope = new ManagementScope(ManagementPath.DefaultPath);
            var query = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter");

            var searcher = new ManagementObjectSearcher(scope, query, options);
            ManagementObjectCollection collection = searcher.Get();
            foreach (ManagementObject obj in collection)
            {
                try
                {
                    PropertyData typeData = obj.Properties["AdapterType"];
                    string typeValue = typeData.Value.ToString();

                    PropertyData propertyData = obj.Properties["MACAddress"];
                    string propertyValue = propertyData.Value.ToString();

                    Console.WriteLine("Adapter: {0}-{1}", propertyValue, typeValue);
                }
                catch (Exception ex)
                {
                }
            }
        }
 public static WmiMonitorBrightnessMethodsCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions)
 {
     if ((mgmtScope == null))
     {
         if ((statMgmtScope == null))
         {
             mgmtScope = new System.Management.ManagementScope();
             mgmtScope.Path.NamespacePath = "root\\wmi";
         }
         else
         {
             mgmtScope = statMgmtScope;
         }
     }
     System.Management.ManagementPath pathObj = new System.Management.ManagementPath();
     pathObj.ClassName     = "WmiMonitorBrightnessMethods";
     pathObj.NamespacePath = "root\\wmi";
     System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null);
     if ((enumOptions == null))
     {
         enumOptions = new System.Management.EnumerationOptions();
         enumOptions.EnsureLocatable = true;
     }
     return(new WmiMonitorBrightnessMethodsCollection(clsObject.GetInstances(enumOptions)));
 }
Ejemplo n.º 3
0
 public static RegistryTreeChangeEventCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions)
 {
     if ((mgmtScope == null))
     {
         if ((statMgmtScope == null))
         {
             mgmtScope = new System.Management.ManagementScope();
             mgmtScope.Path.NamespacePath = "root\\DEFAULT";
         }
         else
         {
             mgmtScope = statMgmtScope;
         }
     }
     System.Management.ManagementPath pathObj = new System.Management.ManagementPath();
     pathObj.ClassName     = "RegistryTreeChangeEvent";
     pathObj.NamespacePath = "root\\DEFAULT";
     System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null);
     if ((enumOptions == null))
     {
         enumOptions = new System.Management.EnumerationOptions();
         enumOptions.EnsureLocatable = true;
     }
     return(new RegistryTreeChangeEventCollection(clsObject.GetInstances(enumOptions)));
 }
        static IEnumerable<byte[]> GetManagementObjects()
        {
            var options = new EnumerationOptions {Rewindable = false, ReturnImmediately = true};
            var scope = new ManagementScope(ManagementPath.DefaultPath);
            var query = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter");

            var searcher = new ManagementObjectSearcher(scope, query, options);
            ManagementObjectCollection collection = searcher.Get();

            foreach (ManagementObject obj in collection)
            {
                byte[] bytes;
                try
                {
                    PropertyData propertyData = obj.Properties["MACAddress"];
                    string propertyValue = propertyData.Value.ToString();

                    bytes = propertyValue.Split(':')
                        .Select(x => byte.Parse(x, NumberStyles.HexNumber))
                        .ToArray();
                }
                catch (Exception)
                {
                    continue;
                }

                if (bytes.Length == 6)
                    yield return bytes;
            }
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            var sb = new StringBuilder();
            var scope = Wmi.GetScope();
            var enumOptions = new EnumerationOptions { EnsureLocatable = true };

            var processor = Processor.GetInstances(scope, enumOptions).Cast<Processor>().FirstOrDefault();
            if (processor != null)
            {
                sb.AppendLine(string.Format("{0,-22} {1}", "Name:", processor.Name));
                sb.AppendLine(string.Format("{0,-22} {1} ({2}-bit)", "Architecture:",
                    processor.Architecture.GetDescription(), processor.DataWidth));
                sb.AppendLine(string.Format("{0,-22} {1}", "Processor ID:", processor.ProcessorId));
            }
            sb.AppendLine();

            var os = new OperatingSystem0(scope);
            {
                sb.AppendLine(string.Format("{0,-22} {1} [{2}] ({3})", "Operating System:", os.Caption, os.Version, os.OSArchitecture));
                sb.AppendLine(string.Format("{0,-22} {1:yyyy-MM-dd HH:mm:ss} ({2,3:dd} days {2:hh}:{2:mm}:{2:ss})",
                    "Install Date", os.InstallDate, (DateTime.Now - os.InstallDate)));
                sb.AppendLine(string.Format("{0,-22} {1:yyyy-MM-dd HH:mm:ss} ({2,3:dd} days {2:hh}:{2:mm}:{2:ss})",
                    "Last boot", os.LastBootUpTime, (DateTime.Now - os.LastBootUpTime)));
            }

            sb.AppendLine();

            Console.WriteLine(sb.ToString());
            Console.Write("Press any key to continue...");
            Console.ReadKey();
        }
 public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions)
 {
     if ((mgmtScope == null))
     {
         if ((statMgmtScope == null))
         {
             mgmtScope = new System.Management.ManagementScope();
             mgmtScope.Path.NamespacePath = "root\\virtualization";
         }
         else
         {
             mgmtScope = statMgmtScope;
         }
     }
     System.Management.ManagementPath pathObj = new System.Management.ManagementPath();
     pathObj.ClassName     = "Msvm_ResourceAllocationSettingData";
     pathObj.NamespacePath = "root\\virtualization";
     System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null);
     if ((enumOptions == null))
     {
         enumOptions = new System.Management.EnumerationOptions();
         enumOptions.EnsureLocatable = true;
     }
     return(new ResourceAllocationSettingDataCollection(clsObject.GetInstances(enumOptions)));
 }
Ejemplo n.º 7
0
 public static Environment0Collection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions)
 {
     if ((mgmtScope == null))
     {
         if ((statMgmtScope == null))
         {
             mgmtScope = new System.Management.ManagementScope();
             mgmtScope.Path.NamespacePath = "root\\cimv2";
         }
         else
         {
             mgmtScope = statMgmtScope;
         }
     }
     System.Management.ManagementPath pathObj = new System.Management.ManagementPath();
     pathObj.ClassName     = "Win32_Environment";
     pathObj.NamespacePath = "root\\cimv2";
     System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null);
     if ((enumOptions == null))
     {
         enumOptions = new System.Management.EnumerationOptions();
         enumOptions.EnsureLocatable = true;
     }
     return(new Environment0Collection(clsObject.GetInstances(enumOptions)));
 }
Ejemplo n.º 8
0
        public void TriggerClientAction(string scheduleId, ManagementScope remote)
        {
            ObjectQuery query = new SelectQuery("SELECT * FROM meta_class WHERE __Class = 'SMS_Client'");
            var eOption = new EnumerationOptions();
            var searcher = new ManagementObjectSearcher(remote, query, eOption);
            var queryCollection = searcher.Get();

            foreach (ManagementObject ro in queryCollection)
            {
                // Obtain in-parameters for the method
                var inParams = ro.GetMethodParameters("TriggerSchedule");

                // Add the input parameters.
                inParams["sScheduleID"] = scheduleId;

                try
                {
                    var outParams = ro.InvokeMethod("TriggerSchedule", inParams, null);

                    ResultConsole.Instance.AddConsoleLine($"Returned with value {_wmiServices.GetProcessReturnValueText(Convert.ToInt32(outParams["ReturnValue"]))}");
                }
                catch (Exception ex)
                {
                    ResultConsole.Instance.AddConsoleLine("Error performing SCCM Client Function due to an error.");
                    _logger.LogError($"Error performing SCCM Client Function due to the following error: {ex.Message}", ex);
                }
            }
        }
Ejemplo n.º 9
0
 public static HostInstanceSettingCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions)
 {
     if ((mgmtScope == null))
     {
         if ((statMgmtScope == null))
         {
             mgmtScope = new System.Management.ManagementScope();
             mgmtScope.Path.NamespacePath = "root\\MicrosoftBizTalkServer";
         }
         else
         {
             mgmtScope = statMgmtScope;
         }
     }
     System.Management.ManagementPath pathObj = new System.Management.ManagementPath();
     pathObj.ClassName     = "MSBTS_HostInstanceSetting";
     pathObj.NamespacePath = "root\\MicrosoftBizTalkServer";
     System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null);
     if ((enumOptions == null))
     {
         enumOptions = new System.Management.EnumerationOptions();
         enumOptions.EnsureLocatable = true;
     }
     return(new HostInstanceSettingCollection(clsObject.GetInstances(enumOptions)));
 }
Ejemplo n.º 10
0
        private static ManagementObjectSearcher MyGetSearcher(ManagementScope scope, string myquery)
        {
            EnumerationOptions options = new EnumerationOptions();
            options.Rewindable = false;
            options.ReturnImmediately = true;

            return new ManagementObjectSearcher(scope, new ObjectQuery(myquery), options);
        }
Ejemplo n.º 11
0
        public string ExecuteQueryReturnJSON(string query)
        {
            ManagementObjectSearcher searcher;
            searcher = new ManagementObjectSearcher(Scope, query);

            EnumerationOptions options = new EnumerationOptions();
            options.ReturnImmediately = true;

            ManagementObjectCollection res = searcher.Get();

            return DataConverter.DataTableToJSON(WmiToDataTable(res));
        }
Ejemplo n.º 12
0
        //internal IWbemServices GetIWbemServices () {
        //  return scope.GetIWbemServices ();
        //}

        //internal ConnectionOptions Connection {
        //  get { return scope.Connection; }
        //}

        //Constructor
        internal ManagementObjectCollection(
            ManagementScope scope,
            EnumerationOptions options, 
            IEnumWbemClassObject enumWbem)
        {
            if (null != options)
                this.options = (EnumerationOptions) options.Clone();
            else
                this.options = new EnumerationOptions ();

            if (null != scope)
                this.scope = (ManagementScope)scope.Clone ();
            else
                this.scope = ManagementScope._Clone(null);

            this.enumWbem = enumWbem;
        }
Ejemplo n.º 13
0
        private static string GetID(string wmiClass, string[] wmiProperties)
        {
            string result = "";


            if (searcher2 == null)
            {
                System.Management.EnumerationOptions k = new System.Management.EnumerationOptions();
                k.DirectRead        = true;
                k.EnumerateDeep     = false;
                k.EnsureLocatable   = false;
                k.Rewindable        = false;
                k.ReturnImmediately = false;
                searcher2           = new System.Management.ManagementObjectSearcher();
                searcher2.Options   = k;
            }
            searcher2.Query.QueryString = "select * from " + wmiClass;
            try
            {
                moc = searcher2.Get();
            }
            catch
            {
                return("");
            }
            foreach (System.Management.ManagementObject mo in moc)
            {
                bool found = false;

                foreach (string wmiProperty in wmiProperties)
                {
                    if (mo[wmiProperty] != null)
                    {
                        found   = true;
                        result += mo[wmiProperty].ToString();
                    }
                }
                if (found)
                {
                    // All properties exist in the same ManagementObject
                    break;
                }
            }
            return(result);
        }
Ejemplo n.º 14
0
        protected override void ExecuteTask() {
            try {
                ObjectQuery query = new ObjectQuery("SELECT * FROM MSBTS_Orchestration"
                    + " WHERE Name = " + SqlQuote(OrchestrationName));

                EnumerationOptions enumerationOptions = new EnumerationOptions();
                enumerationOptions.ReturnImmediately = false;

                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(Scope, query, enumerationOptions)) {
                    ManagementObjectCollection orchestrations = searcher.Get();

                    // ensure we found a matching orchestration
                    if (orchestrations.Count == 0) {
                        throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                            "Orchestration \"{0}\" does not exist on \"{0}\".", 
                            OrchestrationName, Server), Location);
                    }

                    // perform actions on each matching orchestration
                    foreach (ManagementObject orchestration in orchestrations) {
                        try {
                            // invoke each action in the order in which they
                            // were added (in the build file)
                            foreach (IOrchestrationAction action in _actions) {
                                action.Invoke(orchestration);
                            }
                        } catch (Exception ex) {
                            if (FailOnError) {
                                throw;
                            }

                            // log exception and continue processing the actions
                            // for the next orchestration
                            Log(Level.Error, ex.Message);
                        }
                    }
                }
            } catch (BuildException) {
                throw;
            } catch (Exception ex) {
                throw new BuildException("Error looking up orchestration(s).", 
                    Location, ex);
            }
        }
Ejemplo n.º 15
0
 public static Environment0Collection GetInstances(System.Management.ManagementScope mgmtScope, string condition, System.String[] selectedProperties)
 {
     if ((mgmtScope == null))
     {
         if ((statMgmtScope == null))
         {
             mgmtScope = new System.Management.ManagementScope();
             mgmtScope.Path.NamespacePath = "root\\cimv2";
         }
         else
         {
             mgmtScope = statMgmtScope;
         }
     }
     System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Win32_Environment", condition, selectedProperties));
     System.Management.EnumerationOptions       enumOptions    = new System.Management.EnumerationOptions();
     enumOptions.EnsureLocatable = true;
     ObjectSearcher.Options      = enumOptions;
     return(new Environment0Collection(ObjectSearcher.Get()));
 }
Ejemplo n.º 16
0
 public static HostInstanceSettingCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties)
 {
     if ((mgmtScope == null))
     {
         if ((statMgmtScope == null))
         {
             mgmtScope = new System.Management.ManagementScope();
             mgmtScope.Path.NamespacePath = "root\\MicrosoftBizTalkServer";
         }
         else
         {
             mgmtScope = statMgmtScope;
         }
     }
     System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("MSBTS_HostInstanceSetting", condition, selectedProperties));
     System.Management.EnumerationOptions       enumOptions    = new System.Management.EnumerationOptions();
     enumOptions.EnsureLocatable = true;
     ObjectSearcher.Options      = enumOptions;
     return(new HostInstanceSettingCollection(ObjectSearcher.Get()));
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Targets the specified namespace on a specified computer, and scavenges it for all classes, if the bool is set to true. If false, it is used to setup the ManagementPath which
        /// consists of the specified system and specified namespace
        /// </summary>
        /// <param name="pNamespace"></param>
        /// <param name="pHostName"></param>
        public WmiInformationGatherer(string pNamespace, string pHostName, bool pScavenge)
        {
            mRemoteWmiPath = new ManagementPath(@"\\" + pHostName + @"\root\" + pNamespace);

            if (pScavenge)
            {
                try
                {
                    ManagementClass managementClass = new ManagementClass(mRemoteWmiPath);
                    EnumerationOptions scavengeOptions = new EnumerationOptions();
                    scavengeOptions.EnumerateDeep = false;
                    WmiResults = new WmiResult(pHostName);
                    WmiResults.PopulateClassesList(managementClass.GetSubclasses());
                }
                catch (Exception e)
                {
                    WmiResults.WmiError = e;
                }
            }
        }
 public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties)
 {
     if ((mgmtScope == null))
     {
         if ((statMgmtScope == null))
         {
             mgmtScope = new System.Management.ManagementScope();
             mgmtScope.Path.NamespacePath = "root\\virtualization";
         }
         else
         {
             mgmtScope = statMgmtScope;
         }
     }
     System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ResourceAllocationSettingData", condition, selectedProperties));
     System.Management.EnumerationOptions       enumOptions    = new System.Management.EnumerationOptions();
     enumOptions.EnsureLocatable = true;
     ObjectSearcher.Options      = enumOptions;
     return(new ResourceAllocationSettingDataCollection(ObjectSearcher.Get()));
 }
 public ManagementObjectSearcher(ManagementScope scope, ObjectQuery query, EnumerationOptions options)
 {
     this.scope = ManagementScope._Clone(scope);
     if (query != null)
     {
         this.query = (ObjectQuery) query.Clone();
     }
     else
     {
         this.query = new ObjectQuery();
     }
     if (options != null)
     {
         this.options = (EnumerationOptions) options.Clone();
     }
     else
     {
         this.options = new EnumerationOptions();
     }
 }
 internal ManagementObjectCollection(ManagementScope scope, EnumerationOptions options, IEnumWbemClassObject enumWbem)
 {
     if (options != null)
     {
         this.options = (EnumerationOptions) options.Clone();
     }
     else
     {
         this.options = new EnumerationOptions();
     }
     if (scope != null)
     {
         this.scope = scope.Clone();
     }
     else
     {
         this.scope = ManagementScope._Clone(null);
     }
     this.enumWbem = enumWbem;
 }
Ejemplo n.º 21
0
        public WMI(bool recursive, InquiryEntity ie)
        {
            Recursive = recursive;
            this.ie   = ie;

            co = new ConnectionOptions
            {
                Impersonation    = ImpersonationLevel.Impersonate,
                Authentication   = AuthenticationLevel.PacketIntegrity,
                EnablePrivileges = true,
                Timeout          = TimeSpan.MaxValue
            };

            eo = new EnumerationOptions()
            {
                BlockSize         = 1,
                DirectRead        = true,
                ReturnImmediately = true,
                Timeout           = TimeSpan.MaxValue
            };
        }
Ejemplo n.º 22
0
        public ManagementObjectCollection GetRelationshipClasses(string relationshipClass, string relationshipQualifier, string thisRole, EnumerationOptions options)
        {
            EnumerationOptions enumerationOption;

            if (this.Path == null || this.Path.Path == null || this.Path.Path.Length == 0)
            {
                throw new InvalidOperationException();
            }
            else
            {
                this.Initialize(false);
                IEnumWbemClassObject enumWbemClassObject = null;
                if (options != null)
                {
                    enumerationOption = options;
                }
                else
                {
                    enumerationOption = new EnumerationOptions();
                }
                EnumerationOptions enumerationOption1 = enumerationOption;
                enumerationOption1.EnumerateDeep = true;
                RelationshipQuery relationshipQuery = new RelationshipQuery(true, this.Path.Path, relationshipClass, relationshipQualifier, thisRole);
                SecurityHandler   securityHandler   = null;
                int num = 0;
                try
                {
                    securityHandler = base.Scope.GetSecurityHandler();
                    num             = this.scope.GetSecuredIWbemServicesHandler(base.Scope.GetIWbemServices()).ExecQuery_(relationshipQuery.QueryLanguage, relationshipQuery.QueryString, enumerationOption1.Flags, enumerationOption1.GetContext(), ref enumWbemClassObject);
                }
                finally
                {
                    if (securityHandler != null)
                    {
                        securityHandler.Reset();
                    }
                }
                if (num < 0)
                {
                    if (((long)num & (long)-4096) != (long)-2147217408)
                    {
                        Marshal.ThrowExceptionForHR(num);
                    }
                    else
                    {
                        ManagementException.ThrowWithExtendedInfo((ManagementStatus)num);
                    }
                }
                return(new ManagementObjectCollection(base.Scope, enumerationOption1, enumWbemClassObject));
            }
        }
Ejemplo n.º 23
0
 public ManagementObjectCollection GetRelationshipClasses(string relationshipClass, string relationshipQualifier, string thisRole, EnumerationOptions options)
 {
     throw new NotImplementedException();
 }
 public static BcdObjectCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions)
 {
     if ((mgmtScope == null)) {
         if ((statMgmtScope == null)) {
             mgmtScope = new System.Management.ManagementScope();
             mgmtScope.Path.NamespacePath = "root\\WMI";
         }
         else {
             mgmtScope = statMgmtScope;
         }
     }
     System.Management.ManagementPath pathObj = new System.Management.ManagementPath();
     pathObj.ClassName = "BcdObject";
     pathObj.NamespacePath = "root\\WMI";
     System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null);
     if ((enumOptions == null)) {
         enumOptions = new System.Management.EnumerationOptions();
         enumOptions.EnsureLocatable = true;
     }
     return new BcdObjectCollection(clsObject.GetInstances(enumOptions));
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Do the actual connection to remote machine for Get-WMIObject cmdlet and raise operation complete event.
        /// </summary>
        private void ConnectGetWMI()
        {
            GetWmiObjectCommand getObject = (GetWmiObjectCommand)_wmiObject;
            _state = WmiState.Running;
            RaiseWmiOperationState(null, WmiState.Running);
            ConnectionOptions options = getObject.GetConnectionOption();
            if (getObject.List.IsPresent)
            {
                if (!getObject.ValidateClassFormat())
                {
                    ArgumentException e = new ArgumentException(
                        String.Format(
                            Thread.CurrentThread.CurrentCulture,
                            "Class", getObject.Class));

                    internalException = e;
                    _state = WmiState.Failed;
                    RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                    return;
                }
                try
                {
                    if (getObject.Recurse.IsPresent)
                    {
                        ArrayList namespaceArray = new ArrayList();
                        ArrayList sinkArray = new ArrayList();
                        ArrayList connectArray = new ArrayList(); // Optimization for remote namespace
                        int currentNamesapceCount = 0;
                        namespaceArray.Add(getObject.Namespace);
                        bool topNamespace = true;
                        while (currentNamesapceCount < namespaceArray.Count)
                        {
                            string connectNamespace = (string)namespaceArray[currentNamesapceCount];
                            ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, connectNamespace), options);
                            scope.Connect();
                            ManagementClass namespaceClass = new ManagementClass(scope, new ManagementPath("__Namespace"), new ObjectGetOptions());
                            foreach (ManagementBaseObject obj in namespaceClass.GetInstances())
                            {
                                if (!getObject.IsLocalizedNamespace((string)obj["Name"]))
                                {
                                    namespaceArray.Add(connectNamespace + "\\" + obj["Name"]);
                                }
                            }
                            if (topNamespace)
                            {
                                topNamespace = false;
                                sinkArray.Add(_results);
                            }
                            else
                            {
                                sinkArray.Add(_job.GetNewSink());
                            }
                            connectArray.Add(scope);
                            currentNamesapceCount++;
                        }

                        if ((sinkArray.Count != namespaceArray.Count) || (connectArray.Count != namespaceArray.Count)) // not expected throw exception
                        {
                            internalException = new InvalidOperationException();
                            _state = WmiState.Failed;
                            RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                            return;
                        }

                        currentNamesapceCount = 0;
                        while (currentNamesapceCount < namespaceArray.Count)
                        {
                            string connectNamespace = (string)namespaceArray[currentNamesapceCount];
                            ManagementObjectSearcher searcher = getObject.GetObjectList((ManagementScope)connectArray[currentNamesapceCount]);
                            if (searcher == null)
                            {
                                currentNamesapceCount++;
                                continue;
                            }
                            if (topNamespace)
                            {
                                topNamespace = false;
                                searcher.Get(_results);
                            }
                            else
                            {
                                searcher.Get((ManagementOperationObserver)sinkArray[currentNamesapceCount]);
                            }
                            currentNamesapceCount++;
                        }
                    }
                    else
                    {
                        ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, getObject.Namespace), options);
                        scope.Connect();
                        ManagementObjectSearcher searcher = getObject.GetObjectList(scope);
                        if (searcher == null)
                            throw new ManagementException();
                        searcher.Get(_results);
                    }
                }
                catch (ManagementException e)
                {
                    internalException = e;
                    _state = WmiState.Failed;
                    RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                }
                catch (System.Runtime.InteropServices.COMException e)
                {
                    internalException = e;
                    _state = WmiState.Failed;
                    RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                }
                catch (System.UnauthorizedAccessException e)
                {
                    internalException = e;
                    _state = WmiState.Failed;
                    RaiseOperationCompleteEvent(null, OperationState.StopComplete);
                }
                return;
            }
            string queryString = string.IsNullOrEmpty(getObject.Query) ? GetWmiQueryString() : getObject.Query;
            ObjectQuery query = new ObjectQuery(queryString.ToString());
            try
            {
                ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, getObject.Namespace), options);
                EnumerationOptions enumOptions = new EnumerationOptions();
                enumOptions.UseAmendedQualifiers = getObject.Amended;
                enumOptions.DirectRead = getObject.DirectRead;
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query, enumOptions);

                // Execute the WMI command for each count value.
                for (int i = 0; i < _cmdCount; ++i)
                {
                    searcher.Get(_results);
                }
            }
            catch (ManagementException e)
            {
                internalException = e;
                _state = WmiState.Failed;
                RaiseOperationCompleteEvent(null, OperationState.StopComplete);
            }
            catch (System.Runtime.InteropServices.COMException e)
            {
                internalException = e;
                _state = WmiState.Failed;
                RaiseOperationCompleteEvent(null, OperationState.StopComplete);
            }
            catch (System.UnauthorizedAccessException e)
            {
                internalException = e;
                _state = WmiState.Failed;
                RaiseOperationCompleteEvent(null, OperationState.StopComplete);
            }
        }
Ejemplo n.º 26
0
        }//Get()

        //********************************************
        //Get() asynchronous
        //********************************************
        /// <summary>
        ///    <para>Invokes the WMI query, asynchronously, and binds to a watcher to deliver the results.</para>
        /// </summary>
        /// <param name='watcher'>The watcher that raises events triggered by the operation. </param>
        public void Get(ManagementOperationObserver watcher)
        {
            if (null == watcher)
            {
                throw new ArgumentNullException("watcher");
            }

            Initialize();
            IWbemServices wbemServices = scope.GetIWbemServices();

            EnumerationOptions enumOptions = (EnumerationOptions)options.Clone();

            // Ensure we switch off ReturnImmediately as this is invalid for async calls
            enumOptions.ReturnImmediately = false;
            // If someone has registered for progress, make sure we flag it
            if (watcher.HaveListenersForProgress)
            {
                enumOptions.SendStatus = true;
            }

            WmiEventSink    sink            = watcher.GetNewSink(scope, enumOptions.Context);
            SecurityHandler securityHandler = scope.GetSecurityHandler();

            int status = (int)ManagementStatus.NoError;

            try
            {
                //If this is a simple SelectQuery (className only), and the enumerateDeep is set, we have
                //to find out whether this is a class enumeration or instance enumeration and call CreateInstanceEnum/
                //CreateClassEnum appropriately, because with ExecQuery we can't do a deep enumeration.
                if ((query.GetType() == typeof(SelectQuery)) &&
                    (((SelectQuery)query).Condition == null) &&
                    (((SelectQuery)query).SelectedProperties == null) &&
                    (options.EnumerateDeep == true))
                {
                    //Need to make sure that we're not passing invalid flags to enumeration APIs.
                    //The only flags not valid for enumerations are EnsureLocatable & PrototypeOnly.
                    enumOptions.EnsureLocatable = false; enumOptions.PrototypeOnly = false;

                    if (((SelectQuery)query).IsSchemaQuery == false) //deep instance enumeration
                    {
                        status = scope.GetSecuredIWbemServicesHandler(wbemServices).CreateInstanceEnumAsync_(((SelectQuery)query).ClassName,
                                                                                                             enumOptions.Flags,
                                                                                                             enumOptions.GetContext(),
                                                                                                             sink.Stub);
                    }
                    else
                    {
                        status = scope.GetSecuredIWbemServicesHandler(wbemServices).CreateClassEnumAsync_(((SelectQuery)query).ClassName,
                                                                                                          enumOptions.Flags,
                                                                                                          enumOptions.GetContext(),
                                                                                                          sink.Stub);
                    }
                }
                else //we can use ExecQuery
                {
                    //Make sure the EnumerateDeep flag bit is turned off because it's invalid for queries
                    enumOptions.EnumerateDeep = true;
                    status = scope.GetSecuredIWbemServicesHandler(wbemServices).ExecQueryAsync_(
                        query.QueryLanguage,
                        query.QueryString,
                        enumOptions.Flags,
                        enumOptions.GetContext(),
                        sink.Stub);
                }
            }
            catch (COMException e)
            {
                //
                watcher.RemoveSink(sink);
                ManagementException.ThrowWithExtendedInfo(e);
            }
            finally
            {
                securityHandler.Reset();
            }

            if ((status & 0xfffff000) == 0x80041000)
            {
                ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
            }
            else if ((status & 0x80000000) != 0)
            {
                Marshal.ThrowExceptionForHR(status);
            }
        }
Ejemplo n.º 27
0
 public void GetRelationshipClasses(ManagementOperationObserver watcher, string relationshipClass, string relationshipQualifier, string thisRole, EnumerationOptions options)
 {
     throw new NotImplementedException();
 }
 public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions)
 {
     if ((mgmtScope == null)) {
         if ((statMgmtScope == null)) {
             mgmtScope = new System.Management.ManagementScope();
             mgmtScope.Path.NamespacePath = "root\\virtualization";
         }
         else {
             mgmtScope = statMgmtScope;
         }
     }
     System.Management.ManagementPath pathObj = new System.Management.ManagementPath();
     pathObj.ClassName = "Msvm_SyntheticEthernetPortSettingData";
     pathObj.NamespacePath = "root\\virtualization";
     System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null);
     if ((enumOptions == null)) {
         enumOptions = new System.Management.EnumerationOptions();
         enumOptions.EnsureLocatable = true;
     }
     return new SyntheticEthernetPortSettingDataCollection(clsObject.GetInstances(enumOptions));
 }
Ejemplo n.º 29
0
 public void GetSubclasses(ManagementOperationObserver watcher, EnumerationOptions options)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 30
0
 private void InitializeComponent()
 {
     System.Management.EnumerationOptions enumerationOptions1 = new System.Management.EnumerationOptions();
     this.Search                               = new System.Management.ManagementObjectSearcher();
     this.sourceCodeTextBox                    = new System.Windows.Forms.TextBox();
     this.menuStrip                            = new System.Windows.Forms.MenuStrip();
     this.systemInfoToolStripMenuItem          = new System.Windows.Forms.ToolStripMenuItem();
     this.pCNAMEToolStripMenuItem              = new System.Windows.Forms.ToolStripMenuItem();
     this.rAMToolStripMenuItem                 = new System.Windows.Forms.ToolStripMenuItem();
     this.openFileDialog                       = new System.Windows.Forms.OpenFileDialog();
     this.saveFileDialog                       = new System.Windows.Forms.SaveFileDialog();
     this.cyclomaticButton                     = new System.Windows.Forms.Button();
     this.cyclomaticComplexityLabel            = new System.Windows.Forms.Label();
     this.analyseHalsteadButton                = new System.Windows.Forms.Button();
     this.totalNumberOfOperatorsLabel          = new System.Windows.Forms.Label();
     this.numberOfDistinctOperatorsLabel       = new System.Windows.Forms.Label();
     this.totalNumberOfOperandsLabel           = new System.Windows.Forms.Label();
     this.numberOfDistinctOperandsLabel        = new System.Windows.Forms.Label();
     this.theoreticalProgramVocabularyLabel    = new System.Windows.Forms.Label();
     this.theoreticalProgramLengthLabel        = new System.Windows.Forms.Label();
     this.theoreticalProgramVolumeLabel        = new System.Windows.Forms.Label();
     this.levelOfProgrammingQualityLabel       = new System.Windows.Forms.Label();
     this.MIDDLE_GP                            = new System.Windows.Forms.GroupBox();
     this.HAL_GP                               = new System.Windows.Forms.GroupBox();
     this.numberOfElementarySolutionsForULabel = new System.Windows.Forms.Label();
     this.numberOfElementarySolutionsForWLabel = new System.Windows.Forms.Label();
     this.levelOfProgramQualityWithoutTPVLabel = new System.Windows.Forms.Label();
     this.programVocabularyLabel               = new System.Windows.Forms.Label();
     this.programLengthLabel                   = new System.Windows.Forms.Label();
     this.programVolumeLabel                   = new System.Windows.Forms.Label();
     this.TLP_Main                             = new System.Windows.Forms.TableLayoutPanel();
     this.TLP_Metrics                          = new System.Windows.Forms.TableLayoutPanel();
     this.maintainabilityIndexButton           = new System.Windows.Forms.Button();
     this.TOP_GP                               = new System.Windows.Forms.GroupBox();
     this.indexOfCodeMaintainability           = new System.Windows.Forms.Label();
     this.menuStrip.SuspendLayout();
     this.MIDDLE_GP.SuspendLayout();
     this.HAL_GP.SuspendLayout();
     this.TLP_Main.SuspendLayout();
     this.TLP_Metrics.SuspendLayout();
     this.TOP_GP.SuspendLayout();
     this.SuspendLayout();
     //
     // Search
     //
     enumerationOptions1.BlockSize            = 1;
     enumerationOptions1.DirectRead           = false;
     enumerationOptions1.EnsureLocatable      = false;
     enumerationOptions1.EnumerateDeep        = false;
     enumerationOptions1.PrototypeOnly        = false;
     enumerationOptions1.ReturnImmediately    = true;
     enumerationOptions1.Rewindable           = true;
     enumerationOptions1.Timeout              = System.TimeSpan.Parse("10675199.02:48:05.4775807");
     enumerationOptions1.UseAmendedQualifiers = false;
     this.Search.Options = enumerationOptions1;
     this.Search.Query   = new System.Management.ObjectQuery("Select * From Win32_ComputerSystem");
     this.Search.Scope   = new System.Management.ManagementScope("\\\\.\\root\\cimv2");
     //
     // sourceCodeTextBox
     //
     this.sourceCodeTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None;
     this.sourceCodeTextBox.Dock        = System.Windows.Forms.DockStyle.Fill;
     this.sourceCodeTextBox.Font        = new System.Drawing.Font("Consolas", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.sourceCodeTextBox.Location    = new System.Drawing.Point(1009, 0);
     this.sourceCodeTextBox.Margin      = new System.Windows.Forms.Padding(0);
     this.sourceCodeTextBox.MaxLength   = 2147483647;
     this.sourceCodeTextBox.MinimumSize = new System.Drawing.Size(533, 0);
     this.sourceCodeTextBox.Multiline   = true;
     this.sourceCodeTextBox.Name        = "sourceCodeTextBox";
     this.TLP_Main.SetRowSpan(this.sourceCodeTextBox, 4);
     this.sourceCodeTextBox.ScrollBars   = System.Windows.Forms.ScrollBars.Both;
     this.sourceCodeTextBox.Size         = new System.Drawing.Size(726, 761);
     this.sourceCodeTextBox.TabIndex     = 1;
     this.sourceCodeTextBox.WordWrap     = false;
     this.sourceCodeTextBox.TextChanged += new System.EventHandler(this.sourceCodeTextBox_TextChanged);
     this.sourceCodeTextBox.DoubleClick += new System.EventHandler(this.sourceCodeTextBox_DoubleClick);
     //
     // menuStrip
     //
     this.menuStrip.BackColor        = System.Drawing.SystemColors.Window;
     this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
     this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
         this.systemInfoToolStripMenuItem
     });
     this.menuStrip.Location   = new System.Drawing.Point(0, 0);
     this.menuStrip.Name       = "menuStrip";
     this.menuStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
     this.menuStrip.Size       = new System.Drawing.Size(1735, 28);
     this.menuStrip.TabIndex   = 2;
     this.menuStrip.Text       = "File";
     //
     // systemInfoToolStripMenuItem
     //
     this.systemInfoToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
         this.pCNAMEToolStripMenuItem,
         this.rAMToolStripMenuItem
     });
     this.systemInfoToolStripMenuItem.Name = "systemInfoToolStripMenuItem";
     this.systemInfoToolStripMenuItem.Size = new System.Drawing.Size(100, 24);
     this.systemInfoToolStripMenuItem.Text = "System Info";
     //
     // pCNAMEToolStripMenuItem
     //
     this.pCNAMEToolStripMenuItem.Name = "pCNAMEToolStripMenuItem";
     this.pCNAMEToolStripMenuItem.Size = new System.Drawing.Size(480, 26);
     this.pCNAMEToolStripMenuItem.Text = "PC NAMEDESKTOP-RV30RN8";
     //
     // rAMToolStripMenuItem
     //
     this.rAMToolStripMenuItem.Name = "rAMToolStripMenuItem";
     this.rAMToolStripMenuItem.Size = new System.Drawing.Size(480, 26);
     this.rAMToolStripMenuItem.Text = "RAM Intel64 Family 6 Model 158 Stepping 10, GenuineIntel";
     //
     // cyclomaticButton
     //
     this.cyclomaticButton.Dock     = System.Windows.Forms.DockStyle.Fill;
     this.cyclomaticButton.Font     = new System.Drawing.Font("Lucida Fax", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.cyclomaticButton.Location = new System.Drawing.Point(4, 4);
     this.cyclomaticButton.Margin   = new System.Windows.Forms.Padding(4);
     this.cyclomaticButton.Name     = "cyclomaticButton";
     this.cyclomaticButton.Size     = new System.Drawing.Size(328, 70);
     this.cyclomaticButton.TabIndex = 3;
     this.cyclomaticButton.Text     = "CycloMatric Complexity";
     this.cyclomaticButton.UseVisualStyleBackColor = true;
     this.cyclomaticButton.Click += new System.EventHandler(this.mcCabeButton_Click);
     //
     // cyclomaticComplexityLabel
     //
     this.cyclomaticComplexityLabel.AutoSize = true;
     this.cyclomaticComplexityLabel.Font     = new System.Drawing.Font("Lucida Fax", 11.25F);
     this.cyclomaticComplexityLabel.Location = new System.Drawing.Point(8, 49);
     this.cyclomaticComplexityLabel.Margin   = new System.Windows.Forms.Padding(4, 0, 4, 0);
     this.cyclomaticComplexityLabel.Name     = "cyclomaticComplexityLabel";
     this.cyclomaticComplexityLabel.Size     = new System.Drawing.Size(412, 22);
     this.cyclomaticComplexityLabel.TabIndex = 4;
     this.cyclomaticComplexityLabel.Text     = "The cyclomatic complexity of a program: ";
     //
     // analyseHalsteadButton
     //
     this.analyseHalsteadButton.Dock     = System.Windows.Forms.DockStyle.Fill;
     this.analyseHalsteadButton.Font     = new System.Drawing.Font("Lucida Fax", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.analyseHalsteadButton.Location = new System.Drawing.Point(340, 4);
     this.analyseHalsteadButton.Margin   = new System.Windows.Forms.Padding(4);
     this.analyseHalsteadButton.Name     = "analyseHalsteadButton";
     this.analyseHalsteadButton.Size     = new System.Drawing.Size(328, 70);
     this.analyseHalsteadButton.TabIndex = 5;
     this.analyseHalsteadButton.Text     = "Analyse Halstead";
     this.analyseHalsteadButton.UseVisualStyleBackColor = true;
     this.analyseHalsteadButton.Click += new System.EventHandler(this.halsteadButton_Click);
     //
     // totalNumberOfOperatorsLabel
     //
     this.totalNumberOfOperatorsLabel.AutoSize = true;
     this.totalNumberOfOperatorsLabel.Font     = new System.Drawing.Font("Lucida Fax", 11.25F);
     this.totalNumberOfOperatorsLabel.Location = new System.Drawing.Point(8, 94);
     this.totalNumberOfOperatorsLabel.Margin   = new System.Windows.Forms.Padding(4, 0, 4, 0);
     this.totalNumberOfOperatorsLabel.Name     = "totalNumberOfOperatorsLabel";
     this.totalNumberOfOperatorsLabel.Size     = new System.Drawing.Size(316, 22);
     this.totalNumberOfOperatorsLabel.TabIndex = 6;
     this.totalNumberOfOperatorsLabel.Text     = "The total number of operators: ";
     //
     // numberOfDistinctOperatorsLabel
     //
     this.numberOfDistinctOperatorsLabel.AutoSize = true;
     this.numberOfDistinctOperatorsLabel.Font     = new System.Drawing.Font("Lucida Fax", 11.25F);
     this.numberOfDistinctOperatorsLabel.Location = new System.Drawing.Point(8, 32);
     this.numberOfDistinctOperatorsLabel.Margin   = new System.Windows.Forms.Padding(4, 0, 4, 0);
     this.numberOfDistinctOperatorsLabel.Name     = "numberOfDistinctOperatorsLabel";
     this.numberOfDistinctOperatorsLabel.Size     = new System.Drawing.Size(344, 22);
     this.numberOfDistinctOperatorsLabel.TabIndex = 7;
     this.numberOfDistinctOperatorsLabel.Text     = "The number of distinct operators: ";
     //
     // totalNumberOfOperandsLabel
     //
     this.totalNumberOfOperandsLabel.AutoSize = true;
     this.totalNumberOfOperandsLabel.Font     = new System.Drawing.Font("Lucida Fax", 11.25F);
     this.totalNumberOfOperandsLabel.Location = new System.Drawing.Point(8, 118);
     this.totalNumberOfOperandsLabel.Margin   = new System.Windows.Forms.Padding(4, 0, 4, 0);
     this.totalNumberOfOperandsLabel.Name     = "totalNumberOfOperandsLabel";
     this.totalNumberOfOperandsLabel.Size     = new System.Drawing.Size(306, 22);
     this.totalNumberOfOperandsLabel.TabIndex = 8;
     this.totalNumberOfOperandsLabel.Text     = "The total number of operands:";
     //
     // numberOfDistinctOperandsLabel
     //
     this.numberOfDistinctOperandsLabel.AutoSize = true;
     this.numberOfDistinctOperandsLabel.Font     = new System.Drawing.Font("Lucida Fax", 11.25F);
     this.numberOfDistinctOperandsLabel.Location = new System.Drawing.Point(8, 57);
     this.numberOfDistinctOperandsLabel.Margin   = new System.Windows.Forms.Padding(4, 0, 4, 0);
     this.numberOfDistinctOperandsLabel.Name     = "numberOfDistinctOperandsLabel";
     this.numberOfDistinctOperandsLabel.Size     = new System.Drawing.Size(340, 22);
     this.numberOfDistinctOperandsLabel.TabIndex = 9;
     this.numberOfDistinctOperandsLabel.Text     = "The number of distinct operands: ";
     //
     // theoreticalProgramVocabularyLabel
     //
     this.theoreticalProgramVocabularyLabel.AutoSize = true;
     this.theoreticalProgramVocabularyLabel.Font     = new System.Drawing.Font("Lucida Fax", 11.25F);
     this.theoreticalProgramVocabularyLabel.Location = new System.Drawing.Point(8, 241);
     this.theoreticalProgramVocabularyLabel.Margin   = new System.Windows.Forms.Padding(4, 0, 4, 0);
     this.theoreticalProgramVocabularyLabel.Name     = "theoreticalProgramVocabularyLabel";
     this.theoreticalProgramVocabularyLabel.Size     = new System.Drawing.Size(369, 22);
     this.theoreticalProgramVocabularyLabel.TabIndex = 10;
     this.theoreticalProgramVocabularyLabel.Text     = "The theoretical program vocabulary: ";
     //
     // theoreticalProgramLengthLabel
     //
     this.theoreticalProgramLengthLabel.AutoSize = true;
     this.theoreticalProgramLengthLabel.Font     = new System.Drawing.Font("Lucida Fax", 11.25F);
     this.theoreticalProgramLengthLabel.Location = new System.Drawing.Point(8, 266);
     this.theoreticalProgramLengthLabel.Margin   = new System.Windows.Forms.Padding(4, 0, 4, 0);
     this.theoreticalProgramLengthLabel.Name     = "theoreticalProgramLengthLabel";
     this.theoreticalProgramLengthLabel.Size     = new System.Drawing.Size(323, 22);
     this.theoreticalProgramLengthLabel.TabIndex = 16;
     this.theoreticalProgramLengthLabel.Text     = "The theoretical program length: ";
     //
     // theoreticalProgramVolumeLabel
     //
     this.theoreticalProgramVolumeLabel.AutoSize = true;
     this.theoreticalProgramVolumeLabel.Font     = new System.Drawing.Font("Lucida Fax", 11.25F);
     this.theoreticalProgramVolumeLabel.Location = new System.Drawing.Point(8, 290);
     this.theoreticalProgramVolumeLabel.Margin   = new System.Windows.Forms.Padding(4, 0, 4, 0);
     this.theoreticalProgramVolumeLabel.Name     = "theoreticalProgramVolumeLabel";
     this.theoreticalProgramVolumeLabel.Size     = new System.Drawing.Size(333, 22);
     this.theoreticalProgramVolumeLabel.TabIndex = 17;
     this.theoreticalProgramVolumeLabel.Text     = "The theoretical program volume: ";
     //
     // levelOfProgrammingQualityLabel
     //
     this.levelOfProgrammingQualityLabel.AutoSize = true;
     this.levelOfProgrammingQualityLabel.Font     = new System.Drawing.Font("Lucida Fax", 11.25F);
     this.levelOfProgrammingQualityLabel.Location = new System.Drawing.Point(8, 327);
     this.levelOfProgrammingQualityLabel.Margin   = new System.Windows.Forms.Padding(4, 0, 4, 0);
     this.levelOfProgrammingQualityLabel.Name     = "levelOfProgrammingQualityLabel";
     this.levelOfProgrammingQualityLabel.Size     = new System.Drawing.Size(344, 22);
     this.levelOfProgrammingQualityLabel.TabIndex = 18;
     this.levelOfProgrammingQualityLabel.Text     = "The level of programming quality: ";
     //
     // MIDDLE_GP
     //
     this.MIDDLE_GP.BackColor = System.Drawing.Color.Aqua;
     this.MIDDLE_GP.Controls.Add(this.cyclomaticComplexityLabel);
     this.MIDDLE_GP.Dock        = System.Windows.Forms.DockStyle.Fill;
     this.MIDDLE_GP.Font        = new System.Drawing.Font("Lucida Fax", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.MIDDLE_GP.ForeColor   = System.Drawing.Color.Navy;
     this.MIDDLE_GP.Location    = new System.Drawing.Point(0, 0);
     this.MIDDLE_GP.Margin      = new System.Windows.Forms.Padding(0);
     this.MIDDLE_GP.MaximumSize = new System.Drawing.Size(1009, 107);
     this.MIDDLE_GP.Name        = "MIDDLE_GP";
     this.MIDDLE_GP.Padding     = new System.Windows.Forms.Padding(4);
     this.MIDDLE_GP.Size        = new System.Drawing.Size(1009, 107);
     this.MIDDLE_GP.TabIndex    = 22;
     this.MIDDLE_GP.TabStop     = false;
     this.MIDDLE_GP.Text        = "CycloMatric Complexity:";
     this.MIDDLE_GP.Enter      += new System.EventHandler(this.GB_MCM_Enter);
     //
     // HAL_GP
     //
     this.HAL_GP.BackColor = System.Drawing.Color.Aqua;
     this.HAL_GP.Controls.Add(this.numberOfDistinctOperatorsLabel);
     this.HAL_GP.Controls.Add(this.totalNumberOfOperatorsLabel);
     this.HAL_GP.Controls.Add(this.numberOfElementarySolutionsForULabel);
     this.HAL_GP.Controls.Add(this.totalNumberOfOperandsLabel);
     this.HAL_GP.Controls.Add(this.numberOfElementarySolutionsForWLabel);
     this.HAL_GP.Controls.Add(this.numberOfDistinctOperandsLabel);
     this.HAL_GP.Controls.Add(this.levelOfProgramQualityWithoutTPVLabel);
     this.HAL_GP.Controls.Add(this.theoreticalProgramVocabularyLabel);
     this.HAL_GP.Controls.Add(this.levelOfProgrammingQualityLabel);
     this.HAL_GP.Controls.Add(this.programVocabularyLabel);
     this.HAL_GP.Controls.Add(this.theoreticalProgramVolumeLabel);
     this.HAL_GP.Controls.Add(this.programLengthLabel);
     this.HAL_GP.Controls.Add(this.theoreticalProgramLengthLabel);
     this.HAL_GP.Controls.Add(this.programVolumeLabel);
     this.HAL_GP.Dock        = System.Windows.Forms.DockStyle.Fill;
     this.HAL_GP.Font        = new System.Drawing.Font("Lucida Fax", 14.25F);
     this.HAL_GP.ForeColor   = System.Drawing.Color.Navy;
     this.HAL_GP.Location    = new System.Drawing.Point(0, 107);
     this.HAL_GP.Margin      = new System.Windows.Forms.Padding(0);
     this.HAL_GP.MaximumSize = new System.Drawing.Size(1009, 468);
     this.HAL_GP.Name        = "HAL_GP";
     this.HAL_GP.Padding     = new System.Windows.Forms.Padding(4);
     this.HAL_GP.Size        = new System.Drawing.Size(1009, 468);
     this.HAL_GP.TabIndex    = 23;
     this.HAL_GP.TabStop     = false;
     this.HAL_GP.Text        = "Analyse Halstead :";
     this.HAL_GP.Enter      += new System.EventHandler(this.GB_HM_Enter);
     //
     // numberOfElementarySolutionsForULabel
     //
     this.numberOfElementarySolutionsForULabel.AutoSize = true;
     this.numberOfElementarySolutionsForULabel.Font     = new System.Drawing.Font("Lucida Fax", 11.25F);
     this.numberOfElementarySolutionsForULabel.Location = new System.Drawing.Point(8, 414);
     this.numberOfElementarySolutionsForULabel.Margin   = new System.Windows.Forms.Padding(4, 0, 4, 0);
     this.numberOfElementarySolutionsForULabel.Name     = "numberOfElementarySolutionsForULabel";
     this.numberOfElementarySolutionsForULabel.Size     = new System.Drawing.Size(769, 22);
     this.numberOfElementarySolutionsForULabel.TabIndex = 21;
     this.numberOfElementarySolutionsForULabel.Text     = "The number of required elementary solutions for understanding the program: ";
     //
     // numberOfElementarySolutionsForWLabel
     //
     this.numberOfElementarySolutionsForWLabel.AutoSize = true;
     this.numberOfElementarySolutionsForWLabel.Font     = new System.Drawing.Font("Lucida Fax", 11.25F);
     this.numberOfElementarySolutionsForWLabel.Location = new System.Drawing.Point(8, 389);
     this.numberOfElementarySolutionsForWLabel.Margin   = new System.Windows.Forms.Padding(4, 0, 4, 0);
     this.numberOfElementarySolutionsForWLabel.Name     = "numberOfElementarySolutionsForWLabel";
     this.numberOfElementarySolutionsForWLabel.Size     = new System.Drawing.Size(678, 22);
     this.numberOfElementarySolutionsForWLabel.TabIndex = 20;
     this.numberOfElementarySolutionsForWLabel.Text     = "The number of required elementary solutions for writing a program: ";
     //
     // levelOfProgramQualityWithoutTPVLabel
     //
     this.levelOfProgramQualityWithoutTPVLabel.AutoSize = true;
     this.levelOfProgramQualityWithoutTPVLabel.Font     = new System.Drawing.Font("Lucida Fax", 11.25F);
     this.levelOfProgramQualityWithoutTPVLabel.Location = new System.Drawing.Point(8, 352);
     this.levelOfProgramQualityWithoutTPVLabel.Margin   = new System.Windows.Forms.Padding(4, 0, 4, 0);
     this.levelOfProgramQualityWithoutTPVLabel.Name     = "levelOfProgramQualityWithoutTPVLabel";
     this.levelOfProgramQualityWithoutTPVLabel.Size     = new System.Drawing.Size(700, 22);
     this.levelOfProgramQualityWithoutTPVLabel.TabIndex = 19;
     this.levelOfProgramQualityWithoutTPVLabel.Text     = "The level of programming quality without theoretical program volume: ";
     //
     // programVocabularyLabel
     //
     this.programVocabularyLabel.AutoSize = true;
     this.programVocabularyLabel.Font     = new System.Drawing.Font("Lucida Fax", 11.25F);
     this.programVocabularyLabel.Location = new System.Drawing.Point(8, 155);
     this.programVocabularyLabel.Margin   = new System.Windows.Forms.Padding(4, 0, 4, 0);
     this.programVocabularyLabel.Name     = "programVocabularyLabel";
     this.programVocabularyLabel.Size     = new System.Drawing.Size(259, 22);
     this.programVocabularyLabel.TabIndex = 11;
     this.programVocabularyLabel.Text     = "The program vocabulary: ";
     //
     // programLengthLabel
     //
     this.programLengthLabel.AutoSize = true;
     this.programLengthLabel.Font     = new System.Drawing.Font("Lucida Fax", 11.25F);
     this.programLengthLabel.Location = new System.Drawing.Point(8, 180);
     this.programLengthLabel.Margin   = new System.Windows.Forms.Padding(4, 0, 4, 0);
     this.programLengthLabel.Name     = "programLengthLabel";
     this.programLengthLabel.Size     = new System.Drawing.Size(213, 22);
     this.programLengthLabel.TabIndex = 12;
     this.programLengthLabel.Text     = "The program length: ";
     //
     // programVolumeLabel
     //
     this.programVolumeLabel.AutoSize = true;
     this.programVolumeLabel.Font     = new System.Drawing.Font("Lucida Fax", 11.25F);
     this.programVolumeLabel.Location = new System.Drawing.Point(8, 204);
     this.programVolumeLabel.Margin   = new System.Windows.Forms.Padding(4, 0, 4, 0);
     this.programVolumeLabel.Name     = "programVolumeLabel";
     this.programVolumeLabel.Size     = new System.Drawing.Size(223, 22);
     this.programVolumeLabel.TabIndex = 13;
     this.programVolumeLabel.Text     = "The program volume: ";
     //
     // TLP_Main
     //
     this.TLP_Main.BackColor   = System.Drawing.SystemColors.ControlLight;
     this.TLP_Main.ColumnCount = 2;
     this.TLP_Main.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 1009F));
     this.TLP_Main.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
     this.TLP_Main.Controls.Add(this.TLP_Metrics, 0, 3);
     this.TLP_Main.Controls.Add(this.TOP_GP, 0, 2);
     this.TLP_Main.Controls.Add(this.sourceCodeTextBox, 1, 0);
     this.TLP_Main.Controls.Add(this.HAL_GP, 0, 1);
     this.TLP_Main.Controls.Add(this.MIDDLE_GP, 0, 0);
     this.TLP_Main.Dock     = System.Windows.Forms.DockStyle.Fill;
     this.TLP_Main.Location = new System.Drawing.Point(0, 28);
     this.TLP_Main.Margin   = new System.Windows.Forms.Padding(4);
     this.TLP_Main.Name     = "TLP_Main";
     this.TLP_Main.RowCount = 4;
     this.TLP_Main.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 107F));
     this.TLP_Main.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 468F));
     this.TLP_Main.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 107F));
     this.TLP_Main.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
     this.TLP_Main.Size     = new System.Drawing.Size(1735, 761);
     this.TLP_Main.TabIndex = 24;
     //
     // TLP_Metrics
     //
     this.TLP_Metrics.BackColor   = System.Drawing.SystemColors.Window;
     this.TLP_Metrics.ColumnCount = 3;
     this.TLP_Metrics.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
     this.TLP_Metrics.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
     this.TLP_Metrics.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
     this.TLP_Metrics.Controls.Add(this.cyclomaticButton, 0, 0);
     this.TLP_Metrics.Controls.Add(this.analyseHalsteadButton, 1, 0);
     this.TLP_Metrics.Controls.Add(this.maintainabilityIndexButton, 2, 0);
     this.TLP_Metrics.Dock        = System.Windows.Forms.DockStyle.Bottom;
     this.TLP_Metrics.Location    = new System.Drawing.Point(0, 683);
     this.TLP_Metrics.Margin      = new System.Windows.Forms.Padding(0);
     this.TLP_Metrics.MaximumSize = new System.Drawing.Size(1009, 78);
     this.TLP_Metrics.Name        = "TLP_Metrics";
     this.TLP_Metrics.RowCount    = 1;
     this.TLP_Metrics.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
     this.TLP_Metrics.Size     = new System.Drawing.Size(1009, 78);
     this.TLP_Metrics.TabIndex = 25;
     //
     // maintainabilityIndexButton
     //
     this.maintainabilityIndexButton.Dock     = System.Windows.Forms.DockStyle.Fill;
     this.maintainabilityIndexButton.Font     = new System.Drawing.Font("Lucida Fax", 14.25F);
     this.maintainabilityIndexButton.Location = new System.Drawing.Point(676, 4);
     this.maintainabilityIndexButton.Margin   = new System.Windows.Forms.Padding(4);
     this.maintainabilityIndexButton.Name     = "maintainabilityIndexButton";
     this.maintainabilityIndexButton.Size     = new System.Drawing.Size(329, 70);
     this.maintainabilityIndexButton.TabIndex = 6;
     this.maintainabilityIndexButton.Text     = "Maintainability Index";
     this.maintainabilityIndexButton.UseVisualStyleBackColor = true;
     this.maintainabilityIndexButton.Click += new System.EventHandler(this.maintainabilityIndexButton_Click);
     //
     // TOP_GP
     //
     this.TOP_GP.BackColor = System.Drawing.Color.Aqua;
     this.TOP_GP.Controls.Add(this.indexOfCodeMaintainability);
     this.TOP_GP.Dock        = System.Windows.Forms.DockStyle.Fill;
     this.TOP_GP.Font        = new System.Drawing.Font("Lucida Fax", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.TOP_GP.ForeColor   = System.Drawing.Color.Navy;
     this.TOP_GP.Location    = new System.Drawing.Point(0, 575);
     this.TOP_GP.Margin      = new System.Windows.Forms.Padding(0);
     this.TOP_GP.MaximumSize = new System.Drawing.Size(1009, 107);
     this.TOP_GP.Name        = "TOP_GP";
     this.TOP_GP.Padding     = new System.Windows.Forms.Padding(4);
     this.TOP_GP.Size        = new System.Drawing.Size(1009, 107);
     this.TOP_GP.TabIndex    = 25;
     this.TOP_GP.TabStop     = false;
     this.TOP_GP.Text        = "Code maintainability:";
     //
     // indexOfCodeMaintainability
     //
     this.indexOfCodeMaintainability.AutoSize = true;
     this.indexOfCodeMaintainability.Font     = new System.Drawing.Font("Lucida Fax", 11.25F);
     this.indexOfCodeMaintainability.Location = new System.Drawing.Point(8, 49);
     this.indexOfCodeMaintainability.Margin   = new System.Windows.Forms.Padding(4, 0, 4, 0);
     this.indexOfCodeMaintainability.Name     = "indexOfCodeMaintainability";
     this.indexOfCodeMaintainability.Size     = new System.Drawing.Size(346, 22);
     this.indexOfCodeMaintainability.TabIndex = 4;
     this.indexOfCodeMaintainability.Text     = "The index of code maintainability: ";
     //
     // StaticCodeAnalyser
     //
     this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
     this.AutoScaleMode       = System.Windows.Forms.AutoScaleMode.Font;
     this.ClientSize          = new System.Drawing.Size(1735, 789);
     this.Controls.Add(this.TLP_Main);
     this.Controls.Add(this.menuStrip);
     this.MainMenuStrip = this.menuStrip;
     this.Margin        = new System.Windows.Forms.Padding(4);
     this.MinimumSize   = new System.Drawing.Size(1537, 826);
     this.Name          = "StaticCodeAnalyser";
     this.ShowIcon      = false;
     this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
     this.Text          = "Static Code Analyser";
     this.Load         += new System.EventHandler(this.CodeAnalyser_Load);
     this.menuStrip.ResumeLayout(false);
     this.menuStrip.PerformLayout();
     this.MIDDLE_GP.ResumeLayout(false);
     this.MIDDLE_GP.PerformLayout();
     this.HAL_GP.ResumeLayout(false);
     this.HAL_GP.PerformLayout();
     this.TLP_Main.ResumeLayout(false);
     this.TLP_Main.PerformLayout();
     this.TLP_Metrics.ResumeLayout(false);
     this.TOP_GP.ResumeLayout(false);
     this.TOP_GP.PerformLayout();
     this.ResumeLayout(false);
     this.PerformLayout();
 }
Ejemplo n.º 31
0
 public ManagementObjectSearcher(ManagementScope scope, ObjectQuery query, EnumerationOptions options)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 32
0
 public ManagementObjectSearcher(string scope, string queryString, EnumerationOptions options) : this(new ManagementScope(scope), new ObjectQuery(queryString), options)
 {
 }
Ejemplo n.º 33
0
        /// <summary>
        /// ProcessRecord method.
        /// </summary>
        protected override void ProcessRecord()
        {
            // If both LocalCred and DomainCred are not provided, we use the default options
            ConnectionOptions options = new ConnectionOptions
            {
                Authentication = AuthenticationLevel.PacketPrivacy,
                Impersonation = ImpersonationLevel.Impersonate,
                EnablePrivileges = true
            };

            // For Remove-Computer, usually the domain credential is also the local admin credential
            // for the target computer. So use the local credential if given, otherwise use the domain
            // credential to connect to the target machine.
            // If the LocalCred is not given but the DomainCred is available, use the DomainCred for WMI connection.
            if (LocalCredential == null && UnjoinDomainCredential != null)
            {
                options.SecurePassword = UnjoinDomainCredential.Password;
                options.Username = UnjoinDomainCredential.UserName;
            }

            EnumerationOptions enumOptions = new EnumerationOptions { UseAmendedQualifiers = true, DirectRead = true };
            ObjectQuery computerSystemQuery = new ObjectQuery("select * from " + ComputerWMIHelper.WMI_Class_ComputerSystem);

            foreach (string computer in ComputerName)
            {
                string targetComputer = ValidateComputerName(computer);
                if (targetComputer == null)
                {
                    continue;
                }

                bool isLocalhost = targetComputer.Equals("localhost", StringComparison.OrdinalIgnoreCase);
                if (isLocalhost)
                {
                    if (!_containsLocalHost)
                        _containsLocalHost = true;

                    continue;
                }

                DoRemoveComputerAction(computer, false, options, enumOptions, computerSystemQuery);
            }
        }//End ProcessRecord()
Ejemplo n.º 34
0
 public ManagementObjectCollection GetSubclasses(EnumerationOptions options)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 35
0
        }//End ProcessRecord()

        /// <summary>
        /// EndProcessing method: deal with the local computer in the end
        /// </summary>
        protected override void EndProcessing()
        {
            if (!_containsLocalHost) return;

            // If both LocalCred and DomainCred are not provided, we use the default options
            ConnectionOptions options = new ConnectionOptions
            {
                Authentication = AuthenticationLevel.PacketPrivacy,
                Impersonation = ImpersonationLevel.Impersonate,
                EnablePrivileges = true
            };

            // For Remove-Computer, usually the domain credential is also the local admin credential
            // for the target computer. So use the local credential if given, otherwise use the domain
            // credential to connect to the target machine.
            // If the LocalCred is not given but the DomainCred is available, use the DomainCred for WMI connection.
            if (LocalCredential == null && UnjoinDomainCredential != null)
            {
                options.SecurePassword = UnjoinDomainCredential.Password;
                options.Username = UnjoinDomainCredential.UserName;
            }

            EnumerationOptions enumOptions = new EnumerationOptions { UseAmendedQualifiers = true, DirectRead = true };
            ObjectQuery computerSystemQuery = new ObjectQuery("select * from " + ComputerWMIHelper.WMI_Class_ComputerSystem);

            DoRemoveComputerAction("localhost", true, options, enumOptions, computerSystemQuery);
        }
Ejemplo n.º 36
0
        private string setNewLastPosition(ManagementScope scope, EnumerationOptions opt)
        {
            L.Log(LogType.FILE, LogLevel.INFORM, "setNewLastPosition()| Start: Oldfirst_position:" + first_position);
            Int64 lPosition = 0;
            SelectQuery query = null;
            try
            {

                string sWhereClause = "";
                ValidateMe();
                EventLog ev;
                if (remote_host == "")
                    ev = new EventLog(location);
                else
                    ev = new EventLog(location, remote_host);

                string sTarih = ManagementDateTimeConverter.ToDmtfDateTime(DateTime.Now.AddHours(-2));

                if (EventIDToFilter == "")
                {
                    query = new SelectQuery("select CategoryString,ComputerName, EventIdentifier,Type,Message,RecordNumber,SourceName," +
                        "TimeGenerated,User from Win32_NtLogEvent where Logfile ='" + location + "' AND TimeGenerated>'" + sTarih + "'");

                }
                else
                {
                    string[] EventIDArr = EventIDToFilter.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    string FilterText = "";

                    if (EventIDArr.Length < 2)
                    {
                        FilterText = "EventIdentifier <> " + EventIDArr[0];
                    }
                    else
                    {
                        FilterText = "EventIdentifier <> " + EventIDArr[0] + " and ";
                        for (int f = 0; f < EventIDArr.Length - 2; f++)
                        {
                            FilterText += "EventIdentifier <> " + EventIDArr[f] + " and ";
                        }
                        FilterText += "EventIdentifier <> " + EventIDArr[EventIDArr.Length - 1];
                    }
                    query = new SelectQuery("select CategoryString,ComputerName, EventIdentifier,Type,Message,RecordNumber,SourceName," +
                        "TimeGenerated,User from Win32_NtLogEvent where " + FilterText + " and Logfile ='" +
                        location + "' AND TimeGenerated>'" + sTarih + "'");
                }

                L.Log(LogType.FILE, LogLevel.DEBUG, "setNewLastPosition()| query:" + query.QueryString);

                List<ManagementObject> moList = new List<ManagementObject>();
                opt.Timeout = System.TimeSpan.MaxValue;

                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query, opt))
                {

                    //Int32 count = ev.Entries.Count;
                    foreach (ManagementObject mObject in searcher.Get())
                    {
                        lPosition = Convert.ToInt64(mObject["RecordNumber"]);
                        L.Log(LogType.FILE, LogLevel.DEBUG, "setNewLastPosition()| :lPosition" + lPosition);
                        if (fromend == 0)
                        {
                            L.Log(LogType.FILE, LogLevel.DEBUG, "setNewLastPosition()| fromend==1:lPosition" + lPosition);
                            lPosition = lPosition - ev.Entries.Count;
                        }
                        break;
                    }
                }

            }
            catch (Exception exp)
            {
                L.Log(LogType.FILE, LogLevel.ERROR, "setNewLastPosition()| " + exp.Message);
                L.Log(LogType.FILE, LogLevel.ERROR, "setNewLastPosition()| query:" + query.QueryString);
                return "0";
            }

            L.Log(LogType.FILE, LogLevel.DEBUG, "setNewLastPosition()| End :lPosition:" + lPosition.ToString());
            return lPosition.ToString();
        }
 public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties)
 {
     if ((mgmtScope == null)) {
         if ((statMgmtScope == null)) {
             mgmtScope = new System.Management.ManagementScope();
             mgmtScope.Path.NamespacePath = "root\\virtualization";
         }
         else {
             mgmtScope = statMgmtScope;
         }
     }
     System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_SyntheticEthernetPortSettingData", condition, selectedProperties));
     System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions();
     enumOptions.EnsureLocatable = true;
     ObjectSearcher.Options = enumOptions;
     return new SyntheticEthernetPortSettingDataCollection(ObjectSearcher.Get());
 }
Ejemplo n.º 38
0
        public ManagementObjectCollection GetRelationshipClasses(string relationshipClass, string relationshipQualifier, string thisRole, EnumerationOptions options)
        {
            if (((this.Path == null) || (this.Path.Path == null)) || (this.Path.Path.Length == 0))
            {
                throw new InvalidOperationException();
            }
            this.Initialize(false);
            IEnumWbemClassObject ppEnum   = null;
            EnumerationOptions   options2 = (options != null) ? options : new EnumerationOptions();

            options2.EnumerateDeep = true;
            RelationshipQuery query           = new RelationshipQuery(true, this.Path.Path, relationshipClass, relationshipQualifier, thisRole);
            SecurityHandler   securityHandler = null;
            int errorCode = 0;

            try
            {
                securityHandler = base.Scope.GetSecurityHandler();
                errorCode       = base.scope.GetSecuredIWbemServicesHandler(base.Scope.GetIWbemServices()).ExecQuery_(query.QueryLanguage, query.QueryString, options2.Flags, options2.GetContext(), ref ppEnum);
            }
            finally
            {
                if (securityHandler != null)
                {
                    securityHandler.Reset();
                }
            }
            if (errorCode < 0)
            {
                if ((errorCode & 0xfffff000L) == 0x80041000L)
                {
                    ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode);
                }
                else
                {
                    Marshal.ThrowExceptionForHR(errorCode);
                }
            }
            return(new ManagementObjectCollection(base.Scope, options2, ppEnum));
        }
 public static PerfFormattedData_Counters_ProcessorInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions)
 {
     if ((mgmtScope == null)) {
         if ((statMgmtScope == null)) {
             mgmtScope = new System.Management.ManagementScope();
             mgmtScope.Path.NamespacePath = "root\\CIMV2";
         }
         else {
             mgmtScope = statMgmtScope;
         }
     }
     System.Management.ManagementPath pathObj = new System.Management.ManagementPath();
     pathObj.ClassName = "Win32_PerfFormattedData_Counters_ProcessorInformation";
     pathObj.NamespacePath = "root\\CIMV2";
     System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null);
     if ((enumOptions == null)) {
         enumOptions = new System.Management.EnumerationOptions();
         enumOptions.EnsureLocatable = true;
     }
     return new PerfFormattedData_Counters_ProcessorInformationCollection(clsObject.GetInstances(enumOptions));
 }
Ejemplo n.º 40
0
        //********************************************
        //Get()
        //********************************************
        /// <overload>
        ///    Invokes the specified WMI query and returns the resulting collection.
        /// </overload>
        /// <summary>
        ///    <para>Invokes the specified WMI query and returns the
        ///       resulting collection.</para>
        /// </summary>
        /// <returns>
        /// <para>A <see cref='System.Management.ManagementObjectCollection'/> containing the objects that match the
        ///    specified query.</para>
        /// </returns>
        public ManagementObjectCollection Get()
        {
            Initialize();
            IEnumWbemClassObject ew = null;
            SecurityHandler      securityHandler = scope.GetSecurityHandler();
            EnumerationOptions   enumOptions     = (EnumerationOptions)options.Clone();

            int status = (int)ManagementStatus.NoError;

            try
            {
                //If this is a simple SelectQuery (className only), and the enumerateDeep is set, we have
                //to find out whether this is a class enumeration or instance enumeration and call CreateInstanceEnum/
                //CreateClassEnum appropriately, because with ExecQuery we can't do a deep enumeration.
                if ((query.GetType() == typeof(SelectQuery)) &&
                    (((SelectQuery)query).Condition == null) &&
                    (((SelectQuery)query).SelectedProperties == null) &&
                    (options.EnumerateDeep == true))
                {
                    //Need to make sure that we're not passing invalid flags to enumeration APIs.
                    //The only flags not valid for enumerations are EnsureLocatable & PrototypeOnly.
                    enumOptions.EnsureLocatable = false; enumOptions.PrototypeOnly = false;

                    if (((SelectQuery)query).IsSchemaQuery == false) //deep instance enumeration
                    {
                        status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).CreateInstanceEnum_(
                            ((SelectQuery)query).ClassName,
                            enumOptions.Flags,
                            enumOptions.GetContext(),
                            ref ew);
                    }
                    else //deep class enumeration
                    {
                        status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).CreateClassEnum_(((SelectQuery)query).ClassName,
                                                                                                                 enumOptions.Flags,
                                                                                                                 enumOptions.GetContext(),
                                                                                                                 ref ew);
                    }
                }
                else //we can use ExecQuery
                {
                    //Make sure the EnumerateDeep flag bit is turned off because it's invalid for queries
                    enumOptions.EnumerateDeep = true;
                    status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices()).ExecQuery_(
                        query.QueryLanguage,
                        query.QueryString,
                        enumOptions.Flags,
                        enumOptions.GetContext(),
                        ref ew);
                }
            }
            catch (COMException e)
            {
                //
                ManagementException.ThrowWithExtendedInfo(e);
            }
            finally
            {
                securityHandler.Reset();
            }

            if ((status & 0xfffff000) == 0x80041000)
            {
                ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
            }
            else if ((status & 0x80000000) != 0)
            {
                Marshal.ThrowExceptionForHR(status);
            }

            //Create a new collection object for the results

            return(new ManagementObjectCollection(scope, options, ew));
        }//Get()
Ejemplo n.º 41
0
        private void timer1_Tick(object sender, System.Timers.ElapsedEventArgs e)
        {
            timer1.Enabled = false;
            try
            {
                if (!callable.WaitOne(0))
                {
                    L.Log(LogType.FILE, LogLevel.INFORM, "timer1_Tick -- CALLED MULTIPLE TIMES STILL IN USE");
                    callable.WaitOne();
                    try
                    {
                        throw new Exception("Parse already been processed by another thread while this call has made");
                    }
                    finally
                    {
                        callable.ReleaseMutex();
                    }
                }
                try
                {
                    L.Log(LogType.FILE, LogLevel.DEBUG, "Evenlog Yeni");
                    L.Log(LogType.FILE, LogLevel.DEBUG, "Enter timer_tick1 method");
                    L.Log(LogType.FILE, LogLevel.INFORM, "Service Started");
                    if (!InitSystem())
                    {
                        return;
                    }

                    if (start_state & fromend == 1)
                    {
                        if (!Set_LastPosition())
                        {
                            L.Log(LogType.FILE, LogLevel.ERROR,
                                  "Error on setting the last position see log for more details");
                        }
                        start_state = false;
                    }

                    L.Log(LogType.FILE, LogLevel.DEBUG, "Start Connecting host:");
                    L.Log(LogType.FILE, LogLevel.DEBUG, "Remote Host :" + remote_host);
                    if (remote_host == "")
                    {
                        L.Log(LogType.FILE, LogLevel.DEBUG, "Localden Okuyor. ");
                        co = new ConnectionOptions();
                        co.Timeout = new TimeSpan(0, 10, 0);
                        co.Impersonation = ImpersonationLevel.Impersonate;
                        co.Authentication = AuthenticationLevel.PacketPrivacy;
                        scope = new ManagementScope(@"\\localhost\root\cimv2", co);
                    }
                    else
                    {
                        co = new ConnectionOptions();
                        co.Username = user;
                        co.Password = password;
                        co.Timeout = new TimeSpan(0, 10, 0);
                        co.Impersonation = ImpersonationLevel.Impersonate;
                        co.Authentication = AuthenticationLevel.PacketPrivacy;
                        scope = new ManagementScope(@"\\" + remote_host + @"\root\cimv2", co);
                    }

                    scope.Options.Impersonation = ImpersonationLevel.Impersonate;
                    scope.Connect();
                    L.Log(LogType.FILE, LogLevel.DEBUG, "Connection successfull:");

                    // default blocksize = 1, larger value may increase network throughput
                    EnumerationOptions opt = new EnumerationOptions();
                    opt.BlockSize = 1000;

                    first_position = last_position;

                    if (Convert.ToInt64(first_position) <= 0)
                    {
                        first_position = setNewLastPosition(scope, opt);
                        last_position = first_position;
                    }

                    L.Log(LogType.FILE, LogLevel.DEBUG, "first_position is :" + first_position);

                    SelectQuery query = null;
                    if (EventIDToFilter == "")
                    {
                        query =
                            new SelectQuery(
                                "select CategoryString,ComputerName, EventIdentifier,Type,Message,RecordNumber,SourceName," +
                                "TimeGenerated,User from Win32_NtLogEvent where Logfile ='" + location +
                                "' and RecordNumber >=" + first_position +
                                " and RecordNumber <" +
                                Convert.ToString(Convert.ToInt64(first_position) + max_line_towait));

                    }
                    else
                    {
                        string[] EventIDArr = EventIDToFilter.Split(",".ToCharArray(),
                                                                    StringSplitOptions.RemoveEmptyEntries);
                        string FilterText = "";

                        if (EventIDArr.Length < 2)
                        {
                            FilterText = "EventIdentifier <> " + EventIDArr[0];
                        }
                        else
                        {
                            FilterText = "EventIdentifier <> " + EventIDArr[0] + " and ";

                            for (int f = 0; f < EventIDArr.Length - 2; f++)
                            {
                                FilterText += "EventIdentifier <> " + EventIDArr[f] + " and ";
                            }
                            FilterText += "EventIdentifier <> " + EventIDArr[EventIDArr.Length - 1];

                            query =
                                new SelectQuery(
                                    "select CategoryString,ComputerName, EventIdentifier,Type,Message,RecordNumber,SourceName," +
                                    "TimeGenerated,User from Win32_NtLogEvent where " + FilterText + " and Logfile ='" +
                                    location + "' and RecordNumber >=" + first_position + " and RecordNumber <" +
                                    Convert.ToString(Convert.ToInt64(first_position) + max_line_towait));
                        }
                    }

                    L.Log(LogType.FILE, LogLevel.DEBUG, "query is :" + query.QueryString);
                    L.Log(LogType.FILE, LogLevel.DEBUG, "last position :" + last_position);

                    L.Log(LogType.FILE, LogLevel.DEBUG, "Start collection event logs of :" + location);

                    bool resetposition = true;

                    List<ManagementObject> moList = new List<ManagementObject>();

                    using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query, opt))
                    {
                        L.Log(LogType.FILE, LogLevel.DEBUG, "using ManagementObjectSearcher");

                        foreach (ManagementObject mObject in searcher.Get())
                        {
                            moList.Add(mObject);
                        }
                    }
                    L.Log(LogType.FILE, LogLevel.INFORM,
                          "Time passed to retrieve " + moList.Count + " records through WMI: ");

                    foreach (ManagementObject mo in moList)
                    {
                        resetposition = false;

                        if (Convert.ToInt64(mo["RecordNumber"]) == Convert.ToInt64(first_position))
                        {
                            L.Log(LogType.FILE, LogLevel.DEBUG, "first_position==mo[RecordNumber]:" + first_position);
                        }
                        else
                        {
                            if (!Send_Record(mo))
                            {
                                L.Log(LogType.FILE, LogLevel.DEBUG,
                                      "Error on sending record with record number" + mo["RecordNumber"].ToString());
                            }
                            if (Convert.ToInt64(last_position) < Convert.ToInt64(mo["RecordNumber"]))
                            {
                                last_position = mo["RecordNumber"].ToString();
                                L.Log(LogType.FILE, LogLevel.DEBUG, "new last_position : " + last_position.ToString());
                                string dat = mo["TimeGenerated"].ToString().Split('.')[0];
                                L.Log(LogType.FILE, LogLevel.DEBUG, "TimeGenerated1:" + dat);
                                last_recdate = dat.Substring(0, 4) + "/" + dat.Substring(4, 2) + "/" +
                                               dat.Substring(6, 2) + " " + dat.Substring(8, 2) + ":" +
                                               dat.Substring(10, 2) + ":" + dat.Substring(12, 2);
                                //+ "." + dat.Substring(14, 2);
                                last_recdate =
                                    Convert.ToDateTime(last_recdate).AddMinutes(zone).ToString("yyyy/MM/dd HH:mm:ss");
                            }
                        }
                    }

                    DateTime afterRecordsSent = DateTime.Now;
                    L.Log(LogType.FILE, LogLevel.INFORM, "Time passed to send " + moList.Count + " records to memory: ");

                    if (resetposition)
                    {
                        L.Log(LogType.FILE, LogLevel.WARN,
                              "resetposition:No data come Start Reseting the position of the log files");
                        //Set_LastPosition();
                        setNewLastPosition(scope, opt);
                    }
                    Set_Registry(last_position, last_recdate);
                }
                finally
                {
                    callable.ReleaseMutex();
                }
            }

            catch (Exception er)
            {
                L.Log(LogType.FILE, LogLevel.ERROR, er.ToString());
            }
            finally
            {
                timer1.Enabled = true;
                L.Log(LogType.FILE, LogLevel.INFORM, "Service Stopped");
                L.Log(LogType.FILE, LogLevel.DEBUG, "Exiting timer_tick1 method");
            }
        }
Ejemplo n.º 42
0
        public void GetRelationshipClasses(ManagementOperationObserver watcher, string relationshipClass, string relationshipQualifier, string thisRole, EnumerationOptions options)
        {
            EnumerationOptions enumerationOption;

            if (this.Path == null || this.Path.Path == null || this.Path.Path.Length == 0)
            {
                throw new InvalidOperationException();
            }
            else
            {
                if (watcher != null)
                {
                    this.Initialize(true);
                    if (options != null)
                    {
                        enumerationOption = (EnumerationOptions)options.Clone();
                    }
                    else
                    {
                        enumerationOption = new EnumerationOptions();
                    }
                    EnumerationOptions enumerationOption1 = enumerationOption;
                    enumerationOption1.EnumerateDeep     = true;
                    enumerationOption1.ReturnImmediately = false;
                    if (watcher.HaveListenersForProgress)
                    {
                        enumerationOption1.SendStatus = true;
                    }
                    WmiEventSink      newSink           = watcher.GetNewSink(base.Scope, enumerationOption1.Context);
                    RelationshipQuery relationshipQuery = new RelationshipQuery(true, this.Path.Path, relationshipClass, relationshipQualifier, thisRole);
                    SecurityHandler   securityHandler   = base.Scope.GetSecurityHandler();
                    int num = this.scope.GetSecuredIWbemServicesHandler(base.Scope.GetIWbemServices()).ExecQueryAsync_(relationshipQuery.QueryLanguage, relationshipQuery.QueryString, enumerationOption1.Flags, enumerationOption1.GetContext(), newSink.Stub);
                    if (securityHandler != null)
                    {
                        securityHandler.Reset();
                    }
                    if (num < 0)
                    {
                        watcher.RemoveSink(newSink);
                        if (((long)num & (long)-4096) != (long)-2147217408)
                        {
                            Marshal.ThrowExceptionForHR(num);
                        }
                        else
                        {
                            ManagementException.ThrowWithExtendedInfo((ManagementStatus)num);
                            return;
                        }
                    }
                    return;
                }
                else
                {
                    throw new ArgumentNullException("watcher");
                }
            }
        }
 public static PerfFormattedData_Counters_ProcessorInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties)
 {
     if ((mgmtScope == null)) {
         if ((statMgmtScope == null)) {
             mgmtScope = new System.Management.ManagementScope();
             mgmtScope.Path.NamespacePath = "root\\CIMV2";
         }
         else {
             mgmtScope = statMgmtScope;
         }
     }
     System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Win32_PerfFormattedData_Counters_ProcessorInformation", condition, selectedProperties));
     System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions();
     enumOptions.EnsureLocatable = true;
     ObjectSearcher.Options = enumOptions;
     return new PerfFormattedData_Counters_ProcessorInformationCollection(ObjectSearcher.Get());
 }
Ejemplo n.º 44
0
        private void DoAddComputerAction(string computer, string newName, bool isLocalhost, ConnectionOptions options, EnumerationOptions enumOptions, ObjectQuery computerSystemQuery)
        {
            int returnCode = 0;
            bool success = false;
            string computerName = isLocalhost ? _shortLocalMachineName : computer;

            if (ParameterSetName == DomainParameterSet)
            {
                string action = StringUtil.Format(ComputerResources.AddComputerActionDomain, DomainName);
                if (!ShouldProcess(computerName, action))
                {
                    return;
                }
            }
            else
            {
                string action = StringUtil.Format(ComputerResources.AddComputerActionWorkgroup, WorkgroupName);
                if (!ShouldProcess(computerName, action))
                {
                    return;
                }
            }

            // Check the length of the new name
            if (newName != null && newName.Length > ComputerWMIHelper.NetBIOSNameMaxLength)
            {
                string truncatedName = newName.Substring(0, ComputerWMIHelper.NetBIOSNameMaxLength);
                string query = StringUtil.Format(ComputerResources.TruncateNetBIOSName, truncatedName);
                string caption = ComputerResources.TruncateNetBIOSNameCaption;
                if (!Force && !ShouldContinue(query, caption))
                {
                    return;
                }
            }

            // If LocalCred is given, use the local credential for WMI connection. Otherwise, use 
            // the current caller's context (Username = null, Password = null)
            if (LocalCredential != null)
            {
                options.SecurePassword = LocalCredential.Password;
                options.Username = ComputerWMIHelper.GetLocalAdminUserName(computerName, LocalCredential);
            }

            // The local machine will always be processed in the very end. If the
            // current target computer is the local machine, it's the last one to
            // be processed, so we can safely set the Username and Password to be
            // null. We cannot use a user credential when connecting to the local
            // machine.
            if (isLocalhost)
            {
                options.Username = null;
                options.SecurePassword = null;
            }

            ManagementScope scope = new ManagementScope(ComputerWMIHelper.GetScopeString(computer, ComputerWMIHelper.WMI_Path_CIM), options);

            try
            {
                using (var searcher = new ManagementObjectSearcher(scope, computerSystemQuery, enumOptions))
                {
                    foreach (ManagementObject computerSystem in searcher.Get())
                    {
                        using (computerSystem)
                        {
                            // If we are not using the new computer name, check the length of the target machine name 
                            string hostName = (string)computerSystem["DNSHostName"];
                            if (newName == null && hostName.Length > ComputerWMIHelper.NetBIOSNameMaxLength)
                            {
                                string truncatedName = hostName.Substring(0, ComputerWMIHelper.NetBIOSNameMaxLength);
                                string query = StringUtil.Format(ComputerResources.TruncateNetBIOSName, truncatedName);
                                string caption = ComputerResources.TruncateNetBIOSNameCaption;
                                if (!Force && !ShouldContinue(query, caption))
                                {
                                    continue;
                                }
                            }

                            if (newName != null && hostName.Equals(newName, StringComparison.OrdinalIgnoreCase))
                            {
                                WriteErrorHelper(
                                    ComputerResources.NewNameIsOldName,
                                    "NewNameIsOldName",
                                    newName,
                                    ErrorCategory.InvalidArgument,
                                    false,
                                    computerName, newName);
                                continue;
                            }

                            if (ParameterSetName == DomainParameterSet)
                            {
                                if ((bool)computerSystem["PartOfDomain"])
                                {
                                    string curDomainName = (string)LanguagePrimitives.ConvertTo(computerSystem["Domain"], typeof(string), CultureInfo.InvariantCulture);
                                    string shortDomainName = "";
                                    if (curDomainName.Contains("."))
                                    {
                                        int dotIndex = curDomainName.IndexOf(".", StringComparison.OrdinalIgnoreCase);
                                        shortDomainName = curDomainName.Substring(0, dotIndex);
                                    }

                                    // If the target computer is already in the specified domain, throw an error
                                    if (curDomainName.Equals(DomainName, StringComparison.OrdinalIgnoreCase) || shortDomainName.Equals(DomainName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        WriteErrorHelper(ComputerResources.AddComputerToSameDomain,
                                                         "AddComputerToSameDomain", computerName,
                                                         ErrorCategory.InvalidOperation, false, computerName, DomainName);
                                        continue;
                                    }

                                    // Switch between domains
                                    // If the UnjoinDomainCredential is not specified, we assume the DomainCredential can be used for both removing
                                    // the computer from its current domain, and adding the computer to the new domain. This behavior is supported on
                                    // Win7, we don't want to break it.
                                    PSCredential credTobeUsed = UnjoinDomainCredential ?? Credential;
                                    string unjoinDomainUserName = credTobeUsed != null ? credTobeUsed.UserName : null;
                                    string unjoinDomainPassword = credTobeUsed != null ? Utils.GetStringFromSecureString(credTobeUsed.Password) : null;

                                    // Leave the current domain
                                    returnCode = UnjoinDomain(computerSystem, computerName, curDomainName, unjoinDomainUserName, unjoinDomainPassword);
                                    if (returnCode == 0)
                                    {
                                        // Successfully unjoin the old domain, join the computer to the new domain
                                        returnCode = JoinDomain(computerSystem, computerName, curDomainName, null);

                                        if (returnCode == 0 && newName != null)
                                        {
                                            // Rename the computer in the new domain
                                            returnCode = RenameComputer(computerSystem, computerName, newName);
                                        }
                                    }

                                    success = returnCode == 0;
                                }
                                else
                                {
                                    // Add a workgroup computer to domain
                                    string curWorkgroupName = (string)LanguagePrimitives.ConvertTo(computerSystem["Domain"], typeof(string), CultureInfo.InvariantCulture);
                                    returnCode = JoinDomain(computerSystem, computerName, null, curWorkgroupName);

                                    if (returnCode == 0 && newName != null)
                                    {
                                        returnCode = RenameComputer(computerSystem, computerName, newName);
                                    }

                                    success = returnCode == 0;
                                }
                            }
                            else // WorkgroupParameterSet
                            {
                                if ((bool)computerSystem["PartOfDomain"])
                                {
                                    // Remind the user to have local admin credential only if the computer is domain joined
                                    string shouldContinueMsg = ComputerResources.RemoveComputerConfirm;
                                    if (!Force && !ShouldContinue(shouldContinueMsg, null /* null = default caption */ ))
                                    {
                                        continue;
                                    }

                                    // Leave the current domain
                                    string curDomainName = (string)LanguagePrimitives.ConvertTo(computerSystem["Domain"], typeof(string), CultureInfo.InvariantCulture);
                                    string dUserName = Credential != null ? Credential.UserName : null;
                                    string dPassword = Credential != null ? Utils.GetStringFromSecureString(Credential.Password) : null;

                                    returnCode = UnjoinDomain(computerSystem, computerName, curDomainName, dUserName, dPassword);
                                    if (returnCode == 0)
                                    {
                                        // Join the specified workgroup
                                        returnCode = JoinWorkgroup(computerSystem, computerName, curDomainName);
                                        if (returnCode == 0 && newName != null)
                                        {
                                            // Rename the computer
                                            returnCode = RenameComputer(computerSystem, computerName, newName);
                                        }
                                    }

                                    success = returnCode == 0;
                                }
                                else // in workgroup
                                {
                                    string curWorkgroup = (string)LanguagePrimitives.ConvertTo(computerSystem["Domain"], typeof(string), CultureInfo.InvariantCulture);
                                    if (curWorkgroup.Equals(WorkgroupName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        WriteErrorHelper(ComputerResources.AddComputerToSameWorkgroup,
                                                         "AddComputerToSameWorkgroup", computerName,
                                                         ErrorCategory.InvalidOperation, false, computerName, WorkgroupName);
                                        continue;
                                    }

                                    // Join to another workgroup
                                    returnCode = JoinWorkgroup(computerSystem, computerName, null);
                                    if (returnCode == 0 && newName != null)
                                    {
                                        returnCode = RenameComputer(computerSystem, computerName, newName);
                                    }

                                    success = returnCode == 0;
                                }
                            }// end of else -- WorkgroupParameterSet

                            if (PassThru)
                            {
                                WriteObject(ComputerWMIHelper.GetComputerStatusObject(returnCode, computerName));
                            }
                        }
                    }// end of foreach

                    // If successful and the Restart parameter is specified, restart the computer
                    if (success && Restart)
                    {
                        object[] flags = new object[] { 6, 0 };
                        RestartComputerCommand.RestartOneComputerUsingDcom(this, isLocalhost, computerName, flags, options);
                    }

                    // If successful and the Restart parameter is not specified, write out warning
                    if (success && !Restart)
                    {
                        WriteWarning(StringUtil.Format(ComputerResources.RestartNeeded, null, computerName));
                    }
                }
            } // end of try
            catch (ManagementException ex)
            {
                WriteErrorHelper(ComputerResources.FailToConnectToComputer, "AddComputerException", computerName,
                                 ErrorCategory.OperationStopped, false, computerName, ex.Message);
            }
            catch (COMException ex)
            {
                WriteErrorHelper(ComputerResources.FailToConnectToComputer, "AddComputerException", computerName,
                                 ErrorCategory.OperationStopped, false, computerName, ex.Message);
            }
            catch (UnauthorizedAccessException ex)
            {
                WriteErrorHelper(ComputerResources.FailToConnectToComputer, "AddComputerException", computerName,
                                 ErrorCategory.OperationStopped, false, computerName, ex.Message);
            }
        }
 public ManagementObjectSearcher(string scope, string queryString, EnumerationOptions options) : this(new ManagementScope(scope), new ObjectQuery(queryString), options)
 {
 }
Ejemplo n.º 46
0
        /// <summary>
        /// ProcessRecord method
        /// </summary>
        protected override void ProcessRecord()
        {
            if (NewName != null && ComputerName.Length != 1)
            {
                WriteErrorHelper(ComputerResources.CannotRenameMultipleComputers, "CannotRenameMultipleComputers",
                                 NewName, ErrorCategory.InvalidArgument, false);
                return;
            }

            // If LocalCred is not provided, we use the current caller's context
            ConnectionOptions options = new ConnectionOptions
            {
                Authentication = AuthenticationLevel.PacketPrivacy,
                Impersonation = ImpersonationLevel.Impersonate,
                EnablePrivileges = true
            };

            EnumerationOptions enumOptions = new EnumerationOptions { UseAmendedQualifiers = true, DirectRead = true };
            ObjectQuery computerSystemQuery = new ObjectQuery("select * from " + ComputerWMIHelper.WMI_Class_ComputerSystem);

            int oldJoinDomainFlags = _joinDomainflags;
            if (NewName != null && ParameterSetName == DomainParameterSet)
            {
                // We rename the computer after it's joined to the target domain, so writing SPN and DNSHostName attributes 
                // on the computer object should be deferred until the rename operation that follows the join operation
                _joinDomainflags |= (int)JoinOptions.DeferSPNSet;
            }

            try
            {
                foreach (string computer in ComputerName)
                {
                    string targetComputer = ValidateComputerName(computer, NewName != null);
                    if (targetComputer == null)
                    {
                        continue;
                    }

                    bool isLocalhost = targetComputer.Equals("localhost", StringComparison.OrdinalIgnoreCase);
                    if (isLocalhost)
                    {
                        if (!_containsLocalHost)
                            _containsLocalHost = true;
                        _newNameForLocalHost = NewName;

                        continue;
                    }

                    DoAddComputerAction(targetComputer, NewName, false, options, enumOptions, computerSystemQuery);
                }// end of foreach
            }
            finally
            {
                // Reverting the domainflags to previous status if DeferSPNSet is added to the domain flags.
                if (NewName != null && ParameterSetName == DomainParameterSet)
                {
                    _joinDomainflags = oldJoinDomainFlags;
                }
            }
        }// end of ProcessRecord
 public static MessageInstanceCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions)
 {
     if ((mgmtScope == null)) {
         if ((statMgmtScope == null)) {
             mgmtScope = new System.Management.ManagementScope();
             mgmtScope.Path.NamespacePath = "root\\MicrosoftBizTalkServer";
         }
         else {
             mgmtScope = statMgmtScope;
         }
     }
     System.Management.ManagementPath pathObj = new System.Management.ManagementPath();
     pathObj.ClassName = "MSBTS_MessageInstance";
     pathObj.NamespacePath = "root\\MicrosoftBizTalkServer";
     System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null);
     if ((enumOptions == null)) {
         enumOptions = new System.Management.EnumerationOptions();
         enumOptions.EnsureLocatable = true;
     }
     return new MessageInstanceCollection(clsObject.GetInstances(enumOptions));
 }
Ejemplo n.º 48
0
        }// end of ProcessRecord

        /// <summary>
        /// EndProcessing method
        /// </summary>
        protected override void EndProcessing()
        {
            if (!_containsLocalHost) return;

            // If LocalCred is not provided, we use the current caller's context
            ConnectionOptions options = new ConnectionOptions
            {
                Authentication = AuthenticationLevel.PacketPrivacy,
                Impersonation = ImpersonationLevel.Impersonate,
                EnablePrivileges = true
            };

            EnumerationOptions enumOptions = new EnumerationOptions { UseAmendedQualifiers = true, DirectRead = true };
            ObjectQuery computerSystemQuery = new ObjectQuery("select * from " + ComputerWMIHelper.WMI_Class_ComputerSystem);

            DoAddComputerAction("localhost", _newNameForLocalHost, true, options, enumOptions, computerSystemQuery);
        }
 public static BcdObjectCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, System.String [] selectedProperties)
 {
     if ((mgmtScope == null)) {
         if ((statMgmtScope == null)) {
             mgmtScope = new System.Management.ManagementScope();
             mgmtScope.Path.NamespacePath = "root\\WMI";
         }
         else {
             mgmtScope = statMgmtScope;
         }
     }
     System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("BcdObject", condition, selectedProperties));
     System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions();
     enumOptions.EnsureLocatable = true;
     ObjectSearcher.Options = enumOptions;
     return new BcdObjectCollection(ObjectSearcher.Get());
 }
Ejemplo n.º 50
0
 public ManagementObjectSearcher(string scope, string queryString, EnumerationOptions options)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 51
0
        private void DoRemoveComputerAction(string computer, bool isLocalhost, ConnectionOptions options, EnumerationOptions enumOptions, ObjectQuery computerSystemQuery)
        {
            bool successful = false;
            string computerName = isLocalhost ? _shortLocalMachineName : computer;

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

            // If LocalCred is given, use the local credential for WMI connection
            if (LocalCredential != null)
            {
                options.SecurePassword = LocalCredential.Password;
                options.Username = ComputerWMIHelper.GetLocalAdminUserName(computerName, LocalCredential);
            }

            // The local machine will always be processed in the very end. If the
            // current target computer is the local machine, it's the last one to
            // be processed, so we can safely set the Username and Password to be
            // null. We cannot use a user credential when connecting to the local
            // machine.
            if (isLocalhost)
            {
                options.Username = null;
                options.SecurePassword = null;
            }

            ManagementScope scope = new ManagementScope(ComputerWMIHelper.GetScopeString(computer, ComputerWMIHelper.WMI_Path_CIM), options);
            try
            {
                using (var searcher = new ManagementObjectSearcher(scope, computerSystemQuery, enumOptions))
                {
                    foreach (ManagementObject computerSystem in searcher.Get())
                    {
                        using (computerSystem)
                        {
                            if (!(bool)computerSystem["PartOfDomain"])
                            {
                                // Not in a domain, throw out non-terminating error
                                string errMsg = StringUtil.Format(ComputerResources.ComputerNotInDomain, computerName);
                                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "ComputerNotInDomain", ErrorCategory.InvalidOperation, computerName);
                                WriteError(error);
                                continue;
                            }

                            // Remind the user to have local admin credential only if the computer is domain joined
                            string shouldContinueMsg = ComputerResources.RemoveComputerConfirm;
                            if (!Force && !ShouldContinue(shouldContinueMsg, null /* null = default caption */ ))
                            {
                                continue;
                            }

                            int returnCode = 0;
                            string curDomainName = (string)LanguagePrimitives.ConvertTo(computerSystem["Domain"], typeof(string), CultureInfo.InvariantCulture);
                            string dUserName = UnjoinDomainCredential != null ? UnjoinDomainCredential.UserName : null;
                            string dPassword = UnjoinDomainCredential != null ? Utils.GetStringFromSecureString(UnjoinDomainCredential.Password) : null;

                            ManagementBaseObject unjoinParameter = computerSystem.GetMethodParameters("UnjoinDomainOrWorkgroup");
                            unjoinParameter.SetPropertyValue("UserName", dUserName);
                            unjoinParameter.SetPropertyValue("Password", dPassword);
                            unjoinParameter.SetPropertyValue("FUnjoinOptions", 4); // default option, disable the active directory account

                            ManagementBaseObject result = computerSystem.InvokeMethod("UnjoinDomainOrWorkgroup", unjoinParameter, null);
                            Dbg.Diagnostics.Assert(result != null, "result cannot be null if the Unjoin method is invoked");
                            returnCode = Convert.ToInt32(result["ReturnValue"], CultureInfo.CurrentCulture);

                            // Error code 1355 - The specified domain either does not exist or could not be contacted.
                            // This might happen when the old domain is gone or unreachable.
                            // Error code 53 - The network path was not found.
                            // This might happen when the network is not available.
                            if ((returnCode == 1355 || returnCode == 53) && Force)
                            {
                                // When -Force is specified, we unjoin the domain without disable the AD account
                                unjoinParameter.SetPropertyValue("FUnjoinOptions", 0);
                                result = computerSystem.InvokeMethod("UnjoinDomainOrWorkgroup", unjoinParameter, null);
                                Dbg.Diagnostics.Assert(result != null, "result cannot be null if the Unjoin method is invoked");
                                returnCode = Convert.ToInt32(result["ReturnValue"], CultureInfo.CurrentCulture);
                            }

                            if (returnCode != 0)
                            {
                                var ex = new Win32Exception(returnCode);
                                string errMsg = StringUtil.Format(ComputerResources.FailToUnjoinDomain, computerName, curDomainName, ex.Message);
                                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToUnjoinDomain", ErrorCategory.OperationStopped, computerName);
                                WriteError(error);
                            }
                            else
                            {
                                // Join into the specified workgroup if it's given
                                successful = true;
                                if (WorkgroupName != null)
                                {
                                    ManagementBaseObject joinParameter = computerSystem.GetMethodParameters("JoinDomainOrWorkgroup");
                                    joinParameter.SetPropertyValue("Name", WorkgroupName);
                                    joinParameter.SetPropertyValue("Password", null);
                                    joinParameter.SetPropertyValue("UserName", null);
                                    joinParameter.SetPropertyValue("FJoinOptions", 0); // Join in a workgroup

                                    result = computerSystem.InvokeMethod("JoinDomainOrWorkgroup", joinParameter, null);
                                    Dbg.Diagnostics.Assert(result != null, "result cannot be null if the Join method is invoked");
                                    returnCode = Convert.ToInt32(result["ReturnValue"], CultureInfo.CurrentCulture);
                                    if (returnCode != 0)
                                    {
                                        var ex = new Win32Exception(returnCode);
                                        string errMsg = StringUtil.Format(ComputerResources.FailToSwitchFromDomainToWorkgroup, computerName, curDomainName, WorkgroupName, ex.Message);
                                        ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToJoinWorkGroup", ErrorCategory.OperationStopped, computerName);
                                        WriteError(error);
                                    }
                                }
                            }

                            if (PassThru)
                            {
                                WriteObject(ComputerWMIHelper.GetComputerStatusObject(returnCode, computerName));
                            }
                        }
                    }
                }

                // If successful and the Restart parameter is specified, restart the computer
                if (successful && Restart)
                {
                    object[] flags = new object[] { 6, 0 };
                    RestartComputerCommand.RestartOneComputerUsingDcom(this, isLocalhost, computerName, flags, options);
                }

                // If successful and the Restart parameter is not specified, write out warning
                if (successful && !Restart)
                {
                    WriteWarning(StringUtil.Format(ComputerResources.RestartNeeded, null, computerName));
                }
            }
            catch (ManagementException ex)
            {
                string errMsg = StringUtil.Format(ComputerResources.FailToConnectToComputer, computerName, ex.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "RemoveComputerException", ErrorCategory.OperationStopped, computerName);
                WriteError(error);
            }
            catch (COMException ex)
            {
                string errMsg = StringUtil.Format(ComputerResources.FailToConnectToComputer, computerName, ex.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "RemoveComputerException", ErrorCategory.OperationStopped, computerName);
                WriteError(error);
            }
            catch (UnauthorizedAccessException ex)
            {
                string errMsg = StringUtil.Format(ComputerResources.FailToConnectToComputer, computerName, ex.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "RemoveComputerException", ErrorCategory.OperationStopped, computerName);
                WriteError(error);
            }
        }
Ejemplo n.º 52
0
        public void GetRelationshipClasses(ManagementOperationObserver watcher, string relationshipClass, string relationshipQualifier, string thisRole, EnumerationOptions options)
        {
            if (((this.Path == null) || (this.Path.Path == null)) || (this.Path.Path.Length == 0))
            {
                throw new InvalidOperationException();
            }
            if (watcher == null)
            {
                throw new ArgumentNullException("watcher");
            }
            this.Initialize(true);
            EnumerationOptions options2 = (options != null) ? ((EnumerationOptions)options.Clone()) : new EnumerationOptions();

            options2.EnumerateDeep     = true;
            options2.ReturnImmediately = false;
            if (watcher.HaveListenersForProgress)
            {
                options2.SendStatus = true;
            }
            WmiEventSink      newSink         = watcher.GetNewSink(base.Scope, options2.Context);
            RelationshipQuery query           = new RelationshipQuery(true, this.Path.Path, relationshipClass, relationshipQualifier, thisRole);
            SecurityHandler   securityHandler = null;
            int errorCode = 0;

            securityHandler = base.Scope.GetSecurityHandler();
            errorCode       = base.scope.GetSecuredIWbemServicesHandler(base.Scope.GetIWbemServices()).ExecQueryAsync_(query.QueryLanguage, query.QueryString, options2.Flags, options2.GetContext(), newSink.Stub);
            if (securityHandler != null)
            {
                securityHandler.Reset();
            }
            if (errorCode < 0)
            {
                watcher.RemoveSink(newSink);
                if ((errorCode & 0xfffff000L) == 0x80041000L)
                {
                    ManagementException.ThrowWithExtendedInfo((ManagementStatus)errorCode);
                }
                else
                {
                    Marshal.ThrowExceptionForHR(errorCode);
                }
            }
        }
Ejemplo n.º 53
0
 /// <summary>
 /// Execute a given Query with the provided EnumerationOptions.
 /// </summary>
 /// <param name="sQuery">The Query to be executed.</param>
 /// <param name="oEnumOpts">The EnumerationOptions to be used.</param>
 /// <returns>Returns a ManagementObjectCollection.</returns>
 public ManagementObjectCollection ExecuteQuery(string sQuery, EnumerationOptions oEnumOpts)
 {
     ManagementObjectSearcher oSrch = new ManagementObjectSearcher(mScope, new ObjectQuery(sQuery), oEnumOpts);
     return oSrch.Get();
 }
Ejemplo n.º 54
0
        private void processDCOMProtocolForTestConnection()
        {
            ConnectionOptions options = ComputerWMIHelper.GetConnectionOptions(DcomAuthentication, this.Impersonation, this.Credential);
            if (AsJob)
            {
                string filter = QueryString(ComputerName, true, false);
                GetWmiObjectCommand WMICmd = new GetWmiObjectCommand();
                WMICmd.Filter = filter.ToString();
                WMICmd.Class = ComputerWMIHelper.WMI_Class_PingStatus;
                WMICmd.ComputerName = Source;
                WMICmd.Authentication = DcomAuthentication;
                WMICmd.Impersonation = Impersonation;
                WMICmd.ThrottleLimit = throttlelimit;
                PSWmiJob wmiJob = new PSWmiJob(WMICmd, Source, throttlelimit, this.MyInvocation.MyCommand.Name, Count);
                this.JobRepository.Add(wmiJob);
                WriteObject(wmiJob);
            }
            else
            {
                int sourceCount = 0;
                foreach (string fromcomp in Source)
                {
                    try
                    {
                        sourceCount++;
                        EnumerationOptions enumOptions = new EnumerationOptions();
                        enumOptions.UseAmendedQualifiers = true;
                        enumOptions.DirectRead = true;

                        int destCount = 0;
                        foreach (var tocomp in ComputerName)
                        {
                            destCount++;
                            string querystring = QueryString(new string[] { tocomp }, true, true);
                            ObjectQuery query = new ObjectQuery(querystring);
                            ManagementScope scope = new ManagementScope(ComputerWMIHelper.GetScopeString(fromcomp, ComputerWMIHelper.WMI_Path_CIM), options);
                            scope.Options.EnablePrivileges = true;
                            scope.Connect();

                            using (searcher = new ManagementObjectSearcher(scope, query, enumOptions))
                            {
                                for (int j = 0; j <= Count - 1; j++)
                                {
                                    using (ManagementObjectCollection mobj = searcher.Get())
                                    {
                                        int mobjCount = 0;
                                        foreach (ManagementBaseObject obj in mobj)
                                        {
                                            using (obj)
                                            {
                                                mobjCount++;

                                                ProcessPingStatus(obj);

                                                // to delay the request, if case to avoid the delay for the last pingrequest
                                                if (mobjCount < mobj.Count || j < Count - 1 || sourceCount < Source.Length || destCount < ComputerName.Length)
                                                    Thread.Sleep(Delay * 1000);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        searcher = null;
                    }
                    catch (ManagementException e)
                    {
                        ErrorRecord errorRecord = new ErrorRecord(e, "TestConnectionException", ErrorCategory.InvalidOperation, null);
                        WriteError(errorRecord);
                        continue;
                    }
                    catch (System.Runtime.InteropServices.COMException e)
                    {
                        ErrorRecord errorRecord = new ErrorRecord(e, "TestConnectionException", ErrorCategory.InvalidOperation, null);
                        WriteError(errorRecord);
                        continue;
                    }
                }
            }

            if (quiet)
            {
                foreach (string destinationAddress in this.ComputerName)
                {
                    bool destinationResult = false;
                    this.quietResults.TryGetValue(destinationAddress, out destinationResult);
                    WriteObject(destinationResult);
                }
            }
        }