<?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>Adam O&#039;Neil&#039;s C#.NET Blog</title>
	<atom:link href="http://www.seesharpdot.net/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.seesharpdot.net</link>
	<description>A place to put all those useful code blocks</description>
	<lastBuildDate>Wed, 13 Mar 2013 15:32:52 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Generic delimited parsing algorithm</title>
		<link>http://www.seesharpdot.net/?p=245</link>
		<comments>http://www.seesharpdot.net/?p=245#comments</comments>
		<pubDate>Tue, 12 Mar 2013 15:34:14 +0000</pubDate>
		<dc:creator>Adam O'Neil</dc:creator>
				<category><![CDATA[C# Development]]></category>

		<guid isPermaLink="false">http://www.seesharpdot.net/?p=245</guid>
		<description><![CDATA[Hi all, You can use the following extension method to parse any string that is split by a delimiter. It will take care of most issues associated with splitting strings (quotes, etc) and works very well in almost every scenario I have used it in. Good one for the library of extension methods, definitely. &#160;&#160;&#160; [...]]]></description>
				<content:encoded><![CDATA[<p>Hi all,</p>
<p>You can use the following extension method to parse any string that is split by a delimiter. It will take care of most issues associated with splitting strings (quotes, etc) and works very well in almost every scenario I have used it in.</p>
<p>Good one for the library of extension methods, definitely.</p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: gray;">///</span><span style="color: green;"> </span><span style="color: gray;">&lt;summary&gt;</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: gray;">///</span><span style="color: green;"> This method will attepmt to parse the string into its delimited parts, taking a delimiter string as a parameter.</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: gray;">///</span><span style="color: green;"> </span><span style="color: gray;">&lt;/summary&gt;</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: gray;">///</span><span style="color: green;"> </span><span style="color: gray;">&lt;param name=&quot;strLine&quot;&gt;</span><span style="color: green;">The string to parse.</span><span style="color: gray;">&lt;/param&gt;</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: gray;">///</span><span style="color: green;"> </span><span style="color: gray;">&lt;param name=&quot;fieldDelimiter&quot;&gt;</span><span style="color: green;">The string used as a delimiter in the parse string.</span><span style="color: gray;">&lt;/param&gt;</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: gray;">///</span><span style="color: green;"> </span><span style="color: gray;">&lt;returns&gt;&lt;/returns&gt;</span></p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">static</span> <span style="color: #2b91af;">IEnumerable</span>&lt;<span style="color: blue;">string</span>&gt; ParseDelimited(<span style="color: blue;">this</span> <span style="color: blue;">string</span> strLine, <span style="color: blue;">string</span> fieldDelimiter)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">string</span> separatorEscaped = <span style="color: #2b91af;">Regex</span>.Escape(fieldDelimiter);</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">string</span> regularExpression = <span style="color: #a31515;">@&quot;^(?:&quot;&quot;(?&lt;item&gt;[^&quot;&quot;]*)&quot;&quot;|(?&lt;item&gt;[^{0}]*))(?:{0}(?:&quot;&quot;(?&lt;item&gt;[^&quot;&quot;]*)&quot;&quot;|(?&lt;item&gt;[^{0}]*)))*$&quot;</span>;</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> regex = <span style="color: blue;">new</span> <span style="color: #2b91af;">Regex</span>(<span style="color: blue;">string</span>.Format(regularExpression, separatorEscaped));</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> split = regex</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; .Match(strLine)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; .Groups[<span style="color: #a31515;">&quot;item&quot;</span>]</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; .Captures</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; .Cast&lt;<span style="color: #2b91af;">Capture</span>&gt;()</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; .Select(c =&gt; c.Value)</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; .ToArray();</p>
<p style="margin: 0px;">&nbsp;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> split;</p>
<p style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.seesharpdot.net/?feed=rss2&#038;p=245</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FTP &#8211; Get directory listing</title>
		<link>http://www.seesharpdot.net/?p=242</link>
		<comments>http://www.seesharpdot.net/?p=242#comments</comments>
		<pubDate>Tue, 12 Mar 2013 15:30:28 +0000</pubDate>
		<dc:creator>Adam O'Neil</dc:creator>
				<category><![CDATA[C# Development]]></category>
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.seesharpdot.net/?p=242</guid>
		<description><![CDATA[Haven&#8217;t written anything on here for a while &#8211; so I am going to start getting back on it. Here&#8217;s some nice code to get a directory listing from FTP. You get back a list of FTPListDetail objects which can be used to pass to further implementations, such as a download / downloadasync etc. It [...]]]></description>
				<content:encoded><![CDATA[<p>Haven&#8217;t written anything on here for a while &#8211; so I am going to start getting back on it.</p>
<p>Here&#8217;s some nice code to get a directory listing from FTP. You get back a list of FTPListDetail objects which can be used to pass to further implementations, such as a download / downloadasync etc. It uses some nice regex to parse the FTP response.</p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">        <span style="color: gray;">///</span><span style="color: gray;">&lt;summary&gt;</span></p>
<p style="margin: 0px;">        <span style="color: gray;">///</span><span style="color: green;"> Returns a directory listing of the remote FTP host.</span></p>
<p style="margin: 0px;">        <span style="color: gray;">///</span><span style="color: gray;">&lt;/summary&gt;</span></p>
<p style="margin: 0px;">        <span style="color: gray;">///</span><span style="color: gray;">&lt;returns&gt;&lt;/returns&gt;</span></p>
<p style="margin: 0px;">        <span style="color: blue;">public</span> <span style="color: #2b91af;">IEnumerable</span>&lt;<span style="color: #2b91af;">FTPListDetail</span>&gt; GetDirectoryListing()</p>
<p style="margin: 0px;">        {</p>
<p style="margin: 0px;">            <span style="color: blue;">var</span> result = <span style="color: blue;">new</span> <span style="color: #2b91af;">StringBuilder</span>();</p>
<p style="margin: 0px;">            <span style="color: blue;">var</span> request = GetWebRequest(<span style="color: #2b91af;">WebRequestMethods</span>.<span style="color: #2b91af;">Ftp</span>.ListDirectoryDetails);</p>
<p style="margin: 0px;">            <span style="color: blue;">using</span> (<span style="color: blue;">var</span> response = request.GetResponse())</p>
<p style="margin: 0px;">            {</p>
<p style="margin: 0px;">                <span style="color: blue;">using</span> (<span style="color: blue;">var</span> reader = <span style="color: blue;">new</span> <span style="color: #2b91af;">StreamReader</span>(response.GetResponseStream()))</p>
<p style="margin: 0px;">                {</p>
<p style="margin: 0px;">                    <span style="color: blue;">string</span> line = reader.ReadLine();</p>
<p style="margin: 0px;">                    <span style="color: blue;">while</span> (line != <span style="color: blue;">null</span>)</p>
<p style="margin: 0px;">                    {</p>
<p style="margin: 0px;">                        result.Append(line);</p>
<p style="margin: 0px;">                        result.Append(<span style="color: #a31515;">&#8220;\n&#8221;</span>);</p>
<p style="margin: 0px;">                        line = reader.ReadLine();</p>
<p style="margin: 0px;">                    }</p>
<p style="margin: 0px;">                    result.Remove(result.ToString().LastIndexOf(<span style="color: #a31515;">&#8216;\n&#8217;</span>), 1);</p>
<p style="margin: 0px;">                    <span style="color: blue;">var</span> results = result.ToString().Split(<span style="color: #a31515;">&#8216;\n&#8217;</span>);</p>
<p style="margin: 0px;">                    <span style="color: blue;">string</span> regex =</p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;^&#8221;</span> +               <span style="color: green;">//# Start of line</span></p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;(?&lt;dir&gt;[\-ld])&#8221;</span> +          <span style="color: green;">//# File size           </span></p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;(?&lt;permission&gt;[\-rwx]{9})&#8221;</span> +            <span style="color: green;">//# Whitespace          \n</span></p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;\s+&#8221;</span> +            <span style="color: green;">//# Whitespace          \n</span></p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;(?&lt;filecode&gt;\d+)&#8221;</span> +</p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;\s+&#8221;</span> +            <span style="color: green;">//# Whitespace          \n</span></p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;(?&lt;owner&gt;\w+)&#8221;</span> +</p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;\s+&#8221;</span> +            <span style="color: green;">//# Whitespace          \n</span></p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;(?&lt;group&gt;\w+)&#8221;</span> +</p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;\s+&#8221;</span> +            <span style="color: green;">//# Whitespace          \n</span></p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;(?&lt;size&gt;\d+)&#8221;</span> +</p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;\s+&#8221;</span> +            <span style="color: green;">//# Whitespace          \n</span></p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;(?&lt;month&gt;\w{3})&#8221;</span> +          <span style="color: green;">//# Month (3 letters)   \n</span></p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;\s+&#8221;</span> +            <span style="color: green;">//# Whitespace          \n</span></p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;(?&lt;day&gt;\d{1,2})&#8221;</span> +        <span style="color: green;">//# Day (1 or 2 digits) \n</span></p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;\s+&#8221;</span> +            <span style="color: green;">//# Whitespace          \n</span></p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;(?&lt;timeyear&gt;[\d:]{4,5})&#8221;</span> +     <span style="color: green;">//# Time or year        \n</span></p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;\s+&#8221;</span> +            <span style="color: green;">//# Whitespace          \n</span></p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;(?&lt;filename&gt;(.*))&#8221;</span> +            <span style="color: green;">//# Filename            \n</span></p>
<p style="margin: 0px;">                        <span style="color: #a31515;">@&#8221;$&#8221;</span>;                <span style="color: green;">//# End of line</span></p>
<p style="margin: 0px;">                    <span style="color: blue;">foreach</span> (<span style="color: blue;">var</span> parsed <span style="color: blue;">in</span> results)</p>
<p style="margin: 0px;">                    {</p>
<p style="margin: 0px;">                        <span style="color: blue;">var</span> split = <span style="color: blue;">new</span> <span style="color: #2b91af;">Regex</span>(regex)</p>
<p style="margin: 0px;">                            .Match(parsed);</p>
<p style="margin: 0px;">                        <span style="color: blue;">var</span> dir = split.Groups[<span style="color: #a31515;">"dir"</span>].ToString();</p>
<p style="margin: 0px;">                        <span style="color: blue;">var</span> permission = split.Groups[<span style="color: #a31515;">"permission"</span>].ToString();</p>
<p style="margin: 0px;">                        <span style="color: blue;">var</span> filecode = split.Groups[<span style="color: #a31515;">"filecode"</span>].ToString();</p>
<p style="margin: 0px;">                        <span style="color: blue;">var</span> owner = split.Groups[<span style="color: #a31515;">"owner"</span>].ToString();</p>
<p style="margin: 0px;">                        <span style="color: blue;">var</span> group = split.Groups[<span style="color: #a31515;">"group"</span>].ToString();</p>
<p style="margin: 0px;">                        <span style="color: blue;">var</span> size = split.Groups[<span style="color: #a31515;">"size"</span>].ToString();</p>
<p style="margin: 0px;">                        <span style="color: blue;">var</span> month = split.Groups[<span style="color: #a31515;">"month"</span>].ToString();</p>
<p style="margin: 0px;">                        <span style="color: blue;">var</span> timeYear = split.Groups[<span style="color: #a31515;">"timeyear"</span>].ToString();</p>
<p style="margin: 0px;">                        <span style="color: blue;">var</span> day = split.Groups[<span style="color: #a31515;">"day"</span>].ToString();</p>
<p style="margin: 0px;">                        <span style="color: blue;">var</span> filename = split.Groups[<span style="color: #a31515;">"filename"</span>].ToString();</p>
<p style="margin: 0px;">                        <span style="color: blue;">yield</span> <span style="color: blue;">return</span> <span style="color: blue;">new</span> <span style="color: #2b91af;">FTPListDetail</span>()</p>
<p style="margin: 0px;">                        {</p>
<p style="margin: 0px;">                            Dir = dir,</p>
<p style="margin: 0px;">                            Filecode = filecode,</p>
<p style="margin: 0px;">                            Group = group,</p>
<p style="margin: 0px;">                            FullPath = CurrentRemoteDirectory + <span style="color: #a31515;">&#8220;/&#8221;</span> + filename,</p>
<p style="margin: 0px;">                            Name = filename,</p>
<p style="margin: 0px;">                            Owner = owner,</p>
<p style="margin: 0px;">                            Permission = permission,</p>
<p style="margin: 0px;">                            Size = size.ToInt() ?? 0,</p>
<p style="margin: 0px;">                            Month = month,</p>
<p style="margin: 0px;">                            Day = day,</p>
<p style="margin: 0px;">                            YearTime = timeYear</p>
<p style="margin: 0px;">                        };</p>
<p style="margin: 0px;">                    };</p>
<p style="margin: 0px;">                }</p>
<p style="margin: 0px;">            }</p>
<p style="margin: 0px;">        }</p>
</div>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">        <span style="color: gray;">///</span><span style="color: gray;">&lt;summary&gt;</span></p>
<p style="margin: 0px;">        <span style="color: gray;">///</span><span style="color: green;"> Get the request using a specific URI</span></p>
<p style="margin: 0px;">        <span style="color: gray;">///</span><span style="color: gray;">&lt;/summary&gt;</span></p>
<p style="margin: 0px;">        <span style="color: gray;">///</span><span style="color: gray;">&lt;param name=&#8221;method&#8221;&gt;&lt;/param&gt;</span></p>
<p style="margin: 0px;">        <span style="color: gray;">///</span><span style="color: gray;">&lt;param name=&#8221;uri&#8221;&gt;&lt;/param&gt;</span></p>
<p style="margin: 0px;">        <span style="color: gray;">///</span><span style="color: gray;">&lt;returns&gt;&lt;/returns&gt;</span></p>
<p style="margin: 0px;">        <span style="color: blue;">private</span> <span style="color: #2b91af;">FtpWebRequest</span> GetWebRequest(<span style="color: blue;">string</span> method, <span style="color: blue;">string</span> uri)</p>
<p style="margin: 0px;">        {</p>
<p style="margin: 0px;">            <span style="color: #2b91af;">Uri</span> serverUri = <span style="color: blue;">new</span> <span style="color: #2b91af;">Uri</span>(uri);</p>
<p style="margin: 0px;">            <span style="color: blue;">if</span> (serverUri.Scheme != <span style="color: #2b91af;">Uri</span>.UriSchemeFtp)</p>
<p style="margin: 0px;">            {</p>
<p style="margin: 0px;">                <span style="color: blue;">return</span> <span style="color: blue;">null</span>;</p>
<p style="margin: 0px;">            }</p>
<p style="margin: 0px;">            <span style="color: blue;">var</span> reqFTP = (<span style="color: #2b91af;">FtpWebRequest</span>)<span style="color: #2b91af;">FtpWebRequest</span>.Create(serverUri);</p>
<p style="margin: 0px;">            reqFTP.Method = method;</p>
<p style="margin: 0px;">            reqFTP.UseBinary = <span style="color: blue;">true</span>;</p>
<p style="margin: 0px;">            reqFTP.Credentials = <span style="color: blue;">new</span> <span style="color: #2b91af;">NetworkCredential</span>(Connection.Username, Connection.Password);</p>
<p style="margin: 0px;">            reqFTP.Proxy = <span style="color: blue;">null</span>;</p>
<p style="margin: 0px;">            reqFTP.KeepAlive = <span style="color: blue;">false</span>;</p>
<p style="margin: 0px;">            reqFTP.UsePassive = <span style="color: blue;">false</span>;</p>
<p style="margin: 0px;">            <span style="color: blue;">return</span> reqFTP;</p>
<p style="margin: 0px;">        }</p>
</div>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">    <span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">FTPListDetail</span></p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        <span style="color: blue;">public</span> <span style="color: blue;">bool</span> IsDirectory</p>
<p style="margin: 0px;">        {</p>
<p style="margin: 0px;">            <span style="color: blue;">get</span></p>
<p style="margin: 0px;">            {</p>
<p style="margin: 0px;">                <span style="color: blue;">return</span> !<span style="color: blue;">string</span>.IsNullOrWhiteSpace(Dir) &amp;&amp; Dir.EqualsIgnoreCase(<span style="color: #a31515;">&#8220;D&#8221;</span>);</p>
<p style="margin: 0px;">            }</p>
<p style="margin: 0px;">        }</p>
<p style="margin: 0px;">
<p style="margin: 0px;">        <span style="color: blue;">internal</span> <span style="color: blue;">string</span> Dir { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</p>
<p style="margin: 0px;">        <span style="color: blue;">public</span> <span style="color: blue;">string</span> Permission { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</p>
<p style="margin: 0px;">        <span style="color: blue;">public</span> <span style="color: blue;">string</span> Filecode { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</p>
<p style="margin: 0px;">        <span style="color: blue;">public</span> <span style="color: blue;">string</span> Owner { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</p>
<p style="margin: 0px;">        <span style="color: blue;">public</span> <span style="color: blue;">string</span> Group { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</p>
<p style="margin: 0px;">        <span style="color: blue;">public</span> <span style="color: blue;">int</span> Size { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</p>
<p style="margin: 0px;">        <span style="color: blue;">public</span> <span style="color: blue;">string</span> Name { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</p>
<p style="margin: 0px;">        <span style="color: blue;">public</span> <span style="color: blue;">string</span> FullPath { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</p>
<p style="margin: 0px;">
<p style="margin: 0px;">        <span style="color: blue;">internal</span> <span style="color: blue;">string</span> Month { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</p>
<p style="margin: 0px;">        <span style="color: blue;">internal</span> <span style="color: blue;">string</span> Day { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</p>
<p style="margin: 0px;">        <span style="color: blue;">internal</span> <span style="color: blue;">string</span> YearTime { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</p>
<p style="margin: 0px;">
<p style="margin: 0px;">        <span style="color: blue;">public</span> <span style="color: #2b91af;">DateTime</span> Date</p>
<p style="margin: 0px;">        {</p>
<p style="margin: 0px;">            <span style="color: blue;">get</span></p>
<p style="margin: 0px;">            {</p>
<p style="margin: 0px;">                <span style="color: blue;">var</span> month = <span style="color: #2b91af;">DateTime</span>.ParseExact(Month, <span style="color: #a31515;">&#8220;MMM&#8221;</span>, <span style="color: #2b91af;">CultureInfo</span>.CurrentCulture).Month;</p>
<p style="margin: 0px;">
<p style="margin: 0px;">                <span style="color: blue;">if</span> (!YearTime.Contains(<span style="color: #a31515;">&#8220;:&#8221;</span>))</p>
<p style="margin: 0px;">                {</p>
<p style="margin: 0px;">                    <span style="color: blue;">return</span> <span style="color: blue;">new</span> <span style="color: #2b91af;">DateTime</span>(YearTime.ToInt() ?? 0, month, Day.ToInt() ?? 0);</p>
<p style="margin: 0px;">                }</p>
<p style="margin: 0px;">                <span style="color: blue;">else</span></p>
<p style="margin: 0px;">                {</p>
<p style="margin: 0px;">
<p style="margin: 0px;">
<p style="margin: 0px;">                    <span style="color: blue;">var</span> dateTime = YearTime.Split(<span style="color: blue;">new</span> <span style="color: blue;">string</span>[] { <span style="color: #a31515;">&#8220;:&#8221;</span> }, <span style="color: #2b91af;">StringSplitOptions</span>.RemoveEmptyEntries);</p>
<p style="margin: 0px;">                    <span style="color: blue;">if</span> (dateTime.Count() == 2)</p>
<p style="margin: 0px;">                    {</p>
<p style="margin: 0px;">                        <span style="color: blue;">int</span> hour = dateTime[0].ToInt() ?? 0;</p>
<p style="margin: 0px;">                        <span style="color: blue;">int</span> minute = dateTime[1].ToInt() ?? 0;</p>
<p style="margin: 0px;">
<p style="margin: 0px;">                        <span style="color: blue;">return</span> <span style="color: blue;">new</span> <span style="color: #2b91af;">DateTime</span>(<span style="color: #2b91af;">DateTime</span>.Now.Year, month, Day.ToInt() ?? 0, hour, minute, 0);</p>
<p style="margin: 0px;">                    }</p>
<p style="margin: 0px;">                    <span style="color: blue;">return</span> <span style="color: blue;">new</span> <span style="color: #2b91af;">DateTime</span>(<span style="color: #2b91af;">DateTime</span>.Now.Year, Month.ToInt() ?? 0, Day.ToInt() ?? 0);</p>
<p style="margin: 0px;">                }</p>
<p style="margin: 0px;">            }</p>
<p style="margin: 0px;">        }</p>
<p style="margin: 0px;">
<p style="margin: 0px;">        <span style="color: blue;">public</span> <span style="color: blue;">override</span> <span style="color: blue;">string</span> ToString()</p>
<p style="margin: 0px;">        {</p>
<p style="margin: 0px;">            <span style="color: blue;">return</span> <span style="color: blue;">string</span>.Format(<span style="color: #a31515;">&#8220;{0} {1} {2} {3} {4} {5} {6} {7}&#8221;</span>,</p>
<p style="margin: 0px;">                Dir,</p>
<p style="margin: 0px;">                Permission,</p>
<p style="margin: 0px;">                Filecode,</p>
<p style="margin: 0px;">                Owner,</p>
<p style="margin: 0px;">                Group,</p>
<p style="margin: 0px;">                Size,</p>
<p style="margin: 0px;">                Date.ToShortDateString(),</p>
<p style="margin: 0px;">                Name</p>
<p style="margin: 0px;">                );</p>
<p style="margin: 0px;">        }</p>
<p style="margin: 0px;">    }</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.seesharpdot.net/?feed=rss2&#038;p=242</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Refresh rate switching app</title>
		<link>http://www.seesharpdot.net/?p=217</link>
		<comments>http://www.seesharpdot.net/?p=217#comments</comments>
		<pubDate>Mon, 18 Jul 2011 13:22:20 +0000</pubDate>
		<dc:creator>Adam O'Neil</dc:creator>
				<category><![CDATA[C# Development]]></category>
		<category><![CDATA[Refresh Rate Switcher]]></category>

		<guid isPermaLink="false">http://www.seesharpdot.net/?p=217</guid>
		<description><![CDATA[Hi all, I was looking around for an application which sits in the system tray and watches for key combinations to automatically change your monitor refresh rate &#8211; I assumed somebody would have written something to do this, but couldn&#8217;t find a single app, so I wrote something. I have uploaded it here :- http://downloads.seesharpdot.net/files/RefreshSwitcher.zip [...]]]></description>
				<content:encoded><![CDATA[<p>Hi all,</p>
<p>I was looking around for an application which sits in the system tray and watches for key combinations to automatically change your monitor refresh rate &#8211; I assumed somebody would have written something to do this, but couldn&#8217;t find a single app, so I wrote something.</p>
<p>I have uploaded it here :-</p>
<p><a title="Click here to download" href="http://downloads.seesharpdot.net/files/RefreshSwitcher.zip" target="_blank">http://downloads.seesharpdot.net/files/RefreshSwitcher.zip</a></p>
<p>It creates an icon in the system tray &#8211; if you right click you will get a mapping of your current resolution to the different refresh rates supported .. if you change resolution it will update itself to the new available refresh rates. Just add it to your startup section or HKLM/Software/Microsoft/CurrentVersion/Run/ in the  registry to get it to auto-launch at startup.</p>
<p>To use it &#8211; simple note the key combinations .. they will be in the range of :-</p>
<p>Control+Alt+ F1 to Control+Alt+F10</p>
<p>If I get enough coffees bought for me &#8211; I might consider adding some sort of configuration section to it with user configurable key mappings and multi resolution support.</p>
<p>PS. It uses the Low Level Keyboard Hook which is mentioned in the following post :-</p>
<p><a title="http://www.seesharpdot.net/?p=96" href="http://www.seesharpdot.net/?p=96">http://www.seesharpdot.net/?p=96</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.seesharpdot.net/?feed=rss2&#038;p=217</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Copy paste from Excel into a DataTable</title>
		<link>http://www.seesharpdot.net/?p=221</link>
		<comments>http://www.seesharpdot.net/?p=221#comments</comments>
		<pubDate>Tue, 15 Feb 2011 10:18:15 +0000</pubDate>
		<dc:creator>Adam O'Neil</dc:creator>
				<category><![CDATA[C# Development]]></category>
		<category><![CDATA[DataGrid]]></category>
		<category><![CDATA[DataTable]]></category>
		<category><![CDATA[Excel]]></category>
		<category><![CDATA[Paste]]></category>

		<guid isPermaLink="false">http://www.seesharpdot.net/?p=221</guid>
		<description><![CDATA[Ever wanted to copy and paste from Excel into a System.Data.DataTable for displaying in a DataGrid? Here&#8217;s some quick and dirty code to do just that :- private void PasteFromExcel()         {             DataTable tbl = new DataTable();             tbl.TableName = "ImportedTable";             List&#60;string&#62; data = new List&#60;string&#62;(ClipboardData.Split('\n'));             bool firstRow = true;             if (data.Count &#62; 0 &#38;&#38; string.IsNullOrWhiteSpace(data[data.Count - 1]))             {                 data.RemoveAt(data.Count - 1);             }             foreach (string iterationRow in data)             {                 string row = iterationRow;                 if (row.EndsWith("\r"))                 {                     row = row.Substring(0, row.Length - "\r".Length);                 }                 string[] rowData = row.Split(new char[] { '\r', '\x09' });                 DataRow newRow = tbl.NewRow();                 if (firstRow)                 {                     int colNumber = 0;                     foreach (string value in rowData)                     {                         if (string.IsNullOrWhiteSpace(value))                         {                             tbl.Columns.Add(string.Format("[BLANK{0}]", colNumber));                         } [...]]]></description>
				<content:encoded><![CDATA[<p>Ever wanted to copy and paste from Excel into a System.Data.DataTable for displaying in a DataGrid? Here&#8217;s some quick and dirty code to do just that :-</p>
<p><span style="font-family: Consolas, Monaco, 'Courier New', Courier, monospace; font-size: 12px; line-height: 18px; white-space: pre;"> private void PasteFromExcel()</span></p>
<pre>        {
            DataTable tbl = new DataTable();
            tbl.TableName = "ImportedTable";
            List&lt;string&gt; data = new List&lt;string&gt;(ClipboardData.Split('\n'));
            bool firstRow = true;
 
            if (data.Count &gt; 0 &amp;&amp; string.IsNullOrWhiteSpace(data[data.Count - 1]))
            {
                data.RemoveAt(data.Count - 1);
            }
 
            foreach (string iterationRow in data)
            {
                string row = iterationRow;
                if (row.EndsWith("\r"))
                {
                    row = row.Substring(0, row.Length - "\r".Length);
                }
 
                string[] rowData = row.Split(new char[] { '\r', '\x09' });
                DataRow newRow = tbl.NewRow();
                if (firstRow)
                {
                    int colNumber = 0;
                    foreach (string value in rowData)
                    {
                        if (string.IsNullOrWhiteSpace(value))
                        {
                            tbl.Columns.Add(string.Format("[BLANK{0}]", colNumber));
                        }
                        else if (!tbl.Columns.Contains(value))
                        {
                            tbl.Columns.Add(value);
                        }
                        else
                        {
                            tbl.Columns.Add(string.Format("Column {0}", colNumber));
                        }
                        colNumber++;
                    }
                    firstRow = false;
                }
                else
                {
                    for (int i = 0; i &lt; rowData.Length; i++)
                    {
                        if (i &gt;= tbl.Columns.Count) break;
                        newRow[i] = rowData[i];
                    }
                    tbl.Rows.Add(newRow);
                }
            }
 
            this.WorkingTableElement.WorkingTable = tbl;
 
            tableImportGrid.DataSource = null;
            tableImportGrid.RefreshDataSource();
            
            tableImportGrid.DataSource = tbl;
            tableImportGrid.RefreshDataSource();
            tableImportGrid.Refresh();
        }</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.seesharpdot.net/?feed=rss2&#038;p=221</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Custom WebBrowser Control with Zooming and CSS Injection</title>
		<link>http://www.seesharpdot.net/?p=218</link>
		<comments>http://www.seesharpdot.net/?p=218#comments</comments>
		<pubDate>Tue, 15 Feb 2011 10:11:15 +0000</pubDate>
		<dc:creator>Adam O'Neil</dc:creator>
				<category><![CDATA[C# Development]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[AttachInterfaces]]></category>
		<category><![CDATA[axIWebBrowser2]]></category>
		<category><![CDATA[AxWebBrowser]]></category>
		<category><![CDATA[ExecWB]]></category>
		<category><![CDATA[IWebBrowser2]]></category>
		<category><![CDATA[OLECMDID]]></category>
		<category><![CDATA[OLECMDID_OPTICAL_GETZOOMRANG]]></category>
		<category><![CDATA[OLECMDID_OPTICAL_ZOOM]]></category>
		<category><![CDATA[OPTICAL_ZOOM]]></category>
		<category><![CDATA[user32.dll]]></category>
		<category><![CDATA[WebBrowser]]></category>

		<guid isPermaLink="false">http://www.seesharpdot.net/?p=218</guid>
		<description><![CDATA[I thought I would post this custom browser I wrote for a project I am working on. It allows you to access the zoom function of the Internet Explorer browser (AxWebBrowser) by calling a Zoom method (passing in a whole number, expressed as percentage). I also added an InjectCSS() method which allows you to insert [...]]]></description>
				<content:encoded><![CDATA[<p>I thought I would post this custom browser I wrote for a project I am working on. It allows you to access the zoom function of the Internet Explorer browser (AxWebBrowser) by calling a Zoom method (passing in a whole number, expressed as percentage). I also added an InjectCSS() method which allows you to insert some extra CSS into the page (after it is loaded). I used this in a project recently where I didn&#8217;t want to mess with my generated page CSS or HTML, but simple wanted to add a couple of styles for display only purposes.</p>
<pre>    public partial class CustomBrowser : WebBrowser
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern short GetAsyncKeyState(int keyCode);
        public bool IsKeyDown(Keys key)
        {
            return (GetAsyncKeyState((int)key) &amp; 0x8000) != 0;
        }
 
        #region enums
        public enum OLECMDID
        {
            // ...
            OLECMDID_OPTICAL_ZOOM = 63,
            OLECMDID_OPTICAL_GETZOOMRANGE = 64,
            // ...
        }
 
        public enum OLECMDEXECOPT
        {
            // ...
            OLECMDEXECOPT_DONTPROMPTUSER,
            // ...
        }
 
        public enum OLECMDF
        {
            // ...
            OLECMDF_SUPPORTED = 1
        }
        #endregion
 
        #region IWebBrowser2
        [ComImport, /*SuppressUnmanagedCodeSecurity,*/
         TypeLibType(TypeLibTypeFlags.FOleAutomation |
                     TypeLibTypeFlags.FDual |
                     TypeLibTypeFlags.FHidden),
         Guid("D30C1661-CDAF-11d0-8A3E-00C04FC9E26E")]
        public interface IWebBrowser2
        {
            [DispId(100)]
            void GoBack();
            [DispId(0x65)]
            void GoForward();
            [DispId(0x66)]
            void GoHome();
            [DispId(0x67)]
            void GoSearch();
            [DispId(0x68)]
            void Navigate([In] string Url,
                          [In] ref object flags,
                          [In] ref object targetFrameName,
                          [In] ref object postData,
                          [In] ref object headers);
            [DispId(-550)]
            void Refresh();
            [DispId(0x69)]
            void Refresh2([In] ref object level);
            [DispId(0x6a)]
            void Stop();
            [DispId(200)]
            object Application
            {
                [return:
                 MarshalAs(UnmanagedType.IDispatch)]
                get;
            }
            [DispId(0xc9)]
            object Parent
            {
                [return:
                 MarshalAs(UnmanagedType.IDispatch)]
                get;
            }
            [DispId(0xca)]
            object Container
            {
                [return:
                 MarshalAs(UnmanagedType.IDispatch)]
                get;
            }
            [DispId(0xcb)]
            object Document
            {
                [return:
                 MarshalAs(UnmanagedType.IDispatch)]
                get;
            }
            [DispId(0xcc)]
            bool TopLevelContainer { get; }
            [DispId(0xcd)]
            string Type { get; }
            [DispId(0xce)]
            int Left { get; set; }
            [DispId(0xcf)]
            int Top { get; set; }
            [DispId(0xd0)]
            int Width { get; set; }
            [DispId(0xd1)]
            int Height { get; set; }
            [DispId(210)]
            string LocationName { get; }
            [DispId(0xd3)]
            string LocationURL { get; }
            [DispId(0xd4)]
            bool Busy { get; }
            [DispId(300)]
            void Quit();
            [DispId(0x12d)]
            void ClientToWindow(out int pcx, out int pcy);
            [DispId(0x12e)]
            void PutProperty([In] string property,
                             [In] object vtValue);
            [DispId(0x12f)]
            object GetProperty([In] string property);
            [DispId(0)]
            string Name { get; }
            [DispId(-515)]
            int HWND { get; }
            [DispId(400)]
            string FullName { get; }
            [DispId(0x191)]
            string Path { get; }
            [DispId(0x192)]
            bool Visible { get; set; }
            [DispId(0x193)]
            bool StatusBar { get; set; }
            [DispId(0x194)]
            string StatusText { get; set; }
            [DispId(0x195)]
            int ToolBar { get; set; }
            [DispId(0x196)]
            bool MenuBar { get; set; }
            [DispId(0x197)]
            bool FullScreen { get; set; }
            [DispId(500)]
            void Navigate2([In] ref object URL,
                           [In] ref object flags,
                           [In] ref object targetFrameName,
                           [In] ref object postData,
                           [In] ref object headers);
            [DispId(0x1f5)]
            OLECMDF QueryStatusWB([In] OLECMDID cmdID);
            [DispId(0x1f6)]
            void ExecWB([In] OLECMDID cmdID,
                        [In] OLECMDEXECOPT cmdexecopt,
                        ref object pvaIn, IntPtr pvaOut);
            [DispId(0x1f7)]
            void ShowBrowserBar([In] ref object pvaClsid,
                                [In] ref object pvarShow,
                                [In] ref object pvarSize);
            [DispId(-525)]
            WebBrowserReadyState ReadyState { get; }
            [DispId(550)]
            bool Offline { get; set; }
            [DispId(0x227)]
            bool Silent { get; set; }
            [DispId(0x228)]
            bool RegisterAsBrowser { get; set; }
            [DispId(0x229)]
            bool RegisterAsDropTarget { get; set; }
            [DispId(0x22a)]
            bool TheaterMode { get; set; }
            [DispId(0x22b)]
            bool AddressBar { get; set; }
            [DispId(0x22c)]
            bool Resizable { get; set; }
        }
        #endregion
 
        private IWebBrowser2 axIWebBrowser2;
 
        public CustomBrowser()
        {
        }
 
        ~CustomBrowser()
        {
        }
 
        protected override void AttachInterfaces(
            object nativeActiveXObject)
        {
            base.AttachInterfaces(nativeActiveXObject);
            this.axIWebBrowser2 = (IWebBrowser2)nativeActiveXObject;
        }
 
        protected override void DetachInterfaces()
        {
            base.DetachInterfaces();
            this.axIWebBrowser2 = null;
        }
 
        protected override void OnDocumentCompleted(WebBrowserDocumentCompletedEventArgs e)
        {
            base.OnDocumentCompleted(e);
        }
 
        public void InjectCSS()
        {
            try
            {
                mshtml.HTMLDocument test = (mshtml.HTMLDocument)this.Document.DomDocument;
                //inject CSS
                if (test.styleSheets.length &lt; 31)
                { // createStyleSheet throws "Invalid Argument if &gt;31 stylesheets on page
 
                    mshtml.IHTMLStyleSheet css = (mshtml.IHTMLStyleSheet)test.createStyleSheet("", 0);
                    css.cssText = "//Insert Custom CSS here!";
                    // CSS should now affect page
                }
                else
                {
                    System.Console.WriteLine("Could not inject CSS due to styleSheets.length greater than 31");
                    return;
                }
            }
            catch { }
        }
 
        int currentZoom = 100;
        public void Zoom(int factor)
        {
            object pvaIn = factor;
            try
            {
                this.axIWebBrowser2.ExecWB(OLECMDID.OLECMDID_OPTICAL_ZOOM,
                   OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER,
                   ref pvaIn, 
                   IntPtr.Zero);
            }
            catch (Exception)
            {
                throw;
            }
        }
    }</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.seesharpdot.net/?feed=rss2&#038;p=218</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Streaming Files (for Upload/Download) in WCF (Message Contracts)</title>
		<link>http://www.seesharpdot.net/?p=214</link>
		<comments>http://www.seesharpdot.net/?p=214#comments</comments>
		<pubDate>Tue, 15 Feb 2011 10:04:59 +0000</pubDate>
		<dc:creator>Adam O'Neil</dc:creator>
				<category><![CDATA[C# Development]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[WPF / .NET 3.5 Development]]></category>
		<category><![CDATA[Download]]></category>
		<category><![CDATA[IsOneWay]]></category>
		<category><![CDATA[MessageContract]]></category>
		<category><![CDATA[MessageHeader]]></category>
		<category><![CDATA[OperationContract]]></category>
		<category><![CDATA[Streaming Files]]></category>
		<category><![CDATA[Upload]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://www.seesharpdot.net/?p=214</guid>
		<description><![CDATA[I recently had to write some code to perform an upload to a WCF service, and there was a chance that the files could be a touch on the large side so streaming seemed like the best option. There is quite a limited amount of information about this subject &#8211; and configuring the web config [...]]]></description>
				<content:encoded><![CDATA[<p>I recently had to write some code to perform an upload to a WCF service, and there was a chance that the files could be a touch on the large side so streaming seemed like the best option.</p>
<p>There is quite a limited amount of information about this subject &#8211; and configuring the web config is a bit tricky, so I have posted some examples of how to do this in the hope that someone will find it useful..</p>
<p>You need to start by defining some message contracts for your upload / download.. these need to be defined in the  interface for your WCF service (the file that contains the definitions and contracts for your service) :-</p>
<p><span style="font-family: Consolas, Monaco, 'Courier New', Courier, monospace; font-size: 12px; line-height: 18px; white-space: pre;"> [MessageContract]</span></p>
<pre>    public class FileUploadMessage
    {
        [MessageHeader(MustUnderstand = true)]
        public PublishingMetaData Metadata;
        [MessageHeader(MustUnderstand = true)]
        public string AuthenticationKey;
        [MessageBodyMember(Order = 1)]
        public Stream FileByteStream;
    }

    [MessageContract]
    public class FileDownloadMessage
    {
        [MessageHeader(MustUnderstand = true)]
        public PublishingMetaData FileMetaData;
        [MessageHeader(MustUnderstand = true)]
        public string AuthenticationKey;
    }</pre>
<pre>
<pre>    [MessageContract]
    public class FileDownloadReturnMessage
    {
        public FileDownloadReturnMessage(PublishingMetaData metaData, Stream stream)
        {
            this.DownloadedFileMetadata = metaData;
            this.FileByteStream = stream;
        }

        [MessageHeader(MustUnderstand = true)]
        public PublishingMetaData DownloadedFileMetadata;
        [MessageBodyMember(Order = 1)]
        public Stream FileByteStream;
    }</pre>
<pre><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">Notice  that for the FileUploadMessage I have included a Stream.. the PublishingMetaData and AuthenticationKey are custom classes / properties and don't need to be implemented in your version.</span></pre>
<p>I also need to define a couple of web methods in the interface which are used for uploading / downloading files :-</p>
<pre>        [OperationContract(IsOneWay = false)]
        FileDownloadReturnMessage DownloadFile(FileDownloadMessage request);</pre>
<pre>
<pre>        [OperationContract(IsOneWay = true)]
        void UploadFile(FileUploadMessage request);</pre>
<pre>        [OperationContract]
        void AttemptToCloseStream(string authenticationKey, PublishingMetaData metaData);</pre>
<p>Now we have defined our contracts &#8211; here is the implementation (which is contained in the main WCF service class).. I have left my security checking and various other custom code in for illustration purposes, but again this can be removed in your implementation :-</p>
<pre>        public void UploadFile(FileUploadMessage request)
        {
            if (!CheckAuthenticationKey(request.AuthenticationKey)) { throw new SecurityException("The user does not have access."); }
            Stream fileStream = null;
            Stream outputStream = null;

            try
            {
                fileStream = request.FileByteStream;

                string rootPath = ConfigurationManager.AppSettings["RootPath"].ToString();

                DirectoryInfo dirInfo = new DirectoryInfo(rootPath);
                if (!dirInfo.Exists)
                {
                    dirInfo.Create();
                }

                //Create the file in the filesystem - change the extension if you wish, or use a passed in value from metadata ideally
                string newFileName = Path.Combine(rootPath, Guid.NewGuid() + ".xml");

                outputStream = new FileInfo(newFileName).OpenWrite();
                const int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];

                int bytesRead = fileStream.Read(buffer, 0, bufferSize);

                while (bytesRead &gt; 0)
                {
                    outputStream.Write(buffer, 0, bufferSize);
                    bytesRead = fileStream.Read(buffer, 0, bufferSize);
                }
            }
            catch (IOException ex)
            {
                throw new FaultException&lt;IOException&gt;(ex, new FaultReason(ex.Message));
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
                if (outputStream != null)
                {
                    outputStream.Close();
                }
            }
        }</pre>
<p>And here is my download implementation (notice the use of a list of OpenStreams.. this is a workaround to fix a problem I was having with streams being left open .. I use this to allow my program to call the service and ensure the stream is closed after the file is downloaded) :-</p>
<pre>
<pre>        static Dictionary&lt;string, Stream&gt; OpenStreams { get; set; }</pre>
<pre>        public FileDownloadReturnMessage DownloadFile(FileDownloadMessage request)
        {
            try
            {
                if (!CheckAuthenticationKey(request.AuthenticationKey)) { throw new SecurityException("The user does not have access."); }
                string rootPath = ConfigurationManager.AppSettings["RootPath"].ToString();
                Stream fileStream = new FileStream(Path.Combine(rootPath, Path.GetFileName(request.FileMetaData.FileName)), FileMode.Open);
                if (ExecutionResearchService.OpenStreams == null)
                {
                    ExecutionResearchService.OpenStreams = new Dictionary&lt;string, Stream&gt;();
                }
                ExecutionResearchService.OpenStreams.Add(Path.GetFileName(request.FileMetaData.FileName), fileStream);
                return new FileDownloadReturnMessage(new PublishingMetaData(), fileStream);
            }
            catch (IOException ex)
            {
                throw new FaultException&lt;IOException&gt;(ex, new FaultReason(ex.Message));
            }
        }</pre>
<pre>
<pre>        public void AttemptToCloseStream(string authenticationKey, PublishingMetaData metaData)
        {
            if (!CheckAuthenticationKey(authenticationKey)) { throw new SecurityException("The user does not have access."); }
            if (ExecutionResearchService.OpenStreams != null)
            {
                if (ExecutionResearchService.OpenStreams.ContainsKey(Path.GetFileName(metaData.FileName)))
                {
                    Stream stream = ExecutionResearchService.OpenStreams[Path.GetFileName(metaData.FileName)];
                    stream.Flush();
                    stream.Close();
                    OpenStreams.Remove(Path.GetFileName(metaData.FileName));
                }
            }
        }</pre>
<pre>OK - so now we have a file upload method, download method, and the required contracts we need. The services section of the web config looks like this :-</pre>
<pre>
<pre>  &lt;system.serviceModel&gt;
    &lt;behaviors&gt;
      &lt;serviceBehaviors&gt;
        &lt;behavior name="serviceBehavior"&gt;
          &lt;serviceMetadata httpGetEnabled="true"/&gt;
          &lt;serviceDebug includeExceptionDetailInFaults="true" httpHelpPageEnabled="true" /&gt;
          &lt;dataContractSerializer maxItemsInObjectGraph="2147483647"/&gt;
        &lt;/behavior&gt;
      &lt;/serviceBehaviors&gt;
    &lt;/behaviors&gt;
    &lt;services&gt;
      &lt;!--http://services.myserviceaddress.com/service.svc--&gt;
      &lt;service behaviorConfiguration="serviceBehavior" name="Projects.MyServiceName"&gt;
        &lt;endpoint address="http://services.myserviceaddress.com/service.svc"
        name="basicHttpStream"
        binding="basicHttpBinding"
        bindingConfiguration="httpLargeMessageStream"
        contract="Projects.IMyServiceInterface" /&gt;
        &lt;host&gt;
          &lt;baseAddresses&gt;
            &lt;add baseAddress="http://services.myserviceaddress.com/service.svc" /&gt;
            &lt;!--&lt;add baseAddress="http://localhost/ExecutionResearchService/ExecutionResearchService.svc" /&gt;--&gt;
          &lt;/baseAddresses&gt;
        &lt;/host&gt;
        &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/&gt;
      &lt;/service&gt;
    &lt;/services&gt;
    &lt;bindings&gt;
      &lt;basicHttpBinding&gt;
        &lt;binding name="httpLargeMessageStream"
                    maxReceivedMessageSize="2147483647"
                    transferMode="Streamed"
                    messageEncoding="Mtom" /&gt;
      &lt;/basicHttpBinding&gt;
    &lt;/bindings&gt;
  &lt;/system.serviceModel&gt;</pre>
<p>The important bits are the binding section at the bottom &#8211; transferMode = &#8220;Streamed&#8221; and messageEncoding = &#8220;Mtom&#8221; .. also I have set the maxReceivedMessageSize to it&#8217;s maximum value to ensure I can transfer massive files across my web service without issues.</p>
<p>Now &#8211; once these are set up and working in your WCF Service &#8211; we can add a reference to it and call the methods using our client application.. here is some code on how to do this too, because I found help lacking in this area also!</p>
<p>This is how we upload a file &#8211; please change variables, and remove AuthenticationKey and the MetaData objects if you didn&#8217;t use them.</p>
<pre>
<pre>using (ResearchServiceClient client = WebServiceProxy.GetResearchServiceClient())
{
    Stream fileStream = null;
 
    try
    {
        string rootPath = @"C:\MyRootFolder";
        string localDocumentPath = Path.Combine(rootPath, "MyNewFileName.xml");
        fileStream = new FileInfo(localDocumentPath).OpenRead();
        client.UploadFile(WebServiceProxy.AuthenticationKey, LivePaths.WorkingPublishingMetaData, fileStream);
 
        byte[] buffer = new byte[2048];
        int bytesRead = fileStream.Read(buffer, 0, 2048);
        while (bytesRead &gt; 0)
        {
            fileStream.Write(buffer, 0, 2048);
            bytesRead = fileStream.Read(buffer, 0, 2048);
        }
    }
    catch
    {
        throw;
    }
    finally
    {
        if (fileStream != null)
        {
            fileStream.Close();
        }
    }
}</pre>
<pre>using (ResearchServiceClient client = WebServiceProxy.GetResearchServiceClient())
{
    Stream fileStream = null;
    client.DownloadFile(WebServiceProxy.AuthenticationKey, metaData, out fileStream);
 
    Stream outputStream = null;
 
    try
    {</pre>
<pre>        outputStream = new FileInfo("PathForLocalDocument.xml").OpenWrite();
        byte[] buffer = new byte[2048];
 
        int bytesRead = fileStream.Read(buffer, 0, 2048);
 
        while (bytesRead &gt; 0)
        {
            outputStream.Write(buffer, 0, 2048);
            bytesRead = fileStream.Read(buffer, 0, 2048);
        }
    }
    catch
    {
 
    }
    finally
    {
        if (fileStream != null)
        {
            fileStream.Close();
        }
        if (outputStream != null)
        {
            outputStream.Close();
        }
        client.AttemptToCloseStream(WebServiceProxy.AuthenticationKey, metaData);
    }
}</pre>
<p>So &#8211; here&#8217;s the total solution, and notice we put the client.AttemptToCloseStream in the finally section of our Try / Catch which attempts to close the download stream when we have finished with it. It seems like a little bit of a hack, but I scratched my head trying to find a solution to this, and this is the best thing I could come up with.. it works, so it isn&#8217;t that bad.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.seesharpdot.net/?feed=rss2&#038;p=214</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Delivery Notifications in .NET MailMessage</title>
		<link>http://www.seesharpdot.net/?p=209</link>
		<comments>http://www.seesharpdot.net/?p=209#comments</comments>
		<pubDate>Tue, 18 May 2010 14:59:56 +0000</pubDate>
		<dc:creator>Adam O'Neil</dc:creator>
				<category><![CDATA[C# Development]]></category>

		<guid isPermaLink="false">http://www.seesharpdot.net/?p=209</guid>
		<description><![CDATA[If you ever need to get delivery reports when you send emails from within .NET &#8211; here is a nice code snippet which does it. I used this approach to stamp emails with a &#8220;Mail-CustomData&#8221; header which contained information leading back to a database entity. I then watched the mailReplyToAddress with a small program I [...]]]></description>
				<content:encoded><![CDATA[<p>If you ever need to get delivery reports when you send emails from within .NET &#8211; here is a nice code snippet which does it. I used this approach to stamp emails with a &#8220;Mail-CustomData&#8221; header which contained information leading back to a database entity. I then watched the mailReplyToAddress with a small program I wrote and updated the database when the message was received, or failed to deliver.</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">            MailMessage message = <span class="kwrd">new</span> MailMessage();
            message.From = <span class="kwrd">new</span> MailAddress(<span class="str">"DoNotReply@EmailAddress.com"</span>);
            message.ReplyToList.Add(<span class="kwrd">new</span> MailAddress(mailReplyToAddress));
            message.Headers.Add(<span class="str">"Disposition-Notification-To"</span>, mailReplyToAddress);

            message.To.Add(<span class="kwrd">new</span> MailAddress(emailAddress));
            message.IsBodyHtml = <span class="kwrd">true</span>;
            message.Priority = MailPriority.High;
            message.Body = <span class="str">"This is the message."</span>;
            message.Subject = <span class="str">"Mail Message With Delivery Reports"</span>;

            message.Headers.Add(<span class="str">"Mail-CustomData"</span>, <span class="str">"1203495Dflgrk3012"</span>);

            message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess | DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.Delay;

            System.Net.Mail.SmtpClient client = <span class="kwrd">new</span> SmtpClient();
            client.Send(message);</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.seesharpdot.net/?feed=rss2&#038;p=209</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Visual Studio 2010 Intellisense</title>
		<link>http://www.seesharpdot.net/?p=208</link>
		<comments>http://www.seesharpdot.net/?p=208#comments</comments>
		<pubDate>Fri, 14 May 2010 14:37:34 +0000</pubDate>
		<dc:creator>Adam O'Neil</dc:creator>
				<category><![CDATA[C# Development]]></category>

		<guid isPermaLink="false">http://www.seesharpdot.net/?p=208</guid>
		<description><![CDATA[Is anyone else having problems with Visual Studio 2010 intellisense? I find myself constantly having to guess the name of properties and events in my web controls (mostly UserControls, but also ASP.NET Ajax controls) and it&#8217;s starting to get to me! I haven&#8217;t seen anyone complaining about this yet, so I thought it was definitely [...]]]></description>
				<content:encoded><![CDATA[<p>Is anyone else having problems with Visual Studio 2010 intellisense? I find myself constantly having to guess the name of properties and events in my web controls (mostly UserControls, but also ASP.NET Ajax controls) and it&#8217;s starting to get to me!</p>
<p>I haven&#8217;t seen anyone complaining about this yet, so I thought it was definitely about time someone did.</p>
<p>Heres some sites I have been working on recently :- adding the links as a test to see if it makes any difference with the SEO (PS. It does!)</p>
<p><a href="http://www.dougmyallblinds.com">www.dougmyallblinds.com</a> / <a href="http://www.blindsjersey.co.uk">www.blindsjersey.co.uk</a></p>
<p><a href="http://www.phatlicks.com">www.phatlicks.com</a></p>
<p><a href="http://www.perfectdog.co.uk">www.perfectdog.co.uk</a></p>
<p><a href="http://www.animals-on-camera.com">www.animals-on-camera.com</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.seesharpdot.net/?feed=rss2&#038;p=208</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Searching Directories With Linq</title>
		<link>http://www.seesharpdot.net/?p=204</link>
		<comments>http://www.seesharpdot.net/?p=204#comments</comments>
		<pubDate>Fri, 14 May 2010 09:25:55 +0000</pubDate>
		<dc:creator>Adam O'Neil</dc:creator>
				<category><![CDATA[C# Development]]></category>

		<guid isPermaLink="false">http://www.seesharpdot.net/?p=204</guid>
		<description><![CDATA[Haven&#8217;t posted for quite a while &#8211; reason being is that I started a new job with a stockbroker in London and have been very busy. Here&#8217;s the first of many new posts on useful .NET code snippets. Recursively looking through directories for files has always been a bit of a fiddle &#8211; here&#8217;s a [...]]]></description>
				<content:encoded><![CDATA[<p>Haven&#8217;t posted for quite a while &#8211; reason being is that I started a new job with a stockbroker in London and have been very busy. Here&#8217;s the first of many new posts on useful .NET code snippets.</p>
<p>Recursively looking through directories for files has always been a bit of a fiddle &#8211; here&#8217;s a nice easy way to do it with Linq.</p>
<p>NB. I use a custom object here called &#8220;FileDefinition&#8221;.. this can be swapped out to yield return the FileInfo object itself.. just replace :-</p>
<p>yield return new filedefinition;<br />
with<br />
yield return f;</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">        <span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;FileDefinition&gt; SearchFiles(DirectoryInfo directoryinf)
        {
            <span class="kwrd">foreach</span> (var f <span class="kwrd">in</span> directoryinf.GetFiles())
                <span class="kwrd">yield</span> <span class="kwrd">return</span> <span class="kwrd">new</span> FileDefinition(MapUrl(f.DirectoryName), f.DirectoryName, f.Name, f.Length);

            <span class="kwrd">foreach</span> (DirectoryInfo d <span class="kwrd">in</span> directoryinf.GetDirectories())
            {
                <span class="rem">//Recursevly go over all the other directories</span>
                <span class="kwrd">foreach</span> (var f <span class="kwrd">in</span> SearchFiles(d))
                    <span class="kwrd">yield</span> <span class="kwrd">return</span> f;
            }
        }

        <span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;FileDefinition&gt; SearchFilesByExtention(DirectoryInfo directoryinf, <span class="kwrd">string</span> extention)
        {
            <span class="rem">//Return the files first</span>
            <span class="kwrd">foreach</span> (<span class="kwrd">string</span> singleExtension <span class="kwrd">in</span> ParseExtensions(extention))
            {
                <span class="kwrd">foreach</span> (var f <span class="kwrd">in</span> directoryinf.GetFiles().Where(file =&gt; file.Extension == singleExtension))
                    <span class="kwrd">yield</span> <span class="kwrd">return</span> <span class="kwrd">new</span> FileDefinition(MapUrl(f.DirectoryName), f.DirectoryName, f.Name, f.Length);
            }

            <span class="kwrd">foreach</span> (DirectoryInfo d <span class="kwrd">in</span> directoryinf.GetDirectories())
            {
                <span class="rem">//Recursevly go over all the other directories</span>
                <span class="kwrd">foreach</span> (var f <span class="kwrd">in</span> SearchFilesByExtention(d, extention))
                    <span class="kwrd">yield</span> <span class="kwrd">return</span> f;
            }
        }

        <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">string</span>[] ParseExtensions(<span class="kwrd">string</span> extention)
        {
            <span class="kwrd">string</span>[] strings = extention.Split(<span class="kwrd">new</span> <span class="kwrd">string</span>[] { <span class="str">"|"</span> }, StringSplitOptions.RemoveEmptyEntries);
            <span class="kwrd">return</span> strings;
        }</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.seesharpdot.net/?feed=rss2&#038;p=204</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to get album art from Amazon Web Services</title>
		<link>http://www.seesharpdot.net/?p=199</link>
		<comments>http://www.seesharpdot.net/?p=199#comments</comments>
		<pubDate>Mon, 21 Dec 2009 14:50:01 +0000</pubDate>
		<dc:creator>Adam O'Neil</dc:creator>
				<category><![CDATA[C# Development]]></category>

		<guid isPermaLink="false">http://www.seesharpdot.net/?p=199</guid>
		<description><![CDATA[OK &#8211; After a few people have asked .. I have finally rewritten the Amazon Web Services tool to use my newly updated code. It&#8217;s a fresh rewrite with some special wordlist matching code, and it seems to work nicely. It is available here as a Windows Installer (.msi) package http://downloads.seesharpdot.net/files/CoverArtInstaller.msi So &#8211; all you [...]]]></description>
				<content:encoded><![CDATA[<p>OK &#8211; After a few people have asked .. I have finally rewritten the Amazon Web Services tool to use my newly updated code. It&#8217;s a fresh rewrite with some special wordlist matching code, and it seems to work nicely.</p>
<p>It is available here as a Windows Installer (.msi) package</p>
<p><a title="Download File" href="http://downloads.seesharpdot.net/files/CoverArtInstaller.msi" target="_blank">http://downloads.seesharpdot.net/files/CoverArtInstaller.msi</a></p>
<p>So &#8211; all you need to do is install it, then click Browse to find the directory that you use to store all of your movie files. The extension doesn&#8217;t matter as the program does not actually open the files, so they can be any type of movie file. Change the file mask to match the files you want to search for (*.avi *.mov), each separated with a space .. then click &#8220;Create Images&#8221;. The program will now attempt to create a .jpg cover with the same name as the movie file in that folder but with the .jpg extension.. if it cannot find a match it will try some clever searching techniques to try and find one, and eventually give up.</p>
<p>Vista and Windows 7 users &#8211; make sure you run with the correct privileges (right click and run as administrator), or you may not be able to create the files in your target location.</p>
<p>File naming hints &#8211; if you choose file names that match the name of the movie, you have the best chance of success &#8211; if it ends in random tags and words, the program will remove them from the search if they aren&#8217;t in the dictionary.. but ultimately it is just guessing, as it doesn&#8217;t know the real name of the film.</p>
<p>Enjoy! If you have any comments or suggestions, please register and leave them using the form. Don&#8217;t forget to buy me a coffee if you like the application. If I get enough fuel (coffee), I will make the next incarnation more interactive, and the &#8220;Manual Mode&#8221; will allow you to choose the images yourself if several are returned.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.seesharpdot.net/?feed=rss2&#038;p=199</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
