Exemplo n.º 1
0
    public void ListIP()
    {
        try {
            ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection objMOC = objMC.GetInstances();

            foreach (ManagementObject objMO in objMOC) {
                if (!(bool)objMO["ipEnabled"])
                    continue;

                MessageBox.Show(objMO["Caption"] + "," + objMO["ServiceName"] + "," + objMO["MACAddress"]);
                string[] ipaddresses = (string[])objMO["IPAddress"];
                string[] subnets = (string[])objMO["IPSubnet"];
                string[] gateways = (string[])objMO["DefaultIPGateway"];

                MessageBox.Show(objMO["DefaultIPGateway"].ToString());

                MessageBox.Show("IPGateway");
                foreach (string sGate in gateways)
                    MessageBox.Show(sGate);

                MessageBox.Show("Ipaddress");
                foreach (string sIP in ipaddresses)
                    MessageBox.Show(sIP);

                MessageBox.Show("SubNet");
                foreach (string sNet in subnets)
                    MessageBox.Show(sNet);

            }
        }
        catch (Exception ex) {
            MessageBox.Show(ex.Message);
        }
    }
Exemplo n.º 2
0
    //获得网卡序列号----MAc地址
    public string GetMoAddress()
    {
        try
        {
            //读取硬盘序列号
            ManagementObject disk;
            disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
            disk.Get();

            string MoAddress = "BD-CNSOFTWEB";
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc2 = mc.GetInstances();
            foreach (ManagementObject mo in moc2)
            {
                if ((bool)mo["IPEnabled"] == true)
                {
                    string a = mo["MacAddress"].ToString();
                    string c = disk.GetPropertyValue("VolumeSerialNumber").ToString();
                    MoAddress = "BD-" + a + "-" + c + "-CNSOFTWEB";
                    break;
                }
            }
            return MoAddress.ToString().Replace(":", "");
        }
        catch
        {
            return "BD-ERR-CNSOFTWEB";
        }
    }
Exemplo n.º 3
0
 public static string GetHDIndex()
 {
     string str = "";
     ManagementClass class2 = new ManagementClass("Win32_DiskDrive");
     foreach (ManagementObject obj2 in class2.GetInstances())
     {
         str = (string) obj2.Properties["Model"].Value;
     }
     return str;
 }
Exemplo n.º 4
0
 public static string GetCpuIndex()
 {
     string str = "";
     ManagementClass class2 = new ManagementClass("Win32_Processor");
     foreach (ManagementObject obj2 in class2.GetInstances())
     {
         str = obj2.Properties["ProcessorId"].Value.ToString();
     }
     return str;
 }
Exemplo n.º 5
0
 public ProcessCommandLine(String PID)
 {
     ManagementClass mc = new ManagementClass(@"root/cimv2:Win32_Process");
     ManagementObjectCollection mobjects = mc.GetInstances();
     if (DEBUG) Console.WriteLine("{0}", PID);
     foreach (ManagementObject mo in mobjects) {
         if (DEBUG)
             Console.WriteLine(mo["ProcessID"].ToString());
         if (PID == mo["ProcessID"].ToString())
             _CommandLine = mo["CommandLine"].ToString();
     }
 }
Exemplo n.º 6
0
 //���ϵͳʱ��
 // ��ѯCPU���
 // ����WMI����ѯcpuID
 public string GetCpuId()
 {
     ManagementClass mClass = new ManagementClass("Win32_Processor");//CPU������
     ManagementObjectCollection moc = mClass.GetInstances();
     string cpuId=null;
     foreach (ManagementObject mo in moc)
        {
         cpuId = mo.Properties["ProcessorId"].Value.ToString();
         break;
     }
     return cpuId;
 }
Exemplo n.º 7
0
 /// <summary>
 /// 获取CPU编号
 /// </summary>
 /// <returns></returns>
 public string GetCPUId()
 {
     ManagementClass mc = new ManagementClass("Win32_Processor");
         ManagementObjectCollection moc = mc.GetInstances();
         string strID = string.Empty;
         foreach (ManagementObject mo in moc)
         {
             strID = mo.Properties["ProcessorId"].Value.ToString();
             break;
         }
         return strID;
 }
Exemplo n.º 8
0
 /// <summary>
 /// BIOS
 /// </summary>
 /// <returns></returns>
 public string GetBIOS()
 {
     ManagementClass mc = new ManagementClass("Win32_BIOS");
         ManagementObjectCollection moc = mc.GetInstances();
         string strID = null;
         foreach (ManagementObject mo in moc)
         {
             strID = mo.Properties["SerialNumber"].Value.ToString();
             break;
         }
         return strID;
 }
Exemplo n.º 9
0
 /// <summary>
 /// Mac地址
 /// </summary>
 /// <returns></returns>
 public string GetNetCardMacAddress()
 {
     ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
         ManagementObjectCollection moc = mc.GetInstances();
         string strID = null;
         foreach (ManagementObject mo in moc)
         {
             if ((bool)mo["IPEnabled"] == true)
                 strID = mo["MacAddress"].ToString();
         }
         return strID;
 }
Exemplo n.º 10
0
 /// <summary>
 /// 硬盘信息
 /// </summary>
 /// <returns></returns>
 public string GetPhysicalMediaId()
 {
     ManagementClass mc = new ManagementClass("Win32_PhysicalMedia");
         //网上有提到,用Win32_DiskDrive,但是用Win32_DiskDrive获得的硬盘信息中并不包含SerialNumber属性。
         ManagementObjectCollection moc = mc.GetInstances();
         string strID = null;
         foreach (ManagementObject mo in moc)
         {
             strID = mo.Properties["SerialNumber"].Value.ToString();
             break;
         }
         return strID;
 }
Exemplo n.º 11
0
    public static String GetCPUClock()
    {
        ManagementClass mc = new ManagementClass("Win32_Processor");
        ManagementObjectCollection moc = mc.GetInstances();
        String Id = String.Empty;
        foreach (ManagementObject mo in moc)
        {

            Id = mo.Properties["MaxClockSpeed"].Value.ToString();
            break;
        }
        return Id;
    }
Exemplo n.º 12
0
    public static String GetProcessorId()
    {
        ManagementClass mc = new ManagementClass("win32_processor");
            ManagementObjectCollection moc = mc.GetInstances();
            String Id = String.Empty;
            foreach (ManagementObject mo in moc)
            {

                Id = mo.Properties["Name"].Value.ToString();
                break;
            }
            return Id;
    }
Exemplo n.º 13
0
    public static void Main(string[] args)
    {
        // Generate unique system ID
        ManagementClass mc = new ManagementClass("Win32_Processor");
        ManagementObjectCollection moc = mc.GetInstances();
        foreach (ManagementObject mo in moc)
        {
            uuid = mo.Properties["processorID"].Value.ToString();
            Console.WriteLine("Unique ID for agent: " + uuid);
            break;
        }

        // Create the channel.
        TcpChannel clientChannel = new TcpChannel();

        // Register the channel.
        ChannelServices.RegisterChannel(clientChannel, false);

        //// Register as client for remote object.
        //WellKnownClientTypeEntry remoteType = new WellKnownClientTypeEntry(
        //    typeof(IVPrefServiceProvider), "tcp://localhost:6001/vPreServer.rem");
        //RemotingConfiguration.RegisterWellKnownClientType(remoteType);

        //// Create a message sink.
        //string objectUri;
        //System.Runtime.Remoting.Messaging.IMessageSink messageSink =
        //    clientChannel.CreateMessageSink(
        //        "tcp://localhost:6001/vPreServer.rem", null,
        //        out objectUri);
        //Console.WriteLine("The URI of the message sink is {0}.",
        //    objectUri);
        //if (messageSink != null)
        //{
        //    Console.WriteLine("The type of the message sink is {0}.",
        //        messageSink.GetType().ToString());
        //}

        // Create an instance of the remote object.
        IVPrefServiceProvider service = (IVPrefServiceProvider)RemotingServices.Connect(typeof(IVPrefServiceProvider), "tcp://localhost:6001/vPreServer.soap");

        // Invoke a method on the remote object.
        Console.WriteLine("The client is invoking the remote object.");
        Console.WriteLine("count is " + service.returnInterCount());

        while (true)
        {
            System.Threading.Thread.Sleep(2000);
            Dictionary<String, String> dict = IOStatManager.getInstance.getDiskInformation();
            service.reportIO(uuid, dict);
        }
    }
Exemplo n.º 14
0
 public static string GetMacAddress()
 {
     string str = "";
     ManagementClass class2 = new ManagementClass("Win32_NetworkAdapterConfiguration");
     foreach (ManagementObject obj2 in class2.GetInstances())
     {
         if ((bool) obj2["IPEnabled"])
         {
             str = obj2["MacAddress"].ToString();
         }
         obj2.Dispose();
     }
     return str;
 }
Exemplo n.º 15
0
    public static string GetDiskNumber()
    {
        // 取得设备硬盘的序列号
        string strDisk = null;
        ManagementClass cimobject = new ManagementClass("win32_diskdrive");
        ManagementObjectCollection moc = cimobject.GetInstances();
        foreach (ManagementObject myObject in moc)
        {
            strDisk = myObject.Properties["model"].Value.ToString();
            break;
        }

        return strDisk;
    }
Exemplo n.º 16
0
    public static ArrayList GetMACAddress()
    {
        ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection moc = mc.GetInstances();
        ArrayList MACAddress = new ArrayList();

        foreach (ManagementObject mo in moc)
        {
            if (mo["MacAddress"] != null)
            MACAddress.Add(mo["MacAddress"].ToString().Replace(":", ""));

            mo.Dispose();
        }
        return MACAddress;
    }
Exemplo n.º 17
0
 public static string GetCPUId()
 {
     string cpuInfo =  String.Empty;
     string temp=String.Empty;
     ManagementClass mc = new ManagementClass("Win32_Processor");
     ManagementObjectCollection moc = mc.GetInstances();
     foreach(ManagementObject mo in moc)
     {
         if(cpuInfo==String.Empty)
         {// only return cpuInfo from first CPU
             cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
         }
     }
     return cpuInfo;
 }
Exemplo n.º 18
0
 /// <summary>
 /// method for retrieving the CPU Manufacturer
 /// using the WMI class
 /// </summary>
 /// <returns>CPU Manufacturer</returns>
 public static string GetCPUManufacturer()
 {
     string cpuMan = String.Empty;
     //create an instance of the Managemnet class with the
     //Win32_Processor class
     ManagementClass mgmt = new ManagementClass("Win32_Processor");
     //create a ManagementObjectCollection to loop through
     ManagementObjectCollection objCol = mgmt.GetInstances();
     //start our loop for all processors found
     foreach (ManagementObject obj in objCol)
     {
         if (cpuMan == String.Empty)
         {
             // only return manufacturer from first CPU
             cpuMan = obj.Properties["Manufacturer"].Value.ToString();
         }
     }
     return cpuMan;
 }
Exemplo n.º 19
0
 public static int GetCPUCurrentClockSpeed()
 {
     int cpuClockSpeed = 0;
     //create an instance of the Managemnet class with the
     //Win32_Processor class
     ManagementClass mgmt = new ManagementClass("Win32_Processor");
     //create a ManagementObjectCollection to loop through
     ManagementObjectCollection objCol = mgmt.GetInstances();
     //start our loop for all processors found
     foreach (ManagementObject obj in objCol)
     {
         if (cpuClockSpeed == 0)
         {
             // only return cpuStatus from first CPU
             cpuClockSpeed = Convert.ToInt32(obj.Properties["CurrentClockSpeed"].Value.ToString());
         }
     }
     //return the status
     return cpuClockSpeed;
 }
Exemplo n.º 20
0
 /// <summary>
 /// 获取机器号码
 /// </summary>
 /// <returns></returns>
 public static string GetDiskCPUNumber()
 {
     string strDiskCPUNumber = "";
     // 取得设备硬盘的卷标号
     string strDisk = null;
     ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
     ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
     disk.Get();
     strDisk = disk.GetPropertyValue("VolumeSerialNumber").ToString();
     //获得CPU的序列号
     string strCPU = null;
     ManagementClass myCpu = new ManagementClass("win32_Processor");
     ManagementObjectCollection myCpuConnection = myCpu.GetInstances();
     foreach (ManagementObject myObject in myCpuConnection)
     {
         strCPU = myObject.Properties["Processorid"].Value.ToString();
         break;
     }
     return strDiskCPUNumber = strCPU + strDisk;
 }
Exemplo n.º 21
0
    //取CPU编号
    public String GetCpuID()
    {
        try
        {
            ManagementClass mc = new ManagementClass("Win32_Processor");
            ManagementObjectCollection moc = mc.GetInstances();

            String strCpuID = null;
            foreach (ManagementObject mo in moc)
            {
                strCpuID = mo.Properties["ProcessorId"].Value.ToString();
                break;
            }
            return strCpuID;
        }
        catch
        {
            return "";
        }
    }
        public SchemaMapping(Type type, SchemaNaming naming, Hashtable mapTypeToConverterClassName)
        {
            this.codeClassName = (string)mapTypeToConverterClassName[type];
            this.classType     = type;
            bool   flag          = false;
            string baseClassName = ManagedNameAttribute.GetBaseClassName(type);

            this.className           = ManagedNameAttribute.GetMemberName(type);
            this.instrumentationType = InstrumentationClassAttribute.GetAttribute(type).InstrumentationType;
            this.classPath           = naming.NamespaceName + ":" + this.className;
            if (baseClassName == null)
            {
                this.newClass = new ManagementClass(naming.NamespaceName, "", null);
                this.newClass.SystemProperties["__CLASS"].Value = this.className;
            }
            else
            {
                ManagementClass class2 = new ManagementClass(naming.NamespaceName + ":" + baseClassName);
                if (this.instrumentationType == System.Management.Instrumentation.InstrumentationType.Instance)
                {
                    bool flag2 = false;
                    try
                    {
                        QualifierData data = class2.Qualifiers["abstract"];
                        if (data.Value is bool)
                        {
                            flag2 = (bool)data.Value;
                        }
                    }
                    catch (ManagementException exception)
                    {
                        if (exception.ErrorCode != ManagementStatus.NotFound)
                        {
                            throw;
                        }
                    }
                    if (!flag2)
                    {
                        throw new Exception(RC.GetString("CLASSINST_EXCEPT"));
                    }
                }
                this.newClass = class2.Derive(this.className);
            }
            CodeWriter writer  = this.code.AddChild("public class " + this.codeClassName + " : IWmiConverter");
            CodeWriter writer2 = writer.AddChild(new CodeWriter());

            writer2.Line("static ManagementClass managementClass = new ManagementClass(@\"" + this.classPath + "\");");
            writer2.Line("static IntPtr classWbemObjectIP;");
            writer2.Line("static Guid iidIWbemObjectAccess = new Guid(\"49353C9A-516B-11D1-AEA6-00C04FB68820\");");
            writer2.Line("internal ManagementObject instance = managementClass.CreateInstance();");
            writer2.Line("object reflectionInfoTempObj = null ; ");
            writer2.Line("FieldInfo reflectionIWbemClassObjectField = null ; ");
            writer2.Line("IntPtr emptyWbemObject = IntPtr.Zero ; ");
            writer2.Line("IntPtr originalObject = IntPtr.Zero ; ");
            writer2.Line("bool toWmiCalled = false ; ");
            writer2.Line("IntPtr theClone = IntPtr.Zero;");
            writer2.Line("public static ManagementObject emptyInstance = managementClass.CreateInstance();");
            writer2.Line("public IntPtr instWbemObjectAccessIP;");
            CodeWriter writer3 = writer.AddChild("static " + this.codeClassName + "()");

            writer3.Line("classWbemObjectIP = (IntPtr)managementClass;");
            writer3.Line("IntPtr wbemObjectAccessIP;");
            writer3.Line("Marshal.QueryInterface(classWbemObjectIP, ref iidIWbemObjectAccess, out wbemObjectAccessIP);");
            writer3.Line("int cimType;");
            CodeWriter writer4 = writer.AddChild("public " + this.codeClassName + "()");

            writer4.Line("IntPtr wbemObjectIP = (IntPtr)instance;");
            writer4.Line("originalObject = (IntPtr)instance;");
            writer4.Line("Marshal.QueryInterface(wbemObjectIP, ref iidIWbemObjectAccess, out instWbemObjectAccessIP);");
            writer4.Line("FieldInfo tempField = instance.GetType().GetField ( \"_wbemObject\", BindingFlags.Instance | BindingFlags.NonPublic );");
            writer4.Line("if ( tempField == null )");
            writer4.Line("{");
            writer4.Line("   tempField = instance.GetType().GetField ( \"wbemObject\", BindingFlags.Instance | BindingFlags.NonPublic ) ;");
            writer4.Line("}");
            writer4.Line("reflectionInfoTempObj = tempField.GetValue (instance) ;");
            writer4.Line("reflectionIWbemClassObjectField = reflectionInfoTempObj.GetType().GetField (\"pWbemClassObject\", BindingFlags.Instance | BindingFlags.NonPublic );");
            writer4.Line("emptyWbemObject = (IntPtr) emptyInstance;");
            CodeWriter writer5 = writer.AddChild("~" + this.codeClassName + "()");

            writer5.AddChild("if(instWbemObjectAccessIP != IntPtr.Zero)").Line("Marshal.Release(instWbemObjectAccessIP);");
            writer5.Line("if ( toWmiCalled == true )");
            writer5.Line("{");
            writer5.Line("\tMarshal.Release (originalObject);");
            writer5.Line("}");
            CodeWriter writer6 = writer.AddChild("public void ToWMI(object obj)");

            writer6.Line("toWmiCalled = true ;");
            writer6.Line("if(instWbemObjectAccessIP != IntPtr.Zero)");
            writer6.Line("{");
            writer6.Line("    Marshal.Release(instWbemObjectAccessIP);");
            writer6.Line("    instWbemObjectAccessIP = IntPtr.Zero;");
            writer6.Line("}");
            writer6.Line("if(theClone != IntPtr.Zero)");
            writer6.Line("{");
            writer6.Line("    Marshal.Release(theClone);");
            writer6.Line("    theClone = IntPtr.Zero;");
            writer6.Line("}");
            writer6.Line("IWOA.Clone_f(12, emptyWbemObject, out theClone) ;");
            writer6.Line("Marshal.QueryInterface(theClone, ref iidIWbemObjectAccess, out instWbemObjectAccessIP) ;");
            writer6.Line("reflectionIWbemClassObjectField.SetValue ( reflectionInfoTempObj, theClone ) ;");
            writer6.Line(string.Format("{0} instNET = ({0})obj;", type.FullName.Replace('+', '.')));
            writer.AddChild("public static explicit operator IntPtr(" + this.codeClassName + " obj)").Line("return obj.instWbemObjectAccessIP;");
            writer2.Line("public ManagementObject GetInstance() {return instance;}");
            PropertyDataCollection properties = this.newClass.Properties;

            switch (this.instrumentationType)
            {
            case System.Management.Instrumentation.InstrumentationType.Instance:
                properties.Add("ProcessId", CimType.String, false);
                properties.Add("InstanceId", CimType.String, false);
                properties["ProcessId"].Qualifiers.Add("key", true);
                properties["InstanceId"].Qualifiers.Add("key", true);
                this.newClass.Qualifiers.Add("dynamic", true, false, false, false, true);
                this.newClass.Qualifiers.Add("provider", naming.DecoupledProviderInstanceName, false, false, false, true);
                break;

            case System.Management.Instrumentation.InstrumentationType.Abstract:
                this.newClass.Qualifiers.Add("abstract", true, false, false, false, true);
                break;
            }
            int  num   = 0;
            bool flag3 = false;

            foreach (MemberInfo info in type.GetMembers())
            {
                if (((info is FieldInfo) || (info is PropertyInfo)) && (info.GetCustomAttributes(typeof(IgnoreMemberAttribute), false).Length <= 0))
                {
                    Type fieldType;
                    if (info is FieldInfo)
                    {
                        FieldInfo info2 = info as FieldInfo;
                        if (info2.IsStatic)
                        {
                            ThrowUnsupportedMember(info);
                        }
                    }
                    else if (info is PropertyInfo)
                    {
                        PropertyInfo info3 = info as PropertyInfo;
                        if (!info3.CanRead)
                        {
                            ThrowUnsupportedMember(info);
                        }
                        MethodInfo getMethod = info3.GetGetMethod();
                        if ((null == getMethod) || getMethod.IsStatic)
                        {
                            ThrowUnsupportedMember(info);
                        }
                        if (getMethod.GetParameters().Length > 0)
                        {
                            ThrowUnsupportedMember(info);
                        }
                    }
                    string memberName = ManagedNameAttribute.GetMemberName(info);
                    if (info is FieldInfo)
                    {
                        fieldType = (info as FieldInfo).FieldType;
                    }
                    else
                    {
                        fieldType = (info as PropertyInfo).PropertyType;
                    }
                    bool isArray = false;
                    if (fieldType.IsArray)
                    {
                        if (fieldType.GetArrayRank() != 1)
                        {
                            ThrowUnsupportedMember(info);
                        }
                        isArray   = true;
                        fieldType = fieldType.GetElementType();
                    }
                    string str3 = null;
                    string str4 = null;
                    if (mapTypeToConverterClassName.Contains(fieldType))
                    {
                        str4 = (string)mapTypeToConverterClassName[fieldType];
                        str3 = ManagedNameAttribute.GetMemberName(fieldType);
                    }
                    bool flag5 = false;
                    if (fieldType == typeof(object))
                    {
                        flag5 = true;
                        if (!flag)
                        {
                            flag = true;
                            writer2.Line("static Hashtable mapTypeToConverter = new Hashtable();");
                            foreach (DictionaryEntry entry in mapTypeToConverterClassName)
                            {
                                string introduced55 = ((Type)entry.Key).FullName.Replace('+', '.');
                                writer3.Line(string.Format("mapTypeToConverter[typeof({0})] = typeof({1});", introduced55, (string)entry.Value));
                            }
                        }
                    }
                    string str5 = "prop_" + num;
                    string str6 = "handle_" + num++;
                    writer2.Line("static int " + str6 + ";");
                    writer3.Line(string.Format("IWOA.GetPropertyHandle_f27(27, wbemObjectAccessIP, \"{0}\", out cimType, out {1});", memberName, str6));
                    writer2.Line("PropertyData " + str5 + ";");
                    writer4.Line(string.Format("{0} = instance.Properties[\"{1}\"];", str5, memberName));
                    if (flag5)
                    {
                        CodeWriter writer8 = writer6.AddChild(string.Format("if(instNET.{0} != null)", info.Name));
                        writer6.AddChild("else").Line(string.Format("{0}.Value = null;", str5));
                        if (isArray)
                        {
                            writer8.Line(string.Format("int len = instNET.{0}.Length;", info.Name));
                            writer8.Line("ManagementObject[] embeddedObjects = new ManagementObject[len];");
                            writer8.Line("IWmiConverter[] embeddedConverters = new IWmiConverter[len];");
                            CodeWriter writer10 = writer8.AddChild("for(int i=0;i<len;i++)");
                            CodeWriter writer11 = writer10.AddChild(string.Format("if((instNET.{0}[i] != null) && mapTypeToConverter.Contains(instNET.{0}[i].GetType()))", info.Name));
                            writer11.Line(string.Format("Type type = (Type)mapTypeToConverter[instNET.{0}[i].GetType()];", info.Name));
                            writer11.Line("embeddedConverters[i] = (IWmiConverter)Activator.CreateInstance(type);");
                            writer11.Line(string.Format("embeddedConverters[i].ToWMI(instNET.{0}[i]);", info.Name));
                            writer11.Line("embeddedObjects[i] = embeddedConverters[i].GetInstance();");
                            writer10.AddChild("else").Line(string.Format("embeddedObjects[i] = SafeAssign.GetManagementObject(instNET.{0}[i]);", info.Name));
                            writer8.Line(string.Format("{0}.Value = embeddedObjects;", str5));
                        }
                        else
                        {
                            CodeWriter writer12 = writer8.AddChild(string.Format("if(mapTypeToConverter.Contains(instNET.{0}.GetType()))", info.Name));
                            writer12.Line(string.Format("Type type = (Type)mapTypeToConverter[instNET.{0}.GetType()];", info.Name));
                            writer12.Line("IWmiConverter converter = (IWmiConverter)Activator.CreateInstance(type);");
                            writer12.Line(string.Format("converter.ToWMI(instNET.{0});", info.Name));
                            writer12.Line(string.Format("{0}.Value = converter.GetInstance();", str5));
                            writer8.AddChild("else").Line(string.Format("{0}.Value = SafeAssign.GetInstance(instNET.{1});", str5, info.Name));
                        }
                    }
                    else if (str3 != null)
                    {
                        CodeWriter writer13;
                        if (fieldType.IsValueType)
                        {
                            writer13 = writer6;
                        }
                        else
                        {
                            writer13 = writer6.AddChild(string.Format("if(instNET.{0} != null)", info.Name));
                            writer6.AddChild("else").Line(string.Format("{0}.Value = null;", str5));
                        }
                        if (isArray)
                        {
                            writer13.Line(string.Format("int len = instNET.{0}.Length;", info.Name));
                            writer13.Line("ManagementObject[] embeddedObjects = new ManagementObject[len];");
                            writer13.Line(string.Format("{0}[] embeddedConverters = new {0}[len];", str4));
                            CodeWriter writer15 = writer13.AddChild("for(int i=0;i<len;i++)");
                            writer15.Line(string.Format("embeddedConverters[i] = new {0}();", str4));
                            if (fieldType.IsValueType)
                            {
                                writer15.Line(string.Format("embeddedConverters[i].ToWMI(instNET.{0}[i]);", info.Name));
                            }
                            else
                            {
                                writer15.AddChild(string.Format("if(instNET.{0}[i] != null)", info.Name)).Line(string.Format("embeddedConverters[i].ToWMI(instNET.{0}[i]);", info.Name));
                            }
                            writer15.Line("embeddedObjects[i] = embeddedConverters[i].instance;");
                            writer13.Line(string.Format("{0}.Value = embeddedObjects;", str5));
                        }
                        else
                        {
                            writer2.Line(string.Format("{0} lazy_embeddedConverter_{1} = null;", str4, str5));
                            CodeWriter writer18 = writer.AddChild(string.Format("{0} embeddedConverter_{1}", str4, str5)).AddChild("get");
                            writer18.AddChild(string.Format("if(null == lazy_embeddedConverter_{0})", str5)).Line(string.Format("lazy_embeddedConverter_{0} = new {1}();", str5, str4));
                            writer18.Line(string.Format("return lazy_embeddedConverter_{0};", str5));
                            writer13.Line(string.Format("embeddedConverter_{0}.ToWMI(instNET.{1});", str5, info.Name));
                            writer13.Line(string.Format("{0}.Value = embeddedConverter_{0}.instance;", str5));
                        }
                    }
                    else if (!isArray)
                    {
                        if ((fieldType == typeof(byte)) || (fieldType == typeof(sbyte)))
                        {
                            writer6.Line(string.Format("{0} instNET_{1} = instNET.{1} ;", fieldType, info.Name));
                            writer6.Line(string.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 1, ref instNET_{1});", str6, info.Name));
                        }
                        else if (((fieldType == typeof(short)) || (fieldType == typeof(ushort))) || (fieldType == typeof(char)))
                        {
                            writer6.Line(string.Format("{0} instNET_{1} = instNET.{1} ;", fieldType, info.Name));
                            writer6.Line(string.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 2, ref instNET_{1});", str6, info.Name));
                        }
                        else if (((fieldType == typeof(uint)) || (fieldType == typeof(int))) || (fieldType == typeof(float)))
                        {
                            writer6.Line(string.Format("IWOA.WriteDWORD_f31(31, instWbemObjectAccessIP, {0}, instNET.{1});", str6, info.Name));
                        }
                        else if (((fieldType == typeof(ulong)) || (fieldType == typeof(long))) || (fieldType == typeof(double)))
                        {
                            writer6.Line(string.Format("IWOA.WriteQWORD_f33(33, instWbemObjectAccessIP, {0}, instNET.{1});", str6, info.Name));
                        }
                        else if (fieldType == typeof(bool))
                        {
                            writer6.Line(string.Format("if(instNET.{0})", info.Name));
                            writer6.Line(string.Format("    IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 2, ref SafeAssign.boolTrue);", str6));
                            writer6.Line("else");
                            writer6.Line(string.Format("    IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 2, ref SafeAssign.boolFalse);", str6));
                        }
                        else if (fieldType == typeof(string))
                        {
                            writer6.AddChild(string.Format("if(null != instNET.{0})", info.Name)).Line(string.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, (instNET.{1}.Length+1)*2, instNET.{1});", str6, info.Name));
                            writer6.AddChild("else").Line(string.Format("IWOA.Put_f5(5, instWbemObjectAccessIP, \"{0}\", 0, ref nullObj, 8);", memberName));
                            if (!flag3)
                            {
                                flag3 = true;
                                writer2.Line("object nullObj = DBNull.Value;");
                            }
                        }
                        else if ((fieldType == typeof(DateTime)) || (fieldType == typeof(TimeSpan)))
                        {
                            writer6.Line(string.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 52, SafeAssign.WMITimeToString(instNET.{1}));", str6, info.Name));
                        }
                        else
                        {
                            writer6.Line(string.Format("{0}.Value = instNET.{1};", str5, info.Name));
                        }
                    }
                    else if ((fieldType == typeof(DateTime)) || (fieldType == typeof(TimeSpan)))
                    {
                        writer6.AddChild(string.Format("if(null == instNET.{0})", info.Name)).Line(string.Format("{0}.Value = null;", str5));
                        writer6.AddChild("else").Line(string.Format("{0}.Value = SafeAssign.WMITimeArrayToStringArray(instNET.{1});", str5, info.Name));
                    }
                    else
                    {
                        writer6.Line(string.Format("{0}.Value = instNET.{1};", str5, info.Name));
                    }
                    CimType propertyType = CimType.String;
                    if (info.DeclaringType == type)
                    {
                        bool flag6 = true;
                        try
                        {
                            PropertyData data2 = this.newClass.Properties[memberName];
                            CimType      type1 = data2.Type;
                            if (data2.IsLocal)
                            {
                                throw new ArgumentException(string.Format(RC.GetString("MEMBERCONFLILCT_EXCEPT"), info.Name), info.Name);
                            }
                        }
                        catch (ManagementException exception2)
                        {
                            if (exception2.ErrorCode != ManagementStatus.NotFound)
                            {
                                throw;
                            }
                            flag6 = false;
                        }
                        if (!flag6)
                        {
                            if (str3 != null)
                            {
                                propertyType = CimType.Object;
                            }
                            else if (flag5)
                            {
                                propertyType = CimType.Object;
                            }
                            else if (fieldType == typeof(ManagementObject))
                            {
                                propertyType = CimType.Object;
                            }
                            else if (fieldType == typeof(sbyte))
                            {
                                propertyType = CimType.SInt8;
                            }
                            else if (fieldType == typeof(byte))
                            {
                                propertyType = CimType.UInt8;
                            }
                            else if (fieldType == typeof(short))
                            {
                                propertyType = CimType.SInt16;
                            }
                            else if (fieldType == typeof(ushort))
                            {
                                propertyType = CimType.UInt16;
                            }
                            else if (fieldType == typeof(int))
                            {
                                propertyType = CimType.SInt32;
                            }
                            else if (fieldType == typeof(uint))
                            {
                                propertyType = CimType.UInt32;
                            }
                            else if (fieldType == typeof(long))
                            {
                                propertyType = CimType.SInt64;
                            }
                            else if (fieldType == typeof(ulong))
                            {
                                propertyType = CimType.UInt64;
                            }
                            else if (fieldType == typeof(float))
                            {
                                propertyType = CimType.Real32;
                            }
                            else if (fieldType == typeof(double))
                            {
                                propertyType = CimType.Real64;
                            }
                            else if (fieldType == typeof(bool))
                            {
                                propertyType = CimType.Boolean;
                            }
                            else if (fieldType == typeof(string))
                            {
                                propertyType = CimType.String;
                            }
                            else if (fieldType == typeof(char))
                            {
                                propertyType = CimType.Char16;
                            }
                            else if (fieldType == typeof(DateTime))
                            {
                                propertyType = CimType.DateTime;
                            }
                            else if (fieldType == typeof(TimeSpan))
                            {
                                propertyType = CimType.DateTime;
                            }
                            else
                            {
                                ThrowUnsupportedMember(info);
                            }
                            try
                            {
                                properties.Add(memberName, propertyType, isArray);
                            }
                            catch (ManagementException exception3)
                            {
                                ThrowUnsupportedMember(info, exception3);
                            }
                            if (fieldType == typeof(TimeSpan))
                            {
                                PropertyData data3 = properties[memberName];
                                data3.Qualifiers.Add("SubType", "interval", false, true, true, true);
                            }
                            if (str3 != null)
                            {
                                PropertyData data4 = properties[memberName];
                                data4.Qualifiers["CIMTYPE"].Value = "object:" + str3;
                            }
                        }
                    }
                }
            }
            writer3.Line("Marshal.Release(wbemObjectAccessIP);");
        }
Exemplo n.º 23
0
 public ClassHandler(ManagementScope wmiScope, string className)
 {
     this.wmiClass  = new ManagementClass(wmiScope, new ManagementPath(className), null);
     this.className = className;
 }
Exemplo n.º 24
0
    public static String GetWindowMangager()
    {
        ManagementClass mc = new ManagementClass("Win32_OperatingSystem");
        ManagementObjectCollection moc = mc.GetInstances();
        String Id = String.Empty;
        foreach (ManagementObject mo in moc)
        {

            Id = mo.Properties["Version"].Value.ToString();
            break;
        }
        return Id;
    }
Exemplo n.º 25
0
    public static String GetHDInfoFree()
    {
        ManagementClass mc = new ManagementClass("Win32_LogicalDisk");
        ManagementObjectCollection moc = mc.GetInstances();
        String Id = String.Empty;
        foreach (ManagementObject mo in moc)
        {

            Id = mo.Properties["FreeSpace"].Value.ToString();
            break;
        }
        return Id;
    }
Exemplo n.º 26
0
	private static string smethod_22()
	{
		if (!Class1.bool_5)
		{
			Class1.bool_5 = true;
			try
			{
				string text = string.Empty;
				ManagementClass managementClass = new ManagementClass("Win32_DiskDrive");
				ManagementObjectCollection instances = managementClass.GetInstances();
				using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = instances.GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						ManagementObject managementObject = (ManagementObject)enumerator.Current;
						try
						{
							if (text == string.Empty && managementObject.Properties["PnPDeviceID"] != null && managementObject.Properties["PnPDeviceID"].Value != null)
							{
								text = managementObject.Properties["PnPDeviceID"].Value.ToString();
								if (text.Length > 0 && text.IndexOf("USBSTOR") >= 0)
								{
									text = "";
								}
								if (managementObject.Properties["InterfaceType"] != null && managementObject.Properties["InterfaceType"].Value != null)
								{
									if (managementObject.Properties["InterfaceType"].Value.ToString() == "USB")
									{
										text = "";
									}
									if (managementObject.Properties["InterfaceType"].Value.ToString() == "1394")
									{
										text = "";
									}
								}
								if (text.Length != 0)
								{
									break;
								}
								text = string.Empty;
							}
						}
						catch
						{
						}
					}
				}
				if (text == string.Empty)
				{
					text = "";
				}
				Class1.string_9 = text;
				if (Class1.string_9.Length > 0)
				{
					string[] array = Class1.string_9.Split(new char[]
					{
						'\\'
					});
					Class1.string_9 = array[array.Length - 1];
				}
			}
			catch
			{
				Class1.string_9 = "";
			}
		}
		return Class1.string_9;
	}
Exemplo n.º 27
0
        public SchemaMapping(Type type, SchemaNaming naming)
        {
            classType = type;

            string baseClassName = ManagedNameAttribute.GetBaseClassName(type);

            className           = ManagedNameAttribute.GetMemberName(type);
            instrumentationType = InstrumentationClassAttribute.GetAttribute(type).InstrumentationType;

            classPath = naming.NamespaceName + ":" + className;

            if (null == baseClassName)
            {
                newClass = new ManagementClass(naming.NamespaceName, "", null);
                newClass.SystemProperties ["__CLASS"].Value = className;
            }
            else
            {
                ManagementClass baseClass = new ManagementClass(naming.NamespaceName + ":" + baseClassName);
                newClass = baseClass.Derive(className);
            }

            PropertyDataCollection props = newClass.Properties;

            // type specific info
            switch (instrumentationType)
            {
            case InstrumentationType.Event:
                break;

            case InstrumentationType.Instance:
                props.Add("ProcessId", CimType.String, false);
                props.Add("InstanceId", CimType.String, false);
                props["ProcessId"].Qualifiers.Add("key", true);
                props["InstanceId"].Qualifiers.Add("key", true);
                newClass.Qualifiers.Add("dynamic", true, false, false, false, true);
                newClass.Qualifiers.Add("provider", naming.DecoupledProviderInstanceName, false, false, false, true);
                break;

            case InstrumentationType.Abstract:
                newClass.Qualifiers.Add("abstract", true, false, false, false, true);
                break;

            default:
                break;
            }

            foreach (MemberInfo field in type.GetFields())
            {
                if (!(field is FieldInfo || field is PropertyInfo))
                {
                    continue;
                }

                if (field.DeclaringType != type)
                {
                    continue;
                }

                if (field.GetCustomAttributes(typeof(IgnoreMemberAttribute), false).Length > 0)
                {
                    continue;
                }

                String propName = ManagedNameAttribute.GetMemberName(field);


#if REQUIRES_EXPLICIT_DECLARATION_OF_INHERITED_PROPERTIES
                if (InheritedPropertyAttribute.GetAttribute(field) != null)
                {
                    continue;
                }
#else
                // See if this field already exists on the WMI class
                // In other words, is it inherited from a base class
                // TODO: Make this more efficient
                //  - If we have a null base class name, all property names
                //    should be new
                //  - We could get all base class property names into a
                //    hashtable, and look them up from there
                bool propertyExists = true;
                try
                {
                    PropertyData prop = newClass.Properties[propName];
                }
                catch (ManagementException e)
                {
                    if (e.ErrorCode != ManagementStatus.NotFound)
                    {
                        throw e;
                    }
                    else
                    {
                        propertyExists = false;
                    }
                }
                if (propertyExists)
                {
                    continue;
                }
#endif

#if SUPPORTS_ALTERNATE_WMI_PROPERTY_TYPE
                Type t2 = ManagedTypeAttribute.GetManagedType(field);
#else
                Type t2;
                if (field is FieldInfo)
                {
                    t2 = (field as FieldInfo).FieldType;
                }
                else
                {
                    t2 = (field as PropertyInfo).PropertyType;
                }
#endif

                CimType cimtype = CimType.String;

                if (t2 == typeof(SByte))
                {
                    cimtype = CimType.SInt8;
                }
                else if (t2 == typeof(Byte))
                {
                    cimtype = CimType.UInt8;
                }
                else if (t2 == typeof(Int16))
                {
                    cimtype = CimType.SInt16;
                }
                else if (t2 == typeof(UInt16))
                {
                    cimtype = CimType.UInt16;
                }
                else if (t2 == typeof(Int32))
                {
                    cimtype = CimType.SInt32;
                }
                else if (t2 == typeof(UInt32))
                {
                    cimtype = CimType.UInt32;
                }
                else if (t2 == typeof(Int64))
                {
                    cimtype = CimType.SInt64;
                }
                else if (t2 == typeof(UInt64))
                {
                    cimtype = CimType.UInt64;
                }
                else if (t2 == typeof(Single))
                {
                    cimtype = CimType.Real32;
                }
                else if (t2 == typeof(Double))
                {
                    cimtype = CimType.Real64;
                }
                else if (t2 == typeof(Boolean))
                {
                    cimtype = CimType.Boolean;
                }
                else if (t2 == typeof(String))
                {
                    cimtype = CimType.String;
                }
                else if (t2 == typeof(Char))
                {
                    cimtype = CimType.Char16;
                }
                else if (t2 == typeof(DateTime))
                {
                    cimtype = CimType.DateTime;
                }
                else if (t2 == typeof(TimeSpan))
                {
                    cimtype = CimType.DateTime;
                }
                else
                {
                    throw new Exception(String.Format("Unsupported type for event member - {0}", t2.Name));
                }
// HACK: The following line cause a strange System.InvalidProgramException when run through InstallUtil
//				throw new Exception("Unsupported type for event member - " + t2.Name);


//              TODO: if(t2 == typeof(Decimal))

#if SUPPORTS_WMI_DEFAULT_VAULES
                Object defaultValue = ManagedDefaultValueAttribute.GetManagedDefaultValue(field);

                // TODO: Is it safe to make this one line?
                if (null == defaultValue)
                {
                    props.Add(propName, cimtype, false);
                }
                else
                {
                    props.Add(propName, defaultValue, cimtype);
                }
#else
                props.Add(propName, cimtype, false);
#endif

                // Must at 'interval' SubType on TimeSpans
                if (t2 == typeof(TimeSpan))
                {
                    PropertyData prop = props[propName];
                    prop.Qualifiers.Add("SubType", "interval", false, true, true, true);
                }
            }
        }
Exemplo n.º 28
0
        public static Dictionary <long, InterfaceInformation> ListAllInterfaces()
        {
            if (Os.Ver == Os.V.XpOrLower)
            {
                throw new NotSupportedException("Windows Version Too Low");
            }

            var  transId = new Dictionary <string, uint>();
            long accu    = -1;
            var  result  = new Dictionary <long, InterfaceInformation>();

            if (Os.Ver == Os.V.VistaOrSeven)
            {
                ManagementClass nic = new ManagementClass(@"\\.\ROOT\cimv2:Win32_NetworkAdapter");
                foreach (var a in nic.GetInstances())
                {
                    var key   = (uint)a["InterfaceIndex"];
                    var value = new InterfaceInformation {
                        WMI_Win32_NetworkAdapter_Exist = true,
                        WMI_WNA_AdapterType            = a["AdapterType"] as string,
                        WMI_WNA_Availability           = Convert.ToUInt16(a["Availability"]),
                        WMI_WNA_Caption             = a["Caption"] as string,
                        WMI_WNA_Description         = a["Description"] as string,
                        WMI_WNA_DeviceID            = a["DeviceID"] as string,
                        WMI_WNA_GUID                = a["GUID"] as string,
                        WMI_WNA_Index               = Convert.ToUInt32(a["Index"]),
                        WMI_WNA_InterfaceIndex      = Convert.ToUInt32(a["InterfaceIndex"]),
                        WMI_WNA_Name                = a["Name"] as string,
                        WMI_WNA_NetConnectionID     = a["NetConnectionID"] as string,
                        WMI_WNA_NetConnectionStatus = Convert.ToUInt16(a["NetConnectionStatus"]),
                        WMI_WNA_PhysicalAdapter     = Convert.ToBoolean(a["PhysicalAdapter"]),
                        WMI_WNA_Status              = a["Status"] as string
                    };
                    result.Add(key, value);
                    if (!string.IsNullOrEmpty(value.WMI_WNA_GUID))
                    {
                        transId.Add(value.WMI_WNA_GUID, key);
                    }
                }
            }
            else
            {
                // win8 or higher
                ManagementClass nic = new ManagementClass(@"\\.\ROOT\StandardCimv2:MSFT_NetAdapter");
                foreach (var a in nic.GetInstances())
                {
                    var key   = (uint)a["InterfaceIndex"];
                    var value = new InterfaceInformation {
                        WMI_MSFT_NetAdapter_Exist        = true,
                        WMI_MSFT_NA_Availability         = Convert.ToUInt16(a["Availability"]),
                        WMI_MSFT_NA_Caption              = a["Caption"] as string,
                        WMI_MSFT_NA_ConnectorPresent     = Convert.ToBoolean(a["ConnectorPresent"]),
                        WMI_MSFT_NA_Description          = a["Description"] as string,
                        WMI_MSFT_NA_DeviceID             = a["DeviceID"] as string,
                        WMI_MSFT_NA_DeviceName           = a["DeviceName"] as string,
                        WMI_MSFT_NA_HardwareInterface    = Convert.ToBoolean(a["HardwareInterface"]),
                        WMI_MSFT_NA_InterfaceDescription = a["InterfaceDescription"] as string,
                        WMI_MSFT_NA_InterfaceGuid        = a["InterfaceGuid"] as string,
                        WMI_MSFT_NA_InterfaceIndex       = Convert.ToUInt32(a["InterfaceIndex"]),
                        WMI_MSFT_NA_InterfaceName        = a["InterfaceName"] as string,
                        WMI_MSFT_NA_MediaConnectState    = Convert.ToUInt32(a["MediaConnectState"]),
                        WMI_MSFT_NA_MtuSize              = Convert.ToUInt32(a["MtuSize"]),
                        WMI_MSFT_NA_Name        = a["Name"] as string,
                        WMI_MSFT_NA_NetLuid     = Convert.ToUInt64(a["NetLuid"]),
                        WMI_MSFT_NA_PNPDeviceID = a["PNPDeviceID"] as string,
                        WMI_MSFT_NA_Status      = a["Status"] as string,
                        WMI_MSFT_NA_Virtual     = Convert.ToBoolean(a["Virtual"])
                    };

                    result.Add(key, value);
                    if (!string.IsNullOrEmpty(value.WMI_MSFT_NA_DeviceID))
                    {
                        transId.Add(value.WMI_MSFT_NA_DeviceID, key);
                    }
                }
            }

            foreach (var row in IPNetHelper.GetInterfaceTable())
            {
                if (!result.ContainsKey(row.InterfaceIndex))
                {
                    result.Add(row.InterfaceIndex, new InterfaceInformation());
                }
                result[row.InterfaceIndex].IPHLPAPI_IFINTERFACE_ROW_Exist = true;
                result[row.InterfaceIndex].IP_IFR_InterfaceLuid           = row.InterfaceLuid;
                result[row.InterfaceIndex].IP_IFR_InterfaceIndex          = row.InterfaceIndex;
                result[row.InterfaceIndex].IP_IFR_UseAutomaticMetric      = row.UseAutomaticMetric == 1;
                result[row.InterfaceIndex].IP_IFR_Metric               = row.Metric;
                result[row.InterfaceIndex].IP_IFR_NlMtu                = row.NlMtu;
                result[row.InterfaceIndex].IP_IFR_Connected            = row.Connected == 1;
                result[row.InterfaceIndex].IP_IFR_DisableDefaultRoutes = row.DisableDefaultRoutes == 1;
            }

            ManagementClass mc = new ManagementClass(@"\\.\ROOT\cimv2:Win32_NetworkAdapterConfiguration");

            foreach (var a in mc.GetInstances())
            {
                var key = (uint)a["InterfaceIndex"];
                if (!result.ContainsKey(key))
                {
                    result.Add(key, new InterfaceInformation());
                }
                result[key].WMI_Win32_NetworkAdapterConfiguration_Exist = true;
                result[key].WMI_NAC_Caption          = a["Caption"] as string;
                result[key].WMI_NAC_Description      = a["Description"] as string;
                result[key].WMI_NAC_DefaultIPGateway = a["DefaultIPGateway"] == null
                    ? ""
                    : string.Join(", ", (string[])a["DefaultIPGateway"]);
                result[key].WMI_NAC_Index                = Convert.ToUInt32(a["Index"]);
                result[key].WMI_NAC_InterfaceIndex       = Convert.ToUInt32(a["InterfaceIndex"]);
                result[key].WMI_NAC_DNSServerSearchOrder = a["DNSServerSearchOrder"] == null
                    ? ""
                    : string.Join(", ", (string[])a["DNSServerSearchOrder"]);
                result[key].WMI_NAC_DHCPEnabled        = Convert.ToBoolean(a["DHCPEnabled"]);
                result[key].WMI_NAC_IPEnabled          = Convert.ToBoolean(a["IPEnabled"]);
                result[key].WMI_NAC_IPConnectionMetric = Convert.ToUInt32(a["IPConnectionMetric"]);
                result[key].WMI_NAC_IPAddress          = a["IPAddress"] == null
                    ? ""
                    : string.Join(", ", (string[])a["IPAddress"]);
                result[key].WMI_NAC_MTU        = Convert.ToUInt32(a["MTU"]);
                result[key].WMI_NAC_MACAddress = a["MACAddress"] as string;
            }

            foreach (var adaptor in NetworkInterface.GetAllNetworkInterfaces())
            {
                long key;
                if (transId.ContainsKey(adaptor.Id))
                {
                    key = transId[adaptor.Id];
                }
                else
                {
                    if (adaptor.Supports(NetworkInterfaceComponent.IPv4) && result.ContainsKey(adaptor.GetIPProperties().GetIPv4Properties().Index))
                    {
                        key = adaptor.GetIPProperties().GetIPv4Properties().Index;
                    }
                    else
                    {
                        key   = accu;
                        accu -= 1;
                        result.Add(key, new InterfaceInformation());
                    }
                }
                result[key].Net_NetworkInterface_Exist = true;
                result[key].Net_ID                   = adaptor.Id;
                result[key].Net_Description          = adaptor.Description;
                result[key].Net_Name                 = adaptor.Name;
                result[key].Net_OperationalStatus    = adaptor.OperationalStatus.ToString();
                result[key].Net_SupportIPv4          = adaptor.Supports(NetworkInterfaceComponent.IPv4);
                result[key].Net_NetworkInterfaceType = adaptor.NetworkInterfaceType.ToString();
                if (adaptor.Supports(NetworkInterfaceComponent.IPv4))
                {
                    result[key].Net_IPv4Index = adaptor.GetIPProperties().GetIPv4Properties().Index;
                    result[key].Net_IPv4MTU   = adaptor.GetIPProperties().GetIPv4Properties().Mtu;
                }
                result[key].Net_DnsAddresses     = string.Join(", ", adaptor.GetIPProperties().DnsAddresses);
                result[key].Net_GatewayAddresses = string.Join(", ",
                                                               adaptor.GetIPProperties().GatewayAddresses.ToList().ConvertAll(gi => gi.Address.ToString()));
            }

            return(result);
        }
Exemplo n.º 29
0
        public void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            
           HardWareInfo hardWareInfo =new HardWareInfo();
           
           ListBox1.Items.Add("系统名称:"+hardWareInfo.GetSystemName());
           ListBox1.Items.Add("BiosID:"+hardWareInfo.GetBiosID());
           ListBox1.Items.Add("磁盘总空间:"+hardWareInfo.GetHardDiskSpace()[0]+"GB");
           ListBox1.Items.Add("磁盘剩余空间:"+hardWareInfo.GetHardDiskSpace()[1]+"GB");
           ListBox1.Items.Add( "CPU名称:"+hardWareInfo.GetCPUName());
           ListBox1.Items.Add("CPU核心数量:"+hardWareInfo.GetCPUNumber());
          
          
           ListBox1.Items.Add("主板ID:"+hardWareInfo.GetMainBoardID());
          
           ListBox1.Items.Add("显存大小:"+ hardWareInfo.GetGPUMemorySize()+"GB");
           ListBox1.Items.Add("系统内存:"+hardWareInfo.GetSystemMemorySizeOfGB()+"GB");
           
           
           
           
            
            ManagementObjectSearcher objvide = new ManagementObjectSearcher("select * from Win32_VideoController");
            
            foreach (ManagementObject obj in objvide.Get())
            { 
                ListBox1.Items.Add("显卡 - " + obj["Name"]);
           
            }
            
            //创建ManagementObjectSearcher对象
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
            //存储磁盘序列号
            //调用ManagementObjectSearcher类的Get方法取得硬盘序列号
            foreach (ManagementObject mo in searcher.Get())
            {
               //记录获得的磁盘序列号
                ListBox1.Items.Add( "硬盘序列号: "+mo["SerialNumber"].ToString().Trim());//显示硬盘序列号
               
            }
            
            ManagementClass mc = new ManagementClass("Win32_DiskDrive");
            ManagementObjectCollection moj = mc.GetInstances();
            foreach (ManagementObject m in moj)
            {
                ListBox1.Items.Add("磁盘大小:"+m.Properties["Size"].Value.ToString()) ;
            }

            ManagementClass mc1 = new ManagementClass("Win32_OperatingSystem");
            ManagementObjectCollection moc = mc1.GetInstances();
            double sizeAll = 0.0;
            foreach (ManagementObject m in moc)
            {
                if (m.Properties["TotalVisibleMemorySize"].Value != null)
                {
                    sizeAll += Convert.ToDouble(m.Properties["TotalVisibleMemorySize"].Value.ToString());
                     ListBox1.Items.Add("内存大小:" +sizeAll.ToString());
                }
            }
           
            
           
            
           

            //获取CPU序列号代码 
           
            ManagementClass mc2 = new ManagementClass("Win32_Processor");
            ManagementObjectCollection moc1 = mc2.GetInstances();
            foreach (ManagementObject mo in moc1)
            {
               
                 ListBox1.Items.Add("CPU编号:" + mo.Properties["ProcessorId"].Value.ToString());
            }
          
           

            //获取网卡硬件地址 
            
            ManagementClass mc3 = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc4 = mc3.GetInstances();
            foreach (ManagementObject mo in moc4)
            {
                if ((bool)mo["IPEnabled"] == true)
                {
                   
                    ListBox1.Items.Add("MAC地址:" + mo["MacAddress"].ToString());
                }
            }
           
            
           

            //获取IP地址 
            
            ManagementClass mc5 = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc3 = mc5.GetInstances();
            foreach (ManagementObject mo in moc3)
            {
                if ((bool)mo["IPEnabled"] == true)
                {
                    //st=mo["IpAddress"].ToString(); 
                    System.Array ar;
                    ar = (System.Array)(mo.Properties["IpAddress"].Value);
                    string st = ar.GetValue(0).ToString();
                    ListBox1.Items.Add("IP地址:" + st);
                    
                }
            }
           
            
            
           
            ManagementClass mc6 = new ManagementClass("Win32_DiskDrive");
            ManagementObjectCollection moc5 = mc6.GetInstances();
            foreach (ManagementObject mo in moc5)
            {             
                ListBox1.Items.Add("磁盘名称:" + (string)mo.Properties["Model"].Value);
            }
           
           

            
            ManagementClass mc7 = new ManagementClass("Win32_ComputerSystem");
            ManagementObjectCollection moc6 = mc7.GetInstances();
            foreach (ManagementObject mo in moc6)
            {
                
                
                ListBox1.Items.Add("PC类型:" + mo["SystemType"].ToString());
            }
            
            
            //计算机名
            ListBox1.Items.Add("计算机名:"+System.Environment.GetEnvironmentVariable("ComputerName"));
        }
Exemplo n.º 30
0
        private void share_Click(object sender, EventArgs e)
        {
            string sharepath = "C:\\Shares\\";

            if (lbFiles.Items.Count == 0)
            {
                MessageBox.Show("You must select files to share.", "SelectShare", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (lbGroups.Items.Count == 0)
            {
                MessageBox.Show("You must select users/groups with whom to share.", "SelectShare", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (textBox1.Text == "")
            {
                MessageBox.Show("You must select a unique share name.", "SelectShare", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string sname = sharepath + textBox1.Text;

            if (Directory.Exists(sname))
            {
                MessageBox.Show("Chosen share name is in use. Please choose another.", "SelectShare", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Directory.CreateDirectory(sname);

            var choice = groupBox1.Controls.OfType <RadioButton>().FirstOrDefault(r => r.Checked);

            foreach (var fn in lbFiles.Items)
            {
                if (choice == radioButton3)
                {
                    File.Copy(fn.ToString(), sname + "\\" + Path.GetFileName(fn.ToString()));
                }

                if (choice == radioButton4)
                {
                    File.Move(fn.ToString(), sname + "\\" + Path.GetFileName(fn.ToString()));
                }
            }
            try
            {
                ManagementObject oGrpSecurityDescriptor = new ManagementClass(new ManagementPath("Win32_SecurityDescriptor"), null);
                oGrpSecurityDescriptor["ControlFlags"] = 4; //SE_DACL_PRESENT
                var otmp = new object[lbGroups.Items.Count];
                int i    = 0;
                foreach (var ug in lbGroups.Items)
                {
                    otmp[i] = genUGSec(ug.ToString());
                    i++;
                }
                oGrpSecurityDescriptor["DACL"] = otmp;
                ManagementClass      mc       = new ManagementClass("Win32_Share");
                ManagementBaseObject inParams = mc.GetMethodParameters("Create");
                ManagementBaseObject outParams;
                inParams["Description"] = textBox1.Text;
                inParams["Name"]        = textBox1.Text;
                inParams["Path"]        = sname;
                inParams["Type"]        = 0x0; // Disk Drive\ inParams["MaximumAllowed"] = null;
                inParams["Password"]    = null;
                inParams["Access"]      = oGrpSecurityDescriptor;
                outParams = mc.InvokeMethod("Create", inParams, null);
                if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
                {
                    throw new Exception("Unable to share directory.");
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); return; }
        }
 static ManagementObjectCollection \u206F‭‏‫​‬‏​‏‬‪‭​‮‪‌‎‪‭‍‭‍‍‎‎‏‍‬‬‌‌‮‮‬‮([In] ManagementClass obj0)
 {
     // ISSUE: unable to decompile the method.
 }
Exemplo n.º 32
0
        private static void RunRemoteProcesses()
        {
            using (CountingReader reader = new CountingReader(new FileInfo(Global.GetInputPath(Global.Configuration.RawHouseholdPath)).OpenRead())) {
                while (reader.ReadLine() != null)
                {
                    _householdCount++;
                }
            }

            _householdCount--;

            List <RemoteMachine> machines = RemoteMachine.GetAll();
            int range = (int)Math.Ceiling(_householdCount / machines.Count);

            for (int i = 0; i < machines.Count; i++)
            {
                int start = (range * i);
                int end   = (int)Math.Min((range * i) + range - 1, _householdCount - 1);

                RemoteMachine machine = machines[i];

                //run a local remote DaySim session for debugging if desired
                if (Environment.MachineName.Equals(machine.Name, StringComparison.OrdinalIgnoreCase))
                {
                    Process process = new Process {
                        StartInfo =
                        {
                            UseShellExecute = false,
                            CreateNoWindow  = true,
                            FileName        = machine.Filename,
                            Arguments       = machine.Arguments + " /s=" + start + " /e=" + end + " /i=" + i
                        }
                    };

                    process.Start();

                    _processes.Add(Tuple.Create(process, machine, new Timer()));
                }
                else
                {
                    //remote a remote DaySim session using WMI and RPC
                    ConnectionOptions connectionOptions = new ConnectionOptions {
                        Username = Global.Configuration.RemoteUsername, Password = Global.Configuration.RemotePassword
                    };
                    ManagementScope managementScope = new ManagementScope(string.Format(@"\\{0}\ROOT\CIMV2", machine.Name), connectionOptions);

                    managementScope.Connect();

                    ManagementClass      processClass = new ManagementClass(managementScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
                    ManagementBaseObject inParameters = processClass.GetMethodParameters("Create");

                    inParameters["CurrentDirectory"] = machine.CurrentDirectory;
                    inParameters["CommandLine"]      = machine.CommandLine + " /s=" + start + " /e=" + end + " /i=" + i;

                    ManagementBaseObject outParameters = processClass.InvokeMethod("Create", inParameters, null);

                    if ((uint)outParameters.Properties["ReturnValue"].Value == 0)
                    {
                        _instances.Add(Tuple.Create(managementScope, outParameters, machine, new Timer()));
                    }
                }
            }

            List <Thread> threads = new List <Thread>();

            foreach (Tuple <Process, RemoteMachine, Timer> process in _processes)
            {
                ParameterizedThreadStart start = new ParameterizedThreadStart(BeginLocalWatch);
                Thread thread = new Thread(start);

                thread.Start(process);
                threads.Add(thread);
            }

            foreach (Tuple <ManagementScope, ManagementBaseObject, RemoteMachine, Timer> instance in _instances)
            {
                ParameterizedThreadStart start = new ParameterizedThreadStart(BeginRemoteWatch);
                Thread thread = new Thread(start);

                thread.Start(instance);
                threads.Add(thread);
            }

            foreach (Thread thread in threads)
            {
                thread.Join();
            }
        }
Exemplo n.º 33
0
        /// <summary>
        /// 将已填入信息写入数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            //如果有的信息没有填入,则出现提示
            if (txtComputerID.Text == "")
            {
                MessageBox.Show("所有信息不能为空!请再填入一次!");
            }


            //获取本机CPU序列号
            try
            {
                ManagementClass            mc  = new ManagementClass("Win32_Processor");
                ManagementObjectCollection moc = mc.GetInstances();

                String strCpuID = null;
                foreach (ManagementObject mo in moc)
                {
                    strCpuID = mo.Properties["ProcessorId"].Value.ToString();
                    break;
                }
                global.CPU = strCpuID;
            }
            catch
            {
                global.CPU = "";
            }



            //信息如果全部填入,则将数据写入数据库,并传递给全局变量传给下一个窗体
            global.CityID        = cmbCityID.Text;                     //城市编号
            global.CityName      = cmbCityName.Text;                   //城市名
            global.CountyName    = cmbCounty.Text;                     //区县名
            global.SchoolID      = cmbSchoolID.Text;                   //学校编号
            global.SchoolName    = cmbSchoolName.Text;                 //学校名
            global.SchoolKind    = cmbSchoolKind.Text;                 //学校类型
            global.SchoolQuality = cmbSchoolQuality.Text;              //学校性质
            global.ClassID       = cmbClassID.Text;                    //教室编号
            global.ClassAddress  = cmbClassAddress.Text;               //教室地址
            global.ComputerID    = txtComputerID.Text;                 //电脑编号


            /*
             * //调用存储过程
             * //将城市信息写入数据库
             * //String sqlString = "insert into tArea(cityID,cityName,countyName) values(" + global.CityID + "," + global.CityName + "," + global.CountyName + ")";
             * String sqlString = "exec insert InsertArea global.CityID,global.CityName,global.CountyName";
             * rowsDeleted = mDB.ExecuteSQL(sqlString);
             *
             *
             * //将学校信息写入数据库
             * //String sqlString1 = "insert into tSchool(SchoolID,SchoolName,SchoolKind,SchoolQuality) values(" + global.SchoolID + "," + global.SchoolName + "," + global.SchoolKind + "," + global.SchoolQuality + ")";
             * sqlString = "exec insert InsertSchool global.SchoolID,global.SchoolName,global.SchoolKind,global.SchoolQuality";
             * rowsDeleted = mDB.ExecuteSQL(sqlString);
             *
             * //将教室信息写入数据库
             * sqlString = "exec insert InsertClass global.ClassID,global.ClassAddress";
             * // String sqlString2 = "insert into tClass(ClassID,ClassAddress) values(" + global.ClassID + "," + global.ClassAddress + ")";
             * rowsDeleted = mDB.ExecuteSQL(sqlString);
             *
             * //将电脑信息写入数据库
             * sqlString = "exec insert InsertComputer global.ComputerID,global.CPU";
             * // String sqlString3 = "insert into tComputer(ComputerID,CPU) values(" + global.ComputerID + "," + global.CPU + ")";
             * rowsDeleted = mDB.ExecuteSQL(sqlString);
             *
             * // 操作完毕关闭数据库通道
             * mDB.Close();*/

            string        strsql  = "Data Source=127.0.0.1;Initial Catalog=dbProcess;Persist Security Info=True;User ID=sa;Password=LY19971025"; //数据库链接字符串
            string        sql1    = "InsertArea";                                                                                                //要调用的存储过程名
            string        sql2    = "InsertSchool";
            string        sql3    = "InsertClass";
            string        sql4    = " InsertComputer";
            SqlConnection conStr  = new SqlConnection(strsql);    //SQL数据库连接对象,以数据库链接字符串为参数
            SqlCommand    comStr1 = new SqlCommand(sql1, conStr); //SQL语句执行对象,第一个参数是要执行的语句,第二个是数据库连接对象
            SqlCommand    comStr2 = new SqlCommand(sql2, conStr);
            SqlCommand    comStr3 = new SqlCommand(sql3, conStr);
            SqlCommand    comStr4 = new SqlCommand(sql4, conStr);

            comStr1.CommandType = CommandType.StoredProcedure;//因为要使用的是存储过程,所以设置执行类型为存储过程
            comStr2.CommandType = CommandType.StoredProcedure;
            comStr3.CommandType = CommandType.StoredProcedure;
            comStr4.CommandType = CommandType.StoredProcedure;

            /* conStr.Open();//打开数据库连接
             *
             * //依次设定存储过程的参数
             * comStr1.Parameters.Add("@cityID", SqlDbType.VarChar, 10).Value = global.CityID;
             * comStr1.Parameters.Add("@cityName", SqlDbType.VarChar, 20).Value = global.CityName;
             * comStr1.Parameters.Add("@countyName", SqlDbType.VarChar, 20).Value = global.CountyName;
             * MessageBox.Show(comStr1.ExecuteNonQuery().ToString());//执行存储过程
             * conStr.Close();//关闭连接*/

            conStr.Open();//打开数据库连接
            comStr2.Parameters.Add("@cityID", SqlDbType.VarChar, 10).Value        = global.CityID;
            comStr2.Parameters.Add("@schoolID", SqlDbType.VarChar, 20).Value      = global.SchoolID;
            comStr2.Parameters.Add("@countyName", SqlDbType.VarChar, 20).Value    = global.CountyName;
            comStr2.Parameters.Add("@schoolName", SqlDbType.VarChar, 20).Value    = global.SchoolName;
            comStr2.Parameters.Add("@schoolKind", SqlDbType.VarChar, 20).Value    = global.SchoolKind;
            comStr2.Parameters.Add("@schoolQuality", SqlDbType.VarChar, 20).Value = global.ClassAddress;
            MessageBox.Show(comStr3.ExecuteNonQuery().ToString()); //执行存储过程
            conStr.Close();                                        //关闭连接

            /*comStr3.Parameters.Add("@schoolID", SqlDbType.VarChar, 20).Value = global.SchoolID;
             * comStr3.Parameters.Add("@classID", SqlDbType.VarChar, 20).Value = global.ClassID;
             * comStr3.Parameters.Add("@classAddress", SqlDbType.VarChar, 20).Value = cmbClassAddress.Text;
             * MessageBox.Show(comStr2.ExecuteNonQuery().ToString());//执行存储过程
             *
             * comStr3.Parameters.Add("@computerID", SqlDbType.VarChar, 20).Value = global.ComputerID;
             * comStr3.Parameters.Add("@cpuID", SqlDbType.VarChar, 20).Value = global.CPU;
             * MessageBox.Show(comStr4.ExecuteNonQuery().ToString());//执行存储过程
             */



            MessageBox.Show("对咯!");
        }
Exemplo n.º 34
0
        /// <summary>
        /// public static string GetMachineID()
        /// </summary>
        /// <returns></returns>
        public static string GetMachineID()
        {
            string                     CPUID = "";
            ManagementClass            mc    = new ManagementClass("Win32_Processor");
            ManagementObjectCollection moc   = mc.GetInstances();

            foreach (ManagementObject mo in moc)
            {
                CPUID += mo.Properties["ProcessorId"].Value.ToString() + Environment.NewLine;
                break;
            }
            CPUID.PadRight(16, 'A');
            CPUID = CPUID.Substring(0, 4) + CPUID.Substring(12);
            long iCPUID = 0;

            try
            {
                iCPUID = long.Parse(CPUID, System.Globalization.NumberStyles.HexNumber);
            }
            catch
            {
                return("---=== Unknow ===---");
            }
            string strCPUID = "";

            while (iCPUID > 35)
            {
                strCPUID += strCoder[Convert.ToInt32(iCPUID % 35)].ToString();
                iCPUID   /= 35;
            }
            strCPUID += strCoder[Convert.ToInt32(iCPUID)].ToString();
            string MainBoard = "";

            mc  = new ManagementClass("Win32_BaseBoard");
            moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                MainBoard += mo.Properties["SerialNumber"].Value.ToString().Trim();
                break;
            }
            mc.Dispose();
            moc.Dispose();
            string tmpMainBoard = "";

            for (int i = MainBoard.Length - 1; i > -1 && tmpMainBoard.Length < 12; i--)
            {
                if (strCoder.Contains(MainBoard[i].ToString()))
                {
                    tmpMainBoard = MainBoard[i].ToString() + tmpMainBoard;
                }
            }
            tmpMainBoard.PadLeft(12, 'A');
            long iMainboard = 0;

            for (int i = 0; i < tmpMainBoard.Length; i++)
            {
                iMainboard += Convert.ToInt64(strCoder.IndexOf(tmpMainBoard[i]) * Math.Pow(36, i));
            }
            string strMainBoard = "";

            while (iMainboard > 35)
            {
                strMainBoard += strCoder[Convert.ToInt32(iMainboard % 35)].ToString();
                iMainboard   /= 35;
            }
            strMainBoard += strCoder[Convert.ToInt32(iMainboard)].ToString();
            return(strCPUID + strMainBoard);
        }
Exemplo n.º 35
0
        private void applyButton_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;

            // Find correct index for the adapter
            int index = Int32.Parse(btn.Name.Split('_').ElementAt(1));

            // The correct element is found by searching the hierarchy down iteratively
            TextBlock adapterDescription = VisualTreeHelpers.FindChild <TextBlock>(AdapterStackPanel, ("adapter_" + index));
            TextBox   AdapterIP          = VisualTreeHelpers.FindChild <TextBox>(AdapterStackPanel, ("AdapterIP_" + index));
            TextBox   AdapterNetmask     = VisualTreeHelpers.FindChild <TextBox>(AdapterStackPanel, ("AdapterNetmask_" + index));
            TextBox   AdapterGateway     = VisualTreeHelpers.FindChild <TextBox>(AdapterStackPanel, ("AdapterGateway_" + index));
            CheckBox  DHCPselection      = VisualTreeHelpers.FindChild <CheckBox>(AdapterStackPanel, ("AdapterDHCPon_" + index));

            ManagementClass            adapterMC         = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection adapterCollection = adapterMC.GetInstances();

            foreach (ManagementObject adapter in adapterCollection)
            {
                if (String.Equals(adapter["Description"], adapterDescription.Text))
                {
                    // Enable static IP settings or DHCP based on the checkbox selection
                    if (DHCPselection.IsChecked == false)
                    {
                        try
                        {
                            // Set Default Gateway
                            var newGateway = adapter.GetMethodParameters("SetGateways");

                            // First set up the gateways with an empty array to clear the existing gateways
                            // It is assumed here that one gateway per adapter is sufficient
                            newGateway["DefaultIPGateway"]  = new string[] { };
                            newGateway["GatewayCostMetric"] = new int[] { 1 };
                            adapter.InvokeMethod("SetGateways", newGateway, null);

                            // Then add the actual gateway
                            newGateway["DefaultIPGateway"] = new string[] { AdapterGateway.Text };
                            adapter.InvokeMethod("SetGateways", newGateway, null);

                            // Set IP address and Subnet Mask
                            var newAddress = adapter.GetMethodParameters("EnableStatic");
                            newAddress["IPAddress"]  = new string[] { AdapterIP.Text };
                            newAddress["SubnetMask"] = new string[] { AdapterNetmask.Text };
                            adapter.InvokeMethod("EnableStatic", newAddress, null);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Unable to set static IP:\n" + ex.Message);
                        }
                    }
                    else
                    {
                        try
                        {
                            // Clear the gateway list before DHCP updates it so that
                            // no unintended gateways remain in the list
                            var newGateway = adapter.GetMethodParameters("SetGateways");
                            newGateway["DefaultIPGateway"]  = new string[] { };
                            newGateway["GatewayCostMetric"] = new int[] { 1 };
                            adapter.InvokeMethod("SetGateways", newGateway, null);

                            adapter.InvokeMethod("EnableDHCP", null);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Unable to set dynamic IP:\n" + ex.Message);
                        }
                    }

                    // Adapt the callback function to the ElapsedEventHandler format with a lambda expression
                    ApplyButtonTimer.Elapsed += (sender2, e2) => changeApplyButtonColor(sender2, e2, btn);

                    btn.Content    = "Applied";
                    btn.FontSize   = 10;
                    btn.Margin     = new Thickness(680, 5, 0, 0);
                    btn.Background = (SolidColorBrush) new BrushConverter().ConvertFromString(APPLYBUTTON_ALT_BG);

                    ApplyButtonTimer.Stop();
                    ApplyButtonTimer.Start();


                    break; // Further iteration unnecessary
                }
            }
        }
Exemplo n.º 36
0
 public void init()
 {
     _managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
     _nics            = _managementClass.GetInstances();
 }
Exemplo n.º 37
0
        private string GetWindows2000Power(ManagementClass wmiRegistry)
        {
            string powerInfo = "";
            string policy    = "0";

            try {
                ManagementBaseObject inParams = wmiRegistry.GetMethodParameters("GetStringValue");

                inParams["hDefKey"]     = HKEY_CURRENT_USER;
                inParams["sSubKeyName"] = @"Control Panel\PowerCfg";
                inParams["sValueName"]  = "CurrentPowerPolicy";

                ManagementBaseObject outParams = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                if (Convert.ToUInt32(outParams["ReturnValue"]) == 0)
                {
                    policy = outParams["sValue"].ToString();
                    inParams["hDefKey"]     = HKEY_CURRENT_USER;
                    inParams["sSubKeyName"] = @"Control Panel\PowerCfg\PowerPolicies\" + policy;
                    inParams["sValueName"]  = "Policies";

                    outParams = wmiRegistry.InvokeMethod("GetBinaryValue", inParams, null);
                    if (Convert.ToUInt32(outParams["ReturnValue"]) >= 0)
                    {
                        byte[] array = outParams["uValue"] as byte[];
                        string value = "";
                        for (int i = 0; i < array.Length; i++)
                        {
                            value = value + String.Format("{0:X2}", array[i]);
                            int valueLen = value.Length;
                            if ((i + 1) % 8 == 0)
                            {
                                int rowCount = (i + 1) / 8;
                                if (rowCount == 4)
                                {
                                    powerInfo = powerInfo + "" + "Standby_AC=" + ToValue(ReverseString(value.Substring(8, 8)));
                                }
                                else if (rowCount == 5)
                                {
                                    powerInfo = powerInfo + "<BDNA,1>" + "Standby_DC=" + ToValue(ReverseString(value.Substring(0, 8)));
                                    if (valueLen == 16)
                                    {
                                        powerInfo = powerInfo + "<BDNA,1>" + "Processor_Throttle_AC=" + getProcessorThrottle(ReverseString(value.Substring(12, 2)));
                                        powerInfo = powerInfo + "<BDNA,1>" + "Processor_Throttle_DC=" + getProcessorThrottle(ReverseString(value.Substring(14, 2)));
                                    }
                                    else
                                    {
                                        powerInfo = powerInfo + "<BDNA,1>" + "Processor_Throttle_AC=Invalid Data:" + value;
                                    }
                                }
                                else if (rowCount == 8)
                                {
                                    if (valueLen == 16)
                                    {
                                        powerInfo = powerInfo + "<BDNA,1>" + "Monitor_AC=" + ToValue(ReverseString(value.Substring(0, 8)));
                                        powerInfo = powerInfo + "<BDNA,1>" + "Monitor_DC=" + ToValue(ReverseString(value.Substring(8, 8)));
                                    }
                                    else
                                    {
                                        powerInfo = powerInfo + "<BDNA,1>" + "Monitor_AC=Invalid Data:" + value;
                                    }
                                }
                                else if (rowCount == 9)
                                {
                                    if (valueLen == 16)
                                    {
                                        powerInfo = powerInfo + "<BDNA,1>" + "Disk_AC=" + ToValue(ReverseString(value.Substring(0, 8)));
                                        powerInfo = powerInfo + "<BDNA,1>" + "Disk_DC=" + ToValue(ReverseString(value.Substring(8, 8)));
                                    }
                                    else
                                    {
                                        powerInfo = powerInfo + "<BDNA,1>" + "Disk_AC=Invalid Data:" + value;
                                    }
                                }
                                value = "";
                            }
                        }
                    }
                }
                else
                {
                    powerInfo = powerInfo + "\r\n" + "Error retrieving value :" + outParams["ReturnValue"].ToString();
                }
                return(powerInfo);
            } catch (Exception e) {
                powerInfo = powerInfo + "  " + e.ToString();
                return(powerInfo);
            } finally {
            }
        }
        internal static string GetReportServerUrl(string machineName, string instanceName)
        {
            string reportServerVirtualDirectory = String.Empty;
            string fullWmiNamespace             = @"\\" + machineName + string.Format(wmiNamespace, instanceName);

            ManagementScope scope = null;

            ConnectionOptions connOptions = new ConnectionOptions();

            connOptions.Authentication = AuthenticationLevel.PacketPrivacy;

            //Get management scope
            try
            {
                scope = new ManagementScope(fullWmiNamespace, connOptions);
                scope.Connect();

                //Get management class
                ManagementPath   path        = new ManagementPath("MSReportServer_Instance");
                ObjectGetOptions options     = new ObjectGetOptions();
                ManagementClass  serverClass = new ManagementClass(scope, path, options);

                serverClass.Get();

                if (serverClass == null)
                {
                    throw new Exception(string.Format(CultureInfo.InvariantCulture,
                                                      CustomSecurity.WMIClassError));
                }

                //Get instances
                ManagementObjectCollection instances = serverClass.GetInstances();

                foreach (ManagementObject instance in instances)
                {
                    instance.Get();
                    //We're doing this comparison just to make sure we're validating the right instance.
                    //This comparison is more reliable as we do the comparison on the instance name rather
                    //than on any other property.
                    if (instanceName.ToUpper().Equals("RS_" + instance.GetPropertyValue("InstanceName").ToString().ToUpper()))
                    {
                        ManagementBaseObject outParams = (ManagementBaseObject)instance.InvokeMethod("GetReportServerUrls",
                                                                                                     null, null);

                        string[] appNames = (string[])outParams["ApplicationName"];
                        string[] urls     = (string[])outParams["URLs"];

                        for (int i = 0; i < appNames.Length; i++)
                        {
                            if (appNames[i] == "ReportServerWebService")
                            {
                                reportServerVirtualDirectory = urls[i];
                                //Since we only look for ReportServer URL we can safely break here as it would save one more iteration.
                                break;
                            }
                        }
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format(CultureInfo.InvariantCulture,
                                                  CustomSecurity.RSUrlError + ex.Message), ex);
            }

            if (reportServerVirtualDirectory == string.Empty)
            {
                throw new Exception(string.Format(CultureInfo.InvariantCulture,
                                                  CustomSecurity.MissingUrlReservation));
            }

            return(reportServerVirtualDirectory + rsAsmx);
        }
Exemplo n.º 39
0
        //Handles WMI semi-interactive shell
        public void wmiexec(string rhost, string executionPath, string cmdArgs, string domain, string username, string password)
        {
            Console.WriteLine();
            Console.WriteLine("[+] Using WMIExec module semi-interactive shell");
            Console.WriteLine("[+] Be careful what you execute");
            Console.WriteLine();
            string pwd = @"C:\";
            string ln1 = "";

            if (username == "" && password == "")
            {
                while (cmdArgs.ToLower() != "exit")
                {
                    //Handles uploading file to current remote directory
                    if (cmdArgs.ToLower().Contains("put "))
                    {
                        try
                        {
                            Char     delimiter = ' ';
                            String[] put       = cmdArgs.Split(delimiter);
                            string   localPath = put[1];
                            string   remotePath;
                            if (pwd == @"C:\")
                            {
                                remotePath = pwd + put[2];
                            }
                            else
                            {
                                remotePath = pwd + @"\" + put[2];
                            }
                            FileAddRemove uploadFile = new FileAddRemove();
                            uploadFile.upload(localPath, remotePath, rhost, username, password, domain);
                        }
                        catch
                        {
                            Console.WriteLine();
                            Console.WriteLine("[-] Something went wrong with the put command.  Check syntax and try again. ");
                            Console.WriteLine();
                        }
                    }
                    //Handles downloading file from current remote directory
                    else if (cmdArgs.ToLower().Contains("get "))
                    {
                        try
                        {
                            Char     delimiter = ' ';
                            String[] put       = cmdArgs.Split(delimiter);
                            string   localPath = put[2];
                            string   remotePath;
                            if (pwd == @"C:\")
                            {
                                remotePath = pwd + put[1];
                            }
                            else
                            {
                                remotePath = pwd + @"\" + put[1];
                            }
                            FileAddRemove uploadFile = new FileAddRemove();
                            uploadFile.get(localPath, remotePath, rhost, username, password, domain);
                        }
                        catch
                        {
                            Console.WriteLine();
                            Console.WriteLine("[-] Something went wrong with the get command.  Check syntax and try again. ");
                            Console.WriteLine();
                        }
                    }
                    else if (cmdArgs.ToLower().Contains("help"))
                    {
                        Console.WriteLine("Commands             Description");
                        Console.WriteLine("--------             -----------");
                        Console.WriteLine("put                  Upload file from local directory to current shell directory, put fullLocalPath\\File.txt File.txt");
                        Console.WriteLine("get                  Download file from current shell directory to local directory, get File.txt fullLocalPath\\File.txt");
                        Console.WriteLine("help                 Show help menu");
                        Console.WriteLine("exit                 Exit shell");
                    }
                    else
                    {
                        ManagementScope      myScope  = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", rhost));
                        ManagementClass      myClass  = new ManagementClass(myScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
                        ManagementBaseObject myParams = myClass.GetMethodParameters("Create");
                        myParams["CurrentDirectory"] = pwd;
                        myParams["CommandLine"]      = @"cmd /Q /c " + cmdArgs + @" > C:\__LegitFile 2>&1";
                        myClass.InvokeMethod("Create", myParams, null);

                        //Allows enough time to go elapse so output can be read
                        System.Threading.Thread.Sleep(2000);

                        //Handles reading output
                        string output = @"\\" + rhost + @"\C$\__LegitFile";
                        if (File.Exists(output))
                        {
                            using (StreamReader file = new StreamReader(output))
                            {
                                int    counter = 0;
                                string ln;

                                //Reads output file
                                while ((ln = file.ReadLine()) != null)
                                {
                                    //Helps handle bad path
                                    if (ln.Contains("The system cannot find the path specified."))
                                    {
                                        ln1 = ln;
                                    }
                                    Console.WriteLine();
                                    Console.WriteLine(ln);
                                    counter++;
                                }
                                file.Close();
                                File.Delete(output);
                            }
                        }//End if file exits

                        //Handles changing directories
                        if (cmdArgs.ToLower().Contains("cd"))
                        {
                            //Handles if bad directory
                            if (ln1.Contains("The system cannot find the path specified."))
                            {
                                ln1 = "";
                            }
                            else
                            {
                                /*Handles switching to full path - cd C:\Users\ATTE
                                 * Else handles new directory - cd Users\ATTE */
                                if (cmdArgs.ToLower().Contains(":"))
                                {
                                    pwd = cmdArgs.Split(' ')[1];
                                }
                                else
                                {
                                    string pwdOutput = pwd + @">";
                                    if (pwdOutput.Contains(@":\>"))
                                    {
                                        pwd = pwdOutput.Replace(">", cmdArgs.Split(' ')[1]);
                                    }
                                    else if (cmdArgs != "cd ..")
                                    {
                                        pwd = pwd + @">";
                                        pwd = pwd.Replace(">", @"\") + cmdArgs.Split(' ')[1];
                                    }
                                }
                            }

                            //Handles cd .. functionality
                            if (cmdArgs.ToLower().Contains(".."))
                            {
                                string input     = pwd;
                                string backslash = @"\";

                                int index = input.LastIndexOf(@backslash);

                                if (index > 0)
                                {
                                    pwd = input.Substring(0, index);

                                    if (pwd == "C:")
                                    {
                                        pwd = @"C:\";
                                    }
                                }
                                else
                                {
                                    pwd = @"C:\";
                                }
                            }
                        }//End if cmdArgs contain cd
                    }
                    Console.WriteLine();
                    Console.Write(pwd + @">");
                    cmdArgs = Console.ReadLine();
                }
            }
            else
            {
                while (cmdArgs.ToLower() != "exit")
                {
                    //Handles uploading file to current remote directory
                    if (cmdArgs.ToLower().Contains("put "))
                    {
                        try                        {
                            Char     delimiter = ' ';
                            String[] put       = cmdArgs.Split(delimiter);
                            string   localPath = put[1];
                            string   remotePath;
                            if (pwd == @"C:\")
                            {
                                remotePath = pwd + put[2];
                            }
                            else
                            {
                                remotePath = pwd + @"\" + put[2];
                            }
                            FileAddRemove uploadFile = new FileAddRemove();
                            uploadFile.upload(localPath, remotePath, rhost, username, password, domain);
                        }
                        catch
                        {
                            Console.WriteLine();
                            Console.WriteLine("[-] Something went wrong with the put command.  Check syntax and try again. ");
                            Console.WriteLine();
                        }
                    }
                    //Handles downloading file from current remote directory
                    else if (cmdArgs.ToLower().Contains("get "))
                    {
                        try
                        {
                            Char     delimiter = ' ';
                            String[] put       = cmdArgs.Split(delimiter);
                            string   localPath = put[2];
                            string   remotePath;
                            if (pwd == @"C:\")
                            {
                                remotePath = pwd + put[1];
                            }
                            else
                            {
                                remotePath = pwd + @"\" + put[1];
                            }
                            FileAddRemove uploadFile = new FileAddRemove();
                            uploadFile.get(localPath, remotePath, rhost, username, password, domain);
                        }
                        catch
                        {
                            Console.WriteLine();
                            Console.WriteLine("[-] Something went wrong with the get command.  Check syntax and try again. ");
                            Console.WriteLine();
                        }
                    }
                    else if (cmdArgs.ToLower().Contains("help"))
                    {
                        Console.WriteLine("Commands             Description");
                        Console.WriteLine("--------             -----------");
                        Console.WriteLine("put                  Upload file from local directory to current shell directory, put fullLocalPath\\File.txt File.txt");
                        Console.WriteLine("get                  Download file from current shell directory to local directory, get File.txt fullLocalPath\\File.txt");
                        Console.WriteLine("help                 Show help menu");
                        Console.WriteLine("exit                 Exit shell");
                    }
                    else
                    {
                        ConnectionOptions myConnection = new ConnectionOptions();
                        string            uname        = domain + @"\" + username;
                        myConnection.Impersonation    = ImpersonationLevel.Impersonate;
                        myConnection.EnablePrivileges = true;
                        myConnection.Timeout          = new TimeSpan(0, 0, 30);
                        myConnection.Username         = uname;
                        myConnection.Password         = password;
                        ManagementScope      myScope  = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", rhost), myConnection);
                        ManagementClass      myClass  = new ManagementClass(myScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
                        ManagementBaseObject myParams = myClass.GetMethodParameters("Create");
                        myParams["CurrentDirectory"] = pwd;
                        myParams["CommandLine"]      = @"cmd /Q /c " + cmdArgs + @" > C:\__LegitFile 2>&1";
                        myClass.InvokeMethod("Create", myParams, null);

                        //Allows enough time to go elapse so output can be read
                        System.Threading.Thread.Sleep(2000);

                        using (new Impersonation(domain, username, password))
                        {
                            //Handles reading output
                            string output = @"\\" + rhost + @"\C$\__LegitFile";
                            if (File.Exists(output))
                            {
                                using (StreamReader file = new StreamReader(output))
                                {
                                    int    counter = 0;
                                    string ln;

                                    //Reads output file
                                    while ((ln = file.ReadLine()) != null)
                                    {
                                        //Helps handle bad path
                                        if (ln.Contains("The system cannot find the path specified."))
                                        {
                                            ln1 = ln;
                                        }
                                        Console.WriteLine();
                                        Console.WriteLine(ln);
                                        counter++;
                                    }
                                    file.Close();
                                    File.Delete(output);
                                }
                            } //End if file exits
                        }     //end impersonation

                        //Handles changing directories
                        if (cmdArgs.ToLower().Contains("cd"))
                        {
                            //Handles if bad directory
                            if (ln1.Contains("The system cannot find the path specified."))
                            {
                                ln1 = "";
                            }
                            else
                            {
                                /*Handles switching to full path - cd C:\Users\ATTE
                                 * Else handles new directory - cd Users\ATTE */
                                if (cmdArgs.ToLower().Contains(":"))
                                {
                                    pwd = cmdArgs.Split(' ')[1];
                                }
                                else
                                {
                                    string pwdOutput = pwd + @">";
                                    if (pwdOutput.Contains(@":\>"))
                                    {
                                        pwd = pwdOutput.Replace(">", cmdArgs.Split(' ')[1]);
                                    }
                                    else if (cmdArgs != "cd ..")
                                    {
                                        pwd = pwd + @">";
                                        pwd = pwd.Replace(">", @"\") + cmdArgs.Split(' ')[1];
                                    }
                                }
                            }

                            //Handles cd .. functionality
                            if (cmdArgs.ToLower().Contains(".."))
                            {
                                string input     = pwd;
                                string backslash = @"\";

                                int index = input.LastIndexOf(@backslash);

                                if (index > 0)
                                {
                                    pwd = input.Substring(0, index);

                                    if (pwd == "C:")
                                    {
                                        pwd = @"C:\";
                                    }
                                }
                                else
                                {
                                    pwd = @"C:\";
                                }
                            }
                        }//End if cmdArgs contain cd
                    }
                    Console.WriteLine();
                    Console.Write(pwd + @">");
                    cmdArgs = Console.ReadLine();
                }
            }
        }
    public OfficeInstalledProducts GetOfficeVersion()
    {
        var installKeys = new List<string>()
        {
            @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
            @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
        };

        var officeKeys = new List<string>()
        {
            @"SOFTWARE\Microsoft\Office",
            @"SOFTWARE\Wow6432Node\Microsoft\Office"
        };

        string osArchitecture = null;
        var osClass = new ManagementClass("Win32_OperatingSystem");
        foreach (var queryObj in osClass.GetInstances())
        {
            foreach (var prop in queryObj.Properties)
            {
                if (prop.Name == null) continue;
                if (prop.Name.ToLower() == "OSArchitecture".ToLower())
                {
                    if (prop.Value == null) continue;
                    osArchitecture = prop.Value.ToString() ?? "";
                    break;
                }
            }
        }

        // $results = new-object PSObject[] 0;

        // foreach ($computer in $ComputerName) {
        //    if ($Credentials) {
        //       $os=Get-WMIObject win32_operatingsystem -computername $computer -Credential $Credentials
        //    } else {
        //       $os=Get-WMIObject win32_operatingsystem -computername $computer
        //    }

        //    $osArchitecture = $os.OSArchitecture

        //    if ($Credentials) {
        //       $regProv = Get-Wmiobject -list "StdRegProv" -namespace root\default -computername $computer -Credential $Credentials
        //} else {
        //       $regProv = Get-Wmiobject -list "StdRegProv" -namespace root\default -computername $computer
        //}

        var officePathReturn = GetOfficePathList();

        foreach (var regKey in installKeys)
        {
            var keyList = new List<string>();
            var keys = GetRegistrySubKeys(regKey);

            foreach (var key in keys)
            {
                var path = regKey + @"\" + key;
                var installPath = GetRegistryValue(path, "InstallLocation");

                if (string.IsNullOrEmpty(installPath))
                {
                    continue;
                }

                var buildType = "64-Bit";
                if (osArchitecture == "32-bit")
                {
                    buildType = "32-Bit";
                }

                if (regKey.ToUpper().Contains("Wow6432Node".ToUpper()))
                {
                    buildType = "32-Bit";
                }

                if (Regex.Match(key, "{.{8}-.{4}-.{4}-1000-0000000FF1CE}").Success)
                {
                    buildType = "64-Bit";
                }

                if (Regex.Match(key, "{.{8}-.{4}-.{4}-0000-0000000FF1CE}").Success)
                {
                    buildType = "64-Bit";
                }


                var modifyPath = GetRegistryValue(path, "ModifyPath");
                if (!string.IsNullOrEmpty(modifyPath))
                {
                    if (modifyPath.ToLower().Contains("platform=x86"))
                    {
                        buildType = "32-Bit";
                    }

                    if (modifyPath.ToLower().Contains("platform=x64"))
                    {
                        buildType = "64-Bit";
                    }
                }


                var officeProduct = false;
                foreach (var officeInstallPath in officePathReturn.PathList)
                {
                    if (!string.IsNullOrEmpty(officeInstallPath))
                    {
                        var installReg = "^" + installPath.Replace(@"\", @"\\");
                        installReg = installReg.Replace("(", @"\(");
                        installReg = installReg.Replace(@")", @"\)");

                        if (Regex.Match(officeInstallPath, installReg).Success)
                        {
                            officeProduct = true;
                        }
                    }
                }

                if (!officeProduct)
                {
                    continue;
                }


                var name = GetRegistryValue(path, "DisplayName");
                if (name == null) name = "";

                if (officePathReturn.ConfigItemList.Contains(key.ToUpper()) && name.ToUpper().Contains("MICROSOFT OFFICE"))
                {
                    //primaryOfficeProduct = true;
                }

                var version = GetRegistryValue(path, "DisplayVersion");
                modifyPath = GetRegistryValue(path, "ModifyPath");

                var clientCulture = "";

                if (installPath == null) installPath = "";

                var clickToRun = false;
                if (officePathReturn.ClickToRunPathList.Contains(installPath.ToUpper()))
                {
                    clickToRun = true;
                    if (name.ToUpper().Contains("MICROSOFT OFFICE"))
                    {
                        //primaryOfficeProduct = true;
                    }

                    foreach (var cltr in officePathReturn.ClickToRunList)
                    {
                        if (!string.IsNullOrEmpty(cltr.InstallPath))
                        {
                            if (cltr.InstallPath.ToUpper() == installPath.ToUpper())
                            {
                                if (cltr.Bitness == "x64")
                                {
                                    buildType = "64-Bit";
                                }
                                if (cltr.Bitness == "x86")
                                {
                                    buildType = "32-Bit";
                                }
                                clientCulture = cltr.ClientCulture;
                            }
                        }
                    }
                }

                var offInstall = new OfficeInstall
                {
                    DisplayName = name,
                    Version = version,
                    InstallPath = installPath,
                    ClickToRun = clickToRun,
                    Bitness = buildType,
                    ClientCulture = clientCulture
                };
                officePathReturn.ClickToRunList.Add(offInstall);
                //}
            }

        }

        var returnList = officePathReturn.ClickToRunList.Distinct().ToList();

        return new OfficeInstalledProducts()
        {
            OfficeInstalls = returnList,
            OSArchitecture = osArchitecture
        };
    }
Exemplo n.º 41
0
        internal static void Start(string[] args)
        {
            Log.Info("Start");
            if (shutDown)
            {
                Log.Info("Shutdown Time");
                if (Application.Current.MainWindow != null)
                {
                    Application.Current.MainWindow.Close();
                }
                return;
            }

            Log.Info("Decide to ask about wine");
            if (Prefs.AskedIfUsingWine == false)
            {
                Log.Info("Asking about wine");
                var res = MessageBox.Show("Are you running OCTGN on Linux or a Mac using Wine?", "Using Wine",
                                          MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (res == MessageBoxResult.Yes)
                {
                    Prefs.AskedIfUsingWine      = true;
                    Prefs.UsingWine             = true;
                    Prefs.UseHardwareRendering  = false;
                    Prefs.UseGameFonts          = false;
                    Prefs.UseWindowTransparency = false;
                }
                else if (res == MessageBoxResult.No)
                {
                    Prefs.AskedIfUsingWine      = true;
                    Prefs.UsingWine             = false;
                    Prefs.UseHardwareRendering  = true;
                    Prefs.UseGameFonts          = true;
                    Prefs.UseWindowTransparency = true;
                }
            }
            // Check for desktop experience
            if (Prefs.UsingWine == false)
            {
                try
                {
                    Log.Debug("Checking for Desktop Experience");
                    var  objMC  = new ManagementClass("Win32_ServerFeature");
                    var  objMOC = objMC.GetInstances();
                    bool gotIt  = false;
                    foreach (var objMO in objMOC)
                    {
                        if ((UInt32)objMO["ID"] == 35)
                        {
                            Log.Debug("Found Desktop Experience");
                            gotIt = true;
                            break;
                        }
                    }
                    if (!gotIt)
                    {
                        var res =
                            MessageBox.Show(
                                "You are running OCTGN without the windows Desktop Experience installed. This WILL cause visual, gameplay, and sound issues. Though it isn't required, it is HIGHLY recommended. \n\nWould you like to be shown a site to tell you how to turn it on?",
                                "Windows Desktop Experience Missing", MessageBoxButton.YesNo,
                                MessageBoxImage.Exclamation);
                        if (res == MessageBoxResult.Yes)
                        {
                            LaunchUrl(
                                "http://blogs.msdn.com/b/findnavish/archive/2012/06/01/enabling-win-7-desktop-experience-on-windows-server-2008.aspx");
                        }
                        else
                        {
                            MessageBox.Show("Ok, but you've been warned...", "Warning", MessageBoxButton.OK,
                                            MessageBoxImage.Warning);
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Warn(
                        "Check desktop experience error. An error like 'Not Found' is normal and shouldn't be worried about",
                        e);
                }
            }

            //var win = new ShareDeck();
            //win.ShowDialog();
            //return;
            Log.Info("Getting Launcher");
            Launchers.ILauncher launcher = CommandLineHandler.Instance.HandleArguments(Environment.GetCommandLineArgs());
            DeveloperMode = CommandLineHandler.Instance.DevMode;

            Versioned.Setup(Program.DeveloperMode);
            /* This section is automatically generated from the file Scripting/ApiVersions.xml. So, if you enjoy not getting pissed off, don't modify it.*/
            //START_REPLACE_API_VERSION
            Versioned.RegisterVersion(Version.Parse("3.1.0.0"), DateTime.Parse("2014-1-12"), ReleaseMode.Live);
            Versioned.RegisterVersion(Version.Parse("3.1.0.1"), DateTime.Parse("2014-1-22"), ReleaseMode.Live);
            Versioned.RegisterVersion(Version.Parse("3.1.0.2"), DateTime.Parse("2014-1-22"), ReleaseMode.Test);
            Versioned.RegisterFile("PythonApi", "pack://application:,,,/Scripting/Versions/3.1.0.0.py", Version.Parse("3.1.0.0"));
            Versioned.RegisterFile("PythonApi", "pack://application:,,,/Scripting/Versions/3.1.0.1.py", Version.Parse("3.1.0.1"));
            Versioned.RegisterFile("PythonApi", "pack://application:,,,/Scripting/Versions/3.1.0.2.py", Version.Parse("3.1.0.2"));
            //END_REPLACE_API_VERSION
            Versioned.Register <ScriptApi>();

            launcher.Launch();

            if (launcher.Shutdown)
            {
                if (Application.Current.MainWindow != null)
                {
                    Application.Current.MainWindow.Close();
                }
                return;
            }
        }
Exemplo n.º 42
0
        private string GetWindows6Power(ManagementClass wmiRegistry)
        {
            string powerInfo         = "";
            string activePowerScheme = "";

            try {
                ManagementBaseObject inParams = wmiRegistry.GetMethodParameters("GetStringValue");
                inParams["hDefKey"]     = HKEY_LOCAL_MACHINE;
                inParams["sSubKeyName"] = @"SYSTEM\CurrentControlSet\Control\Power\User\PowerSchemes";
                inParams["sValueName"]  = "ActivePowerScheme";

                ManagementBaseObject outParams = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                if (Convert.ToUInt32(outParams["ReturnValue"]) == 0)
                {
                    activePowerScheme = outParams["sValue"].ToString();
                }
                else
                {
                    Console.WriteLine("Error retrieving value : " + outParams["ReturnValue"].ToString());
                }

                if ("a1841308-3541-4fab-bc81-f71556f20b4a".Equals(activePowerScheme))
                {
                    powerInfo = "Processor_Throttle_AC=\"Power saver\"<BDNA,1>Processor_Throttle_DC=\"Power saver\"<BDNA,1>";
                }
                else if ("381b4222-f694-41f0-9685-ff5bb260df2e".Equals(activePowerScheme))
                {
                    powerInfo = "Processor_Throttle_AC=\"Balanced\"<BDNA,1>Processor_Throttle_DC=\"Balanced\"<BDNA,1>";
                }
                else if ("8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c".Equals(activePowerScheme))
                {
                    powerInfo = "Processor_Throttle_AC=\"High performance\"<BDNA,1>Processor_Throttle_DC=\"High performance\"<BDNA,1>";
                }
                inParams["hDefKey"]     = HKEY_LOCAL_MACHINE;
                inParams["sSubKeyName"] = @"SYSTEM\CurrentControlSet\Control\Power\User\PowerSchemes\" + activePowerScheme + @"\7516b95f-f776-4464-8c53-06167f40cc99\3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e";
                inParams["sValueName"]  = "ACSettingIndex";

                outParams = wmiRegistry.InvokeMethod("GetDWORDValue", inParams, null);
                if (Convert.ToUInt32(outParams["ReturnValue"]) == 0)
                {
                    powerInfo = powerInfo + "" + "Monitor_AC=" + IntToValue(string.Format("{0:X2}", outParams["uValue"].ToString()));
                }
                else
                {
                    Console.WriteLine("Error retrieving value : " + outParams["ReturnValue"].ToString());
                }
                inParams["sValueName"] = "DCSettingIndex";
                outParams = wmiRegistry.InvokeMethod("GetDWORDValue", inParams, null);
                if (Convert.ToUInt32(outParams["ReturnValue"]) == 0)
                {
                    powerInfo = powerInfo + "" + "<BDNA,1>Monitor_DC=" + IntToValue(string.Format("{0:X2}", outParams["uValue"].ToString()));
                }
                else
                {
                    Console.WriteLine("Error retrieving value : " + outParams["ReturnValue"].ToString());
                }

                inParams["hDefKey"]     = HKEY_LOCAL_MACHINE;
                inParams["sSubKeyName"] = @"SYSTEM\CurrentControlSet\Control\Power\User\PowerSchemes\" + activePowerScheme + @"\0012ee47-9041-4b5d-9b77-535fba8b1442\6738e2c4-e8a5-4a42-b16a-e040e769756e";
                inParams["sValueName"]  = "ACSettingIndex";

                outParams = wmiRegistry.InvokeMethod("GetDWORDValue", inParams, null);
                if (Convert.ToUInt32(outParams["ReturnValue"]) == 0)
                {
                    powerInfo = powerInfo + "" + "<BDNA,1>Disk_AC=" + IntToValue(string.Format("{0:X2}", outParams["uValue"].ToString()));
                }
                else
                {
                    Console.WriteLine("Error retrieving value : " + outParams["ReturnValue"].ToString());
                }
                inParams["sValueName"] = "DCSettingIndex";
                outParams = wmiRegistry.InvokeMethod("GetDWORDValue", inParams, null);
                if (Convert.ToUInt32(outParams["ReturnValue"]) == 0)
                {
                    powerInfo = powerInfo + "" + "<BDNA,1>Disk_DC=" + IntToValue(string.Format("{0:X2}", outParams["uValue"].ToString()));
                }
                else
                {
                    Console.WriteLine("Error retrieving value : " + outParams["ReturnValue"].ToString());
                }

                inParams["hDefKey"]     = HKEY_LOCAL_MACHINE;
                inParams["sSubKeyName"] = @"SYSTEM\CurrentControlSet\Control\Power\User\PowerSchemes\" + activePowerScheme + @"\238C9FA8-0AAD-41ED-83F4-97BE242C8F20\29f6c1db-86da-48c5-9fdb-f2b67b1f44da";
                inParams["sValueName"]  = "ACSettingIndex";

                outParams = wmiRegistry.InvokeMethod("GetDWORDValue", inParams, null);
                if (Convert.ToUInt32(outParams["ReturnValue"]) == 0)
                {
                    powerInfo = powerInfo + "" + "<BDNA,1>Standby_AC=" + IntToValue(string.Format("{0:X2}", outParams["uValue"].ToString()));
                }
                else
                {
                    Console.WriteLine("Error retrieving value : " + outParams["ReturnValue"].ToString());
                }
                inParams["sValueName"] = "DCSettingIndex";

                outParams = wmiRegistry.InvokeMethod("GetDWORDValue", inParams, null);
                if (Convert.ToUInt32(outParams["ReturnValue"]) == 0)
                {
                    powerInfo = powerInfo + "" + "<BDNA,1>Standby_DC=" + IntToValue(string.Format("{0:X2}", outParams["uValue"].ToString()));
                }
                else
                {
                    Console.WriteLine("Error retrieving value : " + outParams["ReturnValue"].ToString());
                }

                inParams["hDefKey"]     = HKEY_LOCAL_MACHINE;
                inParams["sSubKeyName"] = @"SYSTEM\CurrentControlSet\Control\Power\User\PowerSchemes\" + activePowerScheme + @"\238C9FA8-0AAD-41ED-83F4-97BE242C8F20\9d7815a6-7ee4-497e-8888-515a05f02364";
                inParams["sValueName"]  = "ACSettingIndex";

                outParams = wmiRegistry.InvokeMethod("GetDWORDValue", inParams, null);
                if (Convert.ToUInt32(outParams["ReturnValue"]) == 0)
                {
                    powerInfo = powerInfo + "" + "<BDNA,1>Hibernate_AC=" + IntToValue(string.Format("{0:X2}", outParams["uValue"].ToString()));
                }
                else
                {
                    Console.WriteLine("Error retrieving value : " + outParams["ReturnValue"].ToString());
                }
                inParams["sValueName"] = "DCSettingIndex";
                outParams = wmiRegistry.InvokeMethod("GetDWORDValue", inParams, null);
                if (Convert.ToUInt32(outParams["ReturnValue"]) == 0)
                {
                    powerInfo = powerInfo + "" + "<BDNA,1>Hibernate_DC=" + IntToValue(string.Format("{0:X2}", outParams["uValue"].ToString()));
                }
                else
                {
                    Console.WriteLine("Error retrieving value : " + outParams["ReturnValue"].ToString());
                }

                return(powerInfo);
            } catch (Exception e) {
                //MessageBox.Show(e.ToString());
            }

            return(powerInfo);
        }
Exemplo n.º 43
0
 public static double? GetCpuSpeedInGHz()
 {
     double? GHz = null;
     using (ManagementClass mc = new ManagementClass("Win32_Processor"))
     {
         foreach (ManagementObject mo in mc.GetInstances())
         {
             GHz = 0.001 * (UInt32)mo.Properties["CurrentClockSpeed"].Value;
             break;
         }
     }
     return GHz;
 }
Exemplo n.º 44
0
        internal static void Start(string[] args, bool isTestRelease)
        {
            Log.Info("Start");
            IsReleaseTest           = isTestRelease;
            GameMessage.MuteChecker = () =>
            {
                if (Program.Client == null)
                {
                    return(false);
                }
                return(Program.Client.Muted != 0);
            };

            Log.Info("Setting SSL Validation Helper");
            SSLHelper = new SSLValidationHelper();

            Log.Info("Setting api path");
            Octgn.Site.Api.ApiClient.Site = new Uri(AppConfig.WebsitePath);
            try
            {
                Log.Debug("Setting rendering mode.");
                RenderOptions.ProcessRenderMode = Prefs.UseHardwareRendering ? RenderMode.Default : RenderMode.SoftwareOnly;
            }
            catch (Exception)
            {
                // if the system gets mad, best to leave it alone.
            }

            Log.Info("Setting temp main window");
            Application.Current.MainWindow = new Window();
            try
            {
                Log.Info("Checking if admin");
                var isAdmin = UacHelper.IsProcessElevated && UacHelper.IsUacEnabled;
                if (isAdmin)
                {
                    MessageBox.Show(
                        "You are currently running OCTGN as Administrator. It is recommended that you run as a standard user, or you will most likely run into problems. Please exit OCTGN and run as a standard user.",
                        "WARNING",
                        MessageBoxButton.OK,
                        MessageBoxImage.Exclamation);
                }
            }
            catch (Exception e)
            {
                Log.Warn("Couldn't check if admin", e);
            }

            // Check if running on network drive
            try
            {
                Log.Info("Check if running on network drive");
                var myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                //var myDocs = "\\\\";
                if (myDocs.StartsWith("\\\\") && !CheckNetworkFixInstalled())
                {
                    var res = MessageBox.Show(String.Format(
                                                  @"Your system is currently running on a network share. '{0}'

This will cause OCTGN not to function properly. At this time, the only work around is to install OCTGN on a machine that doesn't map your folders onto a network drive.

You can still use OCTGN, but it most likely won't work.

Would you like to visit our help page for solutions to this problem?", myDocs),
                                              "ERROR", MessageBoxButton.YesNoCancel, MessageBoxImage.Error);

                    if (res == MessageBoxResult.Yes)
                    {
                        LaunchUrl("http://help.octgn.net/solution/articles/4000006491-octgn-on-network-share-mac");
                        shutDown = true;
                    }
                    else if (res == MessageBoxResult.No)
                    {
                    }
                    else
                    {
                        shutDown = true;
                    }
                }
            }
            catch (Exception e)
            {
                Log.Warn("Check if running on network drive failed", e);
                throw;
            }

            Log.Info("Creating Lobby Client");
            LobbyClient = new Skylabs.Lobby.Client(LobbyConfig.Get());
            //Log.Info("Adding trace listeners");
            //Debug.Listeners.Add(DebugListener);
            //DebugTrace.Listeners.Add(DebugListener);
            //Trace.Listeners.Add(DebugListener);
            //ChatLog = new CacheTraceListener();
            //Trace.Listeners.Add(ChatLog);
            Log.Info("Creating Game Message Dispatcher");
            GameMess = new GameMessageDispatcher();
            GameMess.ProcessMessage(
                x =>
            {
                for (var i = 0; i < x.Arguments.Length; i++)
                {
                    var arg       = x.Arguments[i];
                    var cardModel = arg as DataNew.Entities.Card;
                    var cardId    = arg as CardIdentity;
                    var card      = arg as Card;
                    if (card != null && (card.FaceUp || card.MayBeConsideredFaceUp))
                    {
                        cardId = card.Type;
                    }

                    if (cardId != null || cardModel != null)
                    {
                        ChatCard chatCard = null;
                        if (cardId != null)
                        {
                            chatCard = new ChatCard(cardId);
                        }
                        else
                        {
                            chatCard = new ChatCard(cardModel);
                        }
                        if (card != null)
                        {
                            chatCard.SetGameCard(card);
                        }
                        x.Arguments[i] = chatCard;
                    }
                    else
                    {
                        x.Arguments[i] = arg == null ? "[?]" : arg.ToString();
                    }
                }
                return(x);
            });

            Log.Info("Registering versioned stuff");

            //BasePath = Path.GetDirectoryName(typeof (Program).Assembly.Location) + '\\';
            Log.Info("Setting Games Path");
            GameSettings = new GameSettings();
            if (shutDown)
            {
                Log.Info("Shutdown Time");
                if (Application.Current.MainWindow != null)
                {
                    Application.Current.MainWindow.Close();
                }
                return;
            }

            Log.Info("Decide to ask about wine");
            if (Prefs.AskedIfUsingWine == false)
            {
                Log.Info("Asking about wine");
                var res = MessageBox.Show("Are you running OCTGN on Linux or a Mac using Wine?", "Using Wine",
                                          MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (res == MessageBoxResult.Yes)
                {
                    Prefs.AskedIfUsingWine      = true;
                    Prefs.UsingWine             = true;
                    Prefs.UseHardwareRendering  = false;
                    Prefs.UseGameFonts          = false;
                    Prefs.UseWindowTransparency = false;
                }
                else if (res == MessageBoxResult.No)
                {
                    Prefs.AskedIfUsingWine      = true;
                    Prefs.UsingWine             = false;
                    Prefs.UseHardwareRendering  = true;
                    Prefs.UseGameFonts          = true;
                    Prefs.UseWindowTransparency = true;
                }
            }
            // Check for desktop experience
            if (Prefs.UsingWine == false)
            {
                try
                {
                    Log.Debug("Checking for Desktop Experience");
                    var  objMC  = new ManagementClass("Win32_ServerFeature");
                    var  objMOC = objMC.GetInstances();
                    bool gotIt  = false;
                    foreach (var objMO in objMOC)
                    {
                        if ((UInt32)objMO["ID"] == 35)
                        {
                            Log.Debug("Found Desktop Experience");
                            gotIt = true;
                            break;
                        }
                    }
                    if (!gotIt)
                    {
                        var res =
                            MessageBox.Show(
                                "You are running OCTGN without the windows Desktop Experience installed. This WILL cause visual, gameplay, and sound issues. Though it isn't required, it is HIGHLY recommended. \n\nWould you like to be shown a site to tell you how to turn it on?",
                                "Windows Desktop Experience Missing", MessageBoxButton.YesNo,
                                MessageBoxImage.Exclamation);
                        if (res == MessageBoxResult.Yes)
                        {
                            LaunchUrl(
                                "http://blogs.msdn.com/b/findnavish/archive/2012/06/01/enabling-win-7-desktop-experience-on-windows-server-2008.aspx");
                        }
                        else
                        {
                            MessageBox.Show("Ok, but you've been warned...", "Warning", MessageBoxButton.OK,
                                            MessageBoxImage.Warning);
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Warn(
                        "Check desktop experience error. An error like 'Not Found' is normal and shouldn't be worried about",
                        e);
                }
            }
            // Send off user/computer stats
            try
            {
                var osver    = System.Environment.OSVersion.VersionString;
                var osBit    = Win32.Is64BitOperatingSystem;
                var procBit  = Win32.Is64BitProcess;
                var issubbed = SubscriptionModule.Get().IsSubscribed;
                var iswine   = Prefs.UsingWine;
                // Use the API to submit info
            }
            catch (Exception e)
            {
                Log.Warn("Sending stats error", e);
            }
            //var win = new ShareDeck();
            //win.ShowDialog();
            //return;
            Log.Info("Getting Launcher");
            Launchers.ILauncher launcher = CommandLineHandler.Instance.HandleArguments(Environment.GetCommandLineArgs());
            DeveloperMode = CommandLineHandler.Instance.DevMode;

            Versioned.Setup(Program.DeveloperMode);
            /* This section is automatically generated from the file Scripting/ApiVersions.xml. So, if you enjoy not getting pissed off, don't modify it.*/
            //START_REPLACE_API_VERSION
            Versioned.RegisterVersion(Version.Parse("3.1.0.0"), DateTime.Parse("2014-1-12"), ReleaseMode.Live);
            Versioned.RegisterVersion(Version.Parse("3.1.0.1"), DateTime.Parse("2014-1-22"), ReleaseMode.Live);
            Versioned.RegisterVersion(Version.Parse("3.1.0.2"), DateTime.Parse("2015-7-1"), ReleaseMode.Test);
            Versioned.RegisterFile("PythonApi", "pack://application:,,,/Scripting/Versions/3.1.0.0.py", Version.Parse("3.1.0.0"));
            Versioned.RegisterFile("PythonApi", "pack://application:,,,/Scripting/Versions/3.1.0.1.py", Version.Parse("3.1.0.1"));
            Versioned.RegisterFile("PythonApi", "pack://application:,,,/Scripting/Versions/3.1.0.2.py", Version.Parse("3.1.0.2"));
            //END_REPLACE_API_VERSION
            Versioned.Register <ScriptApi>();

            launcher.Launch();

            if (launcher.Shutdown)
            {
                if (Application.Current.MainWindow != null)
                {
                    Application.Current.MainWindow.Close();
                }
                return;
            }
        }
Exemplo n.º 45
0
    public static String GetMotherBoardManu()
    {
        ManagementClass mc = new ManagementClass("Win32_BaseBoard");
        ManagementObjectCollection moc = mc.GetInstances();
        String Id = String.Empty;
        foreach (ManagementObject mo in moc)
        {

            Id = mo.Properties["Manufacturer"].Value.ToString();
            break;
        }
        return Id;
    }
Exemplo n.º 46
0
        public static SystemInfo GetSystemInfo()
        {
            SystemInfo systemInfo = new SystemInfo
            {
                CpuCount    = System.Environment.ProcessorCount,
                TotalMemory = PhysicalMemory,
                Name        = HostName,
                Timestamp   = DateTime.Now,
                IpAddress   = Ip4Address
            };


#if !NET_CORE
            long availablebytes = 0;

            ManagementClass mos = new ManagementClass("Win32_OperatingSystem");
            foreach (var o in mos.GetInstances())
            {
                var mo = (ManagementObject)o;
                if (mo["FreePhysicalMemory"] != null)
                {
                    availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString());
                }
            }

            systemInfo.CpuLoad    = (int)(PcCpuLoad.NextValue());
            systemInfo.FreeMemory = (int)(availablebytes / (1024 * 1024));
            systemInfo.Os         = "Windows";
#else
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                // cpu load
                string loadAvg = RunCommand("cat", "/proc/loadavg");
                systemInfo.CpuLoad = (int)(float.Parse(loadAvg.Split(' ')[2]) * 100);

                var memInfo = RunCommand("free", "-m").Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);

                int usedMem = int.Parse(memInfo[7]);

                systemInfo.FreeMemory = (PhysicalMemory - usedMem);
                systemInfo.Os         = "Linux";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                // cpu load
                string loadAvg = RunCommand("cat", "/proc/loadavg");
                systemInfo.CpuLoad = (int)(float.Parse(loadAvg.Split(' ')[2]) * 100);

                //todo:
                systemInfo.Os = "OSX";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                // Didnot find dotnet core api now.
                //PcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total") { MachineName = "." };
                //PcCpuLoad.NextValue();

                //todo:
                systemInfo.Os = "Windows";
            }
#endif
            return(systemInfo);
        }
Exemplo n.º 47
0
    public static String GetyResolution()
    {
        ManagementClass mc = new ManagementClass("Win32_VideoController");
        ManagementObjectCollection moc = mc.GetInstances();
        String Id = String.Empty;
        foreach (ManagementObject mo in moc)
        {

            Id = mo.Properties["CurrentVerticalResolution"].Value.ToString();
            break;
        }
        return Id;
    }
Exemplo n.º 48
0
        private string GetWindowsXPPower(ManagementClass wmiRegistry)
        {
            string powerInfo = "";
            Dictionary <string, string> resultDic = new Dictionary <string, string>();

            try {
                ManagementBaseObject inParams = wmiRegistry.GetMethodParameters("GetStringValue");
                inParams["hDefKey"]     = HKEY_USERS;
                inParams["sSubKeyName"] = @"";

                ManagementBaseObject outParams  = wmiRegistry.InvokeMethod("EnumKey", inParams, null);
                string[]             valueNames = (string[])outParams["sNames"];
                foreach (string name in valueNames)
                {
                    if (!name.EndsWith("Classes"))
                    {
                        powerInfo               = "";
                        inParams["hDefKey"]     = HKEY_USERS;
                        inParams["sSubKeyName"] = name + @"\Identities";
                        inParams["sValueName"]  = "Last User ID";
                        outParams               = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                        if (Convert.ToUInt32(outParams["ReturnValue"]) == 0)
                        {
                            string lastUserID = outParams["sValue"].ToString();
                            ///////////////////////Get Power Policy/////////////////////////////
                            inParams["hDefKey"]     = HKEY_USERS;
                            inParams["sSubKeyName"] = name + @"\Control Panel\PowerCfg";
                            inParams["sValueName"]  = "CurrentPowerPolicy";

                            outParams = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                            string policy = outParams["sValue"].ToString();
                            //MessageBox.Show(lastUserID + "==" + policy);
                            ///////////////////////Get Power Value(Binary)/////////////////////////////
                            inParams["hDefKey"]     = HKEY_USERS;
                            inParams["sSubKeyName"] = name + @"\Control Panel\PowerCfg\PowerPolicies\" + policy;
                            inParams["sValueName"]  = "Policies";

                            outParams = wmiRegistry.InvokeMethod("GetBinaryValue", inParams, null);
                            if (Convert.ToUInt32(outParams["ReturnValue"]) == 0)
                            {
                                byte[] array = outParams["uValue"] as byte[];
                                string value = "";
                                for (int i = 0; i < array.Length; i++)
                                {
                                    value = value + String.Format("{0:X2}", array[i]);
                                    if ((i + 1) % 8 == 0)
                                    {
                                        int rowCount = (i + 1) / 8;
                                        if (rowCount == 4)
                                        {
                                            powerInfo = powerInfo + "" + "Standby_AC=" + ToValue(ReverseString(value.Substring(8, 8)));
                                        }
                                        else if (rowCount == 5)
                                        {
                                            powerInfo = powerInfo + "<BDNA,1>" + "Standby_DC=" + ToValue(ReverseString(value.Substring(0, 8)));
                                            powerInfo = powerInfo + "<BDNA,1>" + "Processor_Throttle_AC=" + getProcessorThrottle(ReverseString(value.Substring(12, 2)));
                                            powerInfo = powerInfo + "<BDNA,1>" + "Processor_Throttle_DC=" + getProcessorThrottle(ReverseString(value.Substring(14, 2)));
                                        }
                                        else if (rowCount == 8)
                                        {
                                            powerInfo = powerInfo + "<BDNA,1>" + "Monitor_AC=" + ToValue(ReverseString(value.Substring(0, 8)));
                                            powerInfo = powerInfo + "<BDNA,1>" + "Monitor_DC=" + ToValue(ReverseString(value.Substring(8, 8)));
                                        }
                                        else if (rowCount == 9)
                                        {
                                            powerInfo = powerInfo + "<BDNA,1>" + "Disk_AC=" + ToValue(ReverseString(value.Substring(0, 8)));
                                            powerInfo = powerInfo + "<BDNA,1>" + "Disk_DC=" + ToValue(ReverseString(value.Substring(8, 8)));
                                        }
                                        value = "";
                                    }
                                }
                            }
                            if (!resultDic.ContainsKey(lastUserID))
                            {
                                resultDic.Add(lastUserID, powerInfo);
                            }
                        }
                    }
                }
                int resultCount = resultDic.Count;
                foreach (string key in resultDic.Keys)
                {
                    if ("{00000000-0000-0000-0000-000000000000}".Equals(key) && resultCount == 1)
                    {
                        return(resultDic["{00000000-0000-0000-0000-000000000000}"]);
                    }
                    else if ("{00000000-0000-0000-0000-000000000000}".Equals(key) && resultCount > 1)
                    {
                        continue;
                    }
                    else
                    {
                        return(resultDic[key]);
                    }
                }
                return(powerInfo);
            } catch (Exception e) {
                return(powerInfo);
            } finally {
            }
        }
Exemplo n.º 49
0
        public static byte[] GenerateMachineID()
        {
            // this is steamkit's own implementation, it doesn't match what steamclient does
            // but this should make it so individual systems can be identified

            PlatformID platform = Environment.OSVersion.Platform;

            if (platform == PlatformID.Win32NT)
            {
                StringBuilder hwString = new StringBuilder();

                try
                {
                    using (ManagementClass procClass = new ManagementClass("Win32_Processor"))
                    {
                        foreach (var procObj in procClass.GetInstances())
                        {
                            hwString.AppendLine(procObj["ProcessorID"].ToString());
                        }
                    }
                }
                catch { }

                try
                {
                    using (ManagementClass hdClass = new ManagementClass("Win32_LogicalDisk"))
                    {
                        foreach (var hdObj in hdClass.GetInstances())
                        {
                            string hdType = hdObj["DriveType"].ToString();

                            if (hdType != "3")
                            {
                                continue; // only want local disks
                            }
                            hwString.AppendLine(hdObj["VolumeSerialNumber"].ToString());
                        }
                    }
                }
                catch { }

                try
                {
                    using (ManagementClass moboClass = new ManagementClass("Win32_BaseBoard"))
                    {
                        foreach (var moboObj in moboClass.GetInstances())
                        {
                            hwString.AppendLine(moboObj["SerialNumber"].ToString());
                        }
                    }
                }
                catch { }


                try
                {
                    return(CryptoHelper.SHAHash(Encoding.ASCII.GetBytes(hwString.ToString())));
                }
                catch { return(null); }
            }
            else
            {
                // todo: implement me!
                return(null);
            }
        }
Exemplo n.º 50
0
        /// <summary>
        /// Perform collection task specific processing.
        /// </summary>
        ///
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="cleId">Database Id of owning Collection Engine.</param>
        /// <param name="elementId">Database Id of element being collected.</param>
        /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param>
        /// <param name="localTimestamp">Local task dispatch timestamp.</param>
        /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param>
        /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param>
        /// <param name="connection">Connection script results (null if this script does not
        ///     require a remote host connection).</param>
        /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param>
        ///
        /// <returns>Collection results.</returns>
        public CollectionScriptResults ExecuteTask(
            long taskId,
            long cleId,
            long elementId,
            long databaseTimestamp,
            long localTimestamp,
            IDictionary <string, string> attributes,
            IDictionary <string, string> scriptParameters,
            IDictionary <string, object> connection,
            string tftpPath,
            string tftpPath_login,
            string tftpPath_password,
            ITftpDispatcher tftpDispatcher)
        {
            Stopwatch executionTimer = Stopwatch.StartNew();

            m_taskId = taskId.ToString();
            StringBuilder dataRow    = new StringBuilder();
            ResultCodes   resultCode = ResultCodes.RC_SUCCESS;

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Collection script WinRegScript.",
                                  m_taskId);
            string m_collectedData = "";

            try {
                ManagementScope cimvScope    = null;
                ManagementScope defaultScope = null;

                if (null == connection)
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Connection object passed to PowerSettingsCollectionScript is null.",
                                          m_taskId);
                }
                else if (!connection.ContainsKey(@"cimv2"))
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Management scope for CIMV namespace is not present in connection object.",
                                          m_taskId);
                }
                else if (!connection.ContainsKey(@"default"))
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Management scope for Default namespace is not present in connection object.",
                                          m_taskId);
                }
                else
                {
                    cimvScope    = connection[@"cimv2"] as ManagementScope;
                    defaultScope = connection[@"default"] as ManagementScope;

                    if (!cimvScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to CIMV namespace failed",
                                              m_taskId);
                    }
                    else if (!defaultScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to Default namespace failed",
                                              m_taskId);
                    }
                    else
                    {
                        m_wmiRegistry = new ManagementClass(defaultScope, new ManagementPath(@"StdRegProv"), null);
                        using (m_wmiRegistry) {
                            m_collectedData = GetPowerInfo(m_wmiRegistry);
                        }

                        if (ResultCodes.RC_SUCCESS == resultCode)
                        {
                            dataRow.Append(elementId)
                            .Append(',')
                            .Append(attributes[@"powerSettingsDetails"])
                            .Append(',')
                            .Append(scriptParameters[@"CollectorId"])
                            .Append(',')
                            .Append(taskId)
                            .Append(',')
                            .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds)
                            .Append(',')
                            .Append(@"powerSettingsDetails")
                            .Append(',')
                            .Append(BdnaDelimiters.BEGIN_TAG)
                            .Append(m_collectedData)
                            .Append(BdnaDelimiters.END_TAG);
                        }
                    }
                }
            } catch (Exception ex) {
                Lib.LogException(m_taskId,
                                 executionTimer,
                                 "Unhandled exception in PowerSettingsCollectionScript",
                                 ex);
                resultCode = ResultCodes.RC_PROCESSING_EXCEPTION;
            }

            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Collection script PowerSettingsCollectionScript.  Elapsed time {1}.  Result code {2}.",
                                  m_taskId,
                                  executionTimer.Elapsed.ToString(),
                                  resultCode.ToString());
            return(new CollectionScriptResults(resultCode, 0, null, null, null, false, dataRow.ToString()));
        }
Exemplo n.º 51
0
            public WmiInstallerService()
            {
                ManagementClass mc = new ManagementClass(@"root\citrix\xenserver\agent", "CitrixXenServerInstallStatus", null);
                ManagementObjectCollection coll = null;
                int counter = 0;
                while (counter < 10000)
                {
                    try
                    {
                        coll = mc.GetInstances();

                        while (coll.Count == 0 && counter < 10000)
                        {
                            if (coll.Count == 0)
                            {
                                Thread.Sleep(500);
                                counter += 500;
                            }
                            coll = mc.GetInstances();
                        }
                        break;
                    }
                    catch {
                        Thread.Sleep(500);
                        counter += 500;
                    }
                }

                if (coll == null || coll.Count == 0)
                {
                    service = null;
                    return;
                }
                foreach (ManagementObject obj in coll)
                {
                    service = obj;
                }
            }
Exemplo n.º 52
0
//        strUser = "******"
//strPath = "D:\\abc.txt"
//RetVal = AddPermission(strUser,strPath,"R",True)

//'-------------------------------------------------------------------------

//'用于给文件和文件夹添加一条权限设置.返回值: 0-成功,1-账户不存在,2-路径不存在
//'strUser表示用户名或组名
//'strPath表示文件夹路径或文件路径
//'strAccess表示允许权限设置的字符串,字符串中带有相应字母表示允许相应权限: R-读,C-读写,F-完全控制
//'blInherit表示是否继承父目录权限.True为继承,False为不继承

//Function AddPermission(strUser,strPath,strAccess,blInherit)
//        Set objWMIService = GetObject("winmgmts:\\.\root\Cimv2")
//        Set fso = CreateObject("Scripting.FileSystemObject")
//        '得到Win32_SID并判断用户/组/内置账户是否存在
//        Set colUsers = objWMIService.ExecQuery("SELECT * FROM Win32_Account WHERE Name='"&strUser&"'")
//        If colUsers.count<>0 Then
//                For Each objUser In colUsers
//                        strSID = objUser.SID
//                Next
//        Else
//                AddPermission = 1
//                Exit Function
//        End If
//        Set objSID = objWMIService.Get("Win32_SID.SID='"&strSID&"'")
//        '判断文件/文件夹是否存在
//        pathType = ""
//        If fso.fileExists(strPath) Then pathType = "FILE"
//        If fso.folderExists(strPath) Then pathType = "FOLDER"
//        If pathType = "" Then
//                AddPermission = 2
//                Exit Function
//        End If
//        '设置Trustee
//        Set objTrustee = objWMIService.Get("Win32_Trustee").SpawnInstance_()
//        objTrustee.Domain = objSID.ReferencedDomainName
//        objTrustee.Name = objSID.AccountName
//        objTrustee.SID = objSID.BinaryRepresentation
//        objTrustee.SidLength = objSID.SidLength
//        objTrustee.SIDString = objSID.Sid
//        '设置ACE
//        Set objNewACE = objWMIService.Get("Win32_ACE").SpawnInstance_()
//        objNewACE.Trustee = objTrustee
//        objNewACE.AceType = 0
//        If InStr(UCase(strAccess),"R") > 0 Then objNewACE.AccessMask = 1179817
//        If InStr(UCase(strAccess),"C") > 0 Then objNewACE.AccessMask = 1245631
//        If InStr(UCase(strAccess),"F") > 0 Then objNewACE.AccessMask = 2032127
//        If pathType = "FILE" And blInherit = True Then objNewACE.AceFlags = 16
//        If pathType = "FILE" And blInherit = False Then objNewACE.AceFlags = 0
//        If pathType = "FOLDER" And blInherit = True Then objNewACE.AceFlags = 19
//        If pathType = "FOLDER" And blInherit = False Then objNewACE.AceFlags = 3
//        '设置SD
//        Set objFileSecSetting = objWMIService.Get("Win32_LogicalFileSecuritySetting.Path='"&strPath&"'")
//        Call objFileSecSetting.GetSecurityDescriptor(objSD)
//        blSE_DACL_AUTO_INHERITED = True
//        If (objSD.ControlFlags And &H400) = 0 Then
//                blSE_DACL_AUTO_INHERITED = False
//                objSD.ControlFlags = (objSD.ControlFlags Or &H400)                '自动继承位置位,如果是刚创建的目录或文件该位是不置位的,需要置位
//        End If
//        If blInherit = True Then
//                objSD.ControlFlags = (objSD.ControlFlags And &HEFFF)        '阻止继承复位
//        Else
//                objSD.ControlFlags = (objSD.ControlFlags Or &H1400)                '阻止继承位置位,自动继承位置位
//        End If
//        objOldDacl = objSD.Dacl
//        ReDim objNewDacl(0)
//        Set objNewDacl(0) = objNewACE
//        If IsArray(objOldDacl) Then                '权限为空时objOldDacl不是集合不可遍历
//                For Each objACE In objOldDacl
//                        If (blSE_DACL_AUTO_INHERITED=False And blInherit=True) Or ((objACE.AceFlags And 16)>0 And (blInherit=True) Or (LCase(objACE.Trustee.Name)=LCase(strUser))) Then
//                                'Do nothing
//                                '当自动继承位置位为0时即使时继承的权限也会显示为非继承,这时所有权限都不设置
//                                '当自动继承位置位为0时,在继承父目录权限的情况下不设置继承的权限.账户和需要加权限的账户一样时不设置权限
//                        Else
//                                Ubd = UBound(objNewDacl)
//                                ReDim preserve objNewDacl(Ubd+1)
//                                Set objNewDacl(Ubd+1) = objACE
//                        End If
//                Next
//        End If
//        objSD.Dacl = objNewDacl
//        '提交设置修改
//        Call objFileSecSetting.SetSecurityDescriptor(objSD)
//        AddPermission = 0
//        Set fso = Nothing
//End Function



        static void Main(string[] args)
        {
            ConnectionOptions options = new ConnectionOptions();
            //options.EnablePrivileges = true;
            //options.Impersonation = ImpersonationLevel.Impersonate;
            ManagementScope scope = new ManagementScope("\\\\.\\ROOT\\cimv2", options);

            ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Account WHERE Name='" + "andyl_000" + "'");
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection queryCollection = searcher.Get();
            string           sidToGet        = string.Empty;
            ManagementObject accountInstance = null;

            foreach (ManagementObject m in queryCollection)
            {
                // access properties of the WMI object
                //Console.WriteLine("AccountName : {0}", m["AccountName"]);
                sidToGet        = m["SID"].ToString();
                accountInstance = m;
            }

            //SELECT * FROM Win32_Account WHERE Name='"&strUser&"'
            ManagementObject sidInstance = new ManagementObject("Win32_SID.SID='" + sidToGet + "'");

            ManagementClass  trustee    = new ManagementClass("Win32_Trustee");
            ManagementObject objTrustee = trustee.CreateInstance();

            objTrustee["Domain"]    = sidInstance["ReferencedDomainName"];//sidInstance["ReferencedDomainName"];
            objTrustee["Name"]      = sidInstance["AccountName"];
            objTrustee["SID"]       = sidInstance["BinaryRepresentation"];
            objTrustee["SidLength"] = sidInstance["SidLength"];
            objTrustee["SIDString"] = sidInstance["Sid"];

            ManagementClass  ace       = new ManagementClass("Win32_ACE");
            ManagementObject objNewACE = ace.CreateInstance();

            objNewACE["Trustee"]    = objTrustee;
            objNewACE["AceType"]    = 0;
            objNewACE["AccessMask"] = 2032127;
            objNewACE["AceFlags"]   = 19;


            ManagementObject     localFileSecuritySetting = new ManagementObject("Win32_LogicalFileSecuritySetting.Path='" + @"D:\ShareFolder" + "'");
            ManagementBaseObject outParams = localFileSecuritySetting.InvokeMethod("GetSecurityDescriptor", null, null);

            if (((uint)(outParams.Properties["ReturnValue"].Value)) == 0)
            {
                ManagementBaseObject secDescriptor =
                    ((ManagementBaseObject)(outParams.Properties["Descriptor"].Value));
                //The DACL is an array of Win32_ACE objects.
                ManagementBaseObject[] dacl =
                    ((ManagementBaseObject[])(secDescriptor.Properties["Dacl"].Value));
                List <ManagementBaseObject> newDacl = new List <ManagementBaseObject>(dacl);
                newDacl.Add(objNewACE);
                secDescriptor["Dacl"] = newDacl.ToArray();

                ManagementBaseObject inParams =
                    localFileSecuritySetting.GetMethodParameters("SetSecurityDescriptor");
                inParams["Descriptor"] = secDescriptor;

                localFileSecuritySetting.InvokeMethod("SetSecurityDescriptor", inParams, null);
            }

            //securityDescriptor["Dacl"];
            //        Set objFileSecSetting = objWMIService.Get("Win32_LogicalFileSecuritySetting.Path='"&strPath&"'")
            //        Call objFileSecSetting.GetSecurityDescriptor(objSD)
            //        blSE_DACL_AUTO_INHERITED = True
            //        If (objSD.ControlFlags And &H400) = 0 Then
            //                blSE_DACL_AUTO_INHERITED = False
            //                objSD.ControlFlags = (objSD.ControlFlags Or &H400)                '自动继承位置位,如果是刚创建的目录或文件该位是不置位的,需要置位
            //        End If
            //        If blInherit = True Then
            //                objSD.ControlFlags = (objSD.ControlFlags And &HEFFF)        '阻止继承复位
            //        Else
            //                objSD.ControlFlags = (objSD.ControlFlags Or &H1400)                '阻止继承位置位,自动继承位置位
            //        End If
            //        objOldDacl = objSD.Dacl
            //        ReDim objNewDacl(0)
            //        Set objNewDacl(0) = objNewACE
            //        If IsArray(objOldDacl) Then                '权限为空时objOldDacl不是集合不可遍历
            //                For Each objACE In objOldDacl
            //                        If (blSE_DACL_AUTO_INHERITED=False And blInherit=True) Or ((objACE.AceFlags And 16)>0 And (blInherit=True) Or (LCase(objACE.Trustee.Name)=LCase(strUser))) Then
            //                                'Do nothing
            //                                '当自动继承位置位为0时即使时继承的权限也会显示为非继承,这时所有权限都不设置
            //                                '当自动继承位置位为0时,在继承父目录权限的情况下不设置继承的权限.账户和需要加权限的账户一样时不设置权限
            //                        Else
            //                                Ubd = UBound(objNewDacl)
            //                                ReDim preserve objNewDacl(Ubd+1)
            //                                Set objNewDacl(Ubd+1) = objACE
            //                        End If
            //                Next
            //        End If
            //        objSD.Dacl = objNewDacl
            //        '提交设置修改
            //        Call objFileSecSetting.SetSecurityDescriptor(objSD)

            // ManagementObject secDescriptor = new ManagementClass(new ManagementPath("Win32_LogicalFileSecuritySetting"), null);
            //secDescriptor["ControlFlags"] = 4; //SE_DACL_PRESENT
            //secDescriptor["DACL"] = new object[] { objNewACE };


            // ManagementObject share = new ManagementObject(@"\\.\root\cimv2:Win32_Share.Name='ShareFolder'");
            //object invodeResult = share.InvokeMethod("SetShareInfo", new object[] { Int32.MaxValue, "This is John's share", secDescriptor });
            //Console.WriteLine(invodeResult);
            //Set objNewACE = objWMIService.Get("Win32_ACE").SpawnInstance_()
//        objNewACE.Trustee = objTrustee
//        objNewACE.AceType = 0
//        If InStr(UCase(strAccess),"R") > 0 Then objNewACE.AccessMask = 1179817
//        If InStr(UCase(strAccess),"C") > 0 Then objNewACE.AccessMask = 1245631
//        If InStr(UCase(strAccess),"F") > 0 Then objNewACE.AccessMask = 2032127
//        If pathType = "FILE" And blInherit = True Then objNewACE.AceFlags = 16
//        If pathType = "FILE" And blInherit = False Then objNewACE.AceFlags = 0
//        If pathType = "FOLDER" And blInherit = True Then objNewACE.AceFlags = 19
//        If pathType = "FOLDER" And blInherit = False Then objNewACE.AceFlags = 3


            //classs
            //create object query
            //ObjectQuery query = new ObjectQuery("SELECT * FROM WIN32_SID");

            ////create object searcher
            //ManagementObjectSearcher searcher =
            //                        new ManagementObjectSearcher(scope, query);

            ////get collection of WMI objects
            //ManagementObjectCollection queryCollection = searcher.Get();

            ////enumerate the collection.
            //foreach (ManagementObject m in queryCollection)
            //{
            //    // access properties of the WMI object
            //    Console.WriteLine("AccountName : {0}", m["AccountName"]);

            //}
            Console.Read();
        }
Exemplo n.º 53
0
    public static string GetCpuNumber()
    {
        ////获得CPU的序列号
        //string strCPU = null;
        //ManagementClass myCpu = new ManagementClass("win32_Processor");
        //ManagementObjectCollection myCpuConnection = myCpu.GetInstances();
        //foreach (ManagementObject myObject in myCpuConnection)
        //{
        //    strCPU = myObject.Properties["Processorid"].Value.ToString();
        //    break;
        //}
        //return strCPU;

        //2011.4.26ywy修改,用取网卡号替代取CPU号,后者很慢还会重复
        try
        {
            string stringMAC = "";
            ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection MOC = MC.GetInstances();

            foreach (ManagementObject MO in MOC)
            {
                //if ((bool)MO["IPEnabled"] == true)
                //{
                stringMAC = MO["MACAddress"].ToString().Replace(":", "");
                break;

                //}
            }
            return stringMAC;
        }
        catch
        {
            return GetDiskCPUNumber();
        }
    }
        //----SPailleau
        private void MoreInfoCOMPort(string PortName, int i)
        {
            string Probably             = "";
            int    CompteurSteerMachine = 0;

            string[] ListeCom = new string[20];
            int      c        = 0;
            bool     AddCom   = true;
            String   RC       = System.Environment.NewLine;

            using (ManagementClass i_Entity = new ManagementClass("Win32_PnPEntity"))
            {
                foreach (ManagementObject i_Inst in i_Entity.GetInstances())
                {
                    Object o_Guid = i_Inst.GetPropertyValue("ClassGuid");
                    if (o_Guid == null || o_Guid.ToString().ToUpper() != "{4D36E978-E325-11CE-BFC1-08002BE10318}")
                    {
                        continue; // Skip all devices except device class "PORTS"
                    }
                    String s_Caption  = i_Inst.GetPropertyValue("Caption").ToString();
                    String s_Manufact = i_Inst.GetPropertyValue("Manufacturer").ToString();
                    String s_DeviceID = i_Inst.GetPropertyValue("PnpDeviceID").ToString();
                    String s_RegPath  = "HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Enum\\" + s_DeviceID + "\\Device Parameters";
                    String s_PortName = Registry.GetValue(s_RegPath, "PortName", "").ToString();

                    int s32_Pos = s_Caption.IndexOf(" (COM");
                    if (s32_Pos > 0) // remove COM port from description
                    {
                        s_Caption = s_Caption.Substring(0, s32_Pos);
                    }

                    if (s_PortName == PortName)
                    {
                        //On évite les doublons en cas de problèmee USB
                        if (c == 0)
                        {
                            ListeCom[c] = s_PortName;         //Enregistre le nom du port com dans un tableau
                        }
                        else
                        {
                            for (int j = 0; j <= c; j++)
                            {
                                if (s_PortName == ListeCom[j] && c != 0)
                                {
                                    AddCom = false;
                                }
                            }
                        }

                        if (AddCom) //Ajout autorisé
                        {
                            ListeCom[c] = s_PortName;

                            //Check Machine
                            if (s_Manufact.Contains("FTDI") || s_Caption.Contains("CH340"))
                            {
                                if (!mf.spModule1.IsOpen)
                                {
                                    cboxModule1Port.SelectedIndex = i;
                                }
                                Probably = "---> Steer / Machine probable";
                                CompteurSteerMachine++;
                            }
                            //Check GPS
                            else if (s_Manufact.Contains("Microsoft") && s_Caption.Contains("USB"))
                            {
                                if (!mf.spGPS.IsOpen)
                                {
                                    cboxPort.SelectedIndex = i;
                                    cboxBaud.SelectedItem  = "115200";
                                }
                                Probably = "---> GPS probable";
                            }
                            else if (s_Manufact.Contains("standar"))
                            {
                                Probably = "---> Inutile";
                            }
                            else
                            {
                                Probably = "---> Inconnu";
                            }

                            ListComPort.Text += s_PortName + " " + Probably + RC + s_Caption + " - " + s_Manufact + RC + RC;
                            Probably          = "";
                        }

                        c++;
                    }
                }
            }
        }
Exemplo n.º 55
0
    public ManagementObjectCollection getAdapters()
    {
        ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");

        return(objMC.GetInstances());
    }
 public Disk()
 {
     allDrives = DriveInfo.GetDrives();
     m_class   = new ManagementClass("Win32_PerfFormattedData_PerfDisk_PhysicalDisk");
 }
Exemplo n.º 57
0
        /// <summary>
        /// Adds the share permissions.
        /// </summary>
        /// <param name="accountName">Name of the account.</param>
        public void AddSharePermission(string accountName)
        {
            ManagementObject     trustee = null;
            ManagementObject     ace     = null;
            ManagementObject     win32LogicalSecuritySetting = null;
            ManagementObject     share = null;
            ManagementBaseObject getSecurityDescriptorReturn = null;
            ManagementBaseObject securityDescriptor          = null;

            try
            {
                //// Not necessary
                //// NTAccount ntAccount = new NTAccount(accountName);
                //// SecurityIdentifier sid = (SecurityIdentifier)ntAccount.Translate(typeof(SecurityIdentifier));
                //// byte[] sidArray = new byte[sid.BinaryLength];
                //// sid.GetBinaryForm(sidArray, 0);

                trustee         = new ManagementClass(new ManagementPath("Win32_Trustee"), null);
                trustee["Name"] = accountName;
                //// trustee["SID"] = sidArray;

                ace = new ManagementClass(new ManagementPath("Win32_Ace"), null);
                //// Permissions mask http://msdn.microsoft.com/en-us/library/windows/desktop/aa394186(v=vs.85).aspx
                ace["AccessMask"] = 0x1F01FF;
                //// ace["AccessMask"] = 0x1FF;
                ace["AceFlags"] = 3;
                ace["AceType"]  = 0;
                ace["Trustee"]  = trustee;

                win32LogicalSecuritySetting = new ManagementObject(@"root\cimv2:Win32_LogicalShareSecuritySetting.Name='" + this.shareName + "'");

                getSecurityDescriptorReturn = win32LogicalSecuritySetting.InvokeMethod("GetSecurityDescriptor", null, null);

                if ((uint)getSecurityDescriptorReturn["ReturnValue"] != 0)
                {
                    throw new WindowsShareException("Unable to add share permission. Error Code: " + getSecurityDescriptorReturn["ReturnValue"]);
                }

                securityDescriptor = getSecurityDescriptorReturn["Descriptor"] as ManagementBaseObject;
                ManagementBaseObject[] dacl = securityDescriptor["DACL"] as ManagementBaseObject[];

                if (dacl == null)
                {
                    dacl = new ManagementBaseObject[] { ace };
                }
                else
                {
                    Array.Resize(ref dacl, dacl.Length + 1);
                    dacl[dacl.Length - 1] = ace;
                }

                securityDescriptor["DACL"] = dacl;

                share = new ManagementObject(@"root\cimv2:Win32_Share.Name='" + this.shareName + "'");
                uint setShareInfoReturn = (uint)share.InvokeMethod("SetShareInfo", new object[] { null, null, securityDescriptor });

                if (setShareInfoReturn != 0)
                {
                    throw new WindowsShareException("Unable to add share permission. Error code: " + setShareInfoReturn.ToString(CultureInfo.CurrentCulture));
                }
            }
            catch (Exception ex)
            {
                throw new WindowsShareException("Unable to add share permission", ex);
            }
            finally
            {
                if (trustee != null)
                {
                    trustee.Dispose();
                }

                if (ace != null)
                {
                    ace.Dispose();
                }

                if (win32LogicalSecuritySetting != null)
                {
                    win32LogicalSecuritySetting.Dispose();
                }

                if (getSecurityDescriptorReturn != null)
                {
                    getSecurityDescriptorReturn.Dispose();
                }

                if (securityDescriptor != null)
                {
                    securityDescriptor.Dispose();
                }

                if (share != null)
                {
                    share.Dispose();
                }
            }
        }
Exemplo n.º 58
0
    //method to invoke command line on remote machine
    public void InvokeCommand(string command)
    {
        try
        {
            //connection options
            var connOptions = new System.Management.ConnectionOptions();
            connOptions.Authentication   = AuthenticationLevel.PacketPrivacy;
            connOptions.Impersonation    = ImpersonationLevel.Impersonate;
            connOptions.EnablePrivileges = true;
            connOptions.Username         = Domain + "\\" + Username;
            connOptions.Password         = Password;

            //management scope
            var manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", ComputerName), connOptions);
            manScope.Connect();
            ObjectGetOptions objectGetOptions = new ObjectGetOptions();
            objectGetOptions.Timeout = TimeSpan.FromSeconds(20);
            ManagementPath       managementPath = new ManagementPath("Win32_Process");
            ManagementClass      processClass   = new ManagementClass(manScope, managementPath, objectGetOptions);
            ManagementBaseObject inParams       = processClass.GetMethodParameters("Create");

            //script to execute from passed parameter
            inParams["CommandLine"] = command;

            //execute script
            ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);

            //loop through processes until process has quit
            SelectQuery CheckProcess = new SelectQuery("Select * from Win32_Process Where ProcessId = " + outParams["processId"]);

            //counter for loop
            int counter     = 0;
            int loopcounter = Convert.ToInt32(WmiTimeout) / 10;

            //loop until process has died
            while (counter != (loopcounter + 1))
            {
                // create searcher object
                ManagementObjectSearcher ProcessSearcher = new ManagementObjectSearcher(manScope, CheckProcess);
                ProcessSearcher.Options.Timeout = TimeSpan.FromSeconds(20);

                // if it is not null there is a process running
                if (ProcessSearcher.Get().Count != 0)
                {
                    if (counter == loopcounter)
                    {
                        // kill process
                        inParams["CommandLine"] = "cmd /c \"taskkill /f /pid " + outParams["processId"].ToString() + " /t \"";
                        processClass.InvokeMethod("Create", inParams, null);

                        // throw new exception for process timeout
                        throw new Exception("WMI process timeout");
                    }
                    else
                    {
                        counter++;
                        Thread.Sleep(10000);
                    }
                }
                // if it is null then process is not running and break from loop
                else if (ProcessSearcher.Get().Count == 0)
                {
                    break;
                }
            }
        }
        catch (Exception e)
        {
            //catch exception
            throw new Exception(e.Message.ToString());
        }
    }
Exemplo n.º 59
0
        static void RemoteWMIExecuteVBS(string host, string eventName, string username, string password)
        {
            try
            {
                ConnectionOptions options = new ConnectionOptions();
                if (!String.IsNullOrEmpty(username))
                {
                    Console.WriteLine("[*] User credentials: {0}", username);
                    options.Username = username;
                    options.Password = password;
                }
                Console.WriteLine();

                // first create a 30 second timer on the remote host
                ManagementScope  timerScope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", host), options);
                ManagementClass  timerClass = new ManagementClass(timerScope, new ManagementPath("__IntervalTimerInstruction"), null);
                ManagementObject myTimer    = timerClass.CreateInstance();
                myTimer["IntervalBetweenEvents"] = (UInt32)30000;
                myTimer["SkipIfPassed"]          = false;
                myTimer["TimerId"] = "Timer";
                try
                {
                    Console.WriteLine("[*] Creating 'Timer' object on {0}", host);
                    myTimer.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in creating timer object: {0}", ex.Message);
                    return;
                }

                ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\root\subscription", host), options);

                // then install the __EventFilter for the timer object
                ManagementClass  wmiEventFilter = new ManagementClass(scope, new ManagementPath("__EventFilter"), null);
                WqlEventQuery    myEventQuery   = new WqlEventQuery(@"SELECT * FROM __TimerEvent WHERE TimerID = 'Timer'");
                ManagementObject myEventFilter  = wmiEventFilter.CreateInstance();
                myEventFilter["Name"]           = eventName;
                myEventFilter["Query"]          = myEventQuery.QueryString;
                myEventFilter["QueryLanguage"]  = myEventQuery.QueryLanguage;
                myEventFilter["EventNameSpace"] = @"\root\cimv2";
                try
                {
                    Console.WriteLine("[*] Setting '{0}' event filter on {1}", eventName, host);
                    myEventFilter.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in setting event filter: {0}", ex.Message);
                }


                // now create the ActiveScriptEventConsumer payload (VBS)
                ManagementObject myEventConsumer = new ManagementClass(scope, new ManagementPath("ActiveScriptEventConsumer"), null).CreateInstance();

                myEventConsumer["Name"]            = eventName;
                myEventConsumer["ScriptingEngine"] = "VBScript";
                myEventConsumer["ScriptText"]      = vbsPayload;
                myEventConsumer["KillTimeout"]     = (UInt32)45;

                try
                {
                    Console.WriteLine("[*] Setting '{0}' event consumer on {1}", eventName, host);
                    myEventConsumer.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in setting event consumer: {0}", ex.Message);
                }


                // finally bind them together with a __FilterToConsumerBinding
                ManagementObject myBinder = new ManagementClass(scope, new ManagementPath("__FilterToConsumerBinding"), null).CreateInstance();

                myBinder["Filter"]   = myEventFilter.Path.RelativePath;
                myBinder["Consumer"] = myEventConsumer.Path.RelativePath;

                try
                {
                    Console.WriteLine("[*] Binding '{0}' event filter and consumer on {1}", eventName, host);
                    myBinder.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in setting FilterToConsumerBinding: {0}", ex.Message);
                }


                // wait for everything to trigger
                Console.WriteLine("\r\n[*] Waiting 45 seconds for event to trigger on {0} ...\r\n", host);
                System.Threading.Thread.Sleep(45 * 1000);


                // finally, cleanup
                try
                {
                    Console.WriteLine("[*] Removing 'Timer' internal timer from {0}", host);
                    myTimer.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing 'Timer' interval timer: {0}", ex.Message);
                }

                try
                {
                    Console.WriteLine("[*] Removing FilterToConsumerBinding from {0}", host);
                    myBinder.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing FilterToConsumerBinding: {0}", ex.Message);
                }

                try
                {
                    Console.WriteLine("[*] Removing '{0}' event filter from {1}", eventName, host);
                    myEventFilter.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing event filter: {0}", ex.Message);
                }

                try
                {
                    Console.WriteLine("[*] Removing '{0}' event consumer from {0}\r\n", eventName, host);
                    myEventConsumer.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing event consumer: {0}", ex.Message);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("  Exception : {0}", ex.Message));
            }
        }
Exemplo n.º 60
0
        public ManagementObject CreateManagementObject(string className)
        {
            ManagementClass c = new ManagementClass(Scope, new ManagementPath(className), null);

            return(c.CreateInstance());
        }