<?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>James Ball</title>
	<atom:link href="http://jwball.co.uk/feed/" rel="self" type="application/rss+xml" />
	<link>http://jwball.co.uk</link>
	<description></description>
	<lastBuildDate>Sat, 14 Jan 2012 11:57:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>The Singleton Repository Pattern &#8211; Part I</title>
		<link>http://jwball.co.uk/2012/01/the-singleton-repository-pattern-part-i/</link>
		<comments>http://jwball.co.uk/2012/01/the-singleton-repository-pattern-part-i/#comments</comments>
		<pubDate>Sat, 14 Jan 2012 11:57:23 +0000</pubDate>
		<dc:creator>James Ball</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://jwball.co.uk/?p=248</guid>
		<description><![CDATA[For the last few months I’ve been working on a small to medium sized project (~20,000 lines of code) that’s built using WCF RIA and has a Silverlight front end. Up until recently it used a standard DomainService which simply called into Entity Framework with business logic implemented as named update methods in the domain [...]]]></description>
			<content:encoded><![CDATA[<p>For the last few months I’ve been working on a small to medium sized project (~20,000 lines of code) that’s built using WCF RIA and has a Silverlight front end. Up until recently it used a standard DomainService which simply called into Entity Framework with business logic implemented as named update methods in the domain service.</p>
<p>This worked fine, but had two key disadvantages:</p>
<ul>
<li>Difficult to unit test.</li>
<li>Difficult and cumbersome to use the business logic in an ASP.NET application without needlessly instantiating and calling into a DomainService object.</li>
</ul>
<p>My first though was to use the repository pattern which acts as an additional layer between the ORM (Entity Framework in this case) and either the WCF RIA domain service or a straight forward ASP.NET application. However, this approach also has several drawbacks.</p>
<ul>
<li>It still doesn&#8217;t address where to place business logic that has dependencies on multiple entity types.</li>
<li>Each type of entity requires its own strongly typed repository class. In a system with a large number of tables this quickly becomes tedious and hard to maintain.</li>
</ul>
<p>The solution is the Singleton Repository, which is a generic repository that can be used to handle CRUD operations for any type that derives from EntityObject (as long as your associated DomainContext has the particular entity).</p>
<pre class="brush: csharp; title: ; notranslate">
public partial class Despatcher
{
	[ThreadStatic]
	private static Despatcher _instance;

	private ObjectContext _context;

	public static Despatcher Instance
	{
		get
		{
			if (_instance == null)
			{
				_instance = new Despatcher();
			}

			return _instance;
		}
	}

	public ObjectContext Context
	{
		get { return _context; }
		set { _context = value; }
	}

	private Despatcher() { }
}
</pre>
<p>In its present form, we can&#8217;t yet query against the singleton repository without making direct use of the Context property, which would defeat the whole point of having an additional layer of abstraction. The answer is to add a single generic method called GetQuery which returns the correct ObjectQuery for the specified entity type.</p>
<pre class="brush: csharp; title: ; notranslate">
public ObjectQuery&lt;TEntity&gt; GetQuery&lt;TEntity&gt;() where TEntity : EntityObject
{
	if (_context == null)
	{
		throw new Exception(&quot;Context not set&quot;);
	}

	return _context.CreateObjectSet&lt;TEntity&gt;();
}
</pre>
<p>Its then possible to query against the repository without having any knowledge of the underlying ORM or data source.</p>
<pre class="brush: csharp; title: ; notranslate">
var staff = Despatcher.Instance.GetQuery&lt;Staff&gt;().Where(s =&gt; s.Name == &quot;James&quot;);
</pre>
<p>Note that because the repository is a singleton, the same instance can be accessed from anywhere, which means that entity objects can be extended with complex business logic that itself requires the ability to issue queries. For example, something like the following becomes easy:</p>
<pre class="brush: csharp; title: ; notranslate">
public partial class Doctor
{
	public void Sack()
	{
		this.IsSacked = true;

		/* Update patients */
                var patients = Despatcher.Instance.GetQuery&lt;Patient&gt;().Where(d =&gt; d.DoctorID == this.DoctorID)
		foreach(var patient in patients)
		{
			patient.RequiresNewDoctor = true;
		}
	}
}
</pre>
<p>Some would argue that the Sack method should not issue a query and only iterate over the patients loading into the Doctor.Patients EntityCollection. This however has several issues, the first being that it requires (if lazy loading is off) the caller to have knowledge of which relationships to load that the callee will need. If lazy loading is on, the extra care is needed when sending data back to the client through the domain service.</p>
<p>In the next part, I&#8217;ll be looking into generic inserts, updates and deletes which also have the ability to perform custom logic for specific entity types.</p>

				<!-- Social Sharing Toolkit v2.0.4 | http://www.marijnrongen.com/wordpress-plugins/social_sharing_toolkit/ -->
				<div class="mr_social_sharing_wrapper"><span class="mr_social_sharing"><iframe src="https://www.facebook.com/plugins/like.php?locale=en_US&amp;href=http%3A%2F%2Fjwball.co.uk%2F2012%2F01%2Fthe-singleton-repository-pattern-part-i%2F&amp;layout=standard&amp;show_faces=false&amp;width=51px&amp;height=24px" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:51px; height:24px;" allowTransparency="true"></iframe></span><span class="mr_social_sharing"><a href="http://twitter.com/share?url=http%3A%2F%2Fjwball.co.uk%2F2012%2F01%2Fthe-singleton-repository-pattern-part-i%2F&amp;text=The+Singleton+Repository+Pattern+%E2%80%93+Part+I" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/twitter.png" alt="Share on Twitter" title="Share on Twitter"/></a></span><span class="mr_social_sharing"><g:plusone size="medium" count="false" href="http://jwball.co.uk/2012/01/the-singleton-repository-pattern-part-i/"></g:plusone></span><span class="mr_social_sharing"><script type="IN/Share" data-url="http://jwball.co.uk/2012/01/the-singleton-repository-pattern-part-i/"></script></span><span class="mr_social_sharing"><a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fjwball.co.uk%2F2012%2F01%2Fthe-singleton-repository-pattern-part-i%2F&amp;title=The+Singleton+Repository+Pattern+%E2%80%93+Part+I" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/stumbleupon.png" alt="Submit to StumbleUpon" title="Submit to StumbleUpon"/></a></span><span class="mr_social_sharing"><a href="http://digg.com/submit?url=http%3A%2F%2Fjwball.co.uk%2F2012%2F01%2Fthe-singleton-repository-pattern-part-i%2F&amp;title=The+Singleton+Repository+Pattern+%E2%80%93+Part+I" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/digg.png" alt="Digg This" title="Digg This"/></a></span></div>]]></content:encoded>
			<wfw:commentRss>http://jwball.co.uk/2012/01/the-singleton-repository-pattern-part-i/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Design-Time T4 Templates</title>
		<link>http://jwball.co.uk/2011/12/design-time-t4-templates/</link>
		<comments>http://jwball.co.uk/2011/12/design-time-t4-templates/#comments</comments>
		<pubDate>Wed, 07 Dec 2011 01:22:12 +0000</pubDate>
		<dc:creator>James Ball</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[T4]]></category>

		<guid isPermaLink="false">http://jwball.co.uk/?p=228</guid>
		<description><![CDATA[Design-time T4 text templates are a useful feature of Visual Studio that allow us to do a little meta-programming and generate code (or text) which is then compiled as part of a project. One problem I recently came up against which is nicely solved by T4 is a slight difficulty in using F#&#8217;s discriminated unions [...]]]></description>
			<content:encoded><![CDATA[<p>Design-time T4 text templates are a useful feature of Visual Studio that allow us to do a little meta-programming and generate code (or text) which is then compiled as part of a project. One problem I recently came up against which is nicely solved by T4 is a slight difficulty in using F#&#8217;s discriminated unions from C#.</p>
<p>In an F# class library project called Foo, I have the following types defined:</p>
<pre class="brush: fsharp; title: ; notranslate">
namespace Foo

type Vehicle =
    | LandVehicle of LandVehicle
    | WaterVehicle of WaterVehicle
    | AirVehicle of AirVehicle
    | SpaceVehicle of SpaceVehicle

and LandVehicle =
    | PersonalLandVehicle  of PersonalLandVehicle
    | PublicLandVehicle of PublicLandVehicle

and PersonalLandVehicle =
    | Car
    | Bike

... *snip* ...

module Something =
    let GetVehicle() =
        Vehicle.LandVehicle(LandVehicle.PersonalLandVehicle(PersonalLandVehicle.Bike))
</pre>
<p>I also have a C# project called Bar which makes use of the GetVehicle function defined in Foo.</p>
<pre class="brush: csharp; title: ; notranslate">
Vehicle vehicle = Foo.Something.GetVehicle();
</pre>
<p>In order to take an appropriate action depending on whether or not <code>vehicle </code>is any of <code>LandVehicle, WaterVehicle, AirVehicle, SpaceVehicle</code>, it&#8217;s necessary to do something like:</p>
<pre class="brush: csharp; title: ; notranslate">
if (vehicle.IsAirVehicle)
{
	AirVehicle airVehicle = ((Vehicle.AirVehicle)vehicle).Item;
}
else if (vehicle.IsLandVehicle)
{
	LandVehicle landVehicle = ((Vehicle.LandVehicle)vehicle).Item;
}
else if (vehicle.IsSpaceVehicle)
{
	SpaceVehicle spaceVehicle = ((Vehicle.SpaceVehicle)vehicle).Item;
}
else if (vehicle.IsWaterVehicle)
{
	WaterVehicle waterVehicle = ((Vehicle.WaterVehicle)vehicle).Item;
}
</pre>
<p>Note the ugly and awkward typecast which quickly becomes cumbersome when you have many of these unions in a structure such as an AST. However, it can be remedied with the use of an extension methods like this:</p>
<pre class="brush: csharp; title: ; notranslate">
public static class Extensions
{
	public static AirVehicle AsAirVehicle(this Vehicle vehicle)
	{
		return ((Vehicle.AirVehicle)vehicle).Item;
	}

	public static LandVehicle AsLandVehicle(this Vehicle vehicle)
	{
		return ((Vehicle.LandVehicle)vehicle).Item;
	}
}
</pre>
<p>It&#8217;s then possible to replace the ugly typecasting with a more eloquent expression</p>
<pre class="brush: csharp; title: ; notranslate">
AirVehicle airVehicle = vehicle.AsAirVehicle();
</pre>
<p>Of course, we have to write an extension method for each discriminated union and for each of its cases, so for Vehicle and LandVehicle alone we will need 6 extension methods that are fairly identical.</p>
<p>This is where T4 comes into play. First, let&#8217;s add a &#8220;Text Template&#8221; named &#8220;Extensions.tt&#8221; to the C# solution. The next thing to do is open it up, and change the line
<pre class="brush: plain; title: ; notranslate">&lt;#@ output extension=&quot;.txt&quot; #&gt;</pre>
<p> to read
<pre class="brush: plain; title: ; notranslate">&lt;#@ output extension=&quot;.cs&quot; #&gt;</pre>
<p>, which tells T4 to output C# source code. We also need to add the following lines to load the required assemblies:</p>
<pre class="brush: plain; title: ; notranslate">
&lt;#@ assembly name=&quot;System.Core&quot; #&gt;
&lt;#@ assembly name=&quot;FSharp.Core&quot; #&gt;
&lt;#@ import namespace=&quot;System.Linq&quot; #&gt;
&lt;#@ import namespace=&quot;Microsoft.FSharp.Core&quot; #&gt;
</pre>
<p>Now add</p>
<pre class="brush: plain; title: ; notranslate">
using Foo;

namespace Bar
{
	public static class Extensions
	{
		&lt;#
		#&gt;
	}
}
</pre>
<p>Note that any C# code between the <code><#</code> and <code>#></code> symbols will be executed when the template is parsed. It's possible to output text from within the code block by calling "WriteLine" (Not Console.WriteLine!). Now for the interesting bit, we need to somehow loop over all of the types defined in Foo and output the C# source for their relevant extension methods. The final T4 template looks like this:</p>
<pre class="brush: plain; title: ; notranslate">
&lt;#@ template debug=&quot;false&quot; hostspecific=&quot;false&quot; language=&quot;C#&quot; #&gt;
&lt;#@ output extension=&quot;.cs&quot; #&gt;
&lt;#@ assembly name=&quot;System.Core&quot; #&gt;
&lt;#@ assembly name=&quot;FSharp.Core&quot; #&gt;
&lt;#@ import namespace=&quot;System.Linq&quot; #&gt;
&lt;#@ import namespace=&quot;Microsoft.FSharp.Core&quot; #&gt;

using Foo;

namespace Bar
{
	public static class Extensions
	{
		&lt;#
			PushIndent(&quot;\t&quot;);
			PushIndent(&quot;\t&quot;);

			var asm = System.Reflection.Assembly.LoadFrom(@&quot;Z:\Path\To\Foo.dll&quot;);
			foreach (var type in asm.GetTypes().Where(t =&gt; t.Namespace == &quot;Foo&quot; &amp;&amp; t.IsNested == false))
			{
				foreach(var attr in type.GetCustomAttributes(typeof(CompilationMappingAttribute), true))
				{
					if (((CompilationMappingAttribute)attr).SourceConstructFlags == SourceConstructFlags.SumType)
					{
						foreach (var nested in type.GetNestedTypes().Where(t =&gt; t.Name != &quot;Tags&quot; &amp;&amp; t.Name != type.Name))
						{
							WriteLine(&quot;public static {0} As{1}(this {2} node)&quot;, nested.Name, nested.Name, type.Name);
							WriteLine(&quot;{&quot;);
							PushIndent(&quot;\t&quot;);

							WriteLine(&quot;return (({0}.{1})node).Item;&quot;, type.Name, nested.Name);

							PopIndent();
							WriteLine(&quot;}&quot;);
							WriteLine(&quot;&quot;);
						}
					}
				}
			}

			PopIndent();
			PopIndent();
		#&gt;
	}
}
</pre>
<p><strong>Important:</strong> Note the line <code>var asm = System.Reflection.Assembly.LoadFrom(@"Z:\Path\To\Foo.dll");</code>. We need to give an explicit path to the Foo.dll as the T4 engine runs outside of the scope of the project and we therefore could not access the Foo assembly through AppDomain for example.</p>
<p>The final step is to save "Extensions.tt", right click it in the solution explorer and select "Run Custom Tool". A new file, "Extensions.cs" should now be generated with all the required extension methods and looks something like</p>
<pre class="brush: csharp; title: ; notranslate">
using Foo;

namespace Bar
{
	public static class Extensions
	{
		public static LandVehicle AsLandVehicle(this Vehicle node)
		{
			return ((Vehicle.LandVehicle)node).Item;
		}

		public static WaterVehicle AsWaterVehicle(this Vehicle node)
		{
			return ((Vehicle.WaterVehicle)node).Item;
		}

		... *snip* ...
	}
}
</pre>

				<!-- Social Sharing Toolkit v2.0.4 | http://www.marijnrongen.com/wordpress-plugins/social_sharing_toolkit/ -->
				<div class="mr_social_sharing_wrapper"><span class="mr_social_sharing"><iframe src="https://www.facebook.com/plugins/like.php?locale=en_US&amp;href=http%3A%2F%2Fjwball.co.uk%2F2011%2F12%2Fdesign-time-t4-templates%2F&amp;layout=standard&amp;show_faces=false&amp;width=51px&amp;height=24px" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:51px; height:24px;" allowTransparency="true"></iframe></span><span class="mr_social_sharing"><a href="http://twitter.com/share?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F12%2Fdesign-time-t4-templates%2F&amp;text=Design-Time+T4+Templates" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/twitter.png" alt="Share on Twitter" title="Share on Twitter"/></a></span><span class="mr_social_sharing"><g:plusone size="medium" count="false" href="http://jwball.co.uk/2011/12/design-time-t4-templates/"></g:plusone></span><span class="mr_social_sharing"><script type="IN/Share" data-url="http://jwball.co.uk/2011/12/design-time-t4-templates/"></script></span><span class="mr_social_sharing"><a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F12%2Fdesign-time-t4-templates%2F&amp;title=Design-Time+T4+Templates" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/stumbleupon.png" alt="Submit to StumbleUpon" title="Submit to StumbleUpon"/></a></span><span class="mr_social_sharing"><a href="http://digg.com/submit?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F12%2Fdesign-time-t4-templates%2F&amp;title=Design-Time+T4+Templates" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/digg.png" alt="Digg This" title="Digg This"/></a></span></div>]]></content:encoded>
			<wfw:commentRss>http://jwball.co.uk/2011/12/design-time-t4-templates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Computing Perfect Numbers in F#</title>
		<link>http://jwball.co.uk/2011/10/computing-perfect-numbers-in-f/</link>
		<comments>http://jwball.co.uk/2011/10/computing-perfect-numbers-in-f/#comments</comments>
		<pubDate>Mon, 17 Oct 2011 17:17:33 +0000</pubDate>
		<dc:creator>James Ball</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Number Theory]]></category>

		<guid isPermaLink="false">http://jwball.co.uk/?p=205</guid>
		<description><![CDATA[In this (brief) post I&#8217;ll quickly look at how we can naively determine if a number is perfect using F#. A perfect number is an integer, whose proper factors sum to (where a proper factor is all the factors of except for itself). Now, a factor of is any integer, , in the set such [...]]]></description>
			<content:encoded><![CDATA[<p>In this (brief) post I&#8217;ll quickly look at how we can naively determine if a number is perfect using F#.</p>
<p>A perfect number is an integer, <img src='http://jwball.co.uk/latex.php?latex=n&#038;bg=ffffff&#038;fg=000000&#038;s=1' alt='n' title='n' class='latex' /> whose proper factors sum to <img src='http://jwball.co.uk/latex.php?latex=n&#038;bg=ffffff&#038;fg=000000&#038;s=1' alt='n' title='n' class='latex' /> (where a proper factor is all the factors of <img src='http://jwball.co.uk/latex.php?latex=n&#038;bg=ffffff&#038;fg=000000&#038;s=1' alt='n' title='n' class='latex' /> except for <img src='http://jwball.co.uk/latex.php?latex=n&#038;bg=ffffff&#038;fg=000000&#038;s=1' alt='n' title='n' class='latex' /> itself).</p>
<p>Now, a factor of <img src='http://jwball.co.uk/latex.php?latex=n&#038;bg=ffffff&#038;fg=000000&#038;s=1' alt='n' title='n' class='latex' /> is any integer, <img src='http://jwball.co.uk/latex.php?latex=i&#038;bg=ffffff&#038;fg=000000&#038;s=1' alt='i' title='i' class='latex' />, in the set <img src='http://jwball.co.uk/latex.php?latex=%5Cleft%5C%7B%201%2C%202%2C%203%2C%20..%20%2C%20n%5Cright%5C%7D&#038;bg=ffffff&#038;fg=000000&#038;s=1' alt='\left\{ 1, 2, 3, .. , n\right\}' title='\left\{ 1, 2, 3, .. , n\right\}' class='latex' /> such that <img src='http://jwball.co.uk/latex.php?latex=%5Cfrac%7Bn%7D%7Bi%7D&#038;bg=ffffff&#038;fg=000000&#038;s=1' alt='\frac{n}{i}' title='\frac{n}{i}' class='latex' /> is a whole number.</p>
<p>This can be expressed rather eloquently in F# as a lazily evaluated sequence:</p>
<pre class="brush: fsharp; title: ; notranslate">
let get_factors b =
    seq { 1 .. b } |&gt; Seq.filter(fun a -&gt; b % a = 0)

let get_proper_factors b =
    seq { 1 .. (b-1) } |&gt; Seq.filter(fun a -&gt; b % a = 0)
</pre>
<p>The method for determining if a number is perfect should now be clear:</p>
<pre class="brush: fsharp; title: ; notranslate">
let is_perfect b =
    match b with
    | 0 -&gt; false
    | _ -&gt; (b |&gt; get_proper_factors |&gt; Seq.sum) = b
</pre>

				<!-- Social Sharing Toolkit v2.0.4 | http://www.marijnrongen.com/wordpress-plugins/social_sharing_toolkit/ -->
				<div class="mr_social_sharing_wrapper"><span class="mr_social_sharing"><iframe src="https://www.facebook.com/plugins/like.php?locale=en_US&amp;href=http%3A%2F%2Fjwball.co.uk%2F2011%2F10%2Fcomputing-perfect-numbers-in-f%2F&amp;layout=standard&amp;show_faces=false&amp;width=51px&amp;height=24px" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:51px; height:24px;" allowTransparency="true"></iframe></span><span class="mr_social_sharing"><a href="http://twitter.com/share?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F10%2Fcomputing-perfect-numbers-in-f%2F&amp;text=Computing+Perfect+Numbers+in+F%23" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/twitter.png" alt="Share on Twitter" title="Share on Twitter"/></a></span><span class="mr_social_sharing"><g:plusone size="medium" count="false" href="http://jwball.co.uk/2011/10/computing-perfect-numbers-in-f/"></g:plusone></span><span class="mr_social_sharing"><script type="IN/Share" data-url="http://jwball.co.uk/2011/10/computing-perfect-numbers-in-f/"></script></span><span class="mr_social_sharing"><a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F10%2Fcomputing-perfect-numbers-in-f%2F&amp;title=Computing+Perfect+Numbers+in+F%23" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/stumbleupon.png" alt="Submit to StumbleUpon" title="Submit to StumbleUpon"/></a></span><span class="mr_social_sharing"><a href="http://digg.com/submit?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F10%2Fcomputing-perfect-numbers-in-f%2F&amp;title=Computing+Perfect+Numbers+in+F%23" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/digg.png" alt="Digg This" title="Digg This"/></a></span></div>]]></content:encoded>
			<wfw:commentRss>http://jwball.co.uk/2011/10/computing-perfect-numbers-in-f/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>F# &#8211; Sequences and Lists</title>
		<link>http://jwball.co.uk/2011/07/f-sequences-and-lists/</link>
		<comments>http://jwball.co.uk/2011/07/f-sequences-and-lists/#comments</comments>
		<pubDate>Sun, 03 Jul 2011 20:19:04 +0000</pubDate>
		<dc:creator>James Ball</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://jwball.co.uk/?p=188</guid>
		<description><![CDATA[Two useful features of F# are its lists and sequences, both provide similar functionality but with quite drastically different implementations. A sequence is simply an alias for .NET&#8217;s IEnumerable and is therefore evaluated lazily; elements are only computed as they are needed (enumerated over). A list (despite its name) is unrelated to .NET&#8217;s List. It [...]]]></description>
			<content:encoded><![CDATA[<p>Two useful features of F# are its lists and sequences, both provide similar functionality but with quite drastically different implementations.</p>
<p>A sequence is simply an alias for .NET&#8217;s IEnumerable and is therefore evaluated lazily; elements are only computed as they are needed (enumerated over).</p>
<p>A list (despite its name) is unrelated to .NET&#8217;s List. It is an unchangeable (immutable) collection of elements that is evaluated eagerly. Internally they are implemented with the use of a linked list structure which is in contrast to .NET&#8217;s List which internally uses an array. In practical terms, this means that reading elements in F#&#8217;s list becomes progressively slower the further down the list one goes, whilst in .NET&#8217;s List element access times remain constant. However, the fact that F# lists are immutable gives them a sharp advantage over standard .NET Lists in some scenarios.</p>
<p>First, lets look at how a sequence is defined.</p>
<pre class="brush: fsharp; title: ; notranslate">
let squares_seq n =
    seq { for i in 0..n -&gt; (i, i*i) }
</pre>
<p>The squares_seq function returns a sequence of tuples; the first element of each tuple is a number and the second element is that number&#8217;s square.</p>
<p>Now for the same function, but returning a list:</p>
<pre class="brush: fsharp; title: ; notranslate">
let squares_list n =
    [ for i in 0..n -&gt; (i, i*i) ]
</pre>
<p>The code is almost identical except for the square rather than curly braces, as well as the obvious emission of the seq keyword.</p>
<p>If each of these functions was iterated over in a for loop, the effect would be identical:</p>
<pre class="brush: fsharp; title: ; notranslate">
let n = 10

for (i, s) in (squares_seq n) do
    printfn &quot;The square of %d id %d&quot; i s

for (i, s) in (squares_list n) do
    printfn &quot;The square of %d id %d&quot; i s
</pre>
<p>However, drastic differences can be seen when we dig deeper and give thought to the eagerness of the list and the laziness of the sequence. Consider the following code:</p>
<pre class="brush: fsharp; title: ; notranslate">
open System.Diagnostics
let n = 1000000

stopwatch.Start()
squares_seq n |&gt; ignore
stopwatch.Stop()
stopwatch.ElapsedMilliseconds |&gt; printfn &quot;Seq time: %d&quot;

stopwatch.Restart()
squares_list n |&gt; ignore
stopwatch.Stop()
stopwatch.ElapsedMilliseconds |&gt; printfn &quot;List time: %d&quot;
</pre>
<p>Which produces the following output:</p>
<pre class="brush: plain; title: ; notranslate">
Seq time: 1
List time: 693
</pre>
<p>No matter how many elements are in the sequence it will always take exactly the same amount of time to instantiate it as any computation is deferred.</p>
<p>This is further demonstrated if we time how long it takes to iterate over both the sequence and the list once they have already been instantiated.</p>
<pre class="brush: fsharp; title: ; notranslate">
stopwatch.Start()
for (i, s) in squares_seq n do
    (i, s) |&gt; ignore
stopwatch.Stop()
stopwatch.ElapsedMilliseconds |&gt; printfn &quot;Seq time: %d&quot;

stopwatch.Reset()
for (i, s) in squares_list n do
    (i, s) |&gt; ignore
stopwatch.Stop()
stopwatch.ElapsedMilliseconds |&gt; printfn &quot;List time: %d&quot;
</pre>
<p>Which produces the output:</p>
<pre class="brush: plain; title: ; notranslate">
Seq time: 304
List time: 0
</pre>
<p>Presumably, because the list has already been computed and the for loop does nothing, it is optimized out by the compiler and thus takes 0 milliseconds, whilst the sequence for loop has quite a lot of hidden work to do.</p>
<p>It is interesting to note that it takes 304 milliseconds to iterate over the sequence and 693 milliseconds to instantiate the list; roughly twice slower for the same end results (in this particular non-rigorous test).</p>

				<!-- Social Sharing Toolkit v2.0.4 | http://www.marijnrongen.com/wordpress-plugins/social_sharing_toolkit/ -->
				<div class="mr_social_sharing_wrapper"><span class="mr_social_sharing"><iframe src="https://www.facebook.com/plugins/like.php?locale=en_US&amp;href=http%3A%2F%2Fjwball.co.uk%2F2011%2F07%2Ff-sequences-and-lists%2F&amp;layout=standard&amp;show_faces=false&amp;width=51px&amp;height=24px" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:51px; height:24px;" allowTransparency="true"></iframe></span><span class="mr_social_sharing"><a href="http://twitter.com/share?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F07%2Ff-sequences-and-lists%2F&amp;text=F%23+%E2%80%93+Sequences+and+Lists" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/twitter.png" alt="Share on Twitter" title="Share on Twitter"/></a></span><span class="mr_social_sharing"><g:plusone size="medium" count="false" href="http://jwball.co.uk/2011/07/f-sequences-and-lists/"></g:plusone></span><span class="mr_social_sharing"><script type="IN/Share" data-url="http://jwball.co.uk/2011/07/f-sequences-and-lists/"></script></span><span class="mr_social_sharing"><a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F07%2Ff-sequences-and-lists%2F&amp;title=F%23+%E2%80%93+Sequences+and+Lists" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/stumbleupon.png" alt="Submit to StumbleUpon" title="Submit to StumbleUpon"/></a></span><span class="mr_social_sharing"><a href="http://digg.com/submit?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F07%2Ff-sequences-and-lists%2F&amp;title=F%23+%E2%80%93+Sequences+and+Lists" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/digg.png" alt="Digg This" title="Digg This"/></a></span></div>]]></content:encoded>
			<wfw:commentRss>http://jwball.co.uk/2011/07/f-sequences-and-lists/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Real and Protected Segmentation</title>
		<link>http://jwball.co.uk/2011/04/real-and-protected-segmentation/</link>
		<comments>http://jwball.co.uk/2011/04/real-and-protected-segmentation/#comments</comments>
		<pubDate>Wed, 27 Apr 2011 11:00:54 +0000</pubDate>
		<dc:creator>James Ball</dc:creator>
				<category><![CDATA[Assembly]]></category>
		<category><![CDATA[OS Development]]></category>

		<guid isPermaLink="false">http://jwball.co.uk/?p=153</guid>
		<description><![CDATA[One of things that lead to the downfall of my first attempt to write an operating system last summer was not fully understanding how segmentation works and that there are two different types depending on the CPUs mode. In real mode, segmentation is quite simple. A logical address consists of a segment and an offset. [...]]]></description>
			<content:encoded><![CDATA[<p>One of things that lead to the downfall of my first attempt to write an operating system last summer was not fully understanding how segmentation works and that there are two different types depending on the CPUs mode.</p>
<p>In real mode, segmentation is quite simple. A <em>logical</em> address consists of a segment and an offset. This logical address is then converted to a physical address internally by the CPU. To convert the logical address to a physical one, the CPU shifts the segment value 4 bits to the left (equivalent to multiplication by 16) and then adds the value of the offset.</p>
<p>Let&#8217;s look at an example:</p>
<pre class="brush: asm; title: ; notranslate">
mov word ax, [0x07c0:0x0200]
</pre>
<p>So, the segment is 0x07c0 (which refers to the 0x07c0th 64KiB block of memory). First, the segment is shifted 4 bits to the right, leaving us with 0x7c00. Then the offset (0&#215;0200) is added, leaving us with a physical address of 0x7e00. </p>
<p>Pretty simple huh? </p>
<p>One problem you may notice with this is that there isn&#8217;t a unique logical address for each physical address, for example:</p>
<pre class="brush: asm; title: ; notranslate">
mov word ax, [0x07c0:0x0200]
mov word ax, [0x07e0:0x0000]
</pre>
<p>Both instructions refer to exactly the same physical address (0x7e00)!</p>
<p>The story in protected land becomes a little more complex. Segments no longer refer to a 64KiB block of memory, instead they have the following form:</p>
<p>The lowest 2 bits of the segment describe the privilege level that the segment expects to be accessed in (i.e. 0 is ring 0, 1 is ring 1, etc)</p>
<p>The next bit describes which table the CPU should look the segment index up in. A clear bit indicates the segment will be found in the GDT, whilst a set bit indicates it&#8217;ll be found in the LDT.</p>
<p>The remaining 13 bits are the segment index, the index points to an entry in either the LDT or GDT.</p>
<p>In protected mode, a logical address is converted first to a linear address by the CPU. The linear address is then sent through the paging unit to be converted to a physical address.</p>
<p>The conversion to a linear address is performed by taking the upper 13 bits of the segment selector, multiplying it by 8 (the size of an entry in either the GDT and LDT) and using the resulting value as a pointer to the segment descriptor in either the GDT or LDT. The correct segment descriptor contains the linear base address of the segment, which is taken by the CPU and added to the offset.</p>
<p>So for example,</p>
<pre class="brush: asm; title: ; notranslate">
jmp 0x08:0x0200</pre>
<p>The segment is 0&#215;08, or 00001000 in binary. The lower two bits (bit 0 and 1) with a value of 0 show that the segment should only be accessed in ring 0 and the next bit (bit 2) shows that the segment descriptor can be found in the GDT. The remaining 13 bits simply equal 1, which tells the CPU that the corresponding segment descriptor is at position 1 in the GDT.</p>
<p>If the segment descriptor at position 1 in the GDT had a base address of 0xcafe then the CPU adds the base to the offset (0&#215;0200) to give the linear address of 0xccfe. Other checks are made such as checking the privilege level, read and write access, etc. and if they fail, the CPU will raise an exception.</p>
<p>I will be discussing segment descriptors and the GDT in a later post.</p>
<p>Exercise: Look up segment descriptors, the GDT and the LDT in the <a href="http://www.intel.com/products/processor/manuals/">Intel x86 Manual, Volume 3</a>.</p>

				<!-- Social Sharing Toolkit v2.0.4 | http://www.marijnrongen.com/wordpress-plugins/social_sharing_toolkit/ -->
				<div class="mr_social_sharing_wrapper"><span class="mr_social_sharing"><iframe src="https://www.facebook.com/plugins/like.php?locale=en_US&amp;href=http%3A%2F%2Fjwball.co.uk%2F2011%2F04%2Freal-and-protected-segmentation%2F&amp;layout=standard&amp;show_faces=false&amp;width=51px&amp;height=24px" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:51px; height:24px;" allowTransparency="true"></iframe></span><span class="mr_social_sharing"><a href="http://twitter.com/share?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F04%2Freal-and-protected-segmentation%2F&amp;text=Real+and+Protected+Segmentation" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/twitter.png" alt="Share on Twitter" title="Share on Twitter"/></a></span><span class="mr_social_sharing"><g:plusone size="medium" count="false" href="http://jwball.co.uk/2011/04/real-and-protected-segmentation/"></g:plusone></span><span class="mr_social_sharing"><script type="IN/Share" data-url="http://jwball.co.uk/2011/04/real-and-protected-segmentation/"></script></span><span class="mr_social_sharing"><a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F04%2Freal-and-protected-segmentation%2F&amp;title=Real+and+Protected+Segmentation" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/stumbleupon.png" alt="Submit to StumbleUpon" title="Submit to StumbleUpon"/></a></span><span class="mr_social_sharing"><a href="http://digg.com/submit?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F04%2Freal-and-protected-segmentation%2F&amp;title=Real+and+Protected+Segmentation" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/digg.png" alt="Digg This" title="Digg This"/></a></span></div>]]></content:encoded>
			<wfw:commentRss>http://jwball.co.uk/2011/04/real-and-protected-segmentation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Converting Integers to Hex Strings</title>
		<link>http://jwball.co.uk/2011/04/converting-integers-to-hex-strings/</link>
		<comments>http://jwball.co.uk/2011/04/converting-integers-to-hex-strings/#comments</comments>
		<pubDate>Fri, 15 Apr 2011 14:05:55 +0000</pubDate>
		<dc:creator>James Ball</dc:creator>
				<category><![CDATA[Assembly]]></category>
		<category><![CDATA[ascii]]></category>
		<category><![CDATA[hex]]></category>

		<guid isPermaLink="false">http://jwball.co.uk/?p=50</guid>
		<description><![CDATA[This article focuses on how one can go about converting the value of a register to a hex string in x86 real mode assembly. The conversion is almost trivial if we remember that each hex digit directly maps to 4 bits. Let&#8217;s first define the routine which we are going to create; itoa_ax_hex takes the value [...]]]></description>
			<content:encoded><![CDATA[<p>This article focuses on how one can go about converting the value of a register to a hex string in x86 real mode assembly. The conversion is almost trivial if we remember that each hex digit directly maps to 4 bits.</p>
<p>Let&#8217;s first define the routine which we are going to create<em>; itoa_ax_hex</em> takes the value of <strong>AX</strong> and creates a 5 character hex string at the location pointed to by <strong>ES:DI</strong>. Note that the created string is <strong>not</strong> null terminated (the 5th character is for &#8216;h&#8217;). Not null terminating the string allows the calling code to easily copy the string into other strings.</p>
<p>Consider the value <strong>C0DEh</strong>, we can get the first hex digit by performing a bitwise AND with <strong>F000h</strong>, and then shifting the resulting value 12 bits to the right.</p>
<pre class="brush: asm; title: ; notranslate">mov ax, 0xc0de
mov bx, 0xf000
and ax, bx
shr ax, 12</pre>
<p>The value of <strong>AX</strong> is now simply <strong>Ch</strong>. We now need to convert <strong>AX</strong> into its correct ASCII code (<strong>43h</strong>). Notice that if <strong>AX</strong> was less than <strong>Ah</strong>, we could get the ASCII code by adding <strong>30h</strong>. Because <strong>AX</strong> is greater than <strong>9h</strong>, then we must add <strong>37h</strong> to get the correct code. This can be expressed in assembly as:</p>
<pre class="brush: asm; title: ; notranslate">
	cmp ax, 0x09
	jle .1
	add ax, 0x07
.1:	add ax, 0x30
</pre>
<p>The value of<strong> AL</strong> (we can discard the high bits of <strong>AX</strong> as it will never be greater than <strong>Fh</strong>) can then be copied to the location specified by <strong>ES:DI</strong>.</p>
<pre class="brush: asm; title: ; notranslate">
mov [es:di], al
inc di
</pre>
<p>So, now for the 2nd hex digit. We can repeat exactly the same process as before if we simply take the value <strong>C0DEh</strong> and shift it 4 bits to the left, which removes the <strong>C</strong> and puts <strong>0</strong> as the most significant hex digit.</p>
<p>Getting the rest of the digits follows exactly the same method, if we keep a counter of how many digits have been converted then we know that when the counter reaches 4, then all the digits have been converted.</p>
<p>Once all the digits have been converted, the final character is then added.</p>
<pre class="brush: asm; title: ; notranslate">
mov al, 'h'
mov [es:di], al
</pre>
<p>One problem remains, we have incremented <strong>ES:DI</strong> so that it now points to the last character in the string, this obviously presents a problem for the calling code. Simply subtracting 4 from <strong>DI</strong> solves the problem.</p>
<p><strong>Exercise 1</strong>: Write the entire <em>itoa_ax_hex</em> routine to convert all 4 digits of <strong>AX</strong> in a loop.</p>
<p>Solution:</p>
<pre class="brush: asm; collapse: true; light: false; title: ; toolbar: true; notranslate">
itoa_ax_hex:
; Converts the value of AX to its ASCII hex representation.
; IN:	ES:DI - String destination (must be atleast 5 bytes).
;	AX - number to convert
	push bx
	push cx		; Be nice and preserve BX and CX
	mov bx, 0xf000
	xor cx, cx	; CX = 0, counts the number of digits converted
.next:	push ax		; Save AX because AND will alter it
	and ax, bx	; AX now only contains the most significant digit
	shr ax, 12
	cmp ax, 9	; Is the HEX digit a letter?
	jle ._
	add ax, 0x07	; If it is, we need to add an additional 7
._:	add ax, 0x30	; Add 0x30 to bring the digit up to its ASCII code
	mov [es:di], al
	inc di		; Move to the next character.
	inc cx		; Incrememnt the counter. Thats another digit done
	pop ax
	shl ax, 4	; Make the next digit the most significant
	cmp cx, 4
	jne .next	; If CX doesn't yet equal 4, then there are more digits
			; left. Otherwise, we are done and can add the 'h'
			; suffix.
	mov byte [es:di], 'h'
	sub di, 4	; Restore DI to its previous value
	pop cx
	pop bx		; Restore original registers
	ret
</pre>
<p><strong>Exercise 2</strong>: Adapt the routine to convert all 8 digits of <strong>EAX</strong></p>

				<!-- Social Sharing Toolkit v2.0.4 | http://www.marijnrongen.com/wordpress-plugins/social_sharing_toolkit/ -->
				<div class="mr_social_sharing_wrapper"><span class="mr_social_sharing"><iframe src="https://www.facebook.com/plugins/like.php?locale=en_US&amp;href=http%3A%2F%2Fjwball.co.uk%2F2011%2F04%2Fconverting-integers-to-hex-strings%2F&amp;layout=standard&amp;show_faces=false&amp;width=51px&amp;height=24px" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:51px; height:24px;" allowTransparency="true"></iframe></span><span class="mr_social_sharing"><a href="http://twitter.com/share?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F04%2Fconverting-integers-to-hex-strings%2F&amp;text=Converting+Integers+to+Hex+Strings" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/twitter.png" alt="Share on Twitter" title="Share on Twitter"/></a></span><span class="mr_social_sharing"><g:plusone size="medium" count="false" href="http://jwball.co.uk/2011/04/converting-integers-to-hex-strings/"></g:plusone></span><span class="mr_social_sharing"><script type="IN/Share" data-url="http://jwball.co.uk/2011/04/converting-integers-to-hex-strings/"></script></span><span class="mr_social_sharing"><a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F04%2Fconverting-integers-to-hex-strings%2F&amp;title=Converting+Integers+to+Hex+Strings" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/stumbleupon.png" alt="Submit to StumbleUpon" title="Submit to StumbleUpon"/></a></span><span class="mr_social_sharing"><a href="http://digg.com/submit?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F04%2Fconverting-integers-to-hex-strings%2F&amp;title=Converting+Integers+to+Hex+Strings" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/digg.png" alt="Digg This" title="Digg This"/></a></span></div>]]></content:encoded>
			<wfw:commentRss>http://jwball.co.uk/2011/04/converting-integers-to-hex-strings/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing Text to the Screen in Real Mode</title>
		<link>http://jwball.co.uk/2011/04/writing-text-to-the-screen-in-real-mode/</link>
		<comments>http://jwball.co.uk/2011/04/writing-text-to-the-screen-in-real-mode/#comments</comments>
		<pubDate>Thu, 14 Apr 2011 01:35:34 +0000</pubDate>
		<dc:creator>James Ball</dc:creator>
				<category><![CDATA[Assembly]]></category>
		<category><![CDATA[OS Development]]></category>
		<category><![CDATA[vga]]></category>

		<guid isPermaLink="false">http://jwball.co.uk/?p=29</guid>
		<description><![CDATA[There are two methods for writing text to the screen in real mode, one involves the use of BIOS interrupts whilst the other involves writing directly to video memory. In my opinion, using the BIOS routine is a little overkill; it&#8217;s slow and not as &#8220;clean&#8221; as writing directly to the video memory. To start [...]]]></description>
			<content:encoded><![CDATA[<p>There are two methods for writing text to the screen in real mode, one involves the use of BIOS interrupts whilst the other involves writing directly to video memory. In my opinion, using the BIOS routine is a little overkill; it&#8217;s slow and not as &#8220;clean&#8221; as writing directly to the video memory.</p>
<p>To start with, we must understand that there are various different video modes and standards, each which may have video memory mapped to a different region. For example, if the video mode is set to monochrome text mode, then the video memory starts at <strong>b000:0000</strong>, whereas if the video mode is set to 256 bit colour graphics then the video memory is located at <strong>a000:0000</strong>. This article will focus on the standard colour text mode, 80 columns wide and 25 lines deep, whose memory is located at <strong>b800:0000</strong>.</p>
<p>This article also assumes that you understand real mode segmented addressing notation (segment:offset), that you have a basic understanding of x86 assembly language and that you&#8217;re trying to write your own boot loader or operating system.</p>
<p>Let&#8217;s look a little more into the video memory used by colour text mode, as mentioned before, the memory is mapped to a region of ram which starts at <strong>b800:0000</strong>. Because there are 80 columns of characters and 25 lines, this gives the total number of displayable characters as 2000. Each character takes up a byte of space in memory (its ASCII code) and also requires a single attribute byte.</p>
<p>This means that to write the letter &#8216;a&#8217; on the screen in the top left-hand corner, we would need to write the byte <strong>0&#215;61</strong> to <strong>[b800:0000]</strong> and an attribute byte to <strong>[b800:0001]</strong>. Writing a &#8216;b&#8217; next to the &#8216;a&#8217; would require us to write the byte <strong>0&#215;62</strong> to <strong>[b800:0002] </strong>along with an attribute byte into <strong>[b800:0003]</strong>, and so on.</p>
<p>But what is this attribute byte? The lower 4 bits of the attribute byte represent the foreground colour of the character and the high 4 bits represent the background colour of the character. An attribute byte of <strong>0x0f</strong>, for example, gives a white character on a black background.</p>
<p>So, let&#8217;s see an actual example of writing a character to the screen.</p>
<pre class="brush: asm; title: ; notranslate">
mov ax, 0xb800
mov gs, ax			        ; Set GS to point to video memory
xor bx, bx			        ; Set BX to point to the first character
mov byte [gs:bx], 'a'		; Write 'a'
inc bx                                ; Set BX to point to the first attribute byte
mov byte [gs:bx], 0x0f		; Write the attribute byte
inc bx                                ; Set BX to point to the second character
</pre>
<p>This can be represented rather more eloquently in C (and when the CPU is in protected mode) as:</p>
<pre class="brush: cpp; title: ; notranslate">
unsigned char * p = (unsigned char *) 0xb8000;
*p++ = 'a';
*p++ = 0xf;
</pre>
<p>Exercise: Write a function in assembly which prints the string &#8220;Hello, World&#8221; to the screen. Hint: <strong>LODSB</strong> is your friend.</p>
<p>In a future post I&#8217;ll look into scrolling and making use of different text pages.</p>

				<!-- Social Sharing Toolkit v2.0.4 | http://www.marijnrongen.com/wordpress-plugins/social_sharing_toolkit/ -->
				<div class="mr_social_sharing_wrapper"><span class="mr_social_sharing"><iframe src="https://www.facebook.com/plugins/like.php?locale=en_US&amp;href=http%3A%2F%2Fjwball.co.uk%2F2011%2F04%2Fwriting-text-to-the-screen-in-real-mode%2F&amp;layout=standard&amp;show_faces=false&amp;width=51px&amp;height=24px" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:51px; height:24px;" allowTransparency="true"></iframe></span><span class="mr_social_sharing"><a href="http://twitter.com/share?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F04%2Fwriting-text-to-the-screen-in-real-mode%2F&amp;text=Writing+Text+to+the+Screen+in+Real+Mode" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/twitter.png" alt="Share on Twitter" title="Share on Twitter"/></a></span><span class="mr_social_sharing"><g:plusone size="medium" count="false" href="http://jwball.co.uk/2011/04/writing-text-to-the-screen-in-real-mode/"></g:plusone></span><span class="mr_social_sharing"><script type="IN/Share" data-url="http://jwball.co.uk/2011/04/writing-text-to-the-screen-in-real-mode/"></script></span><span class="mr_social_sharing"><a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F04%2Fwriting-text-to-the-screen-in-real-mode%2F&amp;title=Writing+Text+to+the+Screen+in+Real+Mode" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/stumbleupon.png" alt="Submit to StumbleUpon" title="Submit to StumbleUpon"/></a></span><span class="mr_social_sharing"><a href="http://digg.com/submit?url=http%3A%2F%2Fjwball.co.uk%2F2011%2F04%2Fwriting-text-to-the-screen-in-real-mode%2F&amp;title=Writing+Text+to+the+Screen+in+Real+Mode" target="_blank" class="mr_social_sharing_popup_link"><img src="http://jwball.co.uk/wp-content/plugins/social-sharing-toolkit/images/buttons/digg.png" alt="Digg This" title="Digg This"/></a></span></div>]]></content:encoded>
			<wfw:commentRss>http://jwball.co.uk/2011/04/writing-text-to-the-screen-in-real-mode/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

