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

<channel>
	<title>Jonathan C Dickinson &#187; C#</title>
	<atom:link href="http://jonathan.dickinsons.co.za/blog/category/programming/c-sharp/feed/" rel="self" type="application/rss+xml" />
	<link>http://jonathan.dickinsons.co.za/blog</link>
	<description>&#34;Jonathan Chayce Dickinson&#34;.ToString()</description>
	<lastBuildDate>Sat, 26 Feb 2011 14:21:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>Cross-AppDomain Singleton in C#</title>
		<link>http://jonathan.dickinsons.co.za/blog/2010/11/cross-domain-singleton-in-c/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2010/11/cross-domain-singleton-in-c/#comments</comments>
		<pubDate>Tue, 02 Nov 2010 11:12:03 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tricks]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=217</guid>
		<description><![CDATA[How create a cross-AppDomain singleton in C# without using interop calls to the runtime.]]></description>
			<content:encoded><![CDATA[<h2>Scenario</h2>
<p>I have a logging system that contains one or more loggers. These logger should NOT be initialized (or ever constructed) for child domains; this is a problem because each AppDomain in .Net recieves it&#8217;s own static instances.</p>
<h2>Typical Solution</h2>
<p>Most people resort to the MSCOREE library and enumerate all the current AppDomains to find the primary AppDomain. After that they can retrieve the singleton instance from within the primary AppDomain.</p>
<p>This has it&#8217;s problems, most notably interop ties you to an architecture and requires certain CAS policies. Furthermore, I just don&#8217;t like too much interop.</p>
<h2>My Solution</h2>
<p>My solution involves creating a custom AppDomainManager that is aware of the primary AppDomain. The principle is that the AppDomainManager creates a new AppDomain for primary execution. This new domain uses the custom AppDomainManager (which can then control the creation of child domains; and therefore wire itself into them). The code is self-explanatory (hopefully):</p>
<pre class="brush: csharp;">    /// &lt;summary&gt;
    /// Represents a &lt;see cref=&quot;AppDomainManager&quot;/&gt; that is
    /// aware of the primary application AppDomain.
    /// &lt;/summary&gt;
    public class PrimaryAppDomainManager : AppDomainManager
    {
        private static AppDomain _primaryDomain;

        /// &lt;summary&gt;
        /// Gets the primary domain.
        /// &lt;/summary&gt;
        /// &lt;value&gt;The primary domain.&lt;/value&gt;
        public static AppDomain PrimaryDomain
        {
            get
            {
                return _primaryDomain;
            }
        }

        /// &lt;summary&gt;
        /// Sets the primary domain.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;primaryDomain&quot;&gt;The primary domain.&lt;/param&gt;
        private void SetPrimaryDomain(AppDomain primaryDomain)
        {
            _primaryDomain = primaryDomain;
        }

        /// &lt;summary&gt;
        /// Sets the primary domain to self.
        /// &lt;/summary&gt;
        private void SetPrimaryDomainToSelf()
        {
            _primaryDomain = AppDomain.CurrentDomain;
        }

        /// &lt;summary&gt;
        /// Determines whether this is the primary domain.
        /// &lt;/summary&gt;
        /// &lt;value&gt;
        /// 	&lt;see langword=&quot;true&quot;/&gt; if this instance is the primary domain; otherwise, &lt;see langword=&quot;false&quot;/&gt;.
        /// &lt;/value&gt;
        public static bool IsPrimaryDomain
        {
            get
            {
                return _primaryDomain == AppDomain.CurrentDomain;
            }
        }

        /// &lt;summary&gt;
        /// Creates the initial domain.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;friendlyName&quot;&gt;Name of the friendly.&lt;/param&gt;
        /// &lt;param name=&quot;securityInfo&quot;&gt;The security info.&lt;/param&gt;
        /// &lt;param name=&quot;appDomainInfo&quot;&gt;The AppDomain setup info.&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public static AppDomain CreateInitialDomain(string friendlyName, Evidence securityInfo, AppDomainSetup appDomainInfo)
        {
            if (AppDomain.CurrentDomain.DomainManager is PrimaryAppDomainManager)
                return null;

            appDomainInfo = appDomainInfo ?? new AppDomainSetup();
            appDomainInfo.AppDomainManagerAssembly = typeof(PrimaryAppDomainManager).Assembly.FullName;
            appDomainInfo.AppDomainManagerType = typeof(PrimaryAppDomainManager).FullName;

            var appDomain = AppDomainManager.CreateDomainHelper(friendlyName, securityInfo, appDomainInfo);
            ((PrimaryAppDomainManager)appDomain.DomainManager).SetPrimaryDomainToSelf();
            _primaryDomain = appDomain;
            return appDomain;
        }

        /// &lt;summary&gt;
        /// Returns a new or existing application domain.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;friendlyName&quot;&gt;The friendly name of the domain.&lt;/param&gt;
        /// &lt;param name=&quot;securityInfo&quot;&gt;An object that contains evidence mapped through the security policy to establish a top-of-stack permission set.&lt;/param&gt;
        /// &lt;param name=&quot;appDomainInfo&quot;&gt;An object that contains application domain initialization information.&lt;/param&gt;
        /// &lt;returns&gt;A new or existing application domain.&lt;/returns&gt;
        /// &lt;PermissionSet&gt;
        /// 	&lt;IPermission class=&quot;System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089&quot; version=&quot;1&quot; Flags=&quot;ControlEvidence, ControlAppDomain, Infrastructure&quot;/&gt;
        /// &lt;/PermissionSet&gt;
        public override AppDomain CreateDomain(string friendlyName, Evidence securityInfo, AppDomainSetup appDomainInfo)
        {
            appDomainInfo = appDomainInfo ?? new AppDomainSetup();
            appDomainInfo.AppDomainManagerAssembly = typeof(PrimaryAppDomainManager).Assembly.FullName;
            appDomainInfo.AppDomainManagerType = typeof(PrimaryAppDomainManager).FullName;

            var appDomain = base.CreateDomain(friendlyName, securityInfo, appDomainInfo);
            ((PrimaryAppDomainManager)appDomain.DomainManager).SetPrimaryDomain(_primaryDomain);

            return appDomain;
        }
    }</pre>
<p>Note that it isn&#8217;t possible to use the &#8216;real&#8217; primary domain for anything; otherwise any domains created by it would be outside of the control of PrimaryAppDomainManager. Using this we can implement cross-domain thread-safe singleton class:</p>
<pre class="brush: csharp;">    /// &lt;summary&gt;
    /// Represents a cross-domain singleton.
    /// &lt;/summary&gt;
    /// &lt;remarks&gt;
    /// The singleton always lives in the primary domain.
    /// &lt;/remarks&gt;
    public abstract class CrossDomainSingleton&lt;TSelf&gt; : MarshalByRefObject
        where TSelf : CrossDomainSingleton&lt;TSelf&gt;, new()
    {
        // Used to alter the primary domain
        // in a thread safe-manner.
        private class Locker : MarshalByRefObject
        {
            private static object _lock = new object();
            public void Lock()
            {
                Monitor.Enter(_lock);
            }

            public void Exit()
            {
                Monitor.Exit(_lock);
            }

            public TSelf GetSelf()
            {
                // At this point we always have a lock;
                // just check that the instance is still null.
                if (_instance == null)
                {
                    _instance = new TSelf();
                }
                return _instance;
            }
        }

        private static TSelf _instance;
        /// &lt;summary&gt;
        /// Gets the instance.
        /// &lt;/summary&gt;
        /// &lt;value&gt;The instance.&lt;/value&gt;
        public static TSelf Instance
        {
            get
            {
                Contract.Ensures(Contract.Result&lt;TSelf&gt;() != null);
                if (_instance == null)
                {
                    SetInstance();
                }
                return _instance;
            }
        }

        private static void SetInstance()
        {
            Locker locker;
            if (PrimaryAppDomainManager.IsPrimaryDomain)
            {
                // No need for the remoting.
                locker = new Locker();
            }
            else
            {
                // Get the primary domain locker.
                locker = PrimaryAppDomainManager.PrimaryDomain.CreateInstanceAndUnwrap&lt;Locker&gt;();
            }

            try
            {
                locker.Lock();
                _instance = locker.GetSelf();
            }
            finally
            {
                locker.Exit();
            }
        }
    }</pre>
<p>You will need the following extension method somewhere:</p>
<pre class="brush: csharp;">/// &lt;summary&gt;
/// Creates a new instance of the specified type.
/// &lt;/summary&gt;
/// &lt;typeparam name=&quot;T&quot;&gt;The type of object to create.&lt;/typeparam&gt;
/// &lt;param name=&quot;appDomain&quot;&gt;The app domain.&lt;/param&gt;
/// &lt;returns&gt;A proxy for the new object.&lt;/returns&gt;
public static T CreateInstanceAndUnwrap&lt;T&gt;(this AppDomain appDomain)
{
    Contract.Requires&lt;ArgumentNullException&gt;(appDomain != null);
    Contract.Ensures(Contract.Result&lt;T&gt;() != null);

    var res = (T)appDomain.CreateInstanceAndUnwrap(typeof(T));
    return res;
}</pre>
<p>In order for all of this to work you need to make sure that your &#8216;real&#8217; primary domain is never used:</p>
<pre class="brush: csharp;">    class Program : MarshalByRefObject
    {
        /// &lt;summary&gt;
        /// The main entry point for the application.
        /// &lt;/summary&gt;
        static void Main(string[] args)
        {
            new Program().Run(args);
        }

        void Run(string[] args)
        {
            var domain = PrimaryAppDomainManager.CreateInitialDomain(&quot;PrimaryDomain&quot;, null, null);
            if (domain == null)
            {
                // Original Main() code here.
            }
            else
            {
                domain.CreateInstanceAndUnwrap&lt;Program&gt;().Run(args);
            }
        }
    }</pre>
<p>And the singleton classes are simple (thanks to the generic-TSelf trick; which I need to do a post on some time):</p>
<pre class="brush: csharp;">    class Foo : CrossDomainSingleton&lt;Foo&gt;
    {
        public Foo()
        {
            // Singleton initializer.
        }
    }</pre>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2010/11/cross-domain-singleton-in-c/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>WCF and Windows/Custom Auth</title>
		<link>http://jonathan.dickinsons.co.za/blog/2010/10/wcf-windows-custom-aut/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2010/10/wcf-windows-custom-aut/#comments</comments>
		<pubDate>Thu, 28 Oct 2010 08:25:40 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=212</guid>
		<description><![CDATA[Allowing a WCF web client (hosted in IIS) to send either Windows Authentication or Custom Authentication.]]></description>
			<content:encoded><![CDATA[<p>I was tasked with writing an IIS only WCF service. It was required to bind to SOAP (basicHttpBinding) or to REST (webHttpBinding); furthermore both Windows and Basic (rewritten to authenticate against our server, so it is classed as custom) need to be supported.</p>
<p>Initially the custom module would prevent Windows credentials from being accepted. The browser would enter the login dialog loop with valid credentials. This is because the basic module was eagerly checking the Authorization header. I had to make the following fix:</p>
<pre class="brush: csharp;">protected bool IsHeaderPresent
{
    get
    {
        HttpContext context = HttpContext.Current;
        string authHeader = context.Request.Headers["Authorization"];
        return (!string.IsNullOrEmpty(authHeader))
                 &#038;&#038; authHeader.StartsWith("Basic"); // Added this line.
    }
}</pre>
<p>This property is used in the AuthenticateRequest event handler. What you need to do is short-circuit your entire method, as such:</p>
<pre class="brush: csharp;">void context_AuthenticateRequest(object sender, EventArgs e)
{
    if (IsHeaderPresent)
    {
        // Previous method body
    }
}</pre>
<p>Next you need to enable Windows Authentication in IIS. How you do this depends on which version of IIS you are using; and is trivial. You then need to add it to your web.config:</p>
<pre class="brush: xml;">&lt;system.web&gt;
   &lt;authentication mode="Windows" /&gt;
&lt;/system.web&gt;</pre>
<p>The custom authentication module I read indicated that the following needed to be added to the web.config; if you have something like it remove it:</p>
<pre class="brush: xml;">&lt;serviceAuthorization principalPermissionMode="Custom"&gt;
  &lt;authorizationPolicies&gt;
    &lt;add policyType="X.Services.Authentication.HttpContextIdentityPolicy, X.Services.Runtime" /&gt;
    &lt;add policyType="X.Services.Authentication.HttpContextPrincipalPolicy, X.Services.Runtime" /&gt;
  &lt;/authorizationPolicies&gt;
&lt;/serviceAuthorization&gt;</pre>
<p>Now you just need to look for your custom Identity/Principal; versus the Windows one and react accordingly. Good luck!</p>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2010/10/wcf-windows-custom-aut/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code Contracts</title>
		<link>http://jonathan.dickinsons.co.za/blog/2010/01/code-contracts/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2010/01/code-contracts/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 20:38:34 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Short]]></category>
		<category><![CDATA[XMPP Server 2010]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=179</guid>
		<description><![CDATA[I recently started using CodeContracts and have a few tips.]]></description>
			<content:encoded><![CDATA[<p>I have recently started using the <a href="http://research.microsoft.com/en-us/projects/contracts/">Microsoft CodeContracts</a> on a large scale. These have been a fantastic addition to my toolset; because when I get the green flag on my code I know that I am <em>pretty</em> safe (it is beta, after all). I had to migrate quite a bit of code into the contracts and found that it can be quite a daunting task. A few things that I have picked up are:</p>
<ul>
<li>If you are migrating existing code and worrying only about contracts, switch off background checking. Firstly, this means that the results you get are comprehensive and secondly because of the build time you will think twice about hitting that build key again. Long builds == fewer builds == more time thinking == better code.</li>
<li>Use code snippets. The ones provided by Microsoft are great! Think about creating your own or changing them. For example cren and cresn no longer throw ArgumentExceptions for me; they are both ArgumentNullExceptions. I also have snippets like create contract class for (cc &#8211; scaffolding for ContractClassFor) and contract class implementation (cci &#8211; ContractClass attributation).</li>
<li>Invariants are your friend. Figure out what state a class should really be in and depend on that rather than Contract.Requires everywhere.</li>
<li>A well placed Contract.Ensures will save you a lot of grief.</li>
<li>Don&#8217;t loose hope. It may seem like it&#8217;s daunting at first &#8211; but as you start thinking in terms of contracts things become a lot faster. A single well-thought out Contract call will often clear off 5 warnings (for the bigger projects).</li>
<li>Some classes can be skipped ([ContractVerification(false)]) &#8211; especially if they are internal. Don&#8217;t gung-ho and try and get everything in contracts; because sometimes they may be ill-suited for the task (and you would by &#8216;lying&#8217; just to get the stuff to pass). These situations are few and far between; but they are there.</li>
<li>New development = contracts. Full stop.</li>
</ul>
<p>Overall I am finding fewer and fewer Contract failures during each build. This is mainly because CodeContracts is getting me into a better and more disciplined mindset. It&#8217;s a great tool and I highly recommend it.</p>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2010/01/code-contracts/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Automatically Wrap BeginInvoke (dispatch)</title>
		<link>http://jonathan.dickinsons.co.za/blog/2009/12/automatically-wrap-begininvoke-dispatch/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2009/12/automatically-wrap-begininvoke-dispatch/#comments</comments>
		<pubDate>Mon, 14 Dec 2009 07:24:46 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tricks]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=165</guid>
		<description><![CDATA[Easily handle multi-threaded events in .Net WinForms.]]></description>
			<content:encoded><![CDATA[<p><em>C# supports implicit/explicit conversions to Delegates.</em></p>
<p>Yes, big news. I was very surprised when I gave this a shot. It&#8217;s really just one of those things you really don&#8217;t expect to work. So how does this help us? I am sure you are quite sick of writing the following code (the same stuff applies to WPF, you just need to access it via the Dispatch member):</p>
<pre class="brush: csharp;">
void _items_CollectionChanged(object sender, CollectionChangedEventArgs&lt;ConnectionListItem&gt; e)
{
    if (InvokeRequired)
    {
        Invoke(new EventHandler&lt;CollectionChangedEventArgs&lt;ConnectionListItem&gt;&gt;( _items_CollectionChanged ), sender, e);
        return;
    }

}
</pre>
<p>The &#8216;big news&#8217; allows us to do all the heavy lifting for the dispatch BeginInvoke in one simple class (this is a first try &#8211; I&#8217;ll get round to reviewing it later on).</p>
<pre class="brush: csharp;">
    /// &lt;summary&gt;
    /// Represent a wrapper for a delegate.
    /// &lt;/summary&gt;
    /// &lt;typeparam name="T"&gt;The type of event args.&lt;/typeparam&gt;
    public class InvokeEventWrapper&lt;T&gt;
        where T : EventArgs
    {
        private EventHandler&lt;T&gt; _apparantHandler;
        private EventHandler&lt;T&gt; _rawHandler;
        private Control _parent;

        /// &lt;summary&gt;
        /// Initializes a new instance of the &lt;see cref="InvokeDelegateWrapper&lt;T&gt;"/&gt; class.
        /// &lt;/summary&gt;
        /// &lt;param name="parent"&gt;The parent.&lt;/param&gt;
        /// &lt;param name="handler"&gt;The handler.&lt;/param&gt;
        public InvokeEventWrapper(EventHandler&lt;T&gt; handler)
            : this(null, handler)
        {

        }

        /// &lt;summary&gt;
        /// Initializes a new instance of the &lt;see cref="InvokeDelegateWrapper&lt;T&gt;"/&gt; class.
        /// &lt;/summary&gt;
        /// &lt;param name="parent"&gt;The parent.&lt;/param&gt;
        /// &lt;param name="handler"&gt;The handler.&lt;/param&gt;
        public InvokeEventWrapper(Control parent, EventHandler&lt;T&gt; handler)
        {
            if (handler == null)
                throw new ArgumentNullException("handler");
            if (parent == null)
                parent = (Control)handler.Target;

            _parent = parent;
            _rawHandler = handler;
            _apparantHandler = new EventHandler&lt;T&gt;(Raise);
        }

        /// &lt;summary&gt;
        /// Performs an implicit conversion from &lt;see cref="SharedTerminals.InvokeDelegateWrapper&lt;T&gt;"/&gt; to &lt;see cref="System.EventHandler&lt;T&gt;"/&gt;.
        /// &lt;/summary&gt;
        /// &lt;param name="wrapper"&gt;The wrapper.&lt;/param&gt;
        /// &lt;returns&gt;The result of the conversion.&lt;/returns&gt;
        public static implicit operator EventHandler&lt;T&gt;(InvokeEventWrapper&lt;T&gt; wrapper)
        {
            return wrapper._apparantHandler;
        }

        /// &lt;summary&gt;
        /// Raises the event.
        /// &lt;/summary&gt;
        /// &lt;param name="sender"&gt;The sender.&lt;/param&gt;
        /// &lt;param name="e"&gt;The e.&lt;/param&gt;
        private void Raise(object sender, T e)
        {
            if (_parent.InvokeRequired)
                _parent.BeginInvoke(_rawHandler, sender, e);
            else
                _rawHandler(sender, e);
        }
    }
</pre>
<p>Using it is pretty simple:</p>
<ol>
<li>Navigate to the event in Intellisense.</li>
<li>Type <em>+=</em>.</li>
<li>Press Tab.</li>
<li>Replace EventHandler with InvokeEventWrapper.</li>
</ol>
<p>So in the end all of that ugly code becomes:</p>
<pre class="brush: csharp;">
_items.CollectionChanged += new InvokeEventWrapper&lt;CollectionChangedEventArgs&lt;ConnectionListItem&gt;&gt;( _items_CollectionChanged );
</pre>
<p>You will need to hold onto a reference for that wrapper if you wish to unsubscribe from the event (one of the things I need to look at).</p>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2009/12/automatically-wrap-begininvoke-dispatch/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SSRS Timeout on SSL 443 &#8211; Resolved</title>
		<link>http://jonathan.dickinsons.co.za/blog/2009/10/ssrs-timeout-on-ssl-443-resolved/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2009/10/ssrs-timeout-on-ssl-443-resolved/#comments</comments>
		<pubDate>Tue, 06 Oct 2009 16:32:45 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[SSRS]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=161</guid>
		<description><![CDATA[If you are getting either a 'The underlying connection was closed' or 'The operation has timed-out' error when deploying reports manually (add reference to web service) to SSRS via SSL on port 443 this fix may work for you.]]></description>
			<content:encoded><![CDATA[<h2>Manifestation of the Error</h2>
<p>If you attempt to connect to SSRS via the deployment webservice; when SSRS is running in SSL mode (specifically on port 443), you may get one of the following exceptions (which <strong>do not</strong> occur intermittently):</p>
<ul>
<li>The underlying connection was closed: An unexpected error occurred on a send.</li>
<li>The operation has timed-out.</li>
</ul>
<p>You might get it for other &#8220;The underlying connection was closed&#8221; errors, but I have not confirmed that. The issue occurs mainly when you try to upload report definitions that are over approximately 100kb.</p>
<h2>The Solution</h2>
<p>Let me tell you straight up &#8211; there is no reason to disable SSL or alter timeouts. The first thing you want to do is to add a new class to your project; I called mine SslReportService. Implement ReportingService2005 from your WebService reference. You can then override GetWebRequest(Uri) without worrying about your changes being lost of you update your web reference.</p>
<p>Then, in a nutshell:</p>
<pre class="brush: csharp;">class SslReportService : ReportService.ReportingService2005
{
  protected override System.Net.WebRequest GetWebRequest(Uri uri)
  {
    var res = (HttpWebRequest)base.GetWebRequest(uri);
    res.SendChunked = true;
    return res;
  }
}</pre>
<p>Your mileage may vary; so if this turns up nothing <a href="http://blogs.msdn.com/engelsr/articles/497902.aspx">Engels Rajangam</a> has another helpful post on this issue. You might want to read up on this property on <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.sendchunked.aspx">MSDN</a> and <a href="http://www.wintellect.com/CS/blogs/jeffreyr/archive/2009/02/08/httpwebrequest-its-request-stream-and-sending-data-in-chunks.aspx">a pretty good blog post</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2009/10/ssrs-timeout-on-ssl-443-resolved/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>XLinQ Serialization</title>
		<link>http://jonathan.dickinsons.co.za/blog/2009/08/xlinq-serialization/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2009/08/xlinq-serialization/#comments</comments>
		<pubDate>Mon, 03 Aug 2009 09:19:29 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Short]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/2009/08/xlinq-serialization/</guid>
		<description><![CDATA[XmlSerializer suprisingly supports List<xelement>.</xelement>]]></description>
			<content:encoded><![CDATA[<p>Just found out that Microsoft actually had the foresight to support the following scenario:</p>
<pre class="brush: csharp;">/// &lt;summary&gt;
/// Gets the unknown elements as a &lt;see cref="List{XElement}"/&gt;.
/// &lt;/summary&gt;
[XmlAnyElement]
public List&lt;XElement&gt; UnknownElements
{
    get;
    set;
}</pre>
<p>Fantastic (undocumented) news.</p>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2009/08/xlinq-serialization/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Remove System Menu Icon in WPF</title>
		<link>http://jonathan.dickinsons.co.za/blog/2009/07/remove-system-menu-icon-in-wpf/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2009/07/remove-system-menu-icon-in-wpf/#comments</comments>
		<pubDate>Thu, 16 Jul 2009 13:40:47 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code 7 Contest]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Top Hacks]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/2009/07/remove-system-menu-icon-in-wpf/</guid>
		<description><![CDATA[Howto remove the caption bar in WPF.]]></description>
			<content:encoded><![CDATA[<p>I am entering the <a href="http://code7contest.com" target="_blank">Code7 Contest</a> and part of my project is to mimic the network notification icon.</p>
<div id="attachment_61" class="wp-caption aligncenter" style="width: 312px"><a href="http://jonathan.dickinsons.co.za/blog/wp-content/uploads/2009/07/Windows7Network.png"><img class="size-full wp-image-61" title="Windows 7 Network Menu" src="http://jonathan.dickinsons.co.za/blog/wp-content/uploads/2009/07/Windows7Network.png" alt="Windows 7 Network Menu" width="302" height="454" /></a><p class="wp-caption-text">Windows 7 Network Menu</p></div>
<p>The trick to this is to set the caption of the window to null (not empty string) and remove the system menu – at least as far as Windows Forms goes. WPF doesn’t let you do this. I had a few options:</p>
<ul>
<li>Implement a template to mimic the real window template. Not too sure how glass would work here.</li>
<li>Use API calls to do it instead.</li>
</ul>
<p>The second option seemed to be more sensible. As it turns out Windows Forms is doing quite a bit of heavy lifting under the covers – you don’t set the title to null; you actually need to remove the caption (Windows Forms does this for you). In the end it’s as simple as clearing two style flags for the Window.</p>
<div class="code-header">Remove Caption in WPF</div>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:63529eaa-0ca6-4208-853f-10b57d792814" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">private class NativeMethods
{
  [DllImport("user32.dll", EntryPoint = "SetWindowLong")]
  static extern IntPtr SetWindowLongPtr32(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
  [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr")]
  static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
  public static IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong)
  {
      if (IntPtr.Size == 8)
          return SetWindowLongPtr64(hWnd, nIndex, dwNewLong);
      else
          return SetWindowLongPtr32(hWnd, nIndex, dwNewLong);
  }

  [DllImport("user32.dll", EntryPoint = "GetWindowLong")]
  private static extern IntPtr GetWindowLongPtr32(IntPtr hWnd, int nIndex);
  [DllImport("user32.dll", EntryPoint = "GetWindowLongPtr")]
  private static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, int nIndex);
  public static IntPtr GetWindowLong(IntPtr hWnd, int nIndex)
  {
      if (IntPtr.Size == 8)
          return GetWindowLongPtr64(hWnd, nIndex);
      else
          return GetWindowLongPtr32(hWnd, nIndex);
  }

  const int GWL_STYLE = (-16);
  const int WS_SYSMENU = 0x00080000;
  const int WS_CAPTION = 0x00C00000;

  public static void RemoveMenu(IntPtr hwnd)
  {
      int currentStyle = GetWindowLong(hwnd, GWL_STYLE).ToInt32();
      currentStyle &amp;= ~WS_SYSMENU;
      currentStyle &amp;= ~WS_CAPTION;
      int ret = SetWindowLong(hwnd, GWL_STYLE, new IntPtr(currentStyle)).ToInt32();
  }

}</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>You simply call that from OnSourceInitialized.</p>
<div class="code-header">How to use the method</div>
<div id="scid:DFDE9937-D816-47f4-A306-7B60D5CE5AC0:bac81a08-a2b0-4291-9490-ade63e6320ea" class="wlWriterEditableSmartContent" style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px">
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">protected override void OnSourceInitialized(EventArgs e)
{
  base.OnSourceInitialized(e);
  WindowInteropHelper wih = new WindowInteropHelper(this);
  NativeMethods.RemoveMenu(wih.Handle);
}</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>And you will get the following result:</p>
<div id="attachment_63" class="wp-caption aligncenter" style="width: 309px"><a href="http://jonathan.dickinsons.co.za/blog/wp-content/uploads/2009/07/Windows7Mimic.png"><img class="size-full wp-image-63" title="Windows 7 Mimic'ed Menu" src="http://jonathan.dickinsons.co.za/blog/wp-content/uploads/2009/07/Windows7Mimic.png" alt="Windows 7 Mimic'ed Menu" width="299" height="364" /></a><p class="wp-caption-text">Windows 7 Mimic&#39;ed Menu</p></div>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2009/07/remove-system-menu-icon-in-wpf/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Wrapping on Specific Characters</title>
		<link>http://jonathan.dickinsons.co.za/blog/2009/06/wrapping-on-specific-characters/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2009/06/wrapping-on-specific-characters/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 08:27:16 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Migrated]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Top Hacks]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=22</guid>
		<description><![CDATA[How to inform GDI+ that a certain character can be automatically wrapped.]]></description>
			<content:encoded><![CDATA[<p>Recently on a project I was working I needed to wrap on backslash characters  (file and registry paths). Unfortunately the only help StringFormat can provide  is intelligent trimming (e.g. C:\Program Files\&#8230;.\Foo) and not wrapping  options.</p>
<p>I wasn&#8217;t so keen on writing my own text drawing/wrapping algorithm, but how  to wrap at a specific character? One of my co-workers gave me the spark I needed  to figure the whole thing out: use spaces. Now, that is a hack that is visible  to the user, and is plain nasty (C:\ Foo\ Bar just doesn&#8217;t cut it) &#8211; but we live  in a unicode world; and unicode has some very interesting characters. The one  that helps in this situation is ZERO WIDTH SPACE (U + 200B).</p>
<p>How do we use it? Simply do the following:</p>
<div class="code-header">Wrap after backslashes</div>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; "> string wrappable = unwrappable.Replace("\\", "\\\u200B");</pre>
<p>That will allow wraps after backslashes. I am sure you could find non-wrap  counterparts for most wrap characters as well (e.g. NON BREAK SPACE). I started  writing a util class to allow you to wrap before/after any character (that  doesn&#8217;t usually wrap) or not wrap before/after a character (that  usually wraps) - but it was decidedly boring; so I never finished it.</p>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2009/06/wrapping-on-specific-characters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unbox Enum as an Integral Value</title>
		<link>http://jonathan.dickinsons.co.za/blog/2009/06/unbox-enum-as-an-integral-value/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2009/06/unbox-enum-as-an-integral-value/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 08:25:45 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Migrated]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=20</guid>
		<description><![CDATA[How to unbox an enum without needing to know its base type.]]></description>
			<content:encoded><![CDATA[<p>I needed a way to get the integral value of an System.Enum that is boxed. The  solution wasn&#8217;t immediately obvious after my experimentation mainly because:</p>
<ul>
<li>My enum was derived from byte (and I was trying to cast it to an int).</li>
<li>My .Net jitsu wasn&#8217;t up to scratch.</li>
</ul>
<p>Lucky thanks to a friendly guy called <a href="http://stackoverflow.com/questions/746905/get-integral-value-of-boxed-enum/746928#746928" target="_blank">Guffa</a> I managed to create generic solution.</p>
<p>As it turns out you can unbox an enum value to its base type. As such the following can be unboxed to an uint.</p>
<div class="code-header">Unboxing an enum when the underlying type is known</div>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">
struct FoolishStruct : uint
{
   Gluttony,
   Pride,
   Jealousy
}

object sinner = FoolishStruct.Gluttony;
uint value = (uint)sinner; // This works.
</pre>
<p>This gave me the necessary knowledge to hash out the following solution:</p>
<div class="code-header">Unboxing an enum when the underlying type is not known</div>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">
    /// &lt;summary&gt;
    /// Gets the integral value of an enum.
    /// &lt;/summary&gt;
    /// &lt;param name="value"&gt;The enum to get the integral value of.&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    public static T ToIntegral&lt;T&gt;(this object value)
    {
        if(object.ReferenceEquals(value, null))
            throw new ArgumentNullException("value");
        Type rootType = value.GetType();
        if (!rootType.IsEnum)
            throw new ArgumentOutOfRangeException("value", "value must be a boxed enum.");
        Type t = Enum.GetUnderlyingType(rootType);

        switch (t.Name.ToUpperInvariant())
        {
            case "SBYTE":
                return (T)Convert.ChangeType((sbyte) value, typeof(T));
            case "BYTE":
                return (T) Convert.ChangeType((byte) value, typeof(T));
            case "INT16":
                return (T) Convert.ChangeType((Int16) value, typeof(T));
            case "UINT16":
                return (T) Convert.ChangeType((UInt16) value, typeof(T));
            case "INT32":
                return (T) Convert.ChangeType((Int32) value, typeof(T));
            case "UINT32":
                return (T) Convert.ChangeType((UInt32) value, typeof(T));
            case "INT64":
                return (T) Convert.ChangeType((Int64) value, typeof(T));
            case "UINT64":
                return (T) Convert.ChangeType((UInt64) value, typeof(T));
            default:
                throw new NotSupportedException();
        }
    }
</pre>
<p>HTH.</p>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2009/06/unbox-enum-as-an-integral-value/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to close a XML Element using XmlTextWriter</title>
		<link>http://jonathan.dickinsons.co.za/blog/2009/06/how-to-close-a-xml-element-using-xmltextwriter/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2009/06/how-to-close-a-xml-element-using-xmltextwriter/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 08:20:34 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Migrated]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Top Hacks]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=12</guid>
		<description><![CDATA[You can't close an XML element using the XmlTextWriter class unless you write a conflicting state to the document (e.g. Comment). Here is how to get around that.]]></description>
			<content:encoded><![CDATA[<p>Recently with my forays into the XMPP land, I have needed to handle the case  of writing out the following XML (as is, without the closing tag):</p>
<div class="code-header">Single opening tag</div>
<pre class="brush: xml; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">&lt;stream:stream xmlns="http://etherx.jabber.org/streams"  xmlns="jabber:client" from="bob" to="server"&gt;</pre>
<p>Note that the tag is closed. The .Net XML writer keeps that open until you  try and go into a conflicting state such as a new start tag, comment, PI, or  such. Calling Flush() simply doesn&#8217;t work.</p>
<p>My previous methodology used a comment to close it. Thus something like this  was sent out:</p>
<div class="code-header">Using a comment to transfer state</div>
<pre class="brush: xml; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">&lt;stream:stream xmlns="http://etherx.jabber.org/streams"  xmlns="jabber:client" from="bob" to="server"&gt;&lt;!-- Start Stream --&gt;</pre>
<p>Not the best. Some clients dont like comments and the XMPP specification says  that comments SHOULD NOT be used (note, not MUST NOT), so some parsers fall  over.</p>
<p>I finally decided to give fixing it a go. I created a root XML writer class  that had one abstract method: CompleteElement(). I won&#8217;t paste that class in  because it is trivial. I cracked open Reflector and figured out if there was a  common method in XmlTextWriter that handles this. I was in luck, there was  (AutoComplete)! My first attempt simply reflected over the XmlTextWriter and  found the method, enum and enum field. It didn&#8217;t work. XmlWriter.Create() hands  out XmlWellFormedWriters (you can&#8217;t instantiate these directly, the class is  internal). So I looked at it using Reflector and I was in luck again! The only  thing that is different is the name of the method (AdvanceState) and everything  else was exactly the same.</p>
<p>Here it is (most of it is purely wrappers):</p>
<div class="code-header">Complete Streaming XML Writer</div>
<pre class="brush: csharp; gutter: true; first-line: 1; tab-size: 4;  toolbar: true; ">    /// &lt;summary&gt;
    /// Represents a streaming xml text writer.
    /// &lt;/summary&gt;
    public class StreamingXmlTextWriter : StreamingXmlWriter
    {
        private static object __autoCompleteComment;
        private static MethodInfo __autoCompleteMethod;

        static StreamingXmlTextWriter()
        {
            // Get the type.
            Type wellFormedWriter = typeof(XmlTextWriter).Assembly.GetType("System.Xml.XmlWellFormedWriter");

            // Find the method.
            __autoCompleteMethod = wellFormedWriter.GetMethod("AdvanceState", BindingFlags.Instance | BindingFlags.NonPublic);

            // Find the argument.
            Type tokenEnum = wellFormedWriter.GetNestedType("Token", BindingFlags.NonPublic);
            FieldInfo tokenField = tokenEnum.GetField("Comment", BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            __autoCompleteComment = tokenField.GetValue(null);
        }

        private XmlWriter writer;
        public StreamingXmlTextWriter(Stream stream, Encoding encoding)
            : base(stream, encoding)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = encoding;
            settings.OmitXmlDeclaration = true;

            writer = XmlWriter.Create(stream, settings);
        }

        #region Wrapped Methods
        public override void Close()
        {
            writer.Close();
        }

        public override void Flush()
        {
            writer.Flush();
        }

        public override string LookupPrefix(string ns)
        {
            return writer.LookupPrefix(ns);
        }

        public override void WriteBase64(byte[] buffer, int index, int count)
        {
            if (skippedAttribute)
                return;

            writer.WriteBase64(buffer, index, count);
        }

        public override void WriteCData(string text)
        {
            if (skippedAttribute)
                return;

            writer.WriteCData(text);
        }

        public override void WriteCharEntity(char ch)
        {
            if (skippedAttribute)
                return;

            writer.WriteCharEntity(ch);
        }

        public override void WriteChars(char[] buffer, int index, int count)
        {
            if (skippedAttribute)
                return;

            writer.WriteChars(buffer, index, count);
        }

        public override void WriteComment(string text)
        {
            writer.WriteComment(text);
        }

        public override void WriteDocType(string name, string pubid, string sysid, string subset)
        {
            writer.WriteDocType(name, pubid, sysid, subset);
        }

        public override void WriteEndAttribute()
        {
            if (skippedAttribute)
            {
                skippedAttribute = false;
                return;
            }

            writer.WriteEndAttribute();
        }

        public override void WriteEndDocument()
        {
            writer.WriteEndDocument();
        }

        public override void WriteEndElement()
        {
            writer.WriteEndElement();
        }

        public override void WriteEntityRef(string name)
        {
            if (skippedAttribute)
                return;

            writer.WriteEntityRef(name);
        }

        public override void WriteFullEndElement()
        {
            writer.WriteFullEndElement();
        }

        public override void WriteProcessingInstruction(string name, string text)
        {
            writer.WriteProcessingInstruction(name, text);
        }

        public override void WriteRaw(string data)
        {
            writer.WriteRaw(data);
        }

        public override void WriteRaw(char[] buffer, int index, int count)
        {
            writer.WriteRaw(buffer, index, count);
        }

        private bool skippedAttribute;
        public override void WriteStartAttribute(string prefix, string localName, string ns)
        {
            // XSI/XSD must not be emitted.
            if (prefix == "xmlns" || localName == "xmlns")
            {
                if (localName == "xsi" || localName == "xsd")
                {
                    skippedAttribute = true;
                    return;
                }

                ApplyNamespace(prefix, localName, ref ns);
            }
            writer.WriteStartAttribute(prefix, localName, ns);
        }

        public override void WriteStartDocument(bool standalone)
        {
            writer.WriteStartDocument(standalone);
        }

        public override void WriteStartDocument()
        {
            writer.WriteStartDocument();
        }

        public override void WriteStartElement(string prefix, string localName, string ns)
        {
            writer.WriteStartElement(prefix, localName, ns);
        }

        public override System.Xml.WriteState WriteState
        {
            get { return writer.WriteState; }
        }

        public override void WriteString(string text)
        {
            if (skippedAttribute)
                return;

            writer.WriteString(text);
        }

        public override void WriteSurrogateCharEntity(char lowChar, char highChar)
        {
            if (skippedAttribute)
                return;

            writer.WriteSurrogateCharEntity(lowChar, highChar);
        }

        public override void WriteWhitespace(string ws)
        {
            if (skippedAttribute)
                return;

            writer.WriteWhitespace(ws);
        }

        public override XmlWriterSettings Settings
        {
            get
            {
                return writer.Settings;
            }
        }

        public override string XmlLang
        {
            get
            {
                return writer.XmlLang;
            }
        }

        public override XmlSpace XmlSpace
        {
            get
            {
                return writer.XmlSpace;
            }
        }
        #endregion

        public override void CompleteElement()
        {
            PerformAutoComplete();
        }

        private void PerformAutoComplete()
        {
            __autoCompleteMethod.Invoke(writer, new object[] { __autoCompleteComment });
        }
    }</pre>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2009/06/how-to-close-a-xml-element-using-xmltextwriter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

