<?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>Fremus.co.za &#187; C#</title>
	<atom:link href="http://www.fremus.co.za/blog/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.fremus.co.za/blog</link>
	<description>Demistifying Life and Web Development</description>
	<lastBuildDate>Tue, 31 Aug 2010 16:45:27 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Ajax in the .NET environment&#8230;</title>
		<link>http://www.fremus.co.za/blog/2010/08/ajax-in-the-net-environment/</link>
		<comments>http://www.fremus.co.za/blog/2010/08/ajax-in-the-net-environment/#comments</comments>
		<pubDate>Thu, 05 Aug 2010 19:29:25 +0000</pubDate>
		<dc:creator>fr3dr1k</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Web Technologies]]></category>
		<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://www.fremus.co.za/blog/2010/08/ajax-in-the-net-environment/</guid>
		<description><![CDATA[Ajax is not new, its not revolutionary, but it has changed the way I view web development. Javascript no longer comes as a might-have, instead it comes as a critical part of any website application. These days I use JavaScript as the UI scripting tool of choice, and I try to steer away from doing [...]]]></description>
			<content:encoded><![CDATA[<p>Ajax is not new, its not revolutionary, but it has changed the way I view web development. Javascript no longer comes as a might-have, instead it comes as a critical part of any website application. These days I use JavaScript as the UI scripting tool of choice, and I try to steer away from doing to much UI lifting in my server side code. jQuery makes dealing with UI quite pleasant. </p>
<p>I have also, in the last year and a half or so, been coding without MS Ajax. I have let go of things like the UpdatePanel and the Script Manager and have instead come to do direct Ajax calls to .ashx, default.aspx and web services. It feels that when you follow this approach that you have much tighter control over the quality of the UI. So what are your options for making Ajax calls in a .NET environment? I would like to think that there are a few options that stand out:</p>
<ul>
<li>Direct page ajax calls – you can use jQuery’s ajax function to call .ashx and .aspx pages. I have recently started using the [WebMethod] attribute in my .aspx files to make calls, and what I like about it is that you can tell the page to output JSON, which automatically serializes the method’s return type. I have also used ashx files to do ajax calls and this worked well</li>
<li>SOAP-based web services – an approach I learned last year was to use a javascript soap parser to parse soap-based web services. These were mainly .asmx services. You can configure .asmx services to return JSON as well</li>
<li>WCF-services can be configured for SOAP or JSON but also use a REST-like approach</li>
</ul>
<p>What other options are there for .NET developers when making Ajax calls?</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save" onclick="urchinTracker('/outgoing/www.addtoany.com/share_save?referer=');"><img src="http://www.fremus.co.za/blog/wp-content/plugins/add-to-any/favicon.png" width="16" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.fremus.co.za/blog/2010/08/ajax-in-the-net-environment/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Logging frameworks for C#</title>
		<link>http://www.fremus.co.za/blog/2010/07/logging-frameworks-for-c/</link>
		<comments>http://www.fremus.co.za/blog/2010/07/logging-frameworks-for-c/#comments</comments>
		<pubDate>Sun, 11 Jul 2010 12:28:58 +0000</pubDate>
		<dc:creator>fr3dr1k</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.fremus.co.za/blog/2010/07/logging-frameworks-for-c/</guid>
		<description><![CDATA[I find myself going to StackOverflow a lot recently if I need to search for an opinion on something related to C# or ASP.NET. Strangely you will find that in the first 10 results of a Google search you will find one, maybe two, pointing to StackOverflow. I digress, and the reason I am writing [...]]]></description>
			<content:encoded><![CDATA[<p>I find myself going to <a href="http://www.stackoverflow.com" target="_blank" onclick="urchinTracker('/outgoing/www.stackoverflow.com?referer=');">StackOverflow</a> a lot recently if I need to search for an opinion on something related to C# or ASP.NET. Strangely you will find that in the first 10 results of a Google search you will find one, maybe two, pointing to <a href="http://www.stackoverflow.com" target="_blank" onclick="urchinTracker('/outgoing/www.stackoverflow.com?referer=');">StackOverflow</a>. I digress, and the reason I am writing this particular blogpost is to make a list of logging frameworks available to .NET (C#) developers.</p>
<p>Before I go into identifying a few possible solutions I need to try and understand what my need is and what it is I want to achieve. I am going to be tackling various ASP.NET MVC projects within the next two to three months, and I cannot possibly see myself knowing where all the exceptions in my application will happen, or even try and code in such a way that all my try{}catch{} statements catch the correct exception. At the same time there is no excuse to overlook an exception if it happens more than once, you have to handle it. Having noticed how many exceptions a WCF service can throw I know for a fact that I cannot know all the exceptions beforehand either, so I need something, a tool that allows me to see the exceptions, and add it to my code so I can catch them. So the basic need is simple, have a mechanism in place that allows exceptions in my system to be caught.</p>
<p>You might be going, OMW you don’t log? Well I have been with several development teams and I can tell you that not a lot of development teams log system errors. And there is a host of other things they also don’t do, but that is not a part of this blog post.</p>
<p>I searched <a href="http://www.stackoverflow.com" target="_blank" onclick="urchinTracker('/outgoing/www.stackoverflow.com?referer=');">StackOverflow</a>, and to me it seems there are a couple of choices available for logging in the .NET world:</p>
<ul>
<li><a href="http://logging.apache.org/log4net/" target="_blank" onclick="urchinTracker('/outgoing/logging.apache.org/log4net/?referer=');">Log4Net</a>, the popular Java port</li>
<li><a href="http://msdn.microsoft.com/en-us/library/ff648951.aspx" target="_blank" onclick="urchinTracker('/outgoing/msdn.microsoft.com/en-us/library/ff648951.aspx?referer=');">Enterprise Library from Microsoft</a></li>
<li><a href="http://nlog-project.org/" target="_blank" onclick="urchinTracker('/outgoing/nlog-project.org/?referer=');">NLog</a></li>
<li><a href="http://code.google.com/p/elmah/" target="_blank" onclick="urchinTracker('/outgoing/code.google.com/p/elmah/?referer=');">ELMAH for ASP.NET</a></li>
</ul>
<p>Maybe I need to consider all the features offered and decide on the best alternative, which would be:</p>
<ul>
<li>Ease of installation</li>
<li>Ease of getting to the exception logs </li>
</ul>
<p>My intention is to start looking at each one of these this week, and make a decision by the end of the week.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save" onclick="urchinTracker('/outgoing/www.addtoany.com/share_save?referer=');"><img src="http://www.fremus.co.za/blog/wp-content/plugins/add-to-any/favicon.png" width="16" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.fremus.co.za/blog/2010/07/logging-frameworks-for-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What are the data types available in C#?</title>
		<link>http://www.fremus.co.za/blog/2010/04/what-are-the-data-types-available-in-c/</link>
		<comments>http://www.fremus.co.za/blog/2010/04/what-are-the-data-types-available-in-c/#comments</comments>
		<pubDate>Tue, 27 Apr 2010 15:42:56 +0000</pubDate>
		<dc:creator>fr3dr1k</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.fremus.co.za/blog/?p=581</guid>
		<description><![CDATA[Types in C# and the .NET framework are the fundamental building block of program design, and in C# they are divided into built-in, primitive types, and user-defined types. Generally speaking the user-defined types refer to classes, and classes are essentially made up of built-in types and other user-defined types themselves. Primitive types can also be [...]]]></description>
			<content:encoded><![CDATA[<p>Types in C# and the .NET framework are the fundamental building block of program design, and in C# they are divided into built-in, primitive types, and user-defined types. Generally speaking the user-defined types refer to classes, and classes are essentially made up of built-in types and other user-defined types themselves. Primitive types can also be seen as value types, that is a type that has a value in memory, usually called the stack. This is in contrast to reference types that are on the heap, but actually have pointers to themselves on the stack. C# offers the following built-in types:</p>
<ul>
<li>Byte</li>
<li>Char</li>
<li>Int16</li>
<li>UInt16</li>
<li>Int32</li>
<li>UInt32</li>
<li>Long</li>
<li>ULong</li>
<li>Short</li>
<li>UShort</li>
<li>Decimal</li>
<li>Double</li>
<li>Float</li>
<li>SByte</li>
<li>Single</li>
<li>Boolean</li>
<li>Int64</li>
<li>UInt64</li>
</ul>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save" onclick="urchinTracker('/outgoing/www.addtoany.com/share_save?referer=');"><img src="http://www.fremus.co.za/blog/wp-content/plugins/add-to-any/favicon.png" width="16" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.fremus.co.za/blog/2010/04/what-are-the-data-types-available-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Springbok Selector App</title>
		<link>http://www.fremus.co.za/blog/2010/04/springbok-selector-app/</link>
		<comments>http://www.fremus.co.za/blog/2010/04/springbok-selector-app/#comments</comments>
		<pubDate>Mon, 19 Apr 2010 21:40:29 +0000</pubDate>
		<dc:creator>fr3dr1k</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Springboks]]></category>
		<category><![CDATA[HTML Agility]]></category>

		<guid isPermaLink="false">http://www.fremus.co.za/blog/?p=579</guid>
		<description><![CDATA[You all love the Springboks right? Those men in green who do South Africa proud? Well I guess the Kiwis or Aussies or Pommies or&#8230;err wait ok dont like the Springboks that much. But I love em and the other night I started thinking about writing an app that will allow me to select a [...]]]></description>
			<content:encoded><![CDATA[<p>You all love the Springboks right? Those men in green who do South Africa proud? Well I guess the Kiwis or Aussies or Pommies or&#8230;err wait ok dont like the Springboks that much. But I love em and the other night I started thinking about writing an app that will allow me to select a Springbok squad (or two or three) from the Super 14 teams that are currently playing. So what I did is I honestly collected some player and squad information and put it into a database, and the way I did this was to use HtmlAgility to screen scrape player information from www.sarugby.net, and I did it quite easily and successfully got some information and managed to store it. You can see on this page, albeit it might be a bit slow in coming through, that you can search for rugby players <a href="http://fremus.net/rugbyapp/" onclick="urchinTracker('/outgoing/fremus.net/rugbyapp/?referer=');">here</a> and once you have found a rugby player you can also get the rest of his team mates in his squad. Scary what you can do with a good HTML parser. I then took the information and created a few objects with properties and methods, and then I stored the information. Note that my intention is not to make money! I just liked the code that went into it. And the data that I stored I made available through an incomplete interface <a href="http://fremus.net/rugbyapp/springbokselector.aspx" onclick="urchinTracker('/outgoing/fremus.net/rugbyapp/springbokselector.aspx?referer=');">here</a>. You can click on the squads to the right, which displays the players for that squad and if you click on a player you see their information displayed. My next idea was to assign each player to one or more positions and then in the left hand pane create icons that represent rugby jerseys, and then make the players you select &#8220;addable&#8221; to the left until you reach the maximum number of players allowed.</p>
<p>I enjoyed doing it anyway, and I&#8217;m trying to do small projects at night to keep me motivated.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save" onclick="urchinTracker('/outgoing/www.addtoany.com/share_save?referer=');"><img src="http://www.fremus.co.za/blog/wp-content/plugins/add-to-any/favicon.png" width="16" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.fremus.co.za/blog/2010/04/springbok-selector-app/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Doing some C#/CLR stuff</title>
		<link>http://www.fremus.co.za/blog/2010/04/doing-some-cclr-stuff/</link>
		<comments>http://www.fremus.co.za/blog/2010/04/doing-some-cclr-stuff/#comments</comments>
		<pubDate>Sat, 10 Apr 2010 15:44:21 +0000</pubDate>
		<dc:creator>fr3dr1k</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.fremus.co.za/blog/?p=577</guid>
		<description><![CDATA[I am busy doing a CBT course with the idea of writing MCTS exams and I started by doing some stuff on C# and the .NET framework that focuses specifically on types. The .NET framework is a strongly typed framework and what we mean by strongly typed is that each variable (or type) that you [...]]]></description>
			<content:encoded><![CDATA[<p>I am busy doing a CBT course with the idea of writing MCTS exams and I started by doing some stuff on C# and the .NET framework that focuses specifically on types. The .NET framework is a strongly typed framework and what we mean by strongly typed is that each variable (or type) that you define or create in you&#8217;re code must be assigned to a type. C# in particular is a statically, manifestly and strongly typed language. The .NET framework uses the Common Type System (CTS) which means that the type int in C# and the type Integer in VB.NET refer to the same Int32 type in the CLR. It makes sense therefore that in C# you can define types of int as Int32, which means int is just an alias for Int32. Basic/intrinsic types refer to int&#8217;s, bools, long, char, unsigned int, unsigned long, byte, short, sbyte, unsigned short, float and decimal. Its important to understand this because memory in the .NET framework is divided into data structures, named the heap and stack respectively. The basic types are seen as value types that are stored on the stack in a Last In First Out basis. Enumerations, structs and constants are also seen as value types. In contrast user-defined types (objects) are stored on the heap. References to the objects are stored on the stack. If for instance you have an instance of StringBuilder called strb1 and another instance called strb2 and you instantiate strb2 be setting it to strb1 then both instances will point to the same reference on the stack. If you then set the value of strb1 it will have the same value as strb2, and vice verse.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save" onclick="urchinTracker('/outgoing/www.addtoany.com/share_save?referer=');"><img src="http://www.fremus.co.za/blog/wp-content/plugins/add-to-any/favicon.png" width="16" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.fremus.co.za/blog/2010/04/doing-some-cclr-stuff/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Interesting code with HtmlAgilityPack</title>
		<link>http://www.fremus.co.za/blog/2009/12/interesting-code-with-htmlagilitypack/</link>
		<comments>http://www.fremus.co.za/blog/2009/12/interesting-code-with-htmlagilitypack/#comments</comments>
		<pubDate>Sat, 12 Dec 2009 12:04:09 +0000</pubDate>
		<dc:creator>fr3dr1k</dc:creator>
				<category><![CDATA[Browsers]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[HTML Agility]]></category>

		<guid isPermaLink="false">http://www.fremus.co.za/blog/?p=548</guid>
		<description><![CDATA[Yesterday I was busy with HTML to PDF conversion and for this I used the HTML Agility Pack. Everything worked great, except it seemed IE and FF/Chrome render different HTML. So today I took some fairly straightforward HTML and pushed it through HTMLAgility: New Website Under Construction And if I use this code to loop [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I was busy with HTML to PDF conversion and for this I used the HTML Agility Pack. Everything worked great, except it seemed IE and FF/Chrome render different HTML. So today I took some fairly straightforward HTML and pushed it through HTMLAgility:</p>
<pre name="code" class="html">

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>

	<meta name="copyright" content="Copyright (c) 2009 Fredrik Erasmus">
	<meta name="author" content="Fredrik Erasmus">
<link rel="stylesheet" href="css/default.css" type="text/css" media="screen" />
</head>
<body>
<div id="header">
<div id="left_header"></div>
</div>
<div id="container">
<div id="main">
			New Website Under Construction
		</div>
<div id="sidebar">
		</div>
</div>
<div id="footer">
	</div>

</body>
</html>
</pre>
<p>And if I use this code to loop through the childnodes:</p>
<pre name="code" class="csharp">
            HtmlDocument doc = new HtmlDocument();
            string s;
            StringBuilder builder = new StringBuilder();
            using (StreamReader reader = new StreamReader(@"C:\Documents and Settings\user\Desktop\fremus.net\index.htm"))
            {
                while ((s = reader.ReadLine()) != null)
                {
                    builder.AppendLine(s);
                }
            }
            doc.LoadHtml(builder.ToString());
            Console.WriteLine(doc.DocumentNode.ChildNodes.Count);
            foreach (HtmlNode node in doc.DocumentNode.ChildNodes)
            {
                Console.WriteLine(node.Name);
                foreach (HtmlNode childNode in node.ChildNodes)
                {
                    Console.WriteLine("\t\t" + childNode.Name);
                    foreach (HtmlNode grandChildNode in childNode.ChildNodes)
                    {
                        Console.WriteLine("\t\t\t" + grandChildNode.Name);
                    }
                }
            }
</pre>
<p>I get the following result in my command line window:<br />
<a href="http://www.fremus.co.za/blog/wp-content/uploads/2009/12/cmdline.JPG"><img src="http://www.fremus.co.za/blog/wp-content/uploads/2009/12/cmdline.JPG" alt="cmdline" title="cmdline" width="668" height="335" class="alignleft size-full wp-image-549" /></a></p>
<p>As you can see from the output the html node has a text node. The head node has a text node, and it has 9 childnodes including 5 #text nodes. The body node has a text node as well, and it has 7 childnodes, four being #text and the other three being div. So what is this #text node? If you read <a href="http://www.w3schools.com/htmldom/dom_nodes.asp" onclick="urchinTracker('/outgoing/www.w3schools.com/htmldom/dom_nodes.asp?referer=');">this article</a> on the W3C site you will see that it states:</p>
<blockquote><p>A common error in DOM processing is to expect an element node to contain text.</p>
<p>However, the text of an element node is stored in a text node.
</p></blockquote>
<p>On the same page it then gives an example using a title tag. If you do a Google on &#8220;<em>html #text node</em>&#8220;, you will see that the second result points to <a href="http://www.quirksmode.org/dom/intro.html" onclick="urchinTracker('/outgoing/www.quirksmode.org/dom/intro.html?referer=');">an article</a> and if you read the bit on the nodes it seems that each #text node is a child. The #text nodes that appear in the body node seem to point to the text spaces after each div or each element inside the body node. If I change my code slightly:</p>
<pre name="code" class="csharp">
                    Console.WriteLine("\t\t" + childNode.Name);
                    foreach (HtmlNode grandChildNode in childNode.ChildNodes)
                    {
                        Console.WriteLine("\t\t\t" + grandChildNode.Name);
                        Console.WriteLine("\t\t\t\t" + grandChildNode.HasChildNodes);
                    }
</pre>
<p>It tells me that the divs have child elements, but the #text nodes do not. Thus it seems for each &#8216;empty space&#8217; inside a node there exists a #text node. If I amend the HTML from earlier like this:</p>
<pre name="code" class="html">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>

	<meta name="copyright" content="Copyright (c) 2009 Fredrik Erasmus">
	<meta name="author" content="Fredrik Erasmus">
<link rel="stylesheet" href="css/default.css" type="text/css" media="screen" />
</head>
<body>
<div id="footer">

Test
</div>

</body>
</html>
</pre>
<p>Then the footer div will have two text nodes, and the paragraph node will have a textnode. My issues yesterday had to do with the way IE rendered the HTML and that when I used HTMLAgility to parse it, the node counts weren&#8217;t the same. From the sample HTML I have given so far that difference is negligble, but I found that if I went to a site like <a href="http://www.w3schools.com/htmldom/dom_nodes_info.asp" onclick="urchinTracker('/outgoing/www.w3schools.com/htmldom/dom_nodes_info.asp?referer=');">this one</a> and I saved the HTML from IE and Chrome into separate HTML files and I ran my code with that HTML, I got different node counts. Here are two screenshots that illustrate this:<br />
<a href="http://www.fremus.co.za/blog/wp-content/uploads/2009/12/chrome.JPG"><img src="http://www.fremus.co.za/blog/wp-content/uploads/2009/12/chrome.JPG" alt="chrome" title="chrome" width="670" height="338" class="alignleft size-full wp-image-559" /></a><a href="http://www.fremus.co.za/blog/wp-content/uploads/2009/12/ie.JPG"><img src="http://www.fremus.co.za/blog/wp-content/uploads/2009/12/ie.JPG" alt="ie" title="ie" width="666" height="337" class="alignleft size-full wp-image-560" /></a></p>
<p>The first screen is the html from the page saved from chrome and the second one is from ie. Notice the extra text nodes. </p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save" onclick="urchinTracker('/outgoing/www.addtoany.com/share_save?referer=');"><img src="http://www.fremus.co.za/blog/wp-content/plugins/add-to-any/favicon.png" width="16" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.fremus.co.za/blog/2009/12/interesting-code-with-htmlagilitypack/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WCF &#8211; Getting the foundations right</title>
		<link>http://www.fremus.co.za/blog/2009/12/wcf-getting-the-foundations-right/</link>
		<comments>http://www.fremus.co.za/blog/2009/12/wcf-getting-the-foundations-right/#comments</comments>
		<pubDate>Sat, 05 Dec 2009 20:31:46 +0000</pubDate>
		<dc:creator>fr3dr1k</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://www.fremus.co.za/blog/?p=546</guid>
		<description><![CDATA[Ok so admittedly I have been using ASMX services for too long now and the time has come to kick it to the curb and adopt WCF. And the issue I have been having of late was that I was skimming through code just to get stuff done, without spending the time understanding some of [...]]]></description>
			<content:encoded><![CDATA[<p>Ok so admittedly I have been using ASMX services for too long now and the time has come to kick it to the curb and adopt WCF. And the issue I have been having of late was that I was skimming through code just to get stuff done, without spending the time understanding some of the details. </p>
<p>Why would I want to adopt WCF? Well there are the list of reasons found in articles on MSDN, one whitepaper can be <a href="http://msdn.microsoft.com/en-us/library/dd943056.aspx" onclick="urchinTracker('/outgoing/msdn.microsoft.com/en-us/library/dd943056.aspx?referer=');">found here</a>, and of particular interest is the combination of technologies and the general idea that interoperability is the main goal. But these things are just a way of promoting the technology, and its not until you understand what it can do that you realise what it is you are dealing with. And to help you get to that point you need to work through an example, and I found that after I worked through <a href="http://msdn.microsoft.com/en-us/library/ms734712.aspx" onclick="urchinTracker('/outgoing/msdn.microsoft.com/en-us/library/ms734712.aspx?referer=');">the &#8220;Getting Started Tutorial&#8221; example</a>, a light went on and I was like, &#8220;ok I get it&#8221;. Essentially a WCF service is made up of two key elements (there is a third as well) but in terms of C# code there are two key elements:<br />
*An interface marked as a Service Contract using the ServiceContract attribute and with the methods marked as OperationContracts using an attribute with the same name<br />
*A class that implements the methods in the interface</p>
<p>The third part of a WCF service is the configuration settings which can be found in a web.config/app.config&#8217;s system.servicemodel tag. Within the servicemodel section you define service behaviours as well as endpoints. One of the keys to understanding WCF is knowing that a service is defined by its endpoint, see it as a consumer. WCF can be consumed by client web apps, Silverlight apps and desktop apps. The endpoints themselves have configuration settings as well specifically relating to message sizes. </p>
<p>From the tutorial I was able to see that you can run a WCF service in a browser, without having IIS running. Thats something I need to think about but it does pose a few interesting questions. After I did the tutorial I wanted to do a simple REST service, and that took a few minutes but eventually got that sorted. StackOverflow was quite helpful and so was several articles on MSDN, with <a href="http://msdn.microsoft.com/en-us/library/bb885100.aspx" onclick="urchinTracker('/outgoing/msdn.microsoft.com/en-us/library/bb885100.aspx?referer=');">this one</a> being the most helpful.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save" onclick="urchinTracker('/outgoing/www.addtoany.com/share_save?referer=');"><img src="http://www.fremus.co.za/blog/wp-content/plugins/add-to-any/favicon.png" width="16" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.fremus.co.za/blog/2009/12/wcf-getting-the-foundations-right/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using System.Uri&#8217;s Segments property and List().ForEach</title>
		<link>http://www.fremus.co.za/blog/2009/11/using-system-uris-segments-property-and-list-foreach/</link>
		<comments>http://www.fremus.co.za/blog/2009/11/using-system-uris-segments-property-and-list-foreach/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 08:20:59 +0000</pubDate>
		<dc:creator>fr3dr1k</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.fremus.co.za/blog/?p=542</guid>
		<description><![CDATA[You know the feeling when you see someone use a property and you go, nice, I never knew that. Well last night that happened to me after reading Scott Hanselman&#8217;s article on Windows Powershell. In the article he created a script that automatically downloaded his podcasts. To do this he use the System.Uri class which [...]]]></description>
			<content:encoded><![CDATA[<p>You know the feeling when you see someone use a property and you go, nice, I never knew that. Well last night that happened to me after reading Scott Hanselman&#8217;s article on Windows Powershell. In the article he created a script that automatically downloaded his podcasts. To do this he use the System.Uri class which has a property called Segments. Segments returns a string array which consists of elements in a Uri separated by a forward slash &#8216;/&#8217;. So lets say you have this url:</p>
<p>http://developer.yahoo.com/yap/guide/caja-support.html</p>
<p>You could then use System.Uri to get all the bits in the Uri like this:</p>
<pre name="code" class="csharp">
            Uri url = new Uri("http://developer.yahoo.com/yap/guide/caja-support.html");

            string[] arrUri = url.Segments;
            var item = from u in arrUri
                       select u;

            foreach (string s in item)
            {
                Console.WriteLine(s);
            }
</pre>
<p>Something else I started doing or using yesterday is the ToList().ForEach delegate method. I noticed it in the LinqToTwitter api:</p>
<pre name="code" class="csharp">

            var twitterTrends = from trends in tCtx.Trends
                                select trends;

            twitterTrends.ToList().ForEach(t =>
                Console.WriteLine(t.Query));
</pre>
<p>The ForEach works on a list as well, so if you take the same code I wrote earlier using a foreach loop for the Uri segments you can rewrite that as:</p>
<pre name="code" class="csharp">

item.ToList().ForEach(s => Console.WriteLine(s));
</pre>
<p>The variable s is an anonymous type so it infers from the type what type it is. That is shorter code, not sure if its more efficient, but it sure looks nicer.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save" onclick="urchinTracker('/outgoing/www.addtoany.com/share_save?referer=');"><img src="http://www.fremus.co.za/blog/wp-content/plugins/add-to-any/favicon.png" width="16" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.fremus.co.za/blog/2009/11/using-system-uris-segments-property-and-list-foreach/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting POST values with an ASHX file</title>
		<link>http://www.fremus.co.za/blog/2009/11/getting-post-values-with-an-ashx-file/</link>
		<comments>http://www.fremus.co.za/blog/2009/11/getting-post-values-with-an-ashx-file/#comments</comments>
		<pubDate>Wed, 04 Nov 2009 12:56:32 +0000</pubDate>
		<dc:creator>fr3dr1k</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Web Technologies]]></category>

		<guid isPermaLink="false">http://www.fremus.co.za/blog/?p=536</guid>
		<description><![CDATA[Today I had this scenario where I wanted to post items from multiple HTML input elements to a generic handler (.ashx) file without using the action attribute of the form. Specifying the action meant that that you are navigated away from the page where the action is happening, which means re-creating UI logic. How did [...]]]></description>
			<content:encoded><![CDATA[<p>Today I had this scenario where I wanted to post items from multiple HTML input elements to a generic handler (.ashx) file without using the action attribute of the form. Specifying the action meant that that you are navigated away from the page where the action is happening, which means re-creating UI logic. How did I achieve this? By using an XMLHttpRequest and using a POST method. GET places everything inside a querystring, which is ok, but I just wondered what would happen if the content was too long for the querystring. I guess the same can be said for POST, but it just seems POST uses a different way to transfer the data. So lets say you had this JavaScript:</p>
<pre name="code" class="javascript">
    getXMLHTTPPostObject: function(url, elementName, parameters) {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else {
            alert("Your browser does not support XMLHTTP!");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {
                document.getElementById(elementName).innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("POST", url, true);
        xmlhttp.send(parameters);
    }
</pre>
<p>I use this function to create an XMLHttpRequest object by passing it:</p>
<ul>
<li>the URL for the AJAX call</li>
<li>an elementName to put the result of request in</li>
<li>A parameter list</li>
</ul>
<p>I then have a function like this:</p>
<pre name="code" class="javascript">
    addPost: function() {
        objXMLHTTP.getXMLHTTPPostObject("url to handler", "categoryTemp", "postTitle=" + document.getElementById("txtPostTitle").value + "&#038;blogpost=" + document.getElementById("txtBlogPost").value);
    }
</pre>
<p>The function gets the values of two HTML input elements and passes it as parameters. The parameters are then used in the POST HTTPMethod. My next challenge was to get the data in the generic handler (.ashx) so that I can process it. I also wanted to return the data from the ASHX file to see that its processed successfully. So in my handler I created this code:</p>
<pre name="code" class="csharp">
        context.Response.ContentType = "text/plain";
        System.IO.Stream body = context.Request.InputStream;
        System.Text.Encoding encoding = context.Request.ContentEncoding;
        System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
        //if (context.Request.ContentType != null)
        //{
        //    context.Response.Write("Client data content type " + context.Request.ContentType);
        //}
        string s = reader.ReadToEnd();
        string[] content = s.Split('&#038;');
        for (int i = 0; i < content.Length; i++)
        {
            string[] fields = content[i].Split('=');
            context.Response.Write("
<div><strong>" + fields[0] + "</strong></div>

");
            context.Response.Write("
<div>" + fields[1] + "</div>

");
        }
        //context.Response.Write(s);
        body.Close();
        reader.Close();
</pre>
<p>I first create a class of type Stream that is instantiated through the Response.InputStream property, after which I set the content encoding for the response object. I then create a StreamReader instance and call its ReadToEnd method. After this I do some string manipulation and return the text back to the XMLHttpRequest object, which then writes the content to an HTML Element.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save" onclick="urchinTracker('/outgoing/www.addtoany.com/share_save?referer=');"><img src="http://www.fremus.co.za/blog/wp-content/plugins/add-to-any/favicon.png" width="16" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.fremus.co.za/blog/2009/11/getting-post-values-with-an-ashx-file/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting a single XAttribute or XElement</title>
		<link>http://www.fremus.co.za/blog/2009/11/getting-a-single-xattribute-or-xelement/</link>
		<comments>http://www.fremus.co.za/blog/2009/11/getting-a-single-xattribute-or-xelement/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 13:15:43 +0000</pubDate>
		<dc:creator>fr3dr1k</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ to XML]]></category>
		<category><![CDATA[XAttribute]]></category>
		<category><![CDATA[XElement]]></category>

		<guid isPermaLink="false">http://www.fremus.co.za/blog/?p=534</guid>
		<description><![CDATA[I have come across two ways querying XElements or XAttributes: Make an object IEnumerable and loop through the results Use the Single() method to return a single object only Typically you may have a situation where you write some Linq-to-XML like this: IEnumerable attrib = from att in elemInner.Attributes() where (string)att.Name.ToString() == "sectionName" select att; [...]]]></description>
			<content:encoded><![CDATA[<p>I have come across two ways querying XElements or XAttributes:</p>
<ul>
<li>Make an object IEnumerable and loop through the results</li>
<li>Use the <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.single.aspx" onclick="urchinTracker('/outgoing/msdn.microsoft.com/en-us/library/system.linq.enumerable.single.aspx?referer=');">Single()</a> method to return a single object only</li>
</ul>
<p>Typically you may have a situation where you write some Linq-to-XML like this:</p>
<pre name="code" class="csharp">
IEnumerable<XAttribute> attrib = from att in elemInner.Attributes()
                                             where (string)att.Name.ToString() == "sectionName"
                                             select att;
</pre>
<p>To loop through the results you have to use a foreach loop like this:</p>
<pre name="code" class="csharp">

foreach (XAttribute innerAttrib in attrib)
{
     builder.AppendLine("
<h3>" + innerAttrib.Value +"</h3>

");
}
</pre>
<p>If however you just wanted a single attribute result, you could write the same code like this:</p>
<pre name="code" class="csharp">

 XAttribute attribDisplayStyle = (from att in elemInner.Attributes()
                                            where (string)att.Name.ToString() == "sectionName"
                                            select att).Single();
</pre>
<p>Then you only have a single XAttribute instance and you dont need a foreach loop:</p>
<pre name="code" class="csharp">

attribDisplayStyle.Value;
</pre>
<p>You would apply the same logic to XElement as well.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save" onclick="urchinTracker('/outgoing/www.addtoany.com/share_save?referer=');"><img src="http://www.fremus.co.za/blog/wp-content/plugins/add-to-any/favicon.png" width="16" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.fremus.co.za/blog/2009/11/getting-a-single-xattribute-or-xelement/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
