1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tango.Core;
using Tango.Core.DI;
using Tango.Integration.ExternalBridge;
using Tango.PPC.Common.ExternalBridge;
using Tango.PPC.Shared.Performance;
namespace Tango.PPC.Common.Performance
{
[TangoCreateWhenRegistered]
public class DefaultPerformanceService : ExtendedObject, IPerformanceService
{
#region Nested Classes
public static class PerformanceInfo
{
[DllImport("psapi.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetPerformanceInfo([Out] out PerformanceInformation PerformanceInformation, [In] int Size);
[StructLayout(LayoutKind.Sequential)]
public struct PerformanceInformation
{
public int Size;
public IntPtr CommitTotal;
public IntPtr CommitLimit;
public IntPtr CommitPeak;
public IntPtr PhysicalTotal;
public IntPtr PhysicalAvailable;
public IntPtr SystemCache;
public IntPtr KernelTotal;
public IntPtr KernelPaged;
public IntPtr KernelNonPaged;
public IntPtr PageSize;
public int HandlesCount;
public int ProcessCount;
public int ThreadCount;
}
public static Int64 GetPhysicalAvailableMemoryInMiB()
{
PerformanceInformation pi = new PerformanceInformation();
if (GetPerformanceInfo(out pi, Marshal.SizeOf(pi)))
{
return Convert.ToInt64((pi.PhysicalAvailable.ToInt64() * pi.PageSize.ToInt64() / 1048576));
}
else
{
return -1;
}
}
public static Int64 GetTotalMemoryInMiB()
{
PerformanceInformation pi = new PerformanceInformation();
if (GetPerformanceInfo(out pi, Marshal.SizeOf(pi)))
{
return Convert.ToInt64((pi.PhysicalTotal.ToInt64() * pi.PageSize.ToInt64() / 1048576));
}
else
{
return -1;
}
}
}
#endregion
private class PerformanceClient
{
public ExternalBridgeReceiver Receiver { get; set; }
public String Token { get; set; }
}
private List<PerformanceClient> _clients;
private PerformancePackage _package;
private bool _isStarted;
private Thread _performanceThread;
public bool Enabled { get; set; } = true;
public DefaultPerformanceService(IPPCExternalBridgeService externalBridge)
{
_package = new PerformancePackage();
_clients = new List<PerformanceClient>();
externalBridge.RegisterRequestHandler(this);
}
[ExternalBridgeRequestHandlerMethod(typeof(StartPerformanceUpdatesRequest), RequestHandlerLoggingMode.LogRequestNameAndContent)]
public async Task OnStartPerformanceUpdatesRequest(StartPerformanceUpdatesRequest request, String token, ExternalBridgeReceiver receiver)
{
this.ThrowIfDisabled();
if (!_clients.Exists(x => x.Receiver == receiver))
{
_clients.Add(new PerformanceClient() { Receiver = receiver, Token = token });
OnReceiversChanged();
}
await receiver.SendGenericResponse(new StartPerformanceUpdatesResponse() { Package = _package }, token);
}
public void OnReceiverDisconnected(ExternalBridgeReceiver receiver)
{
_clients.RemoveAll(x => x.Receiver == receiver);
OnReceiversChanged();
}
private void OnReceiversChanged()
{
if (_clients.Count > 0 && !_isStarted)
{
_isStarted = true;
_performanceThread = new Thread(PerformanceThreadMethod);
_performanceThread.IsBackground = true;
_performanceThread.Start();
}
else if (_clients.Count == 0 && _isStarted)
{
_isStarted = false;
}
}
private async void PerformanceThreadMethod()
{
while (_isStarted)
{
try
{
_package.ApplicationCPU = (int)GetAppCPU();
_package.CPU = (int)GetTotalCPU();
_package.ApplicationRAM = (int)BytesToMegaBytes(GetAppRam());
_package.MaxRAM = (int)BytesToMegaBytes((long)new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory);
_package.RAM = _package.MaxRAM - (int)PerformanceInfo.GetPhysicalAvailableMemoryInMiB();
DriveInfo info = new DriveInfo("C");
_package.DiskCapacity = (int)BytesToMegaBytes(info.TotalSize);
_package.AvailableDiskSpace = (int)BytesToMegaBytes(info.AvailableFreeSpace);
_package.DateTime = DateTime.Now;
foreach (var client in _clients.ToList().Where(x => x.Receiver.State == Transport.TransportComponentState.Connected))
{
try
{
await client.Receiver.SendGenericResponse(new StartPerformanceUpdatesResponse() { Package = _package }, client.Token);
}
catch (Exception ex)
{
LogManager.Log(ex, "Error sending performance package.");
}
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error creating performance package.");
}
Thread.Sleep(200);
}
}
#region Helpers
private float BytesToMegaBytes(long bytes)
{
return bytes / 1024f / 1024f;
}
public float GetAppCPU()
{
PerformanceCounter cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Process";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = Process.GetCurrentProcess().ProcessName;
// will always start at 0
float firstValue = cpuCounter.NextValue();
System.Threading.Thread.Sleep(1000);
// now matches task manager reading
float secondValue = cpuCounter.NextValue();
return secondValue / Environment.ProcessorCount;
}
public float GetTotalCPU()
{
PerformanceCounter cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
// will always start at 0
float firstValue = cpuCounter.NextValue();
System.Threading.Thread.Sleep(1000);
// now matches task manager reading
float secondValue = cpuCounter.NextValue();
return secondValue;
}
public long GetAppRam()
{
Process proc = Process.GetCurrentProcess();
return proc.PrivateMemorySize64;
}
#endregion
}
}
|