vineri, 2 noiembrie 2012

Coding Style


“Programs are meant to be read by humans and only incidentally for computers to execute.”
— H. Abelson and G. Sussman (in “Structure and Interpretation of Computer Programs”)

vineri, 21 septembrie 2012

C#: Extern Aliases



  • If you have to reference types that have the same name and same namespace, you can use extern aliases to bypass this issue
  • Extern aliases also give you a way to access a single type from two (or more) different versions of the same assembly
  • To reference two assemblies with the same fully-qualified type names, an alias must be specified on the command line, as follows:
    /r:GridV1=grid.dll/r:GridV2=grid20.dllor

    From S
    olution Explorer -> Select Project -> References -> on the Grid -> Right-click -> Select Properties -> Change "Aliases" property:

  •  


  • Add the following directive to the top of the code file: extern alias GridV1;extern alias GridV2;


marți, 28 august 2012

How to resolve assembly binding problem in your .NET application?

How to resolve assembly binding problem in your .NET application?

You can register to the following events of System.AppDomain:

  • AssemblyResolve, 
  • ReflectionOnlyAssemblyResolve, 
  • TypeResolve

joi, 23 august 2012

How to Determine which Version of .NET are Installed on your Machine?

How to determine which version of .NET are installed on your machine?


  1. Open Register Editor (cmd->regedit)
  2. Navigate to register key:
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP
  3. Check for subkeys:

miercuri, 22 august 2012

Windbg: SOSEX: Two new commands to fight with deadlocks: !mlocks & !mwaits



  • !mlocks – Lists all managed locks and unmanaged CriticalSections, along with their owner thread ID.

  • Sample:

    0:000> !mlocks
    Examining SyncBlocks...
    Scanning for ReaderWriterLock instances...
    Scanning for holders of ReaderWriterLock locks...
    Scanning for ReaderWriterLockSlim instances...
    Scanning for holders of ReaderWriterLockSlim locks...
    Examining CriticalSections...

    ClrThread  DbgThread  OsThread    LockType    Lock              LockLevel
    ------------------------------------------------------------------------------
    0x243      88         0x1b4c      SyncBlock   000000000bb60408                
    0x1        0          0x50bc      thinlock    00000000106e17f8  (recursion:2)





  • !mwaits – Lists all waiting threads and, if it can be determined, the lock objects they are waiting on.

  • Sample:

    0:000> !mwaits
    Examining SyncBlocks...
    Scanning for ReaderWriterLock instances...
    Scanning for holders of ReaderWriterLock locks...
    Scanning for ReaderWriterLockSlim instances...
    Scanning for holders of ReaderWriterLockSlim locks...
    Examining CriticalSections...
    Scanning for threads waiting on SyncBlocks...
    *** WARNING: Unable to verify checksum for IxNetwork.Main.dll
    Scanning for threads waiting on ReaderWriterLock locks...
    *** WARNING: Unable to verify checksum for mscorlib.ni.dll
    *** WARNING: Unable to verify checksum for System.ni.dll
    *** WARNING: Unable to verify checksum for System.Management.ni.dll
    Scanning for threads waiting on ReaderWriterLocksSlim locks...
    Scanning for threads waiting on CriticalSections...
    *** WARNING: Unable to verify checksum for System.Core.ni.dll
    *** ERROR: Module load completed but symbols could not be loaded for System.Core.ni.dll
    *** WARNING: Unable to verify checksum for System.Windows.Forms.ni.dll
    *** WARNING: Unable to verify checksum for System.Runtime.Remoting.ni.dll
    Scanning threads for waits on unknown locks..


    ClrThread  DbgThread  OsThread    LockType    Lock              LockLevel
    ------------------------------------------------------------------------------
    0x1b2      81         0x31c       <Unknown>   0000000000000000                
    0x218      86         0x8dc       <Unknown>   0000000000000000                
             
    ...             
                  
    0x3b2      92         0x4a54      <Unknown>   0000000000000000                
    0x16       24         0x4c70      <Unknown>   0000000000000000                
    0x0        3          0x4d08      <Unknown>   0000000000000000                
    0xd        13         0x4e34      SyncBlock   000000000bb60408                
    0xb7       77         0x4fd4      <Unknown>   0000000000000000                
    0x3f       59         0x51b8      <Unknown>   0000000000000000                
    0x21a      87         0x51c0      <Unknown>   0000000000000000                
    0x40       58         0x524c      <Unknown>   0000000000000000                
    0x7        7          0x53d0      <Unknown>   0000000000000000                
    ....


    References:
    http://stevestechspot.com/

    luni, 21 mai 2012

    nestat -b: Display The Ownership of The Active Connection

    netstat (network statistics)

    • The netstat command is used to display the TCP/IP network protocol statistics and information

    nestat -b
    • Display the ownership of the active connection, also.


    miercuri, 16 mai 2012

    Get System Uptime Using "systeminfo" Command

    In order to get system up time you can use the systeminfo command.

    Steps:

    1. Open Command Prompt
    2. Type systeminfo
    3. Check for System Up Time field

    luni, 14 mai 2012

    Windbg: Get Assemblies with Version -- !dlls -v

    0:000> !dlls -v


    0x00192f30: C:\Program Files (x86)\Ixia\IxNetwork\6.30.0.76-EB\IxNetwork.exe
          Base   0x104a0000  EntryPoint  0x104a63fe  Size        0x00012000
          Flags  0x00404000  LoadCount   0x0000ffff  TlsIndex    0x00000000
                 LDRP_ENTRY_PROCESSED
                 LDRP_COR_IMAGE
          Company Name       Ixia
          Product Name       IxNetwork
          Product Version    6.30.0.76
          Original Filename  IxNetwork.exe
          File Description   Ixia IxNetwork
          File Version       6.30.0.76

    0x00193020: C:\Windows\SYSTEM32\ntdll.dll
          Base   0x777c0000  EntryPoint  0x00000000  Size        0x001a9000
          Flags  0x00004004  LoadCount   0x0000ffff  TlsIndex    0x00000000
                 LDRP_IMAGE_DLL
                 LDRP_ENTRY_PROCESSED
          Company Name       Microsoft Corporation
          Product Name       Microsoft® Windows® Operating System
          Product Version    6.1.7601.17725
          Original Filename  ntdll.dll
          File Description   NT Layer DLL
          File Version       6.1.7601.17725 (win7sp1_gdr.111116-1503)

    0x00193620: C:\Windows\SYSTEM32\MSCOREE.DLL
          Base   0x7fefaf10000  EntryPoint  0x7fefaf11134  Size        0x0006f000
          Flags  0x00084004  LoadCount   0x0000ffff  TlsIndex    0x00000000
                 LDRP_IMAGE_DLL
                 LDRP_ENTRY_PROCESSED
                 LDRP_PROCESS_ATTACH_CALLED
          Company Name       Microsoft Corporation
          Product Name       Microsoft® .NET Framework
          Product Version    4.0.40305.0
          Original Filename  mscoree.dll
          File Description   Microsoft .NET Runtime Execution Engine
          File Version       4.0.40305.0 (Main.040305-0000)
    ...


    marți, 8 mai 2012

    Windbg: Get System / Process Uptime

    It is first displayed when a dump is loaded in windbg.
    Else, you can use the .time command

    0:000> .time
    Debug session time: Mon Feb 13 16:49:29.000 2012 (GMT+3)
    System Uptime: 22 days 14:43:03.453
    Process Uptime: 0 days 6:26:00.000
      Kernel time: 0 days 0:04:48.000
      User time: 0 days 2:26:11.000

    Or use vertarget command:


    0:000> vertarget
    Windows 7 Version 7601 (Service Pack 1) MP (12 procs) Free x64
    Product: Server, suite: TerminalServer
    kernel32.dll version: 6.1.7601.17651 (win7sp1_gdr.110715-1504)
    Machine Name:
    Debug session time: Fri May 11 23:34:30.000 2012 (UTC + 3:00)
    System Uptime: 3 days 9:16:56.894
    Process Uptime: 0 days 0:14:54.000
      Kernel time: 0 days 0:00:19.000
      User time: 0 days 0:04:43.000

    miercuri, 25 aprilie 2012

    WindowsFormsHost control leaks memory after dispose | Microsoft Connect

    WindowsFormsHost control leaks memory after dispose | Microsoft Connect: "A WindowsFormsHost control that has been displayed on screen and has created its ActivateWindowListener property will not be collected by the GC after it has been removed from the form and disposed."

    'via Blog this'

    miercuri, 11 aprilie 2012

    System.Collections.Generic.Dictionary and Possible Exceptions

    static void Main(string[] i_args)
    {
        Dictionary<string, string> _names = new Dictionary<string, string>
                                                {{"Iliescu", "Ion"}, {"Basescu", "Traian"}
                                                , {null, "Dorel"}}; //ArgumentNullException
        Console.WriteLine(_names[null]); // ArgumentNullException
        Console.WriteLine(_names["Geoana"]); //KeyNotFoundException
    }

    marți, 10 aprilie 2012

    ExecutionEngineException


    The exception that is thrown when there is an internal error in the execution engine of the common language runtime. This class cannot be inherited. (http://msdn.microsoft.com/en-us/library/system.executionengineexception.aspx)


    Causes: 
    - The application or the system on which it is running is under a heavy load 
    - Concurrent garbage collection is not supported in applications running the WOW64 x86 emulator on 64-bit systems that implement the Intel Itanium architecture (formerly called IA-64). (http://msdn.microsoft.com/en-us/library/at1stbec.aspx)
    - DEVPATH environment variable has been set (http://blogs.msdn.com/b/suzcook/archive/2003/08/15/57238.aspx, http://weblogs.asp.net/tgraham/archive/2004/06/07/150225.aspx)
    - memory corruption in unmanaged code or in the interop with unmanaged code (http://k-mug.org/forums/p/816/2632.aspx)
    - serialization throws ExecutionEngineException (http://forums.silverlight.net/t/86739.aspx/1)




    Other info:
    - Known issue for .NET 1.1: (http://support.microsoft.com/kb/827210/) 
    "If you create a new application domain, and you use the Activator class to create a proxy for an object, you may receive the following exception error message from the application: System.ExecutionEngineException occurred in an unkonwn module"
    http://support.microsoft.com/kb/330900:
    "When you use Microsoft .NET COM Interop, and COM interfaces are being marshaled, a typical exception that occurs when the code runs might cause the marshaled interface to be prematurely cleaned up. If this occurs, when you try to use the interface later, the .NET runtime throws an ExecutionEngineException error."






    joi, 16 februarie 2012

    Get the Module / Assembly for a Method with Windbg

    I have a bug, that it is telling that the application hangs. I have the dump for that hang.
    How to tackle the problem:

    • use !threads to look for locks (in the results there is a column "Lock Count")
      • Results: there is no lock on any thread
    • Check the GUI/main thread:  !CLRStack
    0:000> !CLRStack
    Child SP IP       Call Site
    0041de38 7598f5be [InlinedCallFrame: 0041de38] System.Windows.Forms.UnsafeNativeMethods.WaitMessage()
    0041de34 6cf3737a System.Windows.Forms.Application+ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr, Int32, Int32)
    0041ded0 6cf36e2c System.Windows.Forms.Application+ThreadContext.RunMessageLoopInner(Int32, System.Windows.Forms.ApplicationContext)
    0041df28 6cf36c81 System.Windows.Forms.Application+ThreadContext.RunMessageLoop(Int32, System.Windows.Forms.ApplicationContext)
    0041df58 6d42fefb System.Windows.Forms.Application.RunDialog(System.Windows.Forms.Form)
    0041df6c 6d459f83 System.Windows.Forms.Form.ShowDialog(System.Windows.Forms.IWin32Window)
    0041df70 6d45a1b7 [InlinedCallFrame: 0041df70] 
    0041e008 6d45a1b7 System.Windows.Forms.Form.ShowDialog()
    0041e00c 00be1b5f NS_DGFWKP_GUI.DGFWKP_GUI.CollectButton_Click(System.Object, System.EventArgs)
    0041e074 6ced4ae8 System.Windows.Forms.Control.OnClick(System.EventArgs)
    0041e08c 066c42ba DevExpress.XtraEditors.BaseButton.OnClick(System.EventArgs)
    0041e09c 066c41b7 DevExpress.XtraEditors.BaseButton.OnMouseUp(System.Windows.Forms.MouseEventArgs)
    0041e0d0 6d4395b5 System.Windows.Forms.Control.WmMouseUp(System.Windows.Forms.Message ByRef, System.Windows.Forms.MouseButtons, Int32)
    0041e164 6d7fa1bf System.Windows.Forms.Control.WndProc(System.Windows.Forms.Message ByRef)
    0041e168 0fb17195 [InlinedCallFrame: 0041e168] 
    ...
    • So, it is about a modal dialog  that it is displayed in the back of the main window. Most probably. 
    • It should be used  ShowDialog Method (IWin32Window) method instead to avoid this issue.
    • Now the problem is who is  NS_DGFWKP_GUI .. intuitive name :)
    • Use !ip2md to find out more info about  NS_DGFWKP_GUI.DGFWKP_GUI.CollectButton_Click method
    0:000> !ip2md 00be1b5f
    MethodDesc:   1da5450c
    Method Name:  NS_DGFWKP_GUI.DGFWKP_GUI.CollectButton_Click(System.Object, System.EventArgs)
    Class:        1db037dc
    MethodTable:  1da54620
    mdToken:      06000047
    Module:       1da53c70
    IsJitted:     yes
    CodeAddr:     00be1070
    Transparency: Critical
    • Use  !dumpmodule to find out more info about the module
    0:000> !dumpmodule -mt 1da53c70
    Name:       C:\Program Files (x86)\Ixia\IxNetwork\7.0.0.104-EB\diaggui.dll
    Attributes: PEFile 
    Assembly:   11faf8a8
    LoaderHeap:              00000000
    TypeDefToMethodTableMap: 1db0199c
    TypeRefToMethodTableMap: 1db01a24
    MethodDefToDescMap:      1db01c60
    FieldDefToDescMap:       1db01f3c
    MemberRefToDescMap:      1db0206c
    FileReferencesMap:       1db023fc
    AssemblyReferencesMap:   1db02400
    MetaData start address:  1e18d498 (26680 bytes)

    Types defined in this module

          MT  TypeDef Name
    ------------------------------------------------------------------------------
    1da56448 0x02000002 NS_DGFWKP_GUI.ChassisWindow
    2a30b670 0x02000003 NS_DGFWKP_GUI.ChassisChain
    2a30b754 0x02000004 NS_DGFWKP_GUI.Chassis

    • End "voila", I find the responsible module/package for this issue
    • It will be nice if these namespaces will have a meaningful name in the future.

    duminică, 15 ianuarie 2012

    Converters with Parameters


    Converter


    [ValueConversion(typeof (object), typeof (string))]
    public class StringFormatConverter : IValueConverter {
      public object Convert(object i_value, Type i_targetType, object i_parameter,                              System.Globalization.CultureInfo i_culture) {
        string _format = i_parameter as string;
        if (!string.IsNullOrEmpty(format)) {
             return string.Format(i_culture, _format, i_value);
            }
        return i_value.ToString();
      }
    }


    XAML

    <Window.Resources>
      <HierarchicalData:Employee x:Key="myEmployee" FirstName="George" LastName="Lache" Position="DEV" Salary="2000"></HierarchicalData:Employee>
      <Converter:StringFormatConverter x:Key="StringFormatConverter" />
    </Window.Resources>
    <StackPanel DataContext="{StaticResource myEmployee}">
      <Label Content="{Binding FirstName, Converter={StaticResource StringFormatConverter}, ConverterParameter='Many thanks to {0}'}" />
      <Label Content="{Binding Salary, Converter={StaticResource StringFormatConverter}, ConverterParameter='My salary is thanks to {0:c}'}" />
      <Label Content="{Binding Salary, Converter={StaticResource StringFormatConverter}, ConverterParameter=\{0:c\}}" />
      <TextBox Text="{Binding Path=Salary, StringFormat=\{0:c\}}" />
    </StackPanel>




    Result



    vineri, 13 ianuarie 2012

    Readonly Collections are Wrappers over the Read/Write Collections


        class Program
        {
            static void Main(string[] args)
            {
                //Readonly Collections are Wrapper over the Read/Write Collections
                ObservableCollection<string> _observableCollection = new ObservableCollection<string>() { "Mitica", "Dragomir"};
                ReadOnlyObservableCollection<string > _readOnlyObservable = new ReadOnlyObservableCollection<string>(_observableCollection);
    
                _observableCollection.Add("Gigi");
                //_observableCollection and _readOnlyObservable have both 3 items.
    
                List<string> _list = new List<string> { "Mitica", "Dragomir" };
                List<string> _list2 = new List<string>(_list);//here is created a new list of pointers
                ReadOnlyCollection<string> _collection = new ReadOnlyCollection<string>(_list);
                
                _list.Add("Gigi");
                //_list has 3 items  // _list2 has 2 items // _collection has 3 items
    
                
            }
        }