Define macro for conditional compile

image_pdfimage_print
   


#define win2000
#define release
#undef  win98

using System;
using System.Diagnostics;

    class Test
    {
        [Conditional("DEBUG")]
        public static void DumpState()
        {
            Console.WriteLine("Dump some state...");
        }

        public static void Main()
        {
            string platformName;

            #if winXP       // Compiling for Windows XP
                platformName = "Microsoft Windows XP";
            #elif win2000   // Compiling for Windows 2000
                platformName = "Microsoft Windows 2000";
            #elif winNT     // Compiling for Windows NT
                platformName = "Microsoft Windows NT";
            #elif win98     // Compiling for Windows 98
                platformName = "Microsoft Windows 98";
            #else           // Unknown platform specified
                platformName = "Unknown";
            #endif

            Console.WriteLine(platformName);

            // Call the conditional DumpState method
            DumpState();

        }
    }

           
          


#undef, #elif, and #else preprocessor directives

image_pdfimage_print

#define DEBUG
#undef DEBUG
#define PRODUCTION

class Test {
public static void Main() {
int total = 0;
int counter = 10;

myLabel:
System.Console.WriteLine(“counter = ” + counter);
if (counter < 5) { #if DEBUG System.Console.WriteLine("goto myLabel"); #elif PRODUCTION System.Console.WriteLine("counter < 5"); #else System.Console.WriteLine("goto myLabel, counter < 5"); #endif goto myLabel; } System.Console.WriteLine("total = " + total); } } [/csharp]

Log utility based on File with File.AppendAllText

image_pdfimage_print
   
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


  public static class Logger
  {
    private static string logFile = @"logz.txt";
    private static string errorLogFile = @"errorLogz.txt";

    public static void Log(string s)
    {
      System.IO.File.AppendAllText(logFile, DateTime.Now + ": " + s + Environment.NewLine);
    }

    public static void LogError(string s)
    {
      System.IO.File.AppendAllText(errorLogFile, DateTime.Now + ": " + s + Environment.NewLine);
    }
  }

   
     


Set Text Output To Event Log

image_pdfimage_print


   
 
/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury, 
   Zach Greenvoss, Shripad Kulkarni, Neil Whitlow

Publisher: Peer Information
ISBN: 1861007663
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;

namespace FibersTest
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    /// 
    
    public class fmrFibers : System.Windows.Forms.Form
    {
        private System.Windows.Forms.ListBox lstFibers;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        [DllImport("kernel32.dll")]
        extern static IntPtr ConvertThreadToFiber(int fiberData);

        [DllImport("kernel32.dll")]
        extern static IntPtr CreateFiber(int size, System.Delegate function, int handle);

        [DllImport("kernel32.dll")]
        extern static IntPtr SwitchToFiber(IntPtr fiberAddress);

        [DllImport("kernel32.dll")]
        extern static void DeleteFiber(IntPtr fiberAddress);

        [DllImport("kernel32.dll")]
        extern static int GetLastError();
        delegate void SetTextOutputToEventLog(int number);
        public fmrFibers()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
            Thread t1 = new Thread(new ThreadStart(NewThreadToFiberExecution));
            t1.Start();
        }

        void OutputLog(int fiberNumber)
        {
            this.Invoke(new AddToListBox(SetText), new object[]{fiberNumber});
            SwitchToFiber(obj);
        }

        void SetText(int message)
        {
            lstFibers.Items.Add("Fiber "+message.ToString()+" added this");

        }

        delegate void AddToListBox(int message);

        System.IntPtr obj;

        void NewThreadToFiberExecution()
        {
            try
            {
                SetTextOutputToEventLog stof = new SetTextOutputToEventLog(OutputLog);

                obj = ConvertThreadToFiber(0);
                long l1 = GetLastError();

                System.IntPtr retVal1 = CreateFiber(500, stof, 1);
                System.IntPtr retVal2 = CreateFiber(500, stof, 2);
                System.IntPtr retVal3 = CreateFiber(500, stof, 3);
                System.IntPtr retVal4 = CreateFiber(500, stof, 4);
                System.IntPtr retVal5 = CreateFiber(500, stof, 5);
                if(GetLastError()!=0) throw new Exception("Create Fiber failed!!");

                IntPtr fiber1return = SwitchToFiber(retVal1);
                IntPtr fiber2return = SwitchToFiber(retVal2);
                IntPtr fiber3return = SwitchToFiber(retVal3);
                IntPtr fiber4return = SwitchToFiber(retVal4);
                IntPtr fiber5return = SwitchToFiber(retVal5);
                
                if(GetLastError()!=0) throw new Exception("Create Fiber failed!!");

                DeleteFiber(retVal1);
                DeleteFiber(retVal2);
                DeleteFiber(retVal3);
                DeleteFiber(retVal4);
                DeleteFiber(retVal5);
            }
            catch(Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.lstFibers = new System.Windows.Forms.ListBox();
            this.SuspendLayout();
            // 
            // lstFibers
            // 
            this.lstFibers.Name = "lstFibers";
            this.lstFibers.Size = new System.Drawing.Size(320, 212);
            this.lstFibers.TabIndex = 0;
            // 
            // fmrFibers
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(304, 213);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.lstFibers});
            this.Name = "fmrFibers";
            this.Text = "FibersTest";
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Application.Run(new fmrFibers());
        }
    }
}


           
         
     


Test Log

image_pdfimage_print
   
 

using System;
using System.IO;

public class TestLog
{
     public static void Main()
    {
        string logFile = "LOGFILE.TXT";

        FileStream fs = new FileStream(logFile, FileMode.OpenOrCreate, FileAccess.Write);
        
        StreamWriter sw = new StreamWriter(fs);
        StreamReader sr = new StreamReader(fs);

        sw.WriteLine("First log entry");
        sw.WriteLine("Second log entry");

        while(sr.Peek() > -1)
        {
            Console.WriteLine(sr.ReadLine());
        }

        sw.Close();
        sr.Close();
        fs.Close();
    }
}


           
         
     


Add a EventLogTraceListener to the listener collection and writing error messages to the Application log

image_pdfimage_print
   
 
/*
C# Programming Tips &amp; Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

// LogTrace.cs -- Demonstrates adding a EventLogTraceListener to the listener
//                collection and writing error messages to the Application log.
//
//                Compile this program with the following command line:
//                    C:>csc /debug:full /d:TRACE LogTrace.cs
using System;
using System.Diagnostics;

namespace nsEventLogs
{
    public class LogTrace
    {
        static public void Main ()
        {
// Create the EventLog object
            EventLog EvLog = new EventLog ();
// Register the source if it has not already been registered
            if (!EventLog.SourceExists ("AppLog.exe"))
            {
                Console.WriteLine ("Creating event log source");
                EventLog.CreateEventSource ("AppLog.exe", "Application");
            }
            EvLog.Source = "AppLog.exe";
            Trace.Listeners.Add (new EventLogTraceListener (EvLog));
            Trace.Listeners.Add (new TextWriterTraceListener (Console.Out));
            Trace.WriteLine ("Debugging to the event log");
// Set the source for the messages to be display in the Event Viewer
            EvLog.Source = "AppLog.exe";
        }
    }
}