<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Koen Aerts</title>
	<atom:link href="http://koenaerts.ca/feed/" rel="self" type="application/rss+xml" />
	<link>http://koenaerts.ca</link>
	<description></description>
	<lastBuildDate>Tue, 26 Feb 2013 02:43:27 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Automate Ad Blocking hosts file update on Router with DD-WRT Micro Edition</title>
		<link>http://koenaerts.ca/automate_ad_blocking_hosts_file_on_ddwrt_micro_router/</link>
		<comments>http://koenaerts.ca/automate_ad_blocking_hosts_file_on_ddwrt_micro_router/#comments</comments>
		<pubDate>Wed, 20 Feb 2013 04:20:12 +0000</pubDate>
		<dc:creator>Koen</dc:creator>
				<category><![CDATA[Firmware]]></category>
		<category><![CDATA[Hacks]]></category>
		<category><![CDATA[Scripting]]></category>
		<category><![CDATA[UNIX/Linux]]></category>

		<guid isPermaLink="false">http://koenaerts.ca/?p=655</guid>
		<description><![CDATA[Your DD-WRT enabled router can be configured to block ads as described in the Ad Blocking article. For non-Micro DD-WRT versions the ad blocking hosts file on the router can be updated automatically by a custom shell script that you then execute as a cron job, all on the router itself. However, the Micro editions [...]]]></description>
			<content:encoded><![CDATA[<p>Your <a href="http://www.dd-wrt.ca/">DD-WRT</a> enabled router can be configured to block ads as described in the <a href="http://www.dd-wrt.ca/wiki/index.php/Ad_blocking">Ad Blocking</a> article.</p>
<p>For non-Micro DD-WRT versions the <a href="http://winhelp2002.mvps.org/hosts.htm">ad blocking hosts file</a> on the router can be updated automatically by a custom shell script that you then execute as a cron job, all on the router itself. However, the Micro editions of DD-WRT are too limited and the only way to update the router&#8217;s hosts file is by manually copying it to the router via a telnet session, where you basically copy/paste the entire hosts file contents in the telnet screen. However, after each router reboot you will need to repeat the whole process.</p>
<p>So since you can&#8217;t automate this process on the router, it has to be done somewhere else. For instance if you have a Linux/UNIX server on your network, you could write a shell script that downloads the ad blocking hosts file and then uploads it to the router. You can then add this script to a cron job, for instance to run every day at 1am like this:</p>
<pre class="brush: bash; title: ; notranslate">0 1 * * * /home/user/router_ad_block.sh</pre>
<p>Here is an example of what this script may look like:</p>
<pre class="brush: bash; title: ; notranslate">echo &quot;Downloading hosts file...&quot;
wget -O - http://winhelp2002.mvps.org/hosts.txt | grep 127.0.0.1 |
sed '2,$s/[[:space:]]*#.*$//g;' |
grep -v localhost | tr ' ' '\t' |
tr -s '\t' | tr -d '&#92;&#48;15' | sort -u &gt;/tmp/hosts.tmp

ln=`cat /tmp/hosts.tmp | wc -l`
if [ ${ln} -lt 10 ]; then
  echo &quot;Invalid hosts file.&quot;
  exit
fi

# kill DNS service and upload hosts file
echo &quot;Uploading hosts file to router...&quot;
(
echo open 192.168.1.1
sleep 1
echo &quot;admin&quot;
sleep 1
echo &quot;password&quot;
sleep 1
echo &quot;cd /tmp&quot;
sleep 1
echo &quot;killall dnsmasq&quot;
sleep 5
echo &quot;cat &gt; hosts&quot;
sleep 1
cat /tmp/hosts.tmp
sleep 10
) | telnet &gt; /dev/null
rm /tmp/hosts.tmp

# start DNS service.
echo &quot;Starting DNS service on router...&quot;
(
echo open 192.168.1.1
sleep 1
echo &quot;admin&quot;
sleep 1
echo &quot;password&quot;
sleep 1
echo &quot;dnsmasq --conf-file=/tmp/dnsmasq.conf --addn-hosts=/tmp/hosts&quot;
sleep 5
echo &quot;exit&quot;
sleep 1
) | telnet &gt; /dev/null

echo &quot;Done.&quot;</pre>
]]></content:encoded>
			<wfw:commentRss>http://koenaerts.ca/automate_ad_blocking_hosts_file_on_ddwrt_micro_router/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Merge vmdk files in VMWare Player</title>
		<link>http://koenaerts.ca/merge-vmdk-files-in-vmware-player/</link>
		<comments>http://koenaerts.ca/merge-vmdk-files-in-vmware-player/#comments</comments>
		<pubDate>Sat, 08 Dec 2012 16:14:26 +0000</pubDate>
		<dc:creator>Koen</dc:creator>
				<category><![CDATA[Virtualization]]></category>
		<category><![CDATA[VMware]]></category>

		<guid isPermaLink="false">http://koenaerts.ca/?p=644</guid>
		<description><![CDATA[In order to merge split vmdk files into one, you need to use the vmware-vdiskmanager command. However, this is only available if you have VMware Fusion or VMware Workstation installed. VMware Player doesn&#8217;t have this. Luckily this little utility can be downloaded separately from the VMware site. It is the 1023856-vdiskmanager-windows-7.0.1.exe.zip attachment that you will [...]]]></description>
			<content:encoded><![CDATA[<p>In order to merge split vmdk files into one, you need to use the vmware-vdiskmanager command. However, this is only available if you have VMware Fusion or VMware Workstation installed. VMware Player doesn&#8217;t have this.</p>
<p>Luckily this little utility can be <a href="http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&#038;cmd=displayKC&#038;externalId=1023856">downloaded</a> separately from the <a href="http://www.vmware.com/">VMware site</a>. It is the <code>1023856-vdiskmanager-windows-7.0.1.exe.zip</code> attachment that you will need.</p>
<p>Once downloaded, extract and rename <code>1023856-vdiskmanager-windows-7.0.1.exe</code> to <code>vmware-vdiskmanager.exe</code> and copy or move to the directory where VMware Player is installed. For instance <code>C:\Program Files (x86)\VMware\VMware Player</code></p>
<p>In order to merge vmdk files, open a Command Prompt and CD to the directory where the vmdk files are located. For instance <code>CD \VMWareImages\MyImage</code></p>
<p>Assume you have the following vmdk files :<br />
<code>MyImage.vmdk<br />
MyImage-s001.vmdk<br />
MyImage-s002.vmdk<br />
MyImage-s003.vmdk<br />
MyImage-s004.vmdk<br />
MyImage-s005.vmdk<br />
MyImage-s006.vmdk<br />
MyImage-s007.vmdk<br />
MyImage-s008.vmdk</code></p>
<p>To merge them into one single vmdk file, use the following command:</p>
<pre class="brush: bash; title: ; notranslate">C:\VMWareImages\MyImage&gt;&quot;\Program Files (x86)\VMware\VMware Player\vmware-vdiskmanager.exe&quot; -r &quot;MyImage.vmdk&quot; -t 0 MyNewImage.vmdk</pre>
<p>The new vmdk file will then be created:<br />
<code>Creating disk 'MyNewImage.vmdk'<br />
  Convert: 41% done.</code></p>
<p>Once done, either rename the original vmdk files or move them to a different directory. Finally rename <code>MyNewImage.vmdk</code> to <code>MyImage.vmdk</code> and you&#8217;re all set.</p>
]]></content:encoded>
			<wfw:commentRss>http://koenaerts.ca/merge-vmdk-files-in-vmware-player/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Remove leading zeroes from varchar</title>
		<link>http://koenaerts.ca/remove-leading-zeroes-from-varchar/</link>
		<comments>http://koenaerts.ca/remove-leading-zeroes-from-varchar/#comments</comments>
		<pubDate>Fri, 30 Nov 2012 16:04:06 +0000</pubDate>
		<dc:creator>Koen</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Database]]></category>

		<guid isPermaLink="false">http://koenaerts.ca/?p=632</guid>
		<description><![CDATA[The following example shows one way how you can remove leading zeroes from a varchar column in SQL Server: Returns:]]></description>
			<content:encoded><![CDATA[<p>The following example shows one way how you can remove leading zeroes from a varchar column in SQL Server:</p>
<pre class="brush: sql; title: ; notranslate">declare @MyVal varchar(20);
set @MyVal = '0001234ABC00';
select @MyVal, replace(ltrim(replace(@MyVal, '0', ' ')), ' ', '0')</pre>
<p>Returns:</p>
<pre class="brush: plain; title: ; notranslate">'0001234ABC00', '1234ABC00'</pre>
]]></content:encoded>
			<wfw:commentRss>http://koenaerts.ca/remove-leading-zeroes-from-varchar/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>In Progress Dialog</title>
		<link>http://koenaerts.ca/in-progress-dialog/</link>
		<comments>http://koenaerts.ca/in-progress-dialog/#comments</comments>
		<pubDate>Sat, 27 Oct 2012 04:08:51 +0000</pubDate>
		<dc:creator>Koen</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://koenaerts.ca/?p=622</guid>
		<description><![CDATA[The following C# code shows how to make a Progress Bar in a dialog window that can be shown for tasks that run for an undetermined amount of time. Instead of a regular progress bar that progresses from 0 to 100%, this one shows a little indicator that scrolls back and forth, while in the [...]]]></description>
			<content:encoded><![CDATA[<p>The following C# code shows how to make a Progress Bar in a dialog window that can be shown for tasks that run for an undetermined amount of time.</p>
<p><a href="http://koenaerts.ca/wp-content/uploads/inprogress.png"><img src="http://koenaerts.ca/wp-content/uploads/inprogress.png" alt="" title="In Progress" width="244" height="87" class="alignnone size-full wp-image-623" /></a></p>
<p>Instead of a regular progress bar that progresses from 0 to 100%, this one shows a little indicator that scrolls back and forth, while in the background the time consuming task does its work. Once the task has completed, the dialog window with the progress bar closes automatically.</p>
<p>The dialog with the progress bar is contained in a class file called WaitDialog.cs, for which the source code is shown further below. Here is an example of how WaitDialog can be used:</p>
<pre class="brush: csharp; title: ; notranslate">private WaitDialog waitDialog;

// Event executed when a button is pressed.
private void btnDoStuff_Click(object sender, EventArgs e)
{
  BackgroundWorker worker = new BackgroundWorker();
  worker.DoWork += new DoWorkEventHandler(MyDoFunction);
  worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(MyCompletedFunction);

  waitDialog = new WaitDialog(worker);
  waitDialog.ShowDialog();
}

private void MyDoFunction(object sender, DoWorkEventArgs e)
{
  // Do time consuming stuff.
}

private void MyCompletedFunction(object sender, RunWorkerCompletedEventArgs e)
{
  // Time consuming stuff is done.
  waitDialog.DoneWaiting();
}</pre>
<p>Source code for WaitDialog.cs:</p>
<pre class="brush: csharp; title: ; notranslate">using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace My.Project
{
  public class WaitDialog : Form
  {
    private IContainer components = null;
    private Label label1;
    private WaitingProgressBar progressBar1;

    private Thread waitingThread;
    private BackgroundWorker worker;

    private class Anim : Control
    {
      private WaitingProgressBar pBar;
      private delegate void NextStep();
      private NextStep nextStep;
      public Anim(WaitingProgressBar progressBar)
      {
        pBar = progressBar;
        nextStep = new NextStep(nextStepMethod);
      }
      public void DoIt()
      {
        while (true)
        {
          Thread.Sleep(100);
          pBar.Invoke(nextStep);
        }
      }
      private void nextStepMethod()
      {
        pBar.NextStep();
      }
    }

    private class WaitingProgressBar : ProgressBar
    {
      private int inc = 1;
      private int indWidth = 25;
      private int stepSize = 1;
      private int barWidth = 1;

      public WaitingProgressBar()
        : base()
      {
        barWidth = ClientSize.Width * indWidth / 100;
        this.SetStyle(ControlStyles.UserPaint, true);
        this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
        this.SetStyle(ControlStyles.DoubleBuffer, true);
        this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
        this.Paint += OnPaint;
      }

      public int IndicatorWidthPct
      {
        get { return indWidth; }
        set { indWidth = value; barWidth = ClientSize.Width * indWidth / 100; }
      }

      public int StepSize
      {
        get { return stepSize; }
        set { stepSize = value; }
      }

      public void NextStep()
      {
        if ((inc &gt; 0 &amp;&amp; Value &gt;= Maximum) || (inc &lt; 0 &amp;&amp; Value &lt;= Minimum))
        {
          if (inc &gt; 0)
          {
            inc = -1;
          }
          else
          {
            inc = 1;
          }
        }
        Value += (inc * stepSize);
      }

      private void OnPaint(object sender, PaintEventArgs e)
      {
        Graphics gr = e.Graphics;
        SolidBrush foreColor = new SolidBrush(ForeColor);
        int width = e.ClipRectangle.Width;
        int bw = width * Value / Maximum;
        if (inc &lt; 0)
        {
          int ew = bw + barWidth;
          if (ew &gt; width) { ew = width; }
          gr.FillRectangle(foreColor, bw, e.ClipRectangle.Y, (ew-bw), e.ClipRectangle.Height);
        } else {
          int ew = bw - barWidth;
          if (ew &lt; 0) { ew = 0; }
          gr.FillRectangle(foreColor, ew, e.ClipRectangle.Y, (bw-ew), e.ClipRectangle.Height);
        }
      }
    }

    public WaitDialog(BackgroundWorker bgWorker)
    {
      worker = bgWorker;
      InitializeComponent();
    }

    private void WaitDialog_Load(object sender, EventArgs e)
    {
      waitingThread = new Thread(new ThreadStart((new Anim(progressBar1)).DoIt));
      waitingThread.Start();
      worker.RunWorkerAsync();
    }

    public void DoneWaiting()
    {
      waitingThread.Abort();
      waitingThread.Join();
      waitingThread = null;
      Close();
    }

    protected override void Dispose(bool disposing)
    {
      if (disposing &amp;&amp; (components != null))
      {
        components.Dispose();
      }
      base.Dispose(disposing);
    }

    private void InitializeComponent()
    {
      this.label1 = new Label();
      this.progressBar1 = new WaitingProgressBar();
      this.SuspendLayout();
      //
      // label1
      //
      this.label1.AutoSize = true;
      this.label1.Font = new Font(&quot;Microsoft Sans Serif&quot;,
        11F, FontStyle.Bold, GraphicsUnit.Point, ((byte)(0)));
      this.label1.Location = new Point(12, 9);
      this.label1.Name = &quot;label1&quot;;
      this.label1.Size = new Size(206, 18);
      this.label1.TabIndex = 0;
      this.label1.Text = &quot;In Progress. Please wait...&quot;;
      //
      // progressBar1
      //
      this.progressBar1.Location = new Point(12, 30);
      this.progressBar1.Name = &quot;progressBar1&quot;;
      this.progressBar1.Size = new Size(212, 23);
      this.progressBar1.Style = ProgressBarStyle.Continuous;
      this.progressBar1.StepSize = 4;
      this.progressBar1.TabIndex = 1;
      //
      // WaitDialog
      //
      this.AutoScaleDimensions = new SizeF(6F, 13F);
      this.AutoScaleMode = AutoScaleMode.Font;
      this.ClientSize = new Size(236, 60);
      this.ControlBox = false;
      this.Controls.Add(progressBar1);
      this.Controls.Add(label1);
      this.MaximizeBox = false;
      this.MinimizeBox = false;
      this.Name = &quot;WaitDialog&quot;;
      this.ShowIcon = false;
      this.ShowInTaskbar = false;
      this.SizeGripStyle = SizeGripStyle.Hide;
      this.StartPosition = FormStartPosition.CenterParent;
      this.Text = &quot;In Progress&quot;;
      this.Load += new EventHandler(WaitDialog_Load);
      this.ResumeLayout(false);
      this.PerformLayout();
    }
  }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://koenaerts.ca/in-progress-dialog/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Handling Big Red X DataGridView</title>
		<link>http://koenaerts.ca/big-red-x-datagridview/</link>
		<comments>http://koenaerts.ca/big-red-x-datagridview/#comments</comments>
		<pubDate>Fri, 14 Sep 2012 14:33:48 +0000</pubDate>
		<dc:creator>Koen</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[Errors]]></category>

		<guid isPermaLink="false">http://koenaerts.ca/?p=617</guid>
		<description><![CDATA[The reason why sometimes a grid control shows a big red X and stops working properly is because an unhandled exception has occurred during the control’s OnPaint event. One way to handle this is by extending from the grid control and overriding the OnPaint event so that any exceptions can be handled. Of course, the [...]]]></description>
			<content:encoded><![CDATA[<p>The reason why sometimes a grid control shows a big red X and stops working properly is because an unhandled exception has occurred during the control’s OnPaint event.</p>
<p><a href="http://koenaerts.ca/wp-content/uploads/dgvredx.png"><img src="http://koenaerts.ca/wp-content/uploads/dgvredx-300x58.png" alt="" title="Big Red X" width="300" height="58" class="alignnone size-medium wp-image-618" /></a></p>
<p>One way to handle this is by extending from the grid control and overriding the OnPaint event so that any exceptions can be handled. Of course, the best solution is to try and prevent such exceptions from happening in the first place.</p>
<pre class="brush: csharp; title: ; notranslate">public class SafeDataGridView : DataGridView
{
  protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
  {
    try
    {
      base.OnPaint(e);
    }
    catch (Exception)
    {
      this.Invalidate();
    }
  }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://koenaerts.ca/big-red-x-datagridview/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting Owner of a File in Windows</title>
		<link>http://koenaerts.ca/getting-windows-file-owner/</link>
		<comments>http://koenaerts.ca/getting-windows-file-owner/#comments</comments>
		<pubDate>Fri, 06 Jul 2012 21:02:44 +0000</pubDate>
		<dc:creator>Koen</dc:creator>
				<category><![CDATA[AutoIt]]></category>
		<category><![CDATA[Scripting]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://koenaerts.ca/?p=608</guid>
		<description><![CDATA[Through Windows&#8217; WMI Service you can find out who the owner is of a file. This is somewhat similar to the user/group owner of a file in UNIX or Linux, as shown in the example below, where the file myfile.txt is owned by user root and group root. With the following AutoIt code, you can [...]]]></description>
			<content:encoded><![CDATA[<p>Through Windows&#8217; <a href="http://technet.microsoft.com/en-us/library/ee198932.aspx">WMI Service</a> you can find out who the owner is of a file. This is somewhat similar to the user/group owner of a file in UNIX or Linux, as shown in the example below, where the file <code>myfile.txt</code> is owned by user <code>root</code> and group <code>root</code>.</p>
<pre class="brush: bash; title: ; notranslate">$ ls -al myfile.txt
-rw-rw-r-- 1 root root 0 Jul  6 14:57 myfile.txt</pre>
<p>With the following <a href="http://www.autoitscript.com/site/autoit/">AutoIt</a> code, you can get the owner username of a given file. It should be relatively easy to convert this code to a Visual Basic or C# equivalent, if needed.</p>
<pre class="brush: vb; title: ; notranslate">Func GetOwner($file)
    Local $computer = &quot;.&quot;
    Local $wmi = ObjGet(&quot;winmgmts:{impersonationLevel=impersonate}!\\&quot; &amp; $computer &amp; &quot;\root\cimv2&quot;)

    Dim $res
    $res = $wmi.ExecQuery(&quot;ASSOCIATORS OF {Win32_LogicalFileSecuritySetting='&quot; &amp; $file &amp; &quot;'} WHERE AssocClass=Win32_LogicalFileOwner ResultRole=Owner&quot;)

    For $val In $res
        Return $val.AccountName
    Next
EndFunc</pre>
]]></content:encoded>
			<wfw:commentRss>http://koenaerts.ca/getting-windows-file-owner/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler</title>
		<link>http://koenaerts.ca/project-euler/</link>
		<comments>http://koenaerts.ca/project-euler/#comments</comments>
		<pubDate>Thu, 31 May 2012 18:46:52 +0000</pubDate>
		<dc:creator>Koen</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://koenaerts.ca/?p=602</guid>
		<description><![CDATA[If you plan on learning a new programming language, one good way to get to know the language better is by using it to solve the computational problems found on the Project Euler site. Currently there are about 385 problems to be solved, however more are added regularly. They start out relatively easy but become [...]]]></description>
			<content:encoded><![CDATA[<p>If you plan on learning a new programming language, one good way to get to know the language better is by using it to solve the computational problems found on the <a href="http://projecteuler.net/">Project Euler site</a>.</p>
<p>Currently there are about 385 problems to be solved, however more are added regularly. They start out relatively easy but become more difficult and challenging. As you progress throughout the problems you will find that certain problems often involve similar things. For instance many of the problems involve prime numbers, so as you progress further you can create libraries in your code that can include common functions, such as those that can check whether a given number is a prime number, or a function that can generate prime numbers, etc.</p>
<p>Some of the easier problems can be solved by &#8220;brute force&#8221; approaches, i.e. your program calculates all the possible paths to calculate the greatest sum, however the more difficult problems would require trillions of iterations and computations using the same brute force approach. Therefore you&#8217;ll have to find different and more elegant solutions in order to find the answers.</p>
]]></content:encoded>
			<wfw:commentRss>http://koenaerts.ca/project-euler/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Multi-color Text in ProgressBar</title>
		<link>http://koenaerts.ca/multi-color-text-in-progressbar/</link>
		<comments>http://koenaerts.ca/multi-color-text-in-progressbar/#comments</comments>
		<pubDate>Fri, 27 Apr 2012 03:08:06 +0000</pubDate>
		<dc:creator>Koen</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://koenaerts.ca/?p=594</guid>
		<description><![CDATA[The standard ProgressBar class provided by the .NET Framework does not have a way to write custom text over the progress bar. However, it can still be achieved by extending from the standard ProgressBar and by implementing your own OnPaint event handler. The other thing to keep in mind is the color of the displayed [...]]]></description>
			<content:encoded><![CDATA[<p>The standard <a href="http://msdn.microsoft.com/en-us/library/de047043.aspx">ProgressBar</a> class provided by the <a href="http://msdn.microsoft.com/en-us/library/w0x726c2.aspx">.NET Framework</a> does not have a way to write custom text over the progress bar. However, it can still be achieved by extending from the standard <code>ProgressBar</code> and by implementing your own <code>OnPaint</code> event handler.</p>
<p>The other thing to keep in mind is the color of the displayed text, because its background will be a combination of 2 colors: the section without the progress bar (<code>BackColor</code> &#8211; usually a lighter color) and the section with the progress bar (<code>ForeColor</code> &#8211; usually a darker color). So you need to make sure that the text will be clearly visible on either background color.</p>
<p><a href="http://koenaerts.ca/wp-content/uploads/prgbarmultcol1.png"><img src="http://koenaerts.ca/wp-content/uploads/prgbarmultcol1.png" alt="" title="Multi-color Text in ProgressBar" width="229" height="40" class="alignnone size-full wp-image-595" /></a></p>
<p>One way to deal with this is to display the text in both colors. The text section that has the light background (no progress bar) will be displayed in a dark color, and the text section on the dark background (with progress bar) will have a light color.</p>
<p>To accomplish this effect, we create 2 bitmaps. One that represents the light text (<code>Brushes.White</code>) on the dark background (with progressbar &#8211; see <code>Bitmap b1</code>) and another that represents the dark text (<code>Brushes.Black</code>) on the light background (no progress bar &#8211; see <code>Bitmap b2</code>).</p>
<p><a href="http://koenaerts.ca/wp-content/uploads/prgbarmultcol2.png"><img src="http://koenaerts.ca/wp-content/uploads/prgbarmultcol2.png" alt="" title="2 Bitmaps in ProgressBar" width="229" height="62" class="alignnone size-full wp-image-596" /></a></p>
<p>Lastly, the appropriate <code>Rectangle</code> sections of the 2 Bitmaps are copied to their corresponding <code>Rectangle</code> sections on the <code>Graphics</code> instance of the <code>ProgressBar</code>.</p>
<p>The following C# code shows all the relevant pieces that you can copy to the appropriate places in your <code>Form</code> code.</p>
<pre class="brush: csharp; title: ; notranslate">namespace My.Project
{
  public class MyForm : Form
  {
    private CustomProgressBar progressBar;

    public MyForm()
    {
      InitializeComponent();
    }

    private void InitializeComponent()
    {
      this.progressBar = new CustomProgressBar();

      //
      // progressBar
      //
      this.progressBar.LabelText = null;
      this.progressBar.Location = new Point(0, 0);
      this.progressBar.Name = &quot;progressBar&quot;;
      this.progressBar.Size = new Size(300, 25);
      this.progressBar.Style = ProgressBarStyle.Continuous;
    }

    private void setProgressBarText(string text)
    {
      progressBar.LabelText = text;
      progressBar.Invalidate();
    }

    private void setProgressBarValue(int pct)
    {
      progressBar.Value = pct;
    }

    class CustomProgressBar : ProgressBar
    {
      private string labelText;

      public string LabelText
      {
        get { return labelText; }
        set { labelText = value; }
      }

      public CustomProgressBar() : base()
      {
         this.SetStyle(ControlStyles.UserPaint, true);
         this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
         this.SetStyle(ControlStyles.DoubleBuffer, true);
         this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
         this.Paint += OnPaint;
      }

      private void OnPaint(object sender, PaintEventArgs e)
      {
        Graphics gr = e.Graphics;
        int bw = e.ClipRectangle.Width * this.Value / this.Maximum;
        SolidBrush foreColor = new SolidBrush(this.ForeColor);

        if (string.IsNullOrEmpty(labelText))
        {
          gr.FillRectangle(foreColor, e.ClipRectangle.X,
            e.ClipRectangle.Y, bw, e.ClipRectangle.Height);
        }
        else
        {
          Font textFont = SystemFonts.DefaultFont;
          float left = 5f;
          float top = (this.Height &gt;&gt; 1)
            - (gr.MeasureString(LabelText, textFont).Height / 2.0F);
          PointF labelPos = new PointF(left, top);

          Bitmap b1 = new Bitmap(e.ClipRectangle.Width, e.ClipRectangle.Height);
          Graphics gr1 = Graphics.FromImage(b1);
          gr1.FillRectangle(foreColor, e.ClipRectangle.X,
            e.ClipRectangle.Y, bw, e.ClipRectangle.Height);
          gr1.DrawString(LabelText, textFont, Brushes.White, labelPos);
          Rectangle r1 = new Rectangle(0, 0, bw, e.ClipRectangle.Height);

          Bitmap b2 = new Bitmap(e.ClipRectangle.Width, e.ClipRectangle.Height);
          Graphics gr2 = Graphics.FromImage(b2);
          gr2.FillRectangle(new SolidBrush(this.BackColor), bw,
            e.ClipRectangle.Y, e.ClipRectangle.Width - bw, e.ClipRectangle.Height);
          gr2.DrawString(LabelText, textFont, Brushes.Black, labelPos);
          Rectangle r2 = new Rectangle(bw, 0,
            e.ClipRectangle.Width - bw, e.ClipRectangle.Height);

          gr.DrawImage(b1, r1, r1, GraphicsUnit.Pixel);
          gr.DrawImage(b2, r2, r2, GraphicsUnit.Pixel);
        }
      }
    }
  }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://koenaerts.ca/multi-color-text-in-progressbar/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Total Mouse Control in Javascript</title>
		<link>http://koenaerts.ca/total-mouse-control-in-javascript/</link>
		<comments>http://koenaerts.ca/total-mouse-control-in-javascript/#comments</comments>
		<pubDate>Mon, 23 Apr 2012 02:16:15 +0000</pubDate>
		<dc:creator>Koen</dc:creator>
				<category><![CDATA[HTML]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://koenaerts.ca/?p=580</guid>
		<description><![CDATA[The following article was originally written back in 2006. The code example below shows you how you can include better mouse control over your web pages, even the right-click mouse event. The example below basically shows you a page with 2 boxes on it. These boxes are called &#8216;Drag Me 1&#8242; and &#8216;Drag Me 2&#8242;. [...]]]></description>
			<content:encoded><![CDATA[<p>The following article was originally written back in 2006.</p>
<p>The code example below shows you how you can include better mouse control over your web pages, even the right-click mouse event. </p>
<p>The example below basically shows you a page with 2 boxes on it. These boxes are called &#8216;Drag Me 1&#8242; and &#8216;Drag Me 2&#8242;. Using your mouse, you will be able to drag these boxes on your screen. You can use either mouse button to start the drag event. </p>
<p>On top of the screen, you will see your current mouse position (x, y coordinates) and which was the last mouse button that was pressed down or up (ie right down).<br />
There is also a button that you can click, and it will pop-up a new window that shows you the innerHTML of the body. This way you can see how the page contents are affected by your mouse actions. </p>
<p>The first step on hooking your own event handlers to your mouse actions is to disable the context menu, which pops-up when you click your right mouse button.</p>
<p>Then you define your new event handler functions for the next 3 events:<br />
- mouse up<br />
- mouse down<br />
- mouse move</p>
<p>Next, you hook up the new handlers to your window using the next lines:<br />
window.document.onmousedown = mouseDown;<br />
window.document.onmouseup = mouseUp;<br />
window.document.onmousemove = getMouseXYPos;</p>
<p>And finally, to enable the dragging functionality of the boxes, you will also need to hook up the mousedown and mouseup events to each of the boxes individually:</p>
<pre class="brush: xml; title: ; notranslate">&lt;div onmousedown=&quot;dragPiece(this);&quot; onmouseup=&quot;drop();&quot;&gt;Drag Me 1&lt;/div&gt;</pre>
<p>Enough theory; here&#8217;s the code:</p>
<pre class="brush: xml; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
&lt;!DOCTYPE html PUBLIC
    &quot;-//W3C//DTD XHTML 1.1//EN&quot;
    &quot;http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xml:lang=&quot;en&quot;&gt;
  &lt;head&gt;
    &lt;title&gt;Mouse control example&lt;/title&gt;
    &lt;style type=&quot;text/css&quot;&gt;
      .body {
        background-color:#ffffff;
        color:#000000;
        margin:0;
        overflow-y:scroll;
      }

      .tagnormal {
        background-color:#aabbcc;
        font-size:12px;
        font-weight:normal;
        color:#ffff66;
        width:100px;
        margin:2px;
        padding:2px;
        border-color:#000000;
        border-style:solid;
        border-width:1px;
      }

      .tagdrag {
        background-color:#aabbcc;
        font-size:12px;
        font-weight:normal;
        color:#ffff66;
        width:100px;
        margin:2px;
        padding:2px;
        border-color:#000000;
        border-style:solid;
        border-width:1px;
        border-bottom-width:2px;
        border-right-width:2px;
      }
    &lt;/style&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
    // &lt;![CDATA[
      document.oncontextmenu = new Function(&quot;return false&quot;); 

      // Temporary variables to hold mouse x-y pos.
      var iMousePosX = 0;
      var iMousePosY = 0; 

      var iOrigObjTop;
      var iOrigObjLeft; 

      var iDragObjTopDiff;
      var iDragObjLeftDiff; 

      var rightclick = false;
      var oDragObj = null; 

      // Start dragging
      function dragPiece(sourceObject) {
        // Change object style.
        sourceObject.className = &quot;tagdrag&quot;; 

        // Remember original object position.
        iOrigObjTop = parseInt(sourceObject.style.top);
        iOrigObjLeft = parseInt(sourceObject.style.left); 

        iDragObjTopDiff = iMousePosY - iOrigObjTop;
        iDragObjLeftDiff = iMousePosX - iOrigObjLeft; 

        oDragObj = sourceObject;
      } 

      // Stop dragging
      function drop() {
        oDragObj.className = &quot;tagnormal&quot;;
        oDragObj = null;
      } 

      // Handle mouse key down.
      function mouseDown(e) {
        if (!e) var e = window.event;
        if (e.which) rightclick = (e.which == 3);
        else if (e.button) rightclick = (e.button == 2); 

        if (rightclick) {
          document.getElementById(&quot;mousestat&quot;).innerHTML = &quot;right down&quot;;
          bMouseRightKeyDown = true;
        } else {
          document.getElementById(&quot;mousestat&quot;).innerHTML = &quot;left down&quot;;
          bMouseLeftKeyDown = true;
        }
        return false;
      } 

      // Handle mouse key up.
      function mouseUp(e) {
        if (!e) var e = window.event;
        if (e.which) rightclick = (e.which == 3);
        else if (e.button) rightclick = (e.button == 2); 

        if (rightclick) {
          document.getElementById(&quot;mousestat&quot;).innerHTML = &quot;right up&quot;;
          bMouseRightKeyDown = false;
        } else {
          document.getElementById(&quot;mousestat&quot;).innerHTML = &quot;left up&quot;;
          bMouseLeftKeyDown = false;
        }
        return false;
      } 

      // Process mouse movement.
      function getMouseXY(posX, posY) {
        iMousePosX = posX;
        iMousePosY = posY; 

        document.getElementById(&quot;mousepos&quot;).innerHTML = iMousePosX + &quot;, &quot; + iMousePosY; 

        // Move object, if dragging.
        if (oDragObj != null) {
          oDragObj.style.top = (iMousePosY - iDragObjTopDiff) + &quot;px&quot;;
          oDragObj.style.left = (iMousePosX - iDragObjLeftDiff) + &quot;px&quot;;
        }
      } 

      // Mouse movement event handler
      function getMouseXYPos(e) {
        if (!e) var e = window.event;
        getMouseXY(e.clientX + document.body.scrollLeft,
        e.clientY + document.body.scrollTop);
        return true;
      } 

      function showSource() {
        var popup = window.open('', '');
        popup.document.writeln(&quot;&lt;html&gt;&lt;head&gt;&lt;title&gt;source&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;xmp&gt;&quot;);
        popup.document.writeln(document.getElementById(&quot;canvas&quot;).innerHTML);
        popup.document.writeln(&quot;&lt;/xmp&gt;&lt;/body&gt;&lt;/html&gt;&quot;);
        popup.document.close();
      } 

      // Attach new event handlers.
      window.document.onmousedown = mouseDown;
      window.document.onmouseup = mouseUp;
      window.document.onmousemove = getMouseXYPos;
    // ]]&gt;
    &lt;/script&gt;
  &lt;/head&gt; 

  &lt;body id=&quot;canvas&quot; class=&quot;body&quot;&gt;
    &lt;div&gt;
      &lt;span&gt;Mouse position: &lt;/span&gt;&lt;span id=&quot;mousepos&quot;&gt;&lt;/span&gt;&lt;br /&gt;
      &lt;span&gt;Last Button Status: &lt;/span&gt;&lt;span id=&quot;mousestat&quot;&gt;&lt;/span&gt;&lt;br /&gt;
      &lt;span id=&quot;showsrc&quot; class=&quot;tagnormal&quot; onclick=&quot;showSource();&quot;&gt;
        Click here to show body.innerHTML
      &lt;/span&gt;
    &lt;/div&gt;
    &lt;div id=&quot;lbl1&quot;
         style=&quot;position:absolute;left:10px;top:140px&quot;
         class=&quot;tagnormal&quot;
         onmousedown=&quot;dragPiece(this);&quot;
         onmouseup=&quot;drop();&quot;&gt;Drag Me 1&lt;/div&gt;
    &lt;div id=&quot;lbl2&quot;
         style=&quot;position:absolute;left:10px;top:180px&quot;
         class=&quot;tagnormal&quot;
         onmousedown=&quot;dragPiece(this);&quot;
         onmouseup=&quot;drop();&quot;&gt;Drag Me 2&lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre>
]]></content:encoded>
			<wfw:commentRss>http://koenaerts.ca/total-mouse-control-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Executing private methods in Java</title>
		<link>http://koenaerts.ca/executing-private-methods-in-java/</link>
		<comments>http://koenaerts.ca/executing-private-methods-in-java/#comments</comments>
		<pubDate>Sun, 22 Apr 2012 01:44:02 +0000</pubDate>
		<dc:creator>Koen</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://koenaerts.ca/?p=577</guid>
		<description><![CDATA[Normally, private methods in a class are not visible to other classes and cannot be executed. However, through reflection, which enables dynamic retrieval of classes and data structures by name, you can still access and execute private methods in another class. Consider the following class, which defines a public method called getValue1 and a private [...]]]></description>
			<content:encoded><![CDATA[<p>Normally, private methods in a class are not visible to other classes and cannot be executed. However, through reflection, which enables dynamic retrieval of classes and data structures by name, you can still access and execute private methods in another class.</p>
<p>Consider the following class, which defines a public method called <code>getValue1</code> and a private method called <code>getValue2</code>:</p>
<pre class="brush: java; title: ; notranslate">public class OtherClass {

    public String getValue1(int number) {
        return &quot;public value &quot; + number;
    }

    private String getValue2(int number) {
        return &quot;private value &quot; + number;
    }
}</pre>
<p>Normally this is how you would call the public method <code>getValue1</code>:</p>
<pre class="brush: java; title: ; notranslate">OtherClass myClass1 = new OtherClass();
System.out.println(myClass1.getValue1(123));</pre>
<p>If your code had contained the following line:
<pre class="brush: java; title: ; notranslate">System.out.println(myClass1.getValue2(456));</pre>
<p>it wouldn&#8217;t have compiled due to the following error:<br />
<code>error: getValue2() has private access in OtherClass</code></p>
<p>The example below illustrates how you can use reflection to call the private method <code>getValue2</code> in <code>OtherClass</code>:</p>
<pre class="brush: java; title: ; notranslate">import java.lang.reflect.Method;

public class MainClass {

    public static void main(String[] args)
        throws Throwable
    {
        OtherClass myClass1 = new OtherClass();

        System.out.println(myClass1.getValue1(123));

        // MainClass.java: error: getValue2() has private access in OtherClass
        //System.out.println(myClass1.getValue2(456));

        String val = (String) callMethod(
            myClass1, &quot;getValue2&quot;, new Object[] {456});
        System.out.println(val);
    }

    public static Object callMethod(Object object,
        String methodName, Object[] args)
        throws Throwable
    {
        Class&lt;?&gt; clazz = object.getClass();
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            if (methodName.equals(method.getName())) {
                method.setAccessible(true);
                return method.invoke(object, args);
            }
        }
        return null;
    }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://koenaerts.ca/executing-private-methods-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
