<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Programming and Peace of Mind</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/peaceofmind/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/peaceofmind/feed.xml</link>
    <description />
    <lastBuildDate>Wed, 17 Apr 2019 04:08:18 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Break where the error HRESULT occurs using WinDbg</title>
      <link>https://docs.microsoft.com/archive/blogs/peaceofmind/break-where-the-error-hresult-occurs-using-windbg</link>
      <pubDate>Thu, 05 Feb 2009 10:00:00 GMT</pubDate>
      <dc:creator><![CDATA[enwang]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/peaceofmind/2009/02/05/break-where-the-error-hresult-occurs-using-windbg/</guid>
      <description><![CDATA[When debugging, I found an error&nbsp;HRESULT returned: 0x80020003, but I&nbsp;do not...]]></description>
      <content:encoded><![CDATA[<P>When debugging, I found an error&nbsp;HRESULT returned: 0x80020003, but I&nbsp;do not know&nbsp;which function is producing this error. Instead of going through the call stack, there is a simple way if you use WinDbg. I can start the application and when WinDbg breaks use the following command (on 64 bit machine):</P>
<P><EM>t; z(@rax != 0x0000000080020003)</EM></P>
<P>The application will break where the function returns the error HRESULT.</P>]]></content:encoded>
    </item>
    <item>
      <title>An initialization pattern to avoid problems calling virtual method in constructor</title>
      <link>https://docs.microsoft.com/archive/blogs/peaceofmind/an-initialization-pattern-to-avoid-problems-calling-virtual-method-in-constructor</link>
      <pubDate>Sun, 05 Oct 2008 13:58:00 GMT</pubDate>
      <dc:creator><![CDATA[enwang]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/peaceofmind/2008/10/05/an-initialization-pattern-to-avoid-problems-calling-virtual-method-in-constructor/</guid>
      <description><![CDATA[You are not supposed to call virtual methods in a constructor. The reason being that at the point...]]></description>
      <content:encoded><![CDATA[<P>You are not supposed to call virtual methods in a constructor. The reason being that at the point you call a virtual method in the base class, the derived class has not been initialized. For example, </P><!-- code formatted by https://manoli.net/csharpformat/ --><PRE class=csharpcode>    <SPAN class=kwrd>class</SPAN> Base
    {
        <SPAN class=kwrd>public</SPAN> Base(<SPAN class=kwrd>int</SPAN> input)
        {
            VirtualMethod();
        }
        <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>virtual</SPAN> <SPAN class=kwrd>void</SPAN> VirtualMethod()
        {
        }
    }

    <SPAN class=kwrd>class</SPAN> Derived : Base
    {
        <SPAN class=kwrd>int</SPAN> _val;

        <SPAN class=kwrd>public</SPAN> Derived(<SPAN class=kwrd>int</SPAN> input) : <SPAN class=kwrd>base</SPAN>(input)
        {
            _val = 2 * input;
        }

        <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>override</SPAN> <SPAN class=kwrd>void</SPAN> VirtualMethod()
        {
            Console.WriteLine(<SPAN class=str>"Value is: "</SPAN> + _val.ToString());
        }
    }
</PRE><!-- code formatted by https://manoli.net/csharpformat/ --><PRE class=csharpcode><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-no-proof: yes; mso-fareast-font-family: 'Times New Roman'; mso-fareast-theme-font: minor-fareast; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA">If you create an instance of Derived like</SPAN>&nbsp;</PRE><PRE class=csharpcode>    Derived d = <SPAN class=kwrd>new</SPAN> Derived(5);</PRE>
<P><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: Courier New">the output is not 10 as expected because the constructor of Derived has not been called yet when VirtualMethod is called in Base's constructor. The question is what if you do need to call virtual methods during object creation time. Also do we have to keep track which method is virtual when we make method calls in a constructor? A non-virtual method today may very well be changed to virtual by someone else tomorrow. One solution I found is to have a separate Initialize method to call virtual methods. For example, </SPAN></P><!-- code formatted by https://manoli.net/csharpformat/ --><PRE class=csharpcode>    <SPAN class=kwrd>class</SPAN> Base
    {
        <SPAN class=kwrd>public</SPAN> Base(<SPAN class=kwrd>int</SPAN> input)
        {
            <SPAN class=rem>// Called in Intialize instead of in Constructor</SPAN>
            <SPAN class=rem>// VirtualMethod();</SPAN>
        }

        <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>virtual</SPAN> <SPAN class=kwrd>void</SPAN> Initialize()
        {
            VirtualMethod();
        }

        <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>virtual</SPAN> <SPAN class=kwrd>void</SPAN> VirtualMethod()
        {
        }
    }

    <SPAN class=kwrd>class</SPAN> Derived : Base
    {
        <SPAN class=kwrd>int</SPAN> _val;

        <SPAN class=kwrd>public</SPAN> Derived(<SPAN class=kwrd>int</SPAN> input)
            : <SPAN class=kwrd>base</SPAN>(input)
        {
            _val = 2 * input;
        }

        <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>override</SPAN> <SPAN class=kwrd>void</SPAN> VirtualMethod()
        {
            Console.WriteLine(<SPAN class=str>"Value is: "</SPAN> + _val.ToString());
        }
    }
</PRE>
<P><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: Courier New">To create a Derived instance, you need to call </SPAN></P><!-- code formatted by https://manoli.net/csharpformat/ --><PRE class=csharpcode>    Derived d = <SPAN class=kwrd>new</SPAN> Derived(5);
    d.Initialize();
</PRE>
<P><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: Courier New">The problem is that the caller has to remember to call Initialize after creating the object. I choose to hide the constructor and have a static factory method for clients to create objects, which guarantees that the Initialize method being called. For example, </SPAN></P><!-- code formatted by https://manoli.net/csharpformat/ --><PRE class=csharpcode>    <SPAN class=kwrd>class</SPAN> Base
    {
        <SPAN class=kwrd>protected</SPAN> Base(<SPAN class=kwrd>int</SPAN> input)
        {
            <SPAN class=rem>// Called in Intialize instead of in Constructor</SPAN>
            <SPAN class=rem>// VirtualMethod();</SPAN>
        }

        <SPAN class=kwrd>protected</SPAN> <SPAN class=kwrd>virtual</SPAN> <SPAN class=kwrd>void</SPAN> Initialize()
        {
            VirtualMethod();
        }

        <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>virtual</SPAN> <SPAN class=kwrd>void</SPAN> VirtualMethod()
        {
        }
    }

    <SPAN class=kwrd>class</SPAN> Derived : Base
    {
        <SPAN class=kwrd>int</SPAN> _val;

        <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>static</SPAN> Derived CreateInstance(<SPAN class=kwrd>int</SPAN> input)
        {
            Derived d = <SPAN class=kwrd>new</SPAN> Derived(input);
            d.Initialize();
            <SPAN class=kwrd>return</SPAN> d;
        }

        <SPAN class=kwrd>protected</SPAN> Derived(<SPAN class=kwrd>int</SPAN> input)
            : <SPAN class=kwrd>base</SPAN>(input)
        {
            _val = 2 * input;
        }

        <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>override</SPAN> <SPAN class=kwrd>void</SPAN> VirtualMethod()
        {
            Console.WriteLine(<SPAN class=str>"Value is: "</SPAN> + _val.ToString());
        }
    }
</PRE>
<P><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: Courier New">Creating a Derived object will be like: </SPAN></P><!-- code formatted by https://manoli.net/csharpformat/ --><PRE class=csharpcode>    Derived d = Derived.CreateInstance(5);</PRE>
<P><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: Courier New">I can also go a step furthur to have a rule that the constructor can only be used to initialize fields and never to make method calls. All method calls go into Initialize method. This way there is no more need to keep track whether a method is virtual or not.</SPAN></P>]]></content:encoded>
    </item>
    <item>
      <title>What does it mean for a class to be thread-safe?</title>
      <link>https://docs.microsoft.com/archive/blogs/peaceofmind/what-does-it-mean-for-a-class-to-be-thread-safe</link>
      <pubDate>Wed, 28 May 2008 04:58:00 GMT</pubDate>
      <dc:creator><![CDATA[enwang]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/peaceofmind/2008/05/28/what-does-it-mean-for-a-class-to-be-thread-safe/</guid>
      <description><![CDATA[We often heard the question about whether a class is thread-safe. The answer can be complicated....]]></description>
      <content:encoded><![CDATA[<P>We often heard the question about whether a class is thread-safe. The answer can be complicated. <A class="" title="Effective Java" href="https://www.amazon.com/Effective-Java-Programming-Language-Guide/dp/0201310058" target=_blank mce_href="https://www.amazon.com/Effective-Java-Programming-Language-Guide/dp/0201310058">Effective Java</A> describes 5 levels of thread-safety: </P>
<OL>
<LI>Immutable </LI>
<LI>Thread-safe: multiple threads can access the same instance in any way without causing inconsistent state. </LI>
<LI>Conditionally thread-safe: weaker than thread-safe in that some sequences of method calls need external synchronization. For example, for a class implementing Stack, the class implementation can do proper locking within individual methods like Push and Pop, but it still does not protect against multiple threads calling Push followed by Pop. In this case, the client needs to do synchronization. </LI>
<LI>Thread-compatible: even weaker in that each method may need external synchronization, but it still allows client to write thread-safe code. </LI>
<LI>Thread-hostile: no way for client to write thread-safe code. For example, if private static state access is not synchronized, there is no way for client to know and do synchronization on its own. </LI></OL>
<P>So a better question is: can the class be used in a thread-safe way? That is the reason that in general, a class needs to <A class="" title="Joe Duffy's blog" href="https://www.bluebytesoftware.com/blog/PermaLink,guid,f8404ab3-e3e6-4933-a5bc-b69348deedba.aspx" target=_blank mce_href="https://www.bluebytesoftware.com/blog/PermaLink,guid,f8404ab3-e3e6-4933-a5bc-b69348deedba.aspx">synchronize access to the static state, but not the instance state</A>. </P>]]></content:encoded>
    </item>
    <item>
      <title>Why, in Visual Studio 2008, opening a VSTO Office 2003 AddIn project gets upgrade wizard?</title>
      <link>https://docs.microsoft.com/archive/blogs/peaceofmind/why-in-visual-studio-2008-opening-a-vsto-office-2003-addin-project-gets-upgrade-wizard</link>
      <pubDate>Thu, 15 May 2008 01:20:00 GMT</pubDate>
      <dc:creator><![CDATA[enwang]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/peaceofmind/2008/05/15/why-in-visual-studio-2008-opening-a-vsto-office-2003-addin-project-gets-upgrade-wizard/</guid>
      <description><![CDATA[Recently a customer asks an issue about using VSTO (Visual Studio Tools for Office) in Visual Studio...]]></description>
      <content:encoded><![CDATA[<P>Recently a customer asks an issue about using VSTO (Visual Studio Tools for Office) in Visual Studio 2008. He created an Office 2003 AddIn project, closed it, reopened it, and he is prompted to upgrade. To make it more confusing, the upgrade wizard says the solution is created by a previous version of Visual Studio. The&nbsp;explanation is that, if you don't have Office 2003 installed on your machine, we have assumed you want to upgrade to Office 2007. To override that behavior, you can go to Tools-&gt;Options…-&gt;Office Tools-&gt;Project Upgrade and uncheck "Always upgrade to installed version of Office" like: </P>
<P><IMG title="VSTO Office Upgrade Options" style="WIDTH: 644px; HEIGHT: 384px" height=384 alt="VSTO Office Upgrade Options" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/08/50/65/48/VstoUpgradeOption.PNG" original-url="https://blogs.msdn.com/photos/enwang/images/8506548/original.aspx" width=644 align=baseline mce_src="https://blogs.msdn.com/photos/enwang/images/8506548/original.aspx"></P>
<P><SPAN style="COLOR: #1f497d"></SPAN></P>
<P>Please See <A href="https://msdn.microsoft.com/en-us/library/k2xkefex.aspx" mce_href="https://msdn.microsoft.com/en-us/library/k2xkefex.aspx"><SPAN style="COLOR: #0070c0">https://msdn.microsoft.com/en-us/library/k2xkefex.aspx</SPAN></A> for more info. The upgrade wizard is confusing in this case. We are relying on the Visual Studio standard upgrade mechanism, which (in VS 2008) does not allow external packages like VSTO to modify the wizard UI. So no matter what&nbsp;the real reason to upgrade (Office version upgrade in this case), you always see the message that the solution used a previous version of Visual Studio. Hopefully we can ask the Visual Studio Platform team to make the upgrade wizard extensible in the next version. </P>]]></content:encoded>
    </item>
    <item>
      <title>When to catch all exceptions?</title>
      <link>https://docs.microsoft.com/archive/blogs/peaceofmind/when-to-catch-all-exceptions</link>
      <pubDate>Fri, 09 May 2008 01:56:00 GMT</pubDate>
      <dc:creator><![CDATA[enwang]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/peaceofmind/2008/05/09/when-to-catch-all-exceptions/</guid>
      <description><![CDATA[One of the general guidelines of exception handling in .Net is to catch the exceptions that you know...]]></description>
      <content:encoded><![CDATA[<P>One of the general guidelines of exception handling in .Net is to catch the exceptions that you know how to handle and not to catch all exceptions. Even if you intend to re-throw the exception and know <A href="https://msdn.microsoft.com/en-us/library/ms229005.aspx" mce_href="https://msdn.microsoft.com/en-us/library/ms229005.aspx">the difference between <EM>throw ex </EM>and<EM> throw</EM></A>, it is still better not to do it since <A href="https://kristofverbiest.blogspot.com/2007/02/rethrow-exception-using-throw.html" mce_href="https://kristofverbiest.blogspot.com/2007/02/rethrow-exception-using-throw.html"><EM>throw</EM> does modify the stack trace slightly</A>.<EM> </EM>In reality, <A href="https://www.geocities.com/csharpfaq/exceptions.html" mce_href="https://www.geocities.com/csharpfaq/exceptions.html">this is not easy to follow</A> because you can only rely on documentation about the exceptions a C# method may throw. Documentation is, well, just documentation. However, there is at least one case that it is better to catch all exceptions. That is when the caller does not have a concept of exception at all. For example, you write a component to be consumed through .Net interop by a COM component. Because the exception will be converted to a HRESULT and there is no guarantee that the caller will check the HRESULT, COM interop is effectively "swallowing" the exception. In this case, I found it is much better to catch all exceptions in the .Net method and do some assertion and logging.</P>]]></content:encoded>
    </item>
    <item>
      <title>Determine share mode of opened file handle</title>
      <link>https://docs.microsoft.com/archive/blogs/peaceofmind/determine-share-mode-of-opened-file-handle</link>
      <pubDate>Wed, 07 May 2008 00:52:00 GMT</pubDate>
      <dc:creator><![CDATA[enwang]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/peaceofmind/2008/05/07/determine-share-mode-of-opened-file-handle/</guid>
      <description><![CDATA[If there is a file already opened and you also want to open it, you need to know the share mode:...]]></description>
      <content:encoded><![CDATA[<P>If there is a file already opened and you also want to open it, you need to know the share mode: FILE_SHARE_* the previous CreateFile calls have specified. I came across the problem and the first thing I tried is to use <A class="" title=ProcessMonitor href="https://technet.microsoft.com/en-us/sysinternals/bb896645.aspx?PHPSESSID=d926bdd849b5aab10f7263dd7f5904f2" target=_blank mce_href="https://technet.microsoft.com/en-us/sysinternals/bb896645.aspx?PHPSESSID=d926bdd849b5aab10f7263dd7f5904f2">Process Monitor</A>, which shows all the flags passed in when CreateFile is called. For example, you have information like:</P>
<P>... EXCEL.EXE&nbsp;&nbsp;&nbsp; 5940&nbsp;&nbsp;&nbsp; CreateFile&nbsp;&nbsp;&nbsp; D:\temp\bbbb.xlsx&nbsp;&nbsp;&nbsp; SUCCESS&nbsp;&nbsp;&nbsp; Desired Access: Generic Read/Write, Disposition: OpenIf, Options: Synchronous IO Non-Alert, Non-Directory File, Open No Recall, Attributes: n/a, <STRONG>ShareMode: Read</STRONG>, ... 
<P>However, there can be many CreateFile calls. You have to go through them carefully. With that information, I tried to call:</P>
<BLOCKQUOTE><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-no-proof: yes">
<P class=MsoNormal style="MARGIN: 0in 0in 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-no-proof: yes">HANDLE hFile = CreateFile(<SPAN style="mso-spacerun: yes">&nbsp; </SPAN>_T(<SPAN style="COLOR: #a31515">"d:\\temp\\bbbb.xlsx"</SPAN>),<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0in 0in 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-no-proof: yes"><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>GENERIC_READ,<SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN><SPAN style="COLOR: green">// open for reading<o:p></o:p></SPAN></SPAN></P>
<P class=MsoNormal style="MARGIN: 0in 0in 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-no-proof: yes"><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>FILE_SHARE_READ,<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0in 0in 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-no-proof: yes"><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>NULL,<SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN><SPAN style="COLOR: green">// default security<o:p></o:p></SPAN></SPAN></P>
<P class=MsoNormal style="MARGIN: 0in 0in 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-no-proof: yes"><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>OPEN_EXISTING,<SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN><SPAN style="COLOR: green">// existing file<o:p></o:p></SPAN></SPAN></P>
<P class=MsoNormal style="MARGIN: 0in 0in 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-no-proof: yes"><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>FILE_ATTRIBUTE_NORMAL, <SPAN style="COLOR: green"><o:p></o:p></SPAN></SPAN></P>
<P class=MsoNormal style="MARGIN: 0in 0in 10pt"><SPAN style="FONT-SIZE: 10pt; LINE-HEIGHT: 115%; FONT-FAMILY: 'Courier New'; mso-no-proof: yes"><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>NULL);<SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</SPAN></SPAN></SPAN><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-no-proof: yes; mso-fareast-font-family: Calibri; mso-fareast-theme-font: minor-latin; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA"><SPAN style="mso-spacerun: yes">&nbsp; </SPAN></SPAN></P></BLOCKQUOTE>
<P><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'; mso-no-proof: yes; mso-fareast-font-family: Calibri; mso-fareast-theme-font: minor-latin; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA"><SPAN style="mso-spacerun: yes"></SPAN></SPAN>However It does not work. I&nbsp;suspected whether the information I got from ProcessMonitor is correct. After some searching, I learned that <A class="" title=FILE_OBJECT href="https://msdn.microsoft.com/en-us/library/aa906961.aspx" target=_blank mce_href="https://msdn.microsoft.com/en-us/library/aa906961.aspx">FILE_OBJECT</A> structure actually contains this information. You could use WinDBG to get it. What I did is to choose File-&gt;Kernel Debug...-&gt;Local. Then use <A class="" title="Process Explorer" href="https://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" target=_blank mce_href="https://technet.microsoft.com/en-us/sysinternals/bb896653.aspx">Process Explorer</A> to obtain the file handle address of the file and issue !fileobj on it like:&nbsp; </P>
<BLOCKQUOTE>
<P>lkd&gt; !fileobj 0x8939F1C8 
<P>The output is like: 
<P>\temp\bbbb.xlsx 
<P>Device Object: 0x89e51900&nbsp;&nbsp; \Driver\Ftdisk<BR>Vpb: 0x89e21070<BR>Event signalled<BR>Access: Read Write <STRONG>SharedRead</STRONG> </P></BLOCKQUOTE>
<P>It basically&nbsp;has the same information as what I got from ProcessMonitor. Now staring at it longer, I realized I didn't read <A class="" title="Raymond's blog" href="https://blogs.msdn.com/oldnewthing/archive/2004/05/11/129759.aspx" target=_blank mce_href="https://209.34.241.67/oldnewthing/archive/2004/05/11/129759.aspx">Raymond Chen's blog</A> carefully: the FILE_SHARE_* mode needs to be compatible with previous access mode. In my case, the file has been opened as GENERIC_READ | GENERIC_WRITE, the share mode in the latter CreateFile has to be at least FILE_SHARE_READ | FILE_SHARE_WRITE. Changing that and the file can now be opened.</P>]]></content:encoded>
    </item>
    <item>
      <title>To mock or not to mock?</title>
      <link>https://docs.microsoft.com/archive/blogs/peaceofmind/to-mock-or-not-to-mock</link>
      <pubDate>Sun, 27 Apr 2008 18:18:00 GMT</pubDate>
      <dc:creator><![CDATA[enwang]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/peaceofmind/2008/04/27/to-mock-or-not-to-mock/</guid>
      <description><![CDATA[In Wikipedia's definition of Unit test, it says "Ideally, each test case is independent from the...]]></description>
      <content:encoded><![CDATA[<P>In Wikipedia's definition of <A href="https://en.wikipedia.org/wiki/Unit_test" mce_href="https://en.wikipedia.org/wiki/Unit_test">Unit test</A>, it says "Ideally, each test case is independent from the others; mock or fake objects as well as test harnesses can be used to assist testing a module in isolation." If we follow this definition strictly, whenever the class under test collaborates with other classes, we need to mock the dependent classes. (Here we do not differentiate among mock, stub, fake, etc. A <A href="https://xunitpatterns.com/Test%20Double.html" mce_href="https://xunitpatterns.com/Test%20Double.html">test double</A> might be a better term.) The main benefit of mocking is that we can test our class in isolation. As a result, </P>
<OL>
<LI>If the dependent classes are hard to set up, take too long to run, or are still at an early development stage, mocking can make writing tests easier, and help the tests run faster and be more stable. </LI>
<LI>We can test more thoroughly by manipulating the mock objects to produce input that cannot easily be done with real objects. </LI>
<LI>If a bug is introduced in one class, ideally you will only have one test case fail. We only need to look at the class under test and do not need to worry about the dependent classes. It saves test maintenance and debugging time. </LI></OL>
<P>The disadvantages of mocking are: </P>
<OL>
<LI>It can be extra overhead. To do "pure" unit test, you either create many mock classes or have test code that are specifically for mocking if you use dynamic mocking. The test code can take longer to write and be harder to read and maintain. </LI>
<LI>With mocking, unit tests are testing less. It doesn't test the potential bugs coming from the interaction between classes. Some may argue that's the point of unit testing. Collaboration between classes should be tested by integration tests or functional tests. However, unit tests are our first line of defense. If we can catch bugs early with actually less effort by not mocking, I see no reason to mock unless there are other benefits. </LI>
<LI>If we are doing mocking blindly, we can miss the opportunity of using tests to make our classes more testable. For example, at an extreme, without any mocking, we can change all the interfaces to only use primitive types to achieve the goal of test in isolation. In some cases, it may indeed make sense to change the interface instead of mocking. If we always mock, it can be harder to see that. </LI></OL>
<P>To me, it feels more natural initially not to mock even though it means I may not be doing "pure" unit testing [1]. I'll only mock when it's necessary or it's really better than using the real objects. If we are constantly running tests (unit test or not), when tests fail, the first thing to look at is the last batch of check-ins. So the gain of mocking may not be substantial in a lot of cases. I think if our goal is to have "<A href="https://www.amazon.com/Test-Driven-Development-Addison-Wesley-Signature/dp/0321146530" mce_href="https://www.amazon.com/Test-Driven-Development-Addison-Wesley-Signature/dp/0321146530">clean code that works</A>," we basically want to spend minimum effort to have good design with maximum code coverage. It should be secondary whether we are doing "pure" unit tests or not. </P>
<P>[1] In <A class="" href="https://martinfowler.com/articles/mocksArentStubs.html" mce_href="https://martinfowler.com/articles/mocksArentStubs.html">Mocks Aren't Stubs</A>, Martin Fowler differentiates between Classical TDDers and Mockist TDDers. Classical TDDers (Fowler being one) actually treat unit tests as mini-integration tests. I feel more comfortable with the classical TDD approach. </P>
<P>Keyword: unit test, mock, Martin Fowler </P>]]></content:encoded>
    </item>
    <item>
      <title>Waste-less Programming</title>
      <link>https://docs.microsoft.com/archive/blogs/peaceofmind/waste-less-programming</link>
      <pubDate>Mon, 21 Apr 2008 03:43:00 GMT</pubDate>
      <dc:creator><![CDATA[enwang]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/peaceofmind/2008/04/21/waste-less-programming/</guid>
      <description><![CDATA[Waste-less programming is my way of thinking about getting better at programming. We, as...]]></description>
      <content:encoded><![CDATA[<P>Waste-less programming is my way of thinking about getting better at programming. We, as programmers, all want to build great software. To do that, we want to be the ones that can hit <A href="https://www.joelonsoftware.com/articles/HighNotes.html" mce_href="https://www.joelonsoftware.com/articles/HighNotes.html">higher notes</A>. The time and effort we spend are wasted if they do not help us towards those goals. Sometimes waste-less does not mean simply faster or more efficient. For example, unit testing or running FxCop to check our code is something we should do. However, recently a project I've been working on is cut. If I have been focused on doing unit testing or running FxCop, my effort would've been mostly wasted no matter how efficient I have been. Instead since I've been mostly validating major design decisions, the majority of my work is still applicable to the next project. In <A href="https://www.amazon.com/Beautiful-Code-Leading-Programmers-Practice/dp/0596510047/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1208762932&amp;sr=8-1" mce_href="https://www.amazon.com/Beautiful-Code-Leading-Programmers-Practice/dp/0596510047/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1208762932&amp;sr=8-1">Beautiful Code</A>, Bryan Cantrill mentions that a crucial task at the early stage of a project is to implement the hardest problems and validate the major architecture to try to eliminate those problems that can later invalidate the whole design and architecture. Considering "If you put a spoonful of sewage in a barrel full of wine, you get sewage," the task is to "assure that the most fetid spoonfuls are caught as early as possible, when design changes are still possible—and when the wine can still be saved." Learning from <A href="https://paulgraham.com/hamming.html" mce_href="https://paulgraham.com/hamming.html">Richard Hamming</A> who asks: What're the important problems in your field? Are you working on one of them? If not, why not? I found that asking myself that "Can I do this at a later date? If yes, are there more important things to do?" has been very valuable to avoid waste.</P>]]></content:encoded>
    </item>
    <item>
      <title>Using EventProviderTraceListener</title>
      <link>https://docs.microsoft.com/archive/blogs/peaceofmind/using-eventprovidertracelistener</link>
      <pubDate>Wed, 16 Apr 2008 02:19:00 GMT</pubDate>
      <dc:creator><![CDATA[enwang]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/peaceofmind/2008/04/16/using-eventprovidertracelistener/</guid>
      <description><![CDATA[In .Net framework 3.5, there is a new trace listener, EventProviderTraceListener, which you can use...]]></description>
      <content:encoded><![CDATA[<P>In .Net framework 3.5, there is a new trace listener, EventProviderTraceListener, which you can use to do ETW tracing. There are good <A class="" href="https://msdn2.microsoft.com/en-us/magazine/cc163437.aspx" target=_blank mce_href="https://msdn2.microsoft.com/en-us/magazine/cc163437.aspx">introduction</A> and some intimidating <A class="" href="https://www.atrevido.net/blog/CommentView,guid,1b0c68ce-d168-4210-86fb-4f2b2126bfc0.aspx" target=_blank mce_href="https://www.atrevido.net/blog/CommentView,guid,1b0c68ce-d168-4210-86fb-4f2b2126bfc0.aspx">tips</A>. It took me a while to figure out that, to do a simple ETW trace, you can just configure it like a normal trace listener by having an app config file like: </P>
<P>&lt;configuration&gt; </P>
<P>&lt;system.diagnostics&gt; </P>
<P>&lt;trace autoflush="true" indentsize="4"&gt; </P>
<P>&lt;listeners&gt; </P>
<P>&lt;add name="myListener" type="System.Diagnostics.Eventing.EventProviderTraceListener, System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" initializeData="{BF8671E1-2B70-41f3-AE0C-993C6A7D6763}" /&gt; </P>
<P>&lt;remove name="Default" /&gt; </P>
<P>&lt;/listeners&gt; </P>
<P>&lt;/trace&gt; </P>
<P>&lt;/system.diagnostics&gt; </P>
<P>&lt;/configuration&gt; </P>
<P>I put the event provider ID as initializeData and it seems to work. With that config file, you can simply use Trace.WriteLine("my message"). </P>
<P>To start a trace session, do: </P>
<P>logman start mysession -p {BF8671E1-2B70-41f3-AE0C-993C6A7D6763} -o mytest.etl -ets </P>
<P>After you are done with tracing, you can stop by </P>
<P>logman stop mysession -ets </P>
<P>Then you can use tracerpt to dump the log to readable format. </P>
<P>tracerpt mytest.etl </P>
<P>ETW tracing is very customizable, but for doing simple tracing for debugging, it seems logging a message is enough. One advantage of using ETW tracing is performance. I did some simple measurement with a loop like: </P><!-- code formatted by https://manoli.net/csharpformat/ --><PRE class=csharpcode>            Stopwatch timePerParse = Stopwatch.StartNew();            
            <SPAN class=kwrd>for</SPAN> (<SPAN class=kwrd>int</SPAN> i = 0; i &lt; 50000; ++i)            
            {                
                Trace.WriteLine(<SPAN class=str>"this is using Trace"</SPAN>);
            }
            timePerParse.Stop();
            MessageBox.Show(timePerParse.ElapsedMilliseconds.ToString());</PRE>
<P>The result is like (on a 2.4 GHz machine): </P>
<DIV>
<TABLE class="" style="BORDER-COLLAPSE: collapse" border=0>
<COLGROUP>
<COL style="WIDTH: 319px">
<COL style="WIDTH: 319px"></COLGROUP>
<TBODY vAlign=top>
<TR>
<TD class="" style="BORDER-RIGHT: black 0.5pt solid; PADDING-RIGHT: 7px; BORDER-TOP: black 0.5pt solid; PADDING-LEFT: 7px; BORDER-LEFT: black 0.5pt solid; BORDER-BOTTOM: black 0.5pt solid">
<P>Default trace listener with DBGView.exe</P></TD>
<TD class="" style="BORDER-RIGHT: black 0.5pt solid; PADDING-RIGHT: 7px; BORDER-TOP: black 0.5pt solid; PADDING-LEFT: 7px; BORDER-LEFT: medium none; BORDER-BOTTOM: black 0.5pt solid">
<P>14196ms</P></TD></TR>
<TR>
<TD class="" style="BORDER-RIGHT: black 0.5pt solid; PADDING-RIGHT: 7px; BORDER-TOP: medium none; PADDING-LEFT: 7px; BORDER-LEFT: black 0.5pt solid; BORDER-BOTTOM: black 0.5pt solid">
<P>TextWriterTraceListener</P></TD>
<TD class="" style="BORDER-RIGHT: black 0.5pt solid; PADDING-RIGHT: 7px; BORDER-TOP: medium none; PADDING-LEFT: 7px; BORDER-LEFT: medium none; BORDER-BOTTOM: black 0.5pt solid">
<P>211ms</P></TD></TR>
<TR>
<TD class="" style="BORDER-RIGHT: black 0.5pt solid; PADDING-RIGHT: 7px; BORDER-TOP: medium none; PADDING-LEFT: 7px; BORDER-LEFT: black 0.5pt solid; BORDER-BOTTOM: black 0.5pt solid">
<P>EventProviderTraceListener</P></TD>
<TD class="" style="BORDER-RIGHT: black 0.5pt solid; PADDING-RIGHT: 7px; BORDER-TOP: medium none; PADDING-LEFT: 7px; BORDER-LEFT: medium none; BORDER-BOTTOM: black 0.5pt solid">
<P>77ms</P></TD></TR></TBODY></TABLE></DIV>
<P>Note: EventProviderTraceListener currently is only supported on Vista. </P>
<P>Keywords: ETW tracing EventProviderTraceListener System.Diagnostics.Eventing.EventProviderTraceListener logman.exe tracerpt.exe</P>]]></content:encoded>
    </item>
    <item>
      <title>Abstract Class or Interface II</title>
      <link>https://docs.microsoft.com/archive/blogs/peaceofmind/abstract-class-or-interface-ii</link>
      <pubDate>Mon, 07 Apr 2008 21:38:00 GMT</pubDate>
      <dc:creator><![CDATA[enwang]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/peaceofmind/2008/04/07/abstract-class-or-interface-ii/</guid>
      <description><![CDATA[In previous post, I was convinced that abstract class was the right choice for the work I am doing....]]></description>
      <content:encoded><![CDATA[<P>In <A class="" title="Abstract Class or Interface I" href="https://blogs.msdn.com/peaceofmind/archive/2008/03/31/abstract-class-or-interface.aspx" target=_blank mce_href="https://blogs.msdn.com/peaceofmind/archive/2008/03/31/abstract-class-or-interface.aspx">previous post</A>, I was convinced that abstract class was the right choice for the work I am doing. However, when I got deeper into the work, I had to switch to use interface simply because abstract class does not support multiple inheritance. </P>
<P>I am creating a hierarchy of pure abstract classes to be accessed by user and another hierarchy of classes having the implementation. For example, </P><!-- code formatted by https://manoli.net/csharpformat/ --><PRE class=csharpcode>    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>abstract</SPAN> <SPAN class=kwrd>class</SPAN> Foo
    {
        <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>abstract</SPAN> <SPAN class=kwrd>void</SPAN> Bar();
    }

    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>abstract</SPAN> <SPAN class=kwrd>class</SPAN> SubFoo : Foo
    {
        <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>abstract</SPAN> <SPAN class=kwrd>void</SPAN> Baz();
    }

    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>class</SPAN> FooImpl : Foo
    {
        <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>override</SPAN> <SPAN class=kwrd>void</SPAN> Bar()
        {
            <SPAN class=rem>// implementation</SPAN>
        }
    }
</PRE>
<P>Now if I try to&nbsp;create a class like:</P><!-- code formatted by https://manoli.net/csharpformat/ --><PRE class=csharpcode>    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>class</SPAN> SubFooImpl : SubFoo, FooImpl
    {
        <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>void</SPAN> Baz()
        {
            <SPAN class=rem>// implementation</SPAN>
        }
    }</PRE>
<P>I get syntax error because SubFooImpl cannot inherit from both Foo and FooImpl. The problem here is that SubFooImpl needs to assume the identity of SubFoo and also borrows implementation from FooImpl. You can only use interface in this case. The code will be like: </P><!-- code formatted by https://manoli.net/csharpformat/ --><PRE class=csharpcode>    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>interface</SPAN> IFoo
    {
        <SPAN class=kwrd>void</SPAN> Bar();
    }

    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>interface</SPAN> ISubFoo : IFoo
    {
        <SPAN class=kwrd>void</SPAN> Baz();
    }

    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>class</SPAN> FooImpl : IFoo
    {
        <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>void</SPAN> Bar()
        {
            <SPAN class=rem>// implementation</SPAN>
        }
    }

    <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>class</SPAN> SubFooImpl : FooImpl, ISubFoo
    {
        <SPAN class=kwrd>public</SPAN> <SPAN class=kwrd>void</SPAN> Baz()
        {
            <SPAN class=rem>// implementation</SPAN>
        }
    }</PRE>
<P>This is an example that guidelines of programming is not something we can blindly follow. Without understanding the reasoning and context, they can still lead to the wrong choice.</P>
<P>Keywords: .Net, abstract class, interface</P>]]></content:encoded>
    </item>
  </channel>
</rss>