private void JobQueue_Load(object sender, EventArgs e) { if (OSInfo.IsWindowsVistaOrNewer) { OSInfo.SetWindowTheme(queueListView.Handle, "explorer", null); } }
private static OSInfo GetOSInfo() { ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem"); var result = new OSInfo(); foreach (ManagementObject os in searcher.Get()) { result.Name = os["Caption"].ToString(); result.Version = Version.Parse(os["Version"].ToString()); result.Architecture = "32 bit"; if (result.Version.Major > 5) { result.Architecture = os["OSArchitecture"].ToString(); } continue; } searcher = new ManagementObjectSearcher("SELECT FreePhysicalMemory, TotalVisibleMemorySize FROM Win32_OperatingSystem"); foreach (ManagementObject os in searcher.Get()) { result.TotalVisibleMemory = long.Parse(os["TotalVisibleMemorySize"].ToString()).KbToGb(); result.TotalFreeMemory = long.Parse(os["FreePhysicalMemory"].ToString()).KbToGb(); } string releaseId = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ReleaseId", "")?.ToString(); if (string.IsNullOrEmpty(releaseId)) { releaseId = "<Unknown>"; } result.Release = releaseId; return(result); }
private void LogTree_Load(object sender, EventArgs e) { if (OSInfo.IsWindowsVistaOrNewer) { OSInfo.SetWindowTheme(treeView.Handle, "explorer", null); } }
private static OSInfo GetOSInfo() { ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem"); var result = new OSInfo(); foreach (ManagementObject os in searcher.Get()) { result.Name = os["Caption"].ToString(); result.Version = Version.Parse(os["Version"].ToString()); result.Architecture = "32 bit"; if (result.Version.Major > 5) { result.Architecture = os["OSArchitecture"].ToString(); } continue; } searcher = new ManagementObjectSearcher("SELECT FreePhysicalMemory, TotalVisibleMemorySize FROM Win32_OperatingSystem"); foreach (ManagementObject os in searcher.Get()) { result.TotalVisibleMemory = long.Parse(os["TotalVisibleMemorySize"].ToString()).KbToGb(); result.TotalFreeMemory = long.Parse(os["FreePhysicalMemory"].ToString()).KbToGb(); } return(result); }
private async Task RegisterApplicationInstance(GrpcConnection availableConnection, CancellationToken token) { if (DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId)) { var instanceDiscoveryService = new InstanceDiscoveryService.InstanceDiscoveryServiceClient(availableConnection.GrpcChannel); var agentUUID = Guid.NewGuid().ToString("N"); var registerTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var hostName = Dns.GetHostName(); var osInfo = new OSInfo { Hostname = hostName, OsName = Environment.OSVersion.ToString(), ProcessNo = Process.GetCurrentProcess().Id }; // todo fix Device not configured //var ipv4s = Dns.GetHostAddresses(hostName); //foreach (var ipAddress in ipv4s.Where(x => x.AddressFamily == AddressFamily.InterNetwork)) // osInfo.Ipv4S.Add(ipAddress.ToString()); var applicationInstance = new ApplicationInstance { ApplicationId = RemoteDownstreamConfig.Agent.ApplicationId, AgentUUID = agentUUID, RegisterTime = registerTime, Osinfo = osInfo }; var retry = 0; var applicationInstanceId = 0; while (retry++ < 5 && DictionaryUtil.IsNull(applicationInstanceId)) { var applicationInstanceMapping = await instanceDiscoveryService.registerInstanceAsync(applicationInstance); applicationInstanceId = applicationInstanceMapping.ApplicationInstanceId; if (!DictionaryUtil.IsNull(applicationInstanceId)) { break; } await Task.Delay(500, token); } if (!DictionaryUtil.IsNull(applicationInstanceId)) { RemoteDownstreamConfig.Agent.ApplicationInstanceId = applicationInstanceId; _logger.Info( $"Register application instance success. [applicationInstanceId] = {applicationInstanceId}"); } else { _logger.Warning( "Register application instance fail. Server response null."); } } }
public CrashReporter(WpfCrashReporter wpfCrashReporter, CrashReportConfirmer crashReportConfirmer, AppSettings appSettings, OSInfo osInfo, ILogger logger) { this._wpfCrashReporter = wpfCrashReporter; this._crashReportConfirmer = crashReportConfirmer; this._appSettings = appSettings; this._osInfo = osInfo; this._logger = logger; }
/// <summary> /// Gets the OS Information From Device. /// </summary> /// <returns></returns> public OSInfo GetOsInfo() { var os = new OSInfo { OsName = "Windows", OsType = "Server", OsVersion = "8.0.1.2353" }; return(os); }
public Role_OSBuild_ViewModel(string roleName, ObservableCollection <OSInfo> osList, ObservableCollection <string> builds) { _RoleName = roleName; _OSList = osList; _buildsList = builds; _SelectedOS = _OSList.Where(e => { return(e.DisplayName.IndexOf("16") == -1); }).FirstOrDefault(); SelectedBuild = BuildsList == null? null :BuildsList.FirstOrDefault(); }
protected override async Task Initializing(CancellationToken token) { var application = new Application { ApplicationCode = AgentConfig.ApplicationCode }; var applicationRegisterService = new ApplicationRegisterService.ApplicationRegisterServiceClient(GrpcChannelManager.Instance.Channel); var applicationId = default(int?); while (!applicationId.HasValue || DictionaryUtil.IsNull(applicationId.Value)) { var applicationMapping = await applicationRegisterService.applicationCodeRegisterAsync(application); applicationId = applicationMapping?.Application?.Value; } RemoteDownstreamConfig.Agent.ApplicationId = applicationId.Value; var instanceDiscoveryService = new InstanceDiscoveryService.InstanceDiscoveryServiceClient(GrpcChannelManager.Instance.Channel); var agentUUID = Guid.NewGuid().ToString().Replace("-", ""); var registerTime = DateTime.UtcNow.GetTimeMillis(); var hostName = Dns.GetHostName(); var osInfo = new OSInfo { Hostname = hostName, OsName = Environment.OSVersion.ToString(), ProcessNo = Process.GetCurrentProcess().Id }; // todo fix Device not configured //var ipv4s = Dns.GetHostAddresses(hostName); //foreach (var ipAddress in ipv4s.Where(x => x.AddressFamily == AddressFamily.InterNetwork)) // osInfo.Ipv4S.Add(ipAddress.ToString()); var applicationInstance = new ApplicationInstance { ApplicationId = applicationId.Value, AgentUUID = agentUUID, RegisterTime = registerTime, Osinfo = osInfo }; var applicationInstanceId = 0; while (DictionaryUtil.IsNull(applicationInstanceId)) { var applicationInstanceMapping = await instanceDiscoveryService.registerInstanceAsync(applicationInstance); applicationInstanceId = applicationInstanceMapping.ApplicationInstanceId; } RemoteDownstreamConfig.Agent.ApplicationInstanceId = applicationInstanceId; }
private async Task RegisterApplicationInstance(GrpcConnection availableConnection, CancellationToken token) { if (!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId) && DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId)) { var instanceDiscoveryService = new InstanceDiscoveryService.InstanceDiscoveryServiceClient(availableConnection.GrpcChannel); var agentUUID = Guid.NewGuid().ToString("N"); var registerTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var hostName = Dns.GetHostName(); var osInfo = new OSInfo { Hostname = hostName, OsName = PlatformInformation.GetOSName(), ProcessNo = Process.GetCurrentProcess().Id }; osInfo.Ipv4S.AddRange(GetIpV4S(hostName)); var applicationInstance = new ApplicationInstance { ApplicationId = RemoteDownstreamConfig.Agent.ApplicationId, AgentUUID = agentUUID, RegisterTime = registerTime, Osinfo = osInfo }; var retry = 0; var applicationInstanceId = 0; while (retry++ < 5 && DictionaryUtil.IsNull(applicationInstanceId)) { var applicationInstanceMapping = await instanceDiscoveryService.registerInstanceAsync(applicationInstance); applicationInstanceId = applicationInstanceMapping.ApplicationInstanceId; if (!DictionaryUtil.IsNull(applicationInstanceId)) { break; } await Task.Delay(500, token); } if (!DictionaryUtil.IsNull(applicationInstanceId)) { RemoteDownstreamConfig.Agent.ApplicationInstanceId = applicationInstanceId; _logger.Info( $"Register application instance success. [applicationInstanceId] = {applicationInstanceId}"); } else { _logger.Warning( "Register application instance fail. Server response null."); } } }
private static void PopulateInfo() { if (version != null) { return; // exit here if this info is already populated } osInfo = GetOSInfo(); version = Assembly.GetExecutingAssembly().GetName().Version; curCulture = Thread.CurrentThread.CurrentCulture; }
public ShellSettings() { if (OSInfo.Current == OSNames.Windows) { Editor = OSInfo.GetPath("notepad"); } else { Editor = OSInfo.GetPath("vi"); } }
private OSInfo GetOSPlatform() { OSInfo currentOS = OSInfo.Windows; #if NETCORE if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { currentOS = OSInfo.Linux; } #endif return(currentOS); }
/// <summary> /// Get Device Operating System Information. /// </summary> /// <returns> /// A <see cref="OSInfo"/> /// </returns> public override OSInfo GetOSInfo() { OSInfo oi = new OSInfo(); UIDevice uiDevice = UIDevice.CurrentDevice; oi.Name = uiDevice.SystemName; oi.Version = uiDevice.SystemVersion; oi.Vendor = "Apple Inc."; return(oi); }
public OSInfo GetOSInfo() { var aOperatingSystemInfo = ManagementClassToDictionary("Win32_OperatingSystem"); var osInfo = new OSInfo(); foreach (var values in aOperatingSystemInfo) { var osInfoType = osInfo.GetType(); var property = osInfoType.GetProperty(values.Key); property?.SetValue(osInfo, values.Value); } return(osInfo); }
private static OSInfo GetOSInfo() { ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem"); var result = new OSInfo(); try { foreach (ManagementObject os in searcher.Get()) { result.Name = os["Caption"].ToString(); result.Version = Version.Parse(os["Version"].ToString()); result.Architecture = "32 bit"; if (result.Version.Major > 5) { result.Architecture = os["OSArchitecture"].ToString(); } continue; } } catch (Exception ex) { Log.Error(ex, "{class} {method} {message}", nameof(SystemInfo), nameof(GetOSInfo), $"Error getting OS name and version Info: {ex.Message}"); } try { searcher = new ManagementObjectSearcher("SELECT FreePhysicalMemory, TotalVisibleMemorySize FROM Win32_OperatingSystem"); foreach (ManagementObject os in searcher.Get()) { result.TotalVisibleMemory = long.Parse(os["TotalVisibleMemorySize"].ToString()).KbToGb(); result.TotalFreeMemory = long.Parse(os["FreePhysicalMemory"].ToString()).KbToGb(); } } catch (Exception ex) { Log.Error(ex, "{class} {method} {message}", nameof(SystemInfo), nameof(GetOSInfo), $"Error getting OS memory Info: {ex.Message}"); } string releaseId = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ReleaseId", "")?.ToString(); if (string.IsNullOrEmpty(releaseId)) { releaseId = "<Unknown>"; } result.Release = releaseId; return(result); }
public OSInfo GetOSInfo() { var osInfo = new OSInfo { Description = RuntimeInformation.OSDescription, Architecture = RuntimeInformation.OSArchitecture, FrameworkDescription = RuntimeInformation.FrameworkDescription, Version = System.Environment.OSVersion, Platform = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? OSPlatformType.Linux : RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? OSPlatformType.Windows : RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? OSPlatformType.OSX : OSPlatformType.Unknown, Name = this.OSPrettyName(), }; return(osInfo); }
/// <summary> /// Writes an error, warning, information, success audit, or failure audit /// entry with the given message text to the event log. /// </summary> /// <param name="msg">The string to write to the event log.</param> /// <param name="type">One of the <c>EventLogEntryType</c> values.</param> public static void LogEvent(string source, string msg, EventLogEntryType type, short category, int eventId) { try { OSInfo currentOS = OSInfo.Windows; #if NETCORE if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { currentOS = OSInfo.Unix; } #endif if (currentOS == OSInfo.Windows) { try { int level = (int)type; if ((level & s_logLevel) == level) { using (EventLog ncLog = new EventLog("Application")) { ncLog.Source = source; ncLog.WriteEntry(msg, type, eventId); } } } catch (Exception) { } } else { //To log events on Linux related to daemon only. if (eventId == EventID.ServiceFailure || eventId == EventID.ServiceStart || eventId == EventID.ServiceStop) { try { using (StreamWriter streamWriter = new StreamWriter(GetInstallDir() + Path.DirectorySeparatorChar + serviceLogsPath, true)) { string errorInformation = " Source: " + source + " == EventLogEntryType: " + type.ToString() + " == EventID: " + eventId + " == Message: " + msg; streamWriter.WriteLine(DateTime.Now.ToString() + " == " + errorInformation); streamWriter.WriteLine(" "); } } catch (Exception) { } } } } catch { } }
public static string getPatchesInstalled(string productCode) { //Helper.log("for product code " + productCode); try { string[] patchesCodes = LoadRunner.getPatchesCodes(productCode); string patchesInstalled = null; if (patchesCodes != null) { //Helper.log("Patches codes" + patchesCodes.ToString()); foreach (string patchCode in patchesCodes) { if (patchCode != "Patches") { string keyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products\" + productCode + @"\Patches\" + patchCode; Helper.Log("KeyPath to patch: " + keyPath); if (OSInfo.getOperatingSystemArchitecture().StartsWith("x86")) { RegistryKey rk = Registry.LocalMachine.OpenSubKey(keyPath); patchesInstalled += rk.GetValue("DisplayName").ToString() + " " + Helper.convertInstallDate(rk.GetValue("Installed").ToString()); } else { patchesInstalled += RegistryWOW6432.GetRegKey64(RegHive.HKEY_LOCAL_MACHINE, keyPath, "DisplayName") + " " + Helper.convertInstallDate(RegistryWOW6432.GetRegKey64(RegHive.HKEY_LOCAL_MACHINE, keyPath, "Installed")); } patchesInstalled += Html.br; } } return(patchesInstalled); } return("No patches were detected"); } catch (Exception ex) { return(Html.Error(ex.ToString())); } }
public static NodeOSInfo GetHostInfo(string nodeIP) { NodeOSInfo nodeInfo; if (s_hostInfoMap.TryGetValue(nodeIP, out nodeInfo)) { return(s_hostInfoMap[nodeIP]); } else { OSInfo osInfo = OSDetector.DetectOS(nodeIP); if (OSDetector.hostIP == null) { return(null); } var detectedIP = OSDetector.hostIP; if (detectedIP != null) { nodeIP = detectedIP; } if (osInfo == OSInfo.Linux) { nodeInfo = new NodeOSInfo(nodeIP, OSInfo.Linux); AddHostInfo(nodeIP, nodeInfo); return(nodeInfo); } else if (osInfo == OSInfo.Windows) { nodeInfo = new NodeOSInfo(nodeIP, OSInfo.Windows); AddHostInfo(nodeIP, nodeInfo); return(nodeInfo); } else { nodeInfo = new NodeOSInfo(nodeIP, OSInfo.Unknown); AddHostInfo(nodeIP, nodeInfo); return(nodeInfo); } } }
/// <summary> /// Determines whether this instance [can view changeset in browser]. /// </summary> /// <returns> /// <c>true</c> if this instance [can view changeset in browser]; otherwise, <c>false</c>. /// </returns> public bool CanViewChangesetInBrowser() { var os = new OSInfo().OSPlatform; try { if (os == OSPlatform.Windows) { const string RegKey = @"HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"; const string ItemName = "InstallationType"; // Check version is Client or Server, i.e. excludes Server Core and Nano // Read registry via provider system as Registry class not available in net standard var value = this.cmdlet.SessionState.InvokeProvider.Property .Get(RegKey, new Collection <string> { ItemName }).First().Members .Match(ItemName, PSMemberTypes.NoteProperty).First().Value.ToString(); return(value == "Client" || value == "Server"); } if (os == OSPlatform.Linux) { // Check for desktop (env var XDG_CURRENT_DESKTOP) return(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("XDG_CURRENT_DESKTOP"))); } if (os == OSPlatform.OSX) { // Always have a desktop return(true); } } catch (Exception e) { this.LogDebug($"Unable to determine if changeset can be viewed in browser: {e.Message}"); } return(false); }
private void AssignServerstoRunningCaches() { try { OSInfo currentOS = OSInfo.Windows; #if NETCORE if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux)) { currentOS = OSInfo.Unix; } #endif if (currentOS == OSInfo.Windows) { _nchost.CacheServer.AssignServerstoRunningCaches(); } } catch (Exception ex) { AppUtil.LogEvent(_cacheserver, "An error occurred while assigning servers to running caches. " + ex.ToString(), EventLogEntryType.Error, EventCategories.Error, EventID.ConfigurationError); } }
private static OSInfo GetOSInfo() { ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem"); var result = new OSInfo(); try { foreach (ManagementObject os in searcher.Get()) { result.Name = os["Caption"].ToString(); result.Version = Version.Parse(os["Version"].ToString()); result.Architecture = "32 bit"; if (result.Version.Major > 5) { result.Architecture = os["OSArchitecture"].ToString(); } continue; } } catch (Exception ex) { Log.Error(ex, "{class} {method} {message}", nameof(SystemInfo), nameof(GetOSInfo), $"Error getting OS name and version Info: {ex.Message}"); } try { searcher = new ManagementObjectSearcher("SELECT FreePhysicalMemory, TotalVisibleMemorySize FROM Win32_OperatingSystem"); foreach (ManagementObject os in searcher.Get()) { result.TotalVisibleMemory = long.Parse(os["TotalVisibleMemorySize"].ToString()).KbToGb(); result.TotalFreeMemory = long.Parse(os["FreePhysicalMemory"].ToString()).KbToGb(); } } catch (Exception ex) { Log.Error(ex, "{class} {method} {message}", nameof(SystemInfo), nameof(GetOSInfo), $"Error getting OS memory Info: {ex.Message}"); } return(result); }
/// <summary> /// Writes an error, warning, information, success audit, or failure audit /// entry with the given message text to the event log. /// </summary> /// <param name="msg">The string to write to the event log.</param> /// <param name="type">One of the <c>EventLogEntryType</c> values.</param> public static void LogEvent(string source, string msg, EventLogEntryType type, short category, int eventId) { try { OSInfo currentOS = OSInfo.Windows; #if NETCORE if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { currentOS = OSInfo.Linux; } #endif if (currentOS == OSInfo.Windows) { try { int level = (int)type; if ((level & s_logLevel) == level) { using (EventLog ncLog = new EventLog("Application")) { ncLog.Source = source; ncLog.WriteEntry(msg, type, eventId); } } } catch (Exception) { } } else // For Linux { if (_nCacheEventLogger == null) { _nCacheEventLogger = new NCacheLogger(); _nCacheEventLogger.InitializeEventsLogging(); } _nCacheEventLogger.EventLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss, fff"), source, eventId.ToString(), type.ToString(), msg); } } catch { } }
private void Form1_Load(object sender, EventArgs e) { osInfo = new OSInfo(); ramInfo = new RAMInfo(); videoInfo = new VideoInfo(); processorInfo = new ProcessorInfo(); processManager = new ProcessManager(); processManager.InitStopStartProcess(); processManager.NotifyStopProcess += DeleteProcess; processManager.NotifyStartNewProcess += StartNewProcess; InitCharts(); RefreshMemory(); InitDataTable(); UpdateChartRAM(); TakeInfoAboutOS(); TakeInfoAboutRAM(); UpdateChartProcessor(); TakeInfoAboutProcessor(); TakeInfoAboutVideoAdapter(); }
/// <summary> /// Get OS Version /// </summary> private void GetOSVersion() { string pid = ""; if (Environment.OSVersion.Platform == PlatformID.WinCE) { pid = "Windows CE "; } else { pid = Environment.OSVersion.Platform.ToString(); } OSInfo._OSVERSIONINFO obj = new OSInfo._OSVERSIONINFO(); OSInfo.GetVersionEx(ref obj); pid += string.Format("{0}.{1}", obj.dwMajorVersion, obj.dwMinorVersion); string custVer = PDAInfo.OSInsideVersion; AddToViewAsync(new ViewData("Operating system ver.", pid)); AddToViewAsync(new ViewData("Internal ver.", custVer)); }
public static string GetDofusPath() { if (m_dofusPath == null) { if (!FindDofusPathAuto) { return(m_dofusPath = DofusBasePath); } string programFiles = OSInfo.GetProgramFiles(); if (Directory.Exists(Path.Combine(programFiles, "Dofus2"))) { m_dofusPath = Path.Combine(programFiles, "Dofus2"); } else if (Directory.Exists(Path.Combine(programFiles, "Dofus 2"))) { m_dofusPath = Path.Combine(programFiles, "Dofus 2"); } else { programFiles = OSInfo.GetProgramFilesX86(); if (Directory.Exists(Path.Combine(programFiles, "Dofus2"))) { m_dofusPath = Path.Combine(programFiles, "Dofus2"); } else if (Directory.Exists(Path.Combine(programFiles, "Dofus 2"))) { m_dofusPath = Path.Combine(programFiles, "Dofus 2"); } } } return(m_dofusPath); }
private async Task GetComputerInfoAsync(CancellationToken token) { var sb = new StringBuilder(); int logicalProcessorCount = Environment.ProcessorCount; try { OSInfo osInfo = await OperatingSystemInfoProvider.Instance.GetOSInfoAsync(token); this.osStatus = osInfo.Status; // Active, bound ports. int activePorts = OperatingSystemInfoProvider.Instance.GetActivePortCount(); // Active, ephemeral ports. int activeEphemeralPorts = OperatingSystemInfoProvider.Instance.GetActiveEphemeralPortCount(); (int lowPortOS, int highPortOS) = OperatingSystemInfoProvider.Instance.TupleGetDynamicPortRange(); string osEphemeralPortRange = string.Empty; string fabricAppPortRange = string.Empty; string clusterManifestXml = IsTestRun ? File.ReadAllText( TestManifestPath) : await FabricClientInstance.ClusterManager.GetClusterManifestAsync( AsyncClusterOperationTimeoutSeconds, Token).ConfigureAwait(false); (int lowPortApp, int highPortApp) = NetworkUsage.TupleGetFabricApplicationPortRangeForNodeType( FabricServiceContext.NodeContext.NodeType, clusterManifestXml); int firewalls = NetworkUsage.GetActiveFirewallRulesCount(); // OS info. _ = sb.AppendLine("OS Information:\r\n"); _ = sb.AppendLine($"Name: {osInfo.Name}"); _ = sb.AppendLine($"Version: {osInfo.Version}"); if (string.IsNullOrEmpty(osInfo.InstallDate)) { _ = sb.AppendLine($"InstallDate: {osInfo.InstallDate}"); } _ = sb.AppendLine($"LastBootUpTime*: {osInfo.LastBootUpTime}"); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // WU AutoUpdate - Download enabled. // If the config setting EnableWindowsAutoUpdateCheck is set to false, then don't add this info to sb. if (this.isWUADSettingEnabled) { string auMessage = "WindowsUpdateAutoDownloadEnabled: "; if (this.auStateUnknown) { auMessage += "Unknown"; } else { auMessage += this.isWindowsUpdateAutoDownloadEnabled; } _ = sb.AppendLine(auMessage); } // Not supported for Linux. _ = sb.AppendLine($"OSLanguage: {osInfo.Language}"); _ = sb.AppendLine($"OSHealthStatus*: {osInfo.Status}"); } _ = sb.AppendLine($"NumberOfProcesses*: {osInfo.NumberOfProcesses}"); if (lowPortOS > -1) { osEphemeralPortRange = $"{lowPortOS} - {highPortOS}"; _ = sb.AppendLine($"OSEphemeralTCPPortRange: {osEphemeralPortRange} (Active*: {activeEphemeralPorts})"); } if (lowPortApp > -1) { fabricAppPortRange = $"{lowPortApp} - {highPortApp}"; _ = sb.AppendLine($"FabricApplicationTCPPortRange: {fabricAppPortRange}"); } if (firewalls > -1) { _ = sb.AppendLine($"ActiveFirewallRules*: {firewalls}"); } if (activePorts > -1) { _ = sb.AppendLine($"TotalActiveTCPPorts*: {activePorts}"); } // Hardware info. // Proc/Mem _ = sb.AppendLine($"{Environment.NewLine}Hardware Information:{Environment.NewLine}"); _ = sb.AppendLine($"LogicalProcessorCount: {logicalProcessorCount}"); if (osInfo.TotalVirtualMemorySizeKB > 0) { _ = sb.AppendLine($"TotalVirtualMemorySize: {osInfo.TotalVirtualMemorySizeKB / 1048576} GB"); } if (osInfo.TotalVisibleMemorySizeKB > 0) { _ = sb.AppendLine($"TotalVisibleMemorySize: {osInfo.TotalVisibleMemorySizeKB / 1048576} GB"); } _ = sb.AppendLine($"FreePhysicalMemory*: {Math.Round(osInfo.AvailableMemoryKB / 1048576.0, 2)} GB"); _ = sb.AppendLine($"FreeVirtualMemory*: {Math.Round(osInfo.FreeVirtualMemoryKB / 1048576.0, 2)} GB"); // Disk var drivesInformationTuple = DiskUsage.GetCurrentDiskSpaceTotalAndUsedPercentAllDrives(SizeUnit.Gigabytes); var logicalDriveCount = drivesInformationTuple.Count; string driveInfo = string.Empty; _ = sb.AppendLine($"LogicalDriveCount: {logicalDriveCount}"); foreach (var(driveName, diskSize, percentConsumed) in drivesInformationTuple) { string drvSize; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { string systemDrv = "Data"; if (string.Equals(Environment.SystemDirectory.Substring(0, 1), driveName.Substring(0, 1), StringComparison.OrdinalIgnoreCase)) { systemDrv = "System"; } drvSize = $"Drive {driveName} ({systemDrv}) Size: {diskSize} GB, Consumed*: {percentConsumed}%"; } else { drvSize = $"Mount point: {driveName}, Size: {diskSize} GB, Consumed*: {percentConsumed}%"; } _ = sb.AppendLine(drvSize); driveInfo += $"{drvSize}{Environment.NewLine}"; } string osHotFixes = string.Empty; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { osHotFixes = GetWindowsHotFixes(token); } if (!string.IsNullOrEmpty(osHotFixes)) { _ = sb.AppendLine($"\nWindows Patches/Hot Fixes*:\n\n{osHotFixes}"); } // Dynamic info qualifier (*) _ = sb.AppendLine($"\n* Dynamic data."); this.osReport = sb.ToString(); string hotFixes = string.Empty; // ETW. if (IsEtwEnabled) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { hotFixes = GetWindowsHotFixes(token, generateUrl: false).Replace("\r\n", ", ").TrimEnd(','); } Logger.EtwLogger?.Write( ObserverConstants.FabricObserverETWEventName, new { HealthState = "Ok", Node = NodeName, Observer = ObserverName, OS = osInfo.Name, OSVersion = osInfo.Version, OSInstallDate = osInfo.InstallDate, AutoUpdateEnabled = this.auStateUnknown ? "Unknown" : this.isWindowsUpdateAutoDownloadEnabled.ToString(), osInfo.LastBootUpTime, WindowsAutoUpdateEnabled = this.isWindowsUpdateAutoDownloadEnabled, TotalMemorySizeGB = (int)(osInfo.TotalVisibleMemorySizeKB / 1048576), AvailablePhysicalMemoryGB = Math.Round(osInfo.FreePhysicalMemoryKB / 1048576.0, 2), AvailableVirtualMemoryGB = Math.Round(osInfo.FreeVirtualMemoryKB / 1048576.0, 2), LogicalProcessorCount = logicalProcessorCount, LogicalDriveCount = logicalDriveCount, DriveInfo = driveInfo, NumberOfRunningProcesses = osInfo.NumberOfProcesses, ActiveFirewallRules = firewalls, ActivePorts = activePorts, ActiveEphemeralPorts = activeEphemeralPorts, WindowsDynamicPortRange = osEphemeralPortRange, FabricAppPortRange = fabricAppPortRange, HotFixes = hotFixes, }); } // Telemetry if (IsTelemetryProviderEnabled && IsObserverTelemetryEnabled) { if (string.IsNullOrEmpty(hotFixes) && RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { hotFixes = GetWindowsHotFixes(token, generateUrl: false).Replace("\r\n", ", ").TrimEnd(','); } TelemetryClient?.ReportMetricAsync( new MachineTelemetryData { HealthState = "Ok", Node = NodeName, Observer = ObserverName, OS = osInfo.Name, OSVersion = osInfo.Version, OSInstallDate = osInfo.InstallDate, LastBootUpTime = osInfo.LastBootUpTime, WindowsUpdateAutoDownloadEnabled = this.isWindowsUpdateAutoDownloadEnabled, TotalMemorySizeGB = (int)osInfo.TotalVisibleMemorySizeKB / 1048576, AvailablePhysicalMemoryGB = Math.Round(osInfo.FreePhysicalMemoryKB / 1048576.0, 2), AvailableVirtualMemoryGB = Math.Round(osInfo.FreeVirtualMemoryKB / 1048576.0, 2), LogicalProcessorCount = logicalProcessorCount, LogicalDriveCount = logicalDriveCount, DriveInfo = driveInfo, NumberOfRunningProcesses = osInfo.NumberOfProcesses, ActiveFirewallRules = firewalls, ActivePorts = activePorts, ActiveEphemeralPorts = activeEphemeralPorts, WindowsDynamicPortRange = osEphemeralPortRange, FabricAppPortRange = fabricAppPortRange, HotFixes = hotFixes, }, Token); } } catch (Exception e) when(e is FabricException || e is OperationCanceledException || e is TaskCanceledException || e is InvalidComObjectException) { HealthReporter.ReportFabricObserverServiceHealth( FabricServiceContext.ServiceName.OriginalString, ObserverName, HealthState.Warning, $"Handled Exception processing OS information:{Environment.NewLine}{e}"); } catch (Exception e) { HealthReporter.ReportFabricObserverServiceHealth( FabricServiceContext.ServiceName.OriginalString, ObserverName, HealthState.Error, $"Unhandled Exception processing OS information:{Environment.NewLine}{e}"); throw; } }
/// <summary> /// Initializes the appverse context exposing data to the WebView Javascript DOM. /// </summary> private void InitializeAppverseContext() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); try { #if DEBUG log("Before loading the main HTML, platform will expose some information directly to javascript..."); #endif IPhoneSystem systemService = (IPhoneSystem)IPhoneServiceLocator.GetInstance().GetService("system"); AbstractI18N i18nService = (AbstractI18N)IPhoneServiceLocator.GetInstance().GetService("i18n"); IIo ioService = (IIo)IPhoneServiceLocator.GetInstance().GetService("io"); // 1. Appverse Context (Appverse.is) UnityContext unityContext = systemService.GetUnityContext(); String unityContextJsonString = IPhoneUtils.GetInstance().JSONSerializeObjectData(unityContext); unityContextJsonString = "_AppverseContext = " + unityContextJsonString; this.EvaluateJavascript(unityContextJsonString); // 2. OS Info (Appverse.OSInfo) OSInfo osInfo = systemService.GetOSInfo(); String osInfoJsonString = IPhoneUtils.GetInstance().JSONSerializeObjectData(osInfo); osInfoJsonString = "_OSInfo = " + osInfoJsonString; this.EvaluateJavascript(osInfoJsonString); // 3. Hardware Info (Appverse.HardwareInfo) HardwareInfo hwInfo = systemService.GetOSHardwareInfo(); String hwInfoJsonString = IPhoneUtils.GetInstance().JSONSerializeObjectData(hwInfo); hwInfoJsonString = "_HwInfo = " + hwInfoJsonString; this.EvaluateJavascript(hwInfoJsonString); // 4. Get all configured localized keys (Appverse.i18n) Unity.Core.I18N.Locale[] supportedLocales = i18nService.GetLocaleSupported(); String localizedStrings = "_i18n = {}; _i18n['default'] = '" + i18nService.DefaultLocale + "'; "; String localeLiterals = ""; foreach (Unity.Core.I18N.Locale supportedLocale in supportedLocales) { ResourceLiteralDictionary literals = i18nService.GetResourceLiterals(supportedLocale); String literalsJsonString = IPhoneUtils.GetInstance().JSONSerializeObjectData(literals); localeLiterals = localeLiterals + " _i18n['" + supportedLocale.ToString() + "'] = " + literalsJsonString + "; "; } localizedStrings = localizedStrings + localeLiterals; this.EvaluateJavascript(localizedStrings); // 5. Current device locale Unity.Core.System.Locale currentLocale = systemService.GetLocaleCurrent(); String currentLocaleJsonString = IPhoneUtils.GetInstance().JSONSerializeObjectData(currentLocale); currentLocaleJsonString = "_CurrentDeviceLocale = " + currentLocaleJsonString; this.EvaluateJavascript(currentLocaleJsonString); // 6. Configured IO services endpoints IOService[] services = ioService.GetServices(); String servicesJsonString = "_IOServices = {}; "; foreach (IOService service in services) { String serviceJson = IPhoneUtils.GetInstance().JSONSerializeObjectData(service); servicesJsonString = servicesJsonString + " _IOServices['" + service.Name + "-" + IPhoneUtils.GetInstance().JSONSerializeObjectData(service.Type) + "'] = " + serviceJson + "; "; } this.EvaluateJavascript(servicesJsonString); IPhoneNet NetService = (IPhoneNet)IPhoneServiceLocator.GetInstance().GetService("net"); NetService.CheckConnectivity(); String netJsonString = "_NetworkStatus = " + NetService.getNetStatus(); this.EvaluateJavascript(netJsonString); } catch (Exception ex) { #if DEBUG log("Unable to load Appverse Context. Exception message: " + ex.Message); #endif } stopwatch.Stop(); #if DEBUG log("# Time elapsed initializing Appverse Context: " + stopwatch.Elapsed); #endif }
public void ReadXml(XmlReader r) { while (r.MoveToNextAttribute()) { if (r.Name == "protocol") { protocol = r.Value; } else if (r.Name == "version") { version = r.Value; } else if (r.Name == "ismachine") { ismachine = r.Value; } else if (r.Name == "sessionid") { sessionid = r.Value; } else if (r.Name == "userid") { userid = r.Value; } else if (r.Name == "installsource") { installsource = r.Value; } else if (r.Name == "testsource") { testsource = r.Value; } else if (r.Name == "requestid") { requestid = r.Value; } } while (r.Read()) { switch (r.NodeType) { case XmlNodeType.Element: if (r.Name == "os") { XmlReader s = r.ReadSubtree(); s.Read(); os = new OSInfo(); os.ReadXml(s); s.Close(); } else if (r.Name == "app") { if (apps == null) { apps = new List <AppInfoRequest>(); } XmlReader s = r.ReadSubtree(); s.Read(); AppInfoRequest ai_r = new AppInfoRequest(); ai_r.ReadXml(s); s.Close(); apps.Add(ai_r); } break; } } //r.Read(); //r.ReadAttributeValue(); }