Musings

A random collection

Archive for January 2011

.NET: Trace Logging to Console in C# Applications

In your code put the Trace messages at strategic places

  System.Diagnostics.Trace.TraceInformation(string message);

  System.Diagnostics.Debug.WriteLine("a debug message");

  // this is convenient
  System.Diagnostics.Debug.WriteLineIf(iUnitQty > 50, "This message WILL appear");

  // can event direct log messages to wherever
  TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
  Debug.Listeners.Add(tr1);
        
  TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("Output.txt"));
  Debug.Listeners.Add(tr2);

  TextWriterTraceListener myCreator = new TextWriterTraceListener(System.Console.Out);
  Trace.Listeners.Add(myCreator);

Note: Debug messages will not appear in Release builds, they will be enabled only in Debug builds. Trace messages however will show up in Release & Debug builds.

Stick the following XML in your app.config in “<configuration>” section

  <system.diagnostics>
    <trace autoflush="true" indentsize="4">
      <listeners>
        <add name="configConsoleListener"
             type="System.Diagnostics.ConsoleTraceListener" />
      </listeners>
    </trace>
  </system.diagnostics>

Or

  <system.diagnostics>
    <trace autoflush="true" indentsize="4">
      <listeners>
        <add initializeData="...\console-host.svclog" type="System.Diagnostics.XmlWriterTraceListener" name="traceListener">
            <filter type=""/>
        </add>

        <add name="FileListener"
                 type="System.Diagnostics.TextWriterTraceListener"
                 initializeData=".\blabla-trace.txt" /> 
      </listeners>
    </trace>
  </system.diagnostics>

To add a timestamp or a datetime add TraceOutputOption to your config file:

        <add name="FileListener"
                 type="System.Diagnostics.TextWriterTraceListener"
                 initializeData=".\blabla-trace.txt"
                 traceOuputOptions="DateTime"       <!-- Timestamp|HostName|ThreadID|... -->
                 /> 

Written by curious

January 27, 2011 at 10:24 am

Posted in dotNET

TECH: What process has a port open?

Windows

netstat -aon
# find process id (pid) for who has a port open
tasklist
# find the process name for a pid

Linux

netstat -pn

Written by curious

January 21, 2011 at 2:19 pm

Posted in tech-tips

C++: Explicit vs Implicit Constructors

Explicit constructors cannot take part in an implicit conversion.

class Array
{
public:
    Array(size_t count);            // implicit ctor
    explicit Array(size_t count);
};

Array array = 1; // implicit conversion, ok

void UseArray(const Array& arr);

UseArray(10);    // mistake, want to avoid
  1. Why do we need implicit conversion? Sometimes it is more natural allow implicit conversion
    class Number
    {
    public:
        Number(int n);
    };
    
    Number num = 1233; // natural to do this
    
  2. When do you not need explicit declaration on a constructor? When constructor has more than one parameters.
    class UserName
    {
    public:
        UserName(const string& first, const string& last);
    };
    
    UserName user("Arun", "Singh");
    

More examples

class BigBuffer
{
public:
 BigBuffer(int initialValue)
   { memset(buffer, initialValue, sizeof(buffer)); }
private:
 char buffer[65536];
};

extern void Foo(const BigBuffer& o);

void oops()
{
 Foo(3);
}

Written by curious

January 18, 2011 at 3:41 pm

Posted in C++

.NET: C# Tips

  1. Initializing objects
    public class Point
    {
    	public int X { get; set; }
    	public int Y { get; set; }
    }
    Point a = new Point { X = 0, Y = 1 };
    
    public class Rectangle
    {
    	public Point p1 { get; set; }
    	public Point p2 { get; set; }
    }
    Rectangle r = new Rectangle {
    	p1 = { X = 0, Y = 1 },
    	p2 = { X = 2, Y = 3 }
    };
    
  2. Array Initializer
    int[,] a = new int[,] { {1,2}, {3,4}, {5,6} };
    
  3. Print current time
    DateTime currentSystemTime = DateTime.Now;
    Console.WriteLine(currentSystemTime);
    
  4. Measure time difference
    /* Read the initial time. */
    DateTime startTime = DateTime.Now;
    Console.WriteLine(startTime);
    
    /* Do something that takes up some time. For example sleep for 1.7 seconds. */
    Thread.Sleep(1700);
    
    /* Read the end time. */
    DateTime stopTime = DateTime.Now;
    Console.WriteLine(stopTime);
    
    /* Compute the duration between the initial and the end time. */
    TimeSpan duration = stopTime - startTime;
    Console.WriteLine(duration);
    
    Console.WriteLine("Total time in msecs: " + duration.TotalMilliseconds);
    
  5. Use StopWatch
    [DllImport("kernel32.dll")]
    public static extern bool QueryPerformanceCounter(out long value);
    
    using System.Diagnostics;
    Stopwatch sw = new Stopwatch();
    sw.Start();
    // sw = new StopWatch.StartNew();
    
    Thread.Sleep(1000);
    
    sw.Stop();
    
    sw.ElapsedMilliseconds
    sw.ElapsedTicks * sw.Frequency
    
    

Written by curious

January 5, 2011 at 12:28 pm

Posted in dotNET