/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnAdd_Click(object sender, EventArgs e) { using (NDC.Push(MethodBase.GetCurrentMethod().Name)) { this.lblOperation.Text = "Ładuję obrazki"; int count = 0; FolderBrowserDialog browserDialog = new FolderBrowserDialog(); if (browserDialog.ShowDialog() == DialogResult.OK) { count = Ctx.CollectImages(browserDialog.SelectedPath, (int)nudWidth.Value, (int)nudHeight.Value); } else { //TODO: fix this //this message is stupid //MessageBox.Show(strings.DirectoryDoesNotExist); } log.DebugFormat("Count tiles {0}", count); if (count > 15) { btnGo.Enabled = true; lblAddFirst.Visible = false; } else { btnGo.Enabled = false; lblAddFirst.Visible = true; lblAddFirst.Text = strings.AddAtLeast15Tiles; } this.lblOperation.Text = "Obrazki załadowane"; this.pgbOperation.Value = 0; this.lblPercentage.Text = "0%"; } }
public void TestMultiLogMessage() { NDC.Push("TestNdc"); for (int i = 0; i < 20; ++i) { Log.DebugFormat("debug message {0}", i); } Log.Trace("Trace message"); Log.Debug("Debug message"); Log.Info("Info message"); Log.Notice("Notice message"); Log.InfoFormat("Info message"); Log.InfoFormat("Info message"); Log.InfoFormat("This is a\nmultiline message\nthat should have\nhtml breaks"); Log.InfoFormat("A message with <html> elements that should be rendered as text"); Log.WarnFormat("Warning message (this should be a triggering message)"); Log.InfoFormat("Info message"); Log.ErrorFormat("Error message 1 (a non-trigger error, due to holddown after last warning)"); Log.InfoFormat("Info message"); Log.ErrorFormat("Error message 2"); Log.InfoFormat("Info message"); Log.Trace("Trace message"); Log.Debug("Debug message"); Log.Info("Info message"); Log.Notice("Notice message"); Log.Warn("Warn message"); Log.Error("Error message"); Log.Fatal("Fatal message"); Log.ErrorFormat("Error message 3 (second triggering due to appender being closed)"); }
private async Task TestRule(Rule rule, string connectionString, string collectionId) { using (NDC.Push(rule.RuleId)) { Log.Warn("test started"); Log.Debug(rule.Sql); } var @params = _model.GetParameters(collectionId).Select(x => new SqlParameter(x.ParameterName, x.Value)).ToArray(); try { long count; using (var dbContext = new DbContext(connectionString)) { // ReSharper disable once CoVariantArrayConversion var results = await dbContext.Database.SqlQuery <RuleErrors>(rule.Sql, @params).ToListAsync(); count = results.LongCount(); } using (NDC.Push(rule.RuleId)) Log.Info($"completed with {count} errors"); } catch (Exception ex) { using (NDC.Push(rule.RuleId)) Log.Error(ex.Message); } }
public virtual void destroy() { if (this.state == 5) { return; } if (this.state != 0) { stop(); } this.log.info("Destroying"); NDC.push(Name); try { destroyService(); } catch (Exception throwable) { this.log.error("Destroying failed", throwable); } finally { NDC.pop(); } this.state = 5; this.log.info("Destroyed"); }
public void Submit(Type type, LogLevel level, object obj, string context = null) { if (LogFactory.Instance.GetLogLevel() > level) { return; } try { if (context == null) { context = Guid.NewGuid().ToString(); } string message = obj as string ?? JsonConvert.SerializeObject(obj); using (NDC.Push(context)) { LoggingEvent loggingEvent = new LoggingEvent(new LoggingEventData { TimeStamp = DateTime.Now, Level = ConvertLogLevel(level), Message = message, LoggerName = type.FullName }); _log.Logger.Log(loggingEvent); } } catch (Exception) { // ignore, can't log } }
public virtual void stop() { if (this.state != 3) { return; } this.state = 1; this.log.info("Stopping"); NDC.push(Name); try { stopService(); } catch (Exception throwable) { this.state = 4; this.log.error("Stoping failed", throwable); return; } finally { NDC.pop(); } this.state = 0; this.log.info("Stopped"); }
public virtual void start() { if (this.state != 5 && this.state != 0 && this.state != 4) { return; } this.state = 2; this.log.info("Starting"); NDC.push(Name); try { startService(); } catch (Exception exception) { this.state = 4; this.log.error("Starting failed", exception); throw exception; } finally { NDC.pop(); } this.state = 3; this.log.info("Started"); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void trackBar_ValueChanged(object sender, EventArgs e) { using (NDC.Push(MethodBase.GetCurrentMethod().Name)) { try { this.lblOpacity.Text = trackBar.Value.ToString(); this.pictureBox.Image = null; this.pictureBox.Refresh(); if (this.orginalImage != null) { //using ( var image = new Bitmap(this.orginalImage);//) // { var tmpImage = Image.FromFile(this.tbxBrowse.Text); TextureBrush tBrush = new TextureBrush(Utils.ChangeOpacity(tmpImage, (float)((float)this.trackBar.Value / 100f))); Pen blackPen = new Pen(Color.Black); using (var g = Graphics.FromImage(image)) { g.FillRectangle(tBrush, new Rectangle(0, 0, image.Width, image.Height)); } this.pictureBox.Image = image; this.pictureBox.Refresh(); // } } } catch (OutOfMemoryException ex) { log.Error("Out of memory!", ex); } catch (Exception ex) { log.ErrorFormat("Generic error {0}", ex.Message, ex); } } }
public void SyntaxError(IRecognizer recognizer, IToken offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e) { var file = _fileContextFunc(); using (NDC.Push($"{line}:{charPositionInLine}")) _log.Error(msg); }
/// <summary> /// /// </summary> /// <returns></returns> protected Dictionary <string, Color> FindAverageColorForTiles(List <string> tilesNames) { using (NDC.Push(MethodBase.GetCurrentMethod().Name)) { Dictionary <string, Color> tilesColors = new Dictionary <string, Color>(); foreach (var tilePath in tilesNames) { try { log.DebugFormat("Calculating average color for tile {0}", tilePath); using (Stream stream = new FileStream(tilePath, FileMode.Open)) { Bitmap bitmapTile; using (bitmapTile = (Bitmap)Bitmap.FromStream(stream)) { tilesColors.Add(tilePath, Utils.GetTileAverage(bitmapTile, 0, 0, this.width, this.height)); log.DebugFormat("Color added to collection {0}", tilesColors[tilePath]); OnTileFit(this, new MosaicEventArgs() { TileAverage = tilesColors[tilePath], }); } } } catch (ArgumentException ex) { log.ErrorFormat("{0}: {1}", tilePath, ex.Message); } catch (OutOfMemoryException ex) { log.ErrorFormat("Problem with image {0}", tilePath); log.Error(ex.Message, ex); GC.WaitForPendingFinalizers(); } } return(tilesColors); } }
public Model Build(IDateProvider dateProvider = null, ISchemaProvider schemaProvider = null) { var model = new Model(); var walker = new ParseTreeWalker(); var listener = new MsdsListener(model) { DateProvider = dateProvider ?? new DateProvider(), SchemaProvider = schemaProvider ?? new SchemaProvider() }; foreach (var stream in _streams) { var filestream = stream as FileStream; var filename = filestream == null ? string.Empty : Path.GetFileNameWithoutExtension(((FileStream)stream).Name); using (NDC.Push(Path.GetFileNameWithoutExtension(filename))) { var lexer = new MsdsLexer(new AntlrInputStream(stream)); lexer.RemoveErrorListeners(); lexer.AddErrorListener(new LoggingErrorListener()); var tokens = new CommonTokenStream(lexer); var parser = new MsdsParser(tokens); parser.RemoveErrorListeners(); parser.AddErrorListener(new LoggingErrorListener()); walker.Walk(listener, parser.file()); } } return(model); }
private async Task <bool> RunRule(Rule rule, string connectionString, string collectionId, long ruleValidationId) { using (NDC.Push(rule.RuleId)) { Log.Warn("run started"); Log.Debug(rule.Sql); } // ReSharper disable once CoVariantArrayConversion using (var dbContext = new DbContext(connectionString)) { try { var detailParams = new List <SqlParameter> { new SqlParameter("@RuleValidationId", ruleValidationId) }; detailParams.AddRange( _model.GetParameters(collectionId) .Select(x => new SqlParameter(x.ParameterName, x.Value))); dbContext.Database.CommandTimeout = 60; var result = await dbContext.Database.ExecuteSqlCommandAsync(rule.ExecSql, detailParams.ToArray()); using (NDC.Push(rule.RuleId)) Log.Info($"completed with {result} errors"); } catch (Exception ex) { using (NDC.Push(rule.RuleId)) Log.Error(ex.Message); return(false); } } return(true); }
/// <summary> /// Chnage opacity of image passed in parameter. New image is being returned. /// </summary> /// <param name="img">Image to change opacity</param> /// <param name="opacityvalue">Visibility 0-not visible 100-visible</param> /// <returns></returns> public static Bitmap ChangeOpacity(Image img, float opacityvalue) { using (NDC.Push(MethodBase.GetCurrentMethod().Name)) { try { Bitmap bmp = new Bitmap(img.Width, img.Height); // Determining Width and Height of Source Image using (Graphics graphics = Graphics.FromImage(bmp)) { ColorMatrix colormatrix = new ColorMatrix(); colormatrix.Matrix33 = opacityvalue; ImageAttributes imgAttribute = new ImageAttributes(); imgAttribute.SetColorMatrix(colormatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); graphics.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, imgAttribute); graphics.Dispose(); colormatrix = null; } return(bmp); } catch (Exception ex) { log.Error(ex.Message, ex); return(null); } } }
private void init() { if (ndc != null && NDC.Depth == 0) { NDC.Push(ndc); } }
public void TestRemotedMessageNdcPushPop() { // Setup the remoting appender ConfigureRootAppender(FixFlags.Partial); RemoteLoggingSinkImpl.Instance.Reset(); Logger root; root = ((Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root; string testMessage = string.Format("test message [ {0} ]", (new Random()).Next()); using (NDC.Push("value")) { } // Log a message that will be remoted root.Log(Level.Debug, testMessage, null); // Wait for the remoted object to be delivered Thread.Sleep(2000); LoggingEvent[] events = RemoteLoggingSinkImpl.Instance.Events; Assert.AreEqual(1, events.Length, "Expect to receive 1 remoted event"); Assert.AreEqual(testMessage, events[0].RenderedMessage, "Expect Message match after remoting event"); }
/// <summary> /// /// </summary> /// <param name="bSource"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> public static Color GetTileAverage(Bitmap bSource, int x, int y, int width, int height) { using (NDC.Push(MethodBase.GetCurrentMethod().Name)) { try { long aR = 0; long aG = 0; long aB = 0; for (int w = x; w < x + width; w++) { for (int h = y; h < y + height; h++) { Color cP = bSource.GetPixel(w, h); aR += cP.R; aG += cP.G; aB += cP.B; } } aR = aR / (width * height); aG = aG / (width * height); aB = aB / (width * height); return(Color.FromArgb(255, Convert.ToInt32(aR), Convert.ToInt32(aG), Convert.ToInt32(aB))); } catch (Exception ex) { log.Fatal(ex.Message, ex); throw; } } }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btCancelCalculate_Click(object sender, EventArgs e) { using (NDC.Push(MethodBase.GetCurrentMethod().Name)) { MessageBox.Show(strings.WillBeInFuture, strings.Warning, MessageBoxButtons.OK, MessageBoxIcon.Information); log.Error("Cancel will be present in future"); } }
public override void ExitRuleDefinition([NotNull] MsdsParser.RuleDefinitionContext context) { var ruleId = context.ruleid().GetText(); try { var data = new { schema = SchemaProvider.Value, ruleid = ruleId, iserror = context.REQUIRE() != null, message = context.error().GetText().Replace(@"\'", "''"), tables = AssembleChildComponents(context).Select(x => x.ComponentName).Distinct().ToList(), sqlFilters = _sql.Get(context.filter()), sqlConditions = _sql.Get(context.condition()) }; var ruleSql = _engine.Generate("RuleDefinition", data); _sql.Put(context, ruleSql); var collectionIds = AssembleChildCollectionIds(context); var rule = new Rule(context.ruleid().GetText(), _currentRulesetId, SchemaProvider, collectionIds, ruleSql, data.tables); Model.AddRule(rule); } catch (NullReferenceException ex) { var log = LogManager.GetLogger(this.GetType().ToString()); using (NDC.Push(ruleId)) log.Fatal(ex); } catch (ArgumentException ex) { var log = LogManager.GetLogger(this.GetType().ToString()); using (NDC.Push(ruleId)) log.Fatal(ex); } }
public void leaveFunc() { if (internalLog.IsDebugEnabled) { internalLog.Debug("[exit]"); } NDC.Pop(); }
public void Test() { using (NDC.Push("test2")) { log.Info("return"); Thread.Sleep(100); } }
public void enterFunc(string funcName) { NDC.Push(funcName); if (internalLog.IsDebugEnabled) { internalLog.Debug("[enter]"); } }
/// <summary> /// /// </summary> /// <param name="tilesColors"></param> /// <param name="avgsMaster"></param> /// <param name="tX"></param> /// <param name="tY"></param> /// <returns></returns> protected List <string>[,] MatchTilesToColor(Dictionary <string, Color> tilesColors, Color[,] avgsMaster, int tX, int tY) { using (NDC.Push(MethodBase.GetCurrentMethod().Name)) { var searchCounter = 1; List <string>[,] matchedColors = new List <string> [tX, tY]; Parallel.For(0, tX, x => { Parallel.For(0, tY, (y) => { log.DebugFormat("Color buffer set to {0}", buffer); int i = 0; //maximum = tX * tY + 1; //var percentage = (int)((searchCounter / maximum) * 100); //worker.ReportProgress(percentage, strings.CalculateMosaic); var colors = new List <string>(); while (tilesColors.Count - 1 >= i) { log.DebugFormat("Searchcounter: {0}, index: {1}", searchCounter, i); string name = "tiles\\" + i.ToString() + ".bmp"; log.DebugFormat("Tile name {0}", name); try { if (Utils.GetDifference(avgsMaster[x, y], tilesColors[name]) < buffer) { colors.Add(name); log.InfoFormat("added for x={0} y={1} filename: {2}", x, y, name); } else { // in case of buffer is not enough } } catch (Exception ex) { log.ErrorFormat("Name of tile during error {0}", name); log.Error(ex.Message, ex); } i++; if (tilesColors.Count == i && colors.Count < this.tilesInGroup) { i = 0; buffer += 25; log.InfoFormat("buffer set to {0}", buffer); } } matchedColors[x, y] = colors; searchCounter++; }); }); return(matchedColors); } }
public override Image CalculateColors(string fileName, out Color[,] colorsArray) { using (NDC.Push(MethodBase.GetCurrentMethod().Name)) { var image = Image.FromFile(fileName); var height = this.height; var width = this.width; log.InfoFormat("Images size of {0}x{1}", width, height); var tileSize = new Size((int)width, (int)height); Boolean bitmapLoaded = false; Bitmap masterBitMap = null; log.Info("Averaging colors"); while (!bitmapLoaded) { try { masterBitMap = new Bitmap((Image)image.Clone()); log.InfoFormat("Main image set"); bitmapLoaded = true; } catch (OutOfMemoryException ex) { log.Error(ex.Message, ex); GC.WaitForPendingFinalizers(); } } int tX = masterBitMap.Width / tileSize.Width; int tY = masterBitMap.Height / tileSize.Height; averageColorsOfMasterImage = new Color[tX, tY]; var maximum = tX * tY; try { lock (image) { for (int x = 0; x < tX; x++) { for (int y = 0; y < tY; y++) { averageColorsOfMasterImage[x, y] = Utils.GetTileAverage(masterBitMap, x * tileSize.Width, y * tileSize.Height, tileSize.Width, tileSize.Height); Rectangle r = new Rectangle(tileSize.Width * x, tileSize.Height * y, tileSize.Width, tileSize.Height); using (Graphics g = Graphics.FromImage(image)) { g.FillRectangle(new SolidBrush(averageColorsOfMasterImage[x, y]), r); OnColorCalculated(averageColorsOfMasterImage[x, y], x, y, tX, tY); } } ; } ; } } catch (Exception ex) { log.FatalFormat("Fatal error during putting images into big image"); log.Fatal(ex.Message, ex); } colorsArray = averageColorsOfMasterImage; return(image); } }
private void ClientDisconnected(object sender, EventArgs e) { var channel = (IClientChannel)sender; using (NDC.Push(channel.SessionId)) { Log.Info($"A client disconnected (session: {channel.SessionId})."); } }
public void Dispose() { string s = NDC.Pop(); if (_logger.Logger.IsEnabledFor(Level.Info)) { _logger.InfoFormat("EndScope={0}", s); } }
private void CalculateColorsProgressChanged(object sender, ProgressChangedEventArgs e) { using (NDC.Push(MethodBase.GetCurrentMethod().Name)) { var progres = e.ProgressPercentage; var v = e.UserState as String; this.pgbOperation.Value = progres; this.lblPercentage.Text = string.Format("{0}%", progres); this.lblOperation.Text = v; } }
public void Initialize(IClientChannel channel) { using (NDC.Push(channel.SessionId)) { Log.Info($"A client connected (session: {channel.SessionId})."); } channel.Closed += ClientDisconnected; channel.Faulted += ClientDisconnected; }
public DisposableScope(ILog logger, string s) { _logger = logger; NDC.Push(s); if (_logger.Logger.IsEnabledFor(Level.Info)) { _logger.InfoFormat("BeginScope={0}", s); } }
/// <summary> /// /// </summary> /// <param name="source"></param> /// <param name="target"></param> /// <returns></returns> public static int GetDifference(Color source, Color target) { using (NDC.Push(MethodBase.GetCurrentMethod().Name)) { int dR = Math.Abs(source.R - target.R); int dG = Math.Abs(source.G - target.G); int dB = Math.Abs(source.B - target.B); int diff = Math.Max(dR, dG); diff = Math.Max(diff, dB); return(diff); } }
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { //NDC.Push(channel.SessionId); using (NDC.Push(channel.SessionId)) { var context = OperationContext.Current; var user = context?.ServiceSecurityContext?.WindowsIdentity.Name; var remoteEndpointMsgProp = context?.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; Log.Info($"{remoteEndpointMsgProp?.Address}:{user}:{request.Headers.Action}"); } return(null); }