Here are the examples of the csharp api System.Diagnostics.Stopwatch.Start() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3566 Examples
19
Source : DistributedLockProvider.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
public void AdquireLock()
{
if (_stopwatch.IsRunning)
_stopwatch.Stop();
_stopwatch.Start();
var prevStatus = Status;
Status = LockStatus.Acquired;
if (prevStatus == LockStatus.Pending && _tcs != null)
{
_tcs.SetResult(this);
}
}
19
Source : SerializationBinaryTest.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
[Fact]
public void SeralizeTyped()
{
var sw = new Stopwatch();
sw.Start();
var buffer = _binarySerializer.Serialize(modelA);
sw.Stop();
_testOutput.WriteLine($"BINARY Serialize {sw.ElapsedTicks} ticks {sw.ElapsedMilliseconds} ms");
replacedert.NotNull(buffer);
replacedert.NotEmpty(buffer);
sw.Start();
var result = _binarySerializer.Deserialize<ModelA>(buffer);
sw.Stop();
_testOutput.WriteLine($"BINARY Deserialize {sw.ElapsedTicks} ticks {sw.ElapsedMilliseconds} ms");
replacedert.True(modelA.Equals(result));
_testOutput.WriteLine($"Bytes BINARY:{buffer.Length} bytes");
}
19
Source : SerializationBinaryTest.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
[Fact]
public void SeralizeUntyped()
{
var sw = new Stopwatch();
sw.Start();
var buffer = _binarySerializer.Serialize(modelA);
sw.Stop();
_testOutput.WriteLine($"BINARY Serialize {sw.ElapsedTicks} ticks {sw.ElapsedMilliseconds} ms");
replacedert.NotNull(buffer);
replacedert.NotEmpty(buffer);
sw.Start();
var result = (Dictionary<object, object>) _binarySerializer.Deserialize(buffer);
sw.Stop();
_testOutput.WriteLine($"BINARY Deserialize {sw.ElapsedTicks} ticks {sw.ElapsedMilliseconds} ms");
replacedert.NotNull(result);
replacedert.Equal(Convert.ToInt32(result["IntValue"]), modelA.IntValue);
replacedert.Equal((List<object>)result["ListStringValue"], modelA.ListStringValue);
}
19
Source : SerializationBinaryTest.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
[Fact]
public void SerializeProducts()
{
var products = GetProducts();
var sw = new Stopwatch();
sw.Start();
var buffer = _binarySerializer.Serialize(products);
sw.Stop();
_testOutput.WriteLine($"Binary serialize time {sw.ElapsedTicks} ticks {sw.ElapsedMilliseconds} ms");
_testOutput.WriteLine($"Binary data size {buffer.Length} bytes");
replacedert.NotNull(buffer);
replacedert.NotEmpty(buffer);
sw.Restart();
var result = _binarySerializer.Deserialize<List<Product>>(buffer);
sw.Stop();
_testOutput.WriteLine($"Binary desserialize time {sw.ElapsedTicks} ticks {sw.ElapsedMilliseconds} ms");
replacedert.NotNull(result);
replacedert.Equal(products.Count, result.Count);
replacedertProducts(products, result);
}
19
Source : SerializationBinaryTest.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
[Theory]
[InlineData(true)]
[InlineData(false)]
public void SerializeCompare(bool useNewtonsoft)
{
var sw = new Stopwatch();
sw.Start();
var buffer = _binarySerializer.Serialize(modelA);
sw.Stop();
_testOutput.WriteLine($"BINARY Serialize {sw.ElapsedTicks} ticks {sw.ElapsedMilliseconds} ms");
replacedert.NotNull(buffer);
replacedert.NotEmpty(buffer);
sw.Start();
var result = _binarySerializer.Deserialize<ModelA>(buffer);
sw.Stop();
_testOutput.WriteLine($"BINARY Deserialize {sw.ElapsedTicks} ticks {sw.ElapsedMilliseconds} ms");
replacedert.True(modelA.Equals(result));
sw.Start();
var json = useNewtonsoft ?
JsonConvert.SerializeObject(modelA) :
System.Text.Json.JsonSerializer.Serialize(modelA);
var bytesJson = Encoding.UTF8.GetBytes(json);
sw.Stop();
var formatter = useNewtonsoft ? "Json.NET" : "System.Text.Json";
_testOutput.WriteLine($"{formatter} Serialize {sw.ElapsedTicks} ticks {sw.ElapsedMilliseconds} ms");
sw.Start();
json = Encoding.UTF8.GetString(bytesJson);
result = useNewtonsoft ?
JsonConvert.DeserializeObject<ModelA>(json) :
System.Text.Json.JsonSerializer.Deserialize<ModelA>(json);
sw.Stop();
_testOutput.WriteLine($"{formatter} Deserialize {sw.ElapsedTicks} ticks {sw.ElapsedMilliseconds} ms");
replacedert.True(modelA.Equals(result));
_testOutput.WriteLine($"{formatter}:{bytesJson.Length} bytes BINARY:{buffer.Length} bytes");
}
19
Source : DownloaderObjectModel.cs
with GNU General Public License v3.0
from antikmozib
with GNU General Public License v3.0
from antikmozib
private async Task<DownloadStatus> ProcessStreamsAsync(long bytesDownloadedPreviously)
{
var status = DownloadStatus.Error;
Task<bool> streamTask;
HttpRequestMessage request;
long maxDownloadSpeed = Settings.Default.MaxDownloadSpeed * 1024;
SemapreplacedSlim semapreplacedProgress = new SemapreplacedSlim(1);
IProgress<int> streamProgress = new Progress<int>(async (value) =>
{
await semapreplacedProgress.WaitAsync();
this.BytesDownloadedThisSession += value;
this.TotalBytesCompleted = this.BytesDownloadedThisSession + bytesDownloadedPreviously;
if (!this.SupportsResume)
{
this.TotalBytesToDownload = this.TotalBytesCompleted;
}
_reportBytesProgress.Report(value);
double progress = (double)this.TotalBytesCompleted / (double)this.TotalBytesToDownload * 100;
this.Progress = (int)progress;
semapreplacedProgress.Release();
});
// doesn't support multiple streams or each steam under 1 MB
if (!this.SupportsResume)
{
request = new HttpRequestMessage
{
RequestUri = new Uri(this.Url),
Method = HttpMethod.Get
};
}
else
{
// Set up the request
request = new HttpRequestMessage
{
RequestUri = new Uri(this.Url),
Method = HttpMethod.Get,
Headers = { Range = new RangeHeaderValue(bytesDownloadedPreviously, this.TotalBytesToDownload) }
};
}
_ctsPaused = new CancellationTokenSource();
_ctsCanceled = new CancellationTokenSource();
_ctPause = _ctsPaused.Token;
_ctCancel = _ctsCanceled.Token;
var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(_ctPause, _ctCancel).Token;
// Process the request
streamTask = Task.Run(async () =>
{
try
{
if (!Directory.Exists(Path.GetDirectoryName(this.Destination)))
{
throw new AMDownloaderException("Destination directory does not exist.");
}
if (!File.Exists(TempDestination) && File.Exists(this.Destination))
{
throw new AMDownloaderException("A new download has not been created.");
}
using var destinationStream = new FileStream(TempDestination, FileMode.Append, FileAccess.Write);
using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
using var sourceStream = await response.Content.ReadreplacedtreamAsync();
using var binaryWriter = new BinaryWriter(destinationStream);
byte[] buffer = new byte[AppConstants.DownloaderStreamBufferLength];
int s_bytesReceived = 0;
int read;
var stopWatch = new Stopwatch();
while (true)
{
linkedToken.ThrowIfCancellationRequested();
stopWatch.Start();
read = await sourceStream.ReadAsync(buffer, 0, buffer.Length, linkedToken);
if (read == 0)
{
request.Dispose();
return true;
}
else
{
byte[] data = new byte[read];
buffer.ToList().CopyTo(0, data, 0, read);
binaryWriter.Write(data, 0, data.Length);
s_bytesReceived += read;
streamProgress.Report(data.Length);
}
stopWatch.Stop();
// Speed throttler
if (maxDownloadSpeed > 0 && stopWatch.ElapsedMilliseconds > 0)
{
int s_bytesExpected = (int)((double)maxDownloadSpeed / 1000 * stopWatch.ElapsedMilliseconds);
if (s_bytesReceived > s_bytesExpected)
{
long expectedMilliseconds = (long)(1000 / (double)maxDownloadSpeed * s_bytesReceived);
long delay = expectedMilliseconds - stopWatch.ElapsedMilliseconds;
if (delay > 0) await Task.Delay((int)delay);
s_bytesReceived = 0;
stopWatch.Reset();
}
}
}
}
catch (Exception ex)
{
throw new AMDownloaderException(ex.Message, ex);
}
});
StartReportingProgress();
StartMeasuringEta();
try
{
// Run the tasks
var finished = await streamTask;
// Operation complete; verify state
// completed successfully
if (finished)
{
status = DownloadStatus.Finished;
}
else
{
status = DownloadStatus.Error;
}
}
catch
{
// Paused, cancelled or errored
if (!linkedToken.IsCancellationRequested)
{
status = DownloadStatus.Error;
}
else if (_ctPause.IsCancellationRequested)
{
status = DownloadStatus.Paused;
}
else if (_ctCancel.IsCancellationRequested)
{
status = DownloadStatus.Ready;
}
}
// Update final size
if (!this.SupportsResume) this.TotalBytesToDownload = this.TotalBytesCompleted;
_ctsPaused = null;
_ctsCanceled = null;
_ctPause = default;
_ctCancel = default;
_taskCompletion.SetResult(status);
return status;
}
19
Source : DownloaderObjectModel.cs
with GNU General Public License v3.0
from antikmozib
with GNU General Public License v3.0
from antikmozib
private void StartMeasuringEta()
{
if (!this.SupportsResume)
{
this.TimeRemaining = null;
RaisePropertyChanged(nameof(this.TimeRemaining));
}
else
{
Task.Run(async () =>
{
long bytesFrom = this.TotalBytesCompleted;
long bytesTo;
long bytesCaptured;
Stopwatch stopWatch = new Stopwatch();
while (this.IsBeingDownloaded)
{
stopWatch.Start();
await Task.Delay(1000);
bytesTo = this.TotalBytesCompleted;
bytesCaptured = bytesTo - bytesFrom;
stopWatch.Stop();
double eta = ((this.TotalBytesToDownload ?? 0) - this.TotalBytesCompleted) *
((double)stopWatch.ElapsedMilliseconds / bytesCaptured);
if (eta >= 0)
{
this.TimeRemaining = eta;
RaisePropertyChanged(nameof(this.TimeRemaining));
}
}
}).ContinueWith(t =>
{
this.TimeRemaining = null;
RaisePropertyChanged(nameof(this.TimeRemaining));
});
}
}
19
Source : DownloaderViewModel.cs
with GNU General Public License v3.0
from antikmozib
with GNU General Public License v3.0
from antikmozib
private void StartReportingSpeed()
{
if (_semapreplacedMeasuringSpeed.CurrentCount == 0) return;
Task.Run(async () =>
{
await _semapreplacedMeasuringSpeed.WaitAsync();
var stopWatch = new Stopwatch();
long bytesFrom;
long bytesTo;
long bytesCaptured;
do
{
bytesFrom = 0;
bytesTo = 0;
stopWatch.Start();
bytesFrom = this.BytesDownloaded;
await Task.Delay(1000);
bytesTo = this.BytesDownloaded;
stopWatch.Stop();
bytesCaptured = bytesTo - bytesFrom;
if (bytesCaptured >= 0 && stopWatch.ElapsedMilliseconds > 0)
{
this.Speed = (long)((double)bytesCaptured / ((double)stopWatch.ElapsedMilliseconds / 1000));
RaisePropertyChanged(nameof(this.Speed));
RaisePropertyChanged(nameof(this.BytesDownloaded));
}
stopWatch.Reset();
} while (bytesCaptured > 0);
this.Speed = null;
RaisePropertyChanged(nameof(this.Speed));
_semapreplacedMeasuringSpeed.Release();
});
}
19
Source : ThreadedSimulation.cs
with Apache License 2.0
from AntoineCharton
with Apache License 2.0
from AntoineCharton
void ThreadedUpdate()
{
try
{
while (isThreadActive)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
UpdatePhysics(TargetTimeStep);
var timeRunned = stopWatch.ElapsedMilliseconds;
physicsElapsed = timeRunned;
Thread.Sleep(Convert.ToInt32(Mathf.Max(0, (TargetTimeStep * 1000) - timeRunned)));
totalElapsed = stopWatch.ElapsedMilliseconds;
stopWatch.Stop();
}
}
catch (Exception ex)
{
UnityEngine.Debug.LogError(ex);
throw;
}
UnityEngine.Debug.Log("Thread completed");
Dispose();
}
19
Source : TestPropertyBlocks.cs
with MIT License
from antonsem
with MIT License
from antonsem
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
ChangeColor();
if (Input.GetKeyDown(KeyCode.Alpha1))
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (var i = 0; i < 100000; i++)
{
ChangeColorsHash();
}
stopwatch.Stop();
Debug.Log($"It took {stopwatch.Elapsed.Milliseconds.ToString()}ms to change color of {renderers.Length.ToString()} 100000 times using hash.");
}
if (Input.GetKeyDown(KeyCode.Alpha2))
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (var i = 0; i < 100000; i++)
{
ChangeColorsString();
}
stopwatch.Stop();
Debug.Log($"It took {stopwatch.Elapsed.Milliseconds.ToString()}ms to change color of {renderers.Length.ToString()} 100000 times using string.");
}
}
19
Source : AutomateService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private void TimerTick(object? sender, System.EventArgs e)
{
var now = _dateTimeService.Now();
if (!_stopwatch.IsRunning)
{
// not yet started the meeting...
if (now.Minute % 15 == 0)
{
// start on the nearest quarter hour...
_stopwatch.Start();
_nextStartTime = now.TimeOfDay.Add(TimeSpan.FromMinutes(5));
}
return;
}
var status = _timerService.GetStatus();
CheckIsCurrentTalk(status);
if (_nextStartTime != null && now.TimeOfDay > _nextStartTime)
{
// Start the talk timer...
CheckNotRunning(status);
if (status.TalkId != null)
{
_timerService.StartTalkTimerFromApi(status.TalkId.Value);
}
_nextStartTime = null;
_nextStopTime = now.TimeOfDay.Add(TimeSpan.FromSeconds(status.TargetSeconds));
return;
}
if (_nextStopTime != null && now.TimeOfDay > _nextStopTime)
{
// Stop the talk timer...
CheckIsRunning(status);
if (status.TalkId != null)
{
_timerService.StopTalkTimerFromApi(status.TalkId.Value);
}
_nextStopTime = null;
_nextStartTime = CalculateNextStartTime(status, now);
if (_nextStartTime == null)
{
// all done
_stopwatch.Stop();
_timer.Stop();
}
}
}
19
Source : TalkTimerService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
public void Start(int targetSecs, int talkId, bool isCountingUp)
{
_targetSecs = targetSecs;
_talkId = talkId;
_isCountingUp = isCountingUp;
_stopWatch.Start();
UpdateTimerValue();
_timer.Start();
}
19
Source : Program.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
private static void TestBinding(
Il2cppContext context, TypeDef typeDef,
string imageDir, string imageName, string subDir)
{
MethodDef metDef = IsTestBinding(typeDef);
if (metDef == null)
return;
string testName = string.Format("[{0}]{1}", imageName, typeDef.FullName);
var oldColor = Console.ForegroundColor;
Console.Write("{0} {1}: ", subDir, testName);
context.AddEntry(metDef);
var sw = new Stopwatch();
sw.Start();
string exceptionMsg = null;
try
{
context.Resolve();
}
catch (TypeLoadException ex)
{
exceptionMsg = ex.Message;
}
sw.Stop();
long elapsedMS = sw.ElapsedMilliseconds;
Console.Write("{0}ms, ", elapsedMS);
StringBuilder sb = new StringBuilder();
if (exceptionMsg != null)
sb.Append(exceptionMsg);
else
{
HierarchyDump dumper = new HierarchyDump(context);
/*sb.Append("* MethodTables:\n");
dumper.DumpMethodTables(sb);*/
sb.Append("* Types:\n");
dumper.DumpTypes(sb);
}
var dumpData = Encoding.UTF8.GetBytes(sb.ToString());
string validatedName = ValidatePath(testName);
File.WriteAllBytes(
Path.Combine(imageDir, validatedName + ".dump"),
dumpData);
byte[] cmpData = null;
try
{
cmpData = File.ReadAllBytes(Path.Combine(imageDir, validatedName + ".txt"));
cmpData = ReplaceNewLines(cmpData);
}
catch
{
}
if (cmpData != null && dumpData.SequenceEqual(cmpData))
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Preplaced");
Console.ForegroundColor = oldColor;
++PreplacededTests;
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("FAIL");
Console.ForegroundColor = oldColor;
}
++TotalTests;
context.Reset();
}
19
Source : Program.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
private static void TestCodeGen(
Il2cppContext context, TypeDef typeDef,
string imageDir, string imageName, string subDir)
{
MethodDef metDef = IsTestCodeGen(typeDef);
if (metDef == null)
return;
string testName = string.Format("[{0}]{1}", imageName, typeDef.FullName);
var oldColor = Console.ForegroundColor;
Console.Write("{0,-52}", string.Format("{0} {1}:", subDir, testName));
context.AddEntry(metDef);
var sw = new Stopwatch();
sw.Start();
context.Resolve();
sw.Stop();
long elapsedMS = sw.ElapsedMilliseconds;
Console.Write("{0,-12}", string.Format("Res({0}ms)", elapsedMS));
string strRecLogs = context.GetRecordLogs();
if (strRecLogs != null)
Console.WriteLine('\n' + strRecLogs);
sw.Restart();
var genResult = context.Generate();
sw.Stop();
elapsedMS = sw.ElapsedMilliseconds;
Console.Write("{0,-12}", string.Format("Gen({0}ms)", elapsedMS));
string validatedName = ValidatePath(testName);
string genDir = Path.Combine(imageDir, "../../gen/", validatedName);
// 生成入口测试代码
if (!File.Exists(Path.Combine(genDir, "main.cpp")))
{
var mainUnit = new CompileUnit();
genResult.UnitList.Add(mainUnit);
mainUnit.Name = "main";
string metName = genResult.GetMethodName(metDef, out var metUnitName);
mainUnit.ImplDepends.Add(metUnitName);
mainUnit.ImplCode =
"#include <stdio.h>\n" +
"#include <time.h>\n" +
"#include <string>\n\n" +
"int main()\n" +
"{\n" +
" il2cpp_Init();\n" +
" auto start = clock();\n" +
" auto result = " + metName + "();\n" +
" auto elapsed = clock() - start;\n" +
" printf(\"Result(%s), %ldms\", std::to_string(result).c_str(), elapsed);\n" +
" return 0;\n" +
"}\n";
}
genResult.GenerateIncludes();
Il2cppContext.SaveToFolder(
genDir,
genResult.UnitList,
new HashSet<string> { "main" });
genDir = Path.GetFullPath(genDir);
Console.Write("Building");
bool hasBuildErr = false;
Action<string> actOutput = strOut =>
{
if (!hasBuildErr)
{
if (strOut.IndexOf("warning") != -1)
{
Console.WriteLine("\n{0}", strOut);
}
if (strOut.IndexOf("error") != -1)
{
Console.WriteLine();
hasBuildErr = true;
}
else if (strOut.IndexOf(":") != -1 && strOut.IndexOf("Skipped:") == -1)
Console.Write(".");
}
if (hasBuildErr)
{
Console.Error.WriteLine("{0}", strOut);
}
};
string result = null;
RunCommand(
null,
"build.cmd",
genDir,
actOutput,
actOutput);
if (!hasBuildErr)
{
Console.Write(" Running ");
string runOutput = null;
RunCommand(
null,
"final.exe",
genDir,
strOut => runOutput = strOut,
Console.Error.WriteLine);
Console.Write("{0,-20}", runOutput);
if (runOutput != null)
result = GetRunResult(runOutput);
}
if (result == "0")
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Preplaced");
Console.ForegroundColor = oldColor;
++PreplacededTests;
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("FAIL");
Console.ForegroundColor = oldColor;
}
++TotalTests;
context.Reset();
}
19
Source : Ping.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public Task<Stats> Start(int numberOfMessages, int skipMessages)
{
this.numberOfMessages = numberOfMessages;
this.skipMessages = skipMessages;
this.tsc = new TaskCompletionSource<Stats>();
stopwatch.Start();
messageProducer.Send(pingMessage);
return this.tsc.Task;
}
19
Source : LoadBalancedActionPool.cs
with GNU Lesser General Public License v3.0
from ApexGameTools
with GNU Lesser General Public License v3.0
from ApexGameTools
float? ILoadBalanced.ExecuteUpdate(float deltaTime, float nextInterval)
{
bool moreWork = true;
_watch.Reset();
_watch.Start();
while (moreWork && _watch.ElapsedMilliseconds < _maxMillisecondsUsedPerFrame)
{
moreWork = _iter.MoveNext();
}
this.repeat = moreWork;
if (!moreWork)
{
LoadBalancedActionPool.Return(this);
}
return 0f;
}
19
Source : LoadBalancedQueue.cs
with GNU Lesser General Public License v3.0
from ApexGameTools
with GNU Lesser General Public License v3.0
from ApexGameTools
public void Update()
{
if (!_queue.hasNext)
{
return;
}
var now = _time();
_watch.Reset();
_watch.Start();
var maxUpdates = this.maxUpdatesPerInterval;
int updateCount = 0;
float overDue = 0.0f;
if (autoAdjust)
{
var framesPerInterval = this.defaultUpdateInterval / _deltaTime();
maxUpdates = Mathf.CeilToInt(_queue.count / framesPerInterval);
}
var item = _queue.Peek();
while ((updateCount++ < maxUpdates) && (item.nextUpdate <= now) && (this.autoAdjust || (_watch.ElapsedMilliseconds < this.maxUpdateTimeInMillisecondsPerUpdate)))
{
var deltaTime = now - item.lastUpdate;
overDue += (deltaTime - item.interval);
var nextInterval = item.item.ExecuteUpdate(deltaTime, item.interval).GetValueOrDefault(item.interval);
if (item.item.repeat)
{
//Next interval is the suggested interval or the default. It cannot be 0 since that would lead to continuous updates in this loop.
nextInterval = Mathf.Max(nextInterval, 0.01f);
item.lastUpdate = now;
item.nextUpdate = now + nextInterval;
_queue.ReheapifyDownFrom(0);
}
else
{
var lbi = _queue.Remove();
lbi.Dispose();
}
if (!_queue.hasNext)
{
break;
}
item = _queue.Peek();
}
this.updatedItemsCount = updateCount - 1;
this.updatesOverdueByTotal = overDue;
this.updateMillisecondsUsed = _watch.ElapsedMilliseconds;
}
19
Source : LongRunningAction.cs
with GNU Lesser General Public License v3.0
from ApexGameTools
with GNU Lesser General Public License v3.0
from ApexGameTools
public float? ExecuteUpdate(float deltaTime, float nextInterval)
{
if (_iter == null)
{
_iter = _action();
}
bool moreWork = true;
_watch.Reset();
_watch.Start();
while (moreWork && _watch.ElapsedMilliseconds < _maxMillisecondUsedPerFrame)
{
moreWork = _iter.MoveNext();
}
this.repeat = moreWork;
if (!moreWork)
{
_iter = null;
if (_callback != null)
{
_callback();
}
}
return 0f;
}
19
Source : Marshaller.cs
with GNU Lesser General Public License v3.0
from ApexGameTools
with GNU Lesser General Public License v3.0
from ApexGameTools
internal void ProcessPending()
{
if (_queue.count == 0)
{
return;
}
_watch.Start();
do
{
Action next;
lock (_queue)
{
next = _queue.Dequeue();
}
next();
}
while (_queue.count > 0 && _watch.ElapsedMilliseconds < _maxMillisecondsPerFrame);
_watch.Reset();
}
19
Source : DebugTimer.cs
with GNU Lesser General Public License v3.0
from ApexGameTools
with GNU Lesser General Public License v3.0
from ApexGameTools
[Conditional("UNITY_EDITOR")]
public static void Start()
{
var sw = new Stopwatch();
_watches.Push(sw);
sw.Start();
}
19
Source : DebugTimer.cs
with GNU Lesser General Public License v3.0
from ApexGameTools
with GNU Lesser General Public License v3.0
from ApexGameTools
[Conditional("UNITY_EDITOR")]
public static void StartAverage(int iterations)
{
if (_count <= 0)
{
_avg = 0f;
_iterations = _count = iterations;
_avgWatch = Stopwatch.StartNew();
}
else
{
_avgWatch.Reset();
_avgWatch.Start();
}
}
19
Source : PathService.cs
with GNU Lesser General Public License v3.0
from ApexGameTools
with GNU Lesser General Public License v3.0
from ApexGameTools
public IEnumerator ProcessRequests(int maxMillisecondsPerFrame)
{
if (this.runAsync)
{
throw new InvalidOperationException("Cannot process as coroutine when set to async operation.");
}
while (!this.runAsync)
{
var next = GetNext();
if (next == null)
{
if (_stopwatch.IsRunning)
{
_stopwatch.Reset();
}
yield return null;
}
else
{
var run = true;
var subIter = _engine.ProcessRequestCoroutine(next);
while (run)
{
//Start is called multiple places, due to the enumeration going on in various loops. Start is safe to call multiple times, it will simply do nothing if already started.
_stopwatch.Start();
run = subIter.MoveNext();
if (_stopwatch.ElapsedMilliseconds > maxMillisecondsPerFrame)
{
_stopwatch.Reset();
yield return null;
}
}
}
}
}
19
Source : ControllerApi.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
private string apiGET(string restAPIUrl, string acceptHeader, bool useXSRFHeader)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
try
{
MediaTypeWithQualityHeaderValue accept = new MediaTypeWithQualityHeaderValue(acceptHeader);
if (this._httpClient.DefaultRequestHeaders.Accept.Contains(accept) == false)
{
this._httpClient.DefaultRequestHeaders.Accept.Add(accept);
}
//this._httpClient.DefaultRequestHeaders.Remove("X-CSRF-TOKEN");
if (useXSRFHeader == true)
{
if (this._httpClient.DefaultRequestHeaders.Contains("X-CSRF-TOKEN") == false)
{
// Add CSRF cookie if available
Cookie cookieXSRF = this._cookieContainer.GetCookies(new Uri(this._httpClient.BaseAddress, "controller/auth"))["X-CSRF-TOKEN"];
if (cookieXSRF != null)
{
this._httpClient.DefaultRequestHeaders.Add("X-CSRF-TOKEN", cookieXSRF.Value);
}
}
}
HttpResponseMessage response = this._httpClient.GetAsync(restAPIUrl).Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadreplacedtringAsync().Result;
}
else
{
// For the times when the system throws 500 with some meaningful message
string resultString = response.Content.ReadreplacedtringAsync().Result;
if (resultString.Length > 0)
{
logger.Error("{0}/{1} GET as {2} returned {3} ({4}) with {5}", this.ControllerUrl, restAPIUrl, this.UserName, (int)response.StatusCode, response.ReasonPhrase, resultString);
}
else
{
logger.Error("{0}/{1} GET as {2} returned {3} ({4})", this.ControllerUrl, restAPIUrl, this.UserName, (int)response.StatusCode, response.ReasonPhrase);
}
if (response.StatusCode == HttpStatusCode.Unauthorized ||
response.StatusCode == HttpStatusCode.Forbidden)
{
loggerConsole.Error("{0}/{1} GET as {2} returned {3} ({4})", this.ControllerUrl, restAPIUrl, this.UserName, (int)response.StatusCode, response.ReasonPhrase);
}
return String.Empty;
}
}
catch (Exception ex)
{
logger.Error("{0}/{1} GET as {2} threw {3} ({4})", this.ControllerUrl, restAPIUrl, this.UserName, ex.Message, ex.Source);
logger.Error(ex);
return String.Empty;
}
finally
{
stopWatch.Stop();
logger.Trace("{0}/{1} GET as {2} took {3:c} ({4} ms)", this.ControllerUrl, restAPIUrl, this.UserName, stopWatch.Elapsed.ToString("c"), stopWatch.ElapsedMilliseconds);
}
}
19
Source : ControllerApi.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
private string apiPOST(string restAPIUrl, string acceptHeader, string requestBody, string requestTypeHeader, bool useXSRFHeader)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
try
{
MediaTypeWithQualityHeaderValue accept = new MediaTypeWithQualityHeaderValue(acceptHeader);
if (this._httpClient.DefaultRequestHeaders.Accept.Contains(accept) == false)
{
this._httpClient.DefaultRequestHeaders.Accept.Add(accept);
}
//this._httpClient.DefaultRequestHeaders.Remove("X-CSRF-TOKEN");
if (useXSRFHeader == true)
{
if (this._httpClient.DefaultRequestHeaders.Contains("X-CSRF-TOKEN") == false)
{
// Add CSRF cookie if available
Cookie cookieXSRF = this._cookieContainer.GetCookies(new Uri(this._httpClient.BaseAddress, "controller/auth"))["X-CSRF-TOKEN"];
if (cookieXSRF != null)
{
this._httpClient.DefaultRequestHeaders.Add("X-CSRF-TOKEN", cookieXSRF.Value);
}
}
}
StringContent content = new StringContent(requestBody);
content.Headers.ContentType = new MediaTypeWithQualityHeaderValue(requestTypeHeader);
HttpResponseMessage response = this._httpClient.PostAsync(restAPIUrl, content).Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadreplacedtringAsync().Result;
}
else
{
string resultString = response.Content.ReadreplacedtringAsync().Result;
if (resultString.Length > 0)
{
logger.Error("{0}/{1} POST as {2} returned {3} ({4}) with {5}", this.ControllerUrl, restAPIUrl, this.UserName, (int)response.StatusCode, response.ReasonPhrase, resultString);
}
else
{
logger.Error("{0}/{1} POST as {2} returned {3} ({4})", this.ControllerUrl, restAPIUrl, this.UserName, (int)response.StatusCode, response.ReasonPhrase);
}
if (response.StatusCode == HttpStatusCode.Unauthorized ||
response.StatusCode == HttpStatusCode.Forbidden)
{
loggerConsole.Error("{0}/{1} POST as {2} returned {3} ({4})", this.ControllerUrl, restAPIUrl, this.UserName, (int)response.StatusCode, response.ReasonPhrase);
}
return String.Empty;
}
}
catch (Exception ex)
{
logger.Error("{0}/{1} POST as {2} threw {3} ({4})", this.ControllerUrl, restAPIUrl, this.UserName, ex.Message, ex.Source);
logger.Error(ex);
return String.Empty;
}
finally
{
stopWatch.Stop();
logger.Trace("{0}/{1} POST as {2} took {3:c} ({4} ms)", this.ControllerUrl, restAPIUrl, this.UserName, stopWatch.Elapsed.ToString("c"), stopWatch.ElapsedMilliseconds);
logger.Trace("POST body {0}", requestBody);
}
}
19
Source : Core.cs
with MIT License
from Apostolique
with MIT License
from Apostolique
protected override void LoadContent() {
_realGametime = new Stopwatch();
_realGametime.Start();
_s = new SpriteBatch(GraphicsDevice);
_context = new Context(Path.Combine(replacedemblyDirectory, "Content"), GraphicsDevice);
replacedets.LoadLoadingreplacedets(_context);
_loading = new Loading();
_go = _loading;
Thread thread = new Thread(Loadreplacedets);
thread.Start();
}
19
Source : VLookup.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
{
Stopwatch sw = null;
if (context.Debug)
{
sw = new Stopwatch();
sw.Start();
}
ValidateArguments(arguments, 3);
var lookupArgs = new LookupArguments(arguments, context);
var navigator = LookupNavigatorFactory.Create(LookupDirection.Vertical, lookupArgs, context);
var result = Lookup(navigator, lookupArgs);
if (context.Debug)
{
sw.Stop();
context.Configuration.Logger.LogFunction("VLOOKUP", sw.ElapsedMilliseconds);
}
return result;
}
19
Source : TextFunctionsTests.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
[TestMethod, Ignore]
public void Logtest1()
{
var sw = new Stopwatch();
sw.Start();
using (var pck = new ExcelPackage(new FileInfo(@"c:\temp\denis.xlsx")))
{
var logger = LoggerFactory.CreateTextFileLogger(new FileInfo(@"c:\temp\log1.txt"));
pck.Workbook.FormulaParser.Configure(x => x.AttachLogger(logger));
pck.Workbook.Calculate();
//
}
sw.Stop();
var elapsed = sw.Elapsed;
Console.WriteLine(string.Format("{0} seconds", elapsed.TotalSeconds));
}
19
Source : Issues.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
[TestMethod, Ignore]
public void Issue15173_1()
{
using (var pck = new ExcelPackage(new FileInfo(@"c:\temp\EPPlusIssues\Excel01.xlsx")))
{
var sw = new Stopwatch();
//pck.Workbook.FormulaParser.Configure(x => x.AttachLogger(LoggerFactory.CreateTextFileLogger(new FileInfo(@"c:\Temp\log1.txt"))));
sw.Start();
var ws = pck.Workbook.Worksheets.First();
pck.Workbook.Calculate();
replacedert.AreEqual("20L2300", ws.Cells["F4"].Value);
replacedert.AreEqual("20K2E01", ws.Cells["F5"].Value);
var f7Val = pck.Workbook.Worksheets["MODELLO-TIPO PANNELLO"].Cells["F7"].Value;
replacedert.AreEqual(13.445419, Math.Round((double)f7Val, 6));
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalSeconds); // approx. 10 seconds
}
}
19
Source : Issues.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
[TestMethod, Ignore]
public void Issue15173_2()
{
using (var pck = new ExcelPackage(new FileInfo(@"c:\temp\EPPlusIssues\Excel02.xlsx")))
{
var sw = new Stopwatch();
pck.Workbook.FormulaParser.Configure(x => x.AttachLogger(LoggerFactory.CreateTextFileLogger(new FileInfo(@"c:\Temp\log1.txt"))));
sw.Start();
var ws = pck.Workbook.Worksheets.First();
//ws.Calculate();
pck.Workbook.Calculate();
replacedert.AreEqual("20L2300", ws.Cells["F4"].Value);
replacedert.AreEqual("20K2E01", ws.Cells["F5"].Value);
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalSeconds); // approx. 10 seconds
}
}
19
Source : StartupTimerService.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
public void StartTimer()
{
_stopwatch = new Stopwatch();
_stopwatch.Start();
}
19
Source : HttpHealthCheckBuilderExtensions.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
private static async Task<HealthCheckResult> ExecuteHttpCheckNoRetriesAsync(
Uri uri,
TimeSpan timeout,
bool degradedOnError,
CancellationToken cancellationToken)
{
var sw = new Stopwatch();
try
{
using (var tokenWithTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
tokenWithTimeout.CancelAfter(timeout);
sw.Start();
var response = await HttpClient.GetAsync(uri, tokenWithTimeout.Token).ConfigureAwait(false);
return response.IsSuccessStatusCode
? HealthCheckResult.Healthy($"OK. '{uri}' success. Time taken: {sw.ElapsedMilliseconds}ms.")
: HealthCheckResultOnError(
$"FAILED. '{uri}' status code was {response.StatusCode}. Time taken: {sw.ElapsedMilliseconds}ms.",
degradedOnError);
}
}
catch (Exception ex) when (ex is TaskCanceledException)
{
Logger.ErrorException($"HTTP Health Check '{uri}' did not respond within '{timeout.TotalMilliseconds}'ms.", ex);
return HealthCheckResultOnError($"FAILED. '{uri}' did not respond within {timeout.TotalMilliseconds}ms", degradedOnError);
}
catch (Exception ex) when (ex is TimeoutException)
{
Logger.ErrorException($"HTTP Health Check '{uri}' timed out. Time taken: {sw.ElapsedMilliseconds}ms.", ex);
return HealthCheckResultOnError($"FAILED. '{uri}' timed out. Time taken: {sw.ElapsedMilliseconds}ms.", degradedOnError);
}
catch (Exception ex) when (ex is HttpRequestException)
{
Logger.ErrorException($"HTTP Health Check '{uri}' failed. Time taken: {sw.ElapsedMilliseconds}ms.", ex);
return HealthCheckResultOnError(
$"FAILED. '{uri}' request failed with an unexpected error. Time taken: {sw.ElapsedMilliseconds}ms.",
degradedOnError);
}
catch (Exception ex)
{
var message = $"HTTP Health Check failed to request '{uri}'. Time taken: {sw.ElapsedMilliseconds}ms.";
Logger.ErrorException(message, ex);
return HealthCheckResultOnError($"FAILED. {message}", degradedOnError);
}
finally
{
sw.Stop();
}
}
19
Source : HttpHealthCheckBuilderExtensions.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
private static async Task<HealthCheckResult> ExecuteHealthCheckWithRetriesAsync(
Uri uri,
int retries,
TimeSpan delayBetweenRetries,
TimeSpan timeoutPerRequest,
bool degradedOnError,
CancellationToken cancellationToken)
{
var sw = new Stopwatch();
var attempts = 0;
try
{
sw.Start();
do
{
try
{
attempts++;
using (var tokenWithTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
tokenWithTimeout.CancelAfter(timeoutPerRequest);
var response = await HttpClient.GetAsync(uri, tokenWithTimeout.Token);
if (attempts == retries || response.IsSuccessStatusCode)
{
return response.IsSuccessStatusCode
? HealthCheckResult.Healthy(
$"OK. '{uri}' success. Total Time taken: {sw.ElapsedMilliseconds}ms. Attempts: {attempts}.")
: HealthCheckResultOnError(
$"FAILED. '{uri}' status code was {response.StatusCode}. Time taken: {sw.ElapsedMilliseconds}ms. Attempts: {attempts}.",
degradedOnError);
}
if (response.StatusCode == HttpStatusCode.GatewayTimeout ||
response.StatusCode == HttpStatusCode.ServiceUnavailable)
{
Logger.Error(
$"HTTP Health Check '{uri}' failed with status code {response.StatusCode}. Time taken: {sw.ElapsedMilliseconds}ms. Attempts: {attempts}.");
Logger.Info(
$"Retrying HTTP Health Check '{uri}' in {delayBetweenRetries.TotalMilliseconds}ms. {attempts} / {retries} retries.");
await Task.Delay(delayBetweenRetries, cancellationToken);
}
}
}
catch (Exception ex) when (ex is TaskCanceledException)
{
Logger.ErrorException(
$"HTTP Health Check '{uri}' did not respond within '{timeoutPerRequest.TotalMilliseconds}'ms. Time taken: {sw.ElapsedMilliseconds}ms. Attempts: {attempts}.",
ex);
if (attempts == retries)
{
return HealthCheckResultOnError(
$"FAILED. '{uri}' did not respond within {timeoutPerRequest.TotalMilliseconds}ms. Time taken: {sw.ElapsedMilliseconds}ms. Attempts: {attempts}.",
degradedOnError);
}
await Retry(uri, retries, delayBetweenRetries, attempts, ex, cancellationToken);
}
catch (Exception ex) when (ex is TimeoutException)
{
Logger.ErrorException(
$"HTTP Health Check '{uri}' timed out. Time taken: {sw.ElapsedMilliseconds}ms. Attempts: {attempts}.",
ex);
if (attempts == retries)
{
return HealthCheckResultOnError(
$"FAILED. '{uri}' timed out. Time taken: {sw.ElapsedMilliseconds}ms. Attempts: {attempts}.",
degradedOnError);
}
await Retry(uri, retries, delayBetweenRetries, attempts, ex, cancellationToken);
}
catch (Exception ex) when (ex is HttpRequestException)
{
Logger.ErrorException(
$"HTTP Health Check '{uri}' failed. Time taken: {sw.ElapsedMilliseconds}ms. Attempts: {attempts}.",
ex);
if (attempts == retries)
{
return HealthCheckResultOnError(
$"FAILED. '{uri}' request failed with an unexpected error. Time taken: {sw.ElapsedMilliseconds}ms. Attempts: {attempts}.",
degradedOnError);
}
await Retry(uri, retries, delayBetweenRetries, attempts, ex, cancellationToken);
}
catch (Exception ex)
{
var message =
$"HTTP Health Check failed to request '{uri}'. Time taken: {sw.ElapsedMilliseconds}ms. Attempts: {attempts}.";
if (attempts == retries)
{
Logger.ErrorException(message, ex);
return HealthCheckResultOnError(
$"FAILED. {message}.",
degradedOnError);
}
await Retry(uri, retries, delayBetweenRetries, attempts, ex, cancellationToken);
}
}
while (true);
}
catch (Exception ex) when (ex is TaskCanceledException)
{
Logger.ErrorException(
$"HTTP Health Check '{uri}' did not respond within '{timeoutPerRequest.TotalMilliseconds}'ms. Attempts: {attempts}.",
ex);
return HealthCheckResultOnError(
$"FAILED. '{uri}' did not respond within {timeoutPerRequest.TotalMilliseconds}ms. Attempts: {attempts}.",
degradedOnError);
}
catch (Exception ex)
{
var message = $"HTTP Health Check failed to request '{uri}'. Time taken: {sw.ElapsedMilliseconds}ms. Attempts: {attempts}.";
Logger.ErrorException(message, ex);
return HealthCheckResultOnError(
$"FAILED. {message}",
degradedOnError);
}
finally
{
sw.Stop();
}
}
19
Source : SqlHealthCheckBuilderExtensions.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
private static ValueTask<HealthCheckResult> ExecuteSqlCheckAsync(
string name,
Func<IDbConnection> newDbConnection,
TimeSpan timeout,
bool degradedOnError,
CancellationToken cancellationToken)
{
var sw = new Stopwatch();
try
{
using (var tokenWithTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
tokenWithTimeout.CancelAfter(timeout);
sw.Start();
using (var connection = newDbConnection())
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
using (var command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = "SELECT 1";
var commandResult = Convert.ToInt64(command.ExecuteScalar());
var result = commandResult == 1
? HealthCheckResult.Healthy($"OK. {name}.")
: HealthCheckResultOnError($"FAILED. {name} SELECT failed. Time taken: {sw.ElapsedMilliseconds}ms.", degradedOnError);
return new ValueTask<HealthCheckResult>(result);
}
}
}
}
catch (Exception ex)
{
var failedResult = degradedOnError
? HealthCheckResult.Degraded(ex)
: HealthCheckResult.Unhealthy(ex);
return new ValueTask<HealthCheckResult>(failedResult);
}
}
19
Source : GenerateContent.cs
with MIT License
from aprilyush
with MIT License
from aprilyush
public (bool genStatus,string contentHtml) GenerateContentHtml(int channelId,int id)
{
try
{
Stopwatch watcher = new Stopwatch();
watcher.Start();
var templateModel = ChannelManagerCache.GetContentTemplate(channelId);
if (templateModel == null)
{
return (false, "");
}
var content = _contentApp.GetContentInfo(id);
if (content == null)
{
return (false, "");
}
//加载模板 先取缓存,没有再初始化一个并且加入缓存
this.Doreplacedent = RenderDoreplacedentCache.GetRenderDoreplacedent(templateModel.id);
if (this.Doreplacedent == null)
{
string templateFile = Path.Combine(GlobalContext.WebRootPath, templateModel.template_file);
this.Doreplacedent = new TemplateDoreplacedent(templateModel.template_content, GlobalContext.WebRootPath, templateFile);
RenderDoreplacedentCache.AddRenderDoreplacedent(templateModel.id, this.Doreplacedent);
}
this.Doreplacedent.Variables.SetValue("this", this);
//站点基本信息
var site = SiteManagerCache.GetSiteInfo();
this.Doreplacedent.Variables.SetValue("site", site);
//设置顶部导航条数据
var navigations = _contentApp.GetChannelTree();
this.Doreplacedent.Variables.SetValue("navigations", navigations);
//获取当前文章信息
this.Doreplacedent.Variables.SetValue("content", content);
string renderHtml = this.Doreplacedent.GetRenderText();
renderHtml = HtmlPlayerHandler.CreateVideo(renderHtml);
watcher.Stop();
string msg = $"渲染内容页耗时:{watcher.ElapsedMilliseconds} ms";
LoggerHelper.Info(msg);
return (true, renderHtml);
}
catch(Exception ex)
{
LoggerHelper.Exception(ex);
}
return (false, "");
}
19
Source : GenerateHome.cs
with MIT License
from aprilyush
with MIT License
from aprilyush
public void GenerateHomeHtml()
{
try
{
Stopwatch watcher = new Stopwatch();
watcher.Start();
var templateModel = TemplateManagerCache.GetHomeTemplate();
if (templateModel.id==0)
{
throw new Exception("找不到模板");
}
//加载模板 先取缓存,没有再初始化一个并且加入缓存
this.Doreplacedent = RenderDoreplacedentCache.GetRenderDoreplacedent(templateModel.id);
if (this.Doreplacedent == null)
{
string templateFile = Path.Combine(GlobalContext.WebRootPath, templateModel.template_file);
this.Doreplacedent = new TemplateDoreplacedent(templateModel.template_content, GlobalContext.WebRootPath, templateFile);
RenderDoreplacedentCache.AddRenderDoreplacedent(templateModel.id, this.Doreplacedent);
}
//this.LoadTemplate(templateModel.template_content);
this.Doreplacedent.Variables.SetValue("this", this);
//站点基本信息
var site = SiteManagerCache.GetSiteInfo();
this.Doreplacedent.Variables.SetValue("site", site);
//设置顶部导航条数据
var navigations = _generateContentApp.GetChannelTree();
this.Doreplacedent.Variables.SetValue("navigations", navigations);
//获取栏目文章模板
ElementCollection<Template> templates = this.Doreplacedent.GetChildTemplatesByName("channels");
foreach (Template template in templates)
{
string total = template.Attributes.GetValue("total", "10");
//根据模板块里定义的type属性条件取得新闻数据
var data = _generateContentApp.GetContentSummary(template.Attributes.GetValue("type"),1,int.Parse(total));
//设置变量newsdata的值
template.Variables.SetValue("contents", data);
//取得模板块下Id为newslist的标签(也即是在cnblogs_newsdata.html文件中定义的foreach标签)
//Tag tag = template.GetChildTagById("newslist");
//if (tag is ForEachTag)
//{
// //如果标签为foreach标签则设置其BeforeRender事件用于设置变量表达式{$:#.news.url}的值
// tag.BeforeRender += new System.ComponentModel.CancelEventHandler(Tag_BeforeRender);
//}
}
string contentFilePath = Path.Combine(GlobalContext.WebRootPath, "index.html");
using (var filestream = new FileStream(contentFilePath, FileMode.Create, FileAccess.ReadWrite))
{
string renderHtml = this.Doreplacedent.GetRenderText();
using (StreamWriter writer = new StreamWriter(filestream, Encoding.UTF8))
{
writer.WriteLine(renderHtml);
writer.Flush();
}
}
watcher.Stop();
string msg = $"渲染首页耗时:{watcher.ElapsedMilliseconds} ms";
LoggerHelper.Info(msg);
}
catch (Exception ex)
{
LoggerHelper.Exception(ex);
}
}
19
Source : LinuxMachineInfo.cs
with MIT License
from aprilyush
with MIT License
from aprilyush
public string GetCPURate()
{
//string output = ShellHelper.Bash("top -b -n1 | grep \"Cpu(s)\" | awk '{print $2 + $4}'");
//string cpuRate = output.Trim();
//return cpuRate;
var startTime = DateTime.UtcNow;
var startCpuUsage = Process.GetCurrentProcess().TotalProcessorTime;
var stopWatch = new Stopwatch();
// Start watching CPU
stopWatch.Start();
// Meansure something else, such as .Net Core Middleware
Thread.Sleep(100);
// Stop watching to meansure
stopWatch.Stop();
var endTime = DateTime.UtcNow;
var endCpuUsage = Process.GetCurrentProcess().TotalProcessorTime;
var cpuUsedMs = (endCpuUsage - startCpuUsage).TotalMilliseconds;
var totalMsPreplaceded = (endTime - startTime).TotalMilliseconds;
var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPreplaceded);
var cpuUsagePercentage = Math.Round(cpuUsageTotal * 100, 2);
return cpuUsagePercentage.ToString()+"%";
}
19
Source : WindowsMachineInfo.cs
with MIT License
from aprilyush
with MIT License
from aprilyush
public string GetCPURate()
{
//string output = ShellHelper.Cmd("wmic", "cpu get LoadPercentage");
//string cpuRate = output.Replace("LoadPercentage", string.Empty).Trim();
try
{
//ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PerfFormattedData_PerfOS_Processor");
//var cpuTimes = searcher.Get()
// .Cast<ManagementObject>()
// .Select(mo => new
// {
// Name = mo["Name"],
// Usage = mo["PercentProcessorTime"]
// }).ToList();
//var query = cpuTimes.Where(x => x.Name.ToString() == "_Total").Select(x => x.Usage);
//var cpuUsage = query.SingleOrDefault();
//if (cpuUsage == null)
//{
// return "0";
//}
//return cpuUsage.ToString() + "%";
var startTime = DateTime.UtcNow;
var startCpuUsage = Process.GetCurrentProcess().TotalProcessorTime;
var stopWatch = new Stopwatch();
// Start watching CPU
stopWatch.Start();
// Meansure something else, such as .Net Core Middleware
Thread.Sleep(100);
// Stop watching to meansure
stopWatch.Stop();
var endTime = DateTime.UtcNow;
var endCpuUsage = Process.GetCurrentProcess().TotalProcessorTime;
var cpuUsedMs = (endCpuUsage - startCpuUsage).TotalMilliseconds;
var totalMsPreplaceded = (endTime - startTime).TotalMilliseconds;
var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPreplaceded);
var cpuUsagePercentage = cpuUsageTotal * 100;
return cpuUsagePercentage.ToString();
}
catch(Exception ex)
{
LoggerHelper.Exception(ex);
}
return "";
}
19
Source : BrowserTests.cs
with Apache License 2.0
from aquality-automation
with Apache License 2.0
from aquality-automation
[Test]
public void Should_BePossibleTo_ExecuteAsyncJavaScript()
{
const int expectedDurationInSeconds = 1;
const int operationDurationInSeconds = 1;
new DynamicContentForm().Open();
var stopwatch = new Stopwatch();
stopwatch.Start();
AqualityServices.Browser.ExecuteAsyncScript(GetAsyncTimeoutJavaScript(expectedDurationInSeconds));
stopwatch.Stop();
var durationSeconds = stopwatch.Elapsed.TotalSeconds;
replacedert.Multiple(() =>
{
replacedert.Less(durationSeconds, (expectedDurationInSeconds + operationDurationInSeconds), "Elapsed time should be less than (js + operation) duration");
replacedert.GreaterOrEqual(durationSeconds, expectedDurationInSeconds, "Elapsed time should be greater or equal than js duration");
});
}
19
Source : SaliensBot.cs
with MIT License
from Archomeda
with MIT License
from Archomeda
public async Task ReportScore(int score)
{
for (int i = 0; i < 5; i++)
{
try
{
this.Logger?.LogMessage($"{{action}}Reporting score {{xp}}{score.ToString("#,##0")}{{action}}...");
var stopwatch = new Stopwatch();
stopwatch.Start();
var response = await SaliensApi.ReportScoreAsync(this.Token, score);
stopwatch.Stop();
// Only change the network delay if the last delay was lower
// Don't want to be too eager for an occasional spike
if (this.reportScoreNetworkDelay.TotalMilliseconds == 0 || stopwatch.Elapsed < this.reportScoreNetworkDelay)
this.reportScoreNetworkDelay = stopwatch.Elapsed;
if (!string.IsNullOrWhiteSpace(response.NewScore))
{
if (!string.IsNullOrWhiteSpace(response.NextLevelScore))
this.Logger?.LogMessage($"XP: {{oldxp}}{long.Parse(response.OldScore).ToString("#,##0")}{{reset}} -> {{xp}}{long.Parse(response.NewScore).ToString("#,##0")}{{reset}} (next level at {{reqxp}}{long.Parse(response.NextLevelScore).ToString("#,##0")}{{reset}})");
else
this.Logger?.LogMessage($"XP: {{oldxp}}{long.Parse(response.OldScore).ToString("#,##0")}{{reset}} -> {{xp}}{long.Parse(response.NewScore).ToString("#,##0")}");
}
if (response.NewLevel != response.OldLevel)
this.Logger?.LogMessage($"New level: {{oldlevel}}{response.OldLevel}{{reset}} -> {{level}}{response.NewLevel}{{reset}}");
// States
this.PlayerInfo.Score = response.NewScore;
this.PlayerInfo.Level = response.NewLevel;
this.PlayerInfo.NextLevelScore = response.NextLevelScore;
this.ActiveZone = null;
this.PlayerInfo.ActiveZoneGame = null;
this.PlayerInfo.ActiveZonePosition = null;
this.PlayerInfo.TimeInZone = TimeSpan.FromSeconds(0);
this.State = BotState.OnPlanet;
return;
}
catch (SaliensApiException ex)
{
switch (ex.EResult)
{
case EResult.Fail:
case EResult.Busy:
case EResult.RateLimitExceeded:
case EResult.TimeIsOutOfSync:
if (ex.EResult == EResult.TimeIsOutOfSync)
{
// Decrease the delay with a small amount
this.reportScoreNetworkDelay -= TimeSpan.FromMilliseconds(25);
}
this.Logger?.LogMessage($"{{warn}}Failed to submit score: {ex.Message} - Giving it a few seconds ({i + 1}/5)...");
await Task.Delay(2000);
continue;
case EResult.Expired:
case EResult.NoMatch:
default:
this.Logger?.LogMessage($"{{warn}}Failed to submit score: {ex.Message}");
ResetState();
throw;
}
}
catch (WebException ex)
{
this.Logger?.LogMessage($"{{warn}}Failed to submit score: {ex.Message} - Giving it a few seconds ({i + 1}/5)...");
await Task.Delay(2000);
continue;
}
}
// States, only set when failed
ResetState();
void ResetState()
{
this.ActiveZone = null;
this.PlayerInfo.ActiveZoneGame = null;
this.PlayerInfo.ActiveZonePosition = null;
this.State = BotState.ForcedZoneLeave;
}
}
19
Source : SaliensBot.cs
with MIT License
from Archomeda
with MIT License
from Archomeda
private async Task JoinZone(int zonePosition)
{
for (int i = 0; i < 5; i++)
{
try
{
this.Logger?.LogMessage($"{{action}}Joining {{zone}}zone {zonePosition}{{action}}...");
var stopwatch = new Stopwatch();
stopwatch.Start();
await SaliensApi.JoinZoneAsync(this.Token, zonePosition);
stopwatch.Stop();
var startDate = DateTime.Now;
// If the request took too long, resynchronize the start date
if (stopwatch.Elapsed > TimeSpan.FromSeconds(1))
{
var playerInfo = await SaliensApi.GetPlayerInfoAsync(this.Token, TimeSpan.FromSeconds(0));
var diff = (startDate - (DateTime.Now - playerInfo.TimeInZone));
if (diff > TimeSpan.FromSeconds(0))
{
this.Logger?.LogMessage($"{{action}}Recalibrated zone join time with {{value}}{diff.Negate().TotalSeconds.ToString("0.###")} seconds");
startDate = DateTime.Now - playerInfo.TimeInZone;
}
}
// States
this.ActiveZone = this.ActivePlanet.Zones[zonePosition];
this.ActiveZoneStartDate = startDate;
this.PlayerInfo.ActiveZoneGame = this.ActiveZone.GameId;
this.PlayerInfo.ActiveZonePosition = zonePosition.ToString();
this.PlayerInfo.TimeInZone = TimeSpan.FromSeconds(0);
this.State = BotState.InZone;
this.PresenceUpdateTrigger.SetSaliensPlayerState(this.PlayerInfo);
return;
}
catch (SaliensApiException ex)
{
switch (ex.EResult)
{
case EResult.Fail:
case EResult.Busy:
case EResult.RateLimitExceeded:
this.Logger?.LogMessage($"{{warn}}Failed to join zone: {ex.Message} - Giving it a few seconds ({i + 1}/5)...");
await Task.Delay(2000);
continue;
case EResult.Expired:
case EResult.NoMatch:
default:
this.Logger?.LogMessage($"{{warn}}Failed to join zone: {ex.Message}");
ResetState();
throw;
}
}
catch (WebException ex)
{
this.Logger?.LogMessage($"{{warn}}Failed to join zone: {ex.Message} - Giving it a few seconds ({i + 1}/5)...");
await Task.Delay(2000);
continue;
}
}
// States, only set when failed
ResetState();
void ResetState()
{
this.State = BotState.OnPlanet;
}
}
19
Source : SupportLogger.cs
with MIT License
from ArcturusZhang
with MIT License
from ArcturusZhang
private string GetFormattedTimestamp()
{
if (this.startStopwatch == null)
{
this.startStopwatch = new Stopwatch();
this.startStopwatch.Start();
}
return string.Format("[{0}.{1}]", this.startStopwatch.Elapsed.Seconds, this.startStopwatch.Elapsed.Milliseconds);
}
19
Source : RegionHandler.cs
with MIT License
from ArcturusZhang
with MIT License
from ArcturusZhang
protected internal bool RegionPingThreaded()
{
this.region.Ping = PingWhenFailed;
float rttSum = 0.0f;
int replyCount = 0;
Stopwatch sw = new Stopwatch();
for (this.CurrentAttempt = 0; this.CurrentAttempt < Attempts; this.CurrentAttempt++)
{
bool overtime = false;
sw.Reset();
sw.Start();
try
{
this.ping.StartPing(this.regionAddress);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("RegionPinger.RegionPingThreaded() catched an exception for ping.StartPing(). Exception: " + e + " Source: " + e.Source + " Message: " + e.Message);
break;
}
while (!this.ping.Done())
{
if (sw.ElapsedMilliseconds >= MaxMilliseconsPerPing)
{
overtime = true;
break;
}
#if !NETFX_CORE
System.Threading.Thread.Sleep(0);
#endif
}
sw.Stop();
int rtt = (int)sw.ElapsedMilliseconds;
if (IgnoreInitialAttempt && this.CurrentAttempt == 0)
{
// do nothing.
}
else if (this.ping.Successful && !overtime)
{
rttSum += rtt;
replyCount++;
this.region.Ping = (int)((rttSum) / replyCount);
}
#if !NETFX_CORE
System.Threading.Thread.Sleep(10);
#endif
}
this.Done = true;
this.ping.Dispose();
this.onDoneCall(this.region);
return false;
}
19
Source : ArtworkManager.cs
with MIT License
from Arefu
with MIT License
from Arefu
public void ConvertAll(IEnumerable<Artwork> artworks)
{
var artworkList = artworks.ToList();
var destinationPath = _resourceRepo.GetOutputPath();
long progress = 0;
var numberOfArtwork = artworkList.ToList().Count();
var stopwatch = new Stopwatch();
stopwatch.Start();
_logger.LogInformation(Localization.InformationConvertingImages);
var settings = new ProcessImageSettings
{
SaveFormat = FileFormat.Jpeg,
JpegQuality = 92,
};
foreach (var artwork in artworkList)
{
var imageFile = artwork.ReplacementImageFile;
if (artwork.IsPendulum)
{
ConvertPendulumArtwork(destinationPath, artwork.GameImageFileName, imageFile, settings, artwork.ZibFilename);
}
else
{
ConvertNormalArtwork(destinationPath, artwork.GameImageFileName, imageFile, settings, artwork.ZibFilename);
}
_logger.LogInformation(Localization.InformationProcessingProgress(progress, numberOfArtwork, artwork.GameImageCardName));
progress++;
}
stopwatch.Stop();
_logger.LogInformation(Localization.InformationProcessingDone(numberOfArtwork, MiliToSec(stopwatch.ElapsedMilliseconds)));
}
19
Source : ArtworkManager.cs
with MIT License
from Arefu
with MIT License
from Arefu
public List<Artwork> UpdateArtworkModelsWithReplacement(IEnumerable<Artwork> artworkList, bool useIncludedPendulum)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
var artworks = artworkList.ToList();
var numberOfArtwork = artworks.Count;
long progress = 0;
foreach (var artwork in artworks)
{
if (useIncludedPendulum && artwork.IsPendulum)
{
ProcessArtworkAsPendulum(artwork);
}
else
{
ProcessArtwork(artwork);
}
progress++;
_logger.LogInformation(Localization.InformationProcessingProgress(progress, numberOfArtwork, artwork.GameImageCardName));
}
stopwatch.Stop();
_logger.LogInformation(Localization.InformationProcessingDone(artworks.Count, MiliToSec(stopwatch.ElapsedMilliseconds)));
return artworks;
}
19
Source : Renderer.cs
with MIT License
from Arghonot
with MIT License
from Arghonot
public void Render()
{
Stopwatch watch = new Stopwatch();
watch.Start();
Noise2D map = new Noise2D(
size,
size / 2,
GetInputValue<SerializableModuleBase>("Input", this.Input));
map.GenerateSpherical(
south,
north,
west,
east);
tex = map.GetTexture(grad);
tex.Apply();
watch.Stop();
RenderTime = watch.ElapsedMilliseconds;
}
19
Source : ProfileQueryDecorator.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public TResult Execute(TQuery query)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
var result = _decorated.Execute(query);
stopWatch.Stop();
_logger.Trace(() => string.Format("Query<{0}> executed in {1}ms", query.GetType(), stopWatch.ElapsedMilliseconds));
return result;
}
19
Source : ProfileQueryDecorator.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public async Task<TResult> ExecuteAsync(TQuery query, CancellationToken ctk = default(CancellationToken))
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
var result = await _decorated.ExecuteAsync(query, ctk).ConfigureAwait(false);
stopWatch.Stop();
_logger.Trace(() => string.Format("Query<{0}> executed in {1}ms", query.GetType(), stopWatch.ElapsedMilliseconds));
return result;
}
19
Source : ProfileRequestDecorator.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public TResponse Execute(TRequest request)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
var result = _decorated.Execute(request);
stopWatch.Stop();
_logger.Trace(() => string.Format("Request<{0}> executed in {1}ms", request.GetType(), stopWatch.ElapsedMilliseconds));
return result;
}
19
Source : ProfileRequestDecorator.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public async Task<TResponse> ExecuteAsync(TRequest request, CancellationToken ctk = default(CancellationToken))
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
var result = await _decorated.ExecuteAsync(request, ctk).ConfigureAwait(false);
stopWatch.Stop();
_logger.Trace(() => string.Format("Request<{0}> executed in {1}ms", request.GetType(), stopWatch.ElapsedMilliseconds));
return result;
}
19
Source : SelectionLogic.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
public void SetSelection(TreeNode node)
{
for (int i = 0; i < SelectionCanvas.Children.Count; i++)
{
if (SelectionCanvas.Children[i] is Canvas can)
{
_ = Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() =>
{
can.ZIndex = 0;
});
}
}
ResetActionColours();
if (node != null)
{
SkiaSharp.SKColor selectionColor = SelectionSKColor;
SkiaSharp.SKColor selectionChildColor = SelectionChildSKColor;
if (HighlightMode == HighlightModes.ParentAndChildren || HighlightMode == HighlightModes.Auto)
{
Stopwatch sw = new Stopwatch();
sw.Start();
List<string> childIds = new List<string>((from el in node.GetChildrenRecursiveLazy() select el.Id).Skip(1));
foreach (string childId in childIds)
{
foreach ((double, SKRenderAction) pth in FindPaths(FullSelectionCanvas, childId))
{
pth.Item2.ZIndex = 1;
ChangeActionColour(pth.Item2, selectionChildColor);
}
if (sw.ElapsedMilliseconds > MaxHighlightTime)
{
ResetActionColours();
break;
}
}
sw.Stop();
}
var nodePaths = FindPaths(FullSelectionCanvas, node.Id);
foreach ((double, SKRenderAction) pth in nodePaths)
{
pth.Item2.ZIndex = 2;
ChangeActionColour(pth.Item2, selectionColor);
}
FullSelectionCanvas.InvalidateZIndex();
this.FindControl<StackPanel>("SelectionContainerPanel").Children.Clear();
this.FindControl<TextBlock>("SelectedNodeTextBlock").Text = node.ToString();
int nodeCount = 0;
int tipCount = 0;
List<string> names = new List<string>();
foreach (TreeNode child in node.GetChildrenRecursiveLazy())
{
nodeCount++;
if (child.Children.Count == 0)
{
tipCount++;
if (!string.IsNullOrEmpty(child.Name))
{
names.Add(child.Name);
}
}
}
this.FindControl<TextBlock>("SelectedNodeNodeCountBlock").Text = nodeCount.ToString() + " node" + (nodeCount > 1 ? "s" : "");
this.FindControl<TextBlock>("SelectedNodeLeafCountBlock").Text = tipCount.ToString() + " tip" + (tipCount > 1 ? "s" : "");
this.FindControl<TextBlock>("SelectedNodeNamedLeafCountBlock").Text = names.Count.ToString() + (names.Count > 1 ? " named tips:" : " named tip:");
StringBuilder text = new StringBuilder();
for (int i = 0; i < names.Count; i++)
{
if (i < names.Count - 1)
{
text.AppendLine(names[i]);
}
else
{
text.Append(names[i]);
}
}
this.FindControl<TextBox>("SelectedNodeLeavesBox").Text = text.ToString();
int ind = 0;
foreach (KeyValuePair<string, object> kvp in node.Attributes)
{
Grid attributeString = new Grid() { Margin = new Avalonia.Thickness(5, 5, 0, 0), Height = 20 };
attributeString.Clreplacedes.Add("AttributeLine");
attributeString.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
attributeString.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
attributeString.ColumnDefinitions.Add(new ColumnDefinition(20, GridUnitType.Pixel));
attributeString.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
TrimmedTextBox2 attributeNameBlock = new TrimmedTextBox2() { MaxWidth = 120, Margin = new Avalonia.Thickness(5, 0, 0, 0) };
attributeNameBlock.FontFamily = "resm:TreeViewer.Fonts.?replacedembly=TreeViewer#Open Sans";
attributeNameBlock.FontSize = 13;
attributeNameBlock.FontWeight = Avalonia.Media.FontWeight.Bold;
attributeNameBlock.Text = kvp.Key + ":";
attributeNameBlock.EllipsisText = "... :";
AvaloniaBugFixes.SetToolTip(attributeNameBlock, new TextBlock() { Text = kvp.Key, FontWeight = Avalonia.Media.FontWeight.Regular });
attributeString.Children.Add(attributeNameBlock);
double nameWidth = AvaloniaBugFixes.MeasureTextWidth(attributeNameBlock.Text, attributeNameBlock.FontFamily, attributeNameBlock.FontStyle, attributeNameBlock.FontWeight, attributeNameBlock.FontSize);
TrimmedTextBox2 valueBlock = new TrimmedTextBox2() { FontSize = 13, Margin = new Avalonia.Thickness(0), MaxWidth = 0, Background = Avalonia.Media.Brushes.Transparent };
string attributeType = node.GetAttributeType(kvp.Key);
if (attributeType == "String")
{
string tipText = StringAttributeFormatter(kvp.Value);
if (!string.IsNullOrEmpty(tipText))
{
valueBlock.Text = tipText;
}
}
else if (attributeType == "Number")
{
string tipText = NumberAttributeFormatter(kvp.Value);
if (!string.IsNullOrEmpty(tipText))
{
valueBlock.Text = tipText;
}
}
AvaloniaBugFixes.SetToolTip(valueBlock, new TextBlock() { Text = valueBlock.Text, FontWeight = Avalonia.Media.FontWeight.Regular });
Grid valueBlockParent = new Grid() { Margin = new Avalonia.Thickness(6, 0, 5, 0) };
Grid.SetColumn(valueBlockParent, 1);
valueBlockParent.Children.Add(valueBlock);
valueBlockParent.PropertyChanged += (s, e) =>
{
if (e.Property == Grid.BoundsProperty)
{
valueBlock.MaxWidth = ((Avalonia.Rect)e.NewValue).Width - 10;
}
};
TextBox editValueBox = new TextBox() { Margin = new Avalonia.Thickness(0, 0, 0, 0), Padding = new Avalonia.Thickness(5, 0, 5, 0), IsVisible = false, Height = 20, MaxHeight = 20, MinHeight = 20, MaxWidth = 0, FontSize = 13, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, VerticalContentAlignment = Avalonia.Layout.VerticalAlignment.Center };
editValueBox.Clreplacedes.Add("EditValueBox");
Button editButton = new Button() { Width = 20, Height = 20, Background = Avalonia.Media.Brushes.Transparent, Content = new DPIAwareBox(Icons.GetIcon16("TreeViewer.replacedets.Pencil")) { Width = 16, Height = 16 }, Padding = new Avalonia.Thickness(2) };
editButton.Clreplacedes.Add("SideBarButton");
editButton.Clreplacedes.Add("AttributeEditButton");
Grid.SetColumn(editButton, 2);
Button okButton = new Button() { Width = 20, Height = 20, Background = Avalonia.Media.Brushes.Transparent, Content = new Avalonia.Controls.Shapes.Path() { Width = 10, Height = 10, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, Data = Icons.TickGeometry, StrokeThickness = 2 }, Padding = new Avalonia.Thickness(2), IsVisible = false };
okButton.Clreplacedes.Add("SideBarButton");
okButton.Clreplacedes.Add("AttributeEditButton");
Grid.SetColumn(okButton, 2);
Button cancelButton = new Button() { Width = 20, Height = 20, Background = Avalonia.Media.Brushes.Transparent, Content = new Avalonia.Controls.Shapes.Path() { Width = 10, Height = 10, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, Data = Icons.CrossGeometry, StrokeThickness = 2 }, Padding = new Avalonia.Thickness(2), IsVisible = false };
cancelButton.Clreplacedes.Add("SideBarButton");
cancelButton.Clreplacedes.Add("AttributeEditButton");
Grid.SetColumn(cancelButton, 3);
attributeString.Children.Add(editButton);
attributeString.Children.Add(okButton);
attributeString.Children.Add(cancelButton);
attributeString.Children.Add(valueBlockParent);
Grid editValueBoxParent = new Grid();
Grid.SetColumn(editValueBoxParent, 1);
editValueBoxParent.Children.Add(editValueBox);
editValueBoxParent.PropertyChanged += (s, e) =>
{
if (e.Property == Grid.BoundsProperty)
{
editValueBox.MaxWidth = ((Avalonia.Rect)e.NewValue).Width - 10;
}
};
attributeString.Children.Add(editValueBoxParent);
editButton.Click += (s, e) =>
{
valueBlock.IsVisible = false;
editValueBox.Text = valueBlock.Text;
editValueBox.IsVisible = true;
editValueBox.SelectAll();
editValueBox.Focus();
editButton.Clreplacedes.Add("EditButtonHidden");
okButton.IsVisible = true;
cancelButton.IsVisible = true;
};
valueBlock.DoubleTapped += (s, e) =>
{
valueBlock.IsVisible = false;
editValueBox.Text = valueBlock.Text;
editValueBox.IsVisible = true;
editValueBox.SelectAll();
editValueBox.Focus();
editButton.Clreplacedes.Add("EditButtonHidden");
okButton.IsVisible = true;
cancelButton.IsVisible = true;
};
cancelButton.Click += (s, e) =>
{
valueBlock.IsVisible = true;
editValueBox.IsVisible = false;
editButton.Clreplacedes.Remove("EditButtonHidden");
okButton.IsVisible = false;
cancelButton.IsVisible = false;
};
async void commitAttributeChange()
{
valueBlock.IsVisible = !false;
editValueBox.IsVisible = !true;
editButton.Clreplacedes.Remove("EditButtonHidden");
okButton.IsVisible = !true;
cancelButton.IsVisible = !true;
string value = editValueBox.Text;
if (attributeType == "Number")
{
if (!double.TryParse(editValueBox.Text, out _))
{
await new MessageBox("Attention", "Could not interpret the attribute as a valid Number!").ShowDialog2(this);
return;
}
}
List<string> nodeNames = node.GetNodeNames();
if (nodeNames.Count == 0 || !node.IsLastCommonAncestor(nodeNames))
{
MessageBox box = new MessageBox("Attention!", "The requested node cannot be uniquely identified! Please, make sure that it either has a Name or enough of its children have Names.");
await box.ShowDialog2(this);
return;
}
string id = this.SelectedNode.Id;
Action<Dictionary<string, object>> changeParameter = AddFurtherTransformation((from el in Modules.FurtherTransformationModules where el.Id == "8de06406-68e4-4bd8-97eb-2185a0dd1127" select el).First());
changeParameter(new Dictionary<string, object>() { { "Node:", nodeNames.ToArray() }, { "Attribute:", kvp.Key }, { "Attribute type:", attributeType }, { "New value:", value } });
await UpdateFurtherTransformations(this.FurtherTransformations.Count - 1);
SetSelection(TransformedTree.GetNodeFromId(id));
};
editValueBox.KeyDown += (s, e) =>
{
if (e.Key == Key.Enter)
{
commitAttributeChange();
}
else if (e.Key == Key.Escape)
{
valueBlock.IsVisible = true;
editValueBox.IsVisible = false;
editButton.Clreplacedes.Remove("EditButtonHidden");
okButton.IsVisible = false;
cancelButton.IsVisible = false;
}
};
okButton.Click += (s, e) =>
{
commitAttributeChange();
};
this.FindControl<StackPanel>("SelectionContainerPanel").Children.Add(attributeString);
ind++;
}
IsSelectionAvailable = true;
SelectedNode = node;
if (!SelectionPanelManuallyClosed)
{
IsSelectionPanelOpen = true;
}
}
else
{
SelectionCanvas.InvalidateVisual();
IsSelectionAvailable = false;
SelectedNode = null;
this.FindControl<StackPanel>("SelectionContainerPanel").Children.Clear();
if (IsSelectionPanelOpen)
{
SelectionPanelManuallyClosed = false;
}
IsSelectionPanelOpen = false;
}
}
See More Examples