public OperatingSystemPropertyOverrideAttribute(string objectType, string propertyName, string OSName, string specificVersion) { _type = objectType; _propertyName = propertyName; _osName = OsName; _specificVersion = new OSVersion(specificVersion); }
public Type3Message(string username, string password, byte[] challenge, bool useUnicode, string workstation, bool ntlmv2 = false, string targetName = null, byte[] targetInformation = null) { Username.ThrowIfNull("Username"); password.ThrowIfNull("password"); challenge.ThrowIfNull("challenge"); Encoding = useUnicode ? Encoding.Unicode : Encoding.ASCII; this.Username = Encoding.GetBytes(username); this.Workstation = Encoding.GetBytes(workstation); this.TargetName = string.IsNullOrEmpty(targetName) ? new byte[0] : Encoding.GetBytes(targetName); this.SessionKey = new byte[0]; if (!ntlmv2) { LMResponse = Responses.ComputeLMResponse(challenge, password); NtlmResponse = Responses.ComputeNtlmResponse(challenge, password); } else { byte[] cnonce = GetCNonce(); LMResponse = Responses.ComputeLMv2Response(targetName, username, password, challenge, cnonce); NtlmResponse = Responses.ComputeNtlmv2Response(targetName, username, password, targetInformation, challenge, cnonce); } OSVersion = new OSVersion(6, 1, 7601); }
public OperatingSystemFunctionOverrideAttribute(string objectType, string methodName, string OSName, string specificVersion) { _type = objectType; _methodName = methodName; _osName = OsName; _specificVersion = new OSVersion(specificVersion); }
public OperatingSystemFunctionOverrideAttribute(string objectType,string methodName,string OSName, string minVersion, string maxVersion) { _type = objectType; _methodName = methodName; _osName = OSName; _minVersion = new OSVersion(minVersion); if (maxVersion != null) _maxVersion = new OSVersion(maxVersion); }
public OperatingSystemPropertyOverrideAttribute(string objectType, string propertyName, string OSName, string minVersion, string maxVersion) { _type = objectType; _propertyName = propertyName; _osName = OSName; _minVersion = new OSVersion(minVersion); if (maxVersion != null) _maxVersion = new OSVersion(maxVersion); }
public OperatingSystemPropertyOverrideAttribute(string objectType, string propertyName, string OSName, string[] specificVersions) { _type = objectType; _propertyName = propertyName; _osName = OSName; _specificVersions=new OSVersion[specificVersions.Length]; for (int x=0;x<specificVersions.Length;x++){ _specificVersions[x] = new OSVersion(specificVersions[x]); } }
public OperatingSystemFunctionOverrideAttribute(string objectType, string methodName, string OSName, string[] specificVersions) { _type = objectType; _methodName = methodName; _osName = OSName; _specificVersions=new OSVersion[specificVersions.Length]; for (int x=0;x<specificVersions.Length;x++){ _specificVersions[x] = new OSVersion(specificVersions[x]); } }
static OSEnvironmentHelper() { currentServicePack = (byte)Environment.OSVersion.Version.MajorRevision; int major = Environment.OSVersion.Version.Major; int minor = Environment.OSVersion.Version.Minor; if ((major < 5) || ((major == 5) && (minor == 0))) { currentVersion = OSVersion.PreWinXP; } if ((major == 5) && (minor == 1)) { currentVersion = OSVersion.WinXP; } else if ((major == 5) && (minor == 2)) { currentVersion = OSVersion.Win2003; } else if ((major == 6) && (minor == 0)) { currentVersion = OSVersion.WinVista; } else if ((major == 6) && (minor == 1)) { currentVersion = OSVersion.Win7; } else if ((major == 6) && (minor == 2)) { currentVersion = OSVersion.Win8; } else if ((major > 6) || ((major == 6) && (minor > 2))) { currentVersion = OSVersion.PostWin8; } else { // This should only be possible if major == 5 and minor > 2 Fx.Assert(false, "Unknown OS"); currentVersion = OSVersion.Unknown; } }
public Type1Message(string domain, string workstation) { Domain.ThrowIfNull("Domain"); Workstation.ThrowIfNull("Workstation"); this.Domain = Encoding.ASCII.GetBytes(domain); if (this.Domain.Length >= short.MaxValue) { throw new ArgumentOutOfRangeException("The supplied Domain name must " + "not be longer than " + short.MaxValue); } this.Workstation = Encoding.ASCII.GetBytes(workstation); if (this.Workstation.Length >= short.MaxValue) { throw new ArgumentOutOfRangeException("The supplied Workstation name " + "must not be longer than " + short.MaxValue); } Flags = Flags.NegotiateUnicode | Flags.RequestTarget | Flags.NegotiateNTLM | Flags.NegotiateDomainSupplied | Flags.NegotiateWorkstationSupplied; OSVersion = new OSVersion(6, 1, 7601); }
public void IgnoresLeadingZeroes() { Assert.That(OSVersion.Parse("0012.02.004") == new OSVersion(12, 2, 4)); }
public HeapsWindow(int pid, HeapInformation[] heaps) { InitializeComponent(); this.AddEscapeToClose(); this.SetTopMost(); listHeaps.AddShortcuts(); listHeaps.ContextMenu = menuHeap; GenericViewMenu.AddMenuItems(copyMenuItem.MenuItems, listHeaps, null); // Native threads don't work properly on XP. if (OSVersion.IsBelowOrEqual(WindowsVersion.XP)) { destroyMenuItem.Visible = false; } var comparer = new SortedListViewComparer(listHeaps); listHeaps.ListViewItemSorter = comparer; comparer.CustomSorters.Add(1, (l1, l2) => { HeapInformation heap1 = l1.Tag as HeapInformation; HeapInformation heap2 = l2.Tag as HeapInformation; return(heap1.BytesAllocated.CompareTo(heap2.BytesAllocated)); }); comparer.CustomSorters.Add(2, (l1, l2) => { HeapInformation heap1 = l1.Tag as HeapInformation; HeapInformation heap2 = l2.Tag as HeapInformation; return(heap1.BytesCommitted.CompareTo(heap2.BytesCommitted)); }); _pid = pid; IntPtr defaultHeap = IntPtr.Zero; try { using (var phandle = new ProcessHandle( pid, Program.MinProcessQueryRights | Program.MinProcessReadMemoryRights)) defaultHeap = phandle.GetHeap(); } catch (WindowsException) { } long allocatedTotal = 0, committedTotal = 0; int entriesTotal = 0, tagsTotal = 0, pseudoTagsTotal = 0; foreach (HeapInformation heap in heaps) { ListViewItem litem = listHeaps.Items.Add(new ListViewItem( new string[] { Utils.FormatAddress(heap.Address), heap.BytesAllocated.ToString("N0") + " B", heap.BytesCommitted.ToString("N0") + " B", heap.EntryCount.ToString("N0") //heap.TagCount.ToString("N0"), //heap.PseudoTagCount.ToString("N0") })); litem.Tag = heap; // Make the default heap bold. if (heap.Address == defaultHeap) { litem.Font = new Font(litem.Font, FontStyle.Bold); } // Sum everything up. allocatedTotal += heap.BytesAllocated; committedTotal += heap.BytesCommitted; entriesTotal += heap.EntryCount; tagsTotal += heap.TagCount; pseudoTagsTotal += heap.PseudoTagCount; } // Totals row. listHeaps.Items.Add(new ListViewItem( new string[] { "Totals", allocatedTotal.ToString("N0") + " B", committedTotal.ToString("N0") + " B", entriesTotal.ToString("N0") //tagsTotal.ToString("N0"), //pseudoTagsTotal.ToString("N0") })).Tag = new HeapInformation( IntPtr.Zero, allocatedTotal, committedTotal, tagsTotal, entriesTotal, pseudoTagsTotal ); }
public static bool IsOSVersionLessThan(OSVersion version) { return(!IsOsVersionGreaterThanOrEqual(version)); }
public static bool IsOsVersionGreaterThanOrEqual(OSVersion version) { return(IsOsVersionGreaterThan(version) || IsOsVersion(version)); }
public static OSVersion GetOSVersion() { //var versionString = (string)Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion").GetValue("productName"); OperatingSystem os = System.Environment.OSVersion; Version vs = os.Version; OSVersion operatingSystem = OSVersion.Unknown; if (os.Platform == PlatformID.Win32Windows) { //This is a pre-NT version of Windows switch (vs.Minor) { case 0: operatingSystem = OSVersion.Windows_95; break; case 10: if (vs.Revision.ToString() == "2222A") { operatingSystem = OSVersion.Windows_98SE; } else { operatingSystem = OSVersion.Windows_98; } break; case 90: operatingSystem = OSVersion.Windows_ME; break; default: break; } } else if (os.Platform == PlatformID.Win32NT) { switch (vs.Major) { case 3: operatingSystem = OSVersion.Windows_NT3; break; case 4: operatingSystem = OSVersion.Windows_NT4; break; case 5: if (vs.Minor == 0) { operatingSystem = OSVersion.Windows_2000; } else { operatingSystem = OSVersion.Windows_XP; } break; case 6: if (vs.Minor == 0) { operatingSystem = OSVersion.Windows_Vista; } else if (vs.Minor == 1) { operatingSystem = OSVersion.Windows_7; } else if (vs.Minor == 2) { operatingSystem = OSVersion.Windows_8; } else { operatingSystem = OSVersion.Windows_8_1; } break; case 10: operatingSystem = OSVersion.Windows_10; break; default: break; } } return(operatingSystem); }
public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); // Initializing the ITestSite object if (null == DataSchemaSite) { DataSchemaSite = TestClassBase.BaseTestSite; } adAdapter = new ADDataSchemaAdapter(); adAdapter.Initialize(DataSchemaSite); //Model for AD/DS dcModel = new ModelDomainController(adAdapter.rootDomainDN, null); //Protocol Short Name. DataSchemaSite.DefaultProtocolDocShortName = "MS-ADTS-Schema"; //Specifying the windows version ServerVersion serverVersion = (ServerVersion)adAdapter.PDCOSVersion; if (serverVersion == ServerVersion.Win2003) { serverOS = OSVersion.WinSvr2003; } else if (serverVersion == ServerVersion.Win2008) { serverOS = OSVersion.WinSvr2008; } else if (serverVersion == ServerVersion.Win2008R2) { serverOS = OSVersion.WinSvr2008R2; } else if (serverVersion == ServerVersion.Win2012) { serverOS = OSVersion.WinSvr2012; } else if (serverVersion == ServerVersion.Win2012R2) { serverOS = OSVersion.WinSvr2012R2; } else if (serverVersion == ServerVersion.Win2016) { serverOS = OSVersion.Win2016; } else { serverOS = OSVersion.OtherOS; } //Storing the XML paths. string[] tdSources; if (serverVersion <= ServerVersion.Win2012R2) { tdSources = adAdapter.TDXmlPath.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } else { tdSources = adAdapter.OpenXmlPath.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } Map <string, string> rootDomainDNSubs = new Map <string, string>().Add("<RootDomainDN>", adAdapter.rootDomainDN); DSSchemaLoadResult = dcModel.LoadSchema( SchemaReader.ReadSchema( tdSources, null, true, serverOS), rootDomainDNSubs, serverOS); if (adAdapter.RunLDSTestCases) { string[] ldsTdSource; if (serverVersion <= ServerVersion.Win2012R2) { ldsTdSource = adAdapter.LdsTDXmlPath.Split(','); } else { ldsTdSource = adAdapter.LdsOpenXmlPath.Split(','); } //Model for AD/LDS adamModel = new ModelDomainController(adAdapter.LDSRootObjectName, null); Map <string, string> adamRootDomainDNSubs = new Map <string, string>().Add("<RootDomainDN>", adAdapter.LDSRootObjectName); LDSSchemaLoadResult = adamModel.LoadSchema( SchemaReader.ReadSchema( ldsTdSource, null, true, serverOS), adamRootDomainDNSubs, serverOS); } }
public static OSVersion ReadOSVersion(BinaryReader r) { OSVersion version = new OSVersion(); version.MajorVersion = r.ReadByte(); version.MinorVersion = r.ReadByte(); version.BuildNumber = r.ReadInt16(); r.ReadInt32(); return version; }
/// <summary> /// Obtain a Byte Array List Representing PkeyConfig for Microsoft Windows PIDX Check from Program /// </summary> /// <param name="product">Name of Microsoft Windows Product to Choose based on selection</param> /// <returns>Byte Array Representations of PkeyConfig.xrm-ms files</returns> public static List <byte[]> GetPkeyConfigWindows(string product = "") { // Choose by Product if Provided if (String.IsNullOrWhiteSpace(product)) { // Get Microsoft Windows Edition product = OSVersion.GetWindowsName(); } // Choose PkeyConfigs based on Microsoft Windows Edition switch (product) { case OSVersion.WinVista: case OSVersion.WinServer2008: return(new List <byte[]> { Resources.pkeyconfig_winvista }); case OSVersion.Win7: case OSVersion.WinServer2008R2: return(new List <byte[]> { Resources.pkeyconfig_win7, Resources.pkeyconfig_win7embeddedpos, Resources.pkeyconfig_win7embeddedstd, Resources.pkeyconfig_win7thinpc, }); case OSVersion.Win7Embedded: return(new List <byte[]> { Resources.pkeyconfig_win7embeddedpos, Resources.pkeyconfig_win7embeddedstd, Resources.pkeyconfig_win7thinpc, Resources.pkeyconfig_win7 }); case OSVersion.Win8: case OSVersion.WinServer2012: return(new List <byte[]> { Resources.pkeyconfig_win8, Resources.pkeyconfig_win8csvlk, Resources.pkeyconfig_win8embeddedstd, Resources.pkeyconfig_win8embeddedindustry }); case OSVersion.Win8Embedded: return(new List <byte[]> { Resources.pkeyconfig_win8embeddedstd, Resources.pkeyconfig_win8embeddedindustry, Resources.pkeyconfig_win8, Resources.pkeyconfig_win8csvlk }); case OSVersion.Win81: case OSVersion.Win81Embedded: case OSVersion.WinServer2012R2: return(new List <byte[]> { Resources.pkeyconfig_win81, Resources.pkeyconfig_win81csvlk }); case OSVersion.Win10: case OSVersion.Win10Embedded: case OSVersion.WinServer2016: case OSVersion.WinServer2019: return(new List <byte[]> { // Threshold 1 Resources.pkeyconfig_win10_10240, Resources.pkeyconfig_win10csvlk_10240, // Threshold 2 Resources.pkeyconfig_win10_10586, Resources.pkeyconfig_win10csvlk_10586, // Redstone 1 Resources.pkeyconfig_win10_14393, Resources.pkeyconfig_win10csvlk_14393, // Redstone 2 Resources.pkeyconfig_win10_15063, Resources.pkeyconfig_win10csvlk_15063, // Redstone 3 Resources.pkeyconfig_win10_16299, Resources.pkeyconfig_win10csvlk_16299, // Redstone 4 Resources.pkeyconfig_win10_17134, Resources.pkeyconfig_win10csvlk_17134, // Redstone 5 Resources.pkeyconfig_win10_17763, Resources.pkeyconfig_win10csvlk_17763 }); default: throw new ApplicationException("No PkeyConfig Matching this Product!"); } }
/// <summary> /// Returns true if this wrapper is compatible with the given operating /// system, otherwise false. /// </summary> /// <param name="os">The operating system.</param> public bool IsCompatibleWithOS(OSVersion os) { return(!disallowedOSList.Contains(os)); }
/// <summary> /// Install KMS Server Service and Setup Windows Service Registration /// </summary> /// <param name="installPath">Path to write Program File</param> /// <param name="kmsServerService">Byte Array representation of KMS Server Service Program File </param> /// <returns>Output of Installation Process</returns> public static string InstallKMSServerService(string installPath, byte[] kmsServerService) { using (StringWriter output = new StringWriter()) { // Create Program File try { try { _kmsServerServiceInstallPath = installPath; // Create Windows Defender Exclusion if (OSVersion.GetWindowsNumber() >= 10.0) { CommonUtilities.ExecuteCommand("powershell.exe Add-MpPreference -ExclusionPath " + CommonUtilities.EscapePath(_kmsServerServiceInstallPath) + " -Force", true); } // Create KMS Server Service CommonUtilities.FileCreate(KMSServerServiceFileName, kmsServerService, _kmsServerServiceInstallPath); output.WriteLine("Created " + _kmsServerServiceInstallPath + Path.DirectorySeparatorChar + KMSServerServiceFileName); } catch (Exception) { _kmsServerServiceInstallPath = Environment.GetEnvironmentVariable("windir") + Path.DirectorySeparatorChar + KMSServerServiceName; output.WriteLine("Could not access KMS Server Service path set in Settings, using default installation path."); CommonUtilities.FileCreate(KMSServerServiceFileName, kmsServerService, _kmsServerServiceInstallPath); output.WriteLine("Created " + _kmsServerServiceInstallPath + Path.DirectorySeparatorChar + KMSServerServiceFileName); } } catch (Exception) { // Remove Windows Defender Exclusion if (OSVersion.GetWindowsNumber() >= 10.0) { CommonUtilities.ExecuteCommand("powershell.exe Remove-MpPreference -ExclusionPath " + CommonUtilities.EscapePath(_kmsServerServiceInstallPath) + " -Force", true); } output.WriteLine("Failed to create " + _kmsServerServiceInstallPath + Path.DirectorySeparatorChar + KMSServerServiceFileName); output.Write("KMS Server Service failed to install!"); return(output.ToString()); } // Create Windows Service Registration try { MakeKMSServerServiceRegistration(); output.WriteLine("Created KMS Server Service Registration"); } catch (Exception ex) { output.WriteLine("Failed to create KMS Server Service Registration"); output.WriteLine(ex.Message); output.WriteLine("Cleaning up as KMS Server Service is partially installed"); // Delete Program File try { CommonUtilities.FileDelete(_kmsServerServiceInstallPath + Path.DirectorySeparatorChar + KMSServerServiceFileName); output.WriteLine("Deleted " + _kmsServerServiceInstallPath + Path.DirectorySeparatorChar + KMSServerServiceFileName); } catch (Exception) { output.WriteLine("Failed to delete " + _kmsServerServiceInstallPath + Path.DirectorySeparatorChar + KMSServerServiceFileName); } // Remove Windows Defender Exclusion if (OSVersion.GetWindowsNumber() >= 10.0) { CommonUtilities.ExecuteCommand("powershell.exe Remove-MpPreference -ExclusionPath " + CommonUtilities.EscapePath(_kmsServerServiceInstallPath) + " -Force", true); } output.Write("KMS Server Service failed to install!"); return(output.ToString()); } output.Write("KMS Server Service was succesfully installed."); Services.StartService(KMSServerServiceName); return(output.ToString()); } }
/// <summary> /// Reads the properties of this DirectDrawWrapper from an INI section. /// </summary> /// <param name="section">The INI section.</param> private void Parse(IniSection section) { if (section == null) { Logger.Log("DirectDrawWrapper: Configuration for renderer '" + InternalName + "' not found!"); return; } UIName = section.GetStringValue("UIName", "Unnamed renderer"); if (section.GetBooleanValue("IsDxWnd", false)) { // For backwards compatibility with previous client versions WindowedModeSection = "DxWnd"; WindowedModeKey = "RunInWindow"; BorderlessWindowedModeKey = "NoWindowFrame"; } WindowedModeSection = section.GetStringValue("WindowedModeSection", WindowedModeSection); WindowedModeKey = section.GetStringValue("WindowedModeKey", WindowedModeKey); BorderlessWindowedModeKey = section.GetStringValue("BorderlessWindowedModeKey", BorderlessWindowedModeKey); IsBorderlessWindowedModeKeyReversed = section.GetBooleanValue("IsBorderlessWindowedModeKeyReversed", IsBorderlessWindowedModeKeyReversed); if (BorderlessWindowedModeKey != null && WindowedModeSection == null) { throw new DirectDrawWrapperConfigurationException( "BorderlessWindowedModeKey= is defined for renderer" + $" {InternalName} but WindowedModeSection= is not!"); } Hidden = section.GetBooleanValue("Hidden", false); UseQres = section.GetBooleanValue("UseQres", true); ddrawDLLPath = section.GetStringValue("DLLName", string.Empty); ConfigFileName = section.GetStringValue("ConfigFileName", string.Empty); resConfigFileName = section.GetStringValue("ResConfigFileName", ConfigFileName); filesToCopy = section.GetStringValue("AdditionalFiles", string.Empty).Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); string[] disallowedOSs = section.GetStringValue("DisallowedOperatingSystems", string.Empty).Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string os in disallowedOSs) { OSVersion disallowedOS = (OSVersion)Enum.Parse(typeof(OSVersion), os.Trim()); disallowedOSList.Add(disallowedOS); } if (!string.IsNullOrEmpty(ddrawDLLPath) && !File.Exists(ProgramConstants.GetBaseResourcePath() + ddrawDLLPath)) { Logger.Log("DirectDrawWrapper: File specified in DLLPath= for renderer '" + InternalName + "' does not exist!"); } if (!string.IsNullOrEmpty(resConfigFileName) && !File.Exists(ProgramConstants.GetBaseResourcePath() + resConfigFileName)) { Logger.Log("DirectDrawWrapper: File specified in ConfigFileName= for renderer '" + InternalName + "' does not exist!"); } foreach (var file in filesToCopy) { if (!File.Exists(ProgramConstants.GetBaseResourcePath() + file)) { Logger.Log("DirectDrawWrapper: Additional file '" + file + "' for renderer '" + InternalName + "' does not exist!"); } } }
public SDL2_GamePlatform(Game game) : base(game, Fna.FnaPlatform.Platform.GetSDLPlatform()) { /* SDL2 might complain if an OS that uses SDL_main has not actually * used SDL_main by the time you initialize SDL2. * The only platform that is affected is Windows, but we can skip * their WinMain. This was only added to prevent iOS from exploding. * -flibit */ SDL.SDL_SetMainReady(); // This _should_ be the first real SDL call we make... SDL.SDL_Init( SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_JOYSTICK | SDL.SDL_INIT_GAMECONTROLLER | SDL.SDL_INIT_HAPTIC ); // Set and initialize the SDL2 window Window = new SDL2_GameWindow(); // Create the DisplayMode list displayIndex = SDL.SDL_GetWindowDisplayIndex( Window.Handle ); INTERNAL_GenerateDisplayModes(); // Disable the screensaver. SDL.SDL_DisableScreenSaver(); // We hide the mouse cursor by default. if (IsMouseVisible) { IsMouseVisible = false; } else { /* Since IsMouseVisible is already false, OnMouseVisibleChanged * will NOT be called! So we get to do it ourselves. * -flibit */ SDL.SDL_ShowCursor(0); } // OSX has some fancy fullscreen features, let's use them! if (OSVersion.Equals("Mac OS X")) { string hint = SDL.SDL_GetHint(SDL.SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES); INTERNAL_useFullscreenSpaces = (String.IsNullOrEmpty(hint) || hint.Equals("1")); } else { INTERNAL_useFullscreenSpaces = false; } // Create the OpenAL device OpenALDevice.Initialize(); // Initialize Active Key List keys = new List <Keys>(); // Setup Text Input Control Character Arrays (Only 4 control keys supported at this time) INTERNAL_TextInputControlDown = new bool[4]; INTERNAL_TextInputControlRepeat = new int[4]; // Assume we will have focus. IsActive = true; // Ready to run the loop! INTERNAL_runApplication = true; #if WIIU_GAMEPAD wiiuStream = DRC.drc_new_streamer(); if (wiiuStream == IntPtr.Zero) { System.Console.WriteLine("Failed to alloc GamePad stream!"); return; } if (DRC.drc_start_streamer(wiiuStream) < 1) // ??? { System.Console.WriteLine("Failed to start GamePad stream!"); DRC.drc_delete_streamer(wiiuStream); wiiuStream = IntPtr.Zero; return; } DRC.drc_enable_system_input_feeder(wiiuStream); Rectangle bounds = Window.ClientBounds; wiiuPixelData = new byte[bounds.Width * bounds.Height * 4]; #endif }
public void SetImage(MenuItem mnuItem, Image value, bool ignorePending) { if (_delaySetImageCalls && !ignorePending) { _pendingSetImageCalls.Enqueue(new KeyValuePair <MenuItem, Image>(mnuItem, value)); return; } Properties prop = EnsurePropertiesExists(mnuItem); if (DesignMode) { prop.Image = value; } if (!DesignMode && OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { //Destroy old bitmap object if (prop.renderBmpHbitmap != IntPtr.Zero) { DeleteObject(prop.renderBmpHbitmap); prop.renderBmpHbitmap = IntPtr.Zero; } //if there's no Image, then just bail out if (value == null) { // wj32: clean up resources before doing that... RemoveVistaMenuItem(mnuItem); return; } //convert to 32bppPArgb (the 'P' means The red, green, and blue components are premultiplied, according to the alpha component.) Bitmap renderBmp = new Bitmap(value.Width, value.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); Graphics g = Graphics.FromImage(renderBmp); g.DrawImage(value, 0, 0, value.Width, value.Height); g.Dispose(); prop.renderBmpHbitmap = renderBmp.GetHbitmap(Color.FromArgb(0, 0, 0, 0)); renderBmp.Dispose(); if (formHasBeenIntialized) { AddVistaMenuItem(mnuItem); } } else if (!DesignMode && OSVersion.IsBelow(WindowsVersion.Vista)) { if (prop.PreVistaBitmap != null) { prop.PreVistaBitmap.Dispose(); prop.PreVistaBitmap = null; } if (value == null) { RemoveVistaMenuItem(mnuItem); return; } Bitmap bmp = new Bitmap(value.Width, value.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); Graphics g = Graphics.FromImage(bmp); g.DrawImage(value, 0, 0, value.Width, value.Height); g.Dispose(); prop.PreVistaBitmap = bmp; //for every Pre-Vista Windows, add the parent of the menu item to the list of parents if (formHasBeenIntialized) { AddPreVistaMenuItem(mnuItem); } } }
internal static bool IsAtLeast(OSVersion version) { return IsAtLeast(version, 0); }
private void unloadMenuItem_Click(object sender, EventArgs e) { if (!PhUtils.ShowConfirmMessage( "Unload", _pid != 4 ? "the selected module" : "the selected driver", _pid != 4 ? "Unloading a module may cause the process to crash." : "Unloading a driver may cause system instability.", true )) { return; } if (_pid == 4) { try { var moduleItem = (ModuleItem)listModules.SelectedItems[0].Tag; string serviceName = null; // Try to find the name of the service key for the driver by // looping through the objects in the Driver directory and // opening each one. using (var dhandle = new DirectoryHandle("\\Driver", DirectoryAccess.Query)) { foreach (var obj in dhandle.GetObjects()) { try { using (var driverHandle = new DriverHandle("\\Driver\\" + obj.Name)) { if (driverHandle.GetBasicInformation().DriverStart == moduleItem.BaseAddress) { serviceName = driverHandle.GetServiceKeyName(); break; } } } catch { } } } // If we didn't find the service name, use the driver base name. if (serviceName == null) { if (moduleItem.Name.ToLower().EndsWith(".sys")) { serviceName = moduleItem.Name.Remove(moduleItem.Name.Length - 4, 4); } else { serviceName = moduleItem.Name; } } RegistryKey servicesKey = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services", true); bool serviceKeyCreated; RegistryKey serviceKey; // Check if the service key exists so that we don't delete it // later if it does. if (Array.Exists <string>(servicesKey.GetSubKeyNames(), (keyName) => (string.Compare(keyName, serviceName, true) == 0))) { serviceKeyCreated = false; } else { serviceKeyCreated = true; // Create the service key. serviceKey = servicesKey.CreateSubKey(serviceName); serviceKey.SetValue("ErrorControl", 1, RegistryValueKind.DWord); serviceKey.SetValue("ImagePath", "\\??\\" + moduleItem.FileName, RegistryValueKind.ExpandString); serviceKey.SetValue("Start", 1, RegistryValueKind.DWord); serviceKey.SetValue("Type", 1, RegistryValueKind.DWord); serviceKey.Close(); servicesKey.Flush(); } try { Windows.UnloadDriver(serviceName); } finally { if (serviceKeyCreated) { servicesKey.DeleteSubKeyTree(serviceName); } servicesKey.Close(); } listModules.SelectedItems.Clear(); } catch (Exception ex) { MessageBox.Show("Unable to unload the driver. Make sure Process Hacker " + "is running with administrative privileges. Error:\n\n" + ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { try { using (ProcessHandle phandle = new ProcessHandle(_pid, Program.MinProcessQueryRights | ProcessAccess.VmOperation | ProcessAccess.VmRead | ProcessAccess.VmWrite | ProcessAccess.CreateThread)) { IntPtr baseAddress = ((ModuleItem)listModules.SelectedItems[0].Tag).BaseAddress; phandle.SetModuleReferenceCount(baseAddress, 1); ThreadHandle thread; if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { // Use RtlCreateUserThread to bypass session boundaries. Since // LdrUnloadDll is a native function we don't need to notify CSR. thread = phandle.CreateThread( Loader.GetProcedure("ntdll.dll", "LdrUnloadDll"), baseAddress ); } else { // On XP it seems we need to notify CSR... thread = phandle.CreateThreadWin32( Loader.GetProcedure("kernel32.dll", "FreeLibrary"), baseAddress ); } thread.Wait(1000 * Win32.TimeMsTo100Ns); NtStatus exitStatus = thread.GetExitStatus(); if (exitStatus == NtStatus.DllNotFound) { if (IntPtr.Size == 8) { PhUtils.ShowError("Unable to find the module to unload. This may be caused " + "by an attempt to unload a mapped file or a 32-bit module."); } else { PhUtils.ShowError("Unable to find the module to unload. This may be caused " + "by an attempt to unload a mapped file."); } } else { exitStatus.ThrowIf(); } thread.Dispose(); } listModules.SelectedItems.Clear(); } catch (Exception ex) { PhUtils.ShowException("Unable to unload the module", ex); } } }
/// <summary> /// Creates a new instance of the Type1Message class using the specified /// domain and workstation names. /// </summary> /// <param name="domain">The domain in which the client's workstation has /// membership.</param> /// <param name="workstation">The client's workstation name.</param> /// <exception cref="ArgumentNullException">Thrown if the domain or the /// workstation parameter is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown if the domain /// or the workstation name exceeds the maximum allowed string /// length.</exception> /// <remarks>The domain as well as the workstation name is restricted /// to ASCII characters and must not be longer than 65536 characters. /// </remarks> public Type1Message(string domain, string workstation) { // Fixme: Is domain mandatory? domain.ThrowIfNull("domain"); workstation.ThrowIfNull("workstation"); this.domain = Encoding.ASCII.GetBytes(domain); if (this.domain.Length >= Int16.MaxValue) { throw new ArgumentOutOfRangeException("The supplied domain name must " + "not be longer than " + Int16.MaxValue); } this.workstation = Encoding.ASCII.GetBytes(workstation); if (this.workstation.Length >= Int16.MaxValue) { throw new ArgumentOutOfRangeException("The supplied workstation name " + "must not be longer than " + Int16.MaxValue); } Flags = Flags.NegotiateUnicode | Flags.RequestTarget | Flags.NegotiateNTLM | Flags.NegotiateDomainSupplied | Flags.NegotiateWorkstationSupplied; // We spoof an OS version of Windows 7 Build 7601. OSVersion = new OSVersion(6, 1, 7601); }
private void LoadStage1() { this.InitializeHighlightingColors(); this.LoadSettings(); if (!OSVersion.HasUac) { comboElevationLevel.Enabled = false; } labelPluginDescription.Text = ""; foreach (var plugin in Program.AppInstance.GetPlugins()) { listPlugins.Items.Add(new ListViewItem() { Tag = plugin.Name, Text = plugin.Title }); } bool visualStyles = Application.RenderWithVisualStyles; foreach (TabPage tab in tabControl.TabPages) { foreach (Control c in tab.Controls) { // If we don't have visual styles or we're on XP, fix control backgrounds. if (!visualStyles || OSVersion.IsBelowOrEqual(WindowsVersion.XP)) { if (c is CheckBox) { (c as CheckBox).FlatStyle = FlatStyle.Standard; } if (c is RadioButton) { (c as RadioButton).FlatStyle = FlatStyle.Standard; } } // Add event handlers to enable the apply button. if (c is CheckBox || c is ListView || c is NumericUpDown) { c.Click += (sender, e) => this.EnableApplyButton(); } else if (c is TextBox) { (c as TextBox).TextChanged += (sender, e) => this.EnableApplyButton(); } else if (c is ComboBox) { (c as ComboBox).SelectedIndexChanged += (sender, e) => this.EnableApplyButton(); } else if (c is NumericUpDown) { (c as NumericUpDown).ValueChanged += (sender, e) => this.EnableApplyButton(); } else if (c is ColorModifier) { (c as ColorModifier).ColorChanged += (sender, e) => this.EnableApplyButton(); } else if (c is Button || c is Label || c is GroupBox) { Program.Void(); // Nothing } else { c.Click += (sender, e) => this.EnableApplyButton(); } } } foreach (Control c in UpdaterSettingsGroupBox.Controls) { // If we don't have visual styles or we're on XP, fix control backgrounds. if (!visualStyles || OSVersion.IsBelowOrEqual(WindowsVersion.XP)) { if (c is CheckBox) { (c as CheckBox).FlatStyle = FlatStyle.Standard; } if (c is RadioButton) { (c as RadioButton).FlatStyle = FlatStyle.Standard; } } c.Click += (sender, e) => this.EnableApplyButton(); } }
public static OSVersion GetOperateSystem() { OSVersion version = (Application.platform == RuntimePlatform.WindowsEditor) ? OSVersion.Windows : OSVersion.MacOS; return(version); }
public Handbrake(string Parameters, JobStatus jobStatus, Log jobLog, bool ignoreSuspend = false) : base(Parameters, (OSVersion.GetOSVersion() <= OSVersion.OS.WIN_2003 ? APP_PATH_XP : APP_PATH), jobStatus, jobLog, ignoreSuspend) { _uiAdminSessionProcess = true; // Always assume handbrake is running hardware API's, safety (no harm in running in UI session 1 always) _success = false; //Handbrake look for a +ve output in it's handlers so we start with a false }
/// <summary> /// Starts the main game process. /// </summary> public static void StartGameProcess() { Logger.Log("About to launch main game executable."); OSVersion osVersion = ClientConfiguration.Instance.GetOperatingSystemVersion(); string gameExecutableName = osVersion == OSVersion.UNIX ? ClientConfiguration.Instance.GetUnixGameExecutableName() : ClientConfiguration.Instance.GetGameExecutableName(); if (osVersion == OSVersion.UNIX) { gameExecutableName = ClientConfiguration.Instance.GetUnixGameExecutableName(); } else { gameExecutableName = ClientConfiguration.Instance.GetGameExecutableName(); } string extraCommandLine = ClientConfiguration.Instance.ExtraExeCommandLineParameters; File.Delete(ProgramConstants.GamePath + "DTA.LOG"); File.Delete(ProgramConstants.GamePath + "TI.LOG"); File.Delete(ProgramConstants.GamePath + "TS.LOG"); GameProcessStarting?.Invoke(); if (UserINISettings.Instance.WindowedMode && UseQres) { Logger.Log("Windowed mode is enabled - using QRes."); Process QResProcess = new Process(); QResProcess.StartInfo.FileName = ProgramConstants.QRES_EXECUTABLE; QResProcess.StartInfo.UseShellExecute = false; if (!string.IsNullOrEmpty(extraCommandLine)) { QResProcess.StartInfo.Arguments = "c=16 /R " + "\"" + ProgramConstants.GamePath + gameExecutableName + "\" " + extraCommandLine + " -SPAWN"; } else { QResProcess.StartInfo.Arguments = "c=16 /R " + "\"" + ProgramConstants.GamePath + gameExecutableName + "\" " + "-SPAWN"; } QResProcess.EnableRaisingEvents = true; QResProcess.Exited += new EventHandler(Process_Exited); try { QResProcess.Start(); } catch (Exception ex) { Logger.Log("Error launching QRes: " + ex.Message); MessageBox.Show("Error launching " + ProgramConstants.QRES_EXECUTABLE + ". Please check that your anti-virus isn't blocking the CnCNet Client. " + "You can also try running the client as an administrator." + Environment.NewLine + Environment.NewLine + "You are unable to participate in this match." + Environment.NewLine + Environment.NewLine + "Returned error: " + ex.Message, "Error launching game", MessageBoxButtons.OK); Process_Exited(QResProcess, EventArgs.Empty); return; } if (Environment.ProcessorCount > 1 && SingleCoreAffinity) { QResProcess.ProcessorAffinity = (IntPtr)2; } } else { Process DtaProcess = new Process(); DtaProcess.StartInfo.FileName = gameExecutableName; DtaProcess.StartInfo.UseShellExecute = false; if (!string.IsNullOrEmpty(extraCommandLine)) { DtaProcess.StartInfo.Arguments = " " + extraCommandLine + " -SPAWN"; } else { DtaProcess.StartInfo.Arguments = "-SPAWN"; } DtaProcess.EnableRaisingEvents = true; DtaProcess.Exited += new EventHandler(Process_Exited); try { DtaProcess.Start(); } catch (Exception ex) { Logger.Log("Error launching " + gameExecutableName + ": " + ex.Message); MessageBox.Show("Error launching " + gameExecutableName + ". Please check that your anti-virus isn't blocking the CnCNet Client. " + "You can also try running the client as an administrator." + Environment.NewLine + Environment.NewLine + "You are unable to participate in this match." + Environment.NewLine + Environment.NewLine + "Returned error: " + ex.Message, "Error launching game", MessageBoxButtons.OK); Process_Exited(DtaProcess, EventArgs.Empty); return; } if (Environment.ProcessorCount > 1 && SingleCoreAffinity) { DtaProcess.ProcessorAffinity = (IntPtr)2; } } GameProcessStarted?.Invoke(); Logger.Log("Waiting for qres.dat or " + gameExecutableName + " to exit."); }
/// <summary> /// Reads the OS information data present in version 3 of an NTLM /// type 2 message from the specified BinaryReader. /// </summary> /// <param name="r">The BinaryReader instance to read from.</param> /// <returns>An initialized instance of the OSVersion class.</returns> static OSVersion ReadOSVersion(BinaryReader r) { OSVersion version = new OSVersion(); version.MajorVersion = r.ReadByte(); version.MinorVersion = r.ReadByte(); version.BuildNumber = r.ReadInt16(); // Swallow the reserved 32-bit word. r.ReadInt32(); return version; }
/// <summary> /// Initializes a new instance of the <see cref="Browser"/> class. /// </summary> /// <param name="ua">The value of an HTTP request User-Agent header from the browser to be identified.</param> public Browser(string ua) { Func <Regex, string> getFirstMatch = regex => { var match = regex.Match(ua); if (match != null && match.Groups.Count > 1) { return(match.Groups[1].Value); } return(string.Empty); }; Func <Regex, string> getSecondMatch = regex => { var match = regex.Match(ua); if (match != null && match.Groups.Count > 2) { return(match.Groups[2].Value); } return(string.Empty); }; var iosDevice = getFirstMatch(iOSDeviceRegex); var likeAndroid = LikeAndroidRegex.IsMatch(ua); var android = !likeAndroid && AndroidRegex.IsMatch(ua); var nexusMobile = NexusMobileRegex.IsMatch(ua); var nexusTablet = !nexusMobile && NexusTabletRegex.IsMatch(ua); var chromeOS = ChromeOSRegex.IsMatch(ua); var silk = SilkRegex.IsMatch(ua); var sailfish = SailfishRegex.IsMatch(ua); var tizen = TizenRegex.IsMatch(ua); var webos = WebOSRegex.IsMatch(ua); var windowsPhone = WindowsPhoneRegex.IsMatch(ua); var samsungBrowser = SamsungBrowserRegex.IsMatch(ua); var windows = !windowsPhone && WindowsRegex.IsMatch(ua); var mac = !iosDevice.IsTruthy() && !silk && MacRegex.IsMatch(ua); var linux = !android && !sailfish && !tizen && !webos && LinuxRegex.IsMatch(ua); var edgeVersion = getFirstMatch(EdgeVersionRegex); var versionIdentifier = getFirstMatch(VersionIdentifierRegex); var tablet = TabletRegex.IsMatch(ua) && !TabletPCRegex.IsMatch(ua); var mobile = !tablet && MobileRegex.IsMatch(ua); var xbox = XboxRegex.IsMatch(ua); if (OldOperaRegex.IsMatch(ua)) { Name = "Opera"; Opera = true; Version = versionIdentifier.NullIfFalsy() ?? getFirstMatch(OldOperaVersionRegex); } else if (NewOperaRegex.IsMatch(ua)) { Name = "Opera"; Opera = true; Version = getFirstMatch(NewOperaVersionRegex).NullIfFalsy() ?? versionIdentifier; } else if (SamsungBrowserRegex.IsMatch(ua)) { Name = "Samsung Internet for Android"; SamsungBrowser = true; Version = versionIdentifier.NullIfFalsy() ?? getFirstMatch(SamsungBrowserVersionRegex); } else if (CoastRegex.IsMatch(ua)) { Name = "Opera Coast"; Coast = true; Version = versionIdentifier.NullIfFalsy() ?? getFirstMatch(CoastVersionRegex); } else if (YandexBrowserRegex.IsMatch(ua)) { Name = "Yandex Browser"; YandexBrowser = true; Version = versionIdentifier.NullIfFalsy() ?? getFirstMatch(YandexBrowserVersionRegex); } else if (UcBrowserRegex.IsMatch(ua)) { Name = "UC Browser"; UcBrowser = true; Version = getFirstMatch(UcBrowserVersionRegex); } else if (MaxthonRegex.IsMatch(ua)) { Name = "Maxthon"; Maxthon = true; Version = getFirstMatch(MaxthonVersionRegex); } else if (EpiphanyRegex.IsMatch(ua)) { Name = "Epiphany"; Epiphany = true; Version = getFirstMatch(EpiphanyVersionRegex); } else if (PuffinRegex.IsMatch(ua)) { Name = "Puffin"; Puffin = true; Version = getFirstMatch(PuffinVersionRegex); } else if (SleipnirRegex.IsMatch(ua)) { Name = "Sleipnir"; Sleipnir = true; Version = getFirstMatch(SleipnirVersionRegex); } else if (KMeleonRegex.IsMatch(ua)) { Name = "K-Meleon"; KMeleon = true; Version = getFirstMatch(KMeleonVersionRegex); } else if (windowsPhone) { Name = "Windows Phone"; WindowsPhone = true; if (edgeVersion.IsTruthy()) { MsEdge = true; Version = edgeVersion; } else { MsIE = true; Version = getFirstMatch(IEMobileVersionRegex); } } else if (InternetExplorerRegex.IsMatch(ua)) { Name = "Internet Explorer"; MsIE = true; Version = getFirstMatch(InternetExplorerVersionRegex); } else if (chromeOS) { Name = "Chrome"; ChromeOS = true; ChromeBook = true; Chrome = true; Version = getFirstMatch(ChromeOSVersionRegex); } else if (EdgeRegex.IsMatch(ua)) { Name = "Microsoft Edge"; MsEdge = true; Version = edgeVersion; } else if (VivaldiRegex.IsMatch(ua)) { Name = "Vivaldi"; Vivaldi = true; Version = getFirstMatch(VivaldiVersionRegex).NullIfFalsy() ?? versionIdentifier; } else if (sailfish) { Name = "Sailfish"; Sailfish = true; Version = getFirstMatch(SailfishVersionRegex); } else if (SeaMonkeyRegex.IsMatch(ua)) { Name = "SeaMonkey"; SeaMonkey = true; Version = getFirstMatch(SeaMonkeyVersionRegex); } else if (FirefoxRegex.IsMatch(ua)) { Name = "Firefox"; Firefox = true; Version = getFirstMatch(FirefoxVersionRegex); if (FirefoxOSRegex.IsMatch(ua)) { FirefoxOS = true; } } else if (silk) { Name = "Amazon Silk"; Silk = true; Version = getFirstMatch(SilkVersionRegex); } else if (PhantomJsRegex.IsMatch(ua)) { Name = "PhantomJS"; Phantom = true; Version = getFirstMatch(PhantomJsVersionRegex); } else if (SlimerJsRegex.IsMatch(ua)) { Name = "SlimerJS"; Slimer = true; Version = getFirstMatch(SlimerJsVersionRegex); } else if (BlackberryRegex.IsMatch(ua) || RimRegex.IsMatch(ua)) { Name = "Blackberry"; Blackberry = true; Version = versionIdentifier.NullIfFalsy() ?? getFirstMatch(BlackberryVersionRegex); } else if (webos) { Name = "WebOS"; WebOS = true; Version = versionIdentifier.NullIfFalsy() ?? getFirstMatch(WebOSVersionRegex); if (TouchPadRegex.IsMatch(ua)) { TouchPad = true; } } else if (BadaRegex.IsMatch(ua)) { Name = "Bada"; Bada = true; Version = getFirstMatch(BadaVersionRegex); } else if (tizen) { Name = "Tizen"; Tizen = true; Version = getFirstMatch(TizenVersionRegex).NullIfFalsy() ?? versionIdentifier; } else if (QupZillaRegex.IsMatch(ua)) { Name = "QupZilla"; QupZilla = true; Version = getFirstMatch(QupZillaVersionRegex).NullIfFalsy() ?? versionIdentifier; } else if (ChromiumRegex.IsMatch(ua)) { Name = "Chromium"; Chromium = true; Version = getFirstMatch(ChromiumVersionRegex).NullIfFalsy() ?? versionIdentifier; } else if (ChromeRegex.IsMatch(ua)) { Name = "Chrome"; Chrome = true; Version = getFirstMatch(ChromeVersionRegex); } else if (android) { Name = "Android"; Version = versionIdentifier; } else if (SafariRegex.IsMatch(ua)) { Name = "Safari"; Safari = true; if (versionIdentifier.IsTruthy()) { Version = versionIdentifier; } } else if (iosDevice.IsTruthy()) { Name = iosDevice.Equals("iphone", StringComparison.OrdinalIgnoreCase) ? "iPhone" : iosDevice.Equals("ipad", StringComparison.OrdinalIgnoreCase) ? "iPad" : "iPod"; if (versionIdentifier.IsTruthy()) { Version = versionIdentifier; } } else if (GooglebotRegex.IsMatch(ua)) { Name = "Googlebot"; Googlebot = true; Version = getFirstMatch(GooglebotVersionRegex).NullIfFalsy() ?? versionIdentifier; } else { Name = getFirstMatch(UnknownRegex); Version = getSecondMatch(UnknownRegex); } if (!MsEdge && WebkitRegex.IsMatch(ua)) { if (BlinkRegex.IsMatch(ua)) { Name = Name.NullIfFalsy() ?? "Blink"; Blink = true; } else { Name = Name.NullIfFalsy() ?? "Webkit"; Webkit = true; } if (!Version.IsTruthy() && versionIdentifier.IsTruthy()) { Version = versionIdentifier; } } else if (!Opera && GeckoRegex.IsMatch(ua)) { Name = Name.NullIfFalsy() ?? "Gecko"; Gecko = true; Version = Version.NullIfFalsy() ?? getFirstMatch(GeckoVersionRegex); } if (!WindowsPhone && !MsEdge && (android || Silk)) { Android = true; } else if (!WindowsPhone && !MsEdge && iosDevice.IsTruthy()) { if (iosDevice.Equals("iphone", StringComparison.OrdinalIgnoreCase)) { iPhone = true; } else if (iosDevice.Equals("ipad", StringComparison.OrdinalIgnoreCase)) { iPad = true; } else { iPod = true; } iOS = true; } else if (mac) { Mac = true; } else if (xbox) { Xbox = true; } else if (windows) { Windows = true; } else if (linux) { Linux = true; } var osVersion = string.Empty; if (Windows) { osVersion = getFirstMatch(WindowsOSVersionRegex); if (osVersion == "NT") { osVersion = "NT"; } else if (osVersion == "XP") { osVersion = "XP"; } else if (osVersion == "NT 5.0") { osVersion = "2000"; } else if (osVersion == "NT 5.1") { osVersion = "XP"; } else if (osVersion == "NT 5.2") { osVersion = "2003"; } else if (osVersion == "NT 6.0") { osVersion = "Vista"; } else if (osVersion == "NT 6.1") { osVersion = "7"; } else if (osVersion == "NT 6.2") { osVersion = "8"; } else if (osVersion == "NT 6.3") { osVersion = "8.1"; } else if (osVersion == "NT 10.0") { osVersion = "10"; } else { osVersion = null; } } else if (WindowsPhone) { osVersion = getFirstMatch(WindowsPhoneOSVersionRegex); } else if (Mac) { osVersion = macOSOSVersionReplaceRegex.Replace(getFirstMatch(macOSOSVersionRegex), "."); } else if (iosDevice.IsTruthy()) { osVersion = getFirstMatch(iOSOSVersionRegex); osVersion = iOSOSVersionReplaceRegex.Replace(osVersion, "."); } else if (android) { osVersion = getFirstMatch(AndroidOSVersionRegex); } else if (WebOS) { osVersion = getFirstMatch(WebOSOSVersionRegex); } else if (Blackberry) { osVersion = getFirstMatch(BlackberryOSVersionRegex); } else if (Bada) { osVersion = getFirstMatch(BadaOSVersionRegex); } else if (Tizen) { osVersion = getFirstMatch(TizenOSVersionRegex); } if (osVersion.IsTruthy()) { OSVersion = osVersion; } var osMajorVersion = Windows ? null : osVersion.Split('.')[0].CoerceToInteger(); if (tablet || nexusTablet || iosDevice.Equals("ipad", StringComparison.OrdinalIgnoreCase) || (android && (osMajorVersion == 3 || (osMajorVersion >= 4 && !mobile))) || Silk) { Tablet = true; } else if (mobile || iosDevice.Equals("iphone", StringComparison.OrdinalIgnoreCase) || iosDevice.Equals("ipod", StringComparison.OrdinalIgnoreCase) || android || nexusMobile || Blackberry || WebOS || Bada) { Mobile = true; } var versionFloat = Version.CoerceToFloat(); if (MsEdge || (MsIE && versionFloat >= 10) || (YandexBrowser && versionFloat >= 15) || (Vivaldi && versionFloat >= 1.0) || (Chrome && versionFloat >= 20) || (SamsungBrowser && versionFloat >= 4) || (Firefox && versionFloat >= 20) || (Safari && versionFloat >= 6) || (Opera && versionFloat >= 10.0) || (iOS && OSVersion.IsTruthy() && int.Parse(OSVersion.Split('.')[0]) >= 6) || (Blackberry && versionFloat >= 10.1) || (Chromium && versionFloat >= 20)) { A = true; } else if ((MsIE && versionFloat < 10) || (Chrome && versionFloat < 20) || (Firefox && versionFloat < 20.0) || (Safari && versionFloat < 6) || (Opera && versionFloat < 10.0) || (iOS && OSVersion.IsTruthy() && int.Parse(OSVersion.Split('.')[0]) < 6) || (Chromium && versionFloat < 20)) { C = true; } else { X = true; } }
/// <summary> /// Private constructor. /// </summary> private Type2Message() { TargetInformation = new Type2TargetInformation(); OSVersion = new OSVersion(); }
public static bool IsOsVersionGreaterThan(OSVersion version) { // We can determine that the OS version is greater than the specified version by checking for // the presence of the Universal contract corresonding to the next version. return(ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", (ushort)(version + 1))); }
public void EnsureSetEnvironmentProviderThrowsException() { Action setEnvironmentProvider = () => OSVersion.SetEnvironmentProvider(null); Assert.ThrowsException <ArgumentNullException>(setEnvironmentProvider); }
/// <summary> /// Adds a set of object definitions to the schema. The format of the schema /// is a sequence of lines where objects are separated by empty lines. /// Each line of an object definition is a pair of an attribute display name and an /// attribute value, separated by ':'. Takes care of "bootstrapping" the contents of /// the schema, resolving cyclic dependencies between attribute definitions and objects. /// </summary> /// <param name="schema">The schema, represented as explained above.</param> /// <param name="valueSubstitution">A substitution of strings which should be applied to each value in the /// schema. For example, may map '<rootdomaindn>' as used in schemas to represent the root name of the /// current DC to an actual value</param> /// <param name="serverVersion">Specify the OS version of the server</param> /// <returns>Result of the Load Schema method.</returns> public ModelResult LoadSchema(IEnumerable <string> schema, Map <string, string> valueSubstitution, OSVersion serverVersion) { SequenceContainer <ModelObject> newObjects = new SequenceContainer <ModelObject>(); UnresolvedSyntax unresolvedSyntax = new UnresolvedSyntax(); #region Pass 1: read in objects resolving only builtin attributes // We need this phase for bootstrapping, as we don't have the // attributes available which are used in the objects. Thus // in this phase, we just parse attribute values of a certain set // of builting attributes which are required to get attribute syntax // definitions. InitializeBuiltinAttributes(); ModelObject tempobj = null; ModelObject obj = null; foreach (string rawLine in schema) { string line = (rawLine == null)?null:rawLine.Trim(); if (String.IsNullOrEmpty(line)) { // Object ends here if (obj != null) { if (obj[StandardNames.attributeID] == null && obj[StandardNames.governsId] == null) { if (obj.attributes.Count == 1) { // If the server is Windows 2000 if (serverVersion == OSVersion.WinSvr2000) { string attr = obj.attributes.Keys.ElementAt(0); if (tempobj.attributes.Keys.Contains(attr)) { tempobj.attributes.Keys.Remove(attr); tempobj.attributes.Add(obj.attributes.ElementAt(0)); } else { tempobj.attributes.Add(obj.attributes.ElementAt(0)); } newObjects.RemoveAt(newObjects.Count - 1); newObjects.Add(tempobj); } } else { Checks.Fail("attributeId/governsId is mandatory for each object {0}.", obj[StandardNames.cn]); } } else if (obj[StandardNames.attributeID] != null) { AddAttribute(obj); newObjects.Add(obj); } else if (obj[StandardNames.governsId] != null) { // This is a class definition. Fill in class map. AddClass(obj); newObjects.Add(obj); } tempobj = obj; obj = null; } } else { if (obj == null) { obj = new ModelObject(); } obj.dc = this; string attr, valueString; string[] splits = line.Split(new char[] { ':' }, 2); if (splits == null || splits.Length != 2) { Checks.Fail("invalid schema line '{0}'", line); continue; } attr = splits[0].Trim().ToLower(); valueString = Substitute(valueSubstitution, splits[1].Trim()); AttributeContext parsingContext; if (!builtinAttributeSyntax.TryGetValue(attr, out parsingContext)) { parsingContext = new AttributeContext(this, attr, unresolvedSyntax); } obj[attr] = parsingContext.Parse(valueString); } } #endregion #region Pass 2: resolve syntax of all new objects // As we have now attribute definitions which map to the syntax, we can parse // All values in the new objects. foreach (ModelObject newObj in newObjects) { foreach (string attr in newObj.attributes.Keys) { AttributeContext parsingContext = GetAttributeContext(attr); Value value = newObj[attr]; if (value.Syntax is UnresolvedSyntax) { newObj[attr] = parsingContext.Parse((string)value); } else { Checks.IsTrue( parsingContext.syntax == value.Syntax, "bultin syntax assignment of '{0}' must match syntax declared in schema", attr); } } } #endregion #region Pass 3: add objects // Now all definitions are complete. Add them to schema replica root. foreach (ModelObject newObj in newObjects) { AddChild(schemaReplica.root, newObj); } #endregion #region Pass 4: check consistency // The tree is finally setup. Now check for consistency Consistency.Check(newObjects.ToSequence()); #endregion if (Checks.HasDiagnostics) { return(new ModelResult(ResultCode.ConstraintViolation, Checks.GetAndClearLog(), Checks.GetAndClearDiagnostics())); } else { //return Result.Success; ModelResult tempRes = new ModelResult(ResultCode.Success); tempRes.logMessage = Checks.GetAndClearLog(); return(tempRes); } }
/// <summary> /// Creates a new instance of an NTLM type 3 message using the specified /// values. /// </summary> /// <param name="username">The Windows account name to use for /// authentication.</param> /// <param name="password">The Windows account password to use for /// authentication.</param> /// <param name="challenge">The challenge received from the server as part /// of the NTLM type 2 message.</param> /// <param name="useUnicode">Set this to true, if Unicode encoding has been /// negotiated between client and server.</param> /// <param name="workstation">The client's workstation name.</param> /// <param name="ntlmv2">Set to true to send an NTLMv2 challenge /// response.</param> /// <param name="targetName">The authentication realm in which the /// authenticating account has membership.</param> /// <param name="targetInformation">The target information block from /// the NTLM type 2 message.</param> /// <remarks>The target name is a domain name for domain accounts, or /// a server name for local machine accounts.</remarks> /// <exception cref="ArgumentNullException">Thrown if the username, password /// or challenge parameters are null.</exception> public Type3Message(string username, string password, byte[] challenge, bool useUnicode, string workstation, bool ntlmv2 = false, string targetName = null, byte[] targetInformation = null) { // Preconditions. username.ThrowIfNull("username"); password.ThrowIfNull("password"); challenge.ThrowIfNull("challenge"); encoding = useUnicode ? Encoding.Unicode : Encoding.ASCII; // Setup the security buffers contents. this.username = encoding.GetBytes(username); this.workstation = encoding.GetBytes(workstation); this.targetName = String.IsNullOrEmpty(targetName) ? new byte[0] : encoding.GetBytes(targetName); // The session key is not relevant to authentication. this.sessionKey = new byte[0]; // Compute the actual challenge response data. if (!ntlmv2) { LMResponse = Responses.ComputeLMResponse(challenge, password); NtlmResponse = Responses.ComputeNtlmResponse(challenge, password); } else { byte[] cnonce = GetCNonce(); LMResponse = Responses.ComputeLMv2Response(targetName, username, password, challenge, cnonce); NtlmResponse = Responses.ComputeNtlmv2Response(targetName, username, password, targetInformation, challenge, cnonce); } // We spoof an OS version of Windows 7 Build 7601. OSVersion = new OSVersion(6, 1, 7601); }
public void StopsParsingAtFirstInvalidCharacter() { Assert.That(OSVersion.Parse("12.2 .4") == new OSVersion(12, 2)); }
public SDL2_GamePlatform(Game game) : base(game, SDL.SDL_GetPlatform()) { /* SDL2 might complain if an OS that uses SDL_main has not actually * used SDL_main by the time you initialize SDL2. * The only platform that is affected is Windows, but we can skip * their WinMain. This was only added to prevent iOS from exploding. * -flibit */ SDL.SDL_SetMainReady(); // This _should_ be the first real SDL call we make... SDL.SDL_Init( SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_JOYSTICK | SDL.SDL_INIT_GAMECONTROLLER | SDL.SDL_INIT_HAPTIC ); // Set any hints to match XNA4 behavior... string hint = SDL.SDL_GetHint(SDL.SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS); if (String.IsNullOrEmpty(hint)) { SDL.SDL_SetHint( SDL.SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1" ); } // If available, load the SDL_GameControllerDB string mappingsDB = Path.Combine( TitleContainer.Location, "gamecontrollerdb.txt" ); if (File.Exists(mappingsDB)) { SDL.SDL_GameControllerAddMappingsFromFile( mappingsDB ); } // Set and initialize the SDL2 window bool forceES2 = Environment.GetEnvironmentVariable( "FNA_OPENGL_FORCE_ES2" ) == "1"; Window = new SDL2_GameWindow( forceES2 || OSVersion.Equals("Emscripten") || OSVersion.Equals("Android") || OSVersion.Equals("iOS") ); // Create the DisplayMode list displayIndex = SDL.SDL_GetWindowDisplayIndex( Window.Handle ); INTERNAL_GenerateDisplayModes(); // Disable the screensaver. SDL.SDL_DisableScreenSaver(); // We hide the mouse cursor by default. if (IsMouseVisible) { IsMouseVisible = false; } else { /* Since IsMouseVisible is already false, OnMouseVisibleChanged * will NOT be called! So we get to do it ourselves. * -flibit */ SDL.SDL_ShowCursor(0); } // OSX has some fancy fullscreen features, let's use them! if (OSVersion.Equals("Mac OS X")) { hint = SDL.SDL_GetHint(SDL.SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES); INTERNAL_useFullscreenSpaces = (String.IsNullOrEmpty(hint) || hint.Equals("1")); } else { INTERNAL_useFullscreenSpaces = false; } // Initialize Active Key List keys = new List <Keys>(); // Setup Text Input Control Character Arrays (Only 4 control keys supported at this time) INTERNAL_TextInputControlDown = new bool[4]; INTERNAL_TextInputControlRepeat = new int[4]; // Assume we will have focus. IsActive = true; // Ready to run the loop! INTERNAL_runApplication = true; #if WIIU_GAMEPAD wiiuStream = DRC.drc_new_streamer(); if (wiiuStream == IntPtr.Zero) { System.Console.WriteLine("Failed to alloc GamePad stream!"); return; } if (DRC.drc_start_streamer(wiiuStream) < 1) // ??? { System.Console.WriteLine("Failed to start GamePad stream!"); DRC.drc_delete_streamer(wiiuStream); wiiuStream = IntPtr.Zero; return; } DRC.drc_enable_system_input_feeder(wiiuStream); Rectangle bounds = Window.ClientBounds; wiiuPixelData = new byte[bounds.Width * bounds.Height * 4]; #endif }
public OSData(OSType type, OSVersion version) { OSType = type; OSVersion = version; }
internal static bool IsAtLeast(OSVersion version) { return(IsAtLeast(version, 0)); }
static bool IsAtLeast(OSVersion version, byte servicePack) { Fx.Assert(version != OSVersion.Unknown, "Unknown OS"); if (servicePack == 0) { return version <= currentVersion; } // If a SP value is provided and we have the same OS version, compare SP values if (version == currentVersion) { return servicePack <= currentServicePack; } return version < currentVersion; }
private void LoadWindowsInfo() { #if NETCOREAPP //var machine_guid = ""; //var reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Cryptography"); //if (reg != null) machine_guid = reg.GetValue("MachineGuid") + ""; //if (machine_guid.IsNullOrEmpty()) //{ // reg = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); // if (reg != null) machine_guid = reg.GetValue("MachineGuid") + ""; //} //var reg2 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"); //if (reg2 != null) //{ // OSName = reg2.GetValue("ProductName") + ""; // //OSVersion = reg2.GetValue("CurrentBuild") + ""; //} //Processor = GetInfo("Win32_Processor", "Name"); ////CpuID = GetInfo("Win32_Processor", "ProcessorId"); //var uuid = GetInfo("Win32_ComputerSystemProduct", "UUID"); //Product = GetInfo("Win32_ComputerSystemProduct", "Name"); //DiskID = GetInfo("Win32_DiskDrive", "SerialNumber"); //// UUID取不到时返回 FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF //if (!uuid.IsNullOrEmpty() && !uuid.EqualIgnoreCase("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF", "00000000-0000-0000-0000-000000000000")) // UUID = uuid; ////// 可能因WMI导致读取UUID失败 ////if (UUID.IsNullOrEmpty()) ////{ //// var reg3 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"); //// if (reg3 != null) UUID = reg3.GetValue("ProductId") + ""; ////} //if (!machine_guid.IsNullOrEmpty()) Guid = machine_guid; #endif var str = ""; var os = ReadWmic("os", "Caption", "Version"); if (os != null) { if (os.TryGetValue("Caption", out str)) { OSName = str.TrimStart("Microsoft").Trim(); } if (os.TryGetValue("Version", out str)) { OSVersion = str; } } var csproduct = ReadWmic("csproduct", "Name", "UUID"); if (csproduct != null) { if (csproduct.TryGetValue("Name", out str)) { Product = str; } if (csproduct.TryGetValue("UUID", out str)) { UUID = str; } } var disk = ReadWmic("diskdrive", "serialnumber"); if (disk != null) { if (disk.TryGetValue("serialnumber", out str)) { DiskID = str?.Trim(); } } // 不要在刷新里面取CPU负载,因为运行wmic会导致CPU负载很不准确,影响测量 var cpu = ReadWmic("cpu", "Name", "ProcessorId", "LoadPercentage"); if (cpu != null) { if (cpu.TryGetValue("Name", out str)) { Processor = str; } //if (cpu.TryGetValue("ProcessorId", out str)) CpuID = str; if (cpu.TryGetValue("LoadPercentage", out str)) { CpuRate = (Single)(str.ToDouble() / 100); } } // 从注册表读取 MachineGuid str = Execute("reg", @"query HKLM\SOFTWARE\Microsoft\Cryptography /v MachineGuid"); if (!str.IsNullOrEmpty() && str.Contains("REG_SZ")) { Guid = str.Substring("REG_SZ", null).Trim(); } if (OSName.IsNullOrEmpty()) { OSName = RuntimeInformation.OSDescription.TrimStart("Microsoft").Trim(); } if (OSVersion.IsNullOrEmpty()) { OSVersion = Environment.OSVersion.Version.ToString(); } }
public int CompareTo(ExceptionEvent other) { if (!(OS == null && other.OS == null)) { if (OS == null) { return(-1); } if (other.OS == null) { return(1); } if (!OS.Equals(other.OS)) { return(OS.CompareTo(other.OS)); } } if (!(OSVersion == null && other.OSVersion == null)) { if (OSVersion == null) { return(-1); } if (other.OSVersion == null) { return(1); } if (!OSVersion.Equals(other.OSVersion)) { return(OSVersion.CompareTo(other.OSVersion)); } } if (!(Manufacture == null && other.Manufacture == null)) { if (Manufacture == null) { return(-1); } if (other.Manufacture == null) { return(1); } if (!Manufacture.Equals(other.Manufacture)) { return(Manufacture.CompareTo(other.Manufacture)); } } if (!(Device == null && other.Device == null)) { if (Device == null) { return(-1); } if (other.Device == null) { return(1); } if (!Device.Equals(other.Device)) { return(Device.CompareTo(other.Device)); } } if (!(Resolution == null && other.Resolution == null)) { if (Resolution == null) { return(-1); } if (other.Resolution == null) { return(1); } if (!Resolution.Equals(other.Resolution)) { return(Resolution.CompareTo(other.Resolution)); } } if (!(AppVersion == null && other.AppVersion == null)) { if (AppVersion == null) { return(-1); } if (other.AppVersion == null) { return(1); } if (!AppVersion.Equals(other.AppVersion)) { return(AppVersion.CompareTo(other.AppVersion)); } } if (!(Orientation == null && other.Orientation == null)) { if (Orientation == null) { return(-1); } if (other.Orientation == null) { return(1); } if (!Orientation.Equals(other.Orientation)) { return(Orientation.CompareTo(other.Orientation)); } } if (!(RamCurrent == null && other.RamCurrent == null)) { if (RamCurrent == null) { return(-1); } if (other.RamCurrent == null) { return(1); } if (!RamCurrent.Equals(other.RamCurrent)) { return(RamCurrent.Value.CompareTo(other.RamCurrent.Value)); } } if (!(RamTotal == null && other.RamTotal == null)) { if (RamTotal == null) { return(-1); } if (other.RamTotal == null) { return(1); } if (!RamTotal.Equals(other.RamTotal)) { return(RamTotal.Value.CompareTo(other.RamTotal.Value)); } } if (!Online.Equals(other.Online)) { return(Online.CompareTo(other.Online)); } if (!(Name == null && other.Name == null)) { if (Name == null) { return(-1); } if (other.Name == null) { return(1); } if (!Name.Equals(other.Name)) { return(Name.CompareTo(other.Name)); } } if (!(Error == null && other.Error == null)) { if (Error == null) { return(-1); } if (other.Error == null) { return(1); } if (!Error.Equals(other.Error)) { return(Error.CompareTo(other.Error)); } } if (!NonFatal.Equals(other.NonFatal)) { return(NonFatal.CompareTo(other.NonFatal)); } if (!(Logs == null && other.Logs == null)) { if (Logs == null) { return(-1); } if (other.Logs == null) { return(1); } if (!Logs.Equals(other.Logs)) { return(Logs.CompareTo(other.Logs)); } } if (!Run.Equals(other.Run)) { return(Run.CompareTo(other.Run)); } if (!(OS == null && other.OS == null)) { if (OS == null) { return(-1); } if (other.OS == null) { return(1); } if (!OS.Equals(other.OS)) { return(OS.CompareTo(other.OS)); } } if (!(Custom == null && other.Custom == null)) { if (Custom == null) { return(-1); } if (other.Custom == null) { return(1); } if (!Custom.Count.Equals(other.Custom.Count)) { return(Custom.Count.CompareTo(other.Custom.Count)); } foreach (var a in Custom.Keys) { if (!other.Custom.ContainsKey(a)) { return(-1); } if (!Custom[a].Equals(other.Custom[a])) { return(Custom[a].CompareTo(other.Custom[a])); } } } return(0); }
/// <summary>刷新</summary> public void Init() { var machine_guid = ""; #if __CORE__ var osv = Environment.OSVersion; if (OSVersion.IsNullOrEmpty()) { OSVersion = osv.Version + ""; } if (OSName.IsNullOrEmpty()) { OSName = (osv + "").TrimStart("Microsoft").TrimEnd(OSVersion).Trim(); } if (Guid.IsNullOrEmpty()) { Guid = ""; } if (Runtime.Windows) { var str = ""; var os = ReadWmic("os", "Caption", "Version"); if (os != null) { if (os.TryGetValue("Caption", out str)) { OSName = str.TrimStart("Microsoft").Trim(); } if (os.TryGetValue("Version", out str)) { OSVersion = str; } } var csproduct = ReadWmic("csproduct", "Name", "UUID"); if (csproduct != null) { if (csproduct.TryGetValue("Name", out str)) { Product = str; } if (csproduct.TryGetValue("UUID", out str)) { UUID = str; } } // 不要在刷新里面取CPU负载,因为运行wmic会导致CPU负载很不准确,影响测量 var cpu = ReadWmic("cpu", "Name", "ProcessorId", "LoadPercentage"); if (cpu != null) { if (cpu.TryGetValue("Name", out str)) { Processor = str; } if (cpu.TryGetValue("ProcessorId", out str)) { CpuID = str; } if (cpu.TryGetValue("LoadPercentage", out str)) { CpuRate = (Single)(str.ToDouble() / 100); } } // 从注册表读取 MachineGuid str = Execute("reg", @"query HKLM\SOFTWARE\Microsoft\Cryptography /v MachineGuid"); if (!str.IsNullOrEmpty() && str.Contains("REG_SZ")) { Guid = str.Substring("REG_SZ", null).Trim(); } } // 特别识别Linux发行版 else if (Runtime.Linux) { var str = GetLinuxName(); if (!str.IsNullOrEmpty()) { OSName = str; } // 树莓派优先 Model var dic = ReadInfo("/proc/cpuinfo"); if (dic != null) { if (dic.TryGetValue("Model", out str) || dic.TryGetValue("Hardware", out str) || dic.TryGetValue("cpu model", out str) || dic.TryGetValue("model name", out str)) { Processor = str; } if (dic.TryGetValue("Serial", out str)) { CpuID = str; } } var mid = "/etc/machine-id"; if (!File.Exists(mid)) { mid = "/var/lib/dbus/machine-id"; } if (File.Exists(mid)) { Guid = File.ReadAllText(mid).Trim(); } var file = "/sys/class/dmi/id/product_uuid"; if (File.Exists(file)) { UUID = File.ReadAllText(file).Trim(); } file = "/sys/class/dmi/id/product_name"; if (File.Exists(file)) { Product = File.ReadAllText(file).Trim(); } var dmi = Execute("dmidecode")?.SplitAsDictionary(":", "\n"); if (dmi != null) { if (dmi.TryGetValue("ID", out str)) { CpuID = str.Replace(" ", null); } if (dmi.TryGetValue("UUID", out str)) { UUID = str; } if (dmi.TryGetValue("Product Name", out str)) { Product = str; } //if (TryFind(dmi, new[] { "Serial Number" }, out str)) Guid = str; } } #else // 性能计数器的初始化非常耗时 Task.Factory.StartNew(() => { _cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total") { MachineName = "." }; _cpuCounter.NextValue(); }); var reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Cryptography"); if (reg != null) { machine_guid = reg.GetValue("MachineGuid") + ""; } if (machine_guid.IsNullOrEmpty()) { reg = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); if (reg != null) { machine_guid = reg.GetValue("MachineGuid") + ""; } } var ci = new ComputerInfo(); OSName = ci.OSFullName.TrimStart("Microsoft").Trim(); OSVersion = ci.OSVersion; Memory = ci.TotalPhysicalMemory; _cinfo = ci; Processor = GetInfo("Win32_Processor", "Name"); CpuID = GetInfo("Win32_Processor", "ProcessorId"); UUID = GetInfo("Win32_ComputerSystemProduct", "UUID"); Product = GetInfo("Win32_ComputerSystemProduct", "Name"); //// 读取主板温度,不太准。标准方案是ring0通过IOPort读取CPU温度,太难在基础类库实现 //var str = GetInfo("MSAcpi_ThermalZoneTemperature", "CurrentTemperature"); //if (!str.IsNullOrEmpty()) Temperature = (str.ToDouble() - 2732) / 10.0; #endif if (!machine_guid.IsNullOrEmpty()) { Guid = machine_guid; } // window+netcore 不方便读取注册表,随机生成一个guid,借助文件缓存确保其不变 if (Guid.IsNullOrEmpty()) { Guid = "0-" + System.Guid.NewGuid().ToString(); } if (UUID.IsNullOrEmpty()) { UUID = "0-" + System.Guid.NewGuid().ToString(); } Refresh(); }
static OSVersion GetXcodeVersion() { return(OSVersion.Parse(GetXcodeApplicationName())); }
/// <summary> /// Reads a schema from a set of XML files. Returns an enumeration of lines, where each line /// represents an attribute definition with ':' a separator between attribute name and attribute value, /// and where the empty line indicates the end of an object definition. /// </summary> /// <param name="includeFilePatterns">Included file folders</param> /// <param name="excludeFiles">Excluded file folder</param> /// <param name="isProtocolXMLApplied">Set this to true if new protocol XML applied</param> /// <param name="serverVersion">Specify the OS version of the server</param> /// <returns>Returns string array.</returns> public static string[] ReadSchema(string[] includeFilePatterns, string[] excludeFiles, bool isProtocolXMLApplied, OSVersion serverVersion) { bool criticalOnly = false; List <string> result = new List <string>(); Checks.MakeLog("Start loading of XML data..."); if (isProtocolXMLApplied == true) { foreach (string file in Expand(includeFilePatterns, excludeFiles)) { if (serverVersion >= OSVersion.Win2016) { #region raw XMLs used after Windows Server 2016 are changed to openXML type using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(file, false)) { XNamespace w = @"http://schemas.openxmlformats.org/wordprocessingml/2006/main"; XNamespace xml = @"http://www.w3.org/XML/1998/namespace"; var items = wdDoc.MainDocumentPart.Document.Body; XAttribute currentStyle = null; XAttribute previousStyle = null; string previousLine = ""; foreach (var item in items) { if (item is Paragraph) { XElement xe = XElement.Parse(item.OuterXml); currentStyle = xe.Descendants(w + "pPr").Descendants(w + "pStyle").Attributes(w + "val").FirstOrDefault(); if (currentStyle != null && currentStyle.Value.Equals("Code")) { var texts = xe.Descendants(w + "t"); string currentLine = ""; foreach (var text in texts) { currentLine += text.Value; } if (currentLine.Contains("<SchemaNCDN>")) { currentLine = currentLine.Replace("<SchemaNCDN>", "CN=Schema,CN=Configuration,<RootDomainDN>"); } var testsAttr = texts.Attributes(xml + "space").FirstOrDefault(); if (testsAttr != null && testsAttr.Value.Equals("preserve")) { if (currentLine.StartsWith(" ")) { previousLine += currentLine.TrimStart(); } else { if (!string.IsNullOrEmpty(previousLine)) { result.Add(previousLine); } previousLine = currentLine; } } else { if (!string.IsNullOrEmpty(previousLine)) { result.Add(previousLine); } previousLine = currentLine; } } else if (previousStyle != null && previousStyle.Value.Equals("Code")) { if (!string.IsNullOrEmpty(previousLine)) { // If the code does not end with an empty string, add one to seperate it with other schema objects in the result list. result.Add(previousLine); result.Add(string.Empty); } else { // There exists in TD when code already ends up with an empty string. result.Add(previousLine); } previousLine = ""; } previousStyle = currentStyle; } } } #endregion } else { #region raw XMLs used before Windows Server 2012 R2 System.IO.StreamReader sr = new StreamReader(file); string tmp = sr.ReadToEnd(); sr.Close(); //Get data from <snippet> element int index = tmp.IndexOf("</snippet>"); if (serverVersion == OSVersion.WinSvr2008R2) { if (tmp.IndexOf("windows_unreleased") > -1) { if (tmp.IndexOf("</snippet>", tmp.IndexOf("windows_unreleased")) > -1) { string temper = tmp.Substring(tmp.IndexOf("windows_unreleased")); if (temper.ToLower().Contains("cn:") && temper.ToLower().Contains("ldapdisplayname:")) { tmp = temper; index = tmp.IndexOf("</snippet>"); } } } } if (index > -1) { index = tmp.LastIndexOf(">", index) + 1; string sp = tmp.Substring(index, tmp.IndexOf("</snippet>") - index); index = tmp.IndexOf("<snippet"); string spTag = tmp.Substring(index, tmp.IndexOf(">", index) - index + 1); List <string> autoText = new List <string>(); index = 0; //Get platform information while (index < tmp.Length) { int begin = tmp.IndexOf("<auto_text>", index); if (begin > -1) { int end = tmp.IndexOf("</auto_text>", index); if (begin > -1 && end > -1 && end > begin) { string newAdd = tmp.Substring(begin + "<auto_text>".Length, end - begin - "<auto_text>".Length); bool toAdd = true; foreach (string cont in autoText) { if (cont == newAdd) { toAdd = false; break; } } if (toAdd == true) { autoText.Add(newAdd); } index = end + "</auto_text>".Length; } } else { break; } } List <string> implementationSpecific = new List <string>(); foreach (string tagTla in autoText) { if (!tagTla.Equals("windows") && !tagTla.Equals("exchange_server")) { implementationSpecific.Add(tagTla); } } List <string> lines = new List <string>(); bool isCritical = false; string value = sp; value = value.Replace(" ", String.Empty); //Modified. For new XML files, lines are separated by \n, not \n\r string[] splitTag = { "\n" }; string[] tmpValue = value.Split(splitTag, StringSplitOptions.RemoveEmptyEntries); string parsedValue = String.Empty; for (int k = 0; k < tmpValue.Length; k++) { if (!tmpValue[k].Contains(":") || tmpValue[k].IndexOf(":") == 1) { parsedValue = parsedValue + tmpValue[k]; } else { parsedValue = parsedValue + "\r\n" + tmpValue[k]; } } if (parsedValue.Contains("<RootDomainDN>")) { parsedValue = parsedValue.Replace("<RootDomainDN>", "<RootDomainDN>"); } else if (parsedValue.Contains("<SchemaNCDN>")) { parsedValue = parsedValue.Replace("<SchemaNCDN>", "CN=Schema,CN=Configuration,<RootDomainDN>"); } string[] splitTag2 = { "\r\n" }; tmpValue = parsedValue.Split(splitTag2, StringSplitOptions.RemoveEmptyEntries); string savedString = String.Empty; foreach (string line in tmpValue) { if (line.Length > 0) { if (line[line.Length - 1] != ':') { lines.Add(savedString + line); if (criticalOnly && !isCritical) { isCritical = CheckCritical(line); } savedString = String.Empty; } else { savedString = line; } } } if (!criticalOnly || isCritical) { result.AddRange(lines); result.Add(String.Empty); //separate records by an empty element } } #endregion } } } else { foreach (string file in Expand(includeFilePatterns, excludeFiles)) { XmlTextReader reader = new XmlTextReader(file); reader.XmlResolver = null; reader.DtdProcessing = DtdProcessing.Prohibit; XPathDocument doc = new XPathDocument(reader); XPathNavigator node = doc.CreateNavigator(); // The TD XML has no formal tag for representing the object definitions in ADA* and ADSC. // However, it seems that all those definitions are included in an <example> tag which // in turn contains a <snippet> tag with CDATA, and the snippet tag has a type attribute "syntax". // We use this for identifying the object definitions. However, this code may require // changes if the TD XML representation changes, or if it discovered that we include // too many or not enough objects. foreach (XPathNavigator snippet in node.Select("//example/snippet")) { List <string> implementationSpecific = new List <string>(); foreach (XPathNavigator tagTla in node.Select("//p/tla")) { if ( !tagTla.GetAttribute("rid", String.Empty).Equals("windows") && !tagTla.GetAttribute("rid", String.Empty).Equals("exchange_server")) { implementationSpecific.Add(tagTla.GetAttribute("rid", String.Empty)); } } if ( serverVersion != OSVersion.WinSvr2008R2 && (implementationSpecific.Count == 1 && (implementationSpecific.Contains("windows_server_7")))) { continue; } List <string> lines = new List <string>(); bool isCritical = false; string value = snippet.Value; int i = 0; while (i >= 0) { string line = ExtractLine(value, ref i).Trim(); while (i >= 0 && Char.IsWhiteSpace(value[i])) { line += ExtractLine(value, ref i).Trim(); } if (line != String.Empty) { lines.Add(line); if (criticalOnly && !isCritical) { isCritical = CheckCritical(line); } } } if (!criticalOnly || isCritical) { result.AddRange(lines); result.Add(String.Empty); } } } } Checks.MakeLog("Successfully loaded XML data files..."); return(result.ToArray()); }