<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Somedave</title>
	<atom:link href="http://somedave.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://somedave.wordpress.com</link>
	<description>Notes on .NET, Mono, and XML from Dave Glick</description>
	<lastBuildDate>Fri, 17 Feb 2012 17:07:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='somedave.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Somedave</title>
		<link>http://somedave.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://somedave.wordpress.com/osd.xml" title="Somedave" />
	<atom:link rel='hub' href='http://somedave.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Introducing NiceThreads</title>
		<link>http://somedave.wordpress.com/2012/02/17/introducing-nicethreads/</link>
		<comments>http://somedave.wordpress.com/2012/02/17/introducing-nicethreads/#comments</comments>
		<pubDate>Fri, 17 Feb 2012 17:05:28 +0000</pubDate>
		<dc:creator>somedave</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[nicethreads]]></category>
		<category><![CDATA[opensource]]></category>
		<category><![CDATA[threading]]></category>

		<guid isPermaLink="false">http://somedave.wordpress.com/?p=79</guid>
		<description><![CDATA[NiceThreads is threading utility library designed to make different threading primitives easier to use with a more consistent API. It started out of frustration with the different options (and more specifically, the different APIs) for enabling thread safety and locks in the .NET framework and how much code was required to use some of them. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=somedave.wordpress.com&amp;blog=13050144&amp;post=79&amp;subd=somedave&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>NiceThreads is threading utility library designed to make different threading primitives easier to use with a more consistent API. It started out of frustration with the different options (and more specifically, the different APIs) for enabling thread safety and locks in the .NET framework and how much code was required to use some of them. NiceThreads provides a consistent interface for standard <a href="http://msdn.microsoft.com/en-us/library/system.threading.monitor.aspx">Monitor</a> locks and the <a href="http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx">ReaderWriterLockSlim</a> class (and possibly others in the future). It also provides support for activating and deactivating these locking primitives through the <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx">disposable pattern</a>. Finally, it provides wrappers that can easily provide thread-safety to unsafe objects.</p>
<h2>Common API</h2>
<div>Both Monitor (and the &#8220;lock&#8221; statement which is syntactic sugar for Monitor) and ReaderWriterLockSlim attempt to solve the same problem: preventing conflicting concurrent access to objects that might need to be read or written to by multiple threads. They both do this by limiting access to the object to one thread at a time (or in the case of read locks provided by ReaderWriterLockSlim, only to threads that signal they want read-only access) while making other threads wait their turn. However, even though both classes provide similar functionality they are intended for different uses and have <a href="http://blogs.msdn.com/b/pedram/archive/2007/10/07/a-performance-comparison-of-readerwriterlockslim-with-readerwriterlock.aspx">different tradeoffs</a>. Further, they use similar but different APIs making switching between them difficult.</div>
<div></div>
<div>To solve this problem, NiceThreads provides a consistent ILocker interface that has implementations wrapping both classes and provides a consistent API. The rest of NiceThreads is designed to interact with ILocker allowing interchangeable use of the different types of locking primitives. In addition, the ILocker interface can be used directly to provide a consistent wrapper around either locking class for your own code.</div>
<div></div>
<div>For example:</div>
<p><pre class="brush: csharp;">
ILocker locker = new ReaderWriterLockSlimLocker();
locker.EnterReadLock();
// Do work...
locker.ExitReadLock();
locker = new MonitorLocker();
locker.EnterReadLock();
// Do work...
locker.ExitReadLock();
</pre></p>
<h2>Disposable Pattern</h2>
<div>
<div>Both locking primitives require explicitly activating the lock and subsiquently manually removing the lock when finished. This can lead to problems if the developer forgets to release the lock or ends up exiting the normal program flow (for example, because an exception was thrown). The &#8220;lock&#8221; keyword in C# attempts to make this design easier to use for the Monitor class by abstracting Monitor instantiation and surrounding it&#8217;s use in a control block, however, no such keyword exists for other locking classes such as ReaderWriterLockSlim. In addition, using the &#8220;lock&#8221; keyword means some control is lost over the lifecycle and usage of the underlying Monitor class.</div>
<div></div>
<div>NiceThreads attempts to solve this problem by providing a set of classes that implement IDisposable and wraps an underlying ILocker (which in turn provides consistent access to alternate framework locking classes). They activate the requested lock type on instantiation and free it on disposal. This allows the developer to use the built-in support for the disposable pattern in .NET to automatically free a lock when finished with it by using the &#8220;using&#8221; statement.</div>
<div></div>
<div>For example:</div>
</div>
<div><pre class="brush: csharp;">
ILocker locker = new ReaderWriterLockSlimLocker();
using(new ReadLock(locker))
{
  // Do work...
}
</pre></p>
<h2>Thread-Safe Wrappers</h2>
<div>Even with the added convenience of a consistent API and disposable pattern support, implementing thread-safety for non-thread-safe objects can still require a fair amount of code. For every object that needs to be protected, a new locking object potentially needs to be created and maintained. NiceThreads helps implement thread safety for objects by providing wrapper classes that encapsulate generic locking logic and provide thread-safe access to their underlying object. SyncObject&lt;T&gt; wraps an arbitrary type and ReadOnlySyncObject&lt;T&gt; wraps an arbitrary type while providing &#8220;readonly&#8221; semantics (I.e., once the ReadOnlySyncObject&lt;T&gt; has been constructed, it&#8217;s underlying object cannot be changed). These classes provide a variety of methods to expose their wrapped object in thread-safe ways including thread-safe getting and setting, disposable pattern access, and action/function providers (I.e., lambdas or anonymous methods).</div>
<div></div>
<div>For example:</div>
<p><pre class="brush: csharp;">&lt;/pre&gt;
SyncObject&lt;int&gt; num = new SyncObject&lt;int&gt;(10);
num.Sync = 20; // Access as a property with a thread-safe setter
int value = num.Sync; // Access as a property with a thread-safe getter
using(num.WriteLock())
{
 // We can now access using unsafe code
 num.UnsyncField++; // Provides direct field access
 value = num.Unsync; // Access as a property with an unsafe getter
}
num.DoWrite(n =&gt; n + 10); // Thread-safe write with an Action
value = num.DoRead(n =&gt; n + 100); // Thread-safe read with a Func
&lt;pre&gt;</pre></p>
<h2>Obtaining</h2>
<p>NiceThreads is open source and released under the Apache 2.0 license. It can be obtained here: <a href="https://dracorp.assembla.com/spaces/nicethreads">https://dracorp.assembla.com/spaces/nicethreads</a></div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/somedave.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/somedave.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/somedave.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/somedave.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/somedave.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/somedave.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/somedave.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/somedave.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/somedave.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/somedave.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/somedave.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/somedave.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/somedave.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/somedave.wordpress.com/79/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=somedave.wordpress.com&amp;blog=13050144&amp;post=79&amp;subd=somedave&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://somedave.wordpress.com/2012/02/17/introducing-nicethreads/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eca63cf43d273f0329e7c2ac9fae223b?s=96&#38;d=http%3A%2F%2Fs0.wp.com%2Fi%2Fmu.gif&#38;r=G" medium="image">
			<media:title type="html">somedave</media:title>
		</media:content>
	</item>
		<item>
		<title>XQuery Function To Get The Number Of Week/Work Days</title>
		<link>http://somedave.wordpress.com/2010/06/17/xquery-function-to-get-the-number-of-weekwork-days/</link>
		<comments>http://somedave.wordpress.com/2010/06/17/xquery-function-to-get-the-number-of-weekwork-days/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 20:06:39 +0000</pubDate>
		<dc:creator>somedave</dc:creator>
				<category><![CDATA[Xml]]></category>
		<category><![CDATA[XQuery]]></category>
		<category><![CDATA[networkdays]]></category>
		<category><![CDATA[xml]]></category>
		<category><![CDATA[xquery]]></category>

		<guid isPermaLink="false">http://somedave.wordpress.com/?p=58</guid>
		<description><![CDATA[I&#8217;m back. Don&#8217;t worry (my one reader), I haven&#8217;t given up on this blogging idea. I&#8217;ve just been very busy recently. Today&#8217;s post is an XQuery function designed to get a count of the number of week (or work) days between two dates. It&#8217;s designed to mimic the Excel NETWORKDAYS function. I got the algorithm from Bernal Schooley [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=somedave.wordpress.com&amp;blog=13050144&amp;post=58&amp;subd=somedave&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m back. Don&#8217;t worry (my one reader), I haven&#8217;t given up on this blogging idea. I&#8217;ve just been very busy recently.</p>
<p>Today&#8217;s post is an XQuery function designed to get a count of the number of week (or work) days between two dates. It&#8217;s designed to mimic the Excel NETWORKDAYS function. I got the algorithm from Bernal Schooley in this <a href="http://www.eggheadcafe.com/community/aspnet/2/44982/how-to-calculate-num-of-w.aspx">thread</a> and then adapted it to XQuery. It also makes use of the <a href="http://www.xqueryfunctions.com/">FunctX</a> <a href="http://www.xqueryfunctions.com/xq/functx_day-of-week.html">day-of-week</a> function, so if you have FunctX functions already referenced you can take that part out.</p>
<p><pre class="brush: plain;">

declare namespace functx = &quot;http://www.functx.com&quot;;

declare function functx:day-of-week
 ($date as xs:anyAtomicType?) as xs:integer? {
 if (empty($date))
 then ()
 else
  xs:integer((xs:date($date) - xs:date('1901-01-06')) div xs:dayTimeDuration('P1D')) mod 7
};

declare function local:weekdays
 ($start as xs:anyAtomicType?, $end as xs:anyAtomicType?) as xs:integer? {
 if(empty($start) or empty($end))
 then()
 else
  if($start &gt; $end)
  then -local:weekdays($end, $start)
  else
   let $dayOfWeekStart := functx:day-of-week($start)
   let $dayOfWeekEnd := functx:day-of-week($end)
   let $adjDayOfWeekStart := if($dayOfWeekStart = 0) then 7 else $dayOfWeekStart
   let $adjDayOfWeekEnd := if($dayOfWeekEnd = 0) then 7 else $dayOfWeekEnd
   return
    if($adjDayOfWeekStart &lt;= $adjDayOfWeekEnd)
    then xs:integer((xs:integer(days-from-duration(xs:date($end) - xs:date($start)) div 7) * 5)
     + max(((min((($adjDayOfWeekEnd + 1), 6)) - $adjDayOfWeekStart), 0)))
    else xs:integer((xs:integer(days-from-duration(xs:date($end) - xs:date($start)) div 7) * 5)
     + min((($adjDayOfWeekEnd + 6) - min(($adjDayOfWeekStart, 6)), 5)))
};

</pre></p>
<p>Usage:</p>
<p><pre class="brush: plain;">

local:weekdays('2009-06-01', '2010-06-30')

</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/somedave.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/somedave.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/somedave.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/somedave.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/somedave.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/somedave.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/somedave.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/somedave.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/somedave.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/somedave.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/somedave.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/somedave.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/somedave.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/somedave.wordpress.com/58/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=somedave.wordpress.com&amp;blog=13050144&amp;post=58&amp;subd=somedave&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://somedave.wordpress.com/2010/06/17/xquery-function-to-get-the-number-of-weekwork-days/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eca63cf43d273f0329e7c2ac9fae223b?s=96&#38;d=http%3A%2F%2Fs0.wp.com%2Fi%2Fmu.gif&#38;r=G" medium="image">
			<media:title type="html">somedave</media:title>
		</media:content>
	</item>
		<item>
		<title>Nested Grabs In GtkSharp</title>
		<link>http://somedave.wordpress.com/2010/04/15/nested-grabs-in-gtksharp/</link>
		<comments>http://somedave.wordpress.com/2010/04/15/nested-grabs-in-gtksharp/#comments</comments>
		<pubDate>Thu, 15 Apr 2010 12:55:14 +0000</pubDate>
		<dc:creator>somedave</dc:creator>
				<category><![CDATA[GtkSharp]]></category>
		<category><![CDATA[grab]]></category>
		<category><![CDATA[hasgrab]]></category>

		<guid isPermaLink="false">http://somedave.wordpress.com/?p=50</guid>
		<description><![CDATA[I ran across this while working on some complex GtkSharp grabbing behavior to mimic window focusing for a docking framework. Turns out there is a weird inconsistency in the way Gtk+ manages the grab stack. While the list of grabbed Widgets is indeed a stack, a flag on each Widget (Widget.HasGrab) is used to check if [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=somedave.wordpress.com&amp;blog=13050144&amp;post=50&amp;subd=somedave&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I ran across this while working on some complex GtkSharp grabbing behavior to mimic window focusing for a docking framework. Turns out there is a weird inconsistency in the way Gtk+ manages the grab stack. While the list of grabbed Widgets is indeed a stack, a flag on each Widget (Widget.HasGrab) is used to check if a Widget has the grab or not. The problem is that Grab.Add (which calls the Gtk+ method <a href="http://library.gnome.org/devel/gtk/stable/gtk-General.html#gtk-grab-add">gtk_grab_add</a>) never clears the flag for the currently grabbed Widget if you&#8217;re nesting grabs. That means that <em>every Widget in the grab stack</em> will have Widget.HasGrab set to true. If you try to add a Widget to the grab stack and it&#8217;s already in the stack (even if there are multiple other grabbed Widgets after it in the stack), it won&#8217;t get added. Because the flag is set though, it <em>will</em> get removed at the first place it was in the stack on a call to Grab.Remove (<a href="http://library.gnome.org/devel/gtk/stable/gtk-General.html#gtk-grab-remove">gtk_grab_remove</a>).</p>
<p>While it may not be a bug, this is certainly odd behavior. The solution (at least for me) was to write two small utility methods. SafeAdd first removes the Widget.HasGrab flag to ensure that the Widget always gets added to the grab stack, regardless of if it&#8217;s previously in it. SafeAdd should be paired with SafeRemove which checks the newly grabbed Widget after removing one to make sure it still has the Widget.HasGrab flag set. Note that it doesn&#8217;t clear the Widget.HasGrab flag for grabbed Widget getting replaced by a new grabbed Widget on the grab stack as you might expect. This maintains compatibility with all the other Gtk code that might be expecting Widgets anywhere in the stack to have the flag set.</p>
<p><pre class="brush: csharp;">

public static void SafeAdd(Widget widget)
{
 if (widget == null)
 {
  throw new ArgumentNullException(&quot;widget&quot;);
 }
 if (widget.Sensitive)
 {
  widget.ClearFlag(WidgetFlags.HasGrab);
  Grab.Add(widget);
 }
}

public static void SafeRemove(Widget widget)
{
 if (widget == null)
 {
  throw new ArgumentNullException(&quot;widget&quot;);
 }
 Grab.Remove(widget);
 Widget current = Grab.Current;
 if( current != null &amp;&amp; !current.HasGrab )
 {
  current.SetFlag(WidgetFlags.HasGrab);
 }
}

</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/somedave.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/somedave.wordpress.com/50/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/somedave.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/somedave.wordpress.com/50/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/somedave.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/somedave.wordpress.com/50/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/somedave.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/somedave.wordpress.com/50/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/somedave.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/somedave.wordpress.com/50/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/somedave.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/somedave.wordpress.com/50/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/somedave.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/somedave.wordpress.com/50/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=somedave.wordpress.com&amp;blog=13050144&amp;post=50&amp;subd=somedave&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://somedave.wordpress.com/2010/04/15/nested-grabs-in-gtksharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eca63cf43d273f0329e7c2ac9fae223b?s=96&#38;d=http%3A%2F%2Fs0.wp.com%2Fi%2Fmu.gif&#38;r=G" medium="image">
			<media:title type="html">somedave</media:title>
		</media:content>
	</item>
		<item>
		<title>Right-Click Context Menus In GtkSharp</title>
		<link>http://somedave.wordpress.com/2010/04/12/right-click-context-menus-in-gtksharp/</link>
		<comments>http://somedave.wordpress.com/2010/04/12/right-click-context-menus-in-gtksharp/#comments</comments>
		<pubDate>Mon, 12 Apr 2010 12:50:07 +0000</pubDate>
		<dc:creator>somedave</dc:creator>
				<category><![CDATA[GtkSharp]]></category>
		<category><![CDATA[ButtonPressEvent]]></category>
		<category><![CDATA[Context Menu]]></category>
		<category><![CDATA[ContextMenuHelper]]></category>
		<category><![CDATA[Menu]]></category>
		<category><![CDATA[Popup]]></category>
		<category><![CDATA[PopupMenu]]></category>

		<guid isPermaLink="false">http://somedave.wordpress.com/?p=25</guid>
		<description><![CDATA[To show a context menu in GtkSharp (or &#8220;popup&#8221; as they&#8217;re called in Gtk land), you would normally add an event handler for Widget.PopupMenu, create or use a Menu instance, and then call Menu.Popup. The only problem is that for many widgets, the right-click doesn&#8217;t trigger the Widget.PopupMenu event. This is fine for systems where there is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=somedave.wordpress.com&amp;blog=13050144&amp;post=25&amp;subd=somedave&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>To show a context menu in GtkSharp (or &#8220;popup&#8221; as they&#8217;re called in Gtk land), you would normally add an event handler for Widget.PopupMenu, create or use a Menu instance, and then call Menu.Popup. The only problem is that for many widgets, the right-click doesn&#8217;t trigger the Widget.PopupMenu event. This is fine for systems where there is no right mouse button or where a right-click isn&#8217;t the customary way of initiating context menus. However, on systems where there is a user expectation that the way to open a context menu is through a right-click (such as Windows), we need some way to trigger one.</p>
<p>The situation is complicated a little bit by the existing behavior of Widget.PopupMenu. According to the <a href="http://library.gnome.org/devel/gtk/unstable/gtk-migrating-checklist.html#checklist-popup-menu">Gtk manual</a>, &#8220;By default, the key binding mechanism is set to emit this signal when the Shift+F10 or Menu keys are pressed while a widget has the focus.&#8221; There is a recommendation in the manual that if a developer wants context menus on right-click they should handle the Widget.ButtonPressEvent, listen for the appropriate clicks, and launch the menu using the Menu.Popup method. This is all fine except that now you&#8217;ve got two things to listen to to get proper context menu handling: Widget.PopupMenu and Widget.ButtonPressEvent. It would be nice if there were just one event to handle that got raised anytime a context menu needed to be displayed.</p>
<p>The following class does just that. You can &#8220;attach&#8221; it to any Widget and it will listen for the Widget.PopupMenu event to work with the default context menu handling and the Widget.ButtonPressEvent to also work with right-clicks. When either of these occur, it will first propagate the event through to the underlying Widget (in case there are other things that are supposed to be triggered by whatever event caused the context menu) and then raise a ContextMenuHelper.ContextMenu event that you can handle and use to display the context menu regardless of what triggered it. This method should ensure proper event handling and ordering while reducing duplication of code by enabling a single event for context menu handling.</p>
<p><pre class="brush: csharp;">

using System;
using Gdk;
using GLib;
using Gtk;

namespace Somedave
{
 public class ContextMenuEventArgs : EventArgs
 {
  private Widget widget;
  public Widget Widget { get { return widget; } }

  private bool rightClick;
  public bool RightClick { get { return rightClick; } }

  public ContextMenuEventArgs(Widget widget, bool rightClick)
  {
   this.widget = widget;
   this.rightClick = rightClick;
  }
 }

 public class ContextMenuHelper
 {
  public event EventHandler&lt;ContextMenuEventArgs&gt; ContextMenu;

  public ContextMenuHelper()
  {}

  public ContextMenuHelper(Widget widget)
  {
   AttachToWidget(widget);
  }

  public ContextMenuHelper(Widget widget, EventHandler handler)
  {
   AttachToWidget(widget);
   ContextMenu += handler;
  }

  public void AttachToWidget(Widget widget)
  {
   widget.PopupMenu += Widget_PopupMenu;
   widget.ButtonPressEvent += Widget_ButtonPressEvent;
  }

  public void DetachFromWidget(Widget widget)
  {
   widget.PopupMenu -= Widget_PopupMenu;
   widget.ButtonPressEvent -= Widget_ButtonPressEvent;
  }

  [GLib.ConnectBefore]
  private void Widget_PopupMenu(object o, PopupMenuArgs args)
  {
   RaiseContextMenuEvent(args, (Widget)o, false);
  }

  [GLib.ConnectBefore]
  private void Widget_ButtonPressEvent(object o, ButtonPressEventArgs args)
  {
   if (args.Event.Button == 3 &amp;&amp; args.Event.Type == EventType.ButtonPress)
   {
    RaiseContextMenuEvent(args, (Widget)o, true);
   }
  }

  private bool propagating = false;   //Prevent reentry

  private void RaiseContextMenuEvent(SignalArgs signalArgs, Widget widget, bool rightClick)
  {
   if (!propagating)
   {
    //Propagate the event
    Event evnt = Gtk.Global.CurrentEvent;
    propagating = true;
    Gtk.Global.PropagateEvent(widget, evnt);
    propagating = false;
    signalArgs.RetVal = true;     //The widget already processed the event in the propagation

    //Raise the context menu event
    ContextMenuEventArgs args = new ContextMenuEventArgs(widget, rightClick);
    if (ContextMenu != null)
    {
     ContextMenu.Invoke(this, args);
    }
   }
  }
 }
}

</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/somedave.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/somedave.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/somedave.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/somedave.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/somedave.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/somedave.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/somedave.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/somedave.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/somedave.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/somedave.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/somedave.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/somedave.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/somedave.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/somedave.wordpress.com/25/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=somedave.wordpress.com&amp;blog=13050144&amp;post=25&amp;subd=somedave&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://somedave.wordpress.com/2010/04/12/right-click-context-menus-in-gtksharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eca63cf43d273f0329e7c2ac9fae223b?s=96&#38;d=http%3A%2F%2Fs0.wp.com%2Fi%2Fmu.gif&#38;r=G" medium="image">
			<media:title type="html">somedave</media:title>
		</media:content>
	</item>
		<item>
		<title>Exporting A TreeView To CSV</title>
		<link>http://somedave.wordpress.com/2010/04/09/exporting-a-treeview-to-csv/</link>
		<comments>http://somedave.wordpress.com/2010/04/09/exporting-a-treeview-to-csv/#comments</comments>
		<pubDate>Fri, 09 Apr 2010 15:52:55 +0000</pubDate>
		<dc:creator>somedave</dc:creator>
				<category><![CDATA[GtkSharp]]></category>
		<category><![CDATA[CellRenderer]]></category>
		<category><![CDATA[CSV]]></category>
		<category><![CDATA[TreeModel]]></category>
		<category><![CDATA[TreeView]]></category>
		<category><![CDATA[TreeViewColumn]]></category>

		<guid isPermaLink="false">http://somedave.wordpress.com/?p=9</guid>
		<description><![CDATA[I recently had to create some functionality to export a TreeView widget to a CSV file for further analysis. Since I tend to think about generic behavior, I decided to code up a method that would take any arbitrary TreeView and perform the export operation. Luckily, the TreeView widget and the attached TreeModel both contain a lot of functionality for [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=somedave.wordpress.com&amp;blog=13050144&amp;post=9&amp;subd=somedave&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I recently had to create some functionality to export a TreeView widget to a CSV file for further analysis. Since I tend to think about generic behavior, I decided to code up a method that would take any arbitrary TreeView and perform the export operation. Luckily, the TreeView widget and the attached TreeModel both contain a lot of functionality for accessing the data and it&#8217;s presentation. I decided that I wanted the exported CSV file to represent the perspective of the model as currently represented in the TreeView including column visibility and sort order. This led to the trickiest part of the process. Because a CellRenderer can be customized using cell data functions (such as those added by a call to TreeViewColumn.SetCellDataFunc), I had to pull the content to export from the CellRenderer as opposed to pulling directly from the TreeModel. Turns out there&#8217;s a method to take the TreeIter from a TreeModel and apply it to all the CellRenderers in a given TreeViewColumn. Since I really only care about textual content, I decided to only export those columns that contain CellRendererText renderers.</p>
<p>After working out the algorithm to fetch what needed to be exported I thought I was ready to roll. Turns out that the CSV pseudo-standard is pretty complex though (the RFC is <a href="http://www.rfc-editor.org/rfc/rfc4180.txt">here</a>), and I quickly got bogged down in writing all kinds of special cases for escaping, quoting, etc. Thankfully, someone else had already been down this road and I was able to find the excellent <a href="http://kbcsv.codeplex.com/">KBCsv</a> library which will write and read formatted CSV files. My only complaint was that it used another utility library purely for convenience in exception generation and null checking (I already use a ton of libraries in our application and I&#8217;d prefer not to add any unnecessarily). I replaced the calls to the utility library with the language equivalents, but that&#8217;s totally a personal preference.</p>
<p>Without further adieu, I present the TreeViewHelper.ExportToCsv and TreeViewHelper.ExportToCsvFile methods&#8230;</p>
<p><pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.IO;
using Gtk;
using Kent.Boogaart.KBCsv;

namespace Somedave
{
 public static class TreeViewHelper
 {
  public static bool ExportToCsv(TreeView treeView, Window parent)
  {
   FileChooserDialog fcd = new FileChooserDialog(&quot;Export File&quot;, parent, FileChooserAction.Save,
   &quot;Cancel&quot;, ResponseType.Cancel, &quot;Export&quot;, ResponseType.Accept);
   fcd.DoOverwriteConfirmation = true;
   FileFilter filter = new FileFilter { Name = &quot;CSV File&quot; };
   filter.AddPattern(&quot;*.csv&quot;);
   fcd.AddFilter(filter);
   if (fcd.Run() == (int)ResponseType.Accept)
   {
    string path = fcd.Filename;
    fcd.Destroy();
    return ExportToCsvFile(treeView, path);
   }
   fcd.Destroy();
   return false;
  }

  public static bool ExportToCsvFile(TreeView treeView, string path)
  {
   //Get the iterator
   TreeIter iter;
   if (treeView.Model.GetIterFirst(out iter))
   {
    //Create the stream
    using (StreamWriter streamWriter = new StreamWriter(path, false))
    {
     //Create the CSV writer
     using (CsvWriter csvWriter = new CsvWriter(streamWriter))
     {
      List&lt;string&gt; headers = new List&lt;string&gt;();
      List&lt;string&gt; values = new List&lt;string&gt;();

      //Traverse the tree
      do
      {
       values.Clear();
       foreach (TreeViewColumn column in treeView.Columns)
       {
        //Only output visible columns
        if (column.Visible)
        {
         //Loop through CellRenderers to make sure we have a CellRendererText
         string value = null;
         column.CellSetCellData(treeView.Model, iter, false, false);
         foreach (CellRenderer renderer in column.CellRenderers)
         {
          CellRendererText text = renderer as CellRendererText;
          if (text != null)
          {
           //Setting value indicates this column had a CellRendererText and should be included
           if (value == null)
           {
            value = String.Empty;
           }

           //Add the header if the first time through
           if (headers != null)
           {
            headers.Add(column.Title);
           }

           //Append to the value
           if (text.Text != null)
           {
            value += text.Text;
           }
          }
         }
         if (value != null)
         {
          values.Add(value);
         }
        }
       }

       //Output the header
       if (headers != null)
       {
        csvWriter.WriteHeaderRecord(headers.ToArray());
        headers = null;
       }

       //Output the values
       csvWriter.WriteDataRecord(values.ToArray());
      } while (treeView.Model.IterNext(ref iter));
     }
    }
    return true;
   }
   return false;
  }
 }
}
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/somedave.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/somedave.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/somedave.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/somedave.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/somedave.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/somedave.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/somedave.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/somedave.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/somedave.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/somedave.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/somedave.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/somedave.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/somedave.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/somedave.wordpress.com/9/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=somedave.wordpress.com&amp;blog=13050144&amp;post=9&amp;subd=somedave&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://somedave.wordpress.com/2010/04/09/exporting-a-treeview-to-csv/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eca63cf43d273f0329e7c2ac9fae223b?s=96&#38;d=http%3A%2F%2Fs0.wp.com%2Fi%2Fmu.gif&#38;r=G" medium="image">
			<media:title type="html">somedave</media:title>
		</media:content>
	</item>
		<item>
		<title>Introduction</title>
		<link>http://somedave.wordpress.com/2010/04/09/introduction/</link>
		<comments>http://somedave.wordpress.com/2010/04/09/introduction/#comments</comments>
		<pubDate>Fri, 09 Apr 2010 14:33:19 +0000</pubDate>
		<dc:creator>somedave</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>

		<guid isPermaLink="false">http://somedave.wordpress.com/?p=5</guid>
		<description><![CDATA[About Me My name is Dave Glick and I live in Northern Virginia with my wife, son, and dog. I&#8217;ve been developing software in one form or another for most of my life, starting with a programming class given by the dad of a friend when we were in third or fourth grade (unfortunately, my budding geek cred was [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=somedave.wordpress.com&amp;blog=13050144&amp;post=5&amp;subd=somedave&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h1>About Me</h1>
<p>My name is Dave Glick and I live in Northern Virginia with my wife, son, and dog. I&#8217;ve been developing software in one form or another for most of my life, starting with a programming class given by the dad of a friend when we were in third or fourth grade (unfortunately, my budding geek cred was unappreciated on the playground at recess). I can still remember sitting in their basement and pouring over sheet-fed printouts of BASIC code from my Guess The Number game trying to figure out why the computer always chose the same two numbers. I&#8217;m sure I learned a valuable lesson about properly seeding random number generators or something, but what I managed to take with me was that debugging code from a printout is a royal pain.</p>
<p>I started programming as a job in high school. After school was out I would drive over to a local ISP and code up web pages for their clients in between answering support calls. I learned most of what I know about Linux and Unix while grepping log files and rebooting servers trying to figure out why the old lady on the phone couldn&#8217;t get her thirty images of cats emailed to her entire extended family. Believe me, every horror story you&#8217;ve ever heard about technical support calls is probably true. In any case, I managed to do a good enough job that they took me off of the support desk to work on web projects exclusively. I stayed with them through college honing my skills and earning some spending money. At one point, they even got me an on-site contract with a hot events management startup in DC during the frenzy of the first dotcom boom. I remember there was an office there where the door was always closed. On the wall outside the door there was a little white board with lots of tick marks. When I noticed the number of tick marks were always varying, I asked what was going on. I was told that one of their best software guys was in the room and the ticks represented how many hours he had been in there without stepping out. When I came to the office one evening and there were seven or eight ticks on the whiteboard, I couldn&#8217;t help but wonder if the guy had expired out of frustration while looking at printouts of code. I never did see him the entire four months I worked there.</p>
<p>Once the dotcom bubble burst, web work was a lot more difficult to find and the ISP I worked for was having problems of its own competing against the rising popularity of cheap and available broadband. I ended up getting a job in one of the thousands of small defense contracting companies in the Northern Virginia area. I&#8217;ve stayed in that industry for almost ten years now while completing an undergraduate degree in Computer Graphics Design, a graduate degree in Software Engineering, a graduate certificate in Web-Based Software Engineering, and an MCSE certification. I currently work for <a href="http://www.dracorp.com">Data Research and Analysis Corporation</a> developing cross-platform networking and distributed modeling and simulation tools using .NET, Mono, GtkSharp, and XML.</p>
<h1>Why Blog?</h1>
<p>In doing the research for starting this blog I noticed almost every blog author I respect has a paragraph or two in their introductory posts about why they blog. For me the answer is simple, I do a lot of cool stuff and work out a lot of hard problems that people never see. Though my Google-fu is pretty strong, I&#8217;m always frustrated when I have a problem and can&#8217;t find any mentions of it. I always end up thinking &#8220;well, <em>someone</em> must have run into this before.&#8221; Hopefully I can spare others some of that frustration by publishing things I learn about and work out.</p>
<p>I also want to educate and inform about my chosen architecture stack. I&#8217;ve been doing development with .NET, Mono, GtkSharp, and XML for a while now and have come to appreciate the simplicity and power that these technologies provide. Unfortunately, the area of cross-platform and Microsoft-independant .NET development doesn&#8217;t get as much attention as I think it should. I&#8217;m hopeful that I can add my voice to those already out there and help continue to make people aware that there is .NET life beyond Microsoft (though I don&#8217;t have anything against Microsoft, and I like a lot of what they do).</p>
<h1>Okay, But Seriously, Why Do You Really Blog?</h1>
<p>I can&#8217;t deny it&#8217;s also good for a little ego boost :)</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/somedave.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/somedave.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/somedave.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/somedave.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/somedave.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/somedave.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/somedave.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/somedave.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/somedave.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/somedave.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/somedave.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/somedave.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/somedave.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/somedave.wordpress.com/5/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=somedave.wordpress.com&amp;blog=13050144&amp;post=5&amp;subd=somedave&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://somedave.wordpress.com/2010/04/09/introduction/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eca63cf43d273f0329e7c2ac9fae223b?s=96&#38;d=http%3A%2F%2Fs0.wp.com%2Fi%2Fmu.gif&#38;r=G" medium="image">
			<media:title type="html">somedave</media:title>
		</media:content>
	</item>
	</channel>
</rss>
