public async Task CancelUploadSession(OneDriveUploadSession session) { // If the session is already cancelled, nothing to do if (session.State == OneDriveFileUploadState.Cancelled) { return; } CounterManager.LogSyncJobCounter( Constants.CounterNames.ApiCall, 1, new CounterDimension( Constants.DimensionNames.OperationName, "CancelUploadSession")); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Delete, session.UploadUrl); HttpResponseMessage response = await this.SendOneDriveRequest(request).ConfigureAwait(false); if (response.StatusCode == HttpStatusCode.NoContent) { session.State = OneDriveFileUploadState.Cancelled; return; } Logger.Warning( "Failed to cancel upload session for file {0} (ParenId={1})", session.ItemName, session.ParentId); LogRequest(request, this.oneDriveHttpClient.BaseAddress, true); LogResponse(response, true); throw new OneDriveHttpException("Failed to cancel the upload session.", response.StatusCode); }
IEnumerator Restart() { yield return(new WaitForSeconds(4)); CounterManager.restartValues(); SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); }
private static void LogApiCallCounter(HttpRequestMessage request) { // A backblaze API request should have the following formats: // https://<domain>/b2api/v1/b2_authorize_account // https://<domain>/b2api/v1/b2_upload_file/foo/bar // We want to isolate the 'b2_' segment and extract the operation name // Find the segment containing "b2api/" var segments = request.RequestUri.Segments; int idx = segments.IndexOf("b2api/", true); if (idx < 0) { throw new Exception("Failed to locate 'b2api' segment in URI " + request.RequestUri); } // The op name will be 2 segments after the b2api/ segment. Ensure that it exists if (segments.Length <= idx + 2) { throw new Exception("URI " + request.RequestUri + " is not formatted correctly (idx=" + idx + ")"); } // Isoate the segment string opNameSegment = segments[idx + 2]; // Ensure it starts with b2_ in case there is a strange call Pre.Assert(opNameSegment.StartsWith("b2_")); CounterManager.LogSyncJobCounter( Constants.CounterNames.ApiCall, 1, new CounterDimension(Constants.DimensionNames.ApiCallName, opNameSegment.Trim('/'))); }
private static void LogApiCallCounter(HttpRequestMessage request, string opName) { if (string.IsNullOrWhiteSpace(opName)) { // OpName was not provided, so try to figure it out if (request.RequestUri.Query.Contains("comp=list") && request.Method == HttpMethod.Get) { opName = "ListContainers"; } } if (opName == null) { string message = string.Format( "Failed to determine counter op name from Uri {0}", request.RequestUri); #if DEBUG throw new Exception(message); #else Logger.Warning(message); return; #endif } CounterManager.LogSyncJobCounter( Constants.CounterNames.ApiCall, 1, new CounterDimension(Constants.DimensionNames.ApiCallName, opName)); }
public Form1() { InitializeComponent(); BindCounterTypesComboBox(); uIHandler = new UIHandler(ListBoxCounters, PanelControls); counterManager = new CounterManager(uIHandler.NotifyCompleted, uIHandler.UpdateStatus); }
// ========================================================================================= Timer event handler private static void MaintenanceTimerElapsed(object state) { // Increment the global cycle counter. Different maintenance tasks may // rely on this to decide whether they should be executed in the // current cycle. Interlocked.Increment(ref _currentCycle); // preventing the counter from overflow if (_currentCycle > 100000) { _currentCycle = 0; } if (SnTrace.System.Enabled) { SnTrace.System.Write("CPU: {0}%, RAM: {1} KBytes available (working set: {2} bytes)", CounterManager.GetCPUUsage(), CounterManager.GetAvailableRAM(), Environment.WorkingSet); } // start maintenance tasks asychronously Task.Run(() => CleanupFiles()); Task.Run(() => StartADSync()); }
/* ============================================================================== Init */ public ClusterChannel(IClusterMessageFormatter formatter, ClusterMemberInfo clusterMemberInfo) { _incomingMessages = new List <ClusterMessage>(); CounterManager.Reset("IncomingMessages"); CounterManager.Reset("TotalMessagesToProcess"); m_formatter = formatter; m_clusterMemberInfo = clusterMemberInfo; // initiate processing threads for (var i = 0; i < Configuration.Messaging.MessageProcessorThreadCount; i++) { try { var thstart = new ParameterizedThreadStart(CheckProcessableMessages); var thread = new Thread(thstart); thread.Name = i.ToString(); thread.Start(); SnTrace.Messaging.Write("ClusterChannel: 'CheckProcessableMessages' thread started. ManagedThreadId: {0}", thread.ManagedThreadId); } catch (Exception ex) { SnLog.WriteException(ex); } } }
static void Main(string[] args) { counters = new CounterManager(uIHandler.NotifyCompleted, uIHandler.UpdateStatus); foreach (ICounter counter in uIHandler.CollectCountersInfo()) { counters.AddCounter(counter); } if (counters.ActiveCounters.Count == 0) { Console.WriteLine("No counter created"); } else { Console.WriteLine($"Created {counters.ActiveCounters.Count} counter(s):"); foreach (ICounter counter in counters.ActiveCounters) { Console.WriteLine(counter); } Console.WriteLine($"Press any key to start"); Console.ReadKey(true); counters.StartAllCounters(); } Console.ReadKey(true); }
static void Main(string[] args) { //use switch statement to determine file type or get input parameter var sourceUrl = @"C:\lorem.txt"; var outputUrl = @"C:\output.csv"; //assume we chose .txt for src and .csv for output file types InputFile src = new InputFile(sourceUrl, new TextContentHandler()); OutputFile output = new OutputFile(outputUrl, new CSVContentHandler()); //test swapping file types //IInputFile src = new InputFile(sourceUrl, new CSVContentHandler()); //IOutputFile output = new OutputFile(outputUrl, new TextContentHandler()); CounterManager mgr = new CounterManager(src, output); try { mgr.HandleCount(); } catch (Exception e) { Console.WriteLine(e.Message); } Console.ReadLine(); }
public void StopCounter() { ICounterManager manager = new CounterManager(CPU_Processor_Time_Counter); bool startState; bool endState; //start counter on its own thread var thread = new Thread(() => manager.StartCounter()); try { thread.Start(); startState = manager.GetStartStopState(); manager.StopCounter(); endState = manager.GetStartStopState(); Assert.IsFalse(startState); Assert.IsTrue(endState); } catch (Exception e) { Console.WriteLine(e); } thread.Abort(); }
static void Main(string[] args) { #if DEBUG // use the args below to specify output text filename once that's implemented //args = new[] { "wap.txt", "out.txt" }; args = new[] { "test.txt" }; #endif CounterManager capp = new CounterManager(args); }
private void Kill() { if (isAlive) { CounterManager.addScore(30); } isAlive = false; StartCoroutine(KillToad()); }
private void Start() { m_playerManager = GetComponentInChildren <PlayerManager>(); Duration = m_duration; m_levelSetting = new LevelSetting(); m_counterGameplayManager = new CounterManager(); }
void Awake() { if (instance != null) { Debug.LogWarning("More than one instance of CounterManager found!"); return; } instance = this; }
// ============================================================================================ IHttpModule public void Init(HttpApplication context) { CounterManager.Reset("DelayingRequests"); context.BeginRequest += OnEnter; context.EndRequest += OnEndRequest; context.AuthenticateRequest += OnAuthenticate; context.AuthorizeRequest += OnAuthorize; context.PreSendRequestHeaders += new EventHandler(OnPreSendRequestHeaders); }
// See https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_createuploadsession public async Task <OneDriveUploadSession> CreateUploadSession(string parentItemId, string name, long length) { if (string.IsNullOrWhiteSpace(parentItemId)) { throw new ArgumentNullException(nameof(parentItemId)); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } // TODO: Check for the maximum file size limit if (length <= 0) { throw new ArgumentOutOfRangeException(nameof(length)); } if (this.uploadSessions.Any(s => s.ParentId == parentItemId && s.ItemName == name)) { throw new InvalidOperationException("An upload session for this item already exists."); } HttpRequestMessage request = new HttpRequestMessage( HttpMethod.Post, string.Format("/v1.0/drive/items/{0}:/{1}:/upload.createSession", parentItemId, HttpUtility.UrlEncode(name))); CounterManager.LogSyncJobCounter( Constants.CounterNames.ApiCall, 1, new CounterDimension( Constants.DimensionNames.OperationName, "CreateUploadSession")); HttpResponseMessage response = await this.SendOneDriveRequest(request).ConfigureAwait(false); JObject responseObject = await response.Content.ReadAsJObjectAsync().ConfigureAwait(false); var newSession = new OneDriveUploadSession( parentItemId, name, responseObject["uploadUrl"].Value <string>(), responseObject["expirationDateTime"].Value <DateTime>(), length); Logger.Info( "Created OneDrive upload session with parentItemId={0}, name={1}, expirationDateTime={2}", parentItemId, name, newSession.ExpirationDateTime); this.uploadSessions.Add(newSession); return(newSession); }
public void GetSystemUpTime() { ICounterManager manager = new CounterManager(System_Up_Time); var firstValue = TimeSpan.Parse(manager.GetCounterValue()); Thread.Sleep(1000); var secondValue = TimeSpan.Parse(manager.GetCounterValue()); Assert.Less(firstValue, secondValue); }
private void UpdateViewBuffer(CounterManager counterManager) { lock (viewBuffer) { viewBuffer.Clear(); foreach (ICounter counter in counterManager.ActiveCounters) { viewBuffer.Add(new CounterViewItem(counter, counter == counterManager.LastActiveCounter)); } } }
public int GetScore(CounterManager counterManager) { //(100 * 10) - ((10 - 10) * 50) * -1 int command = (100 * BestCommand) - ((BestCommand - counterManager.Command) * 50) * -1; int objective = counterManager.Objective * 200; int gem = counterManager.Gem * 50; Score = command + objective + gem; return(Score); }
// Mario collides the base private void OnTriggerEnter2D(Collider2D other) { var isSuperMarioHead = other.tag == "SuperMarioHead"; if (isSuperMarioHead) { CounterManager.addScore(10); var position = new Vector3(transform.position.x, transform.position.y + 1f, transform.position.z); Instantiate(Coin, position, transform.rotation); StartCoroutine(KillObject()); } }
//public static Tuple<int, int> GetGapSizeInfo() //{ // _gapRWSync.EnterReadLock(); // try // { // var gapSize = 0; // for (int i = 0; i < GapSegments; i++) // gapSize += _gaps[i].Count; // _peakGapSize = Math.Max(_peakGapSize, gapSize); // return new Tuple<int, int>(gapSize, _peakGapSize); // } // finally // { // _gapRWSync.ExitReadLock(); // } //} public static void SetGapSizeCounter() { var result = 0; for (int i = 0; i < GapSegments; i++) { result += _gaps[i].Count; } // set perf counter CounterManager.SetRawValue(COUNTERNAME_GAPSIZE, Convert.ToInt64(result)); }
public async Task SendUploadFragment(OneDriveUploadSession uploadSession, byte[] fragmentBuffer, long offset) { switch (uploadSession.State) { case OneDriveFileUploadState.NotStarted: uploadSession.State = OneDriveFileUploadState.InProgress; break; case OneDriveFileUploadState.Completed: throw new OneDriveException("Cannot upload fragment to completed upload session."); case OneDriveFileUploadState.Faulted: throw new OneDriveException("Cannot upload fragment to faulted upload session."); case OneDriveFileUploadState.Cancelled: throw new OneDriveException("Cannot upload fragment to cancelled upload session."); } HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, uploadSession.UploadUrl) { Content = new ByteArrayContent(fragmentBuffer) }; request.Content.Headers.ContentLength = fragmentBuffer.LongLength; request.Content.Headers.ContentRange = new ContentRangeHeaderValue( offset, offset + fragmentBuffer.Length - 1, uploadSession.Length); CounterManager.LogSyncJobCounter( Constants.CounterNames.ApiCall, 1, new CounterDimension( Constants.DimensionNames.OperationName, "SendUploadFragment")); var response = await this.SendOneDriveRequest(request).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { uploadSession.State = OneDriveFileUploadState.Faulted; } if (response.StatusCode == HttpStatusCode.Created || response.StatusCode == HttpStatusCode.OK) { // 201 indicates that the upload is complete. uploadSession.State = OneDriveFileUploadState.Completed; uploadSession.Item = await response.Content.ReadAsJsonAsync <Item>().ConfigureAwait(false); this.uploadSessions.Remove(uploadSession); } }
// Init private void Awake() { stateManager = gameObject.GetComponent <StateManager>(); playerManager = gameObject.GetComponent <PlayerManager>(); counterManager = gameObject.GetComponent <CounterManager>(); storageManager = gameObject.GetComponent <StorageManager>(); customerManager = gameObject.GetComponent <CustomerManager>(); tutorialManager = gameObject.GetComponent <TutorialManager>(); tutorialState = GameObject.FindGameObjectWithTag("TutorialState").GetComponent <TutorialState>(); itemManager = gameObject.GetComponent <ItemManager>(); soundManager = GameObject.FindGameObjectWithTag("Sound").GetComponent <SoundManager>(); selectorController = GameObject.FindGameObjectWithTag("Selector").GetComponent <SelectorController>(); }
// Start is called before the first frame update void Awake() { if (Instance && Instance != this) { Destroy(gameObject); } else { DontDestroyOnLoad(gameObject); Instance = this; counterText.text = "0/" + max; } }
public void GetProcessorTime() { ICounterManager manager = new CounterManager(CPU_Processor_Time_Counter); //Act var firstValue = float.Parse(manager.GetCounterValue()); Thread.Sleep(1000); var secondValue = float.Parse(manager.GetCounterValue()); // Assert Assert.IsTrue(firstValue > 0 && secondValue > 0); }
internal virtual void OnMessageReceived(Stream messageBody) { ClusterMessage message = m_formatter.Deserialize(messageBody); lock (_messageListSwitchSync) { _incomingMessages.Add(message); CounterManager.SetRawValue("IncomingMessages", Convert.ToInt64(_incomingMessages.Count)); var totalMessages = _incomingMessages.Count + _messagesCount; CounterManager.SetRawValue("TotalMessagesToProcess", Convert.ToInt64(totalMessages)); //_incomingMessageSignal.Set(); } }
protected override void OnStart(string[] args) { serviceThread = new Thread(new ThreadStart(() => { try { //set up logging string eventLogSource = "PC2CW Service"; if (!EventLog.SourceExists(eventLogSource)) { EventLog.CreateEventSource(eventLogSource, "Application"); } //setup dependencies var builder = new ContainerBuilder(); EventLog.WriteEntry(eventLogSource, "Setting up dependencies", EventLogEntryType.Information); //todo: configuration based provider setup builder.Register <IisServerWorkerProcessCpuLister>(c => new IisServerWorkerProcessCpuLister()).As <IPerformanceCounterLister>(); builder.Register <IisServerSiteTrafficCountLister>(c => new IisServerSiteTrafficCountLister()).As <IPerformanceCounterLister>(); //setup manager manager = new CounterManager(builder); manager.WriteToLog = x => { //do not log every single status report, as this means we're storing all the stats in the event log! // this should only be used in debug #if DEBUG string message = String.Format("{0:yyyyMMdd-HHmmss} {1}", DateTime.Now, x); EventLog.WriteEntry(eventLogSource, message, EventLogEntryType.Information); #endif }; EventLog.WriteEntry(eventLogSource, "Starting CounterManager...", EventLogEntryType.Information); manager.Start(); EventLog.WriteEntry(eventLogSource, "CounterManager started", EventLogEntryType.Information); } catch (Exception ex) { //todo: log eception stopping string eventLogSource = "PC2CW Service"; if (!EventLog.SourceExists(eventLogSource)) { EventLog.CreateEventSource(eventLogSource, "Application"); } EventLog.WriteEntry(eventLogSource, "Error in main service thread: " + ex.Message + Environment.NewLine + ex.StackTrace, EventLogEntryType.Error); } })); serviceThread.Start(); }
public void UpdateStatus(CounterManager counterManager) { Console.Clear(); foreach (ICounter counter in counterManager.ActiveCounters) { string prefix = " "; if (counter == counterManager.LastActiveCounter) { prefix = ">"; } Console.WriteLine($"{prefix}{counter.ToString()}"); } }
void Awake() { audios = GetComponents <AudioSource>(); mainAudioSource = audios[1]; effectsAudioSource = audios[0]; clipDead = Resources.Load <AudioClip>("Sounds/smb_mariodie"); winGame = Resources.Load <AudioClip>("Sounds/smb_stage_clear"); Score.text = CounterManager.getScore().ToString(StringFormat); Coins.text = CounterManager.getCoins().ToString(); Timer.text = InitialTime.ToString(StringFormat); marioController.OnKilled += RestartLevel; }
// Init private void Awake() { stateManager = gameObject.GetComponent <StateManager>(); counterManager = gameObject.GetComponent <CounterManager>(); itemManager = gameObject.GetComponent <ItemManager>(); cameraManager = gameObject.GetComponent <CameraManager>(); storageManager = gameObject.GetComponent <StorageManager>(); itemInteractions = gameObject.GetComponent <ItemInteractions>(); soundManager = GameObject.FindGameObjectWithTag("Sound").GetComponent <SoundManager>(); tutorialManager = gameObject.GetComponent <TutorialManager>(); tutorialState = GameObject.FindGameObjectWithTag("TutorialState").GetComponent <TutorialState>(); chef = GameObject.FindGameObjectWithTag("Chef"); selectorController = GameObject.FindGameObjectWithTag("Selector").GetComponent <SelectorController>(); }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MonitorForm)); this.panel2 = new System.Windows.Forms.Panel(); this.counterManager = new Osherove.PerfPlus.Controls.CounterManager(); this.lblScale = new System.Windows.Forms.Label(); this.cmdScaleMinus = new System.Windows.Forms.Button(); this.cmdScalePlus = new System.Windows.Forms.Button(); this.cmbTargetASPApp = new System.Windows.Forms.ComboBox(); this.splitter1 = new System.Windows.Forms.Splitter(); this.tabMenu = new System.Windows.Forms.ContextMenu(); this.menuItem9 = new System.Windows.Forms.MenuItem(); this.menuItem14 = new System.Windows.Forms.MenuItem(); this.menuItem10 = new System.Windows.Forms.MenuItem(); this.menuItem11 = new System.Windows.Forms.MenuItem(); this.menuItem13 = new System.Windows.Forms.MenuItem(); this.menuItem12 = new System.Windows.Forms.MenuItem(); this.monView = new Osherove.PerfPlus.Controls.SysMonitorView(); this.panel2.SuspendLayout(); this.SuspendLayout(); // // panel2 // this.panel2.BackColor = System.Drawing.SystemColors.Control; this.panel2.Controls.Add(this.counterManager); this.panel2.Controls.Add(this.lblScale); this.panel2.Controls.Add(this.cmdScaleMinus); this.panel2.Controls.Add(this.cmdScalePlus); this.panel2.Controls.Add(this.cmbTargetASPApp); this.panel2.Dock = System.Windows.Forms.DockStyle.Left; this.panel2.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(177))); this.panel2.Location = new System.Drawing.Point(0, 0); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(224, 486); this.panel2.TabIndex = 9; // // counterManager // this.counterManager.ActivateNewTabCallback = null; this.counterManager.Dock = System.Windows.Forms.DockStyle.Bottom; this.counterManager.Location = new System.Drawing.Point(0, 158); this.counterManager.MasterFolder = null; this.counterManager.Name = "counterManager"; this.counterManager.Size = new System.Drawing.Size(224, 328); this.counterManager.SysMonHelper = null; this.counterManager.TabIndex = 12; // // lblScale // this.lblScale.AutoSize = true; this.lblScale.Location = new System.Drawing.Point(16, 16); this.lblScale.Name = "lblScale"; this.lblScale.Size = new System.Drawing.Size(113, 19); this.lblScale.TabIndex = 7; this.lblScale.Text = "Target ASP app:"; // // cmdScaleMinus // this.cmdScaleMinus.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.cmdScaleMinus.Location = new System.Drawing.Point(72, 88); this.cmdScaleMinus.Name = "cmdScaleMinus"; this.cmdScaleMinus.Size = new System.Drawing.Size(32, 23); this.cmdScaleMinus.TabIndex = 10; this.cmdScaleMinus.Text = "-"; // // cmdScalePlus // this.cmdScalePlus.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.cmdScalePlus.Location = new System.Drawing.Point(32, 88); this.cmdScalePlus.Name = "cmdScalePlus"; this.cmdScalePlus.Size = new System.Drawing.Size(32, 23); this.cmdScalePlus.TabIndex = 9; this.cmdScalePlus.Text = "+"; // // cmbTargetASPApp // this.cmbTargetASPApp.Location = new System.Drawing.Point(16, 40); this.cmbTargetASPApp.Name = "cmbTargetASPApp"; this.cmbTargetASPApp.Size = new System.Drawing.Size(121, 24); this.cmbTargetASPApp.TabIndex = 8; this.cmbTargetASPApp.Text = "__Total__"; // // splitter1 // this.splitter1.Location = new System.Drawing.Point(224, 0); this.splitter1.Name = "splitter1"; this.splitter1.Size = new System.Drawing.Size(8, 486); this.splitter1.TabIndex = 12; this.splitter1.TabStop = false; // // tabMenu // this.tabMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem9, this.menuItem14, this.menuItem10, this.menuItem11, this.menuItem13, this.menuItem12}); // // menuItem9 // this.menuItem9.DefaultItem = true; this.menuItem9.Index = 0; this.menuItem9.Text = "&Close Tab"; // // menuItem14 // this.menuItem14.Index = 1; this.menuItem14.Text = "-"; // // menuItem10 // this.menuItem10.Index = 2; this.menuItem10.Text = "Close &Other Tabs"; // // menuItem11 // this.menuItem11.Index = 3; this.menuItem11.Text = "Close &All Tabs"; // // menuItem13 // this.menuItem13.Index = 4; this.menuItem13.Text = "-"; // // menuItem12 // this.menuItem12.Index = 5; this.menuItem12.Text = "&Rename..."; // // monView // this.monView.Dock = System.Windows.Forms.DockStyle.Fill; this.monView.Location = new System.Drawing.Point(232, 0); this.monView.Name = "monView"; this.monView.Size = new System.Drawing.Size(456, 486); this.monView.TabIndex = 13; // // MonitorForm // this.AutoScaleBaseSize = new System.Drawing.Size(7, 16); this.ClientSize = new System.Drawing.Size(688, 486); this.Controls.Add(this.monView); this.Controls.Add(this.splitter1); this.Controls.Add(this.panel2); this.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(177))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.KeyPreview = true; this.Name = "MonitorForm"; this.Text = "PerfMon+ By Roy osherove"; this.Closing += new System.ComponentModel.CancelEventHandler(this.MonitorForm_Closing); this.Load += new System.EventHandler(this.MonitorForm_Load); this.panel2.ResumeLayout(false); this.ResumeLayout(false); }