May 27, 2008

Performance counter

Performance counter is used to monitor the running status of an application. The application itself just output the performance data. The data itself don't need to be calcuated by the application, the data is used by external application, like performance MMC. Here discussed how to output performance data only. To output performance data takes several steps.

  1. First setup the register performance counter, and its belong category. For example:
                CounterCreationDataCollection counterCreationDataCollection = new CounterCreationDataCollection();
    
                // Add the counter.
                CounterCreationData averageCount64 = new CounterCreationData();
                averageCount64.CounterType = PerformanceCounterType.AverageCount64;
                averageCount64.CounterName = "AverageCounter64Sample";
                counterCreationDataCollection.Add(averageCount64);
    
                // Add the base counter.
                CounterCreationData averageCount64Base = new CounterCreationData();
                averageCount64Base.CounterType = PerformanceCounterType.AverageBase;
                averageCount64Base.CounterName = "AverageCounter64SampleBase";
                counterCreationDataCollection.Add(averageCount64Base);
    
                // Create the category.
                PerformanceCounterCategory.Create("AverageCounter64SampleCategory",
                "Demonstrates usage of the AverageCounter64 performance counter type.",
                PerformanceCounterCategoryType.SingleInstance, counterCreationDataCollection);
    
                

    When instrumenting applications (creating and writing custom performance counters), you might be working with performance counter types that rely on an accompanying base counter that is used in the calculations. The base counter must be immediately after its associated counter in the CounterCreationDataCollection collection your application uses. Please note the base counter is not visible to the performance MMC.

    Base counter type

    Performance counter types

    AverageBase

    AverageTimer32

    AverageCount64

    CounterMultiBase

    CounterMultiTimer

    CounterMultiTimerInverse

    CounterMultiTimer100Ns

    CounterMultiTimer100NsInverse

    RawBase

    RawFraction

    SampleBase

    SampleFraction

  2. Then you need to get a reference of the performance counter
                CounterCreationDataCollection counterCreationDataCollection = new CounterCreationDataCollection();
    
                // Add the counter.
                CounterCreationData averageCount64 = new CounterCreationData();
                averageCount64.CounterType = PerformanceCounterType.AverageCount64;
                averageCount64.CounterName = "AverageCounter64Sample";
                counterCreationDataCollection.Add(averageCount64);
    
                // Add the base counter.
                CounterCreationData averageCount64Base = new CounterCreationData();
                averageCount64Base.CounterType = PerformanceCounterType.AverageBase;
                averageCount64Base.CounterName = "AverageCounter64SampleBase";
                counterCreationDataCollection.Add(averageCount64Base);
    
                // Create the category.
                PerformanceCounterCategory.Create("AverageCounter64SampleCategory",
                "Demonstrates usage of the AverageCounter64 performance counter type.",
                PerformanceCounterCategoryType.SingleInstance, counterCreationDataCollection);
    
                
  3. The last step is output the counter.
    pc.IncrementBy(value); basedPc.Increment();

May 18, 2008

Output a tempalte to file

You can output the result of a template to file system but use the command line and the code smith project file. The default behavior is that code smith engine, call the template's GetFileName method, and output the result to a text file with that file name. CodeTemplate also has a method RenderToFile(fileName). This method is not to be called inside the template itself, because it will fall into infinitive loop, because itself will call Render method. RenderToFile(fileName) is to be called by external client. But the fileName logic should be maintained inside the template. So we can create the follow the code to implement our requirement.

            public class BaseTemplate: CodeTemplate
            {
            //this make the file name both read and write
            // you can encapsulate the logic in the getter method
            public string OutputFile
            {
            get
            {
            return fileName;
            }
            set
            {
            fileName = value;
            }
            }

            //this override the base method
            public override string GetFileName()
            {
            return OutputFileNmae;
            }

            //this is new method, it should be also called by client
            public void GenerateFile()
            {
            this.RenderToFile(this.GetFileName(), true);

            }
            }

            

May 14, 2008

Call External Method

In a workflow, to call the external method, you need the following ready.

  • The workflow need a interface marked with ExternalDataExchange. In the callExternalMethodActivity node, you need to configure the InterfaceType, MethodName, MethodInvoking, and what value to be used as passed-in parameter.
  • In workflow host, you need to config the workflow runtime to service the ExternalService. When a workflow instance execute an callExternalMethodActivity, it will ask the workflow runtime to supply a service.
            //workflow definition
            [ExternalDataExchange]
            public interface ICustomerService
            {
            void SendCustomerData(string customerName);
            }

            //host enviroment code
            public class CustomerService : ICustomerService
            {

            public void SendCustomerData(string customerName)
            {
            Console.WriteLine(customerName);
            }
            }

            ExternalDataExchangeService xchangeSvc = new ExternalDataExchangeService();
            workflowRuntime.AddService(xchangeSvc);
            CustomerService custSvc = new CustomerService();
            xchangeSvc.AddService(custSvc);


            

May 9, 2008

Monitor and lock

Below is sample code about how to use Monitor.

            MyClass obj;
            //Some code to initialize obj;
            //This section is now thread-safe:
            Monitor.Enter(obj);
            obj.DoSomething(  );
            Monitor.Exit(obj);
            

This is a little bit misleading. Because the point here is not obj.DoSomething(), the point here Monitor.Enter(obj), and Montior.Exit(obj). If another thread call obj.DoSomething at the same time, but not following the Enter/Exit fashion, the obj.DoSomething is not protected at all. The mechanics there is that you can not Call Monitor.Enter(obj) successfully at the same time. If one thread enter the obj, another thread need to wait until the other thread exit the object. Tomake this pattern easy to use, c# introduce lock keyword. if method is static, you can follow the following example

            public class Demolock
            {
            public static void MethodOne()
            {
            lock (typeof(Demolock))
            {
            Console.WriteLine("methodone at " + DateTime.Now.ToString());
            Thread.Sleep(2000);
            }
            }

            public static void MethodTwo()
            {
            lock (typeof(Demolock))
            {
            Console.WriteLine("methodtwo at " + DateTime.Now.ToString());
            Thread.Sleep(2000);
            }
            }
            }
            

If the method is instance method, and you want to protect all the instance method at the same level, you can use this example. In this example, MethodThree of one instance can be called during the MethodOne of the same instance is called, but MethodOne of one instance can not be called during the MethodTwo of the same instance is called.

            public class Demolock
            {

            public void MethodOne()
            {
            lock (this)
            {
            Console.WriteLine("methodone at " + DateTime.Now.ToString());
            Thread.Sleep(2000);
            }
            }

            public void MethodTwo()
            {
            lock (this)
            {
            Console.WriteLine("methodtwo at " + DateTime.Now.ToString());
            Thread.Sleep(2000);
            }
            }

            public void MethodThree()
            {
            Console.WriteLine("methodtwo at " + DateTime.Now.ToString());
            Thread.Sleep(2000);

            }
            }
            

If the different instance methods are independent, you just want to limit protect the entrance of individual method, you need to create different lock object for different method. For example

            public class Demolock
            {
            object objOne = new object();
            object objTwo = new object();

            public void MethodOne()
            {
            lock (objOne)
            {
            Console.WriteLine("methodone at " + DateTime.Now.ToString());
            Thread.Sleep(2000);
            }
            }

            public void MethodTwo()
            {
            lock (objTwo)
            {
            Console.WriteLine("methodtwo at " + DateTime.Now.ToString());
            Thread.Sleep(2000);
            }
            }
            }

            

Because this programming model is so common, .NET has built-in compiler support for it, called synchronized methods. The MethodImpl method attribute, defined in the System.Runtime.CompilerServices namespace, accepts an enum of type MethodImplOptions. One of the enum values is MethodImplOptions.Synchronized. When the MethodImpl method attribute is applied on a method with that enum value, the compiler instructs the .NET runtime to lock the object on method entry and unlock it on exit. This is semantically equivalent to encasing the method code with a lock statement. For example, consider this method definition:

            using System.Runtime.CompilerServices;

            public class MyClass
            {
            [MethodImpl(MethodImplOptions.Synchronized)]
            public void DoSomething(  )
            {
            /* Method code */
            }
            //Class members
            }

            

This method is semantically identical to the following:

            public class MyClass
            {
            public void DoSomething(  )
            {
            lock(this)
            {
            /* Method code */
            }
            }
            //Class members
            }

            using System.Runtime.CompilerServices;

            public class MyClass
            {
            int m_Number = 0;
            int Number
            {
            [MethodImpl(MethodImplOptions.Synchronized)]
            get
            {
            return m_Number;
            }
            [MethodImpl(MethodImplOptions.Synchronized)]
            set
            {
            m_Number = value;
            }
            }
            }
            

For the producer/consumer scenario, after producer produce the result, it should signal consumer to work, after consumer finished, it should signal producer.

            public class Demolock
            {
            public void Produce()
            {
            lock (this)
            {
            for (int i = 0; i < 10; i++)
            {
            Console.WriteLine("Produce at " + DateTime.Now.ToString());
            Monitor.Pulse(this);
            Monitor.Wait(this);
            }
            }
            }

            public void Consume()
            {
            lock (this)
            {
            for (int i = 0; i < 10; i++)
            {
            Console.WriteLine("Consume at " + DateTime.Now.ToString());
            Monitor.Pulse(this);
            Monitor.Wait(this, 1000);
            }
            }
            }
            }
            

Thread Interrupt vs Abort

Both methods can terminate a thread. The difference is that they raise difference exception, interrupt can use goto to save its life, abort can not use goto to save its life, and abort can pass some information into the running thread by calling Abort(object stateInfo). The running thread can access this object by ThreadAbortException.ExceptionState .

            class Program
            {
            static void Main(string[] args)
            {
            ThreadStart ts = new ThreadStart(DoSomething);
            Thread t = new Thread(ts);
            t.Start();
            Thread.Sleep(1000);
            //t.Interrupt();
            t.Abort();
            Console.WriteLine("mainthread finished");
            }

            static void DoSomething()
            {
            Resurrection:
            try
            {
            Thread.Sleep(2000);
            Console.WriteLine("do something finished");
            }
            catch (ThreadInterruptedException ex)
            {
            Console.WriteLine("DoSomething is interrupted");
            goto Resurrection;

            }
            catch (ThreadAbortException ex)
            {
            Console.WriteLine("DoSomething is aborted");
            goto Resurrection;
            }

            }

            }

            

Threads and exceptions

If the thread method completes its execution, .NET will shutdown the thread gracefully. However, any unhandled exception thrown on the call stack of the thread will terminate not just the thread but also will trigger shutdown of hosting process itself. The one exception to this rule is the ThreadAbortException, which will only terminate the aborted thread. This behavior is a breaking change introduced by .NET 2.0. In contract, .NET 1.1 will only terminate the thread that encountered the unhandled exception. When porting .NET 1.1 applications to .NET 2.0, make sure that your thread methods always catch and handle any exception, otherwise you risk unplanned application termination.

May 5, 2008

CallExternalMethod

A workflow can use a activity of type CallExternalMethod. This method is a member of type which addressed with ExteranlDataExchange attribute. To make the method call useful, the parameter of the method should be the information that need to send to client. So the workflow should be responsible to supply the parameters.

At the host side, the workflow runtime should have the provide the ExternalDataExchangeService and the service should have a service which implement the agreed interface. The workflow instance will ask the workflow runtime for an instance implementing the agreed type. After that the workflow instance should construct the parameter and call that method with the parameter.

WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(WorkflowLib.Workflow1));
//
ExternalDataExchangeService xchangeSvc = new ExternalDataExchangeService();
workflowRuntime.AddService(xchangeSvc);
CustomerService custSvc = new CustomerService();
xchangeSvc.AddService(custSvc);

May 2, 2008

Initialize a configuration section

in the configuration file, not config section is defined, you can use the following code to initialize the configuration.

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
MyConfigSection sec = fred.GetSection("MyConfigSection") as MyConfigSection;
if (sec == null)
{
  Console.WriteLine("sec is null");
  sec = new MyConfigSection();
  sec.SectionInformation.AllowDefinition = ConfigurationAllowDefinition.MachineToApplication;
  sec.Age = 12;
  config.Sections.Add("mysec", sec);
  config.Save(ConfigurationSaveMode.Minimal);
}

Please note that the sec should be also initialized, if there is not, only the Section definiton is defined, but not the actual configuration section.

RefreshSection not fresh

ConfigurationManager.RefershSection does not really refresh the section. To refersh, you need to OpenConfiuration and GetSection again. RefreshSection does not have any effect at all.

May 1, 2008

Use KeyValueConfigurationCollection

AppSettings mapped to

            
            
            
            
Then we write our code the access that seciton. Please note that we are not going to use the ConfigurationSection itself, what we are interested is the property in ConfigurationSetting, which is AppSettingsSection.Settings . Below is the code.
            public class Settings
            {
            private static KeyValueConfigurationCollection keywords;
            private static System.Configuration.Configuration config;
            private static System.Configuration.Configuration Config
            {
            get
            {
            if (config == null)
            {
            config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            }
            return config;
            }
            }

            public static KeyValueConfigurationCollection Keywords
            {
            get
            {
            if (keywords == null)
            {
            AppSettingsSection section = Config.GetSection("Keywords") as AppSettingsSection;
            keywords = section.Settings;
            }
            return keywords;
            }
            }

            public static void Save()
            {
            Config.Save();
            }
            }

            

To use the the settings, we can write the following code.

            Console.WriteLine(Settings.Keywords.Count.ToString());
            Settings.Keywords.Add("type", "html");
            Settings.Save();
            

ConfigurationSection

If you want to have your custom configuration, the first step is to create a ConfigurationSection. ConfigurationSection itself it is also a ConfigurationElement. Sometime your configuration setting can be very simple, for example it only has some properties of build in type such as string or boolean. Sometime it has complex property in this case you need to create a use ConfigurationElement or ConfigurationElementCollection to support that property. The same thing applies to the new ConfigurationElement.

Requirement s for logo

  • Who is your audience?

    Determine which people will view this logo and their interests? What is the product of the company.

  • What do competitors' logos look like?

    Take a look at some competitors of the company for which you're designing the logo. How can you make a logo that stands out in a positive way?

  • Deside the format for the logo.

    Since we’re designing logos for the World Wide Web, you’ll need to create either JPEG or GIF images that are 72 dpi, and use RGB color mode. If these logos were for print work, you’d want to use no less than 300 dpi, and use CMYK color mode.