<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.shamsulamry.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>Shamsul Amry's Brain Dump</title>
	
	<link>http://shamsulamry.com</link>
	<description>Jotting down stuffs</description>
	<lastBuildDate>Tue, 27 Apr 2010 09:28:14 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.shamsulamry.com/shamsulamry" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="shamsulamry" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" /><item>
		<title>StableHost Linux Shared Hosting – 75% Off For Life</title>
		<link>http://shamsulamry.com/blog/stablehost-75percent-off-for-life-coupon/</link>
		<comments>http://shamsulamry.com/blog/stablehost-75percent-off-for-life-coupon/#comments</comments>
		<pubDate>Tue, 27 Apr 2010 02:50:33 +0000</pubDate>
		<dc:creator>Amry</dc:creator>
		
		<guid isPermaLink="false">http://shamsulamry.com/?p=269</guid>
		<description><![CDATA[I haven&#8217;t blogged for quite some time, had been dead busy with work. However I got this email from StableHost, the hosting provider that I am using for this blog. And since it is a very-limited-time-and-registrations offer, I thought of sharing it along with you.

To all customers -
As you know, we never send out emails <a href="http://shamsulamry.com/blog/stablehost-75percent-off-for-life-coupon/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>I haven&#8217;t blogged for quite some time, had been dead busy with work. However I got this email from <a href="http://shamsulamry.com/recommends/StableHost">StableHost</a>, the hosting provider that I am using for this blog. And since it is a very-limited-time-and-registrations offer, I thought of sharing it along with you.</p>
<p><span id="more-269"></span></p>
<blockquote><p>To all customers -</p>
<p>As you know, we never send out emails unless we are having an  upcoming maintenance or server issues.   However, we wanted to tell you  about a special that we are <strong>running the next few days (or the first 500  new clients, whatever comes first) </strong></p>
<p>We are offering <strong>75% off for life</strong> on any new shared hosting account in  our US network. Use coupon code <a href="http://shamsulamry.com/recommends/StableHost"><strong>AREWECRAZY</strong></a> at checkout. This does  not apply to our Europe servers, sorry!</p>
<p>This is the perfect time if you have multiple shared hosting accounts  with other providers, to move them over to StableHost and get an  amazing deal. You already know we have a rock solid network and  support, take advantage of this offer today! It will *never* happen  again!</p>
<p>Also, if you have friends on other hosting companies, now is the time  to convince them to move over to us!   By doing so, your friend gets an  amazing discount and we will also credit you with 3 free months of  shared hosting or 1 month of reseller hosting. Once your friend signs  up, please either reply to this email, or open up a ticket with sales  to let us know their domain name and we will credit your account.</p>
<p>Thanks for your business the past few years, in 2009, StableHost grew  700% alone. We couldn&#8217;t have done it without you guys!</p>
<p>&#8211;StableHost Sales</p></blockquote>
<p>They offered a coupon code with bigger lifetime discount than the one I used when I registered mine early this year. At 75% off the price, I can get a StableHost Plus package which is 15x bigger than StableHost Basic for nearly the same price (I got 50% lifetime off for it). I ended up registering for it, will probably terminate my original package.</p>
<p>As stated in the email, the offer will only run within the next few days, limited to first 500 registrations only. So <a href="http://shamsulamry.com/recommends/StableHost">grab the offer now before it&#8217;s gone</a>, I personally recommend it (at least to the date of this writing, I&#8217;m still happy with them). And did I mention they literally accept monthly payment too?</p>
<p>Hope you like the coupon. And if you don&#8217;t mind, do leave your domain name in the comments section down below if you decide to register so that I can claim the 3 free months of shared hosting from them. <img src='http://shamsulamry.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Well, I will be going back to work. Later~</p>
]]></content:encoded>
			<wfw:commentRss>http://shamsulamry.com/blog/stablehost-75percent-off-for-life-coupon/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 12 – Faster brute-forcing using Parallel LINQ</title>
		<link>http://shamsulamry.com/blog/project-euler-problem-12-faster-bruteforcing-parallel-linq/</link>
		<comments>http://shamsulamry.com/blog/project-euler-problem-12-faster-bruteforcing-parallel-linq/#comments</comments>
		<pubDate>Sun, 21 Mar 2010 06:45:06 +0000</pubDate>
		<dc:creator>Amry</dc:creator>
		
		<guid isPermaLink="false">http://shamsulamry.com/?p=239</guid>
		<description><![CDATA[Building on the previous code, the CountFactor method would be a good  candidate to be executed in parallel. It is doing the heavy  calculation of finding the number of factor a number has, and it has no  dependency on any other external factor.
Previously, when there is no PLINQ, we would have to <a href="http://shamsulamry.com/blog/project-euler-problem-12-faster-bruteforcing-parallel-linq/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>Building on the previous code, the CountFactor method would be a good  candidate to be executed in parallel. It is doing the heavy  calculation of finding the number of factor a number has, and it has no  dependency on any other external factor.</p>
<p>Previously, when there is no PLINQ, we would have to do multithreading manually, and I would have probably came up with something like this:<span id="more-239"></span></p>
<pre class="brush: csharp;">
static int SolveUsingMultiThread(int numberOfFactors)
{
	const int numberOfThreads = 2;

	ManualResetEvent[] waitHandles = new ManualResetEvent[numberOfThreads];
	int[] answers = new int[numberOfThreads];

	var triangleNumberSequence = EnumSequenceOfTriangleNumbers().GetEnumerator();

	ParameterizedThreadStart countFactorThread = delegate(object obj) {
		int n;

		do {
			lock (triangleNumberSequence) {
				triangleNumberSequence.MoveNext();
				n = triangleNumberSequence.Current;
			}
		} while (CountFactor(n) &lt; numberOfFactors);

		int index = (int) obj;
		answers[index] = n;
		waitHandles[index].Set();
	};

	for (int i = 0; i &lt; numberOfThreads; i++) {
		waitHandles[i] = new ManualResetEvent(false);
		Thread thread = new Thread(countFactorThread);
		thread.Start(i);
	}

	WaitHandle.WaitAll(waitHandles);
	return answers.Min();
}
</pre>
<p>Note: I written the code above after I tested on the PLINQ code just to show what multithreading code may look like. It was written quite quickly without much thought. But if you are still curious on how fast it is &#8211; well, it took 450 ms. Yes, it is even a bit slower than the normal one, and I have no intention on fixing it to be faster because I&#8217;m having fun doing PLINQ, and even more fun doing F#. <img src='http://shamsulamry.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<h2>PLINQ Attempt 1 – Unsatisfying</h2>
<p>PLINQ is supposed to make it easier on us compared to using the manual multithreading method. Here is my first attempt to &#8220;parallelize&#8221; the code using PLINQ:</p>
<pre class="brush: csharp;">
static int SolveUsingPLinq1(int numberOfFactors)
{
	var query = from n in EnumSequenceOfTriangleNumbers()
					.AsParallel().AsOrdered()
				where CountFactor(n) &gt;= numberOfFactors
				select n;

	return query.First();
}
</pre>
<p>The time for this is 381 ms. It was doing 403 ms for the sequential code. Not good enough. I expected something around half the time.</p>
<h2>PLINQ Attempt 2 – Even more of a failure</h2>
<pre class="brush: csharp;">
static int SolveUsingPLinq2(int numberOfFactors)
{
	var query1 = from n in EnumSequenceOfTriangleNumbers()
				 select new { TriangleNumber = n,
					 FactorCount = CountFactor(n) };

	var query2 = from a in query1.AsParallel().AsOrdered()
				 where a.FactorCount &gt;= numberOfFactors
				 select a;

	return query2.First().TriangleNumber;
}
</pre>
<p>This code is executing even longer: 590 ms. I stopped a bit and started to google around for PLINQ stuff.</p>
<h2>PLINQ Attempt 3 – Still nowhere near what I was expecting</h2>
<p>Then I found this article on MSDN: <a href="http://msdn.microsoft.com/en-us/library/dd997399%28VS.100%29.aspx">Understanding Speedup in PLINQ</a>.<br />
Reading the code example there, I came to the thought:</p>
<blockquote><p>Aha! The source of the triangle numbers should be marked as being parallel-able, then the heavy lifting of the CountFactor method should be put in the select part of the query. This should create the select results in parallel.</p></blockquote>
<p>Based on that thought, I then came up with the next code:</p>
<pre class="brush: csharp;">
static int SolveUsingPLinq3(int numberOfFactors)
{
	var query1 = from n in EnumSequenceOfTriangleNumbers()
					 .AsParallel().AsOrdered()
				 select new { TriangleNumber = n,
					 FactorCount = CountFactor(n) };

	var query2 = from a in query1
				 where a.FactorCount &gt;= numberOfFactors
				 select a;

	return query2.First().TriangleNumber;
}
</pre>
<p>376 ms. Still not half the time. This shouldn&#8217;t be it.</p>
<h2>PLINQ Attempt 4 &#8211; Eureka!</h2>
<p>I don&#8217;t remember how I came to this, but here&#8217;s the final code and the one that I&#8217;m happy with the result:</p>
<pre class="brush: csharp;">
static int SolveUsingPLinq4(int numberOfFactors)
{
	var query = from n in EnumSequenceOfTriangleNumbers()
					.AsParallel().AsOrdered()
				select new { TriangleNumber = n,
					FactorCount = CountFactor(n) };

	return query
		.First(a =&gt; a.FactorCount &gt;= numberOfFactors)
		.TriangleNumber;
}
</pre>
<p>234 ms! This is what I call parallel, though I can&#8217;t really explain much on the best way to use PLINQ. <img src='http://shamsulamry.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<h2>Random Conclusion</h2>
<ul>
<li>The source of a query (the from statement) should be something relatively cheap to generate, and it should be turned to a parallel source using the .AsParallel() extension method call.</li>
<li>The heavy computation should be put as a projection of the query (in the select statement).</li>
<li>Where you put the criteria is based on what you want from the query – I know, an easy escape statement, I don&#8217;t really have any good advise on this. <img src='http://shamsulamry.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://shamsulamry.com/blog/project-euler-problem-12-faster-bruteforcing-parallel-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 12 – First time F# version</title>
		<link>http://shamsulamry.com/blog/project-euler-problem-12-first-time-fsharp-version/</link>
		<comments>http://shamsulamry.com/blog/project-euler-problem-12-first-time-fsharp-version/#comments</comments>
		<pubDate>Fri, 19 Mar 2010 14:53:39 +0000</pubDate>
		<dc:creator>Amry</dc:creator>
		
		<guid isPermaLink="false">http://shamsulamry.com/?p=227</guid>
		<description><![CDATA[This is my first time doing F#. Also my first time doing functional programming at all. The F# code is based on the Brute-Force Method 3 that I came up with. Only managed to get about 3960 ms, that’s about 10 times the execution time of my C# code. I don&#8217;t think F# is meant <a href="http://shamsulamry.com/blog/project-euler-problem-12-first-time-fsharp-version/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>This is my first time doing F#. Also my first time doing functional programming at all. The F# code is based on the <a href="http://shamsulamry.com/blog/project-euler-problem-12-solution-using-basic-csharp-and-linq/#brute-force-method-3">Brute-Force Method 3</a> that I came up with. Only managed to get about 3960 ms, that’s about 10 times the execution time of my C# code. I don&#8217;t think F# is meant to be slow, so probably it&#8217;s me not doing it the right way.</p>
<p><span id="more-227"></span>Here’s my first F# code:</p>
<pre class="brush: fsharp;">
open System
open System.Diagnostics

let stopwatch = Stopwatch.StartNew()

let triangleNumberSeq =
    Seq.unfold
        (fun (number, triangleNumber) -&gt;
            Some (triangleNumber, (number+1, triangleNumber+number+1)))
        (1, 1)

let inline divide (number: int) (divisor: int) =
    let quotient = number / divisor
    let modulus = number % divisor
    (quotient, modulus)

let inline divideSeq n =
    let divideN = divide n
    Seq.unfold
        (fun divisor -&gt;
            match divideN divisor with
            | (quotient, modulus) when divisor &lt;= quotient -&gt;
                Some ((divisor, quotient, modulus), divisor+1)
            | _ -&gt; None)
        1
    |&gt; Seq.filter (fun (_, _, modulus) -&gt; modulus = 0)

let countFactor n =
    Seq.fold
        (fun count divideResult -&gt;
            match divideResult with
            | (divisor, quotient, _) when divisor &lt; quotient -&gt; count+2
            | _ -&gt; count+1)
        0 (divideSeq n)

let answer =
    Seq.find
        (fun triangleNumber -&gt; countFactor triangleNumber &gt; 500)
        triangleNumberSeq

stopwatch.Stop()
printfn &quot;Answer: %d&quot; answer
printfn &quot;Elapsed: %d ms&quot; stopwatch.ElapsedMilliseconds
Console.ReadKey(true) |&gt; ignore
</pre>
<p>I will be really grateful if anyone can tell me any tips on improving my F# code. Nevertheless, coming up next, the PLINQ version.</p>
]]></content:encoded>
			<wfw:commentRss>http://shamsulamry.com/blog/project-euler-problem-12-first-time-fsharp-version/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler Problem 12 – Solution using basic C# and LINQ</title>
		<link>http://shamsulamry.com/blog/project-euler-problem-12-solution-using-basic-csharp-and-linq/</link>
		<comments>http://shamsulamry.com/blog/project-euler-problem-12-solution-using-basic-csharp-and-linq/#comments</comments>
		<pubDate>Sun, 14 Mar 2010 09:50:40 +0000</pubDate>
		<dc:creator>Amry</dc:creator>
		
		<guid isPermaLink="false">http://shamsulamry.com/?p=212</guid>
		<description><![CDATA[Two days ago I had been looking at re-playing with Project Euler problems, after I solved a few of them last time (quite some time ago). I looked at the problem list, and decided to try solve the top-most unsolved problem I have: Problem 12. I managed to come up with a brute-force code that <a href="http://shamsulamry.com/blog/project-euler-problem-12-solution-using-basic-csharp-and-linq/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>Two days ago I had been looking at re-playing with <a href="http://projecteuler.net">Project Euler</a> problems, after I solved a few of them last time (quite some time ago). I looked at the problem list, and decided to try solve the top-most unsolved problem I have: <a href="http://projecteuler.net/index.php?section=problems&amp;id=12">Problem 12</a>. I managed to come up with a brute-force code that calculated the answer in about 403 ms on an Intel Core2 Duo T9600 @ 2.80GHz machine.</p>
<h2>Understanding the problem</h2>
<blockquote><p>The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:</p>
<p>1, 3, 6, 10, 15, 21, 28, 36, 45, 55, &#8230;</p></blockquote>
<p>Given the example, I guess the mathematical function explanation of the triangle numbers would be something along this line: <em>f</em>(n) –&gt; 1+2+3+…+n where n=1, 2, 3, …</p>
<p>We are then required to come up with something to find the first triangle number to have over 500 divisors. In clearer words, we are required to find the first triangle number to have 501 divisors, within one minute, complying to the Project Euler’s <a href="http://projecteuler.net/index.php?section=about">one-minute rule</a>:</p>
<blockquote>
<h5>I&#8217;ve written my program but should it take days to get to the answer?</h5>
<p>Absolutely not! Each problem has been designed according to a &#8220;one-minute rule&#8221;, which means that although it may take several hours to design a successful algorithm with more difficult problems, an efficient implementation will allow a solution to be obtained on a modestly powered computer in less than one minute.</p></blockquote>
<p><span id="more-212"></span><strong><span style="color: #ff0000;">Spoiler alert:</span></strong> All that follows after this will be discussions of the solution I came up with for this problem.</p>
<h2>Methods of solving</h2>
<p>The methods I came up with are all purely brute-force, not making use of any proved mathematical methods, which if available, should be able to solve problems a lot more efficiently.</p>
<h4>Brute-Force Method 1</h4>
<p>The most inefficient way. The steps:</p>
<ol>
<li>Try to divide the current triangle number, n with the divisors: 1, …, n.</li>
<li>Count the number of divisors that can be divided evenly.</li>
<li>If the count reaches 501, stop, this is the triangle number we are looking for.</li>
<li>If not, on to the next triangle number.</li>
</ol>
<h4>Brute-Force Method 2</h4>
<p>Other than the number 1, the rest of the numbers (not just triangle numbers) will have at least two divisors: 1 and the number itself. And the biggest divisor for a number, besides the number itself, will not be more than the number itself divided by two. For example, the biggest divisor for the number 10, besides the number 10 itself, will not be more than 5.</p>
<p>The steps:</p>
<ol>
<li>Ignore the first triangle number: 1. Start directly with the second triangle number: 3 (result of 1+2).</li>
<li>Start the count of divisors with 2, as all numbers other than 1 will have at least two divisors.</li>
<li>Try to divide the current triangle number, n with the divisors: 2, 3, 4, …, n/2.</li>
<li>Continue on with Step 2-4 of Brute-Force Method 1.</li>
</ol>
<h4>Brute-Force Method 3</h4>
<p>Let’s think more cleverly:</p>
<ol>
<li>Every divisors are pairs. If a number divided by x results to y, the same number divided by y will result to x. E.g 10 / 5 = 2, 10 / 2 = 5. So for each divisor found, we can add 2 to the divisor count.</li>
<li>There are also “twin-pairs divisors”. E.g 36 / 6 = 6. For each of these divisors found, we add 1 to the divisor count.</li>
</ol>
<p>The steps:</p>
<ol>
<li>Start directly with the second triangle number: 3.</li>
<li>Start the count of divisors with 2.</li>
<li>Try to divide the current triangle number, n with the divisors: 2, 3, 4, … (while n / divisor &gt; divisor). For each divisor that can be divided evenly, add 2 to the count of divisors.</li>
<li>When n / divisor &lt;= divisor, check to see if it is a “twin-pair divisor”. If it is, add 1 to the count of divisors.</li>
<li>If the count reaches 501, stop, this is the triangle number we are looking for.</li>
<li>If not, on to the next triangle number.</li>
</ol>
<h2>The basic C# code</h2>
<p>I will be using the steps listed in Brute-Force Method 3 which is the best brute-force method I can come up with.</p>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace Problem12
{
    class Program
    {
        static void Main()
        {
            long msecs = 0;
            int answer = 0;
            for (int i = 0; i &lt; 10; i++) {
                Stopwatch stopwatch = Stopwatch.StartNew();
                answer = SolveUsingLinq(501);
                stopwatch.Stop();
                msecs += stopwatch.ElapsedMilliseconds;
            }
            Console.WriteLine(&quot;Answer: {0}&quot;, answer);
            Console.WriteLine(&quot;Elapsed: {0}&quot;, msecs / 10);
        }

        static int SolveUsingBasicMethod(int numberOfFactors)
        {
            foreach (int n in EnumSequenceOfTriangleNumbers()) {
                if (CountFactor(n) &gt;= numberOfFactors) {
                    return n;
                }
            }

            // This code is unreachable. EnumSequenceOfTriangleNumbers will infinitely return the next triangle number, limited to Int32.MaxValue.
            return 0;
        }

        /// &lt;summary&gt;
        /// Returns a stream of triangle numbers, starting from the second triangle number: 3.
        /// &lt;/summary&gt;
        static IEnumerable&lt;int&gt; EnumSequenceOfTriangleNumbers()
        {
            int i = 2;
            int n = 1;
            while (true) {
                n += i++;
                yield return n;
            }
        }

        /// &lt;summary&gt;
        /// Returns the number of factors / divisors for the given number using the steps outlined in Brute-Force Method 3.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;n&quot;&gt;The number to have its factors counted.&lt;/param&gt;
        /// &lt;returns&gt;The number of factors.&lt;/returns&gt;
        static int CountFactor(int n)
        {
            int count = 2;
            int divisor = 2;
            int quotient = n / divisor;

            while (quotient &gt; divisor) {
                if (n % divisor == 0) {
                    count += 2;
                }
                quotient = n / ++divisor;
            }

            if (quotient == divisor &amp;&amp; n % divisor == 0) {
                count++;
            }

            return count;
        }
    }
}
</pre>
<p>This code took about 403 ms on an Intel Core2 Duo T9600 @ 2.80GHz to calculate the answer.</p>
<h2>The LINQ version of the code</h2>
<p>The actual reason I’m re-playing with the Project Euler’s problems is to learn new stuffs which I had no chance of learning at my workplace. And guess what: LINQ is still considered one of the things in my what’s new list. I had not much chance of doing anything with it as I’m still using Microsoft Visual Studio 2005 and .NET Framework 2.0 up till now, when Visual Studio 2008 had been around for quite some time and Visual Studio 2010 will be entering the market soon enough.</p>
<p>Enough rambles.</p>
<p>Back to the code, the LINQ version will be built on top of the basic code.</p>
<pre class="brush: csharp;">
using System.Linq;

...

static int SolveUsingLinq(int numberOfFactors)
{
	var query = from n in EnumSequenceOfTriangleNumbers()
				where CountFactor(n) &gt;= numberOfFactors
				select n;

	return query.First();
}
</pre>
<p>This code took about 404 ms. No noticeable time difference if compared against the basic code.</p>
<p>I will be looking into the even newer Parallel LINQ. The CountFactor method would be a good candidate to be executed in parallel i.e counting the factors of two triangle numbers at one time (two at a time since I am running the code on a dual core machine). I have some rough idea on coding manual threading for it, but let’s see how PLINQ can make it simpler. And perhaps I’ll try to do an F# version as well. <img src='http://shamsulamry.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://shamsulamry.com/blog/project-euler-problem-12-solution-using-basic-csharp-and-linq/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PGP Single Pass Sign and Encrypt .NET Stream</title>
		<link>http://shamsulamry.com/blog/pgp-single-pass-sign-encrypt-dotnet-stream/</link>
		<comments>http://shamsulamry.com/blog/pgp-single-pass-sign-encrypt-dotnet-stream/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 09:24:23 +0000</pubDate>
		<dc:creator>Amry</dc:creator>
		
		<guid isPermaLink="false">http://shamsulamry.com/?p=185</guid>
		<description><![CDATA[In a recent software development project, I was required to be able to read PGP encrypted content, do something, and write PGP encrypted result. The project allowed calling of PGP (or GPG) command line to do the encryption and decryption needed. However that did not feel right to me. Googled a bit and then I <a href="http://shamsulamry.com/blog/pgp-single-pass-sign-encrypt-dotnet-stream/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>In a recent software development project, I was required to be able to read PGP encrypted content, do something, and write PGP encrypted result. The project allowed calling of PGP (or GPG) command line to do the encryption and decryption needed. However that did not feel right to me. Googled a bit and then I found the <a href="http://www.bouncycastle.org/csharp/">Bouncy Castle C# Crypto APIs</a>, that among everything else, included support for PGP without having any external dependency.</p>
<p>The compiled assembly for the Bouncy Castle APIs can be downloaded from the website, however it was compiled for the .NET 1.1 runtime version. You can easily download the source code instead and compile it for the other .NET versions if you want to. I managed to compile the source code for the .NET 2.0 runtime version without any changes to the original source code.</p>
<p>The bigger issue at using the Bouncy Castle APIs is that it does not seem to have any proper documentation for it. <span id="more-185"></span>There are examples provided in the downloadable source code which you can read through to figure out how to do things. I was lazy at that time, and managed to find this blog entry: <a href="http://jopinblog.wordpress.com/2008/06/23/pgp-single-pass-sign-and-encrypt-with-bouncy-castle/">PGP Single Pass Sign and Encrypt with Bouncy Castle</a> that provided me with the code to encrypt file contents using PGP.</p>
<p>From that code, I refactored it bit by bit:</p>
<ul>
<li>Factored out the actualFileName (string) parameter so that the actual input content can be from any source, not just physical files.</li>
<li>Factored out the keyIn (Stream) and keyId (long) parameters so that the handling of the secret key that will be used to sign the input content can be externalized from the sign and encrypted method itself.</li>
<li>Removed the armor (bool) and withIntegrityCheck (bool) parameters and made both of it as constants of true instead so that the generated output will always be armored and integrity-checked. It can easily be made into parameters back again if need to.</li>
<li>Removed the embeddedFileName (string) parameter and made it as a constant of empty string since the file name value is not important to generate proper signed-and-encrypted output.</li>
<li>Made it into a .NET Stream so that allow it to be used as any other .NET Streams and the output can be chained to any imaginable .NET Streams such as MemoryStream, HttpResponse&#8217;s OutputStream, etc. Usage example will be provided at the end of this blog post.</li>
</ul>
<h2>The Code for the .NET Stream</h2>
<pre class="brush: csharp; collapse: true; light: false; toolbar: true;">
using System;
using System.IO;
using Org.BouncyCastle.Bcpg;
using Org.BouncyCastle.Bcpg.OpenPgp;
using Org.BouncyCastle.Security;

class PgpSignAndEncryptStream : Stream
{
	readonly Stream outputStream;
	readonly Stream armoredOutputStream;
	readonly PgpEncryptedDataGenerator encryptedDataGenerator;
	readonly Stream encryptedOutputStream;
	readonly PgpCompressedDataGenerator compressedDataGenerator;
	readonly Stream compressedOutputStream;
	readonly PgpSignatureGenerator signatureGenerator;
	readonly PgpLiteralDataGenerator literalDataGenerator;
	readonly Stream literalOutputStream;
	bool closed = false;

	public PgpSignAndEncryptStream(Stream outputStream, PgpPublicKey encryptionPublicKey, PgpSecretKey signatureSecretKey, string signatureSecretPassword)
	{
		//
		// literal + signature -&gt; compress -&gt; encrypt -&gt; armored -&gt; output
		//

		const int BUFFER_SIZE = 1 &lt;&lt; 16; // should always be power of 2
		const bool armor = true;
		const bool withIntegrityCheck = true;
		const string fileName = &quot;&quot;;
		DateTime modificationTime = DateTime.UtcNow;

		this.outputStream = outputStream;

		//
		// Always create armored output
		//
		if (armor) {
			outputStream = new ArmoredOutputStream(outputStream);
			armoredOutputStream = outputStream;
		}

		//
		// Init encrypted data generator
		//
		encryptedDataGenerator =
			new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());
		encryptedDataGenerator.AddMethod(encryptionPublicKey);
		encryptedOutputStream = encryptedDataGenerator.Open(outputStream, new byte[BUFFER_SIZE]);

		//
		// Init compression
		//
		compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
		compressedOutputStream = compressedDataGenerator.Open(encryptedOutputStream);

		//
		// Init signature
		//
		signatureGenerator = new PgpSignatureGenerator(signatureSecretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1);
        PgpPrivateKey signaturePrivateKey = signatureSecretKey.ExtractPrivateKey(signatureSecretPassword.ToCharArray());
		signatureGenerator.InitSign(PgpSignature.BinaryDocument, signaturePrivateKey);
		foreach (string userId in signatureSecretKey.PublicKey.GetUserIds()) {
			PgpSignatureSubpacketGenerator signatureSubpacketGenerator = new PgpSignatureSubpacketGenerator();
			signatureSubpacketGenerator.SetSignerUserId(false, userId);
			signatureGenerator.SetHashedSubpackets(signatureSubpacketGenerator.Generate());
			// Just the first one!
			break;
		}
		signatureGenerator.GenerateOnePassVersion(false).Encode(compressedOutputStream);

		//
		// Create the literal data generator output stream
		//
		literalDataGenerator = new PgpLiteralDataGenerator();
		literalOutputStream = literalDataGenerator.Open(compressedOutputStream, PgpLiteralData.Binary,
											   fileName, modificationTime, new byte[BUFFER_SIZE]);
	}

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

	public override long Seek(long offset, SeekOrigin origin)
	{
		throw new NotSupportedException();
	}

	public override void SetLength(long value)
	{
		throw new NotSupportedException();
	}

	public override int Read(byte[] buffer, int offset, int count)
	{
		throw new NotSupportedException();
	}

	public override void Write(byte[] buffer, int offset, int count)
	{
		literalOutputStream.Write(buffer, offset, count);
		signatureGenerator.Update(buffer, offset, count);
	}

	public override void Close()
	{
		if (closed) {
			return;
		}

		closed = true;

		literalOutputStream.Close();
		literalDataGenerator.Close();
		signatureGenerator.Generate().Encode(compressedOutputStream);
		compressedOutputStream.Close();
		compressedDataGenerator.Close();
		encryptedOutputStream.Close();
		encryptedDataGenerator.Close();

		if (armoredOutputStream != null) {
			armoredOutputStream.Close();
		}

		outputStream.Close();
	}

	public override bool CanRead
	{
		get { return false; }
	}

	public override bool CanSeek
	{
		get { return false; }
	}

	public override bool CanWrite
	{
		get { return true; }
	}

	public override long Length
	{
		get { throw new NotSupportedException(); }
	}

	public override long Position
	{
		get { throw new NotSupportedException(); }
		set { throw new NotSupportedException(); }
	}
}
</pre>
<h2>Usage Example of the .NET Stream</h2>
<p>Assumption made for now: you know how to actually get the public key and the secret key out of the keyring files. Later I will write another post on how to get the keys.</p>
<h4>Using StreamWriter to write encrypted string to a file</h4>
<pre class="brush: csharp;">
using System.IO;
using Org.BouncyCastle.Bcpg.OpenPgp;

...

PgpPublicKey publicKey = null; // get this value from somewhere
PgpSecretKey secretKey = null; // get this value from somewhere
string password = null; // get this value from somewhere

Stream outputStream = File.OpenWrite(&quot;output.txt&quot;); // this can be replaced with any other output stream e.g. MemoryStream
PgpSignAndEncryptStream pgpOutStream = new PgpSignAndEncryptStream(outputStream, publicKey, secretKey, password);
StreamWriter writer = new StreamWriter(pgpOutStream);

writer.Write(&quot;This text will be signed and encrypted into output.txt&quot;);

writer.Close();
pgpOutStream.Close();
outputStream.Close();
</pre>
<h4>Sign and encrypt one whole input file</h4>
<pre class="brush: csharp;">
using System.IO;
using Org.BouncyCastle.Bcpg.OpenPgp;

...

PgpPublicKey publicKey = null; // get this value from somewhere
PgpSecretKey secretKey = null; // get this value from somewhere
string password = null; // get this value from somewhere

Stream inputStream = File.OpenRead(&quot;input.txt&quot;);
Stream outputStream = File.OpenWrite(&quot;output.txt&quot;);
PgpSignAndEncryptStream pgpOutStream = new PgpSignAndEncryptStream(outputStream, publicKey, secretKey, password);

byte[] buffer = new byte[4096];
int readCount;
while ((readCount = inputStream.Read(buffer, 0, buffer.Length)) &gt; 0) {
    outputStream.Write(buffer, 0, readCount);
}

outputStream.Close();
inputStream.Close();
</pre>
<h2>Pending Related Posts</h2>
<ul>
<li>As mentioned earlier, a post on how to get the public keys and secret keys out of the keyring files. And probably on how to use GPG to import the keys into the keyring files as I can&#8217;t seem to find out how to programmatically import a public key block into a public key ring file.</li>
<li>PGP Decrypt and Single Pass Signature Verify .NET Stream. The working code is already in my hard disk, will share it later.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://shamsulamry.com/blog/pgp-single-pass-sign-encrypt-dotnet-stream/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Kena masuk wad semalaman, nasib baik ada medical card boleh guna</title>
		<link>http://shamsulamry.com/blog/kena-masuk-wad-semalaman/</link>
		<comments>http://shamsulamry.com/blog/kena-masuk-wad-semalaman/#comments</comments>
		<pubDate>Mon, 22 Feb 2010 02:16:16 +0000</pubDate>
		<dc:creator>Amry</dc:creator>
		
		<guid isPermaLink="false">http://shamsulamry.com/?p=162</guid>
		<description><![CDATA[Balik Kelantan konon nak bercuti. Nak dijadikan cerita hari Selasa (16 Feb 2010), round nak cari klinik panel Great Eastern / Compumed (company punya panel provider) di Kota Bharu sebab nak check ada bengkak tetiba tumbuh. Pusing punya pusing, susah betul nak cari klinik panel yang buka. Rasanya lagi banyak klinik yang tutup daripada yang <a href="http://shamsulamry.com/blog/kena-masuk-wad-semalaman/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>Balik Kelantan konon nak bercuti. Nak dijadikan cerita hari Selasa (16 Feb 2010), <em>round</em> nak cari klinik panel Great Eastern / Compumed (<em>company</em> punya <em>panel provider</em>) di Kota Bharu sebab nak <em>check</em> ada bengkak tetiba tumbuh. Pusing punya pusing, susah betul nak cari klinik panel yang buka. Rasanya lagi banyak klinik yang tutup daripada yang buka, sempena cuti Raya Cina.</p>
<p>Sebab susah dan dah malas punya pasal, terus redah Hospital Pakar Perdana. Dah sampai hospital, nasib baik hospital buka (takkan hospital pun cuti Raya Cina <em>ye</em> tak). Jumpa doktor. Doktor kata <em><a href="http://en.wikipedia.org/wiki/Abscess">abscess</a></em>, kena masuk wad untuk buat pembedahan <em>kecik</em> nak buang benda tu. <em>Second time</em> kena masuk wad seumur hidup setakat ni, <em>first time</em> masuk wad hospital swasta. Tak <em>tau</em> prosedur apa kena buat. Jakun.</p>
<p><span id="more-162"></span>Ikut je apa <em>nurse</em> / kerani / pembantu doktor / <em>pape la</em> nama jawatan tu suruh buat:</p>
<ol>
<li>Dia tanya ada insuran tak. Ya, saya ada (sambil mengeluarkan kad medikal Prudential BSN Takaful daripada <em>wallet</em>). Bagi je <em>kat</em> <em>nurse</em> tu, dia pun uruskan selebihnya.</li>
<li>Dah <em>setel</em> urusan insuran. Dia tanya nak bilik <em>camne</em>. Saya kata, nak bilik paling <em>best</em> yang kad medikal tu boleh <em>cover</em>. Dapat la bilik bertiga sebab bilik berdua dan bilik single <em>fully occupied</em>. Bilik <em>VIP</em> tak masuk cerita sama sekali.</li>
<li>Lepas tu dia bawa turun bawah ke kaunter pembayaran pesakit luar. Kena bayar RM250 deposit, akan dapat balik lepas <em>discharge</em> nanti kata pegawai yang duduk <em>kat</em> kaunter terima bayaran tu.</li>
<li>Dah bayar tu <em>nurse</em> tu pun bawa ke wad. Hmm, bilik bertiga tapi <em>takde</em> orang lain. <em>Cool</em>.</li>
</ol>
<p>Duduk dalam wad sambil tengok <em>TV</em>. Nak makan tak boleh, doktor suruh puasa. Tunggu <em>je la</em> sejam dua tiga jam untuk sesi pembedahan. Ni kira <em>first time</em> nak kena bedah, walaupun <em>kecik</em>. <em>No idea</em> apa akan jadi, tapi <em>nurse</em> ada <em>bagitau</em> doktor akan bagi bius. So mula terpikir, bagi bius tu <em>camne</em>. Pandangan akan jadi gelap macam rasa nak pitam tu ke? Ke pandangan akan <em>distort</em> lepas tu pengsan? Tu <em>la</em> dia teka-teki yang kerap bermain dalam otak ni sebelum masa pembedahan. Rasa macam <em>excited</em> pun ada <em>gak</em> memikirkan soalan tu, langsung takde rasa gementar, kenapa entah.</p>
<p><em>Then</em> ada <em>sorang</em> pesakit baru masuk katil sebelah. <em>Alaa</em>, dah <em>takde privacy</em>. <em>Takpe</em> lagi. Tak lama lepas tu, <em>sorang</em> lagi pesakit masuk katil hujung sana. Hoi hoii, ni hospital ke pasar malam? Bising. Bising. Bisinggg. Nak melawat buat <em>la</em> cara nak melawat, jangan buat cara <em>shopping kat</em> pasar malam. <em>Nurse</em>, belum ada bilik <em>single</em> yang kosong ke? Aihh~</p>
<p>Sampai masanya, <em>nurse</em> suruh baring atas katil, dia nak tolak ke bilik pembedahan. Saya pun cakap, &#8220;<em>Nurse</em>, saya jalan kaki je boleh tak?&#8221;, di dalam hati. Terbaring atas katil tengok je la lampu-lampu siling tu bergerak macam dalam cerita set ER tu. Tetiba rasa gementar mula datang sikit demi sikit. Aihh, apsal <em>plak</em> nak <em>start</em> gementar ni. Masuk <em>je</em> bilik pembedahan, <em>nurse</em> bagi borang nak <em>sign</em>. Dia kata kena <em>sign</em> sebab doktor nak <em>inject</em> bius. Tak sempat nak baca apa borang tu tulis, tengah rasa sikit cemas dah masa tu. Tapi terbayang macam dia tulis, &#8220;Kami tidak akan bertanggungjawab sekiranya <em>pape</em> jadi <em>kat</em> anda&#8221; je. Huhu~</p>
<p>Doktor pun start cucuk bius, sambil <em>nurse</em> pegang benda yang <em>supply</em> oksigen tu ke muka. Doktor suruh bernafas oksigen tu perlahan-lahan. Masa tu otak start pikir balik, konon nak cabar lawan tengok berapa lama boleh bertahan nak lawan <em>effect</em> bius tu. Konon boleh <em>la</em> tahan sekejap sebelum mata mula lelap. <em>Hampeh</em>. Beberapa saat lepas tu, terasa macam berpinar <em>je</em> mata. <em>Next thing</em>, <em>nurse</em> cakap, &#8220;Dah bangun Encik Shamsul?&#8221;. Aihh, bila masa pengsan ni? Tak sempat nak melawan pun lagi. Tanya <em>nurse</em>, berapa lama dah saya pengsan. <em>Nurse</em> kata dah sejam lebih.</p>
<p><em>Nurse</em> tanya, larat tak nak bangun pindah katil. Cuba bangun, boleh bangun, tapi tak berapa nak larat angkat tubuh ni. Bius<em> still in effect</em>. Pindah katil sebelah, <em>then nurse</em> pun tolak katil tu balik wad. Untuk malam tu sampai esoknya, sekadar rehat-rehat sambil kena <em>inject</em> antibiotik, makan pil dan sebagainya. Semalam doktor kata pagi boleh <em>discharge</em>, tapi petang baru datang <em>check</em>. Doktor tak baik, tak ikut janji. Nak balik. Doktor dah bagi <em>release</em>, <em>nurse plak</em> kata biasa nak proses insuran amik masa 3-4 jam juga. Aihh <em>pulak</em>. Nak balik~</p>
<p>2 <em>PM</em>, <em>time</em> tu doktor kata boleh balik. 5 <em>PM</em>, baru <em>nurse</em> panggil kata insuran dah siap proses. Pergi kaunter nak <em>collect</em> ubat dan deposit. Tapi ubat je dapat <em>collect</em>, deposit tak dapat. Kena tambah lagi ada. Insuran <em>cover</em> 90% je, 10% kena bayar duit sendiri. Nasib baik ada duit masa tu. <em>Takpe</em>, nanti <em>claim</em> insuran <em>opis</em> punya <em>la</em> untuk 10% tu, boleh <em>kot</em>. Semalam ada <em>call</em> agen insuran Prudential tu, bagitau saya kena masuk wad. Tanya apa kena buat. Dia ada sebut pasal ko-takaful, kalau masuk satu malam <em>je</em> kena bayar 10%, dan apa entah lagi. Tak paham. Redah <em>je la</em>. Sekarang dah boleh keluar. Horei! Kesian <em>wife</em> semalaman susah nak <em>tido kat</em> wad tu gara-gara gangguan jiran dan nyamuk.</p>
<p><em>So</em>, beberapa pengajaran berkaitan dan kurang berkaitan yang telah diperolehi kali ni:</p>
<ol>
<li><span style="color: #ff0000;"><strong>Sila bawa duit lebih ke hospital sekalipun anda ada kad medikal apa jenis sekalipun.</strong></span> <em>Just in case</em> kad medikal tu <em>cover</em> 90% <em>je</em>, macam saya. Sebaiknya <em>study</em> balik pasal penggunaan kad medikal tu dengan agen insuran anda.</li>
<li>Great Eastern / Compumed tak <em>best</em>. Susah nak cari klinik panel yang boleh terima kad dia. Kalau boleh terima pun, kad dia bukan jenis yang boleh senang-senang <em>swipe</em> macam <em>certain medical card</em> yang lain. Tapi <em>customer service</em> dia OK, walaupun tak berapa membantu sebab dia tak boleh nak provide klinik panel berdekatan daerah di Kelantan. <em>End up</em> pergi klinik memana, bayar pakai duit sendiri dan kemudian <em>claim</em> balik, dan tunggu entah berapa bulan sebelum <em>claim</em> tu diproses.</li>
<li>Sekiranya anda pengguna Celcom, anda boleh <em>call</em> *118# untuk mendapatkan menu di mana anda boleh <em>activate</em> perkhidmatan Broadband Daily yang membolehkan anda menggunakan internet dengan caj RM6 selama 24 jam (<em>instead of</em> 10 sen bagi setiap 10 KB) apabila anda bosan di dalam wad.</li>
</ol>
<p>Sekian saja <em>entry</em> untuk kali ni. Nak keluar pergi klinik untuk tukar <em>dressing</em> tempat dibedah tu. Doktor bagi MC 7 hari, cuti seminggu Raya Cina kali ni tak perlu guna <em>annual leave</em>. <em>Yess</em>! <img src='http://shamsulamry.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://shamsulamry.com/blog/kena-masuk-wad-semalaman/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Migrating to own domain, Part 3</title>
		<link>http://shamsulamry.com/blog/migrating-domain-part-3/</link>
		<comments>http://shamsulamry.com/blog/migrating-domain-part-3/#comments</comments>
		<pubDate>Fri, 12 Feb 2010 13:05:45 +0000</pubDate>
		<dc:creator>Amry</dc:creator>
		
		<guid isPermaLink="false">http://shamsulamry.com/?p=148</guid>
		<description><![CDATA[Done:

Breadcrumbs. Hacked the theme to put in Yoast Breadcrumbs at the top of posts and pages.
Function for sharing. Hacked the theme to put in AddToAny button in the footer part of posts.
Snap Shots. Implemented Snap Shots™ Plugin for Wordpress.org into the blog, enabled only for external links.
Creative Commons notice for my source codes. Used Creative <a href="http://shamsulamry.com/blog/migrating-domain-part-3/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>Done:</p>
<ol>
<li><strong>Breadcrumbs.</strong> Hacked the theme to put in <a href="http://yoast.com/wordpress/breadcrumbs/">Yoast Breadcrumbs</a> at the top of posts and pages.</li>
<li><strong>Function for sharing.</strong> Hacked the theme to put in <a href="http://www.addtoany.com/">AddToAny</a> button in the footer part of posts.</li>
<li><strong>Snap Shots.</strong> Implemented <a href="http://www.snap.com/about/shots_central.php">Snap Shots™ Plugin for Wordpress.org</a> into the blog, enabled only for external links.</li>
<li><strong>Creative Commons notice for my source codes. </strong>Used <a href="http://www.g-loaded.eu/2006/01/14/creative-commons-configurator-wordpress-plugin/">Creative Commons Configurator</a> to put in Creative Commons notice at the end of each post. I actually intended only to mark my posts which include source codes, but it seems there&#8217;s no per-post settings for it, so all posts it is.</li>
<li><strong>Sitemap page.</strong> Installed the <a href="http://www.dagondesign.com/articles/sitemap-generator-plugin-for-wordpress/">Dagon Design Sitemap Generator</a> plugin for the sitemap page.</li>
</ol>
<p>To do:</p>
<ol>
<li><strong>OpenID login for comments.</strong> I tried a couple of plugins related to OpenId, but they didn&#8217;t actually work as I imagined, so I deactivated them at the moment. In my mind, I would like to have the functionality that will allow users to login using their OpenId-compatible accounts, such as GMail, or Facebook, or Tweeter etc. Then the avatar in the comments will use the one that they use as their profile picture. Something like that.</li>
<li><strong>Subscribe to comments.</strong> Already installed the <a href="http://txfx.net/code/wordpress/subscribe-to-comments/">Subcribe to Comments</a> plugin, but have not completed the integration into the current theme yet.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://shamsulamry.com/blog/migrating-domain-part-3/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Fixing the Mystique theme Twitter settings issue</title>
		<link>http://shamsulamry.com/blog/fixing-mystique-theme-twitter-issue/</link>
		<comments>http://shamsulamry.com/blog/fixing-mystique-theme-twitter-issue/#comments</comments>
		<pubDate>Sat, 30 Jan 2010 17:51:04 +0000</pubDate>
		<dc:creator>Amry</dc:creator>
		
		<guid isPermaLink="false">http://shamsulamry.com/?p=41</guid>
		<description><![CDATA[I am using the Mystique theme for this WordPress blog. It is a nice theme, however there is an issue that needs fixing &#8211; The Twitter widget in the default theme layout somehow defaults to WordPress&#8217;s Twitter account, and there&#8217;s no setting for that. The Twitter username is hardcoded into the theme code.
In this article, <a href="http://shamsulamry.com/blog/fixing-mystique-theme-twitter-issue/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>I am using the <a href="http://digitalnature.ro/projects/mystique/">Mystique</a> theme for this WordPress blog. It is a nice theme, however there is an issue that needs fixing &#8211; The Twitter widget in the default theme layout somehow defaults to WordPress&#8217;s Twitter account, and there&#8217;s no setting for that. The Twitter username is <a href="http://wordpress.org/support/topic/341150">hardcoded into the theme code</a>.</p>
<p>In this article, I will post the changes I did to the original theme in order to fix the Twitter issue. At the end of the article, I will provide a link to a zip file which you can download, extract to the Mystique&#8217;s theme directory and overwrite the original theme files.</p>
<p>Before that, disclaimers:</p>
<ol>
<li>I am not a WordPress expert. This is my first time hacking away a WordPress theme. I mostly did quick tries-n-errors when implementing this hack.</li>
<li>This hack is not in any way endorsed by the original creator of the Mystique theme.</li>
</ol>
<p>With that said, <strong>use this hack at your own risk</strong>. I will appreciate any feedback if you do try out this hack. <img src='http://shamsulamry.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><span id="more-41"></span></p>
<h2>Adding a Twitter tab to the Mystique settings</h2>
<p>I added a new tab for the Mystique settings. Take a look at the following screenshot to see how it looks like:</p>
<p style="text-align: center;"><img class="size-full wp-image-71 aligncenter" title="New Twitter tab in the Mystique theme settings" src="http://shamsulamry.com/wp-content/uploads/2010/01/Created-the-new-Twitter-tab-in-Mystique-theme-settings.png" alt="Created the new Twitter tab in the Mystique theme settings" width="599" height="244" /></p>
<p>Under that tab, you can set your own Twitter username to be used instead of the default WordPress&#8217;s.</p>
<p>The following code changes were made to lib/admin.php:</p>
<pre class="brush: php; first-line: 245; highlight: [246];">
if (isset($_POST['head_code'])): $options['head_code'] = stripslashes($_POST['head_code']); endif;
if (isset($_POST['twitter_username'])): $options['twitter_username'] = stripslashes($_POST['twitter_username']); endif; // Hacked by Amry
for ($i=1; $i&lt;=6; $i++)
</pre>
<pre class="brush: php; first-line: 344; highlight: [345]; html-script: true;">
 &lt;li&gt;&lt;a href='#tab-8'&gt;&lt;?php _e(&quot;User CSS&quot;,&quot;mystique&quot;); ?&gt;&lt;/a&gt;&lt;/li&gt;
 &lt;li&gt;&lt;a href='#tab-9'&gt;&lt;?php _e(&quot;Twitter&quot;,&quot;mystique&quot;); ?&gt;&lt;/a&gt;&lt;/li&gt;&lt;!-- Hacked by Amry --&gt;
&lt;/ul&gt;
</pre>
<pre class="brush: php; auto-links: false; first-line: 855; highlight: [855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875]; html-script: true;">
 &lt;!-- Hacked by Amry --&gt;
 &lt;div id=&quot;tab-9&quot;&gt;
  &lt;table style=&quot;width: auto&quot;&gt;
   &lt;tr&gt;
    &lt;th scope=&quot;row&quot;&gt;&lt;p&gt;&lt;?php _e(&quot;Twitter Username&quot;,&quot;mystique&quot;); ?&gt;&lt;/p&gt;&lt;/th&gt;
    &lt;td&gt;&lt;input name=&quot;twitter_username&quot; id=&quot;opt_twitter_username&quot; type=&quot;text&quot; value=&quot;&lt;?php $twitter_username = wp_specialchars(get_mystique_option('twitter_username')); echo $twitter_username != '' ? $twitter_username : 'wordpress'; ?&gt;&quot; /&gt;&lt;/td&gt;
   &lt;/tr&gt;

   &lt;tr&gt;
    &lt;th scope=&quot;row&quot;&gt;&lt;/th&gt;
    &lt;td&gt;
     &lt;h3&gt;&lt;?php _e(&quot;What does this do?&quot;,&quot;mystique&quot;); ?&gt;&lt;/h3&gt;
     &lt;ul style=&quot;list-style: disc&quot;&gt;
      &lt;li&gt;&lt;em&gt;&lt;?php printf(__('link the Twitter settings in the default layout to your own account','mystique')); ?&gt;&lt;/em&gt;&lt;/li&gt;
      &lt;li&gt;&lt;em&gt;&lt;?php printf(__('this is hacked by &lt;a href=&quot;http://ShamsulAmry.com/blog/fixing-mystique-theme-twitter-issue&quot;&gt;Amry&lt;/a&gt; and is not supported by the original theme creator, use at your own risk','mystique')); ?&gt;&lt;/em&gt;&lt;/li&gt;
     &lt;/ul&gt;
    &lt;/td&gt;
   &lt;/tr&gt;

  &lt;/table&gt;
 &lt;/div&gt;

&lt;/div&gt;
&lt;!-- /sections --&gt;
</pre>
<h2>Fixing the Twitter widget in the sidebar</h2>
<p>The original theme hardcoded the Twitter username to always use &#8220;wordpress&#8221;. I changed it a bit so that it reads from the saved setting in the previous step.</p>
<p>The following code changes were made to sidebar.php:</p>
<pre class="brush: php; first-line: 18; highlight: [22,23,24,25,26];">
&lt;?php if(function_exists('the_widget')):  // only in wp 2.8+

 the_widget('SidebarTabsWidget', array('orderby' =&gt; 'name', 'postcount' =&gt; true, 'showcategories' =&gt; true, 'showtags' =&gt; true, 'showarchives' =&gt; true, 'showpopular' =&gt; true, 'showrecentcomm' =&gt; true), array('widget_id'=&gt;'instance-sidebartabswidget','before_widget' =&gt; '&lt;li&gt;&lt;div&gt;','after_widget' =&gt; '&lt;/div&gt;&lt;/li&gt;','before_title' =&gt; '&lt;h3&gt;&lt;span&gt;','after_title' =&gt; '&lt;/span&gt;&lt;/h3&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;'));

 // Hacked by Amry
 $twitter_username = wp_specialchars(get_mystique_option('twitter_username'));
 if ($twitter_username == '') $twitter_username = 'wordpress';

 the_widget('TwitterWidget', array('title'=&gt;__('My latest tweets','mystique'), 'twituser'=&gt;$twitter_username, 'twitcount'=&gt;'4'), array('widget_id'=&gt;'instance-twitterwidget','before_widget' =&gt; '&lt;li&gt;&lt;div&gt;','after_widget' =&gt; '&lt;/div&gt;&lt;/li&gt;','before_title' =&gt; '&lt;h3&gt;&lt;span&gt;','after_title' =&gt; '&lt;/span&gt;&lt;/h3&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;'));

 the_widget('LoginWidget', array(), array('widget_id'=&gt;'instance-loginwidget','before_widget' =&gt; '&lt;li&gt;&lt;div&gt;','after_widget' =&gt; '&lt;/div&gt;&lt;/li&gt;','before_title' =&gt; '&lt;h3&gt;&lt;span&gt;','after_title' =&gt; '&lt;/span&gt;&lt;/h3&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;'));

 endif; ?&gt;
</pre>
<h2>Fixing the Twitter account linked from the header</h2>
<p>The original code in the theme was somehow reading the Twitter username from some setting. Nevertheless, I commented that out and replaced it so that it reads from the saved setting that I had just created.</p>
<p>The following code changes were made to header.php:</p>
<pre class="brush: php; auto-links: false; first-line: 52; highlight: [55,56,57,58,59]; html-script: true;">
&lt;?php
 //$twituser = get_mystique_option('twitter_id');
 // if(is_active_widget('TwitterWidget'))
 // Hacked by Amry
 //$twitinfo =  get_option('mystique-twitter');
 //$twituser = $twitinfo['last_twitter_id'];
 $twituser = wp_specialchars(get_mystique_option('twitter_username'));
 if ($twituser == '') $twituser = 'wordpress';

 if ($twituser): ?&gt;
 &lt;a href=&quot;http://www.twitter.com/&lt;?php echo $twituser; ?&gt;&quot; title=&quot;&lt;?php _e(&quot;Follow me on Twitter!&quot;,&quot;mystique&quot;); ?&gt;&quot;&gt;&lt;span&gt;&lt;?php _e(&quot;Follow me on Twitter!&quot;,&quot;mystique&quot;); ?&gt;&lt;/span&gt;&lt;/a&gt;
 &lt;?php endif; ?&gt;
</pre>
<h2>Download the changed files</h2>
<p>Click to download: <a href="/download/Mystique-Twitter-fix.zip">Mystique-Twitter-fix.zip</a>. This zip file contains lib/header.php, sidebar.php and header.php. Simply overwrite the original theme files with these to implement the changes. It would be a good practice to <strong>back up the original files before overwriting it in case you need to revert back</strong>.<br />
Hope this helps! <img src='http://shamsulamry.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://shamsulamry.com/blog/fixing-mystique-theme-twitter-issue/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Migrating to own domain, Part 2</title>
		<link>http://shamsulamry.com/blog/migrating-domain-part-2/</link>
		<comments>http://shamsulamry.com/blog/migrating-domain-part-2/#comments</comments>
		<pubDate>Sat, 30 Jan 2010 01:10:43 +0000</pubDate>
		<dc:creator>Amry</dc:creator>
		
		<guid isPermaLink="false">http://shamsulamry.com/?p=35</guid>
		<description><![CDATA[It&#8217;s Saturday morning, and I&#8217;m back at setting up the blog.

Looking for new themes to try out. The previous theme I set for few days: Inanis Glass, based on Windows Vista layout looked geeky. Nothing wrong with that but the theme felt &#8220;heavy&#8221; to load.
Trying out the Mystique theme. Looks fine. Felt lighter. But how <a href="http://shamsulamry.com/blog/migrating-domain-part-2/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s Saturday morning, and I&#8217;m back at setting up the blog.</p>
<ol>
<li><strong>Looking for new themes to try out.</strong> The previous theme I set for few days: Inanis Glass, based on Windows Vista layout looked geeky. Nothing wrong with that but the theme felt &#8220;heavy&#8221; to load.</li>
<li><strong>Trying out the Mystique theme.</strong> Looks fine. Felt lighter. But how do I set the Twitter widget to show <a href="http://twitter.com/shamsulamry">mine</a> instead of Wordpress&#8217;s? Can&#8217;t seem to find in the settings. Tried to drag the widget to the sidebar, but then the original sidebar layout disappears. Will look at it later. <span style="color: #ff0000;"><strong>Update Jan 31, 2010:</strong></span> See <a href="http://shamsulamry.com/blog/fixing-mystique-theme-twitter-issue/">Fixing the Mystique theme Twitter issue</a>.</li>
<li><strong>Learnt about Wordpress&#8217;s shortcodes from <a href="http://digitalnature.ro/blog/extend-wordpress-functionality-with-shortcodes/">the Mystique theme&#8217;s blog</a>.</strong> I see. So it is shortcodes I&#8217;m looking for to make the sourcecode tags appear like it was in WordPress.com.</li>
<li><strong>Looking for a SyntaxHighlighter sourcecode shortcode as seen on WordPress.com.</strong> The shortcode API seemed to already be there since WordPress 2.5. Now it is already 2.9. There should already be existing plugins implementing the sourcecode shortcode. Better search first before reinventing the wheel unnecessarily. Searched. Found: <a href="http://wordpress.org/extend/plugins/syntaxhighlighter/">SyntaxHighlighter Evolved</a>. Nice!</li>
<li><strong>Looking for an external link handler.</strong> What I want is some sort of plugin that will allow me to handle external links differently, like displaying an icon next to that link, sort of like that. Found: <a href="http://wordpress.org/extend/plugins/sem-external-links/">External Link</a>.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://shamsulamry.com/blog/migrating-domain-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Migrating to own domain</title>
		<link>http://shamsulamry.com/blog/migrating-domain/</link>
		<comments>http://shamsulamry.com/blog/migrating-domain/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 00:19:29 +0000</pubDate>
		<dc:creator>Amry</dc:creator>
		
		<guid isPermaLink="false">http://shamsulamry.com/?p=24</guid>
		<description><![CDATA[Somehow I can&#8217;t bring myself to use shamsulamry.wordpress.com that long. Simply cannot. Bought ShamsulAmry.com, will be taking a bit time to setup this one.
And I noticed the syntax highlighting stuff is not working anymore and there&#8217;s no existing syntax highlighting plug-in that could make it just work like before. So it will be either I <a href="http://shamsulamry.com/blog/migrating-domain/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>Somehow I can&#8217;t bring myself to use shamsulamry.wordpress.com that long. Simply cannot. Bought ShamsulAmry.com, will be taking a bit time to setup this one.</p>
<p>And I noticed the syntax highlighting stuff is not working anymore and there&#8217;s no existing syntax highlighting plug-in that could make it just work like before. So it will be either I need to edit the existing posts, or challenge myself to learn how to write my first WordPress plug-in that would make it simply work like before. <img src='http://shamsulamry.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://shamsulamry.com/blog/migrating-domain/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss><!-- WP Super Cache is installed but broken. The path to wp-cache-phase1.php in wp-content/advanced-cache.php must be fixed! -->
