private static bool TriggerMail(string source, string serviceName, bool isStartSuccess, string body) { using (MetricTracker.Track(MethodBase.GetCurrentMethod())) { var msgServiceStartTry = isStartSuccess ? Constants.MsgServiceRestartSuccess : Constants.MsgServiceRestartFail; var backgroundColor = isStartSuccess ? Constants.Green : Constants.Red; body = string.Format(Constants.BodyTemplate.Replace(Environment.NewLine, string.Empty).Replace("\t", string.Empty), Constants.Restart, backgroundColor, msgServiceStartTry, body); var emailData = new EmailData { Subject = string.Format(Constants.SubjectTemplate, serviceName), Body = body, IsBodyHtml = true, FromMailAddress = Config.EmailSection.FromMailAddress, FromDisplayName = Config.EmailSection.FromDisplayName, ToMailAddress = Config.EmailSection.ToMailAddress, FromMailPassword = Config.SecureSection.FromMailPassword, Host = Config.EmailSection.Host, Port = Config.EmailSection.Port, EnableSsl = Config.EmailSection.EnableSsl, TimeOutInMilliseconds = Config.EmailSection.TimeoutInMilliseconds }; return(MailSender.SendMail(emailData, source)); } }
public static string ToHtml(this Dictionary <string, string> dic, string title) { using (MetricTracker.Track(MethodBase.GetCurrentMethod())) { var table = new HtmlTable(); var html = string.Format(Constants.TitleFormat, title); var flag = false; var isFirstItem = true; foreach (var item in dic) { table.Rows.Add(new HtmlTableRow { Cells = { new HtmlTableCell { InnerHtml = item.Key }, new HtmlTableCell{ InnerHtml = item.Value } }, BgColor = isFirstItem ? Constants.HeaderColor : (flag ? Constants.Grey : Constants.White) }); isFirstItem = false; flag = !flag; } using (var sw = new StringWriter()) { table.RenderControl(new HtmlTextWriter(sw)); html += sw.ToString(); } return(html); } }
public static Dictionary <string, string> GetServiceGeneralInfo(ServiceController sc) { using (MetricTracker.Track(MethodBase.GetCurrentMethod())) { var path = "Win32_Service.Name='" + sc.ServiceName + "'"; var managementObj = new ManagementObject(path); var properties = new List <string>() { "DisplayName", "Description", "StartMode", "StartName", }; var dic = new Dictionary <string, string> { { "Property".Bold(), "Value".Bold() }, { "Machine", Environment.MachineName }, { "Username", System.Security.Principal.WindowsIdentity.GetCurrent().Name }, }; properties.ForEach(prop => dic.Add(prop, (managementObj[prop] == null) ? string.Empty : managementObj[prop].ToString())); return(dic); } }
public static Dictionary <string, string> GetDictionary(string headerColumn1, string headerColumn2, ServiceController[] services) { using (MetricTracker.Track(MethodBase.GetCurrentMethod())) { var dic = new Dictionary <string, string> { { headerColumn1.Bold(), headerColumn2.Bold() } }; services.ToList().ForEach(svc => dic.Add(svc.DisplayName, svc.Status.ToString())); return(dic); } }
public static List <KeyVal <string, Dictionary <string, string> > > GetOtherThanExeConfigData(string[] configFilePaths) { using (MetricTracker.Track(MethodBase.GetCurrentMethod())) { var list = new List <KeyVal <string, Dictionary <string, string> > >(); foreach (var configPath in configFilePaths) { var dicConfigData = new Dictionary <string, string> { { "Node".Bold(), "Value".Bold() } }; if (!File.Exists(configPath)) { continue; } var document = XDocument.Load(configPath); var xml = document.ToString(); var rdr = XmlReader.Create(new StringReader(xml)); var key = string.Empty; while (rdr.Read()) { switch (rdr.NodeType) { case XmlNodeType.Element: key = rdr.LocalName; break; case XmlNodeType.Text: var value = rdr.Value; dicConfigData.Add(key, value); break; } } var pair = new KeyVal <string, Dictionary <string, string> > { Id = configPath, Value = dicConfigData }; list.Add(pair); } return(list); } }
public static bool SendMail(EmailData emailData, string source) { using (MetricTracker.Track(MethodBase.GetCurrentMethod())) { try { var fromMailAddress = new MailAddress(emailData.FromMailAddress, emailData.FromDisplayName); using (var smtp = new SmtpClient { Host = emailData.Host, Port = emailData.Port, EnableSsl = emailData.EnableSsl, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromMailAddress.Address, emailData.FromMailPassword), Timeout = emailData.TimeOutInMilliseconds, }) { using (var msg = new MailMessage() { From = fromMailAddress, Subject = emailData.Subject, Body = emailData.Body, IsBodyHtml = emailData.IsBodyHtml }) { var toAddresses = emailData.ToMailAddress.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); foreach (var address in toAddresses) { msg.To.Add(address.Trim()); } smtp.Send(msg); EventLog.WriteEntry(source, emailData.Body, EventLogEntryType.Information, 0); return(true); } } } catch (Exception ex) { EventLog.WriteEntry(source, ex.Message, EventLogEntryType.Error, 0); return(false); } } }
public static string[] GetAllConfigFromSpecifiedDirectory(string customConfigDirectoryPath) { using (MetricTracker.Track(MethodBase.GetCurrentMethod())) { var allConfigPaths = new string[0]; try { allConfigPaths = Directory.GetFiles(customConfigDirectoryPath, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".config") || s.EndsWith(".xml")).ToArray(); } catch (Exception ex) { EventLog.WriteEntry(Constants.WswService, ex.Message, EventLogEntryType.Error, 0); } return(allConfigPaths); } }
public LocalStage( IServiceProvider services, ITransportSerializer serializer, ITelemetry <LocalStage> telemetry, IActorDirectory actorDirectory, IStageDirectory stageDirectory, ILogger <LocalStage> logger, IOptions <NanoServiceOptions> serviceOptions, PubSubManager pubsub) { _services = services; _actorDirectory = actorDirectory; _stageDirectory = stageDirectory; _pubsub = pubsub; _serializer = serializer; StageGuid = Guid.NewGuid().ToString(); _logger = logger; _telemetry = telemetry; _serviceOptions = serviceOptions.Value; var stageDefaultProperty = new Dictionary <string, string> { { "StageId", StageGuid } }; _telemetry.SetProperties(stageDefaultProperty); _reqSecondMeter = _telemetry.Meter( "Stage.Requests", TimeSpan.FromSeconds(60) ); _actorInstancesMetric = _telemetry.Metric( "Stage.ActiveActorInstances"); _deactivatedInstancesMeter = _telemetry.Meter("Stage.DeactivatedActorInstances", TimeSpan.FromSeconds(60)); }
public static Dictionary <string, string> ToDictionary(string headerColumn1, string headerColumn2, object record) { using (MetricTracker.Track(MethodBase.GetCurrentMethod())) { var dic = new Dictionary <string, string> { { headerColumn1.Bold(), headerColumn2.Bold() } }; if (record == null) { dic.Add("Event record is null while reading Event viewer logs", ""); } else { record.GetType().GetProperties().ToList().ForEach(prop => dic[prop.Name] = (prop.GetValue(record, null) == null) ? "NULL" : ((prop.PropertyType == typeof(DateTime?)) ? prop.GetValue(record, null).ToString() + string.Format("({0} in {1} culture)", CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern, Thread.CurrentThread.CurrentCulture.Name) : prop.GetValue(record, null).ToString())); } return(dic); } }
public async Task RedisPing() { _redisPingTracker = _telemetry.Metric("Stage.Redis.Ping", new Dictionary <string, string>() { ["FromStage"] = _guid }); while (true) { try { await Task.Delay(5000); var ping = await _multiplexer.GetDatabase().PingAsync(); _redisPingTracker.Track(ping.TotalMilliseconds); } catch (Exception ex) { } } }
public void Performance_Complex_Object() { long ms = 0; int[] levelIds = new int[5]; using (MetricTracker m = new MetricTracker("Starting simple object", t => ms = t)) { Level1 level1 = new Level1(); level1.Value = "test"; level1.Id = levelIds[0]++; level1.levels = new List <Level2>(); Trace.WriteLine("Starting the test"); for (int i = 0; i < 1296; i++) { Level2 curLevel2 = new Level2(); level1.levels.Add(curLevel2); curLevel2.Id = levelIds[1]++; curLevel2.Value = "test" + i.ToString(); curLevel2.levels = new List <Level3>(); } using (Levels context = new Levels()) { context.Level1.Add(level1); context.SaveChanges(); Trace.WriteLine("Done simple save"); } ms.Should().BeLessThan(2960); ms = 0; } using (new MetricTracker("Starting complex object", t => ms = t)) using (Levels context = new Levels()) { SaveComplexObject(context, levelIds); } ms.Should().BeLessThan(1440); ms = 0; }
/// <summary> /// Updates Mail sent flag in service xml /// </summary> /// <param name="category">Service category</param> /// <param name="serviceName">Sevice name</param> /// <param name="isMailSent">Indicates if the mail has been sent</param> private static void UpdateIsMailSentFlag(string category, string serviceName, bool isMailSent) { using (MetricTracker.Track(MethodBase.GetCurrentMethod())) { lock (LockConfig) { var conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); try { ((ServiceSection)conf.GetSection(Constants.ServiceSection)).Categories[category] .Services[serviceName] .IsMailSent = isMailSent; conf.Save(); // Note: All comments in the saved xml will get cleaned up (Ref: https://stackoverflow.com/questions/1954358/can-configurationmanager-retain-xml-comments-on-save) } catch (Exception ex) { EventLog.WriteEntry(Constants.WswService, ex.Message, EventLogEntryType.Error, 0); } } } }
private static void RunPageTest(TestSettings settings) { string url; using (var browser = new IE(ConfigurationManager.AppSettings["WebpageTestUrl"])) { browser.TextField(Find.ById("url")).Value = settings.Url; if (!string.IsNullOrEmpty(settings.TestLocation)) browser.SelectList(Find.ById("location")).SelectByValue(settings.TestLocation); if (!string.IsNullOrEmpty(settings.Browser)) browser.SelectList(Find.ById("browser")).SelectByValue(settings.Browser); browser.Link(Find.ById("advanced_settings")).ClickNoWait(); if (!string.IsNullOrEmpty(settings.Speed)) browser.SelectList(Find.ById("connection")).SelectByValue(settings.Speed); if (settings.IsPrivate) browser.CheckBox(Find.ById("keep_test_private")).Change(); if (!string.IsNullOrEmpty(settings.Username)) browser.TextField(Find.ById("username")).TypeText(settings.Username); if (!string.IsNullOrEmpty(settings.Password)) browser.TextField(Find.ById("password")).TypeText(settings.Password); browser.Button(Find.ByName("submit")).Click(); browser.WaitUntilContainsText("First View", settings.Timeout); if (browser.ContainsText("partially complete")) { Thread.Sleep(10000); browser.Refresh(); } browser.WaitUntilContainsText("Raw page data", settings.Timeout); url = browser.Link(Find.ByText("Raw page data")).Url; } var csvRequest = (HttpWebRequest) WebRequest.Create(url); csvRequest.Accept = "text/csv"; var data = new List<PageData>(); using (var stream = csvRequest.GetResponse().GetResponseStream()) { if (stream != null) { using (var reader = new StreamReader(stream)) { using (var context = new CsvReader(reader)) { while (context.Read()) { var counter = data.Count; var item = new PageData(); item.EventName = counter == 0 ? "Empty Cache" : "Cached Run " + counter; item.Url = context.GetField<string>(3); item.LoadTime = TimeSpan.FromMilliseconds(context.GetField<int>(4)); item.TimeToFirstByte = TimeSpan.FromMilliseconds(context.GetField<int>(5)); item.Requests = context.GetField<int>(11); data.Add(item); } } } } } var host = ConfigurationManager.AppSettings["MetricTracking:Host"]; var port = int.Parse(ConfigurationManager.AppSettings["MetricTracking:Port"]); using (var metric = new MetricTracker(host, port)) { foreach (var run in data) { Console.WriteLine(run.EventName + "\t" + run.LoadTime); var prefix = settings.Prefix + run.EventName.Replace(" ", string.Empty) + "."; metric.Timing(prefix + "LoadTime", run.LoadTime.TotalMilliseconds); metric.Timing(prefix + "TimeToFirstByte", run.TimeToFirstByte.TotalMilliseconds); metric.Value(prefix + "Requests", run.Requests); } } }
public void Poor_Performance() { long ms = 0; using (MetricTracker m = new MetricTracker("Starting simple object", t => ms = t)) { Level1 level1 = new Level1(); level1.Value = "test"; level1.levels = new List <Level2>(); Trace.WriteLine("Starting the test"); for (int i = 0; i < 1296; i++) { Level2 curLevel2 = new Level2(); level1.levels.Add(curLevel2); curLevel2.Value = "test" + i.ToString(); curLevel2.levels = new List <Level3>(); } using (LevelsPoor context = new LevelsPoor()) { context.Level1.Add(level1); context.SaveChanges(); Trace.WriteLine("Done simple save"); } ms.Should().BeLessThan(2960); ms = 0; } using (LevelsPoor context = new LevelsPoor()) using (new MetricTracker("Starting complex object", t => ms = t)) { Level1 level1 = new Level1(); level1.Value = "test"; level1.levels = new List <Level2>(); for (int i = 0; i < 5; i++) { Level2 curLevel2 = new Level2(); level1.levels.Add(curLevel2); curLevel2.Value = "test" + i.ToString(); curLevel2.levels = new List <Level3>(); for (int j = 0; j < 5; j++) { Level3 curLevel3 = new Level3(); curLevel2.levels.Add(curLevel3); curLevel3.Value = "test" + j.ToString(); curLevel3.levels = new List <Level4>(); for (int k = 0; k < 10; k++) { Level4 curLevel4 = new Level4(); curLevel3.levels.Add(curLevel4); curLevel4.Value = "test" + k.ToString(); curLevel4.levels = new List <Level5>(); for (int l = 0; l < 10; l++) { Level5 curLevel5 = new Level5(); curLevel4.levels.Add(curLevel5); curLevel5.Value = "test" + l.ToString(); } } } } context.Level1.Add(level1); context.SaveChanges(); } ms.Should().BeLessThan(15000); ms = 0; }
void Start() { shooter = GetComponentInChildren <ShootAtMouse>(); teleporter = GetComponentInChildren <TeleportToThing>(); tracker = Camera.main.GetComponent <MetricTracker>(); }