Programming‎ > ‎

.NET

Here are some general tips for .NET programming (C# and C++/CLI are mixed) 

Update: 4/5/2024

Index



How can I see the progress of multiple tasks?

It is very easy to create multiple tasks run at the same time in .NET. We needed a way to see the progress of multiple tasks. Here is how I did.


	Task task1 = Task.Run((Action) method1);
	Task task2 = Task.Run((Action) method2);
	Task task3 = Task.Run((Action) method3);
	Task task4 = Task.Run((Action) method4);
	Task [] taskArray = new [] { task1, task2, task3, task4 };
	for (int percentDone = 0; percentDone < 100; percentDone += 25)
	{
	   int index = Task.WaitAny(taskArray); // returns the index of the task finished
	   taskArray = taskArray.Where(t => t != taskArray[indx]).ToArray(); // remove the finished task
	   callback.Invoke(percentDone); // notify
	}
    

Top


How can I convert List to Dictionary?

I have a list of objects and I like to create a dictionary with key being one of the object property.I also want to create new object for value. It turned out that LINQ will simplify a lot. I have StnGseFuelSulfurContents with fuel type (int), sulfur content, year, source. On the other hand I have enum GSEFuelType and GSEFuelSulfurContent class. Dictionary had to be translated from LINQ object.


	var dic = sdc.StnGseFuelSulfurContents             
	          .Where(y => y.Source == source)  // select EDMS or MOVES201X             
              .GroupBy(                 
                       x => (GSEFuelType) x.FuelType,                 
                       x => new GSEFuelSulfurContent((GSEFuelType) x.FuelType, x.SulfurContent, x.Year, x.Source),                
                       (key, g) => new {Type = key, List= g.ToList()})             
              .ToDictionary(h => h.Type, h => h.List);
	

Top


How can I switch on an object Type?

I wanted to have a switch based on an object Type (I had to handle 13 different objects coming in and I did not want to do "if.. elseif ..." repeated 13 times). Thanks to cdiggins https://stackoverflow.com/questions/7252186/switch-case-on-type-c/7301514#7301514. Here is how:

  
    public class TypeSwitch  
    {    
      Dictionary<Type, Action<object>> matches = new Dictionary<Type, Action<object>>();    

      public TypeSwitch Case<T>(Action<T> action)     
      {      
        matches.Add(typeof(T), (x) => action((T)x)); 
        return this;    
      }
	  
      public void Switch(object x)    
      {      
        Action<object> action;      
        if (matches.TryGetValue(x.GetType(), out action)      
        {        
          action(x);      
        }      
        else // switch default      
        {        
          return;      
        }    
      }  
    }
	
	The usage is 
	
	// setup
	TypeSwitch ts = new typeSwitch();  
	ts.Case<A>((a)=>{ use(a); });  
	ts.Case<B>((b)=>{ use(b); });  
	...  
	// use
	ts.Switch(x); // based on the type of x, handled correctly.  no need for if...else...
	

Top


How can I catch exception in Task.Factory.StartNew?

If I used Task.Factory.StartNew, then it may generate AggregateException. How to catch this? Thanks to Stackoverflow, there is a way. https://stackoverflow.com/questions/14883850/catching-error-when-using-task-factory. You add the following:

    
	Task.Factory    
	.StartNew(..)    
	.ContinueWith(tsk =>{
	   var flattened = tsk.Exception?.Flatten();      
	   flattened?.Handle(ex =>      
	   {        
	     MessageBox.Show($"Error is {ex.Message)");        
		 return true;      
	   }
	 );     
	},     
	TaskContinuationOptions.OnlyOnFaulted); /// this is important

Top


How can I have dtor for a static class?

Here is the stackoverflow reference http://stackoverflow.com/questions/4364665/static-destructor.


  public static class Foo  
  {    
    private static readonly Destructor Finalize = new Destructor();    
	private sealed class Destructor    
	{      
	  ~Destructor()      
	  {        ...      
	  }    
	}    
	...
	

Top


How can I check the user being admin in code?

Here is the code (  using System.Security.Principal;  )

  
  public bool IsAdministrator()  
  {    
    WindowsIdentity identity = WindowsIdentity.GetCurrent();    
    WindowsPrincipal principal = new WindowsPrincipal(identity);    
    return principal.IsInRole(WindowsBuiltInRole.Administrator);  
  }
  

Top


How can I embed resources (bmp, file etc.) in DLL and use it?

Sometimes you want to embed resource (image, file, binary object) in DLL and use it from your application. In your DLL project, add the object in some foler of the project.  Let us name it as "Template" and the binary object, Study.bak.  The property setting for study.bak must be set as "Embedded Resource" for Build Action.   When built this DLL, the resource will be inside.   You access it using module.GetManifestResourceStream(module.GetName().Name + ".Template.Study.bak").  You must have System.IO and System.Reflection namespaces. This link explains. Essentially you use reflection to access the object name.

Top



How can I add StyleCop to check coding standards?

StyleCop is a way to enforce the coding standards for developers. Here is the way to add it to the Visual Studio project. You have to hand edit the csproj file. In the following I'm specifying the StyleCop library directory using ..\.

 
  1. Add PropertyGroup for StyleCop    
     <PropertyGroup>      
	 <StyleCopTargets>..\..\..\..\Libraries\StyleCop\StyleCop.Targets</StyleCopTargets>      
	 <StyleCopTreatErrorsAsWarnings>true</StyleCopTreatErrorsAsWarnings>    
     </PropertyGroup> 
  2. Import it into the project    
     <Import Project="$(StyleCopTargets)" />
  

You may want to fix StyleCop errors automatically. The VS extension tools are not perfect but are helpful in fixing the errors: StyleCopFixer (which is only for VS2010) and its variation StyleCop Fixer (which works for VS2010 and VS2013).

Top



How can I write a unit test for a static private method?

You cannot use PrivateObject for testing static private method. You have to use PrivateType.

  
  PrivateType pt = new PrivateType(typeof(SOxHandler));  
  actual = (bool) pt.InvokeStatic("isOnRoadEquiv", new object[] { type }); 
  // "type" is the argument passed  
  Assert.AreEqual(expected, actual);
  

Top


How can I write a unit test of a private method with 'out' params

Before VS2011, Visual Studio is creating a shadow class and thus it is easy to write a unit test for any private methods. Now you have to use PrivateObject with reflection syntax. Thus the question arise: how to write a unit test for a private method with out parameters. Some people use delegate but there is a much simpler method as you see below:

 
  This is the private method of MyClass I want to test: 
  private void GetStartAndEnd(out DateTime start, out DateTIme end) 
  Here is the test:   
  MyClass mc = new MyClass();   
  PrivateObject pobj = new PrivateObject(mc);   
  object [] output = new object [2];   
  pobj.Invoke("GetStartAndEnd", output);   
  DateTime startTime = (DateTIme) output[0];   
  DateTime endTime = (DateTime) output[1];
  

Top


How can I solve "No way to resolve conflict?

When trying to compile a .Net4 application on Visual Studio 2013 with SqlServer 2012, I received a message from the comiler:

 
  No way to resolve conflict between "Microsoft.SqlServer.Types, Version=11.0.0.0, Culture=neutral, 
  PublicKeyToken=89845dcd8080cc91" and "Microsoft.SqlServer.Types, 
  Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91". 
  Choosing "Microsoft.SqlServer.Types, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" 
  arbitrarily. Consider app.config remapping of assembly "Microsoft.SqlServer.Types, Culture=neutral, 
  PublicKeyToken=89845dcd8080cc91" from Version "10.0.0.0" 
  [C:\WINDOWS\assembly\GAC_MSIL  Microsoft.SqlServer.Types\10.0.0.0__89845dcd8080cc91\Microsoft.SqlServer.Types.dll] 
  to Version "11.0.0.0" 
  [C:\Program Files (x86)\Microsoft SQL Server\110\SDK\Assemblies \Microsoft.SqlServer.Types.dll] to solve conflict 
  and get rid of warning.
  

Here is how to solve the problem. This problem occurs for a Windows executable program and thusyou can add app.config and add the following:

  
  <runtime>    
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1" appliesTo="v1.0.3705" >      
	<dependentAssembly>        
	<assemblyIdentity name="Microsoft.SqlServer.Types" Culture="neutral" PublicKeyToken="89845dcd8080cc91" />        
	<bindingRedirect oldVersion="10.0.0.0" newVersion="11.0.0.0" />      
	</dependentAssembly>    
	</assemblyBinding>  
  </runtime>
  
The statement must be within <configuration> and <\configuration>.

Top


Why my unit test fails on comparison of doubles?

Here is the example of the failure:Failed Assert.AreEqual failed.Expected:<0.177699998021126>. Actual:<0.177699998021126>. Note that both digits exactly match. The hint for the solution is that the expected value was takenfrom the SQL Server manager column. It turned out that SQL server manager uses G-formatfor reporting double value. When I convert the value to string using R-format (round-trip format),then it revealed that the value is actually 0.17769999802112579, not 0.177699998021126. The lesson is that you always compare using the "R"-formatted string (i.e. ToString("R")). Now Microsoft recommends to use G17 format under 64 bit OS.

Top


How can I convert int to hex and hex to int?

Here is how http://www.geekpedia.com/KB8_How-do-I-convert-from-decimal-to-hex-and-hex-to-decimal.html.

  
  int dec = 123;  
  string hex = dec.ToString("X");  
  int dec2 = int.Parse(hex, System.Globalization.NumberStyles.HexNumber);
  
where "X" can have N, i.e. "X4" for four "digit" and "x" will be in lower case.

Top


How can I convert numeric(38,0) to C# type?

I wrote a ADO.NET cmd to retrieve the last inserted identity value whose return type is numeric(38, 0). I know that we use that identity is int. A simple cast like (int) cmd.ExecuteScalar() does not work and throw exception of "cannot unbox to ..." error. You have to do a double cast like (int)(decimal) cm.dExecuteScalar().

Top


What does "R" format specifier do?

In C#, you get a string by value.ToString() most of the time, but I encounter the code value.ToSting("R"). Here is the description.

  
  The round-trip ("R") format specifier guarantees that a numeric value that is converted   
  to a string will be parsed back into the same numeric value. This format is supported only   
  for the Single, Double, and BigInteger types.  
  When a BigInteger value is formatted using this specifier, its string representation 
  contains all the significant digits in the BigInteger value. 
  When a Single or Double value is formatted using this specifier, it is first tested using 
  the general format, with 15 digits of precision for a Double and 7 digits of precision 
  for a Single.  If the value is successfully parsed back to the same numeric value, it is 
  formatted using the general format specifier. If the value is not successfully parsed back 
  to the same numeric value, it is formatted using 17 digits of precision for a Double and 
  9 digits of precision for a Single. Although you can include a precision specifier, it is 
  ignored. Round trips are given precedence over precision when using this specifier.  
  Now Microsoft recommends using "G17" for x64 system.
  See https://docs.microsoft.com/en-us/dotnet/api/system.double.tostring?view=netframework-4.6.1
  

Top


How to make HashSet (no duplication) work?

You want to produce a collection with all unique elements. You use HashSet, butended up not using what you thought "equal". A simple example of a location class with double x and double y. The end result was that even though x, y are exactly the same, HashSet kept all the locations with the same x and y. It turns out that HashSet uses two methods to "equal" decision and you customize the object to fit your need of "equal".

 
  public class a 
  {   
    // you customize the two methods   
	public override int GetHashCode() 
	{ /* Implementation */ }   
	public override bool Equals(a obj) 
	{ /* Implementation */ } }
  

Top


Microsoft source code viewer

Here is the link http://referencesource-beta.microsoft.com/

Top


How can I convert XML into a class?

I have an object defined in XML and I like to get a C# class for it. This is possible due to the Microsoft xsd.exe. See http://www.codeproject.com/Articles/11317/From-XML-to-Strong-Types-in-C.

  
  xsd file.xml
  -> produces file.xsd  
  xsd file.xsd /c     
  -> produces file.cs
  

Top


Use IEnumerable.Any()

When you use LINQ, you usually encounter the situation of whether there isa list. Don't use Count, since it has to enumerate. Use Any()so that it does not have to enumerate. In particular, when you just need the firstelement in IEnumerable.

Top


Useful [Flags] enum trick

Making enum as [Flags] provides a very useful tool for setting options, i.e. a single integer stores multiple options. For example,

   
  [Flags]    
  public enum Pollutant    
  {      
    CO2 = 0x01, // 0 is used for no option      
    CO = 0x02,       
    HC = 0x04    
  }    
  Pollutant type = (Pollutant) 7;    
  Console.WriteLine("{0} is {1}", (int) type, type.ToString());    
  // produces the output '7 is "CO2, CO, HC"'    
  string typeTxt = "HC, CO, CO2";    
  type = (Pollutant) Enum.Parse(typeof(Pollutant), typeTxt);    
  Console.WriteLine("{0} is {1}", typeTxt, (int) type);
  

Top


How can I create a list of enum?

I wanted to create a list of enum. Here is how where Pollutant is an enum.

  
  List<Pollutant> list = new List<Pollutant>();  
  foreach (Pollutant val in Enum.GetValues(typeof(Pollutant)))    
    list.Add(val);
  

How about getting the "names" of enum?

    
  string[] names = Pollutant.GetNames(typeof(Pollutant));
  

Top


How can I extract a statement containing 'Exx' where xx is a digit?

I had to parse a text starting with 'Exx' where xx is a digit like 08, etc. Fortunately you can useRegEx under .NET.

  
  Match matchResult = Regex.Match(input, @"\bE\d{2}\s");
  // word begins with 'E', then two digits, and then space
  if (matchResult.Success)  
  {    
    string errorMsg = input.SubString(matchResult.Index);  
  }   
  

Top


How can I read the config section?

The application configuration file can have sections which makes it easy to organize configuration parameters.Unfortunately Microsoft obsoleted ConfigurationManager.GetSection() preferring more complicated handler class. Fortunately the configuration file is just an XML file and it is easy to read them using LINQtoXML XElement. Here is how. You can see how small the routine is. The Microsoft handler is so ugly when I used .NET Reflectorto analyze the code.

    
  protected Dictionary<string, string> GetSection(string secName)    
  {      
    XElement config = XElement.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    XElement step1 = config.Element(secName);      
    Dictionary<string, string> settings = new Dictionary();      
	foreach (XElement e in step1.Elements())      
	{        
	  string key = "";        
	  string value = "";        
	  foreach (var attrib in e.Attributes())        
	  {          
	    if (attrib.Name == "key")            
		  key = attrib.Value;          
        else if (attrib.Name == "value")            
          value = attrib.Value;        
	  }        
	  settings.Add(key, value);      
	}      
	
	return settings;    
  }
  
  where this routine is used to read the section like the following  

  <configSections>     
    <section name="Step1" type="NameValueSectionHandler" >  
  <\configSections>  
  <Step1>    
  <add key="SurfaceFile" value="..\..\SampleWeather\Surface - Jan 2010.op" />    
  <add key="Format" value="ISHD" />    
  <add key="StartDate" value="2010/01/01" />    
  <add key="EndDate" value="2010/01/31" />  
  </Step1>

Top


The fastest way to concatenate many strings into one string

I thought that I should use StringBuilder Append. This is wrong. It is very inefficient. Here is the most efficient way. I noticed the following will speed up by order of magnitude while creating ADO.NET insert statements for SQL Server 2008 where you can use one insert statement with many rows.

  
  string [] bits = new string [] { s1, s2, s3, ..., sn };  
  string final = string.Join(string.Empty, bits);
  
Note that the first argument is the separator for bits. This will create a memory only once and copy bits into the allocated memory.

Top


How to set up a solution for both 32 bit and 64 bit compile?

The convenience of .NET framework is that the compiler creates the MSIL object and thus it is independent of the platform (x86 or x64). The only thing picks the platform is the startup exe. Therefore, you need to create x86 or x64 only for the executable project, but keep the library platform as AnyCPU. Another catch is that when you compile the executable as AnyCPU, the current machine OS will set the platform, i.e. when you are compiling on x64, then your executable is of x64 even though you specified AnyCPU. Since we are compiling for both x86 and x64, we do the following:

  
  1. Set All libraries to be built as AnyCPU (whose out will be into bin\Release and bin\Debug).  
  2. Create configurations (x86, x64) for the executable project from AnyCPU platform.  
  3. Modify x86 Debug Output path to bin\x86\Debug, x86 Release to bin\x86\Release.  
  4. Modify x64 Debug Output path to bin\X64\Debug, x64 Release to bin\x64\Release.  
  5. Make sure each configuration is set as follows:       
     x86 Debug ... libraries AnyCPU, executable Debug x86       
     x86 Release ... libraries AnyCPU, executable Release x86       
     x64 Debug ... libraries AnyCPU, executable Debug x64       
     x64 Release ... libraries AnyCPU, executable Release x64  
  6. Libraries will be compiled into Debug and Release and automatically copied into      
     the appropriate directory for x86 or x64 executable.
  

Top


How can I run a member function in STA?

I'm calling a COM-wrapped object inside the member function. As you know, COM must be called in STA. The console application is easy to do this in that you add atribute [STAThread] on Main. This makes the entire application STA. Is there an alternative? Yes, creating a thread and run a member function in STA as follows where p is an object and Test is a member function taking a parameter i:

   
  Thread thread = new Thread(() => { p.Test(i);});   
  thread.SetApartmentState(ApartmentState.STA);   
  thread.Start();   
  thread.Join();
  
  instead of    
  
  p.Test(i);
  

Top


Short good description of Managed Extensibility Framework (MEF)?

Here is the quick introduction: http://www.codeproject.com/Articles/376033/From-Zero-to-Proficient-with-MEF. This article does not describe the Rejection and how to diagnose. The following articles do this http://msdn.microsoft.com/en-us/magazine/ee291628.aspx and http://blogs.msdn.com/b/dsplaisted/archive/2010/07/13/how-to-debug-and-diagnose-mef-failures.aspx.

Top


How can I read a file another application is using?

If you just use path for fstream, then you get an exception. I just wanted to see how a file is processed by opening a file in Excel and parsing it in my app.Here is the way. Note that FileShare is the flag for the other application which is usually have read/write.

   
  using (FileStream fstr = new FileStream(iffFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))   
  using (StreamReader str = new StreamReader(fstr))   
  {   
    ...
  }
  

Top


How can I call a derived class method from a base class?

I created a Form subclass whose base class has a control and I like to handleevent on that control in my subclass, i.e. call a subclass member from thebase class. Thanks to StackOverflow, here is the way.

 
  using System.Reflection;  
  ...  
  this.GetType().InvokeMember(
  "MethodName",       
  System.Reflection.BindingFlags.InvokeMethod,       
  null, 
  obj,       
  new object [] {...}  // this is the argument list  
  );

Top


System.Random bug discovered!

While investigating the period of various random number generators, I found a seriousbug in Microsoft .NET System.Random implementation.

Microsoft says that the Random class is based on Donald E. Knuth's subtractive random number generator algorithm. For more information,see D. E. Knuth. "The Art of Computer Programming, volume 2: Seminumerical Algorithms". Addison-Wesley, Reading, MA, second edition, 1981.

The problem was discovered when I use .NET Reflector to see what is implemented. Knuth was very specific about the lagged Fibonacci sequence coefficient (24 and 55). Somehow Microsoft mistyped the value to be 21 in place of 31 (=55-24). Due to this mistype, the random number generated no longer has the guanrantee on the period to be longer than (2^55-1). The Knuth version of lags (24, 55) has been tested by many people about the property of the generated numbers but not the one created by Microsoft.

It is very easy to identify the typo. It seems that Microsoft just copied the routine (ran3) from Numerical Recipes v.2 page. 283 verbatim (even the variable names are copied), not from Knuth book which has a complete different wayof initializing.

This bug is acknowledged by Microsoft. The new link is in github where many discussions were done when Microsoft was to create new .NETCore version. However the argument is closed now. See https://github.com/dotnet/runtime/issues/23198. Old link is gone: http://connect.microsoft.com/VisualStudio/feedback/details/634761/system-random-serious-bug.

Top


Is there a .NET 4 version of LocBaml (localization tool)?

WPF is made for localization, but it is easy to do with LocBaml. Unfortunately the originalone was not made for .NET4. I tried to compile under VS2010 by clicking the .csproj. It compiles but when I click Properties, then it crashed with COM error. Thanks to Michael Sync, he created the version for .NET 4. You go to this page: http://michaelsync.net/2010/03/01/locbaml-for-net-4-0.

Top


How can I start a child process and get the stdout?

Sometimes you want to run a command line tool from your application and get the output.Here is how.

       
  Process process = new Process        
  {          
    StartInfo =          
	{            
	  FileName = Path.Combine(PERFORMANCE_DIR, "vsinstr.exe"),            
	  Arguments = ("/coverage " + assemblyName),            
	  RedirectStandardOutput = true,            
	  UseShellExecute=false          
	}        
  };        
  process.Start();        
  string res = process.StandardOutput.ReadToEnd();        
  process.WaitForExit();
  
Note that ReadToEnd() must be run before prcoess.WaitForExit(). Otherwise a deadlock happens.

Top


How can I get the code coverage information for a unit test from a command line?

It took me a while to get the code coverage. Here is the way. This requires the Visual Studio Premium or Ultimate which has (VSDir)\Team Tools\Performance Tools where vsinstr.exe etc resides. Here we assume that you created unittest.dll and module.dll.

 
  1. Use the VS command console window and move to the location where (unittest.dll) is found. 
  2. Issue a command in the console window:      
     vsinstr -coverage (module.dll)    
	 where (module.dll) is the one you want to get the code coverage.    
	 It returns with the message "Successfully instrumented file (module.dll).    
	 If your unit test uses more than one modules, you may repeat this procedure. 
  3. Issue a command in the console window:      
     start vsperfmon -coverage -output:(unittest).coverage     
	 This will open another console window. 
  4. Issue a command in the original console window:      
     mstest /testcontainer:(unittest.dll)    
	 This will run the unit tests built in the dll. 
  5. Issue a command in the original console.window:      
     vsperfcmd -shutdown    
     This will shutdown the other console window ("Profile Monitor"). 
  6. Double click on the file (unittest).coverage under VS2010.    
     This will open "Code Coverage Results" window and show you the overall coverage and each    
	 unit test function coverage values.
  

Top


How can I have a unit test with a data

Visual Studio can create unit tests easily by just specifying the class in a unit test wizard.What I needed was to deserialize an object from a file to use for the unit test. Googling tells me about the test setting. It did not work. Here is the way it worked for me.

  
  1. Add a file in the root directory of your unit test.  
  2. Set the property of this file as "Build Action | Content" and "Copy to Output | Copy always".  
  3. Add the attribute to the unit test class       
     [DeploymentItem("(filename)")]
  
In this way, the file is copied into the output directory for unit test and thus you can open it without specifying the path.

Top


How can I have access to an internal property?

I need to have access to an internal property of a different assembly whose name I know. There are two ways to do this. If you can modify the assembly info of the assembly, you add [assembly:InternalsVisibleTo("your assembly")] in AssemblInfo.cs. Usually this is not possible. The only way is to use Reflection to get the property. For example, if you havean instance of a class obj, then

  
  System.Reflection.BindingFlags flag = System.Reflection.BindingFlags.NonPublic                                         
                                        | System.Reflection.BindingFlags.Instance;  
  System.Reflection.PropertyInfo prop = obj.GetType().GetProperty("propname", flag);  
  // prop.GetValue(obj, null);  
  // or if you know the field name, then use this   
  System.Reflection.FieldInfo fld = obj.GetType().GetField("fieldname", flag);   
  // fld.GetValue(obj);
Note that you need two flags (just NonPublic only does not work).

Top


How can I avoid many if-else for FactoryPattern?

I created a StrategyFactory and many Strategy classes. Using a particular strategy was done by giving StrategyFactory a string. Initially I had many if-else to pick the right strategy which looked really ugly. What I did was the following:

  
  // base class  
  public class Strategy { ... }  
  // subclassed concrete strategies  
  public class MyOptionStrategy: Strategy { ... }  
  public class YourOptionStrategy: Strategy { ... }  
  ...  
  static public class StrategyFactory  
  {    
    static Dictionary strategyDictionary;        
	
	// static ctor will be called before anything done    
	static StrategyFactory()    
	{      
	  strategyDictionary = new Dictionary();      
	  strategyDictionary.Add("MyOption", typeOf(MyOptionStrategy));      
	  strategyDictionary.Add("YourOption", typeOf(YourOptionStrategy));      
	  ...    
	}        
	
	static public Strategy GetStrategy(string choice)    
	{      
	  Type strategyType;      
	  bool res = strategyDictionary.TryGetValue(choice, out strategyType);      
	  if (res == true)      
	  {        
	    // use reflection to create an object from type        
		Strategy rsObject = Activator.CreateInstance(strategyType) as Strategy;        
		if (rsObject != null)          
		  return rsObject;        
		else          
		  throw new NotImplementedException();      
	  }      
	  else        
	    throw new NotImplementedException();    
	}  
  }
  

Top


How can I detect the process being 32 or 64 bit?

It turned out that the CLR maximum object size is only 2 Gbytes independent of 32 bit or 64 bit. I wanted to test this but I need to test whether the program is compiled for 32 bit or 64 bit.

  
  static bool System.Environment.Is64bitProcess;
  

Top


How can I print the bit pattern of a float?

.NET stores the float in LittleEndian (Java stores in BigEndian). Another issue is the BitArrayconvention of how to create a bit pattern from bytes. Another issue is that BitArray does not take float as an argument (only integral type). Here is the routine after figuring out all the conventions.

   
  static void PrintBitPattern(float f)    
  {      
    byte[] bytes = BitConverter.GetBytes(f);      
	BitArray bits = new BitArray(bytes);      
	for (int i = bits.Length; i > 0; --i) // start from the highest in BigEndian sense      
	{        
	  Console.Write("{0}", bits[i - 1] ? 1 : 0);        
	  if (i % 4 == 1)          
	    Console.Write(" ");      
	}      
    Console.WriteLine("");    
  }

Top


How to resolve "Interop type XXX cannot be embedded. Use the applicable interface instead"?

When I referenced ArcGIS .NET assembly, I got this error. This is due to the fact that ArcGIS is a COM interop library. The quick fix is:

  
  Right click on the particular assembly and bring up Properties  
  Set "Embed Interop Types" to be False
  Or  
  Change the name of the class to the one without Class as explained in the ref below.
  
The detailed explanation about this message is explained in http://blogs.msdn.com/b/mshneer/archive/2009/12/07/interop-type-xxx-cannot-be-embedded-use-the-applicable-interface-instead.aspx. In particular, he explains how to fix.

Top


How can I select files with multiple filter?

Directory.GetFile() takes a single filter. My need is to use multiple filter. Here is what I find on google. Sorry I forgot where I got this.

   
  static string[] MyGetFiles(string sourceFolder, string filters, SearchOption so)   
  {     
    return filters.Split('|').SelectMany(filter 
	    => Directory.GetFiles(sourceFolder, filter, so)).ToArray();   
  }
  

Top


What is the equivalent of DebugBreak in .NET?

It is very useful to insert break when something wrong happens. In Win32 you have void WINAPI DebugBreak(void). In .NET you have Debugger.Break() (using System.Diagnostics).

Top


How can I get nullable value from app.config?

Sometimes you want to have a nullable value in app.config. Here is how:

    
  static private Nullable<T> GetNullableValueFromAppConfig<T>(string key) 
  where T : struct    
  {      
    System.Configuration.AppSettingsReader configReader = new AppSettingsReader();      
    string valueTxt = "";      
	try      
	{        
	  valueTxt = (string)configReader.GetValue(key, typeof(string));      
	}      
	catch (Exception)      
	{        
	  return null;      
	}      
	if (valueTxt == null)  // value = "(None)"  undocumented way to get null        
	  return null;          
	if (valueTxt.ToUpper() == "NULL")  // in this case, user put "null" in appconfig.        
	  return null;      
	Nullable val;      
	try      
	{        
	  val = (T)Convert.ChangeType(valueTxt, typeof(T));      
	}      
	catch (Exception)      
	{        
	  return null;      
	}      
	return val;    
  }
  

Top


What is the smallest positive double value?

We had to calculate a noise in DB from the energy and accumulate. Unfortunately when the energy is zero, then log(energy) produces NaN, which causes accumulated values become NaN. since NaN + anything = NaN. Thus I thought that we use the smallest positive value in place of zero. It is not double.MinValue in C#, since it is the "largest" negative value. You have to use double.Epsilon. No, this is not C++ epsilon nor C DBL_EPSILON. Read http://www.johndcook.com/blog/2010/06/08/c-math-gotchas/.

Top


How can I convert text into T ?

I wanted to write a generic appconfig value reader. My method was to read first as string and then convert the string into a particular type. Here is the way:

  
  T val = (T) Convert.ChangeType(valueTxt, typeof(T));
  

Top


Give me a prototype reflection to get method and execute?

In .NET you can get methods in a type without having a documentation on that type. Here is the prototype:

 
  using System.Reflections; 
  ...  
  // all available methods 
  MethodInfo [] infos = typeof(class).GetMethods(); 
  // find parameters of a particular method called name 
  MethodInfo method = typeof(class).GetMethod(name); 
  ParameterInfo [] pars = method.GetParameters(); 
  // the type of parameter 
  Type parType = pars[i].ParameterType; 
  // return type of a method 
  Type type = method.ReturnType; 
  // execute a method 
  object retObj = method.Invoke((instance of class object), 
                          new object [] { par1, par2, ...}); 
  // create an instance 
  object dynamicObject = Activator.CreateInstance(typeof(class)); 
  // get all properties 
  PropertyInfo [] props = typeof(class).GetProperties(); 
  // get value of a property for indexed arg 
  object val = props[i].GetValue(dynamicObject, new object [] {...}); 
  // type of property 
  Type propType = props[i].PropertyType; 
  // set value 
  props[i].SetValue(dynamicObject, value, new object [] {...});
  

Top


What are the differences between .NET4 and .NET4 Client Profile?

Under Visual Studio 2010, you have a choice of .NET4 vs. .NET4 Client Profile for .NET Framework library. Here is the explanation from the web: http://blogs.msdn.com/b/jgoldb/archive/2010/04/12/what-s-new-in-net-framework-4-client-profile-rtm.aspx.

Top


How can I get thread ID?

I wanted to identify the thread which is shown in Thread Window under VS2008. Under .NET, threading is done differently from OS thread and read http://stackoverflow.com/questions/1679243/c-net-how-to-get-the-thread-id-from-a-thread. However, the thread ID shown in VS2008 is the OS threadID and thus

   
  AppDomain.GetCurrentThreadId()
  or   
  [DllImport("Kernel32", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)]   
  public static extern Int32 GetCurrentWin32ThreadId();
  
By the way, AppDomain.GetCurrentThreadID() is marked as "obsoleted". DotNetThread ID is obtained by System.Threading.Thread.CurrentThread.ManagedThreadId

Top


How can I handle NaN in floating point ops?

If you encounter NaN in calculation, you want to deal with it, otherwise all the operations on that number become NaN, e.g. NaN + normal number = NaN, etc. You cannot use Double.NaN for comparison. You have to use Double.IsNaN(val) function to check.

Top


Subtle difference in value type list and ref type list

I wanted to modify an element in List. It turned out that depending whether T is value type or reference type you have to code differently.

   
  List<ARef> listRef;   
  ...   
  listRef[3].val = 3;
  works,but for a value type you have to do   
  List<AVal> listVal;   
  ...   
  AVal tmp = listVal[3]; /
  / or whatever to copy the object   
  tmp.val = 3;   
  listVal[3] = tmp;
  

Top


How can I not display Assert dialog?

When you put Debug.Assert(...) and the condition is met, then it will pop up a dialog to ask whether to Abort, Retry, or Ignore. You can turn off this dialog to keep going by adding App.config the following (help from Ben):

  
  <configuration>    
  <system.diagnostics>      
  <trace>        
  <listeners>          
  <!-- clear all listners -->          
  <clear/>        
  </listeners>      
  </trace>      
  <assert assertuienabled="false" />    
  </system.diagnostics>  
  </configuration>
  

Top


How can I do AsyncDelegate threading?

I had manual threading with WorkerThreaqd(object obj). I wanted to convert to AsyncDelegate threading. It turned out that it is quite easy. The benefit of AsyncDelegate is that you get unhandled exceptions brought back to the main thread at EndInvoke().

  
  // keep track to be used at EndInvoke()  
  List<IAsyncResult> asyncList = new List();  
  List<WaitCallback> callbackList = new List();  
  asyncList.Clear();  
  while (doThreading)  
  {    
    WaitCallback method = new WaitCallback(WorkerThread);    
    IAsyncResult cookie = method.BeginInvoke(this, null, null);    
    // cache these    
    asyncList.Add(cookie);    
    callbackList.Add(method);  
  }  
  ....  
  // Wait for each WorkerThread() to end.  
  int i=0;   
  foreach (var callbackItem in callbackList)  
  {    
    try     
    {      
      callbackItem.EndInvoke(asyncList[i]);      
      ++i;    
    }    
    catch(Exception ex)    
    {      
      // handle exception    
    }  
  }
  

Top


How can I Invoke a method from a different thread?

When you are doing a Windows Form, sometimes you have to do Invoke(), since the debugger complains about "Cross-thread operation not valid: Control 'myApp' accessed from a thread other than the thread it was created on". Here is the quick way of doing.


  // using anonymous method        
  myApp.Invoke((MethodInvoker)delegate() { myApp.Close(); });
  // using lamba expression        
  myApp.Invoke((MethodInvoker)(() => { myApp.Close(); }));
  

Top


How can I show different data using the same DataGridView?

I wanted to show an object members which has many components in a DataGridView, since DataGridView can bindto a DataSet which is created from a Xml string. I can create object members in XML strings by serializing the object. Everything worked except DataGridView was not able to be updated. I tried datagridview.DataSource = null, but it did not do anything but rows cleared with the same column headers. It turned out that DataSet has to be newed everytime you want to show a different data. Another way is to do DataSet.Columns.Clear().

Top


How can I obtain System Info using WMI?

I needed to obtain the system information like OS, memory, etc. One way is to use Registry. Another way is to use Windows Management Interface (WMI). Here is the way:add reference to System.Management and then

   
  using System.Management;      
  ObjectQuery winQuery = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");   
  ManagementObjectSearcher searcher = new ManagementObjectSearcher(winQuery);   
  foreach (ManagementObject item in searcher.Get())   
  {     
    Debug.WriteLine("Caption = " + item["Caption"]); 
	// Microsoft Windows 7 Professional     
	Debug.WriteLine("Service Pack = " + item["CSDVersion"]); 
	// null if no service pack     
	Debug.WriteLine("OS Architecture = " + item["OSArchitecture"]); 
	// 32-bit or 64-bit     
	Debug.WriteLine("Total Visible Physical Memory = " + item["TotalVisibleMemorySize"]);     
	Debug.WriteLine("Total Virtual Memory = " + item["TotalVirtualMemorySize"]);     
	Debug.WriteLine("Available Virtual Memory = " + item["FreeVirtualMemory"]);   
  }
  

Top


How can I create a deep-copy of an object?

If the class is serializable, then you can use the serializer to create a deep-copy.

  
  static public T DeepCopy(T obj)  
  {    
    using (MemoryStream mstr = new MemoryStream())    
    {      
	  NetDataContractSerializer ndcs = new NetDataContractSerializer();      
	  ndcs.Serialize(mstr, obj);      
	  mstr.Flush();      
	  mstr.Seek(0, SeekOrigin.Begin);       
	  return (T) ndcs.Deserialize(mstr);    
    }  
  }
  

Top


How can I compare value-equalness of two objects?

I wanted to compare two generic objects for their equality. If they are serializable, then you can use DataContractSerializer and XDocument.DeepEquals() for compare as follows:

    
  static public bool CompareObject(object obj1, object obj2)    
  {      
    string a;      
    using (MemoryStream mstr = new MemoryStream())      
	{        
	  NetDataContractSerializer ndcs = new NetDataContractSerializer();        
	  ndcs.Serialize(mstr, obj1);        
	  byte[] byteContent = mstr.ToArray();        
	  a = System.Text.Encoding.UTF8.GetString(byteContent);      
    }      
    
    string b;      
    using (MemoryStream mstr = new MemoryStream())      
    {        
	  NetDataContractSerializer ndcs = new NetDataContractSerializer();        
	  ndcs.Serialize(mstr, obj2);        
	  byte[] byteContent = mstr.ToArray();        
	  b = System.Text.Encoding.UTF8.GetString(byteContent);      
    }      
	XDocument adoc = XDocument.Parse(a);      
	XDocument bdoc = XDocument.Parse(b);      
	return XDocument.DeepEquals(adoc, bdoc);    
  }
  

Top


How can I sort a list with two criteria?

I had the need to sort list with two criteria, first along the ID and then along the time-step. Here is the generic routine. It turned out that LINQ does a nice job if you can specify a key, i.e. Func<TSource, TKey> in the following way:

   
  var query = from m in list               
  orderby m.Name, m.Age               
  select m;or    
  var query = list.OrderBy(m=>m.Name).ThenBy(m=>m.Age);
  
in the case of person list. More generic case (Comparer) is the following but not neat.

  using System.Collections.Generic;
  ...  
  public class DoubleSorter  
  {    
    public static void Sort<T>(ref List<T> myList, IComparer<T> comp1, IComparer<T> comp2)    
	{      
	  // sorted along comp1      
	  myList.Sort(comp1);      
	  // now sorted along comp2 within the same comp1 criteria      
	  int last = myList.Count;      
	  int start = 0;      
	  int count = 0;      
	  int i = 0;      
	  while (start != last)      
	  {        
	    // find out the boundary of the same value along comp1 sort        
		for (i=start; i < last; ++i)        
		{          
		  T first = myList[i];          
		  if (comp1.Compare(first, myList[start]) == 0)            
		    continue;          
		  else            
		    break;        
		}        
		count = i - start;        
		if (count != 1) // count = 1, then no need to sort          
		  myList.Sort(start, count, comp2);        
		start = i;      
	  }    
	}  
  }
  

Top


How can I convert Ascii byte array into string?

Instead of serializing to a file by NetDataContractSerializer, I serialized to MemoryStream. Unfortunately MemoryStream returns only byte[] array. I like to see the text content. Here is the way. Originally I looked at the output array which looked like an ASCII text. It turned out that the serializer uses UTF8 and thus you have to use UTF8 (I found this out by trying to serialize a huge object graph which caused the out-of-memory error. This emitted the call trace.)

  
  // Ascii bytes into string    
  byte [] bytes = mstr.ToArray();    
  string txt = System.Text.Encoding.UTF8.GetString(bytes);  
  // String to bytes    
  byte [] bytes = System.Text.Encoding.UTF8.GetBytes("asciitext");
  

Top


What are the differences between any CPU, x86, x64 platform option?

If you compile .NET program, the platform option usually is Any CPU. I was wondering what are the differences between any CPU, x86, and x64. Microsoft Windows SDK has a tool called CorFlags.exe (in C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin), which can tell you how .NET dlls and applications are compiled. The following shows the example output of CorFlags on a .NET library:


  AnyCPU  
  Version   : v2.0.50727  
  CLR Header: 2.5  PE        
  : PE32              
  <<<<  
  CorFlags  : 9  
  ILONLY    : 1  
  32BIT     : 0                 
  <<<<  
  Signed    : 1
  x86 (32 bit)  
  Version   : v2.0.50727  
  CLR Header: 2.5  
  PE        : PE32              
  <<<<  
  CorFlags  : 11  
  ILONLY    : 1  
  32BIT     : 1                 
  <<<< 
  32 bit  Signed    : 1
  x64 (64bit)  
  Version   : v2.0.50727  
  CLR Header: 2.5  
  PE        : PE32+             
  <<<<< 
  64 bit  CorFlags  : 9  
  ILONLY    : 1  
  32BIT     : 0                 
  <<<<<   
  Signed    : 1
  

If compiled with /x86, then it will run on a 32 bit Windows or on a 64 bit Windows in WOW64 environment as a 32 bit process.   If compiled with /x64, then it will run only on a 64 bit Windows.  If compiled with /anycpu, then it will run natively on both 32 bit and 64 bit windows.   

It turned out that only two libraries loaded are differently when run: mscorlib.dll and System.Data.dll taken from either GAC_32 or GAC_64. The rest are taken from GAC_MSIL.

Top


What are the compression options under .NET?

There are two options for compression, GZipStream and ZipPackage, from Microsoft. However, GZipStream cannot handle filenames nor directories and uses gzip compression. ZipPakcage can handle directories and uses zip compression. It implements Microsoft IPackage so that it is different from the standard zip file. There are two Open-Source projects available: DotNetZip (handles zip compressin only and License is Microsoft Public License (Ms-PL)) and SharpLibZip (handles zip, gzip, tar, bzip2 and license is GPL). Both libraries used under stream way compresses better than those of Microsoft. For my small XML file of 117 KBytes, DotNetZip and SharplibZip compressed to 12 KBytes. Meanwhile Microsoft GZIP and ZipPackage produced 16 KBytes. Here are the examples of usage.

  
  // first define CopyStream() (piping)  
  int CopyStream(Stream input, Stream output)  
  {    
    byte[] buffer = new byte[0x1000];    
	int totCounts = 0;    
	int counts = 0;    
	while ((counts = input.Read(buffer, 0, buffer.Length)) > 0)    
	{      
	  output.Write(buffer, 0, counts);      
	  totCounts += counts;    
	}    
	return totCounts;  
  }  
  // GZipStream compression  
  using System.IO.Compression;  
  ...  
  int totCounts = 0;  
  using (GZipStream compressor = new GZipStream(outstr, CompressionMode.Compress, true))  
  {    
    // take instr, put it into compressor which is connected to outstr    
	totCounts = CopyStream(instr, compressor);  
  }  
  // uncompression is to connect compressor with instr, change option to CompressionMode.Decompress,  
  // and CopyStream(compressor, outstr).  
  // ZipPackage compressing xml text  
  using System.IO.Packaging;  
  ...  
  private const string PackageRelationshipType 
  // unique relationship address     = @"http://schemas.microsoft.com/opc/2006/csc/document";  
  using (Package package = Package.Open(outstr, FileMode.Create))  
  {    
    Uri partUri = PackUriHelper.CreatePartUri(new Uri(obj.ToString() + ".xml", UriKind.Relative));    
	PackagePart partDocument      
	 = package.CreatePart(partUri,System.Net.Mime.MediaTypeNames.Text.Xml, CompressionOption.Maximum);    
	// take instr, put it into compressor which is connected to outstr    
	totCounts = CopyStream(instr, partDocument.GetStream());    
	package.CreateRelationship(partDocument.Uri, TargetMode.Internal, PackageRelationshipType);  
  }  
  // ZipPackage uncompression  
  using (Package package = Package.Open(instr)) // connect instr  
  {    
    PackagePart docuPart = null;    
	Uri uriDocumentTarget = null;    
	// find the content    
	foreach (PackageRelationship rel in package.GetRelationshipsByType(PackageRelationshipType))    
	{      
	  // Resolve the Relationship Target Uri so the Document Part can be retrieved.      
	  uriDocumentTarget = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), rel.TargetUri);      
	  // Open the Document Part, write the contents to a file.      
	  docuPart = package.GetPart(uriDocumentTarget);      
	  int totCounts = 0;      
	  // run compressor to get outstr      
	  totCounts = CopyStream(docuPart.GetStream(),outstr);    
	}  
  }  
  // Open Source way  
  // using ICSharpCode.SharpZipLib.Zip; 
  // SharpZipLib  
  using Ionic.Zip;                      
  // DotNetZip  
  ...  
  // Compression  
  int totCounts = 0;  
  using (ZipOutputStream compressor = new ZipOutputStream(outstr))  
  {    
    ///////////////////////////////////////////////////////    
	// SharpZip    
	// ZipEntry entry = new ZipEntry(obj.ToString()); 
	// add name    
	// compressor.PutNextEntry(entry);    
	// compressor.SetLevel(Level);    
	///////////////////////////////////////////////////////    
	// DotNetZip     
	// the name we put in becomes the filename when unzipped under the Zip Tool    
	compressor.PutNextEntry(obj.ToString());    
	compressor.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;    
	// take instr, put it into compressor which is connected to outstr    
	totCounts = CopyStream(instr, compressor);  
  }  
  // Uncompression (same for both ShaprZipLib and DotNetZip  
  using (ZipInputStream compressor = new ZipInputStream(instr))  
  {    
    ZipEntry entr = compressor.GetNextEntry();    
	int totCounts = 0;    
	// take input str, put it into compressor    
	totCounts = CopyStream(compressor, outstr);  
  }
  

Top


What are the pros and cons of various serializers?

At this time (.NET v3.5sp1), we have the following serialization methods: 

class namepros and cons
Binary Formatter [Serializable] for class required, Compact, Binary, .NET only, Handle generics, Implements IFormatter, Reference preservation enabled.

namespace: System.Runtime.Serialization.Formatters.Binary

reference: System
SoapFormatter [Serializable] for class required, XML format text, Cannot handle generics (throw), Deprecated?, Implements IFormatter

namespace: System.Runtime.Serialization.Formatters.Soap

reference: System.Runtime.Serialization.Formatters.Soap
XmlSerializer XML format, Needs default ctor, Need Type, Only public member (but not readonly) serialized, Cannot handle generics (no throw), Reference preservation enabled.

namespace: System.Xml.Serialization

reference: System.Xml
DataContractSerializer XML format, Serialize everything when [Serializable] attribute on the class (without [Serializable], only public members with read/write access serialized), Need Type, Handle generics, Reference preservation not default (must be set by ctor).

namespace: System.Runtime.Serialization

reference: System.Runtime.Serialization
NetDataContractSerializer XML format, Serialize everything when [Serializable] attribute on the class (without [Serializable], only public members with read/write access serialized), No need for Type, .NET only, Handle generics, Implements IFormatter, Reference preservation enabled. Note that the data serialized by NetDataContractSerializer can be read by DataContractSerializer.

namespace: System.Runtime.Serialization

reference: System.Runtime.Serialization
DataContractJsonSerializer JSON output, Usable by JavaScript, Serialize everything when [Serializable] attribute on the class (without [Serializable], only public members with read/write access serialized), Need Type, Handle generics, No reference preservation option.

namespace: System.Runtime.Serialization.Json

reference: System.ServiceModel.Web

Top


How can I suppress some warnings during compilation?

It is ideal to remove all warning messages during compilation from your program. However, it is not always possible. Thus we need a way. In C#, you use /nowarn:(number) for the compiler argument. You can set this compiler argument in Properties → Build → Suppress Warnings TextEdit Box.  However, this affects the entire code compilation.  If you want to do this in some region of the code, then C# uses a slightly different syntax from C++.  For example, if you get a "warning CS0253", then you surround the code line in the following way (error number is 0253, not CS0253):

  
  #pragma warning disable 0253  
  ...  
  #pragma warning restore
  
Compared with C++ way:
  
  #pragma warning (push)  
  #pragma warning (disable:(number))  
  ...  
  #pragma warning (pop)
  

Top


Is there a dynamic-cast gotcha?

In C#, you use as for dynamic cast. However, when you override operator!=(), then you should not do the following:

   
  Mine m = obj as Mine;   
  if (m != null)     
  ...
  

This is because the left hand side is typeof(Mine) and thus the compiler will use overridden operator!=(), which is not what you want. You have to do the following:

   
  Mine m = obj as Mine;   
  if ((object) m != null) // you have to use Object comparison, not Mine comparison     
  ...
  

Top


How can I create a dialog from Form?

There are two kinds of dialogs: Modal dialog and modeless dialog. Under MFC, it was a real pain to create a modeless dialog. you have to use Create and PostNcDestroy() to "delete this". Under .NET you just do

    
  Form1 form = new Form1();  
  // For modal dialog, you do     
  form.ShowDialog();  
  // For modeless dialog, you do    
  form.Show();
  
It is important to assign AcceptButton and CancelButton in the form property so that Return key hit behaves as OK and ESC key hit behaves as Cancel. See next tip for improvement.

Top


How can I handle input verification on close?

Just add OKButton_Click handler and check there just like MFC OnOK.  Note that the last place you can check is FormClosing event.   When you call Close(), it will cause FormClosing event and if you add a handler, then you can conntrol whether it actually closes or not.   If you set FormClosingEventArgs e.Cancel = true, then your form will never close.  If you set e.Cancel = false, then it proceeds to close.

Top

How can I fix the error "System.Threading.ThreadStateException"?

I got an error from Managed C++ built on Visual Studio 2005 Sp1:

An unhandled exception of type 'System.Threading.ThreadStateException' occurred in System.Windows.Forms.dll

Additional information: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process.

You just add [STAThread] in front of main():

   
  [STAThread]   int main()   
  {   ...   
  }
  

Top


How can I sign both digital signature and strong name?

Under Managed C++, I can sign both digital signature and strong name. Unfortunately both will check the file consistency and you need to do a slight trick. In our case, we timestamp the version "after" the build. Thus we cannot use the keypair snk at the build time (otherwise the file gets modified (corrupted)). Here is the way we come up. The trick is that you don't sign strong signature full but delayed.


  Generate key using sn.
  $ sn -k keyPair.snk
  Then, get the public key out of keyPair.snk.
  $ sn -p keyPair.snk pubKey.snk
  Build your Assembly with only pubKey.snk.
  [assembly:AssemblyDelaySignAttribute(true)];
  [assembly:AssemblyKeyFileAttribute("..\\..\\Certificate\\pubKey.snk")];
  Add the post build event in the project property:
  "$(ProjectDir)..\..\Bin\stampver.exe" -v"$(ProjectDir)..\..\Bin\stampfile.txt" $(OutDir)/my.exe
  sn -R $(Outdir)/my.exe $(Outdir)/../Certificate/keyPair.snk
  "$(ProjectDir)..\..\Certificate\signtool.exe" sign 
    /f $(ProjectDir)..\..\Certificate\retcert.pfx 
    /t http://timestamp.verisign.com/scripts/timstamp.dll /p #$@! 
	$(OutDir)/my.exe
  
The first line corresponds to the version stamping we do. We put our certificate and .snk in the directory called "Certificate". Note that #$@! is the password for the certificate for retcert.pfx. We generated .pfx from .spc and .pvk provided by Thawte, using pvk2pfx.exe

Top


How can I reinstall ASP.NET?

If you know what to do, it is easy (otherwise how can I think of this?).


  $ cd %WinDir%\Microsoft.NET\Framework\v2.0.50727
  $ aspnet_regiis -iStart installing ASP.NET (2.0.50727)
  ........................
  Finished installing ASP.NET (2.0.50727).
  

Top


How can I set the icon for an application or a form?

When I was using MFC, I can easily add an icon for the application in the resource. Under .NET, you have to do for an aapplication:

  
  Right-click on the application project → Properties   
  Application tab → Resources →   
  Use the ... button to pick the icon.  
  It automatically copies the icon  into the project directory.
  
For a Form under VS2008, you do
  
  Go to the design view of a Form (Form1.h [Desgin])  
  Right Click on the form.   
  Select Properties  
  Click on Icon to pick the icon.
  

Top


How can I add Installer for Windows Service


  1. Solution Explorer->Service1.cs->RightClick->View Designer
  2. Right Click on the Service1.cs[Design] on empty space.
  3. Click on "Add Installer"
  4. Modify ServiceProcessInstaller Account property to "Local System".   That
     is, in ProjectInstaller.Designer.cs,       
	 this.serviceProcessInstaller1.Account  = System.ServieProcess.ServiceAccount.LocalSystem;   
	 this.serviceProcessInstaller1.Username = null;   
	 this.serviceProcessInstaller1.Password = null;
  5. Modify ServiceInstaller StartType property to "Manual".   
     this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Manual;
  6. Compile
  7. Goto Visual Studio Command line tool and do       
     InstallUtil MySharpService.exe
  8. For uninstallation, do   
     InstallUtil MySharpService.exe /u"
  

Top


How can I change the path for Windows Services?

Windows Service run as a virtual user:"LocalSystem" which has administrative rights on the system. The working directory is set to %WINDOWS%System32 (even though the executable lives in a different directory) and the default temp is %WINDOWS%\TEMP. No home directory exists for this user and no accesss to network files. If you want to use your own DLLs, you want to change the current directory to be the directory where the window service executable exists. The wizard generated code for your service has OnStart() and you add code to modify the current directory. This means that all your DLLs must be delay loaded, since these cannot be loaded before OnStart().

   
  protected override void OnStart(string[] args)    
  {      
    Process pc = Process.GetCurrentProcess();      
	// set directory to the place where exe is stored      
	String dirBefore = Directory.GetCurrentDirectory().ToString();      
	Debug.WriteLine("dir before " + dirBefore);      
	Directory.SetCurrentDirectory(pc.MainModule.FileName.Substring(0, pc.MainModule.FileName.LastIndexOf(@"\")));      
	String dirAfter = Directory.GetCurrentDirectory().ToString();      
	Debug.WriteLine("dir after " + dirAfter);    
  }
  

In order to see Debug string, you must run DebugView before you start your service ( DebugView by sysinternals).

Top


How can I add System.ServiceModel reference to VS2005 project?

In order to use WCF (Windows Communication Foundation), you have to add reference to System.ServiceModel. Unfortunately, Visual Studio 2005 SP1 won't show this under Add Reference dialog. Make sure that you have .NET framework whose version is higher than or equal to 3.0 (now 3.5). You use Browse tab to point to Program Files\Reference Assembly\Microsoft\Framework\v3.0\System.ServiceModel.dll.

Top


How to configure HTTP?

Here is the way to do this in Vista. Here is HttpConfig utility link (alternative to Microsoft httpcfg).

Top


What is the format option for Console::WriteLine?

Console::WriteLine has a format option. Here is the list

 
  1. Standard Numeric Format Specifiers;  
     {index[,length]:[Format][digit]}    
	 (C) Currency: . . . . . . . . {0:C}    
	 (D) Decimal:. . . . . . . . . {0:D}    
	 (E) Scientific: . . . . . . . {1:E}    
	 (F) Fixed point:. . . . . . . {1:F}    
	 (G) General:. . . . . . . . . {0:G}  (default single 7 digit, double 15 digit)        
	     (default):. . . . . . . . {0} (default = 'G')    
	 (N) Number: . . . . . . . . . {0:N}    
	 (P) Percent:. . . . . . . . . {1:P}    
	 (R) Round-trip: . . . . . . . {1:R}    
	 (X) Hexadecimal:. . . . . . . {0:X} 
  2. Standard DateTime Format Specifiers);    
     (d) Short date: . . . . . . . {0:d}    
	 (D) Long date:. . . . . . . . {0:D}    
	 (t) Short time: . . . . . . . {0:t}    
	 (T) Long time:. . . . . . . . {0:T}    
	 (f) Full date/short time: . . {0:f}    
	 (F) Full date/long time:. . . {0:F}    
	 (g) General date/short time:. {0:g}    
	 (G) General date/long time: . {0:G}        
	 (default):. . . . . . . . {0} (default = 'G')    
	 (M) Month:. . . . . . . . . . {0:M}    
	 (R) RFC1123:. . . . . . . . . {0:R}    
	 (s) Sortable: . . . . . . . . {0:s}    
	 (u) Universal sortable: . . . {0:u} (invariant)    
	 (U) Universal full date/time: {0:U}    
	 (Y) Year: . . . . . . . . . . {0:Y} 
  3. Format a Color enumeration value    
     (G) General:. . . . . . . . . {0:G}        
	 (default):. . . . . . . . {0} (default = 'G')    
	 (F) Flags:. . . . . . . . . . {0:F} (flags or integer)    
	 (D) Decimal number: . . . . . {0:D}    
	 (X) Hexadecimal:. . . . . . . {0:X}      
  

You have to watch out for the formatting difference between .NET and C/C++. The .NET default (G format) uses the float(double) precision to be 7(15) digits, in contrast to C/C++ to be 6 digits for both float and double. Thus unless you specifly both length and digit, you cannot compare float or double formatted printout made by .NET and C/C++ programs. Actually it is really a pain to compare floats (read in http://docs.sun.com/source/806-3568/ncg_goldberg.html).

The object member, ToString(), can take the same formatting syntax.

  
  byte b = 0xFE;  
  Console.WriteLine(b.ToString("X2");
  

Another diversion is DateTime.ToString(format) (here) where format can be one of
string[] standardFmts = {"d", "D", "f", "F", "g", "G", "m", "o", "R", "s", "t", "T", "u", "U", "y"};

         
  d: 6/15/2008       
  D: Sunday, June 15, 2008       
  f: Sunday, June 15, 2008 9:15 PM       
  F: Sunday, June 15, 2008 9:15:07 PM       
  g: 6/15/2008 9:15 PM       
  G: 6/15/2008 9:15:07 PM       
  m: June 15       
  o: 2008-06-15T21:15:07.0000000       
  R: Sun, 15 Jun 2008 21:15:07 GMT       
  s: 2008-06-15T21:15:07       
  t: 9:15 PM       
  T: 9:15:07 PM       
  u: 2008-06-15 21:15:07Z       
  U: Monday, June 16, 2008 4:15:07 AM       
  y: June, 2008
  

Top


Home

What is RawFormat of Bitmap?

Bitmap documentation says that RawFormat is the original format when read-in. When I look at RawForma.ToString(), I get "[ImageFormat: b96b3cae-0728-11d3-9d7b-0000f81ef32e]". James Miles in Thomas Johansen's Blog clarified completely. It turned that this is due to a ImageFormat::ToString() bug. In stead of "Equals(bmp)", somebody used "==bmp" and thus it never matches and the default is to return ("[ImageFormat: "+this.guid+"]"). Therefore you have to do the following stupid things:


  C#: image.RawFormat.ToString() == ImageFormat.Jpeg.Guid.ToString()  etc.
  C++/CLI: image->RawFormat->ToString() == Imaging::ImageFormat::Jpeg->Guid.ToString();
  

Top


How can I create a nested directory?

Java.IO has mkdirs(), but .NET Framework does not need such a thing (thanks Avner Kashtan),

  
  System.IO.Directory.CreateDirectory("c:\\a\\b\\c\\d\\e\\");
  

Top


How can I access an image in resource built in my app?

Usually About dialog in an application contains a fixed image. MSDN article talks about GetManifestResourceStream to retrieve an image from the application resource. My first try for my About dialog did not work. I hit upon http://www.attilan.com/2006/08/accessing_embedded_resources_u.php to find what I needed. Here is the summary.

  
  // Make sure that the image resource property has   
  // Build Action   
  Embedded Resource  
  // otherwise resource won't have this image  
  using System.Reflection;  
  // Assembly  
  using System.Diagnostics; 
  // Debug.WriteLine  
  using System.IO;          
  // Stream  
  using System.Drawing;     
  // Bitmap  
  Assembly assembly_ = Assembly.GetExecutingAssembly();  
  /////////////////////////////////////  
  // listing resources for debugging to make sure  
  // that you call the correct name   
  //////////////////////////////////////  
  // string[] names = assembly_.GetManifestResourceNames();  
  // foreach (string name in names)  
  //   Debug.WriteLine(name);  
  // Look at the solution under Resources for the correct   
  // case-sensitive name for your image  
  Stream s = assembly_.GetManifestResourceStream("MobilEyesRCS.Resources.Retica256.bmp");  
  Bitmap bmp = new Bitmap(s);  
  s.Close();  
  pictureBox1.Image = bmp;
  

Top


How can I lock on a value (non-ref) object?

In multithreading lock<object> is the easiest way to synchronize access. Unfortunately lock() takes only reference type object. Don't try to use Monitor.Entor(value)/Monitor.Exit(value). The reason is that the boxed object created is different from Enter to Exit and thus it won't work. You have to use System.Threading.Interlocked member funcitons.

  
  System.Threading.Interlocked 
  static members are  
  Increment(ref value);  
  Decrement(ref value);  
  Add(ref value1, value2)  
  Exchange(ref v1, v2);  
  CompareExchange(ref v1, v2, comparand);  
  Read(ref value64);  where value is of type Int32 or Int64. 
  
This guarantees the atomic operation.

Top


How can I serialize multiple objects at once?

The serialize/deserialize sample code always talks about a single object serialization. If you want multiple object serialized, then you have to do the following way. When you repeat serializer, it will add the header to each object serialized and thus you will waste space. Worse, if you use XMLSerializer, then it will throw exception when you try to look at the resulting XML file. The trick is to use object array to be serialized.   When using SoapFormatter, you have to add reference to System.Runtime.Serialization.Formatters.Soap.


  // I have serializable class objects, MyType mine and DerivedMyType dmine...      
  // where DerivedMyType is derived from MyType      
  using System.Runtime.Serialization;      
  using System.Runtime.Serialization.Formatters.Binary; 
  // Binary formatter      
  using System.Runtime.Serialization.Formatters.Soap;   
  // Soap formatter      
  ...     
  FileStream fs = new FileStream("MyType.xml", FileMode.Create);      
  SoapFormatter sformatter = new SoapFormatter();      
  // make object array      
  object [] list = { mine, dmine };      
  // then serialize
  sformatter.Serialize(fs, list);      
  fs.Close();      
  // Read back      
  FileStream fs2 = new FileStream("MyType.xml", FileMode.Open);      
  object[] list2 = null;      
  list2 = (object[]) sformatter.Deserialize(fs2);      
  ((MyType) list2[0]).Print();      
  ((MyType) list2[1]).Print();      
  fs2.Close();
  

I thought that the same thing can be done for a generic class object. Soap formatter immediately throws exception, saying that Soap formatter cannot handle generics. Thus I went to XmlSerializer (using System.Xml.Serialization).  (The price for moving to XmlSerilizer is that it can only serialize public data members.)  Unfortnately when I did the following:


object[] list2 = { obj1, obj2 }; XmlSerializer xs = new XmlSerializer(typeof(object[]));
I got throw. If I specified the more specific type like typeof(BankAccount<Person>), then it

BankAccount<Person> list = { me, you }; XmlSerializer xs = new XmlSerializer(typeof(BankAccount<Person> [])); xs.Serialize(str, list);
worked.

Top


Describe various WMI Events you can trigger

Windows provide a way to get information about windows system called WMI (Windows Management Instrumentation). The way to get information is based on the query language called WQL (SQL for WMI). Its syntax is described http://msdn.microsoft.com/en-us/library/aa394606(VS.85).aspx. The query string looks like "SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA Win32_Process". Unfortunately the intellisense does not help here because it is just a string. You have to know each valid word to get the query work. The first thing is the event for FROM. That is called "WMI event". The description is given http://msdn.microsoft.com/en-us/library/aa390355(VS.85).aspx. The entire classes under WMI is described in http://msdn.microsoft.com/en-us/library/aa394554%28VS.85%29.aspx. (... still editing this)

Top


RBS: Give me the list of built-in roles for WindowsPrincipal

Windows has WindowsIdentity and WindowsPrincipal (which provides user's group membership). Using these two classes, you can restrict access to your program at runtime. One of the restriction you can put is based on the role: RoleBasedSecurity. Here is the list of built-in roles:

Built in Role MemberGroup
WindowsBuiltInRole.AccountOperatorAccount Operators
WindowsBuiltInRole.AdministratorAdministrators
WindowsBuiltInRole.BackupOperatorBackup Operators
WindowsBuiltInRole.GuestGuests
WindowsBuiltInRole.PowerUserPower Users
WindowsBuiltInRole.PrintOperatorPrint Operators
WindowsBuiltInRole.ReplicatorReplicator
WindowsBuiltInRole.SystemOperatorServer Operators
WindowsBuiltInRole.UserUsers

You use this role in the following way:

  
  using System.Security.Principal;  
  ...  
  WindowsIdentity curId = WindowsIdentity.GetCurrent();  
  WindowsPrincipal curPrin = new WindowsPrincipal(curId);  
  System.AppDomain.CurrentDomain.SetPrincipalPolity(PrincipalPolicy.WindowsPrincipal);  
  if (curPrin.IsInRole(WindowsBuiltIn.Administrator)    
  ...
  

Note that under Windows7, you do not get Administrator unless you run the program as Administrator even though you belong to the administrator group.

Top


How can I send email without getting authentication failure?

System.Net.Mail (deprecated System.Web.Mail) looks so easy to send emails but when I tried the simple code, I got a "authentication failure" throw. It turned out that I need to attach Credentials to SmtpClient in the following way for my verizon.net account:

   
  using System.Net.Mail;   
  ...   
  MailMessage m = new MailMesssage("from", "to", "subject", "message");   
  // another way   
  // MailMessage m = new MailMessage();   
  // m.To.Add(new MailAddress("tosa.yasunari@gmail.com"));   
  // m.From = new MailAddress("ytosa@verizon.net");   
  // m.Subject = "Testing";   
  // m.SubjectEncoding = System.Text.Encoding.GetEncoding("iso-2022-jp");   
  // m.BodyEncoding = m.SubjectEncoding;   
  // m.Headers.Add("Content-Transfer-Encoding", "7bit");   
  // m.Body = "testing japanese encoding";   
  //        
  // use the correct values for "from" and "to"   
  SmtpClient client = new SmtpClient("smtp server address", 25);    
  // 25 is the standard port   
  client.Credentials = new NetworkCredential("username", "password"); 
  // note explicit password   
  client.Send(m);
  

I tried to use the encoding and Verizon regard the message with encoding specified as spam and refuse to deliver.

Top


How can I sort a list of CultureInfo?

If you want a user to select Culture, you may want to put a combobox with CultureName in it. You also want the combobox to be sorted. Under WPF Combobox, there is no sort option. A quick way to sort is first to create list and use .Sort. Unforutnately it will crash, since CultureInfo does not implement IComparable. Thus you just implement it in this way

  
  // Add IComparable so that I can sort  
  public class MyCultureInfo : CultureInfo, IComparable  
  {    
    public MyCultureInfo():base(CultureInfo.InvariantCulture.Name) { }    
    public MyCultureInfo(CultureInfo ci):base(ci.Name) { }    
    public int CompareTo(object obj)    
    {      
      return this.DisplayName.CompareTo(((CultureInfo) obj).DisplayName);    
    }  
  }  
  // here is the combobox creation routine  
  List<MyCultureInfo> 
  clist = new List<MyCultureInfo>();  
  foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures))    
  clist.Add(new MyCultureInfo(ci));  
  clist.Sort(); 
  // you cannot sort cultureinfo  
  cultureComboBox.ItemsSource = clist;
  

Top


Home

Updated 6/21/2010