<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-1945083783625463663</id><updated>2025-01-26T11:34:17.460-08:00</updated><title type='text'>.NET and Beyond</title><subtitle type='html'>A developer&#39;s notes - C# / .NET</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><link rel='next' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default?start-index=26&amp;max-results=25'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>35</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-9042369794605277709</id><published>2014-12-16T20:34:00.000-08:00</published><updated>2014-12-16T20:36:07.303-08:00</updated><title type='text'>How to debug SQLCLR in VS 2012</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is how to debug your SQLCLR code in Visual Studio.&lt;br /&gt;
I assume that you already have your SQLCLR DLL and its related stored procedure set up in your SQL Server.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;ol style=&quot;line-height: 1.5em;&quot;&gt;
&lt;li&gt;Launch VS 2012.&lt;/li&gt;
&lt;li&gt;Open &quot;SQL Server Object Explorer&quot; (can be opened from View -&amp;gt; SQL Server Object Explorer menu)&lt;/li&gt;
&lt;li&gt;In SQL Server Object Explorer, add connection to target SQL Server (ex: local SQL server) where SQLCLR is located. Local SQL instance will be best for debugging.&lt;/li&gt;
&lt;li&gt;Rightclick on the connection and choose [Allow SQL/CLR debugging].&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhhQfhZGGLWe3Z0tg7eoZONgmJKcTEsqkYLSyD9pEQj0edVtcKM54BzJ2WIIqYIJAcBTOuRPOkIZtozXYNry9wlOPxaXgbldJfJ-6xBSr3AThlU1Fgu_9xzCQv0-16RZqRlUYr8LRODtA4/s1600/sqlclr-allow.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;
&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhhQfhZGGLWe3Z0tg7eoZONgmJKcTEsqkYLSyD9pEQj0edVtcKM54BzJ2WIIqYIJAcBTOuRPOkIZtozXYNry9wlOPxaXgbldJfJ-6xBSr3AThlU1Fgu_9xzCQv0-16RZqRlUYr8LRODtA4/s1600/sqlclr-allow.png&quot; /&gt;&lt;/a&gt;
&lt;br /&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;Find your stored procedure (or function) you want to debug. This SP should be entry point of the SQLCLR.&lt;/li&gt;
&lt;li&gt;Rightclick on the SP and choose &quot;Debug Procedure&quot;&lt;/li&gt;
&lt;li&gt;Enter input value in the &quot;Debug Stored Procedure&quot; dialog and click OK. This will open new SQLQuery window and automatically generate TSQL script to start debugging.&lt;/li&gt;
&lt;li&gt;In SQLQuery document window, choose [Execute With Debugger]. This will start debugging at the first line.
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTe7Antt3j0MMo6QPpVbl5EKJvMXvpR8ljqiACAq1vcjyUyK-a1Yi_A698aAsgHt828fGShqauZfh2LqnuuJgz89fvWGnx2Mhu5E-wOIai2GObfTXPeQc0L2LRy_b_NZR1hS2TVxhOr_s/s1600/sqlclr-debugging.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTe7Antt3j0MMo6QPpVbl5EKJvMXvpR8ljqiACAq1vcjyUyK-a1Yi_A698aAsgHt828fGShqauZfh2LqnuuJgz89fvWGnx2Mhu5E-wOIai2GObfTXPeQc0L2LRy_b_NZR1hS2TVxhOr_s/s1600/sqlclr-debugging.png&quot; height=&quot;252&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;
&lt;br /&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;Click [Step Into] button at the SP call that invokes SQLCLR call.&lt;/li&gt;
&lt;li&gt;Now you are in SQLCLR C# code (or any other .NET code) and you can step into, step out in the C# code.&lt;/li&gt;
&lt;/ol&gt;
&lt;br /&gt;
&lt;br /&gt;</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/9042369794605277709/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2014/12/how-to-debug-sqlclr-in-vs-2012.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/9042369794605277709'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/9042369794605277709'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2014/12/how-to-debug-sqlclr-in-vs-2012.html' title='How to debug SQLCLR in VS 2012'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhhQfhZGGLWe3Z0tg7eoZONgmJKcTEsqkYLSyD9pEQj0edVtcKM54BzJ2WIIqYIJAcBTOuRPOkIZtozXYNry9wlOPxaXgbldJfJ-6xBSr3AThlU1Fgu_9xzCQv0-16RZqRlUYr8LRODtA4/s72-c/sqlclr-allow.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-1760167084996160218</id><published>2013-08-04T13:10:00.001-07:00</published><updated>2013-08-04T13:10:39.394-07:00</updated><title type='text'>Excel programming - OutOfMemoryException when setting value to a cell</title><content type='html'>&lt;div style=&quot;clear: both;&quot;&gt;
&lt;/div&gt;
I ran into OutOfMemory exception when setting a value to a cell in Excel.&lt;br /&gt;
Here is a simplified example in C#. 
&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;&lt;span style=&quot;color: blue;&quot;&gt;using Excel = Microsoft.Office.Interop.Excel;  //Excel PIA 12.0
//...

Excel.Application excelApp = new Excel.Application();
Excel.Workbook wb = excelApp.Workbooks.Add(Type.Missing);

Excel.Worksheet ws = wb.Worksheets.get_Item(1) as Excel.Worksheet;

string val = &quot;-&quot; + &quot;&quot;.PadRight(8192, &#39; &#39;);
ws.Cells[1, 1] = val;

//....&lt;/span&gt;
&lt;/pre&gt;
&lt;br /&gt;
Running this code throws OutOfMemoryException with the following message:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&amp;nbsp; &amp;nbsp;Not enough storage is available to complete this operation.&amp;nbsp;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&amp;nbsp; &amp;nbsp;(Exception from HRESULT: 0x8007000E (E_OUTOFMEMORY))&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
When tried to set the same value to a cell manually in Excel, I got more detail message.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&amp;nbsp; &amp;nbsp;Formula is too long. Formulas may not exceed 8192 characters.&amp;nbsp;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
So it makes more sense. When text begins with -, Excel consider it as Excel Formula.&lt;br /&gt;
In Excel 2007 - 2010, the max size of formula is 8192 (In Excel 2003, it is 1024).&lt;br /&gt;
&lt;br /&gt;
So workaround might be to replace the first character with something else or prepend something in front of the text.&lt;br /&gt;
&lt;br /&gt;</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/1760167084996160218/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2013/08/excel-programming-outofmemoryexception.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/1760167084996160218'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/1760167084996160218'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2013/08/excel-programming-outofmemoryexception.html' title='Excel programming - OutOfMemoryException when setting value to a cell'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-3653109270583178127</id><published>2013-05-24T15:30:00.001-07:00</published><updated>2013-05-24T15:30:37.715-07:00</updated><title type='text'>installutil.exe - System.BadImageFormatException Could not load file or assembly or one of its dependencies</title><content type='html'>A .NET framework utility, installutil.exe, is used to install or uninstall .NET assembly to Windows Service. To uninstall existing service and reinstall new binaries, one can create a batch as below. That is, stop existing service and uninstall existing service. And then install new service and start it again.
&lt;div style=&quot;clear:both&quot;&gt;&lt;/div&gt;

&lt;pre&gt;
net stop &quot;My Service&quot;
%SystemRoot%\Microsoft.Net\Framework\v4.0.30319\installutil.exe /u MyService.exe
%SystemRoot%\Microsoft.Net\Framework\v4.0.30319\installutil.exe MyService.exe
net start &quot;My Service&quot;
&lt;/pre&gt;

&lt;p&gt;The script worked fine but one day the batch was failed with the following error.&lt;/p&gt;
&lt;pre&gt;
Exception occurred while initializing the installation:
System.BadImageFormatException: Could not load file or assembly &#39;file:///D:\Services\MyService.exe&#39; or one of its dependencies. An attempt was made to load a program with an incorrect format..
&lt;/pre&gt;

As it turned out, the MyService.exe assembly happened to be 64bit binary and the installutil.exe was for 32 bit.
So changing the installutil.exe path to 64 bit folder made it working.

&lt;pre&gt;
%SystemRoot%\Microsoft.Net\Framework64\v4.0.30319\installutil.exe MyService.exe
&lt;/pre&gt;
&lt;br /&gt;
</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/3653109270583178127/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2013/05/installutilexe-systembadimageformatexce.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/3653109270583178127'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/3653109270583178127'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2013/05/installutilexe-systembadimageformatexce.html' title='installutil.exe - System.BadImageFormatException Could not load file or assembly or one of its dependencies'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-6729808847649525149</id><published>2013-04-06T12:24:00.000-07:00</published><updated>2013-04-06T12:24:34.529-07:00</updated><title type='text'>Add new line in .resx resource string</title><content type='html'>A simple topic. When adding newline such as \n or \r\n in .RESX resource string, Visual Studio actually escapes the backslash character, so the actual data that is saved is double backslash (\\) instead od single backslash. For example, for input &quot;\n&quot; in .RESX resource editor, the actual data will be&amp;nbsp;\\n&amp;nbsp; in .resx.&lt;br /&gt;
&lt;br /&gt;
So if one tries to display that resource string in, say,&amp;nbsp;message box, the 2 characters &quot;\n&quot; will be displayed&amp;nbsp;instead of new line&amp;nbsp;which one expects.&lt;br /&gt;
&lt;br /&gt;
For example, let&#39;s say ErrorMsg in Resource1.resx has some error message like &quot;Error : invalid data.\n{0}.&quot;&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;
msg = string.Format(Resource1.ErrorMsg, errInfo);
MessageBox.Show(this, msg, &quot;Error&quot;);
&lt;/pre&gt;
&lt;br /&gt;
The code above will display&amp;nbsp;something like &quot;Error : invalid data.\nwrong chars found&quot; in one line.
&lt;br /&gt;
To add new line between two sentence, double backslash should be replaced by single backslash or Environment.NewLine.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;
msg = string.Format(Resource1.ErrorMsg, errInfo);
msg = msg.Replace(&quot;\\n&quot;, Environment.NewLine);
MessageBox.Show(this, msg, &quot;Error&quot;);
&lt;/pre&gt;
</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/6729808847649525149/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2013/04/add-new-line-in-resx-resource-string.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/6729808847649525149'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/6729808847649525149'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2013/04/add-new-line-in-resx-resource-string.html' title='Add new line in .resx resource string'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-4003822133303662616</id><published>2013-03-30T20:47:00.003-07:00</published><updated>2013-03-30T20:51:54.417-07:00</updated><title type='text'>A connection was successfully established with the server, but then an error occurred during the pre-login handshake</title><content type='html'>One of my .NET application threw SqlConnection exception with the following error. &lt;br /&gt;
&lt;br /&gt;
&quot;A connection was successfully established with the server, but then an error &lt;br /&gt;
occurred during the pre-login handshake.&quot;&lt;br /&gt;
&lt;br /&gt;
This application used to work fine but all of sudden it stopped working. The code is pretty typical ADO.NET connection routine. It failed&amp;nbsp;at conn.Open(). Interestingly, it only occurred when connecting to remote server. Connecting to local SQL server worked fine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;nbsp; string connectionString = &quot;Data Source=abc.com;Initial Catalog=testdb;User ID=user1;Password=1234;&quot;;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;using (SqlConnection conn = new SqlConnection(connectionString))&lt;br /&gt;
&amp;nbsp; {&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; conn.Open();&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; //.....&lt;br /&gt;
&amp;nbsp; }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One explanation can be found in &lt;a href=&quot;http://support.microsoft.com/kb/2568167&quot;&gt;http://support.microsoft.com/kb/2568167&lt;/a&gt;.&lt;br /&gt;
I ran the following command to reset and then&amp;nbsp;everything&amp;nbsp;worked fine.&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; C&amp;gt; &lt;strong&gt;netsh winsock reset&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;Of course, there will be so many different&amp;nbsp;reasons/solutions&amp;nbsp;for this same error. I just wanted to jot down one case&amp;nbsp;of those.&lt;br /&gt;
</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/4003822133303662616/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2013/03/a-connection-was-successfully.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/4003822133303662616'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/4003822133303662616'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2013/03/a-connection-was-successfully.html' title='A connection was successfully established with the server, but then an error occurred during the pre-login handshake'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-4859499376253001184</id><published>2013-02-26T17:36:00.000-08:00</published><updated>2013-02-26T17:36:43.158-08:00</updated><title type='text'>Send email from cmd script using Powershell</title><content type='html'>In C#, sending mail is a simple task. We create an instance of System.Net.Mail.SmtpClient class and then call Send method with MailMessage object. Sometimes smalle task is done by using windows shell script. If we have to use shell script in .cmd file, how do we send email? Well, shell command does not have a command for sendmail, so we probably can use third party utility. If we do not want to download and install the 3rd party tool on your system on whatever reason, we can utilize Powershell which can create and use .NET classes.
&lt;br /&gt;
&lt;div style=&quot;clear: both;&quot;&gt;
&lt;/div&gt;
Let&#39;s say we have a .cmd file that runs an application and we want to send an alert&amp;nbsp;email when the app is failed. The following code snippet shows that it runs MyApp.exe and check its&amp;nbsp;exit code and&amp;nbsp; some literal text (Result=Pass) to verify that the app is successful. If it fails, it calls Powershell script (sendmail.ps1) which is located in the same folder.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;@ECHO OFF
REM Run App
MyApp.exe data.ini &amp;gt; MyApp.out 2&amp;gt;&amp;amp;1

echo EXIT_CODE : %errorlevel%

REM Check exit code
if %errorlevel% NEQ 0 (
  echo ErrorLevel is &quot;%errorlevel%&quot;
  GOTO Error
)

REM Check valid output
find /i &quot;Result=Pass&quot; MyApp.out
if %errorlevel% NEQ 0 (
  echo Result : Fail
  GOTO Error
)

echo Result : Pass
GOTO End

:Error
Powershell .\sendmail.ps1
EXIT /B -1

:End
EXIT /B 0
@ECHO ON
&lt;/pre&gt;
&lt;p&gt;
The next code is powershell script that sends email. It creates various .NET objects related to mail and set their properties as we do in other languages like C#. If SMTP server is valid server name and client credential is valid, the mail will be delivered via SMTP.
&lt;/p&gt;
&lt;pre&gt;#
# sendmail.ps1
#
$from = New-Object system.net.mail.MailAddress &quot;sender@live.com&quot;
$to = New-Object system.net.mail.MailAddress &quot;receiver@live.com&quot;
$message = new-object system.net.mail.MailMessage $from, $to
$message.Subject = &quot;[FAILED] Scheduled Task Failed&quot;
$message.Body = &quot;Scheduled Task failed on Machine1. Please investigate the failure.&quot;

$smtpserver = &quot;smtphost.domain.com&quot;
$client = new-object system.net.mail.smtpclient $smtpserver
$client.UseDefaultCredentials = $TRUE
$client.Send($message)
&lt;/pre&gt;
</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/4859499376253001184/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2013/02/send-email-from-cmd-script-using.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/4859499376253001184'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/4859499376253001184'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2013/02/send-email-from-cmd-script-using.html' title='Send email from cmd script using Powershell'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-444742550910476394</id><published>2012-12-24T17:48:00.000-08:00</published><updated>2012-12-24T17:48:10.021-08:00</updated><title type='text'>C# : Simulate concurrent calls to SQL Server</title><content type='html'>I happened to need to write a small C# routine that simulate a lot of concurrent calls to a stored procedure in SQL Server. The purpose of this application&amp;nbsp;was to simulate deadlock scenario that occurred in production server.&amp;nbsp;A lot of&amp;nbsp;&lt;a href=&quot;http://sqlbeyond.blogspot.com/2012/12/deadlock-in-highly-concurrent-situation.html&quot;&gt;deadlock occurred at highly concurrent situation &lt;/a&gt;only, so simulating the condition in test environment is very helpful to figure out deadlock root cause and also to validate deadlock fix.&lt;br /&gt;
I simplified the case and write a sample code that pretty much done the same thing.&lt;br /&gt;
&lt;div style=&quot;clear: both;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;pre&gt;using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;

namespace NS
{
    class Program
    {
        static void Main(string[] args)
        {
            Parallel.For(0, 100, (i) =&amp;gt; Run(i));
        }

        static void Run(int i)
        {
            string strConn = &quot;Data Source=(local);Initial Catalog=MyDB;Integrated Security=true&quot;;

            using (SqlConnection conn = new SqlConnection(strConn))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(&quot;sp_GetNext&quot;, conn);
                cmd.CommandType = CommandType.StoredProcedure;

                // Input param
                SqlParameter pInput = new SqlParameter(&quot;@in&quot;, SqlDbType.Int);
                pInput.Direction = ParameterDirection.Input;
                pInput.Value = 1;
                cmd.Parameters.Add(pInput);
                
                // Output param
                SqlParameter pOutput = new SqlParameter(&quot;@out&quot;, SqlDbType.Int);
                pOutput.Direction = ParameterDirection.Output;
                cmd.Parameters.Add(pOutput);

                cmd.ExecuteNonQuery();

                Console.WriteLine(pOutput.Value);
            }
        }
    }
}
&lt;/pre&gt;
&lt;br /&gt;
The calling stored procedure is nothing special, it is ordinary ADO.NET routine to make a SP call. To simulate concurrent calls, I called Run() method by using Parallel.For(). This Parallel.For() method runs Run() method 100 times, almost concurrently. Depending on CPU cores, the actual number of worker threads can vary but it will&amp;nbsp;simulate as many concurrent calls as possible from one machine. If test machine has single CPU or is a slow machine, probably the simulation might fail. But it gaves me decent level of simulation with my&amp;nbsp;eight core machine.</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/444742550910476394/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2012/12/c-simulate-concurrent-calls-to-sql.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/444742550910476394'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/444742550910476394'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2012/12/c-simulate-concurrent-calls-to-sql.html' title='C# : Simulate concurrent calls to SQL Server'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-4924227847148039831</id><published>2012-09-19T14:33:00.001-07:00</published><updated>2012-09-19T14:33:24.720-07:00</updated><title type='text'>WPF DataGrid - Column Sorting</title><content type='html'>Small note for column sorting in WPF DataGrid control. How can we show data in DataGrid initially&amp;nbsp;in descending order? If a column is in&amp;nbsp;descending order, two things should be done. Firstly, the data should be sorted accordingly, that is, descending order. Secondly, the header of the column is supposed to show down arrow mark which represents &quot;descending order.&quot;&lt;br /&gt;
&lt;br /&gt;
To show down arrow mark in column header, add SortDirection attribute to the column.&amp;nbsp;In example&amp;nbsp;below, &quot;ID&quot; column has SortDirection=Descending attribute.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;&amp;lt;DataGrid Name=&quot;dataGrid1&quot; AutoGenerateColumns=&quot;False&quot;&amp;gt;
    &amp;lt;DataGrid.Columns&amp;gt;
        &amp;lt;DataGridTextColumn Header=&quot;ID&quot; Binding=&quot;{Binding ID}&quot;
             SortDirection=&quot;Descending&quot; /&amp;gt;
        &amp;lt;DataGridTextColumn Header=&quot;Name&quot; Binding=&quot;{Binding Name}&quot;/&amp;gt;
    &amp;lt;/DataGrid.Columns&amp;gt;
&amp;lt;/DataGrid&amp;gt;
&lt;/pre&gt;
&lt;br /&gt;
To actually show sorted data, your data source should be sorted in descending order. If your data source is SQL data source, best way is doing it in SQL ORDER BY statement. If your data source is in memory collection, LINQ might be good way of doing sorting. Another approach is to use SortDescriptions property in DataGrid.Items as you can see below. The code below added ID as sorting column in descending order.

&lt;br /&gt;
&lt;pre&gt;
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        List&amp;lt;MyData&amp;gt; myItems = new List&amp;lt;MyData&amp;gt;();
        myItems.Add(new MyData(1, &amp;quot;Lee&amp;quot;));
        myItems.Add(new MyData(2, &amp;quot;kim&amp;quot;));

        dataGrid1.Items.SortDescriptions.Add(
new SortDescription(&amp;quot;ID&amp;quot;, ListSortDirection.Descending));
        dataGrid1.ItemsSource = myItems;
    }
}

public class MyData
{
    public int ID { get; set; }
    public string Name { get; set; }
    public MyData() { }
    public MyData(int id, string name)
    {
        this.ID = id;
        this.Name = name;
    }
}
&lt;/pre&gt;

</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/4924227847148039831/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2012/09/wpf-datagrid-column-sorting.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/4924227847148039831'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/4924227847148039831'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2012/09/wpf-datagrid-column-sorting.html' title='WPF DataGrid - Column Sorting'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-831242871967898774</id><published>2012-08-17T21:50:00.000-07:00</published><updated>2012-08-17T21:50:11.234-07:00</updated><title type='text'>WPF PropertyGrid - display partial enum values in ComboBox</title><content type='html'>In &lt;a href=&quot;http://dotnetbeyond.blogspot.com/2012/08/filter-enum-type-show-subset-of-enum.html&quot; target=&quot;_blank&quot;&gt;the previous post&lt;/a&gt;, I explained a way of getting a subset of enum values. This post shows an example of displaying a subset of enum onto WPF PropertyGrid. In WPF 4.0, there is no standard&amp;nbsp;built-in PropertyGrid control&amp;nbsp;but one can find a good&amp;nbsp;PropertyGrid&amp;nbsp;from&amp;nbsp;&lt;a href=&quot;http://wpftoolkit.codeplex.com/&quot; target=&quot;_blank&quot;&gt;Extended WPF ToolKit&lt;/a&gt;&amp;nbsp;at codeplex website. As of now, its latest version is 1.6 but due to some compatibility issue, I happen to use v1.5. Since this is open source, you can also download source code from the website.&lt;br /&gt;
&lt;div style=&quot;clear: both;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
In WPF PropertyGrid 1.5, there is no way of doing enum filtering as we expect (of course). In order to&amp;nbsp;facilitate enum filtering, I added an editor EnumFilterComboBoxEditor&amp;nbsp;derived from ComboBoxEditor.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;public class EnumFilterComboBoxEditor&amp;lt;T&amp;gt; : ComboBoxEditor where T : struct
{
    public EnumFilterComboBoxEditor()
    {
    }

    protected override void ResolveValueBinding(PropertyItem propertyItem)
    {
        EnumFilter&amp;lt;T&amp;gt; enumFilter = (EnumFilter&amp;lt;T&amp;gt;)propertyItem.Value;
        var _binding = new Binding(&quot;Value&quot;);
        _binding.Source = enumFilter;
        _binding.ValidatesOnExceptions = true;
        _binding.ValidatesOnDataErrors = true;
        _binding.Mode = propertyItem.IsWriteable ? BindingMode.TwoWay : BindingMode.OneWay;
        _binding.Converter = CreateValueConverter();
        BindingOperations.SetBinding(Editor, ValueProperty, _binding);
    }

    protected override IList&amp;lt;object&amp;gt; CreateItemsSource(PropertyItem propertyItem)
    {
        return GetValues(propertyItem.Value);
    }

    private static object[] GetValues(object enumObject)
    {
        List&amp;lt;object&amp;gt; values = new List&amp;lt;object&amp;gt;();

        EnumFilter&amp;lt;T&amp;gt; enumFilter = (EnumFilter&amp;lt;T&amp;gt;)enumObject;            
        var enums = enumFilter.GetEnums();
        foreach (var e in enums)
        {
            values.Add(e);
        }

        return values.ToArray();
    }
}
&lt;/pre&gt;
&lt;br /&gt;
ResolveValueBinding() sets binding between source property EnumFilter&amp;lt;T&amp;gt;.Value and target Editor.ValueProperty. CreateItemsSource() sets all possible values of ComboBox items where we call GetEnums() method to get filtered enum values. And now to invoke this new type of editor, the following code added to PropertyGrid class (line 478 in propertygrid.cs).&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;else if (propertyItem.PropertyType.BaseType == typeof(Common.EnumFilter))
{
    Type tenum = propertyItem.Value.GetType().GetGenericArguments()[0];
    Type filterEditor = typeof(EnumFilterComboBoxEditor&amp;lt;&amp;gt;).MakeGenericType(tenum);
    editor = (ITypeEditor)Activator.CreateInstance(filterEditor, true);                        
}
else if (propertyItem.PropertyType.IsEnum) // all Enums
    editor = new EnumComboBoxEditor();
&lt;/pre&gt;
&lt;br /&gt;
Basically what it does is check the PropertyType and sets different editor based on the type. For enum filtering case, propertyItem.Value is EnumFilter&amp;lt;T&amp;gt; object. And calling GetGenericArguments()[0] returns the first generic argument type&amp;nbsp;(that is, T). For example,&amp;nbsp;for EnumFilter&amp;lt;MartType&amp;gt;, GetGenericArguments()[0] will return MartType. Next line MakeGenericType() call returns concrete type from generics by using passed argument (tenum). So filterEditor will be EnumFilterComboBoxEditor&amp;lt;MartType&amp;gt; type. Please note C# generics&amp;nbsp;cannot be&amp;nbsp;a type unless generic argument T&amp;nbsp;is specified. Once we got the concrete type, we can create an instance from it by using Activator.CreateInstance() method as seen in the next line. I think the sample code snippet is not optimized due to lack of time. Just wanted to summarize my thought...&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/831242871967898774/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2012/08/wpf-propertygrid-display-partial-enum.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/831242871967898774'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/831242871967898774'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2012/08/wpf-propertygrid-display-partial-enum.html' title='WPF PropertyGrid - display partial enum values in ComboBox'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-162365080080527478</id><published>2012-08-17T17:13:00.001-07:00</published><updated>2012-08-17T21:52:58.295-07:00</updated><title type='text'>Filter enum type - Show a subset of enum values</title><content type='html'>I happen to run into the case where I have to display a subset of enum type values instead of displaying the all elements - which is common case -&amp;nbsp;of the enum type. .NET enum is a predefined type, should be defined&amp;nbsp;at compile time&amp;nbsp;and cannot be dynamically built at run time. &lt;br /&gt;
&lt;br /&gt;
To illustrate the problem domain, let&#39;s say we have a enum called MartType as follows.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;pre&gt;public enum MartType{
   Safeway,
   QFC,
   Alberson,
   HMart
}
&lt;/pre&gt;
&lt;br /&gt;
If we display&amp;nbsp;a enum type property in PropertyGrid (actually I&amp;nbsp;used WPF property grid which is included in &lt;a href=&quot;http://wpftoolkit.codeplex.com/releases/view/71499&quot;&gt;WPF extended toolkit&lt;/a&gt;), it will show a combox editor containing all enum values.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZ55GKRk7_A6RJlczDTo6gvX6kELL-Sq_IaPBsNieFGbse6FNaqCDao5303uAFpMzAEOLd5dI1D31htlIUPJwCUbUlwpHm4W23Wjs4QMA-MnLE6cP1WjnFSdS1KTKxq88tqYATNW6zDE0/s1600/all_enum_elements.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;210&quot; mda=&quot;true&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZ55GKRk7_A6RJlczDTo6gvX6kELL-Sq_IaPBsNieFGbse6FNaqCDao5303uAFpMzAEOLd5dI1D31htlIUPJwCUbUlwpHm4W23Wjs4QMA-MnLE6cP1WjnFSdS1KTKxq88tqYATNW6zDE0/s320/all_enum_elements.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
Now, what if we want to display a subset of enum values based on Area? For example, in case of another city (Bellevue), we only want to show 3 grocery stores.&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhcH327bGhi5FONKFOrFzGyeEVKqAQNqDt3E87hEtSueHvOCNwukLvTbcP_DcKOfCqMJ_yvk3nwly17pjBDdj6Ai1_zrliAM1UberHosp5vEf5b06LjnVmYQJOZg06SaT5DCVTmeQIrPN8/s1600/subset_of_enum.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;195&quot; mda=&quot;true&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhcH327bGhi5FONKFOrFzGyeEVKqAQNqDt3E87hEtSueHvOCNwukLvTbcP_DcKOfCqMJ_yvk3nwly17pjBDdj6Ai1_zrliAM1UberHosp5vEf5b06LjnVmYQJOZg06SaT5DCVTmeQIrPN8/s320/subset_of_enum.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
In order to do this, one should restrict ItemsSource data for the ComboBox. And in order to accomplish this in WPF PropertyGrid control, one have to add a special editor to handle this special case (will write about this later).&lt;br /&gt;
&lt;br /&gt;
For the example above, let&#39;s say we expose 2 properties like this.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;public string Area { get; set; }
public EnumFilter&amp;lt;MartType&amp;gt;&lt;marttype&gt; AreaMartType { get; set; }
&lt;/marttype&gt;&lt;/pre&gt;
&lt;br /&gt;
AreaMartType public property is not simply MartType enum, but a EnumFilter of MartType. This AreaMartType is set by the following helper private method, which returns filtered enum based on areaNo.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;private EnumFilter&amp;lt;MartType&amp;gt;&lt;marttype&gt; FilterMarts(int areaNo, MartType selectedMart)
{
    List&lt;marttype&gt; subset = new List&lt;marttype&gt;();
    switch (areaNo)
    {
        case 1:
            subset.Add(MartType.QFC);
            subset.Add(MartType.Alberson);
            subset.Add(MartType.HMart);
            break;
        case 2:
            subset.Add(MartType.QFC);
            subset.Add(MartType.Alberson);
            subset.Add(MartType.Safeway);
            break;
        case 3:                    
            subset.Add(MartType.Alberson);
            subset.Add(MartType.Safeway);
            subset.Add(MartType.HMart);
            break;
        default:
            subset.Add(MartType.QFC);
            subset.Add(MartType.Alberson);
            subset.Add(MartType.Safeway);
            subset.Add(MartType.HMart);
            break;
    }
    EnumFilter&amp;lt;MartType&amp;gt;&lt;marttype&gt; enumFilter = new EnumFilter&amp;lt;MartType&amp;gt;&lt;marttype&gt;(subset);
    enumFilter.Value = selectedMart;
    return enumFilter;
}
&lt;/marttype&gt;&lt;/marttype&gt;&lt;/marttype&gt;&lt;/marttype&gt;&lt;/marttype&gt;&lt;/pre&gt;
&lt;br /&gt;
So EnumFilter of T class takes enum value list which is a subset of enum values. And GetEnums() method actually do the filtering work based on the given subset. By IEnumerable and yield only filtered one, it can dynamically retrieve a subset of enum items.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;public class EnumFilter
{        
}
public class EnumFilter&amp;lt;T&amp;gt;&lt;t&gt; : EnumFilter, INotifyPropertyChanged
    where T : struct
{
    private List&lt;t&gt; _elements;
    private T _value;

    public EnumFilter()
    {
        _elements = new List&amp;lt;T&amp;gt;&lt;t&gt;();
    }

    public EnumFilter(List&amp;lt;T&amp;gt;&lt;t&gt; elements)
    {
        _elements = elements;
    }

    public IEnumerable&amp;lt;T&amp;gt;&lt;t&gt; GetEnums()
    {
        foreach (var field in typeof(T).GetFields(
            BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static))
        {
            T enumVal = (T)field.GetValue(null);
            if (_elements.Contains(enumVal))
            {
                yield return enumVal;
            }
        }
    }

    public T Value
    {
        get { return _value; }
        set
        {
            _value = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(&quot;Value&quot;));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
&lt;/t&gt;&lt;/t&gt;&lt;/t&gt;&lt;/t&gt;&lt;/t&gt;&lt;/pre&gt;
&lt;br /&gt;
How we display the subset of enums in WPF PropertyGrid is little different topic but related. Will write more. (Please see : &lt;a href=&quot;http://dotnetbeyond.blogspot.com/2012/08/wpf-propertygrid-display-partial-enum.html&quot;&gt;http://dotnetbeyond.blogspot.com/2012/08/wpf-propertygrid-display-partial-enum.html&lt;/a&gt;&amp;nbsp;)</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/162365080080527478/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2012/08/filter-enum-type-show-subset-of-enum.html#comment-form' title='5 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/162365080080527478'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/162365080080527478'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2012/08/filter-enum-type-show-subset-of-enum.html' title='Filter enum type - Show a subset of enum values'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZ55GKRk7_A6RJlczDTo6gvX6kELL-Sq_IaPBsNieFGbse6FNaqCDao5303uAFpMzAEOLd5dI1D31htlIUPJwCUbUlwpHm4W23Wjs4QMA-MnLE6cP1WjnFSdS1KTKxq88tqYATNW6zDE0/s72-c/all_enum_elements.png" height="72" width="72"/><thr:total>5</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-1004359342113135315</id><published>2012-04-20T15:04:00.000-07:00</published><updated>2012-04-20T15:04:59.519-07:00</updated><title type='text'>WPF ribbonwindow - doubleclicking application icon causes Shutdown</title><content type='html'>A WPF application whose main window is created from WPF RibbonWindow shows different behavior between closing right-top close (X) button and doubleclicking application icon on the left-top side.&lt;br /&gt;
&lt;br /&gt;
When clicking right-topmost Close button, the window is closed and developer can cancel window close in window&#39;s Closing event handler by settting e.Cancel to true. Here is a callstack example when the Close button is clicked. Alt-F4 has the same effect as clicking Close button.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;  Console.MainWindow.WindowConsole_Closing(object sender, System.ComponentModel.CancelEventArgs e) Line 679 C#
  PresentationFramework.dll!System.Windows.Window.OnClosing(System.ComponentModel.CancelEventArgs e) + 0x8c bytes 
  PresentationFramework.dll!System.Windows.Window.WmClose() + 0x96 bytes 
  .............
  WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame) + 0xc1 bytes 
  WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes 
  WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4c bytes 
  PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x17 bytes 
  PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes 
  PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes 
  PresentationFramework.dll!System.Windows.Application.Run() + 0x1b bytes 
  Mitutoyo.QCCAT.Console.exe!Mitutoyo.QCCAT.Console.App.Main() + 0x5e bytes Unknown
  
&lt;/pre&gt;&lt;br /&gt;
If a user doubleclicks leftmost application icon, the application initiates app shutdown and send window close signals to all windows. But, if window close event handler cancels, it will not be honored and simply ignored and keep going for shutdown. This means develoepr cannot cancel window close, no matter what. Here is the call stack when app icon is doubleclicked. You can see Application.DoShutdown() in the middle.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;&gt; Console.MainWindow.WindowConsole_Closing(object sender, System.ComponentModel.CancelEventArgs e) Line 679 C#
  PresentationFramework.dll!System.Windows.Window.OnClosing(System.ComponentModel.CancelEventArgs e) + 0x8c bytes 
  PresentationFramework.dll!System.Windows.Window.WmClose() + 0x96 bytes 
  PresentationFramework.dll!System.Windows.Window.InternalClose(bool shutdown, bool ignoreCancel) + 0xa1 bytes 
  PresentationFramework.dll!System.Windows.Application.DoShutdown() + 0x1b6 bytes 
  PresentationFramework.dll!System.Windows.Application.ShutdownImpl() + 0x1c bytes 
  PresentationFramework.dll!System.Windows.Application.ShutdownCallback(object arg) + 0x5 bytes 
  ...........
  [Managed to Native Transition] 
  WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame) + 0xc1 bytes 
  WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes 
  WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4c bytes 
  PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x17 bytes 
  PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes 
  PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes 
  PresentationFramework.dll!System.Windows.Application.Run() + 0x1b bytes 
  Mitutoyo.QCCAT.Console.exe!Mitutoyo.QCCAT.Console.App.Main() + 0x5e bytes Unknown
  
&lt;/pre&gt;&lt;br /&gt;
One can work around this problem by overwriting Applications.Close behavior. Here is a code snippet. &lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt; public partial class MainWindow : RibbonWindow
 {
    public MainWindow()
    {
       InitializeComponent();
       this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, ApplicationCloseExecuted)); 
    }
          
    private void ApplicationCloseExecuted(object sender,
             ExecutedRoutedEventArgs e)
    {
       this.Close();
    }

    private void Window_Closing(object sender, CancelEventArgs e)
    {
       if (MsgBox(&quot;Sure?&quot;) == true) {
          Terminate();
       }
       else {
          e.Cancel = true; // cancel window close
       }
    }
 }
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/1004359342113135315/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2012/04/wpf-ribbonwindow-doubleclicking.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/1004359342113135315'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/1004359342113135315'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2012/04/wpf-ribbonwindow-doubleclicking.html' title='WPF ribbonwindow - doubleclicking application icon causes Shutdown'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-155030338359548542</id><published>2012-04-12T14:13:00.000-07:00</published><updated>2013-07-18T20:23:23.858-07:00</updated><title type='text'>LINQ to Entities : this method cannot be translated into a store expression</title><content type='html'>In LINQ to Entities or LINQ to SQL, if C# user-defined function is used in query expression, this function cannot be translated to SQL expression so the following error can occur.&lt;br /&gt;
&lt;br /&gt;
{&quot;LINQ to Entities does not recognize the method &#39;System.Collections.Generic.IList`1[System.String] getEmp(Int32)&#39; method, and this method cannot be translated into a store expression.&quot;}&lt;br /&gt;
&lt;br /&gt;
Here is an example of calling C# function directly from LINQ query. This will throw an exception since getEmp cannot be converted to a pure SQL statement.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;private void WrongRun()
{
    MyDBEntities db = new MyDBEntities();
    var p = from d in db.Depts
            where d.ID == 1
            from emp in getEmp(d.ID)
            select new { d.Name, emp };

    foreach (var x in p)
    {
        Debug.WriteLine(x.Name + &quot;: &quot; + x.emp);
    }
}

public IList&lt;string&gt; getEmp(int deptid)
{
    return new EmpData().GetEmps(deptid);            
}
&lt;/string&gt;&lt;/pre&gt;
&lt;br /&gt;
Assuming there is primary key (Dept.ID) / foreign key (Emp.DeptID) relationship between Dept and Emp table, the problem can go away by rewriting LINQ query as follows.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;private void Run()
{
    MyDBEntities db = new MyDBEntities();
    var p = from d in db.Depts
            where d.ID == 1
            from emp in d.Emps
            select new { d.Name, emp.EmpID };

    foreach (var x in p)
    {
        Debug.WriteLine(x.Name + &quot;: &quot; + x.EmpID);
    }
}
&lt;/pre&gt;
&lt;br /&gt;
The relationship between Dept and Emp is 1 to many, so SelectMany() expression will be used if it is rewritten in LINQ methods.</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/155030338359548542/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2012/04/linq-to-entities-this-method-cannot-be.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/155030338359548542'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/155030338359548542'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2012/04/linq-to-entities-this-method-cannot-be.html' title='LINQ to Entities : this method cannot be translated into a store expression'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-5378812537194346205</id><published>2012-04-05T16:45:00.000-07:00</published><updated>2012-04-05T16:45:04.336-07:00</updated><title type='text'>InstallShield : Check running process or get process list (InstallScript)</title><content type='html'>InstallShield does not provide any native function for checking processes, which led users to use Win32 API or WMI provider if they want to check a process or get process list. I found a &#39;List and Shut Down Running Applications&#39; code in http://www.installsite.org but the code was not working in Windows 7 64bit machine. I didn&#39;t want to spend too much time on it, so moved on and tried WMI approach which worked for me.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Check to see if specific process is running.&lt;/b&gt;&lt;br /&gt;
IsAppRunning() function checks to see if a specified process is currently running on the machine. Basically the code finds a process in Win32_Process WMI class.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;function BOOL IsAppRunning(appName)      
 OBJECT wmi, procs;      
begin         
  try
    set wmi = CoGetObject( &quot;winmgmts://./root/cimv2&quot;, &quot;&quot; ); 
    if ( !IsObject(wmi) ) then   
        return FALSE;
    endif;
    set procs = wmi.ExecQuery (&quot;Select * from Win32_Process Where Name = &#39;&quot; + appName + &quot;&#39;&quot; ); 
    if (!IsObject(procs)) then    
 return FALSE;
    endif;          
                
    if (procs.Count &gt; 0) then
       return TRUE;
    endif;
  catch  
  endcatch;
  return FALSE;
end;
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;Get running processes&lt;/b&gt;&lt;br /&gt;
Another similar code is about getting all processes currently running on the machine. This task also can be done by referring to Win32_Process class but it requires to enumerate all data from the result. This looping task is tricky and cannot be done by simply using for loop. Again, http://www.installsite.org site provides &#39;Get Object and ForEach in InstallScript&#39; code and it worked great for me.&lt;br /&gt;
&lt;br /&gt;
(1)Download GetObject.zip from installsite.org &lt;br /&gt;
&lt;br /&gt;
(2)Unzip it and copy IsGetObj.dll to InstallShield (2010/mine) - Behavior and Login - Support Files / Billboards - Language Independent. This will copy the DLL file to SUPPORTDIR directory which is only available during installation. SUPPORTDIR is temp folder typically created under current user folder.&lt;br /&gt;
&lt;br /&gt;
(3) Add prototype at the top of the script&lt;br /&gt;
&lt;pre&gt;   prototype ISGetObj.ForEachStart(byref OBJECT, byref VARIANT);
   prototype ISGetObj.ForEachGetNextItem(byref VARIANT, byref OBJECT);
&lt;/pre&gt;(4) Use ForEachStart and ForEachGetNextItem function to iterate item from WMI query resultset.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;function STRING GetProcesses()      
  OBJECT wmi, procs, procItem;      
  VARIANT __varEnumHolder;  
  STRING procList;
begin         
  try
   set wmi = CoGetObject( &quot;winmgmts://./root/cimv2&quot;, &quot;&quot; ); 
   if ( !IsObject(wmi) ) then   
      return &quot;&quot;;
   endif;
   set procs = wmi.ExecQuery(&quot;Select * from Win32_Process&quot;); 
   if (!IsObject(procs)) then    
      return &quot;&quot;;
   endif;          
                
   UseDLL(SUPPORTDIR ^ &quot;IsGetObj.dll&quot;);   
   ForEachStart(procs, __varEnumHolder);    
   while(0 == ForEachGetNextItem(__varEnumHolder, procItem))  
     procList = procList + &quot;\n&quot; + procItem.Name;
   endwhile;       
   
   set __varEnumHolder = NOTHING;
   UnUseDLL(&quot;IsGetObj.dll&quot;);
  catch  
  endcatch;
  return procList;
end;   
&lt;/pre&gt;&lt;br /&gt;
The example above returns all running process names separated by CR.</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/5378812537194346205/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2012/04/installshield-check-running-process-or.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/5378812537194346205'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/5378812537194346205'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2012/04/installshield-check-running-process-or.html' title='InstallShield : Check running process or get process list (InstallScript)'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-7058559565869480588</id><published>2012-04-04T15:51:00.000-07:00</published><updated>2012-04-04T15:51:25.845-07:00</updated><title type='text'>Display empty string in DateTimePicker</title><content type='html'>By default, WinForms DateTimePicker control displays current date. Depending on Format property of the DateTimePicker control, it can display long date and time(Format=Long), short date(Format=Short) or time only(Format=Time). And if the Format is set to Custom, various user defined format is possible.&lt;br /&gt;
&lt;br /&gt;
When it comes to DateTimePicker, some people prefers to display empty string instead of current date/time when the form is first shown up. And the thing is DateTimePicker control does not allow you to enter empty string easily, since Value property of the control is DateTime type which does not allow null value. If it were DateTime? nullable type, displaying empty string would have been an easy task. Some developers make Nullable DateTimePicker control by inheriting it, but a workaround can be used by utilizing custom format.&lt;br /&gt;
&lt;pre&gt;public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        // Setting CustomFormat to a Space.            
        dateTimePicker1.Format = DateTimePickerFormat.Custom;
        dateTimePicker1.CustomFormat = &quot; &quot;;            
    }
    private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
    {
        // Change Format to Long,Short or Time
        dateTimePicker1.Format = DateTimePickerFormat.Short;
        // add more
    }
}
&lt;/pre&gt;&lt;br /&gt;
To add empty string to DateTimePicker textbox, set Format to Custom and then assign empty string to CustomFormat property in form Load event handler or form constructor. Once user starts changing the DateTimePicker value, we reset the Format back to normal format such as Long, Short, Time.</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/7058559565869480588/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2012/04/display-empty-string-in-datetimepicker.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/7058559565869480588'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/7058559565869480588'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2012/04/display-empty-string-in-datetimepicker.html' title='Display empty string in DateTimePicker'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-489989004320866393</id><published>2011-12-11T09:00:00.000-08:00</published><updated>2011-12-11T09:00:54.514-08:00</updated><title type='text'>Error &quot;The project type is not supported by this installation&quot; for web project</title><content type='html'>I happened to reinstall Visual Studio 2010, then when I opened an existing solution that contains a Class dll project and a web project, I got an error &quot;The project type is not supported by this installation&quot; for the web project only. So when I looked in the .csproj file in edit mode in Visual Studio, found a red line under &amp;lt;SilverlightApplicationList&amp;gt; &amp;lt;/SilverlightApplicationList&amp;gt;. I removed it and tried again. But then &amp;lt;SccAuxPath&amp;gt;SAK&amp;lt;/SccAuxPath&amp;gt; got a red line. Since this property is about TFS, spent some time by googling TFS project setttings (since I also reinstalled TFS), but in vain.&lt;br /&gt;
&lt;br /&gt;&lt;br /&gt;
Finally it tried all other projects and noticed only web project had this kind of problem. It turned out that I did not install Visual Web Developer component when installing Visual Studio 2010. There are many reasons of this error &quot;The project type is not... installation&quot; but error messages in VS project edit mode was kind of confusing. &lt;br /&gt;
After adding Visual Web Developer in Add/Remove Program, it worked fine.</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/489989004320866393/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/12/error-project-type-is-not-supported-by.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/489989004320866393'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/489989004320866393'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/12/error-project-type-is-not-supported-by.html' title='Error &quot;The project type is not supported by this installation&quot; for web project'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-346465127395172126</id><published>2011-10-25T10:54:00.000-07:00</published><updated>2011-10-25T11:07:25.857-07:00</updated><title type='text'>How to set cursor position in RichTextBox in WinForms</title><content type='html'>How can we set cursor position in WinForms RichTextBox control? One way of doing it is to use RichTextBox.Select() method. This method takes two parameters. First parameter is a starting character index and second one is the length of the selection. &lt;br /&gt;
&lt;div style=&quot;clear: both&quot;&gt;&lt;/div&gt;The following code snippet shows how to set cursor on the current position when mouse rightclick button is clicked.&lt;br /&gt;
&lt;pre&gt;private void richTextBox1_MouseDown(object sender, MouseEventArgs e)
{
   if (e.Button == System.Windows.Forms.MouseButtons.Right)
   {
      int index = richTextBox1.GetCharIndexFromPosition(e.Location);
      richTextBox1.Select(index, 0);
   }
}
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/346465127395172126/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/10/how-to-set-cursor-position-in.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/346465127395172126'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/346465127395172126'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/10/how-to-set-cursor-position-in.html' title='How to set cursor position in RichTextBox in WinForms'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-2473640723330322203</id><published>2011-10-11T17:08:00.000-07:00</published><updated>2011-10-11T17:08:08.765-07:00</updated><title type='text'>Multiple UI threads in WinForms</title><content type='html'>Most WinForms application has one main UI thread and some background worker threads. And it is very typical and clean way of doing multi-threading in WinForms. But, in some special situaions, you might want to create multiple UI threads so that each thread has each form independently. The following sample shows how to create multiple UI threads in WinForms.&lt;br /&gt;
&lt;div style=&quot;clear: both;&quot;&gt;&lt;/div&gt;&lt;br /&gt;
First in Main(), it launches a form called &#39;MainForm&#39; with Application.Run() method. Application.Run() creates message pump for a UI form, in this case, in main UI thread.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;static class Program
{
   /// &lt;summary&gt;
   /// The main entry point for the application.
   /// &lt;/summary&gt;
   [STAThread]
   static void Main()
   {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new MainForm());
   }
}
&lt;/pre&gt;&lt;br /&gt;
In Form_Load() of MainForm, we create 3 new Forms from 3 different threads.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;public partial class MainForm : Form
{
   public MainForm()
   {
      InitializeComponent();
   }

   private void MainForm_Load(object sender, EventArgs e)
   {
      // Start new UI thread for Form1
      Thread thread1 = new Thread(ShowForm1);
      thread1.Start();

      // Start new UI thread for Form2
      Thread thread2 = new Thread(() =&amp;gt; { Form2 f2 = new Form2(); Application.Run(f2); });
      thread2.Start();

      // Start new UI thread for Form3
      Thread thread3 = new Thread(ShowForm3);
      thread3.Start();
   }

   void ShowForm1()
   {
      // message pump with Application.Run()
      Application.Run(new Form1());
   }

   void ShowForm3()
   {
      Form3 f3 = new Form3();
      // Start message pump by using ShowDialog()
      f3.ShowDialog(); 
   }
}
&lt;/pre&gt;&lt;br /&gt;
First thread, thread1, runs ShowForm1() function which is simply calls Application.Run() against new Form1 instance. This thread creates new message pump for Form1 and works separately from MainForm.&lt;br /&gt;
&lt;br /&gt;
Second thread, thread2, shows an example of using anonymous delegate to launch Form2. Basically it&#39;s the same as ShowForm1().&lt;br /&gt;
&lt;br /&gt;
Third thread, thread3, calls ShowForm3() function where Form3 is launched by using ShowDialog(). If one uses Show() method instead of ShowDialog() here, thread will show the Form3 but then the form will be closed immediately since the thread will exit. ShowDialog begins new message pump for Form3 and will stay until user clicks Close button.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhc1w5fHNustAUrdi8KZPnCNaiabDQE2ptt9STs672iJHx1qHn-mPS9T5RwCuM8OUEXCT8Z61pe_SEJ8EEp7qPyRnZ92dDh-6TbsxRe8aD3jfgoM1tUhZjk1bYanCYJsrHKPBwVUqgNwuA/s1600/multiple-ui-threads.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;361&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhc1w5fHNustAUrdi8KZPnCNaiabDQE2ptt9STs672iJHx1qHn-mPS9T5RwCuM8OUEXCT8Z61pe_SEJ8EEp7qPyRnZ92dDh-6TbsxRe8aD3jfgoM1tUhZjk1bYanCYJsrHKPBwVUqgNwuA/s400/multiple-ui-threads.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div style=&quot;clear: both;&quot;&gt;&lt;/div&gt;&lt;br /&gt;
Each UI thread will work separately. Once all forms are closed, the application will be closed.</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/2473640723330322203/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/10/multiple-ui-threads-in-winforms.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/2473640723330322203'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/2473640723330322203'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/10/multiple-ui-threads-in-winforms.html' title='Multiple UI threads in WinForms'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhc1w5fHNustAUrdi8KZPnCNaiabDQE2ptt9STs672iJHx1qHn-mPS9T5RwCuM8OUEXCT8Z61pe_SEJ8EEp7qPyRnZ92dDh-6TbsxRe8aD3jfgoM1tUhZjk1bYanCYJsrHKPBwVUqgNwuA/s72-c/multiple-ui-threads.png" height="72" width="72"/><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-576060759969145748</id><published>2011-09-26T17:09:00.000-07:00</published><updated>2011-09-26T17:11:16.886-07:00</updated><title type='text'>Read/Write Data in Excel using OleDb (C#)</title><content type='html'>There are many ways of read/write data in Excel file. This post shows a simple example of using System.Data.OleDb in C#. One of advantages of using this method is no need to have Office in client machine.&lt;br /&gt;
&lt;div style=&quot;clear: both;&quot;&gt;&lt;/div&gt;&lt;br /&gt;
The code snippet below shows how to connect to Excel using OleDB, how to select, update and insert data. There is DELETE operation here since it is not supported by OLEDB provider.&lt;br /&gt;
&lt;pre&gt;private void Run()
{
   string szConn = @&quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\temp\test.xls;Extended Properties=&#39;Excel 8.0;HDR=No&#39;&quot;;
   OleDbConnection conn = new OleDbConnection(szConn);
   conn.Open();

   // Select
   OleDbCommand cmd = new OleDbCommand(&quot;SELECT * FROM [Sheet1$]&quot;, conn);
   OleDbDataAdapter adpt = new OleDbDataAdapter(cmd);
   DataSet ds = new DataSet();
   adpt.Fill(ds);

   foreach (DataRow dr in ds.Tables[0].Rows)
   {
      string data = string.Format(&quot;F1:{0}, F2:{1}, F3:{2}&quot;, dr[0], dr[1], dr[2]);
      MessageBox.Show(data);
   }
         
   // Update
   cmd = new OleDbCommand(&quot;UPDATE [Sheet1$] SET F2=&#39;Hello&#39; WHERE F1=&#39;a&#39;&quot;, conn); 
   cmd.ExecuteNonQuery();

   cmd = new OleDbCommand(&quot;UPDATE [Sheet1$A2:C2] SET F2=&#39;World&#39;&quot;, conn);
   cmd.ExecuteNonQuery();

   // Insert
   cmd = new OleDbCommand(&quot;INSERT INTO [Sheet1$](F1,F2,F3) VALUES (&#39;A3&#39;,&#39;B3&#39;,&#39;C3&#39;)&quot;, conn);
   cmd.ExecuteNonQuery();

   conn.Close();
}
&lt;/pre&gt;&lt;br /&gt;
Before:&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0DoBwX7stQGaKMZ0Tgms9de3icDOC-biz4syKdqyR_hlhW58l3txcwYFGLk5g2VYN9dOc_mWUgpIewiZHtP_fbPcdSr6Z0y-gKEBlliLGowjN01ufoaOePVm1YfXTBQCpsEbBQn_3UqE/s1600/excel-initial-data.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0DoBwX7stQGaKMZ0Tgms9de3icDOC-biz4syKdqyR_hlhW58l3txcwYFGLk5g2VYN9dOc_mWUgpIewiZHtP_fbPcdSr6Z0y-gKEBlliLGowjN01ufoaOePVm1YfXTBQCpsEbBQn_3UqE/s1600/excel-initial-data.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
After:&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgjU5oG7QH1MCiv9OnpBxXXGLEqNHPb-XMbLYGwMaM1VfwwatVsWI-J1OorTKm9jRwMo9YZTWtA8SH3t1NGR1O2NVQKRXUnp45ZyB4Abc1ZMNPR_eoTP1Knxr58T9ul9gudLXko7lAD3Xw/s1600/excel-result.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgjU5oG7QH1MCiv9OnpBxXXGLEqNHPb-XMbLYGwMaM1VfwwatVsWI-J1OorTKm9jRwMo9YZTWtA8SH3t1NGR1O2NVQKRXUnp45ZyB4Abc1ZMNPR_eoTP1Knxr58T9ul9gudLXko7lAD3Xw/s1600/excel-result.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
For connection string, HDR=Yes is default value and it specifies the first row of Excel is used for Column name. Having header in first row is typical case but if you do not want to use HDR, you have to specify HDR=No explicitly.&lt;br /&gt;
&lt;br /&gt;
The Table(?) name in Excel is sheet name and its syntax is &quot;[sheetName$]&quot;&lt;br /&gt;
For example, [Sheet1$] is first sheet &#39;Sheet1&#39; in the Excel file. In Excel, you can specify specific region by adding &quot;range&quot; after $ sign. That is, [Sheet1$A1:C1] represents first 3 columns (A to C) in first row (1).&lt;br /&gt;
&lt;br /&gt;
Select/Update/Delete syntax is pretty much the same as other data store. One thing to note is that if HDR is NO, the column names are automatically generated and so F1 means first field, F2 means 2nd field, and so on. If HDR is used, you can use the same column name as you define in first header row.</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/576060759969145748/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/09/readwrite-data-in-excel-using-oledb-c.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/576060759969145748'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/576060759969145748'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/09/readwrite-data-in-excel-using-oledb-c.html' title='Read/Write Data in Excel using OleDb (C#)'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0DoBwX7stQGaKMZ0Tgms9de3icDOC-biz4syKdqyR_hlhW58l3txcwYFGLk5g2VYN9dOc_mWUgpIewiZHtP_fbPcdSr6Z0y-gKEBlliLGowjN01ufoaOePVm1YfXTBQCpsEbBQn_3UqE/s72-c/excel-initial-data.png" height="72" width="72"/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-8644548781805892370</id><published>2011-09-22T19:32:00.000-07:00</published><updated>2013-02-20T22:29:44.981-08:00</updated><title type='text'>Format Specifier in C#</title><content type='html'>By and large there are two type of format specifiers in C# / .NET world : Standard Format Specifier and Custom Format Specifier. This post summarizes frequently used format specifiers.&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;clear: both;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
The general syntax for output formatter does look like this:&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;{n, w:tp}
      n: argument number
      w: width
      t: data type
      p: precision

      ex)  string.Format(&quot;{0,9:N2}&quot;, v);
&lt;/pre&gt;
&lt;br /&gt;
The below format specifiers are frequently used by developers.&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;&lt;b&gt;Standard Format Specifiers for Numeric Type&lt;/b&gt;&lt;/u&gt;&lt;br /&gt;
&lt;br /&gt;
(Case insensitive)&lt;br /&gt;
C : Currency&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; string.Format(&quot;{0:C}&quot;, 1234567) =&amp;gt; $1,234,567&lt;/span&gt;&lt;br /&gt;
D : Decimal &lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style=&quot;color: blue;&quot;&gt;string.Format(&quot;{0:D7}&quot;, 123456) =&amp;gt; 0123456&lt;/span&gt;&lt;br /&gt;
E : Scientific &lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; string.Format(&quot;{0:E}&quot;, 12345.6) =&amp;gt; 1.23456E+004&lt;/span&gt;&lt;br /&gt;
F : Fixed point &lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style=&quot;color: blue;&quot;&gt;string.Format(&quot;{0:F3}&quot;,12345.6) =&amp;gt; 12345.600&lt;/span&gt;&lt;br /&gt;
N : Number &lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style=&quot;color: blue;&quot;&gt;string.Format(&quot;{0:N2}&quot;,1234.567)=&amp;gt; 1,234.57&lt;/span&gt;&lt;br /&gt;
X : Hexadecimal &lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style=&quot;color: blue;&quot;&gt;string.Format(&quot;{0:X}&quot;, 255) =&amp;gt; FF&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;&lt;b&gt;Standard Format Specifiers for DateTime Type&lt;/b&gt;&lt;/u&gt;&lt;br /&gt;
&lt;br /&gt;
d : Short date &lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style=&quot;color: blue;&quot;&gt;string.Format(&quot;{0:d}&quot;, today) =&amp;gt; 11/21/2011&lt;/span&gt;&lt;br /&gt;
D : Long date &lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style=&quot;color: blue;&quot;&gt;string.Format(&quot;{0:D}&quot;, today) =&amp;gt; Firday, July 5, 2010&lt;/span&gt;&lt;br /&gt;
t : Short time &lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style=&quot;color: blue;&quot;&gt;string.Format(&quot;{0:t}&quot;, today) =&amp;gt; 4:05 PM&lt;/span&gt;&lt;br /&gt;
T : Long time &lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style=&quot;color: blue;&quot;&gt;string.Format(&quot;{0:T}&quot;, today) =&amp;gt; 4:05:55 PM&lt;/span&gt;&lt;br /&gt;
g : General datetime (short time)&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style=&quot;color: blue;&quot;&gt;string.Format(&quot;{0:g}&quot;, today) =&amp;gt; Firday, July 5, 20104:05:55 PM&lt;/span&gt;&lt;br /&gt;
G : General datetime &lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style=&quot;color: blue;&quot;&gt;string.Format(&quot;{0:g}&quot;, today) =&amp;gt; Firday, July 5, 20104:05:55 PM &lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;&lt;b&gt;Custom Format Specifiers for Numeric Type&lt;/b&gt;&lt;/u&gt;&lt;br /&gt;
&lt;br /&gt;
# : Digit placeholder (no leading zeros)&lt;br /&gt;
0 : Zero placeholder (w/ leading zeros)&lt;br /&gt;
. : Decimal point&lt;br /&gt;
, : Thousands operator&lt;br /&gt;
; : Section separator&lt;br /&gt;
&lt;br /&gt;
ex)&lt;br /&gt;
&amp;nbsp;&amp;nbsp; val = 12345;&lt;br /&gt;
&amp;nbsp;&amp;nbsp; &lt;span style=&quot;color: blue;&quot;&gt;string.Format(&quot;{0:#,##0;(#,##0)}&quot;, val) &lt;/span&gt;&lt;br /&gt;
&amp;nbsp;&amp;nbsp; =&amp;gt; 12,345&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp; val = -12345;&lt;br /&gt;
&amp;nbsp;&amp;nbsp; &lt;span style=&quot;color: blue;&quot;&gt;string.Format(&quot;{0:#,##0;(#,##0)}&quot;, val)&lt;/span&gt; &lt;br /&gt;
&amp;nbsp;&amp;nbsp; =&amp;gt; (12,345)&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp; val = 0;&lt;br /&gt;
&amp;nbsp;&amp;nbsp; &lt;span style=&quot;color: blue;&quot;&gt;string.Format(&quot;{0:#,##0;(#,##0);Zero}&quot;, val)&lt;/span&gt; &lt;br /&gt;
&amp;nbsp;&amp;nbsp; =&amp;gt; Zero&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;&lt;b&gt;Custom Format Specifiers for DateTime Type&lt;/b&gt;&lt;/u&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;M   : Month. Single digit for &amp;lt;10
MM  : Two digit month
MMM : Abbreviated name of the month
d   : Day. Single digit
dd  : Two digit day
ddd : Abbreviated name of the day
yy  : Two digit year 
yyyy: Four digit year
h   : Hour (12hr)
hh  : Two digit hour (12hr)
H / HH : Hour (24 hr)
m   : Minute
mm  : Two digit minute
s   : Second
ss  : Two digit second
tt  : AM / PM
&lt;/pre&gt;
ex) &lt;span style=&quot;color: blue;&quot;&gt;string.Format(&quot;{0:yyyy/MM/dd}&quot;, DateTime.Today) =&amp;gt; 2011/11/22&lt;/span&gt;</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/8644548781805892370/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/09/format-specifier-in-c.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/8644548781805892370'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/8644548781805892370'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/09/format-specifier-in-c.html' title='Format Specifier in C#'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-1525143568527979842</id><published>2011-09-14T10:45:00.000-07:00</published><updated>2011-09-14T10:45:35.280-07:00</updated><title type='text'>How to check MouseDown event for all controls in WinForm</title><content type='html'>When a Form contains several child controls and nested UserControls, mouse click event is not propagated to parent form in&amp;nbsp;WinForm. If one uses WPF, there is no need to add your code since WPF basically supports RoutedEvents. However, WinForm does not support Routed Events, so you have to manually implements the appropriate mechanism. &lt;br /&gt;
&lt;br /&gt;
One way of doing is using Application.AddMessageFilter() method which basically add custom message filter to the application. Your custom MessageFilter should implement IMessageFilter interface which only has one method - IMessageFilter.PreFilterMessage(). In this method, you determine whether you want to filter out the message or you can add your custom code for specific message.&lt;br /&gt;
&lt;br /&gt;
Here is an example of using MessageFilter. To check whether any control in the Form is clicked, I added a static property but this is only for simplified demonstration purpose, more options are available.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;using System;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
   static class Program
   {
      [STAThread]
      static void Main()
      {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);

         // Add Message Filter to precheck MouseDown
         IMessageFilter myFilter = new MyMessageFilter();
         Application.AddMessageFilter(myFilter);

         Application.Run(new Form1());
      }
   }

   public class MyMessageFilter : IMessageFilter
   {      
      public bool PreFilterMessage(ref Message m)
      {
         if (m.Msg == 0x201) //WM_LBUTTONDOWN
         {
            Form1.FormClicked = true; 
         }
         return false; // do not filter
      }
   }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;pre&gt;namespace WindowsFormsApplication2
{
   public partial class Form1 : Form
   {            
      public static bool FormClicked {get; internal set;}      
      public Form1()
      {
         InitializeComponent();
      }
   }
}
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/1525143568527979842/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/09/how-to-check-mousedown-event-for-all.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/1525143568527979842'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/1525143568527979842'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/09/how-to-check-mousedown-event-for-all.html' title='How to check MouseDown event for all controls in WinForm'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-8866768892205883076</id><published>2011-08-31T14:41:00.000-07:00</published><updated>2011-08-31T14:41:06.199-07:00</updated><title type='text'>VS : Changing .config file using conditional post-build event</title><content type='html'>Sometimes .config file - either app config file or web.config file - needs to be changed based on some condition during the build time.&amp;nbsp;For example, one might want to use local SQL connection string in one case and use remote SQL connection string for another case.&amp;nbsp;Due to pre-build / post-build event feature&amp;nbsp;of Visual Studio, these cases can be solved without big effort. &lt;br /&gt;
&lt;br /&gt;
Let&#39;s say one wants to use remote SQL connection by default and use local SQL connection only when special parameter (called &lt;span style=&quot;color: #1f497d; font-family: &amp;quot;Calibri&amp;quot;,&amp;quot;sans-serif&amp;quot;; font-size: 11pt; mso-ansi-language: EN-US; mso-bidi-language: AR-SA; mso-fareast-font-family: &amp;quot;Malgun Gothic&amp;quot;; mso-fareast-language: KO; mso-fareast-theme-font: minor-fareast;&quot;&gt;&lt;strong&gt;UseLocalSQL&lt;/strong&gt;&lt;/span&gt;) is&amp;nbsp;defined. To implement this sceanrio, first one needs to add the condition to Post&amp;nbsp;build event in&amp;nbsp;VS Project Properties dialog. &lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZUVr7AVmb5gQTsBF0etyDUGUHv1BCbFBvYEC811rApX8DhLZhhxLrVYrfPyetF26F8GWOifOqQqkEG-2PVcFlCyHAs5F6HtylQfEK_3hVrZciCIdTcdKTlT0_-WWeyWWBycUEAP7n78Q/s1600/post-build-event.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;258&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZUVr7AVmb5gQTsBF0etyDUGUHv1BCbFBvYEC811rApX8DhLZhhxLrVYrfPyetF26F8GWOifOqQqkEG-2PVcFlCyHAs5F6HtylQfEK_3hVrZciCIdTcdKTlT0_-WWeyWWBycUEAP7n78Q/s400/post-build-event.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;font-family: Calibri;&quot;&gt;if &#39;$(UseLocalSQL)&#39;==&#39;True&#39; Copy &quot;$(ProjectDir)LocalApp.config&quot; &quot;$(TargetPath).config&quot; /y&lt;o:p&gt;&lt;/o:p&gt;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
This means if UseLocalSQL parameter is defined and it&#39;s true,&amp;nbsp;the copy .config&amp;nbsp;command will be executed. If local SQL is not needed, default app.config will have remote SQL connection string.&lt;br /&gt;
(NOTE: one can also use pre-build event instead of post-build event. It&#39;s matter of implementation choice)&lt;br /&gt;
&lt;br /&gt;
If one needs to use MSBUILD tool, the following can be used. &lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #1f497d;&quot;&gt;&lt;span style=&quot;font-family: Calibri;&quot;&gt;&lt;span style=&quot;color: black;&quot;&gt;C&amp;gt;&lt;b&gt;msbuild test.sln /t:Rebuild /p:Configuration=Release /p:UseLocalSQL=True&lt;o:p&gt;&lt;/o:p&gt;&lt;/b&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
And if one uses TFS build system, the msbuild paramaeter can be specified as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhl2oYaxFqjiKrsOMBZBh_BooSG1n1FzJ6VlPsUa5KydFXF6tY_Iz9LQ7SHhZAHRFZyEkH1z7lhuBcMJrwJZoIcRgj245qr1XXf4K2BwWChyeXBlhiWD81e0Ggf_6Xna6ZgnN08QjOheVw/s1600/tfs-build-parameter.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;298&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhl2oYaxFqjiKrsOMBZBh_BooSG1n1FzJ6VlPsUa5KydFXF6tY_Iz9LQ7SHhZAHRFZyEkH1z7lhuBcMJrwJZoIcRgj245qr1XXf4K2BwWChyeXBlhiWD81e0Ggf_6Xna6ZgnN08QjOheVw/s400/tfs-build-parameter.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/8866768892205883076/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/08/vs-changing-config-file-using.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/8866768892205883076'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/8866768892205883076'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/08/vs-changing-config-file-using.html' title='VS : Changing .config file using conditional post-build event'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZUVr7AVmb5gQTsBF0etyDUGUHv1BCbFBvYEC811rApX8DhLZhhxLrVYrfPyetF26F8GWOifOqQqkEG-2PVcFlCyHAs5F6HtylQfEK_3hVrZciCIdTcdKTlT0_-WWeyWWBycUEAP7n78Q/s72-c/post-build-event.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-2872403682977078995</id><published>2011-08-26T16:41:00.000-07:00</published><updated>2011-08-26T16:41:02.929-07:00</updated><title type='text'>WPF RibbonControl : RibbonApplicationSplitMenuItem triggers click command twice</title><content type='html'>In&amp;nbsp;WPF RibbonControl 4.0, single&amp;nbsp;menu click on RibbonApplicationSplotMenuItem&amp;nbsp;caused click&amp;nbsp;event triggers twice. This means that if the menu is supposed to show a dialog, two same dialogs are going to pop up.&lt;br /&gt;
&lt;div style=&quot;clear: both;&quot;&gt;&lt;/div&gt;&lt;br /&gt;
Here is an xaml that is using RibbonApplicationSplotMenuItem.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ribbon:&lt;span style=&quot;color: red;&quot;&gt;RibbonApplicationSplitMenuItem&lt;/span&gt; x:Uid=&quot;saveAsSplitMenu&quot; Header=&quot;Save As&quot;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Command=&quot;SaveAs&quot; CommandParameter=&quot;SaveAsFile&quot;&amp;gt;&lt;br /&gt;
&amp;nbsp;&amp;nbsp; &amp;lt;ribbon:RibbonApplicationMenuItem x:Uid=&quot;saveAsDoc&quot; Header=&quot;Save As Doc&quot;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Command=&quot;SaveAs&quot; CommandParameter=&quot;Doc&quot; /&amp;gt;&lt;br /&gt;
&amp;nbsp;&amp;nbsp; &amp;lt;ribbon:RibbonApplicationMenuItem x:Uid=&quot;saveAsTxt&quot; Header=&quot;Save As Text&quot;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Command=&quot;SaveAs&quot; CommandParameter=&quot;Text&quot; /&amp;gt;&lt;br /&gt;
&amp;lt;/ribbon:RibbonApplicationSplitMenuItem&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
And let&#39;s say we registered CommandBinding for built-in&amp;nbsp;ApplicationCommands.SaveAs command as follows.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #2b91af; font-family: Courier New; font-size: small;&quot;&gt;&lt;span style=&quot;color: #2b91af; font-family: Courier New; font-size: small;&quot;&gt;&lt;span style=&quot;color: #2b91af; font-family: Courier New; font-size: small;&quot;&gt;CommandManager.RegisterClassCommandBinding(typeof(RibbonWindow), &lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; new CommandBinding(ApplicationCommands.SaveAs, ExecutedSaveAsCommand, CanExecuteSaveAs));&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
ExecutedCommand handler is defined as follows.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;private void ExecutedSaveAsCommand(object sender, ExecutedRoutedEventArgs e)
{         
    ....
    switch(e.Parameter.ToString())
    {
       case &quot;...&quot;: 
         break;
         ... 
       case &quot;SaveAsFile&quot;:
         if (e.OriginalSource.GetType() == 
             typeof(RibbonApplicationSplitMenuItem))
         {
            this.SaveAsFile();
         }
         break;
    }
}
&lt;/pre&gt;&lt;br /&gt;
RibbonApplicationSplitMenuItem triggers&amp;nbsp;two events with different OriginalSource: one for RibbonButton and the other for RibbonApplicationSplitMenuItem. The example above shows event filtering&amp;nbsp;of RibbonApplicationSplitMenuItem source. This might be considered as workaround until it will be fixed(?) later&amp;nbsp;in RibbonControlLibary.&lt;br /&gt;
</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/2872403682977078995/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/08/wpf-ribboncontrol-ribbonapplicationspli.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/2872403682977078995'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/2872403682977078995'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/08/wpf-ribboncontrol-ribbonapplicationspli.html' title='WPF RibbonControl : RibbonApplicationSplitMenuItem triggers click command twice'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-6675211346434095078</id><published>2011-08-01T19:57:00.000-07:00</published><updated>2011-08-01T19:57:41.035-07:00</updated><title type='text'>WPF - how to display different category in a TreeView using DataTemplateSelector</title><content type='html'>WPF TreeView typically displays hierarchical tree view by using HierarchicalDataTemplate. This HierarchicalDataTemplate allows you to display different types in different ways. For example, for class A type&amp;nbsp;child node, one might want to display image and name while for class B child node, one might need to display name and size textblock. This usually can be archieved by using DataType attribute.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;&amp;lt;HierarchicalDataTemplate x:Key=&quot;LargeAreaTemplate&quot; &lt;u&gt;DataType=&quot;{x:Type vm:LargeArea}&quot;&lt;/u&gt; &amp;gt;
&lt;/pre&gt;If one needs one hierarchical structure with consistent parent-child relationship, defining DataType in HierarchicalDataTemplate will do the trick. However, what if one needs two different hierarchies in a tree view? If two different categories (let&#39;s say, &amp;nbsp;for many-to-many relationship) should be shown in a give tree view, how can it be done with HierarchicalDataTemplate? The following picture shows an example.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0K4dFIalBUmem8P76Vbss2L6bRJankl9HLgoeKaCTc3ZmsKIN4-wtWjjkxeYjY7l1vUIQ0xJiaTFnRJME5ANw5Snx1B9HMH9-g_Quel1jJi8WLCEkNueo9HdSO_1ZH7vzW8a00z_VVj8/s1600/Different-category-in-wpf-tree.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; cssfloat: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;251&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0K4dFIalBUmem8P76Vbss2L6bRJankl9HLgoeKaCTc3ZmsKIN4-wtWjjkxeYjY7l1vUIQ0xJiaTFnRJME5ANw5Snx1B9HMH9-g_Quel1jJi8WLCEkNueo9HdSO_1ZH7vzW8a00z_VVj8/s400/Different-category-in-wpf-tree.png&quot; t$=&quot;true&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
There are 2 categories. By Area category shows Age child nodes. By Age category shows Area child nodes. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In a XAML, we can add&amp;nbsp;different hierarchical data templates per each category. For [By Area] view, Area is parent and Age is child node type and vice versa for [By Age] view.&amp;nbsp;If you look at below example, you can see that&amp;nbsp;each category view has different data templates.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;&amp;lt;Window x:Class=&quot;Tree.MainWindow&quot;
        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
        Title=&quot;MainWindow&quot; Height=&quot;323&quot; Width=&quot;253&quot;
        xmlns:vm=&quot;clr-namespace:Tree&quot;
        &amp;gt;
    
    &amp;lt;Window.Resources&amp;gt;
        &amp;lt;vm:MyTemplateSelector x:Key=&quot;MyTemplateSelector&quot; /&amp;gt;       
        
        &amp;lt;!-- AREA VIEW --&amp;gt;
        &amp;lt;HierarchicalDataTemplate x:Key=&quot;LargeAreaTemplate&quot; DataType=&quot;{x:Type vm:LargeArea}&quot; 
                                  ItemsSource=&quot;{Binding AgeCollection}&quot;
                                  ItemTemplateSelector=&quot;{StaticResource MyTemplateSelector}&quot;&amp;gt;
            &amp;lt;StackPanel Orientation=&quot;Horizontal&quot;&amp;gt;
                &amp;lt;TextBlock Text=&quot;{Binding Name}&quot; /&amp;gt;
                &amp;lt;TextBlock Text=&quot; : Size=&quot; /&amp;gt;
                &amp;lt;TextBlock Text=&quot;{Binding AreaSize}&quot; /&amp;gt;
            &amp;lt;/StackPanel&amp;gt;
        &amp;lt;/HierarchicalDataTemplate&amp;gt;
        &amp;lt;HierarchicalDataTemplate x:Key=&quot;SmallAreaTemplate&quot; DataType=&quot;{x:Type vm:SmallArea}&quot; 
                                  ItemsSource=&quot;{Binding AgeCollection}&quot;
                                  ItemTemplateSelector=&quot;{StaticResource MyTemplateSelector}&quot;&amp;gt;            
            &amp;lt;StackPanel Orientation=&quot;Horizontal&quot;&amp;gt;                
                &amp;lt;TextBlock Text=&quot;{Binding Name}&quot; /&amp;gt;
                &amp;lt;TextBlock Text=&quot; : Population=&quot; /&amp;gt;
                &amp;lt;TextBlock Text=&quot;{Binding Population}&quot; /&amp;gt;
            &amp;lt;/StackPanel&amp;gt;            
        &amp;lt;/HierarchicalDataTemplate&amp;gt;
        &amp;lt;HierarchicalDataTemplate x:Key=&quot;LeafAgeTemplate&quot; DataType=&quot;{x:Type vm:Age}&quot;                                   
                                  ItemTemplateSelector=&quot;{StaticResource MyTemplateSelector}&quot;&amp;gt;
            &amp;lt;StackPanel Orientation=&quot;Horizontal&quot;&amp;gt;
                &amp;lt;TextBlock Text=&quot;{Binding Name}&quot; /&amp;gt;
            &amp;lt;/StackPanel&amp;gt;
        &amp;lt;/HierarchicalDataTemplate&amp;gt;


        &amp;lt;!-- AGE VIEW --&amp;gt;
        &amp;lt;HierarchicalDataTemplate x:Key=&quot;AgeTemplate&quot; DataType=&quot;{x:Type vm:Age}&quot; 
                                  ItemsSource=&quot;{Binding AreaCollection}&quot;
                                  ItemTemplateSelector=&quot;{StaticResource MyTemplateSelector}&quot;&amp;gt;               
            &amp;lt;StackPanel Orientation=&quot;Horizontal&quot;&amp;gt;                
                &amp;lt;TextBlock Text=&quot;{Binding Name}&quot; /&amp;gt;
            &amp;lt;/StackPanel&amp;gt;
        &amp;lt;/HierarchicalDataTemplate&amp;gt;
        &amp;lt;HierarchicalDataTemplate x:Key=&quot;LeafLargeAreaTemplate&quot; DataType=&quot;{x:Type vm:LargeArea}&quot;                                   
                                  ItemTemplateSelector=&quot;{StaticResource MyTemplateSelector}&quot;&amp;gt;
            &amp;lt;StackPanel Orientation=&quot;Horizontal&quot;&amp;gt;
                &amp;lt;TextBlock Text=&quot;{Binding Name}&quot; /&amp;gt;
                &amp;lt;TextBlock Text=&quot; : Size=&quot; /&amp;gt;
                &amp;lt;TextBlock Text=&quot;{Binding AreaSize}&quot; /&amp;gt;
            &amp;lt;/StackPanel&amp;gt;
        &amp;lt;/HierarchicalDataTemplate&amp;gt;
        &amp;lt;HierarchicalDataTemplate x:Key=&quot;LeafSmallAreaTemplate&quot; DataType=&quot;{x:Type vm:SmallArea}&quot;                                   
                                  ItemTemplateSelector=&quot;{StaticResource MyTemplateSelector}&quot;&amp;gt;
            &amp;lt;StackPanel Orientation=&quot;Horizontal&quot;&amp;gt;
                &amp;lt;TextBlock Text=&quot;{Binding Name}&quot; /&amp;gt;
                &amp;lt;TextBlock Text=&quot; : Population=&quot; /&amp;gt;
                &amp;lt;TextBlock Text=&quot;{Binding Population}&quot; /&amp;gt;
            &amp;lt;/StackPanel&amp;gt;
        &amp;lt;/HierarchicalDataTemplate&amp;gt;

        &amp;lt;!-- Style --&amp;gt;
        &amp;lt;Style TargetType=&quot;TreeViewItem&quot;&amp;gt;
            &amp;lt;Setter Property=&quot;IsExpanded&quot; Value=&quot;True&quot;/&amp;gt;
        &amp;lt;/Style&amp;gt;                
    &amp;lt;/Window.Resources&amp;gt;    
    
    &amp;lt;Grid Height=&quot;282&quot; Width=&quot;230&quot;&amp;gt;
        &amp;lt;Button Content=&quot;By Area&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;20,20,0,0&quot; 
                Name=&quot;btnArea&quot; VerticalAlignment=&quot;Top&quot; Width=&quot;90&quot; Click=&quot;btnArea_Click&quot; /&amp;gt;
        &amp;lt;Button Content=&quot;By Age&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Right&quot; Margin=&quot;0,20,26,0&quot;
                Name=&quot;btnAge&quot; VerticalAlignment=&quot;Top&quot; Width=&quot;90&quot; Click=&quot;btnAge_Click&quot; /&amp;gt;

        &amp;lt;TreeView Name=&quot;treeView1&quot; HorizontalAlignment=&quot;Left&quot; VerticalAlignment=&quot;Top&quot; 
                  Margin=&quot;20,49,0,0&quot; Width=&quot;184&quot; Height=&quot;216&quot; 
                  ItemsSource=&quot;{Binding Path=MyItems}&quot;  
                  ItemTemplateSelector=&quot;{StaticResource MyTemplateSelector}&quot;&amp;gt;
        &amp;lt;/TreeView&amp;gt;
    &amp;lt;/Grid&amp;gt;    
&amp;lt;/Window&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
Since TreeView only selects one unique data template at a time for any given type, the sample above is using custom data template selector&amp;nbsp;in ItemTemplateSelector. In a code behind file, the following class is defined.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;public class MyTemplateSelector : DataTemplateSelector
   { 
      public override DataTemplate SelectTemplate(object item, DependencyObject container) 
      { 
         MethodInfo mi = container.GetType().GetMethod(&quot;FindResource&quot;) as MethodInfo;         
         if (mi != null)
         {
            if (MainWindow.ViewMode == ViewMode.ByArea)
            {
               switch (item.ToString())
               {
                  case &quot;Tree.LargeArea&quot;:
                     return mi.Invoke(container, new object[] { &quot;LargeAreaTemplate&quot; }) as DataTemplate;
                  case &quot;Tree.SmallArea&quot;:
                     return mi.Invoke(container, new object[] { &quot;SmallAreaTemplate&quot; }) as DataTemplate;
                  case &quot;Tree.Age&quot;:
                     return mi.Invoke(container, new object[] { &quot;LeafAgeTemplate&quot; }) as DataTemplate;
               }
            }
            else
               switch (item.ToString())
               {
                  case &quot;Tree.Age&quot;:
                     return mi.Invoke(container, new object[] { &quot;AgeTemplate&quot; }) as DataTemplate;
                  case &quot;Tree.LargeArea&quot;:
                     return mi.Invoke(container, new object[] { &quot;LeafLargeAreaTemplate&quot; }) as DataTemplate;
                  case &quot;Tree.SmallArea&quot;:
                     return mi.Invoke(container, new object[] { &quot;LeafSmallAreaTemplate&quot; }) as DataTemplate;
               }
         }      
         return null; 
      } 
   }
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Basically what it does is to&amp;nbsp;find appropriate data template and return it back to TreeView. If null is returned, TreeView searches for appropriate hierarchical data template for the DataType.</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/6675211346434095078/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/08/wpf-how-to-display-different-category.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/6675211346434095078'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/6675211346434095078'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/08/wpf-how-to-display-different-category.html' title='WPF - how to display different category in a TreeView using DataTemplateSelector'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0K4dFIalBUmem8P76Vbss2L6bRJankl9HLgoeKaCTc3ZmsKIN4-wtWjjkxeYjY7l1vUIQ0xJiaTFnRJME5ANw5Snx1B9HMH9-g_Quel1jJi8WLCEkNueo9HdSO_1ZH7vzW8a00z_VVj8/s72-c/Different-category-in-wpf-tree.png" height="72" width="72"/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-7127804827516086989</id><published>2011-07-06T14:57:00.000-07:00</published><updated>2011-08-16T15:10:11.215-07:00</updated><title type='text'>How to right justify text in textbox</title><content type='html'>WinForm TextBox control does not have any property or method that right justify text in the control. But this goal can be archieved by using SelectionStart and SelectionLength&amp;nbsp;property. If you set SelectionStart to last position of the textbox and give a SelectionLength to zero, it mimics&amp;nbsp;moving TextBox position&amp;nbsp;to the end.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is how to right-justify text in the TextBox control.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: Courier New; font-size: small;&quot;&gt;&lt;span style=&quot;font-family: Courier New; font-size: small;&quot;&gt;&lt;span style=&quot;color: blue;&quot;&gt;private&lt;/span&gt;&lt;span style=&quot;font-family: Courier New; font-size: small;&quot;&gt;&lt;span style=&quot;font-family: Courier New; font-size: small;&quot;&gt; &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;color: blue; font-family: Courier New; font-size: small;&quot;&gt;&lt;span style=&quot;color: blue; font-family: Courier New; font-size: small;&quot;&gt;&lt;span style=&quot;color: blue; font-family: Courier New; font-size: small;&quot;&gt;void&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;font-family: Courier New; font-size: small;&quot;&gt;&lt;span style=&quot;font-family: Courier New; font-size: small;&quot;&gt; RightJustify(TextBox textbox)&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
{&lt;br /&gt;
&amp;nbsp; textbox.SelectionStart = textbox.Text.Length;&lt;br /&gt;
&amp;nbsp; textbox.SelectionLength = 0;&lt;br /&gt;
}&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/7127804827516086989/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/07/how-to-right-justify-text-in-textbox.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/7127804827516086989'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/7127804827516086989'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/07/how-to-right-justify-text-in-textbox.html' title='How to right justify text in textbox'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1945083783625463663.post-4937436007450023233</id><published>2011-06-04T21:30:00.000-07:00</published><updated>2011-08-12T17:06:44.783-07:00</updated><title type='text'>UIA - how to automate WPF Ribbon control</title><content type='html'>Microsoft Ribbon for WPF 4.0 is not well working with Coded UI Test.&amp;nbsp;UI recording against WPF&amp;nbsp;ribbon control&amp;nbsp;might work but replaying automation is likely not working. One way of getting around this problem is to use UIA (aka UIAutomation).&lt;br /&gt;
&lt;br /&gt;
Here is an example of WPF Ribbon control in XAML.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;&amp;lt;ribbonwindow height=&quot;480&quot; title=&quot;MainWindow&quot; width=&quot;640&quot; x:class=&quot;WpfRibbonApplication1.MainWindow&quot; x:name=&quot;RibbonWindow&quot; xmlns:ribbon=&quot;clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;&amp;gt;

 &amp;lt;grid x:name=&quot;LayoutRoot&quot;&amp;gt;
        &amp;lt;grid.rowdefinitions&amp;gt;
            &amp;lt;rowdefinition height=&quot;Auto&quot;&amp;gt;&amp;lt;/rowdefinition&amp;gt;
            &amp;lt;rowdefinition height=&quot;*&quot;&amp;gt;&amp;lt;/rowdefinition&amp;gt;
        &amp;lt;/grid.rowdefinitions&amp;gt;

        &amp;lt;ribbon automationproperties.name=&quot;myRibbon&quot; x:name=&quot;myRibbon&quot;&amp;gt;
            &amp;lt;ribbon.applicationmenu&amp;gt;
                &amp;lt;ribbonapplicationmenu smallimagesource=&quot;Images\SmallIcon.png&quot;&amp;gt;
                    &amp;lt;ribbonapplicationmenuitem header=&quot;Hello _Ribbon&quot; imagesource=&quot;Images\LargeIcon.png&quot; x:name=&quot;MenuItem1&quot;&amp;gt;&amp;lt;/ribbonapplicationmenuitem&amp;gt;
                &amp;lt;/ribbonapplicationmenu&amp;gt;
            &amp;lt;/ribbon.applicationmenu&amp;gt;
            &amp;lt;ribbontab header=&quot;Home&quot; x:name=&quot;HomeTab&quot;&amp;gt;
                &amp;lt;ribbongroup header=&quot;Group1&quot; x:name=&quot;Group1&quot;&amp;gt;
                    &amp;lt;ribbonbutton label=&quot;Button1&quot; largeimagesource=&quot;Images\LargeIcon.png&quot; x:name=&quot;Button1&quot;&amp;gt;&amp;lt;/ribbonbutton&amp;gt;

                    &amp;lt;ribbonbutton label=&quot;Button2&quot; smallimagesource=&quot;Images\SmallIcon.png&quot; x:name=&quot;Button2&quot;&amp;gt;&amp;lt;/ribbonbutton&amp;gt;
                    &amp;lt;ribbonbutton label=&quot;Button3&quot; smallimagesource=&quot;Images\SmallIcon.png&quot; x:name=&quot;Button3&quot;&amp;gt;&amp;lt;/ribbonbutton&amp;gt;
                    &amp;lt;ribbonbutton label=&quot;Button4&quot; smallimagesource=&quot;Images\SmallIcon.png&quot; x:name=&quot;Button4&quot;&amp;gt;&amp;lt;/ribbonbutton&amp;gt;
                    
                &amp;lt;/ribbongroup&amp;gt;
                
            &amp;lt;/ribbontab&amp;gt;
            &amp;lt;ribbontab header=&quot;View&quot; x:name=&quot;ViewTab&quot;&amp;gt;
                &amp;lt;ribbongroup header=&quot;Group2&quot; x:name=&quot;Group2&quot;&amp;gt;
                    &amp;lt;ribbonbutton click=&quot;Button11_Click&quot; label=&quot;Button11&quot; largeimagesource=&quot;Images\LargeIcon.png&quot; x:name=&quot;Button11&quot;&amp;gt;&amp;lt;/ribbonbutton&amp;gt;
                &amp;lt;/ribbongroup&amp;gt;
            &amp;lt;/ribbontab&amp;gt;
        &amp;lt;/ribbon&amp;gt;        
    &amp;lt;/grid&amp;gt;
&amp;lt;/ribbonwindow&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
If the application is run, it displays ribbon menus as follows.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8wx19tcRjRRD-P2CncqXyMDhwjMeZRUF-aLDfItMZlD-8jh_Wbrrtst9k6JOtLELvuPHjN_ETZteladW0ACCBF83dNS-g7bmYC4Lk_18hG2YAbTfY6flMoxV_LNAUUqwXa3O7fexoniU/s1600/wpf-ribbon-control.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; cssfloat: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;248&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8wx19tcRjRRD-P2CncqXyMDhwjMeZRUF-aLDfItMZlD-8jh_Wbrrtst9k6JOtLELvuPHjN_ETZteladW0ACCBF83dNS-g7bmYC4Lk_18hG2YAbTfY6flMoxV_LNAUUqwXa3O7fexoniU/s320/wpf-ribbon-control.png&quot; t$=&quot;true&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In order to automate the ribbon control, one can&amp;nbsp;use UIAutomation and here is an example. Please note that two references - UIAutomationClient and UIAutomationTypes - should be added to the Test Project.&lt;br /&gt;
&lt;pre&gt;using System.Threading;
using System.Windows.Automation;  //UIAutomationClient
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UIATestProject
{
    [TestClass]
    public class RibbonTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            AutomationElement root = AutomationElement.RootElement;

            PropertyCondition appCond1 = new PropertyCondition(AutomationElementIdentifiers.NameProperty, &quot;MainWindow&quot;);
            PropertyCondition appCond2 = new PropertyCondition(AutomationElementIdentifiers.ClassNameProperty, &quot;Window&quot;);
            AndCondition appCond = new AndCondition(appCond1, appCond2);
            AutomationElement app = root.FindFirst(TreeScope.Descendants, appCond);

            PropertyCondition ribbonCond1 = new PropertyCondition(AutomationElementIdentifiers.ClassNameProperty, &quot;Ribbon&quot;);
            PropertyCondition ribbonCond2 = new PropertyCondition(AutomationElementIdentifiers.NameProperty, &quot;myRibbon&quot;);
            AndCondition ribbonCond = new AndCondition(ribbonCond1, ribbonCond2);
            AutomationElement custom = app.FindFirst(TreeScope.Descendants, ribbonCond);

            PropertyCondition homeCond = new PropertyCondition(AutomationElementIdentifiers.NameProperty, &quot;Home&quot;);
            AutomationElement homeTab = custom.FindFirst(TreeScope.Descendants, homeCond);
            PropertyCondition viewCond = new PropertyCondition(AutomationElementIdentifiers.NameProperty, &quot;View&quot;);
            AutomationElement viewTab = custom.FindFirst(TreeScope.Descendants, viewCond);
            
            SelectMenu(homeTab);            
            SelectMenu(viewTab);
        }

        private void SelectMenu(AutomationElement elem)
        {
            SelectionItemPattern patt = elem.GetCurrentPattern(SelectionItemPattern.Pattern) as SelectionItemPattern;
            patt.Select();
        }
    }
}
&lt;/pre&gt;&lt;br /&gt;
Basically what the code does is to look for UI elements from the UI hierarchy and select UI menu&amp;nbsp;element by using SelectionItemPattern. Typically &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms727247.aspx&quot;&gt;UISpy.exe&lt;/a&gt; is used&amp;nbsp;to check UI hierarchy and to get element detail information.</content><link rel='replies' type='application/atom+xml' href='http://dotnetbeyond.blogspot.com/feeds/4937436007450023233/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/08/uia-how-to-automate-wpf-ribbon-control.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/4937436007450023233'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1945083783625463663/posts/default/4937436007450023233'/><link rel='alternate' type='text/html' href='http://dotnetbeyond.blogspot.com/2011/08/uia-how-to-automate-wpf-ribbon-control.html' title='UIA - how to automate WPF Ribbon control'/><author><name>Alex</name><uri>http://www.blogger.com/profile/14466854366502861778</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8wx19tcRjRRD-P2CncqXyMDhwjMeZRUF-aLDfItMZlD-8jh_Wbrrtst9k6JOtLELvuPHjN_ETZteladW0ACCBF83dNS-g7bmYC4Lk_18hG2YAbTfY6flMoxV_LNAUUqwXa3O7fexoniU/s72-c/wpf-ribbon-control.png" height="72" width="72"/><thr:total>0</thr:total></entry></feed>