<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Guardian's Home</title>
	
	<link>http://www.nablasoft.com/guardian</link>
	<description>.NET, Software Developing, Mammoths and Various Life Things...</description>
	<lastBuildDate>Fri, 06 Nov 2009 12:33:53 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<image><url>http://www.feedburner.com/fb/images/pub/fb_pwrd.gif</url></image><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/GuardiansHome" type="application/rss+xml" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
		<title>WSS / SharePoint: adding filtering capabilities to the CustomListViewWebPart – Filter Chain Fixed</title>
		<link>http://feedproxy.google.com/~r/GuardiansHome/~3/IknWHe6Rv-o/</link>
		<comments>http://www.nablasoft.com/guardian/index.php/2009/11/06/wss-sharepoint-adding-filtering-capabilities-customlistviewwebpart-filter-chain-fixed/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 12:24:00 +0000</pubDate>
		<dc:creator>Guardian</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[SharePoint/WSS]]></category>
		<category><![CDATA[SharePoint;WSS;Custom;Current User;Filter;ListViewWebPart;CustomListViewWebPart]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/guardian/index.php/2009/11/06/wss-sharepoint-adding-filtering-capabilities-customlistviewwebpart-filter-chain-fixed/</guid>
		<description><![CDATA[I had a lot of good feedbacks on that SharePoint filtering articles series, the guys that wrote me spotted on a nasty bug on how I was building the chain of filters in CAML.
In my code I did something like: &#60;or&#62;&#60;eq&#62;&#8230;&#60;/eq&#62;&#60;eq&#62;&#8230;&#60;/eq&#62;&#60;eq&#62;&#8230;&#60;/eq&#62;&#60;/or&#62; which is WRONG!
Due to the lack of a good testing (I worked with only [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F11%2F06%2Fwss-sharepoint-adding-filtering-capabilities-customlistviewwebpart-filter-chain-fixed%2F"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F11%2F06%2Fwss-sharepoint-adding-filtering-capabilities-customlistviewwebpart-filter-chain-fixed%2F" height="61" width="51" /></a></div><p>I had a lot of good feedbacks on that SharePoint filtering articles series, the guys that wrote me spotted on a nasty bug on how I was building the chain of filters in CAML.</p>
<p>In my code I did something like: &lt;or&gt;&lt;eq&gt;&#8230;&lt;/eq&gt;&lt;eq&gt;&#8230;&lt;/eq&gt;&lt;eq&gt;&#8230;&lt;/eq&gt;&lt;/or&gt; which is WRONG!</p>
<p>Due to the lack of a good testing (I worked with only two values I didn’t get it at start).</p>
<p>The correct chain should be: &lt;or&gt;&lt;or&gt;&lt;eq&gt;&#8230;&lt;/eq&gt;&lt;eq&gt;&#8230;&lt;/eq&gt;&lt;/or&gt;&lt;eq&gt;&#8230;&lt;/eq&gt;&lt;/or&gt;.</p>
<p>Today I found 1 hour to fix the problem which was present in two pieces of the code: once when building the single filters and once when concatenating the multiple filters to obtain the final query.</p>
<p>Here’s the code that contains the bug fixes. As a note to all my readers: again I did not had time to test it deeply (I checked the algorithm to generate the query, but I didn’t tested it against a SharePoint database due to the lack of time), so check it before using it in a production environment.</p>
<div class="csharpcode-wrapper">
<div class="csharpcode">
<pre class="alt">[Guid(<span class="str">"b7ea3f7d-b260-4ce8-9fd0-3af5aee8e0d6"</span>)]</pre>
<pre class="alteven"><span class="kwrd">public</span> <span class="kwrd">class</span> CustomListViewWebPart : System.Web.UI.WebControls.WebParts.WebPart</pre>
<pre class="alt">{</pre>
<pre class="alteven">   <span class="preproc">#region</span> Properties</pre>
<pre class="alt"></pre>
<pre class="alteven">   <span class="kwrd">private</span> <span class="kwrd">readonly</span> ILogger _logger = LoggerFactory.GetLogger();</pre>
<pre class="alt"></pre>
<pre class="alteven">   <span class="rem">/// &lt;summary&gt;</span></pre>
<pre class="alt">   <span class="rem">/// The List we are displaying</span></pre>
<pre class="alteven">   <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre class="alt">   [Personalizable(<span class="kwrd">true</span>),</pre>
<pre class="alteven">   WebBrowsable,</pre>
<pre class="alt">   WebPartStorage(Storage.Shared),</pre>
<pre class="alteven">   SPWebCategoryName(<span class="str">"Settings"</span>),</pre>
<pre class="alt">   WebDisplayName(<span class="str">"Source List Name"</span>),</pre>
<pre class="alteven">   WebDescription(<span class="str">"Pass the name of the List to show"</span>)]</pre>
<pre class="alt">   <span class="kwrd">public</span> <span class="kwrd">string</span> SourceList { get; set; }</pre>
<pre class="alteven"></pre>
<pre class="alt">   <span class="rem">/// &lt;summary&gt;</span></pre>
<pre class="alteven">   <span class="rem">/// The Default View of the list</span></pre>
<pre class="alt">   <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre class="alteven">   [Personalizable(<span class="kwrd">true</span>),</pre>
<pre class="alt">   WebBrowsable,</pre>
<pre class="alteven">   WebPartStorage(Storage.Shared),</pre>
<pre class="alt">   SPWebCategoryName(<span class="str">"Settings"</span>),</pre>
<pre class="alteven">   WebDisplayName(<span class="str">"View"</span>),</pre>
<pre class="alt">   WebDescription(<span class="str">"Pass the name of the View that you want to apply to the List"</span>)]</pre>
<pre class="alteven">   <span class="kwrd">public</span> <span class="kwrd">string</span> ViewOfSourceList { get; set; }</pre>
<pre class="alt"></pre>
<pre class="alteven">   <span class="rem">/// &lt;summary&gt;</span></pre>
<pre class="alt">   <span class="rem">/// a CAML query to filter the object</span></pre>
<pre class="alteven">   <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre class="alt">   <span class="rem">/// &lt;remarks&gt;</span></pre>
<pre class="alteven">   <span class="rem">/// in a later revision we will use one or more filter providers to set this</span></pre>
<pre class="alt">   <span class="rem">/// &lt;/remarks&gt;</span></pre>
<pre class="alteven">   [Personalizable(<span class="kwrd">true</span>),</pre>
<pre class="alt">   WebBrowsable,</pre>
<pre class="alteven">   WebPartStorage(Storage.Shared),</pre>
<pre class="alt">   SPWebCategoryName(<span class="str">"Settings"</span>),</pre>
<pre class="alteven">   WebDisplayName(<span class="str">"Query"</span>),</pre>
<pre class="alt">   WebDescription(<span class="str">"Pass the Filter Query, if you wire up some Filter WebParts they have priority over the query and this will be ignored"</span>)]</pre>
<pre class="alteven">   <span class="kwrd">public</span> <span class="kwrd">string</span> FilterQuery { get; set; }</pre>
<pre class="alt"></pre>
<pre class="alteven">   <span class="kwrd">private</span> <span class="kwrd">readonly</span> List&lt;IFilterValues&gt; _filterProviders = <span class="kwrd">new</span> List&lt;IFilterValues&gt;();</pre>
<pre class="alt"></pre>
<pre class="alteven">   <span class="kwrd">private</span> List&lt;IFilterValues&gt; FilterProviders</pre>
<pre class="alt">   {</pre>
<pre class="alteven">      get { <span class="kwrd">return</span> _filterProviders; }</pre>
<pre class="alt">   }</pre>
<pre class="alteven"></pre>
<pre class="alt">   <span class="preproc">#endregion</span></pre>
<pre class="alteven"></pre>
<pre class="alt">   <span class="kwrd">public</span> CustomListViewWebPart()</pre>
<pre class="alteven">   {</pre>
<pre class="alt">      ExportMode = WebPartExportMode.All;</pre>
<pre class="alteven">   }</pre>
<pre class="alt"></pre>
<pre class="alteven">   <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> CreateChildControls()</pre>
<pre class="alt">   {</pre>
<pre class="alteven">      <span class="kwrd">base</span>.CreateChildControls();</pre>
<pre class="alt"></pre>
<pre class="alteven">      SPWeb web = SPContext.Current.Web;</pre>
<pre class="alt">      {</pre>
<pre class="alteven">         <span class="kwrd">try</span></pre>
<pre class="alt">         {</pre>
<pre class="alteven">            SPList list = web.Lists[SourceList];</pre>
<pre class="alt"></pre>
<pre class="alteven">            <span class="rem">// create the toolbar, actually we cannot hide it, we'll need to extend the webpart and those options</span></pre>
<pre class="alt">            ViewToolBar toolbar = <span class="kwrd">new</span> ViewToolBar();</pre>
<pre class="alteven">            SPContext context = SPContext.GetContext(Context, list.Views[ViewOfSourceList].ID, list.ID, SPContext.Current.Web);</pre>
<pre class="alt">            toolbar.RenderContext = context;</pre>
<pre class="alteven">            Controls.Add(toolbar);</pre>
<pre class="alt"></pre>
<pre class="alteven">            <span class="rem">// get a reference to the view we want to use (or use the default view if nothing is specified)</span></pre>
<pre class="alt">            SPView webPartView;</pre>
<pre class="alteven">            <span class="kwrd">if</span> (!<span class="kwrd">string</span>.IsNullOrEmpty(ViewOfSourceList))</pre>
<pre class="alt">               webPartView = web.Lists[SourceList].Views[ViewOfSourceList];</pre>
<pre class="alteven">            <span class="kwrd">else</span></pre>
<pre class="alt">               webPartView = web.Lists[SourceList].DefaultView;</pre>
<pre class="alteven"></pre>
<pre class="alt">            <span class="rem">// create a new view based on the original one and attach the filter query to it</span></pre>
<pre class="alteven">            <span class="rem">// in this way we do not need to modify/update the original element and</span></pre>
<pre class="alt">            <span class="rem">// even a user without updating permissions can use this webpart</span></pre>
<pre class="alteven">            XmlDocument domDoc = <span class="kwrd">new</span> XmlDocument();</pre>
<pre class="alt">            domDoc.LoadXml(webPartView.SchemaXml);</pre>
<pre class="alteven">            SPView view = <span class="kwrd">new</span> SPView(list, domDoc);</pre>
<pre class="alt">            _logger.AppendLogFormat(<span class="str">"View ID: {0}"</span>, view.ID);</pre>
<pre class="alteven"></pre>
<pre class="alt">            <span class="rem">// build the filter</span></pre>
<pre class="alteven">            ApplyFilters(list, view);</pre>
<pre class="alt"></pre>
<pre class="alteven">            <span class="rem">// render the view</span></pre>
<pre class="alt">            Literal lbl = <span class="kwrd">new</span> Literal();</pre>
<pre class="alteven">            lbl.Text = view.RenderAsHtml();</pre>
<pre class="alt">            Controls.Add(lbl);</pre>
<pre class="alteven"></pre>
<pre class="alt">            <span class="rem">// add the logging messages if there are any</span></pre>
<pre class="alteven">            <span class="kwrd">string</span> lg = _logger.ToString();</pre>
<pre class="alt">            <span class="kwrd">if</span> (!<span class="kwrd">string</span>.IsNullOrEmpty(lg))</pre>
<pre class="alteven">            {</pre>
<pre class="alt">               Literal logLbl = <span class="kwrd">new</span> Literal();</pre>
<pre class="alteven">               logLbl.Text = <span class="str">"&lt;br/&gt;"</span> + lg;</pre>
<pre class="alt">               Controls.Add(logLbl);</pre>
<pre class="alteven">            }</pre>
<pre class="alt">         }</pre>
<pre class="alteven">         <span class="kwrd">catch</span> (Exception ex)</pre>
<pre class="alt">         {</pre>
<pre class="alteven">            <span class="rem">// todo: have a better way to report errors!</span></pre>
<pre class="alt">            Label lbl = <span class="kwrd">new</span> Label();</pre>
<pre class="alteven">            lbl.Text = _logger.ToString() + <span class="str">"&lt;br /&gt;"</span>;</pre>
<pre class="alt">            lbl.Text += <span class="str">"Error occured: "</span>;</pre>
<pre class="alteven">            lbl.Text += ex.Message + <span class="str">"&lt;br /&gt;"</span> + ex.StackTrace;</pre>
<pre class="alt">            Controls.Add(lbl);</pre>
<pre class="alteven">         }</pre>
<pre class="alt">      }</pre>
<pre class="alteven">   }</pre>
<pre class="alt"></pre>
<pre class="alteven">   <span class="rem">/// &lt;summary&gt;</span></pre>
<pre class="alt">   <span class="rem">/// how to concatenate different filters</span></pre>
<pre class="alteven">   <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre class="alt">   <span class="kwrd">const</span> <span class="kwrd">string</span> FiltersConcatenation = <span class="str">"And"</span>;</pre>
<pre class="alteven">   <span class="rem">/// &lt;summary&gt;</span></pre>
<pre class="alt">   <span class="rem">/// how to concatenate multiple values in the same filter</span></pre>
<pre class="alteven">   <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre class="alt">   <span class="kwrd">const</span> <span class="kwrd">string</span> FiltersMultipleValuesConcatenation = <span class="str">"Or"</span>;</pre>
<pre class="alteven"></pre>
<pre class="alt">   <span class="kwrd">private</span> <span class="kwrd">void</span> ApplyFilters(SPList list, SPView view)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">      _logger.AppendLogFormat(<span class="str">"Filters numbers: {0}"</span>, FilterProviders.Count);</pre>
<pre class="alteven">      <span class="kwrd">if</span> (FilterProviders.Count == 0)</pre>
<pre class="alt">         view.Query = FilterQuery;</pre>
<pre class="alteven">      <span class="kwrd">else</span></pre>
<pre class="alt">      {</pre>
<pre class="alteven">         <span class="kwrd">if</span> (FilterProviders.Count &gt; 0)</pre>
<pre class="alt">         {</pre>
<pre class="alteven">            <span class="rem">// build the filter according to the passed data</span></pre>
<pre class="alt"></pre>
<pre class="alteven">            <span class="rem">// holds each internal filter</span></pre>
<pre class="alt">            List&lt;<span class="kwrd">string</span>&gt; filters = BuildFiltersList(list);</pre>
<pre class="alteven"></pre>
<pre class="alt">            <span class="rem">// assign the list of filters, concatenate them if more than one</span></pre>
<pre class="alteven">            <span class="kwrd">if</span> (filters.Count &gt; 0)</pre>
<pre class="alt">            {</pre>
<pre class="alteven">               StringBuilder sb = <span class="kwrd">new</span> StringBuilder();</pre>
<pre class="alt">               sb.Append(<span class="str">"&lt;Where&gt;"</span>);</pre>
<pre class="alteven"></pre>
<pre class="alt">               <span class="kwrd">if</span> (filters.Count == 1)</pre>
<pre class="alteven">                  sb.Append(filters[0]);</pre>
<pre class="alt">               <span class="kwrd">else</span></pre>
<pre class="alteven">               {</pre>
<pre class="alt">                  <span class="rem">// we have more than 1 filter and we need to concat</span></pre>
<pre class="alteven">                  <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; filters.Count; i++)</pre>
<pre class="alt">                  {</pre>
<pre class="alteven">                     <span class="kwrd">if</span> (i != 1)</pre>
<pre class="alt">                        sb.Insert(0, String.Format(<span class="str">"&lt;{0}&gt;"</span>, FiltersConcatenation));</pre>
<pre class="alteven">                     sb.Append(filters[i]);</pre>
<pre class="alt">                     <span class="kwrd">if</span> (i &gt; 0)</pre>
<pre class="alteven">                        sb.AppendFormat(<span class="str">"&lt;/{0}&gt;"</span>, FiltersConcatenation);</pre>
<pre class="alt">                  }</pre>
<pre class="alteven">               }</pre>
<pre class="alt"></pre>
<pre class="alteven">               sb.Append(<span class="str">"&lt;/Where&gt;"</span>);</pre>
<pre class="alt"></pre>
<pre class="alteven">               <span class="kwrd">string</span> query = sb.ToString();</pre>
<pre class="alt">               view.Query = query;</pre>
<pre class="alteven">               _logger.AppendLog(<span class="str">"query: {0}"</span> + query);</pre>
<pre class="alt">            }</pre>
<pre class="alteven">            _logger.AppendLog(<span class="str">"query: -"</span>);</pre>
<pre class="alt">         }</pre>
<pre class="alteven">      }</pre>
<pre class="alt">   }</pre>
<pre class="alteven"></pre>
<pre class="alt">   <span class="rem">/// &lt;summary&gt;</span></pre>
<pre class="alteven">   <span class="rem">/// build the filter list to apply to the view</span></pre>
<pre class="alt">   <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre class="alteven">   <span class="rem">/// &lt;param name="list"&gt;&lt;/param&gt;</span></pre>
<pre class="alt">   <span class="rem">/// &lt;returns&gt;&lt;/returns&gt;</span></pre>
<pre class="alteven">   <span class="kwrd">private</span> List&lt;<span class="kwrd">string</span>&gt; BuildFiltersList(SPList list)</pre>
<pre class="alt">   {</pre>
<pre class="alteven">      List&lt;<span class="kwrd">string</span>&gt; filters = <span class="kwrd">new</span> List&lt;<span class="kwrd">string</span>&gt;();</pre>
<pre class="alt"></pre>
<pre class="alteven">      ReadOnlyCollection&lt;<span class="kwrd">string</span>&gt; paramValues;</pre>
<pre class="alt">      <span class="kwrd">foreach</span> (IFilterValues f <span class="kwrd">in</span> FilterProviders)</pre>
<pre class="alteven">      {</pre>
<pre class="alt">         paramValues = f.ParameterValues;</pre>
<pre class="alteven"></pre>
<pre class="alt">         _logger.AppendLogFormat(<span class="str">"Filter: {0}"</span>, f.ParameterName);</pre>
<pre class="alteven">         _logger.AppendLogFormat(<span class="str">"Filter Params: {0}"</span>, (paramValues != <span class="kwrd">null</span>));</pre>
<pre class="alt"></pre>
<pre class="alteven">         <span class="kwrd">if</span> ((paramValues != <span class="kwrd">null</span>) &amp;&amp; (paramValues.Count &gt; 0))</pre>
<pre class="alt">         {</pre>
<pre class="alteven">            StringBuilder innerSb = <span class="kwrd">new</span> StringBuilder();</pre>
<pre class="alt">            _logger.AppendLogFormat(<span class="str">"Found filter: {0}  values n: {1}"</span>, f.ParameterName, paramValues.Count);</pre>
<pre class="alteven"></pre>
<pre class="alt">            <span class="rem">// check for single parameter value</span></pre>
<pre class="alteven">            <span class="kwrd">if</span> (paramValues.Count == 1)</pre>
<pre class="alt">               innerSb.AppendFormat(<span class="str">"&lt;Eq&gt;&lt;FieldRef Name='{0}' /&gt;&lt;Value Type='{1}'&gt;{2}&lt;/Value&gt;&lt;/Eq&gt;"</span>,</pre>
<pre class="alteven">                                    list.Fields[f.ParameterName].InternalName,</pre>
<pre class="alt">                                    list.Fields[f.ParameterName].TypeAsString,</pre>
<pre class="alteven">                                    paramValues[0]);</pre>
<pre class="alt">            <span class="kwrd">else</span></pre>
<pre class="alteven">            {</pre>
<pre class="alt">               <span class="rem">// multiple values we need to concat in the right way for a CAML query</span></pre>
<pre class="alteven">               <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; paramValues.Count; i++)</pre>
<pre class="alt">               {</pre>
<pre class="alteven">                  <span class="kwrd">if</span> (i != 1)</pre>
<pre class="alt">                     innerSb.Insert(0, String.Format(<span class="str">"&lt;{0}&gt;"</span>, FiltersMultipleValuesConcatenation));</pre>
<pre class="alteven">                  innerSb.AppendFormat(<span class="str">"&lt;Eq&gt;&lt;FieldRef Name='{0}' /&gt;&lt;Value Type='{1}'&gt;{2}&lt;/Value&gt;&lt;/Eq&gt;"</span>,</pre>
<pre class="alt">                                       list.Fields[f.ParameterName].InternalName,</pre>
<pre class="alteven">                                       list.Fields[f.ParameterName].TypeAsString,</pre>
<pre class="alt">                                       paramValues[i]);</pre>
<pre class="alteven">                  <span class="kwrd">if</span> (i &gt; 0)</pre>
<pre class="alt">                     innerSb.AppendFormat(<span class="str">"&lt;/{0}&gt;"</span>, FiltersMultipleValuesConcatenation);</pre>
<pre class="alteven">               }</pre>
<pre class="alt">            }</pre>
<pre class="alteven"></pre>
<pre class="alt">            filters.Add(innerSb.ToString());</pre>
<pre class="alteven">         }</pre>
<pre class="alt">      }</pre>
<pre class="alteven">      <span class="kwrd">return</span> filters;</pre>
<pre class="alt">   }</pre>
<pre class="alteven"></pre>
<pre class="alt">   <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Render(HtmlTextWriter writer)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">      EnsureChildControls();</pre>
<pre class="alteven">      <span class="kwrd">base</span>.Render(writer);</pre>
<pre class="alt">   }</pre>
<pre class="alteven"></pre>
<pre class="alt">   [ConnectionConsumer(<span class="str">"Filters"</span>, <span class="str">"FiltersForConsumer"</span>, AllowsMultipleConnections = <span class="kwrd">true</span>)]</pre>
<pre class="alteven">   <span class="kwrd">public</span> <span class="kwrd">void</span> SetFilter(IFilterValues filterValues)</pre>
<pre class="alt">   {</pre>
<pre class="alteven">      <span class="kwrd">if</span> (filterValues != <span class="kwrd">null</span>)</pre>
<pre class="alt">      {</pre>
<pre class="alteven">         <span class="rem">// EnsureChildControls();</span></pre>
<pre class="alt">         _logger.AppendLog(<span class="str">"Assigning filters"</span>);</pre>
<pre class="alteven">         _logger.AppendLogFormat(<span class="str">"Assigning filter: {0}"</span>, filterValues.ParameterName);</pre>
<pre class="alt">         _logger.AppendLogFormat(<span class="str">"Assigning filter: {0}"</span>, (filterValues.ParameterValues != <span class="kwrd">null</span>));</pre>
<pre class="alteven"></pre>
<pre class="alt">         filterValues.SetConsumerParameters(GetParameters());</pre>
<pre class="alteven"></pre>
<pre class="alt">         FilterProviders.Add(filterValues);</pre>
<pre class="alteven"></pre>
<pre class="alt">         _logger.AppendLog(<span class="str">"Filters Assigned"</span>);</pre>
<pre class="alteven">      }</pre>
<pre class="alt">   }</pre>
<pre class="alteven"></pre>
<pre class="alt">   <span class="rem">/// &lt;summary&gt;</span></pre>
<pre class="alteven">   <span class="rem">/// Build a parameter List to allow the filtering of the List on the values provided</span></pre>
<pre class="alt">   <span class="rem">/// by a series of filters.</span></pre>
<pre class="alteven">   <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre class="alt">   <span class="rem">/// &lt;returns&gt;&lt;/returns&gt;</span></pre>
<pre class="alteven">   <span class="kwrd">private</span> ReadOnlyCollection&lt;ConsumerParameter&gt; GetParameters()</pre>
<pre class="alt">   {</pre>
<pre class="alteven">      List&lt;ConsumerParameter&gt; parameters = <span class="kwrd">new</span> List&lt;ConsumerParameter&gt;();</pre>
<pre class="alt">      <span class="rem">// we get all the fields of the list we are displaying</span></pre>
<pre class="alteven">      SPList list = SPContext.Current.Web.Lists[SourceList];</pre>
<pre class="alt">      <span class="rem">// we build a parameter for any field of the list (similar to the standard ListViewWebPart)</span></pre>
<pre class="alteven">      <span class="kwrd">foreach</span> (SPField item <span class="kwrd">in</span> list.Fields)</pre>
<pre class="alt">         parameters.Add(<span class="kwrd">new</span> ConsumerParameter(item.Title,</pre>
<pre class="alteven">             ConsumerParameterCapabilities.SupportsMultipleValues |</pre>
<pre class="alt">             ConsumerParameterCapabilities.SupportsAllValue |</pre>
<pre class="alteven">             ConsumerParameterCapabilities.SupportsEmptyValue |</pre>
<pre class="alt">             ConsumerParameterCapabilities.SupportsSingleValue));</pre>
<pre class="alteven"></pre>
<pre class="alt">      <span class="kwrd">return</span> <span class="kwrd">new</span> ReadOnlyCollection&lt;ConsumerParameter&gt;(parameters);</pre>
<pre class="alteven">   }</pre>
<pre class="alt"></pre>
<pre class="alteven">}</pre>
</div>
</div>
<p>Any further suggestion, modification and fixes are welcome <img src='http://www.nablasoft.com/guardian/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/GuardiansHome/~4/IknWHe6Rv-o" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.nablasoft.com/guardian/index.php/2009/11/06/wss-sharepoint-adding-filtering-capabilities-customlistviewwebpart-filter-chain-fixed/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.nablasoft.com/guardian/index.php/2009/11/06/wss-sharepoint-adding-filtering-capabilities-customlistviewwebpart-filter-chain-fixed/</feedburner:origLink></item>
		<item>
		<title>Create an EML file the easy way</title>
		<link>http://feedproxy.google.com/~r/GuardiansHome/~3/8SHVLxTIImw/</link>
		<comments>http://www.nablasoft.com/guardian/index.php/2009/11/05/create-an-eml-file-the-easy-way/#comments</comments>
		<pubDate>Thu, 05 Nov 2009 11:30:00 +0000</pubDate>
		<dc:creator>Guardian</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[create]]></category>
		<category><![CDATA[eml]]></category>
		<category><![CDATA[programmatically]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/guardian/index.php/2009/11/05/create-an-eml-file-the-easy-way/</guid>
		<description><![CDATA[Many email readers (like Windows Mail, Outlook, Thunderbird&#8230;) use this format to store emails in files; I needed an easy way to create those files to send emails using the default email program the client has configured on his system.
Looking the the framework class documentation I’ve found that the SmtpClient class, specifying its DeliveryMethod to [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F11%2F05%2Fcreate-an-eml-file-the-easy-way%2F"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F11%2F05%2Fcreate-an-eml-file-the-easy-way%2F" height="61" width="51" /></a></div><p>Many email readers (like Windows Mail, Outlook, Thunderbird&#8230;) use this format to store emails in files; I needed an easy way to create those files to send emails using the default email program the client has configured on his system.</p>
<p>Looking the the framework class documentation I’ve found that the <em>SmtpClient</em> class, specifying its <em>DeliveryMethod</em> to <em>SmtpDeliveryMethod.SpecifiedPickupDirectory</em> and <em>PickupDirectoryLocation</em> to the destination folder you want the files to be placed, can generate those files for you, without the need of any external library.</p>
<p>The code was quite straightforward:</p>
<div class="csharpcode-wrapper">
<div class="csharpcode">
<pre class="alt"><span class="rem">/// &lt;summary&gt;</span></pre>
<pre class="alteven"><span class="rem">/// Creates an eml file to be delivered with the default mail client</span></pre>
<pre class="alt"><span class="rem">/// &lt;/summary&gt;</span></pre>
<pre class="alteven"><span class="rem">/// &lt;param name=&quot;from&quot;&gt;address that sends the email&lt;/param&gt;</span></pre>
<pre class="alt"><span class="rem">/// &lt;param name=&quot;to&quot;&gt;address to which send the email&lt;/param&gt;</span></pre>
<pre class="alteven"><span class="rem">/// &lt;param name=&quot;subject&quot;&gt;subject&lt;/param&gt;</span></pre>
<pre class="alt"><span class="rem">/// &lt;param name=&quot;body&quot;&gt;body&lt;/param&gt;</span></pre>
<pre class="alteven"><span class="rem">/// &lt;param name=&quot;attachments&quot;&gt;list of attachments&lt;/param&gt;</span></pre>
<pre class="alt"><span class="rem">/// &lt;param name=&quot;destFolder&quot;&gt;destination folder to store the file&lt;/param&gt;</span></pre>
<pre class="alteven"><span class="rem">/// &lt;returns&gt;The complete path of the newely generated EML file&lt;/returns&gt;</span></pre>
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">string</span> CreateEml(<span class="kwrd">string</span> from,</pre>
<pre class="alteven">                               <span class="kwrd">string</span> to,</pre>
<pre class="alt">                               <span class="kwrd">string</span> subject,</pre>
<pre class="alteven">                               <span class="kwrd">string</span> body,</pre>
<pre class="alt">                               IEnumerable&lt;Attachment&gt; attachments,</pre>
<pre class="alteven">                               <span class="kwrd">string</span> destFolder)</pre>
<pre class="alt">{</pre>
<pre class="alteven">   <span class="kwrd">using</span> (MailMessage mail = <span class="kwrd">new</span> MailMessage())</pre>
<pre class="alt">   {</pre>
<pre class="alteven">      mail.From = <span class="kwrd">new</span> MailAddress(from);</pre>
<pre class="alt">      mail.To.Add(to);</pre>
<pre class="alteven">      mail.Subject = subject;</pre>
<pre class="alt">      mail.Body = body;</pre>
<pre class="alteven">      <span class="kwrd">if</span> (attachments != <span class="kwrd">null</span>)</pre>
<pre class="alt">         <span class="kwrd">foreach</span> (var attachment <span class="kwrd">in</span> attachments)</pre>
<pre class="alteven">            mail.Attachments.Add(attachment);</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">      SmtpClient smtpClient = <span class="kwrd">new</span> SmtpClient</pre>
<pre class="alt">                                 {</pre>
<pre class="alteven">                                    PickupDirectoryLocation = destFolder,</pre>
<pre class="alt">                                    DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory</pre>
<pre class="alteven">                                 };</pre>
<pre class="alt">      smtpClient.Send(mail);</pre>
<pre class="alteven">   }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">   DirectoryInfo dir = <span class="kwrd">new</span> DirectoryInfo(destFolder);</pre>
<pre class="alt">   FileInfo file = dir.GetFiles(<span class="str">&quot;*.eml&quot;</span>, SearchOption.TopDirectoryOnly).OrderByDescending(m =&gt; m.CreationTimeUtc).First();</pre>
<pre class="alteven">   <span class="kwrd">return</span> file.FullName;</pre>
<pre class="alt">}</pre>
</p></div>
</div>
<p>The function returns the full path of the newly created eml file, you can use it in a System.Diagnostics.Process.Start() call to open the default email client of the user. </p>
<img src="http://feeds.feedburner.com/~r/GuardiansHome/~4/8SHVLxTIImw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.nablasoft.com/guardian/index.php/2009/11/05/create-an-eml-file-the-easy-way/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.nablasoft.com/guardian/index.php/2009/11/05/create-an-eml-file-the-easy-way/</feedburner:origLink></item>
		<item>
		<title>How to migrate a Windows XP installation from an IDE to a SATA hard drive</title>
		<link>http://feedproxy.google.com/~r/GuardiansHome/~3/eDUjgBxYWgo/</link>
		<comments>http://www.nablasoft.com/guardian/index.php/2009/11/03/how-to-migrate-a-windows-xp-installation-from-an-ide-to-a-sata-hard-drive/#comments</comments>
		<pubDate>Tue, 03 Nov 2009 12:47:00 +0000</pubDate>
		<dc:creator>Guardian</dc:creator>
				<category><![CDATA[Freetime talking]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[disk copy]]></category>
		<category><![CDATA[IDE]]></category>
		<category><![CDATA[Migrate installation]]></category>
		<category><![CDATA[Migration]]></category>
		<category><![CDATA[SATA]]></category>
		<category><![CDATA[Windows XP]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/guardian/index.php/2009/11/03/how-to-migrate-a-windows-xp-installation-from-an-ide-to-a-sata-hard-drive/</guid>
		<description><![CDATA[These days I made myself and my bro a ‘Christmas Gift’ and I bought a couple of 10k rpm hard drives to give our systems some speed up. In my childlike mind I thought: migrate the system will be easy..just clone the HD data to the new one, maybe perform a quick system repair to [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F11%2F03%2Fhow-to-migrate-a-windows-xp-installation-from-an-ide-to-a-sata-hard-drive%2F"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F11%2F03%2Fhow-to-migrate-a-windows-xp-installation-from-an-ide-to-a-sata-hard-drive%2F" height="61" width="51" /></a></div><p>These days I made myself and my bro a ‘Christmas Gift’ and I bought a couple of 10k rpm hard drives to give our systems some speed up. In my childlike mind I thought: migrate the system will be easy..just clone the HD data to the new one, maybe perform a quick system repair to adjust and driver assignment letter issue that can arise and we are cool.</p>
<p>Well&#8230;it was a long journey to figure out how to resolve all the problems we had, today we start with the Windows XP migration, in a next article I’ll talk about the Vista migration.</p>
<p>To successfully migrate a Windows XP installation you need 3 different tools, I tend to use all free stuff if I can:</p>
<ul>
<li>A disk cloning tool: EASEUS has a nice and free solution that worked well for me: <a href="http://www.easeus.com/disk-copy/" target="_blank">EASEUS DISK COPY</a> </li>
<li>A partition manager tool: again EASEUS to the rescue with the free version of <a href="http://www.partition-tool.com/personal.htm" target="_blank">EASEUS Partition Master Personal Edition</a>&#160; </li>
<li>To fix the boot issues that will arise you need to use the <a href="http://www.partition-saving.com/" target="_blank">Partition Saving suite</a> (in the download section look for the ‘spartiso.zip’ file). </li>
</ul>
<p>Here are the steps I made:</p>
<ol>
<li>Burn the Disk Copy and Partition Savings in two bootable CDs. </li>
<li>Connect the new HD to the system and start Windows from your old IDE drive, this step is needed to let the system load the SATA drivers if required. </li>
<li>Boot the Disk Copy tool and perform an copy of the Windows partition to the new drive (it will have the same size of the original one, that’s why you need a partition manager tool after) </li>
<li>When finished, just to be safe, remove/disconnect your previous HD and try to boot from the new HD. </li>
<li>If it all work you can go to step 14.      <br /><em>Here’s when my problems arose, instead of seeing the windows logo and the operating system the screen was totally black with the prompt flashing on the upper left corner.</em> </li>
<li>Boot from the Partition Savings CD and type ‘savepart’ at the prompt to start the utility </li>
<li>Choose &quot;update windows2000/xp/vista registry&quot; </li>
<li>Click on the partition that has your system ( “C” usually ) and take note of the drive letter this is your mounted device drive letter. </li>
<li>You will now see a list of directories, choose the &quot;WINDOWS&quot; directory </li>
<li>On next screen you choose the disk which has the partition whose registry definition you want to update </li>
<li>You choose the partition for which you want to update the definition in the registry </li>
<li>The last box is the &quot;drive letter to affect this partition&quot; box. You must choose from this list the drive letter you want to be associated with the partition selected with two previous windows. This is where it will show you the &quot;partition ID drive letter&quot; it should be the same as the &quot;mounted device drive letter&quot;.      <br />[extensive documentation can be found in the Partition Saving help files] </li>
<li>Reboot the system, it should start without problems and load windows, but your partition will have the same size as the original drive. </li>
<li>Install the partition manager tool and resize your partition to take advantage of your new HD. </li>
</ol>
<p>Enjoy your migrated system <img src='http://www.nablasoft.com/guardian/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/GuardiansHome/~4/eDUjgBxYWgo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.nablasoft.com/guardian/index.php/2009/11/03/how-to-migrate-a-windows-xp-installation-from-an-ide-to-a-sata-hard-drive/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.nablasoft.com/guardian/index.php/2009/11/03/how-to-migrate-a-windows-xp-installation-from-an-ide-to-a-sata-hard-drive/</feedburner:origLink></item>
		<item>
		<title>Using Regular Expressions to identify possible bugs in code</title>
		<link>http://feedproxy.google.com/~r/GuardiansHome/~3/Fa1RS7fpURk/</link>
		<comments>http://www.nablasoft.com/guardian/index.php/2009/10/29/using-regular-expressions-to-identify-possible-bugs-in-code/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 12:00:00 +0000</pubDate>
		<dc:creator>Guardian</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Bugs]]></category>
		<category><![CDATA[Find]]></category>
		<category><![CDATA[Regular Expression]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/guardian/index.php/2009/10/29/using-regular-expressions-to-identify-possible-bugs-in-code/</guid>
		<description><![CDATA[In the past few days I was moved to analyze some legacy code from a huge web application written by a company I work with. I have to write some new modules to integrate in this application; but while I was reviewing the code to ‘learn’ the style and code format used (to try to [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F10%2F29%2Fusing-regular-expressions-to-identify-possible-bugs-in-code%2F"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F10%2F29%2Fusing-regular-expressions-to-identify-possible-bugs-in-code%2F" height="61" width="51" /></a></div><p>In the past few days I was moved to analyze some legacy code from a huge web application written by a company I work with. I have to write some new modules to integrate in this application; but while I was reviewing the code to ‘learn’ the style and code format used (to try to build code similar to the one already written for uniformity and ease of maintenance for the other guys I work with), I faced code like this:</p>
<div class="csharpcode-wrapper">
<div class="csharpcode">
<pre class="alt">...</pre>
<pre class="alteven"><span class="kwrd">using</span> (DbCommand c = CurrentDatabase.GetSqlStringCommand(sql))</pre>
<pre class="alt">{</pre>
<pre class="alteven">   CurrentDatabase.AddInParameter(c, <span class="str">&quot;UserId&quot;</span>, DbType.String, UserName);</pre>
<pre class="alt">   IDataReader dr;</pre>
<pre class="alteven">   List&lt;Filiale&gt; list = <span class="kwrd">new</span> List&lt;Filiale&gt;();</pre>
<pre class="alt">   dr = CurrentDatabase.ExecuteReader(c);</pre>
<pre class="alteven">   <span class="kwrd">while</span> (dr.Read())</pre>
<pre class="alt">   {</pre>
<pre class="alteven">      list.Add(BuildObjectFromDataRow(dr));</pre>
<pre class="alt">   }</pre>
<pre class="alteven">   <span class="kwrd">return</span> list;</pre>
<pre class="alt">}</pre>
<pre class="alteven">...</pre>
</p></div>
</div>
<p>Can you see the bug here ? </p>
<p>The DataReader is created, used &#8230; and never closed&#8230;that is: a big resource leak! I looked around and found some more code similar to this one.</p>
<p>The solution is indeed huge (60+ projects) and with many classes for the data access written in an ‘old-style’ fashion. So we need a way to easily identify the ‘critical’ sections and check the code for similar resource leaks, because we do not want to check file by file if we can avoid it. I thought of it a bit and a solution came into my mind.</p>
<p>The best practice is to wrap each DataReader inside a using statement to clean up resources properly, and it is already used in many code fragments of the solution, so:</p>
<blockquote>
<p>Why can’t I try to use the Visual Studio ‘Find and Replace’ feature with some regular expression, looking for all the pieces of code that contains an ExecuteReader() call not wrapped inside a using statement?</p>
</blockquote>
<p>So I opened my favorite Regex editor an wrote down something like this:</p>
<div class="csharpcode-wrapper">
<div class="csharpcode">
<pre class="alt">^(?!.*\busing\b).*ExecuteReader</pre>
</p></div>
</div>
<p>It basically looks for any line that contains the ‘ExecuteReader’ string and do not contains the ‘using’ string-</p>
<p>I tested it with some code snippets and seemed to work, the bad news is: you can’t use this in Visual Studio..because the regex syntax is a bit different from the standard, check the VS or the MSDN help for the syntax.</p>
<p>You have to modify the expression like this:</p>
<div class="csharpcode-wrapper">
<div class="csharpcode">
<pre class="alt">^(~(.*&lt;<span class="kwrd">using</span>&gt;)).*ExecuteReader</pre>
</p></div>
</div>
<p><a href="http://www.nablasoft.com/guardian/wp-content/uploads/Usingregularexpressionstoidentifypossibl_B138/regexfindreplace.jpg"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="regex-findreplace" border="0" alt="regex-findreplace" src="http://www.nablasoft.com/guardian/wp-content/uploads/Usingregularexpressionstoidentifypossibl_B138/regexfindreplace_thumb.jpg" width="204" height="309" /></a> </p>
<p>Using this method you can easily identify all the code to check to fix the bug mentioned above. A similar technique can be used to identify anything you like in your code.</p>
<img src="http://feeds.feedburner.com/~r/GuardiansHome/~4/Fa1RS7fpURk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.nablasoft.com/guardian/index.php/2009/10/29/using-regular-expressions-to-identify-possible-bugs-in-code/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.nablasoft.com/guardian/index.php/2009/10/29/using-regular-expressions-to-identify-possible-bugs-in-code/</feedburner:origLink></item>
		<item>
		<title>When CloseMainWindow() fails: closing an application programmatically</title>
		<link>http://feedproxy.google.com/~r/GuardiansHome/~3/qFG_VpUSeLI/</link>
		<comments>http://www.nablasoft.com/guardian/index.php/2009/10/26/closemainwindow-wm_close-sc_close-closing-application-programmatically/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 16:18:00 +0000</pubDate>
		<dc:creator>Guardian</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[CloseMainWindow]]></category>
		<category><![CDATA[SC_CLOSE]]></category>
		<category><![CDATA[WM_CLOSE]]></category>
		<category><![CDATA[WM_SYSCOMMAND]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/guardian/index.php/2009/10/26/closemainwindow-wm_close-sc_close-closing-application-programmatically/</guid>
		<description><![CDATA[These days I’m working on a custom application updater for our products and I had the need to Close the main Application process from the Updater process. My first implementation involved getting the main application process ID and then use something like:


...
processToWait = Process.GetProcessById(pid)
mProcessToWait.CloseMainWindow()
mProcessToWait.WaitForExit()
mProcessToWait.Close()
...


Which at first worked well.
Then I’ve started to play with things like [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F10%2F26%2Fclosemainwindow-wm_close-sc_close-closing-application-programmatically%2F"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F10%2F26%2Fclosemainwindow-wm_close-sc_close-closing-application-programmatically%2F" height="61" width="51" /></a></div><p>These days I’m working on a custom application updater for our products and I had the need to Close the main Application process from the Updater process. My first implementation involved getting the main application process ID and then use something like:</p>
<div class="csharpcode-wrapper">
<div class="csharpcode">
<pre class="alt">...</pre>
<pre class="alteven">processToWait = Process.GetProcessById(pid)</pre>
<pre class="alt">mProcessToWait.CloseMainWindow()</pre>
<pre class="alteven">mProcessToWait.WaitForExit()</pre>
<pre class="alt">mProcessToWait.Close()</pre>
<pre class="alteven">...</pre>
</div>
</div>
<p>Which at first worked well.</p>
<p>Then I’ve started to play with things like Impersonation and Process spawning with different credential (to overcome some permissions problems in a production environment related to the application update process). The actual scenario is like this one: the main application runs under the user currently logged in the computer, while the Updater need to run as a different user with higher privileges. And all of a sudden the CloseMainWindow() function stopped to work&#8230;that is the application didn’t seemed to receive the close notification anymore (the usual ‘Do you really want to close?’ message box didn’t pop-up).</p>
<p>Doing more tests I noticed that the same things would have happened if the main application was minimized on the taskbar with both the application and the updater running under the same User.</p>
<p>Using Reflector/Spy++ and some other tools and investigating a bit it came out that the WM_CLOSE message wasn’t processed in these circumstances&#8230;and CloseMainWindow() is basically a wrapper function to post a WM_CLOSE message, so I had to look for an alternative way.</p>
<p>It came into my mind that since we are dealing with windows, I could simulate the input that the user gives using the ‘Windows/Control box menu’, I have no Framework API to do the task so I had to use some unmanaged code and post a WM_SYSCOMMAND with SC_CLOSE as parameter (the msdn reference is here <a href="http://msdn.microsoft.com/en-us/library/ms646360(VS.85).aspx" target="_blank">WM_SYSCOMMAND</a>).</p>
<p>This is how the final code looks like:</p>
<div class="csharpcode-wrapper">
<div class="csharpcode">
<pre class="alt">...</pre>
<pre class="alteven"><span class="kwrd">Const</span> WM_SYSCOMMAND <span class="kwrd">As</span> Int32 = &amp;H112</pre>
<pre class="alt"><span class="kwrd">Const</span> SC_CLOSE <span class="kwrd">As</span> Int32 = &amp;HF060I</pre>
<pre class="alteven"></pre>
<pre class="alt"><span class="kwrd">Declare</span> <span class="kwrd">Function</span> PostMessage <span class="kwrd">Lib</span> <span class="str">"user32.dll"</span> <span class="kwrd">Alias</span> <span class="str">"PostMessageA"</span> ( _</pre>
<pre class="alteven">  <span class="kwrd">ByVal</span> hwnd <span class="kwrd">As</span> Int32, _</pre>
<pre class="alt">  <span class="kwrd">ByVal</span> wMsg <span class="kwrd">As</span> Int32, _</pre>
<pre class="alteven">  <span class="kwrd">ByVal</span> wParam <span class="kwrd">As</span> Int32, _</pre>
<pre class="alt">  <span class="kwrd">ByVal</span> lParam <span class="kwrd">As</span> Int32) <span class="kwrd">As</span> Int32</pre>
<pre class="alteven">...</pre>
<pre class="alt"><span class="kwrd">Dim</span> handle <span class="kwrd">As</span> IntPtr = mProcessToWait.MainWindowHandle</pre>
<pre class="alteven">PostMessage(handle.ToInt32, WM_SYSCOMMAND, SC_CLOSE, 0)</pre>
<pre class="alt">mProcessToWait.WaitForExit()</pre>
<pre class="alteven">mProcessToWait.Close()</pre>
</div>
</div>
<p>I have to admit I don’t like to use unmanaged code if I can avoid it, but this works in the scenarios in which CloseMainWindow() fails.</p>
<img src="http://feeds.feedburner.com/~r/GuardiansHome/~4/qFG_VpUSeLI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.nablasoft.com/guardian/index.php/2009/10/26/closemainwindow-wm_close-sc_close-closing-application-programmatically/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.nablasoft.com/guardian/index.php/2009/10/26/closemainwindow-wm_close-sc_close-closing-application-programmatically/</feedburner:origLink></item>
		<item>
		<title>DotNetMarche Workshop material – Refactoring 2 the max</title>
		<link>http://feedproxy.google.com/~r/GuardiansHome/~3/mLyE2Mz2upU/</link>
		<comments>http://www.nablasoft.com/guardian/index.php/2009/10/21/dotnetmarche-workshop-material-refactoring-2-the-max/#comments</comments>
		<pubDate>Wed, 21 Oct 2009 14:36:00 +0000</pubDate>
		<dc:creator>Guardian</dc:creator>
				<category><![CDATA[Freetime talking]]></category>
		<category><![CDATA[dotnetmarche]]></category>
		<category><![CDATA[refactoring]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/guardian/index.php/2009/10/21/dotnetmarche-workshop-material-refactoring-2-the-max/</guid>
		<description><![CDATA[Recently, together with Diego Guidi, Alfredo Morresi and Gian Maria Ricci, I was the speaker in the 11th workshop presented by our .net user group DotNetMarche.
We talked about solution refactoring presenting some guidelines and why/how you should do refactoring (Alfredo Morresi); then we had a session in which we presented some advances features of Resharper, [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F10%2F21%2Fdotnetmarche-workshop-material-refactoring-2-the-max%2F"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F10%2F21%2Fdotnetmarche-workshop-material-refactoring-2-the-max%2F" height="61" width="51" /></a></div><p>Recently, together with <a href="http://lacorrente.blogspot.com" target="_blank">Diego Guidi</a>, <a href="http://www.rainbowbreeze.it/" target="_blank">Alfredo Morresi</a> and <a href="http://www.nablasoft.com/alkampfer" target="_blank">Gian Maria Ricci</a>, I was the speaker in the 11th workshop presented by our .net user group <a href="http://www.dotnetmarche.org" target="_blank">DotNetMarche</a>.</p>
<p>We talked about solution refactoring presenting some guidelines and why/how you should do refactoring (Alfredo Morresi); then we had a session in which we presented some advances features of Resharper, one of the tool we use to help us during the refactoring activities (Diego Guidi).</p>
<p>The 3rd session (held by the proud owner of this blog <img src='http://www.nablasoft.com/guardian/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ) was about refactoring ASP.NET pages and controls, showing how you can refactor a completely non structured and fully hardcoded solution to reach an MVC approach, while improving the general performances of the pages/controls at the same time.</p>
<p>The last session (Gian Maria Ricci) was devoted to ASP.NET pages refactoring, showing you how the refactoring activity of a page or control in different components can facilitate the testing of each piece of the application.</p>
<p>If you are interested, the material of the workshop is available following this link: <a href="http://dotnetmarche.org/files/folders/11_-_refactoring_2themax_09102009/default.aspx" target="_blank">http://dotnetmarche.org/files/folders/11_-_refactoring_2themax_09102009/default.aspx</a></p>
<p>The website of the user group is in Italian (cause we are a local community), but the slides and the source code presented are written in English.</p>
<img src="http://feeds.feedburner.com/~r/GuardiansHome/~4/mLyE2Mz2upU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.nablasoft.com/guardian/index.php/2009/10/21/dotnetmarche-workshop-material-refactoring-2-the-max/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.nablasoft.com/guardian/index.php/2009/10/21/dotnetmarche-workshop-material-refactoring-2-the-max/</feedburner:origLink></item>
		<item>
		<title>Castle Windsor: Transient Objects and Release Policies</title>
		<link>http://feedproxy.google.com/~r/GuardiansHome/~3/SS-hRxUSOFQ/</link>
		<comments>http://www.nablasoft.com/guardian/index.php/2009/10/16/castle-windsor-transient-objects-and-release-policies/#comments</comments>
		<pubDate>Fri, 16 Oct 2009 15:40:00 +0000</pubDate>
		<dc:creator>Guardian</dc:creator>
				<category><![CDATA[Castle Windsor]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[LifecycledComponentsReleasePolicy]]></category>
		<category><![CDATA[ReleasePolicy]]></category>
		<category><![CDATA[Transient]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/guardian/index.php/2009/10/16/castle-windsor-transient-objects-and-release-policies/</guid>
		<description><![CDATA[I’m not a Castle Windsor expert and I started using it heavily some months ago. These days I’m profiling some of the applications I wrote in the past to try to optimize the memory usage and reduce the footprint they allocate.
Using some profiling tools I came across one of the most frequent (and biggest) mistakes [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F10%2F16%2Fcastle-windsor-transient-objects-and-release-policies%2F"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F10%2F16%2Fcastle-windsor-transient-objects-and-release-policies%2F" height="61" width="51" /></a></div><p>I’m not a Castle Windsor expert and I started using it heavily some months ago. These days I’m profiling some of the applications I wrote in the past to try to optimize the memory usage and reduce the footprint they allocate.</p>
<p>Using some profiling tools I came across one of the most frequent (and biggest) mistakes you can do while using Castle Windsor with Transient objects: I always forget to call the Release() function from the container from which I requested the object.</p>
<p>This simply happened because Castle do not handle transient DISPOSABLE objects the way I was thinking. In my mind a ‘Transient’ object is (was) something I require from the container and then I have FULL CONTROL over its life, the container (or the factory) should completely forget of the object itself.</p>
<p>Well&#8230;it isn’t like that, the default behavior that Castle implements is to keep track of any DISPOSABLE object he creates to deallocate them in the right way when the container itself is disposed.</p>
<p>There are a number of good reasons for this to happen, and it actually is a quite long discussion; you can find some info in these posts:</p>
<p><a href="http://elegantcode.com/2008/12/14/the-component-burden/">http://elegantcode.com/2008/12/14/the-component-burden/</a></p>
<p><a href="http://hammett.castleproject.org/?p=252">http://hammett.castleproject.org/?p=252</a></p>
<p>some other posts from my friend Alkampfer gives you some more info on the same mistake I made:</p>
<p><a href="http://www.nablasoft.com/Alkampfer/?p=104">http://www.nablasoft.com/Alkampfer/?p=104</a></p>
<p><a href="http://www.nablasoft.com/Alkampfer/?p=105">http://www.nablasoft.com/Alkampfer/?p=105</a></p>
<p><a href="http://www.nablasoft.com/alkampfer/index.php/2008/02/29/again-on-castle-transient-and-the-custom-lifecycle/">http://www.nablasoft.com/alkampfer/index.php/2008/02/29/again-on-castle-transient-and-the-custom-lifecycle/</a></p>
<p>If, like me, you used some static IoC container that lived along the whole life of the application you can see the huge impact this behavior has on the memory allocated by the application: since the container keeps a reference to any disposable object (even the transient ones) you allocated, they will never be released during a GC action.</p>
<p>So&#8230;how to modify the default Castle behavior to match my view? The goal is simple: we want to keep the actual object tracking for all the objects lifestyle types (singleton, pooled, etc&#8230;), but we do not want to track transient object; in this way the CLR is able to reclaim the memory they use during a GC call.</p>
<p>It all seemed hard to obtain until I found out that Castle have configurable Release Policies that actually handle the object tracking, here you can find some ‘small’ documentation on the default policies that come with castle: <a href="http://www.castleproject.org/container/documentation/trunk/advanced/releasepolicy.html">http://www.castleproject.org/container/documentation/trunk/advanced/releasepolicy.html</a>. LifecycledComponentsReleasePolicy is actually the default one.</p>
<p>At first my solution was to implement a new policy that modified the tracking behavior for transient objects:</p>
<div class="csharpcode-wrapper">
<div class="csharpcode">
<pre class="alt"><span class="rem">/// &lt;summary&gt;</span></pre>
<pre class="alteven"><span class="rem">/// Inherits from the default ReleasePolicy; do not track our own transient objects.</span></pre>
<pre class="alt"><span class="rem">/// Only tracks components that have decommission steps</span></pre>
<pre class="alteven"><span class="rem">/// registered or have pooled lifestyle.</span></pre>
<pre class="alt"><span class="rem">/// &lt;/summary&gt;</span></pre>
<pre class="alteven">[Serializable]</pre>
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> TrulyTransientReleasePolicy : LifecycledComponentsReleasePolicy</pre>
<pre class="alteven">{</pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Track(<span class="kwrd">object</span> instance, Burden burden)</pre>
<pre class="alteven">    {</pre>
<pre class="alt">        ComponentModel model = burden.Model;</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">        <span class="rem">// to modify the way Castle handles the Transient object uncomment the following lines</span></pre>
<pre class="alteven">        <span class="kwrd">if</span> (model.LifestyleType == LifestyleType.Transient)</pre>
<pre class="alt">            <span class="kwrd">return</span>;</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">        <span class="kwrd">base</span>.Track(instance, burden);</pre>
<pre class="alteven">    }</pre>
<pre class="alt">}</pre>
</p></div>
</div>
<p>After some more thinking I decided to modify it a bit and add a custom LifestyleManager class to use toghether with this policy to not alter the default behavior defined by the transient attribute in Castle, here’s my final solution:</p>
<div class="csharpcode-wrapper">
<div class="csharpcode">
<pre class="alt"><span class="rem">/// &lt;summary&gt;</span></pre>
<pre class="alteven"><span class="rem">/// a custom Lifestyle, it will inerit from the standard class so if the TrulyTransientReleasePolicy policy</span></pre>
<pre class="alt"><span class="rem">/// isn't used these objects are handled as standard transient objects </span></pre>
<pre class="alteven"><span class="rem">/// &lt;/summary&gt;</span></pre>
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> TrulyTransientLifestyleManager : TransientLifestyleManager</pre>
<pre class="alteven">{</pre>
<pre class="alt">}</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt"><span class="rem">/// &lt;summary&gt;</span></pre>
<pre class="alteven"><span class="rem">/// Inherits from the default ReleasePolicy; do not track our own transient objects.</span></pre>
<pre class="alt"><span class="rem">/// Only tracks components that have decommission steps</span></pre>
<pre class="alteven"><span class="rem">/// registered or have pooled lifestyle.</span></pre>
<pre class="alt"><span class="rem">/// &lt;/summary&gt;</span></pre>
<pre class="alteven">[Serializable]</pre>
<pre class="alt"><span class="kwrd">public</span> <span class="kwrd">class</span> TrulyTransientReleasePolicy : LifecycledComponentsReleasePolicy</pre>
<pre class="alteven">{</pre>
<pre class="alt">   <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Track(<span class="kwrd">object</span> instance, Burden burden)</pre>
<pre class="alteven">   {</pre>
<pre class="alt">      ComponentModel model = burden.Model;</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">      <span class="rem">// to modify the way Castle handles the Transient object uncomment the following lines</span></pre>
<pre class="alteven">      <span class="rem">//if (model.LifestyleType == LifestyleType.Transient)</span></pre>
<pre class="alt">      <span class="rem">//   return;</span></pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">      <span class="rem">// we skip the tracking for object marked with our custom Transient lifestyle manager</span></pre>
<pre class="alteven">      <span class="kwrd">if</span> ((model.LifestyleType == LifestyleType.Custom) &amp;&amp;</pre>
<pre class="alt">          (<span class="kwrd">typeof</span>(TrulyTransientLifestyleManager) == model.CustomLifestyle))</pre>
<pre class="alteven">         <span class="kwrd">return</span>;</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">      <span class="kwrd">base</span>.Track(instance, burden);</pre>
<pre class="alt">   }</pre>
<pre class="alteven">}</pre>
</p></div>
</div>
<p>To ‘force’ Castle to use this policy you have to write some code:</p>
<div class="csharpcode-wrapper">
<div class="csharpcode">
<pre class="alt">...</pre>
<pre class="alteven">_container = <span class="kwrd">new</span> WindsorContainer(</pre>
<pre class="alt">   <span class="kwrd">new</span> XmlInterpreter(<span class="kwrd">new</span> ConfigResource(<span class="str">&quot;services&quot;</span>)));</pre>
<pre class="alteven">_container.Kernel.ReleasePolicy = <span class="kwrd">new</span> TrulyTransientReleasePolicy();</pre>
<pre class="alt">...</pre>
</p></div>
</div>
<p>Due to the lack of documentation I haven’t found a way to configure this policy using the configuration file, I’ll update this post when I can figure out how to do it.</p>
<p>Here’s how you can define the components in the configuration file</p>
<div class="csharpcode-wrapper">
<div class="csharpcode">
<pre class="alt">...</pre>
<pre class="alteven"><span class="kwrd">&lt;</span><span class="html">components</span><span class="kwrd">&gt;</span></pre>
<pre class="alt">   <span class="rem">&lt;!-- test data provider, this one returns some hardcoded data --&gt;</span></pre>
<pre class="alteven">   <span class="kwrd">&lt;</span><span class="html">component</span> <span class="attr">id</span><span class="kwrd">=&quot;DisposableEntity&quot;</span></pre>
<pre class="alt">              <span class="attr">service</span><span class="kwrd">=&quot;IoCRelease.Entities.ITestEntity,IoCRelease&quot;</span></pre>
<pre class="alteven">              <span class="attr">type</span><span class="kwrd">=&quot;IoCRelease.Entities.DisposableEntity,IoCRelease&quot;</span></pre>
<pre class="alt">              <span class="attr">lifestyle</span><span class="kwrd">=&quot;transient&quot;</span><span class="kwrd">&gt;</span></pre>
<pre class="alteven">   <span class="kwrd">&lt;/</span><span class="html">component</span><span class="kwrd">&gt;</span></pre>
<pre class="alt">   <span class="kwrd">&lt;</span><span class="html">component</span> <span class="attr">id</span><span class="kwrd">=&quot;DisposableEntityTransient&quot;</span></pre>
<pre class="alteven">              <span class="attr">service</span><span class="kwrd">=&quot;IoCRelease.Entities.ITestEntity,IoCRelease&quot;</span></pre>
<pre class="alt">              <span class="attr">type</span><span class="kwrd">=&quot;IoCRelease.Entities.DisposableEntity,IoCRelease&quot;</span></pre>
<pre class="alteven">              <span class="attr">lifestyle</span><span class="kwrd">=&quot;custom&quot;</span></pre>
<pre class="alt">              <span class="attr">customLifestyleType</span><span class="kwrd">=&quot;IoCRelease.Castle.TrulyTransientLifestyleManager,IoCRelease&quot;</span><span class="kwrd">&gt;</span></pre>
<pre class="alteven">   <span class="kwrd">&lt;/</span><span class="html">component</span><span class="kwrd">&gt;</span></pre>
<pre class="alt">   <span class="kwrd">&lt;</span><span class="html">component</span> <span class="attr">id</span><span class="kwrd">=&quot;Entity&quot;</span></pre>
<pre class="alteven">              <span class="attr">service</span><span class="kwrd">=&quot;IoCRelease.Entities.ITestEntity,IoCRelease&quot;</span></pre>
<pre class="alt">              <span class="attr">type</span><span class="kwrd">=&quot;IoCRelease.Entities.Entity,IoCRelease&quot;</span></pre>
<pre class="alteven">              <span class="attr">lifestyle</span><span class="kwrd">=&quot;transient&quot;</span><span class="kwrd">&gt;</span></pre>
<pre class="alt">   <span class="kwrd">&lt;/</span><span class="html">component</span><span class="kwrd">&gt;</span></pre>
<pre class="alteven"><span class="kwrd">&lt;/</span><span class="html">components</span><span class="kwrd">&gt;</span></pre>
<pre class="alt">...</pre>
</p></div>
</div>
<p>The code sample (based on Alkampfer’s code) that comes with this articles presents a couple of test that when executed with the NUnit console will show you what happens using the custom policy:</p>
<p>For the normal LifecycledComponentsReleasePolicy you can see the Dispose is called (the counter gets increment) and we do not have any Finalize call (which was suppressed in the dispose pattern).</p>
<p><a href="http://www.nablasoft.com/guardian/wp-content/uploads/CastleWindsorTransientObjectsandReleaseP_EBF6/IoCRelease1.jpg"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="IoCRelease1" border="0" alt="IoCRelease1" src="http://www.nablasoft.com/guardian/wp-content/uploads/CastleWindsorTransientObjectsandReleaseP_EBF6/IoCRelease1_thumb.jpg" width="544" height="159" /></a> </p>
<p>For the TrulyTransientReleasePolicy you can see that the Dispose is never directly called (the counter remains at 0), while the CLR calls the Finalize when the objects are garbage collected.</p>
<p><a href="http://www.nablasoft.com/guardian/wp-content/uploads/CastleWindsorTransientObjectsandReleaseP_EBF6/IoCRelease2.jpg"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="IoCRelease2" border="0" alt="IoCRelease2" src="http://www.nablasoft.com/guardian/wp-content/uploads/CastleWindsorTransientObjectsandReleaseP_EBF6/IoCRelease2_thumb.jpg" width="544" height="139" /></a> </p>
<p>At this point you have to remember that using the TrulyTransientLifestyleManager and the TrulyTransientReleasePolicy <strong>YOU are responsible for the object lifetime</strong>, but they are no more anchored to the container and the runtime is able to reclaim their memory if never used.</p>
<p>The good thing is that if you want to implement this behavior in an existing application (to do a quick fix at that huge memory leak you had, while working on a better way to handle/deallocate your objects) all you have to do is to change the Castle configuration file and to inject the policy into the container.</p>
<p>Test project:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:8eb9d37f-1541-4f29-b6f4-1eea890d4876:90fd7759-75ff-429d-8c83-2754fe74ac24" class="wlWriterEditableSmartContent">
<div><a href="http://www.nablasoft.com/guardian/wp-content/uploads/CastleWindsorTransientObjectsandReleaseP_EBF6/IoCReleaseTests.zip" target="_self">IoCReleaseTests.zip</a></div>
</p>
</div>
<img src="http://feeds.feedburner.com/~r/GuardiansHome/~4/SS-hRxUSOFQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.nablasoft.com/guardian/index.php/2009/10/16/castle-windsor-transient-objects-and-release-policies/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.nablasoft.com/guardian/index.php/2009/10/16/castle-windsor-transient-objects-and-release-policies/</feedburner:origLink></item>
		<item>
		<title>Missing .NET Performance Counters: how to solve it</title>
		<link>http://feedproxy.google.com/~r/GuardiansHome/~3/YWu4wgHOSQ4/</link>
		<comments>http://www.nablasoft.com/guardian/index.php/2009/10/07/missing-net-performance-counters-solve/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 15:55:00 +0000</pubDate>
		<dc:creator>Guardian</dc:creator>
				<category><![CDATA[Freetime talking]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[counters]]></category>
		<category><![CDATA[missing]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/guardian/index.php/2009/10/07/missing-net-performance-counters-solve/</guid>
		<description><![CDATA[Today I’ve started to profile my applications to try to see if I have some memory leaks and performances bottlenecks.
I just started the inspection trying to look at some performance counters (especially to check if the memory allocated by my application kept growing)&#8230; but I had the surprise of the day when I couldn0t find [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F10%2F07%2Fmissing-net-performance-counters-solve%2F"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F10%2F07%2Fmissing-net-performance-counters-solve%2F" height="61" width="51" /></a></div><p>Today I’ve started to profile my applications to try to see if I have some memory leaks and performances bottlenecks.</p>
<p>I just started the inspection trying to look at some performance counters (especially to check if the memory allocated by my application kept growing)&#8230; but I had the surprise of the day when I couldn0t find any .Net related performance counter on my system.</p>
<p>At first I tried everything I knew to unload and reload performance counters, with the usual commands:</p>
<div class="csharpcode-wrapper">
<div class="csharpcode">
<pre class="alt">unlodctr .NETFramework</pre>
<pre class="alteven">lodctr c:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\corperfmonsymbols.ini</pre>
</p></div>
</div>
<p>But they didn’t worked&#8230;</p>
<p>Then I started to look around some registry keys and I found this one:</p>
<p>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\.NETFramework</p>
<p>that seemed to contains information related to the performance counters&#8230;I googled a bit and found this Microsoft knowledge base articles that clarified the thing: <a title="http://support.microsoft.com/?scid=kb%3Ben-us%3B312113&amp;x=18&amp;y=14" href="http://support.microsoft.com/?scid=kb%3Ben-us%3B312113&amp;x=18&amp;y=14">http://support.microsoft.com/?scid=kb%3Ben-us%3B312113&amp;x=18&amp;y=14</a></p>
<p>It seems that an application messed up with my registry trying to speedup its load times and in doing so it disabled the performance counters modifying the key ‘<strong>Library’</strong> under ‘HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\.NETFramework\Performance’ to the non valid value ‘<b>donotload_mscoree.dll</b>’; Reverting this back to mscoree.dll and reloading the Perfmon utility I had my counters back.</p>
<p>It costed me only 1 hour and a half of my time!</p>
<img src="http://feeds.feedburner.com/~r/GuardiansHome/~4/YWu4wgHOSQ4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.nablasoft.com/guardian/index.php/2009/10/07/missing-net-performance-counters-solve/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.nablasoft.com/guardian/index.php/2009/10/07/missing-net-performance-counters-solve/</feedburner:origLink></item>
		<item>
		<title>WSS / SharePoint : filter Users with the PeopleEditor control</title>
		<link>http://feedproxy.google.com/~r/GuardiansHome/~3/K6gHOVWwcKw/</link>
		<comments>http://www.nablasoft.com/guardian/index.php/2009/09/23/wss-sharepoint-filter-users-peopleeditor/#comments</comments>
		<pubDate>Wed, 23 Sep 2009 10:42:00 +0000</pubDate>
		<dc:creator>Guardian</dc:creator>
				<category><![CDATA[SharePoint/WSS]]></category>
		<category><![CDATA[SharePoint;WSS;Custom;Current User;Filter]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/guardian/index.php/2009/09/23/wss-sharepoint-filter-users-peopleeditor/</guid>
		<description><![CDATA[Given the ListViewWebPart with advanced filtering capabilities we wrote in the previous articles, we want to extend it again and provide the ability to select which user (or users) we will use to filter our data out.
We can just write a simple web part that wraps the standard PeopleEditor control that comes with WSS or [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F09%2F23%2Fwss-sharepoint-filter-users-peopleeditor%2F"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F09%2F23%2Fwss-sharepoint-filter-users-peopleeditor%2F" height="61" width="51" /></a></div><p>Given the ListViewWebPart with advanced filtering capabilities we wrote in the previous articles, we want to extend it again and provide the ability to select which user (or users) we will use to filter our data out.</p>
<p>We can just write a simple web part that wraps the standard PeopleEditor control that comes with WSS or SharePoint.</p>
<p>The code is pretty straightforward, the PeopleEditor will be created and added to the Controls collection of the web part in the CreateChildControls() function. We will parse the data that the control exposes in the ITransformableFilterValues.ParameterValues property: each valid selected user will be contained in the PeopleEditor.ResolvedEntities collection (which contains PickerEntity objects).</p>
<p>The full code is listed below:</p>
<div class="csharpcode-wrapper">
<div class="csharpcode">
<pre class="alt">[Guid(<span class="str">&quot;4fddd9c3-37bf-48b9-84a2-0b4d96f98f92&quot;</span>)]</pre>
<pre class="alteven"><span class="kwrd">public</span> <span class="kwrd">class</span> SelectedUserFilterWebPart : wsswebparts.WebPart, wsswebparts.ITransformableFilterValues</pre>
<pre class="alt">{</pre>
<pre class="alteven">   <span class="kwrd">private</span> PeopleEditor _pplEditor;</pre>
<pre class="alt">   <span class="kwrd">private</span> Button _btnApplyFilter;</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> CreateChildControls()</pre>
<pre class="alteven">   {</pre>
<pre class="alt">      <span class="kwrd">base</span>.CreateChildControls();</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">      _pplEditor = <span class="kwrd">new</span> PeopleEditor();</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">      Controls.Add(_pplEditor);</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">      _btnApplyFilter = <span class="kwrd">new</span> Button();</pre>
<pre class="alteven">      _btnApplyFilter.Text = <span class="str">&quot;Apply Filter&quot;</span>;</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">      Controls.Add(_btnApplyFilter);</pre>
<pre class="alt">   }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">   <span class="kwrd">private</span> List&lt;String&gt; GetSelectedEntries()</pre>
<pre class="alteven">   {</pre>
<pre class="alt">      List&lt;String&gt; selectedEnties = <span class="kwrd">new</span> List&lt;String&gt;();</pre>
<pre class="alteven">      <span class="kwrd">try</span></pre>
<pre class="alt">      {</pre>
<pre class="alteven">         <span class="kwrd">foreach</span> (PickerEntity entity <span class="kwrd">in</span> _pplEditor.ResolvedEntities)</pre>
<pre class="alt">         {</pre>
<pre class="alteven">            <span class="kwrd">if</span> (entity.IsResolved)</pre>
<pre class="alt">            {</pre>
<pre class="alteven">               selectedEnties.Add(entity.DisplayText);</pre>
<pre class="alt">            }</pre>
<pre class="alteven">         }</pre>
<pre class="alt">      }</pre>
<pre class="alteven">      <span class="kwrd">catch</span> (Exception)</pre>
<pre class="alt">      {</pre>
<pre class="alteven">      }</pre>
<pre class="alt">      <span class="kwrd">return</span> selectedEnties;</pre>
<pre class="alteven">   }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">    <span class="rem">// Implementations of the ITransformableFilterValues properties.</span></pre>
<pre class="alt">    [wsswebparts.WebPartStorage(wsswebparts.Storage.None)]</pre>
<pre class="alteven">    <span class="kwrd">public</span> <span class="kwrd">virtual</span> <span class="kwrd">bool</span> AllowMultipleValues</pre>
<pre class="alt">    {</pre>
<pre class="alteven">        get</pre>
<pre class="alt">        {</pre>
<pre class="alteven">            <span class="kwrd">return</span> <span class="kwrd">true</span>;</pre>
<pre class="alt">        }</pre>
<pre class="alteven">    }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">    [wsswebparts.WebPartStorage(wsswebparts.Storage.None)]</pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">virtual</span> <span class="kwrd">bool</span> AllowAllValue</pre>
<pre class="alteven">    {</pre>
<pre class="alt">        get</pre>
<pre class="alteven">        {</pre>
<pre class="alt">            <span class="kwrd">return</span> <span class="kwrd">true</span>;</pre>
<pre class="alteven">        }</pre>
<pre class="alt">    }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">    [wsswebparts.WebPartStorage(wsswebparts.Storage.None)]</pre>
<pre class="alteven">    <span class="kwrd">public</span> <span class="kwrd">virtual</span> <span class="kwrd">bool</span> AllowEmptyValue</pre>
<pre class="alt">    {</pre>
<pre class="alteven">        get</pre>
<pre class="alt">        {</pre>
<pre class="alteven">            <span class="kwrd">return</span> <span class="kwrd">true</span>;</pre>
<pre class="alt">        }</pre>
<pre class="alteven">    }</pre>
<pre class="alt">&#160;</pre>
<pre class="alteven">    [wsswebparts.WebPartStorage(wsswebparts.Storage.None)]</pre>
<pre class="alt">    <span class="kwrd">public</span> <span class="kwrd">virtual</span> <span class="kwrd">string</span> ParameterName</pre>
<pre class="alteven">    {</pre>
<pre class="alt">        get</pre>
<pre class="alteven">        {</pre>
<pre class="alt">            <span class="kwrd">return</span> <span class="str">&quot;SelectedUser&quot;</span>;</pre>
<pre class="alteven">        }</pre>
<pre class="alt">    }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">    [wsswebparts.WebPartStorage(wsswebparts.Storage.None)]</pre>
<pre class="alteven">    <span class="kwrd">public</span> <span class="kwrd">virtual</span> ReadOnlyCollection&lt;<span class="kwrd">string</span>&gt; ParameterValues</pre>
<pre class="alt">    {</pre>
<pre class="alteven">        get</pre>
<pre class="alt">        {</pre>
<pre class="alteven">           List&lt;String&gt; data = GetSelectedEntries();</pre>
<pre class="alt">           <span class="kwrd">if</span> (data.Count == 0)</pre>
<pre class="alteven">              <span class="kwrd">return</span> <span class="kwrd">null</span>;</pre>
<pre class="alt">           <span class="kwrd">return</span> <span class="kwrd">new</span> ReadOnlyCollection&lt;<span class="kwrd">string</span>&gt;(data);</pre>
<pre class="alteven">        }</pre>
<pre class="alt">    }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">    <span class="rem">// Use the ConnectionProvider attribute to specify the method that the Web Part</span></pre>
<pre class="alteven">    <span class="rem">// Framework should call to allow us to return an instance of our ITransformableFilterValues interface.</span></pre>
<pre class="alt">    [aspnetwebparts.ConnectionProvider(<span class="str">&quot;Selected User Filter&quot;</span>, <span class="str">&quot;ITransformableFilterValues&quot;</span>, AllowsMultipleConnections = <span class="kwrd">true</span>)]</pre>
<pre class="alteven">    <span class="kwrd">public</span> wsswebparts.ITransformableFilterValues SetConnectionInterface()</pre>
<pre class="alt">    {</pre>
<pre class="alteven">        <span class="kwrd">return</span> <span class="kwrd">this</span>;</pre>
<pre class="alt">    }</pre>
<pre class="alteven">&#160;</pre>
<pre class="alt">}</pre>
</p></div>
</div>
<p>Here’s a screenshot of the web parts in action.</p>
<p><a href="http://www.nablasoft.com/guardian/wp-content/uploads/WSSSharePointacustomwebparttousethePeopl_ADD7/SharePointSelectedUser.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="SharePointSelectedUser" border="0" alt="SharePointSelectedUser" src="http://www.nablasoft.com/guardian/wp-content/uploads/WSSSharePointacustomwebparttousethePeopl_ADD7/SharePointSelectedUser_thumb.png" width="604" height="316" /></a> </p>
<p>With this solution you can filter on the currently logged user, or a user of your choice even in WSS without having to rely on MOSS extensions.</p>
<img src="http://feeds.feedburner.com/~r/GuardiansHome/~4/K6gHOVWwcKw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.nablasoft.com/guardian/index.php/2009/09/23/wss-sharepoint-filter-users-peopleeditor/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.nablasoft.com/guardian/index.php/2009/09/23/wss-sharepoint-filter-users-peopleeditor/</feedburner:origLink></item>
		<item>
		<title>svchost.exe (LocalSystemNetworkRestricted) 100% Hard Disk usage</title>
		<link>http://feedproxy.google.com/~r/GuardiansHome/~3/oUUQ6I4UWs8/</link>
		<comments>http://www.nablasoft.com/guardian/index.php/2009/09/22/svchostexe-localsystemnetworkrestricted-100-hard-disk-usage/#comments</comments>
		<pubDate>Tue, 22 Sep 2009 11:00:00 +0000</pubDate>
		<dc:creator>Guardian</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[100%]]></category>
		<category><![CDATA[HDD]]></category>
		<category><![CDATA[localsystemnetworkrestricted]]></category>
		<category><![CDATA[Superfect]]></category>
		<category><![CDATA[svchost]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/guardian/index.php/2009/09/22/svchostexe-localsystemnetworkrestricted-100-hard-disk-usage/</guid>
		<description><![CDATA[Today on of my Vista developing workstations suddenly became very slow, the CPU was almost free and its usage was around 3-5%, the Hard Drive instead was overloaded with work, with its activity at 100% all the time. Trying to do any operation on the system requested ages..like 1 or 2 min to open the [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F09%2F22%2Fsvchostexe-localsystemnetworkrestricted-100-hard-disk-usage%2F"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.nablasoft.com%2Fguardian%2Findex.php%2F2009%2F09%2F22%2Fsvchostexe-localsystemnetworkrestricted-100-hard-disk-usage%2F" height="61" width="51" /></a></div><p>Today on of my Vista developing workstations suddenly became very slow, the CPU was almost free and its usage was around 3-5%, the Hard Drive instead was overloaded with work, with its activity at 100% all the time. Trying to do any operation on the system requested ages..like 1 or 2 min to open the start menu or display a window.</p>
<p>Restating the system didn’t helped much, so I started to investigate the problem; opening the task manager and then the resource monitor I found out that I have many processes called like svchost.exe (LocalSystemNetworkRestricted) that were reading every files on the system (even the file related to the games I play at night).</p>
<p>So I opened the services management console to find something that could be run using svchost, I looked at every service there and found out that the ‘SuperFetch’ service (‘Ottimizzazione avvio’ in my Italian OS) was launched with this command: svchost.exe -k LocalSystemNetworkRestricted.</p>
<p>I disabled the service and rebooted the machine (I had to perform an hard reset cause the system was still hung reading the files on the disk). After the restart the problem disappeared and the system is back to be responsive.</p>
<p>In the end, it must be a bug of some sort related to the SuperFetch service, cause it ran fine for months without causing any problem.</p>
<img src="http://feeds.feedburner.com/~r/GuardiansHome/~4/oUUQ6I4UWs8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.nablasoft.com/guardian/index.php/2009/09/22/svchostexe-localsystemnetworkrestricted-100-hard-disk-usage/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.nablasoft.com/guardian/index.php/2009/09/22/svchostexe-localsystemnetworkrestricted-100-hard-disk-usage/</feedburner:origLink></item>
	</channel>
</rss>
