<?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>Pearl Tech &#187; Chad Ferguson</title>
	<atom:link href="http://blog.pearltechnology.com/author/chadf/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.pearltechnology.com</link>
	<description></description>
	<lastBuildDate>Fri, 17 Feb 2012 17:35:27 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>JQGrid Client Side Sorting with .NET Dates</title>
		<link>http://blog.pearltechnology.com/jqgrid-client-side-sorting-with-net-dates/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://blog.pearltechnology.com/jqgrid-client-side-sorting-with-net-dates/#comments</comments>
		<pubDate>Fri, 17 Feb 2012 17:35:27 +0000</pubDate>
		<dc:creator>Chad Ferguson</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>

		<guid isPermaLink="false">http://blog.pearltechnology.com/?p=1292</guid>
		<description><![CDATA[I recently came across a limitation of the wonderful Jquery JQGrid. The grid supports a load once mode, that does one server call to retrieve the data and then goes into a local mode where all searching, sorting, and paging are client-side only. Unfortunately JQGrid does not support the .NET date format and when sorting [...]]]></description>
			<content:encoded><![CDATA[<p>I recently came across a limitation of the wonderful <a href="http://jquery.com/">Jquery </a><a href="http://www.trirand.com/blog/">JQGrid</a>. The grid supports a load once mode, that does one server call to retrieve the data and then goes into a local mode where all searching, sorting, and paging are client-side only. Unfortunately <a href="http://www.trirand.com/blog/">JQGrid </a>does not support the .NET date format and when sorting by the date field the <a href="http://www.trirand.com/blog/">JQGrid </a>function parseDate fails resulting in no sorting and no error thrown.  Since I did not want to go through the headache of getting another team to change the datatype of the date field I set out to find a way to handle it on the client side. Unfortunately my many searches of <a href="http://www.google.com/">google</a> and <a href="http://stackoverflow.com">stack overflow</a> resulted in nothing, so I had to settle with the programmer’s last resource which is to write it himself.   Thankfully this was an easy fix, and utilizing overriding I did it without having to change the <a href="http://www.trirand.com/blog/">JQGrid </a>source. The parseDate function that is called accepts both the format the date should be in, and the value. So we can start by adding a function to our own .js file with that same signature as seen below:</p>
<p><code>$.jgrid.parseDate = function (format, value) {<br />
}</code></p>
<p>Note: this .js file will need to be loaded after the <a href="http://www.trirand.com/blog/">JQGrid </a>.js file</p>
<p>So first we will need to create some functions that will format our date into a string so that the sorter can handle it much better. I have included two functions below, that we use that both converts the .NET date type to a javascript data, and then converts it to a string in the format that we use. </p>
<p><code>function formatDateValue(value) {<br />
    var date = convertToDate(value);<br />
    var curr_date = date.getDate();<br />
    if (curr_date < 10)<br />
        curr_date = '0' + curr_date;<br />
    var curr_month = date.getMonth();<br />
    curr_month++;<br />
    if (curr_month < 10)<br />
        curr_month = '0' + curr_month;<br />
    var curr_year = date.getFullYear();<br />
    var datestring = curr_month + "/" + curr_date + "/" + curr_year;<br />
    return datestring;<br />
}</p>
<p>function convertToDate(value) {<br />
    var date;<br />
    if (Object.prototype.toString.call(value) === '[object Date]')<br />
        date = value;<br />
    else if (value.indexOf('Date(') != -1)<br />
        date = new Date(parseInt(value.substr(6))); // json type<br />
    else<br />
        date = new Date(value);<br />
    return date;<br />
}<br />
</code><br />
Finally we need to just bring over the code from the <a href="http://www.trirand.com/blog/">JQGrid </a>src and simply add a call to our function at the top:</p>
<p><code><br />
$.jgrid.parseDate = function (format, value) {<br />
    var date = formatDateValue(value); //call to our function to correct the issue<br />
    var tsp = { m: 1, d: 1, y: 1970, h: 0, i: 0, s: 0 }, k, hl, dM, regdate = /[\\\/:_;.,\t\T\s-]/;<br />
    if (date &#038;&#038; date !== null &#038;&#038; date !== undefined) {<br />
        date = $.trim(date);<br />
        date = date.split(regdate);<br />
        format = format.split(regdate);<br />
        var dfmt = $.jgrid.formatter.date.monthNames;<br />
        var afmt = $.jgrid.formatter.date.AmPm;<br />
        var h12to24 = function (ampm, h) {<br />
            if (ampm === 0) { if (h == 12) { h = 0; } }<br />
            else { if (h != 12) { h += 12; } }<br />
            return h;<br />
        };<br />
        for (k = 0, hl = format.length; k < hl; k++) {<br />
            if (format[k] == 'M') {<br />
                dM = $.inArray(date[k], dfmt);<br />
                if (dM !== -1 &#038;&#038; dM < 12) { date[k] = dM + 1; }<br />
            }<br />
            if (format[k] == 'F') {<br />
                dM = $.inArray(date[k], dfmt);<br />
                if (dM !== -1 &#038;&#038; dM > 11) { date[k] = dM + 1 - 12; }<br />
            }<br />
            if (format[k] == 'a') {<br />
                dM = $.inArray(date[k], afmt);<br />
                if (dM !== -1 &#038;&#038; dM < 2 &#038;&#038; date[k] == afmt[dM]) {<br />
                    date[k] = dM;<br />
                    tsp.h = h12to24(date[k], tsp.h);<br />
                }<br />
            }<br />
            if (format[k] == 'A') {<br />
                dM = $.inArray(date[k], afmt);<br />
                if (dM !== -1 &#038;&#038; dM > 1 &#038;&#038; date[k] == afmt[dM]) {<br />
                    date[k] = dM - 2;<br />
                    tsp.h = h12to24(date[k], tsp.h);<br />
                }<br />
            }<br />
            if (date[k] !== undefined) {<br />
                tsp[format[k].toLowerCase()] = parseInt(date[k], 10);<br />
            }<br />
        }<br />
        tsp.m = parseInt(tsp.m, 10) - 1;<br />
        var ty = tsp.y;<br />
        if (ty >= 70 &#038;&#038; ty <= 99) { tsp.y = 1900 + tsp.y; }<br />
        else if (ty >= 0 &#038;&#038; ty <= 69) { tsp.y = 2000 + tsp.y; }<br />
    }<br />
    return new Date(tsp.y, tsp.m, tsp.d, tsp.h, tsp.i, tsp.s, 0);<br />
}<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pearltechnology.com/jqgrid-client-side-sorting-with-net-dates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JQGrid and Jquery &#8211; Move toolbar below pager</title>
		<link>http://blog.pearltechnology.com/jqgrid-and-jquery-move-toolbar-below-pager/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://blog.pearltechnology.com/jqgrid-and-jquery-move-toolbar-below-pager/#comments</comments>
		<pubDate>Thu, 05 Jan 2012 14:47:55 +0000</pubDate>
		<dc:creator>Chad Ferguson</dc:creator>
				<category><![CDATA[Application Development]]></category>
		<category><![CDATA[JQGrid]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://blog.pearltechnology.com/?p=1288</guid>
		<description><![CDATA[For a current client it was requested that I move the JQGrid toolbar below the pager if a pager exists. The Toolbar is a nice feature of the JQGrid which can be used for pratically anything. Unfortunately the way the toolbar is set up can be hard to work with. The toolbar can be set [...]]]></description>
			<content:encoded><![CDATA[<p>For a current client it was requested that I move the JQGrid toolbar below the pager if a pager exists. The Toolbar is a nice feature of the JQGrid which can be used for pratically anything. Unfortunately the way the toolbar is set up can be hard to work with. The toolbar can be set into one of 3 positions: Above the header row (Top), below the footer row (Bottom), and both (Both). When the either the top or bottom option is selected a toolbar with id t_<your gridid> is created. If the Both option is selected the Top toolbar will have an id of t_<your gridid> and the bottom will have an id of tb_<your gridid>. This complicates things since I only want to move the bottom toolbar. Thankefully Jquery has a method, <a href="http://api.jquery.com/last/">Last</a>, that will solve the problem. Last does what we need which is grab the last child of a selector. The grid&#8217;s sections are divided up into divs under a parent div with the id of gview_<your gridid>. If a bottom toolbar exists, it will always be the last div under that parent. So first we check if a pager exists, then get the last child of the gview div, and if that child has a class of ui-userdata, which indicates that it is a toolbar, we can detach it and insert it after the pager as seen below.</p>
<p><code><br />
function moveLowerJQGridToolbar(gridid) {<br />
    var pager = $('#' + gridid + '_pager');<br />
    if ($(pager).exists()) {<br />
        var lastChild = $('#gview_' + gridid).children().last();<br />
        if (lastChild.hasClass('ui-userdata')) {<br />
            var toolbar = $(lastChild).detach();<br />
            $(toolbar).insertAfter(pager);<br />
        }<br />
    }<br />
}</code></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pearltechnology.com/jqgrid-and-jquery-move-toolbar-below-pager/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XNA Tutorial Series 1: Golf (Patience) Solitaire Part II – Deck Class</title>
		<link>http://blog.pearltechnology.com/xna-tutorial-series-1-golf-patience-solitaire-part-ii-%e2%80%93-deck-class/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://blog.pearltechnology.com/xna-tutorial-series-1-golf-patience-solitaire-part-ii-%e2%80%93-deck-class/#comments</comments>
		<pubDate>Mon, 19 Dec 2011 19:46:32 +0000</pubDate>
		<dc:creator>Chad Ferguson</dc:creator>
				<category><![CDATA[Application Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Game Programming]]></category>
		<category><![CDATA[XNA; Solitaire]]></category>

		<guid isPermaLink="false">http://blog.pearltechnology.com/?p=1283</guid>
		<description><![CDATA[Golf Solitaire as described by wikipedia:
Golf is a Patience game where players try to earn the lowest number of points (as in golf, the sport) over the course of nine deals (or &#8220;holes&#8221; to further use golfing teminology). It has a tableau of 35 face-up cards and a higher ratio of skill to luck than [...]]]></description>
			<content:encoded><![CDATA[<p>Golf Solitaire as described by wikipedia:</p>
<p>Golf is a Patience game where players try to earn the lowest number of points (as in golf, the sport) over the course of nine deals (or &#8220;holes&#8221; to further use golfing teminology). It has a tableau of 35 face-up cards and a higher ratio of skill to luck than most other solitaire card games.</p>
<p>My attempts in this tutorial series will be able to keep the code reusable and hopefully build onto this series with other Card/Solitaire games. </p>
<p><strong>XNA Tutorial Series 1: Golf (Patience) Solitaire Part III &#8211; Deck Class</strong><br />
For this tutorial we will focus on the class that will handle the logic for a group of cards. Start by right clicking on your classes folder and adding a new class called Deck.cs. The first thing we will need to do is setup are using&#8217;s as follows:<br />
<code><br />
        using System;<br />
        using System.Collections.Generic;<br />
        using System.Linq;<br />
        using Microsoft.Xna.Framework;<br />
        using Microsoft.Xna.Framework.Content;<br />
        using Microsoft.Xna.Framework.Graphics;<br />
        using Microsoft.Xna.Framework.Input;<br />
</code></p>
<p>Next set your class to be public.</p>
<p>Now we can begin by adding a Enum to our class to represent a deck type:<br />
<code><br />
        public enum DeckType<br />
        {<br />
            User = 1,<br />
            Source,<br />
            Waste,<br />
            Target<br />
        };<br />
</code></p>
<p>Now we can setup the individual properties that a Card will have, I will show the code first and then proceed to explain what each property is for:<br />
<code><br />
        protected List cards = new List();<br />
        protected Point pos;<br />
        protected int deckID;<br />
        protected DeckType deckType;<br />
        Texture2D background;</p>
<p>        public virtual Point Position<br />
        {<br />
            get<br />
            {<br />
                return pos;<br />
            }<br />
            set<br />
            {<br />
                pos = value;<br />
            }<br />
        }</p>
<p>        public DeckType Type<br />
        {<br />
            get<br />
            {<br />
                return deckType;<br />
            }<br />
        }<br />
</code><br />
cards will be a list of the cards in the deck, pos is a point that is used for offsetting a card image so you can have one card on top of another and see the values for both. deckID is an ID for keeping track of the decks. DeckType to indicate the enum for which type of deck it is, and a texture to store the decks background.</p>
<p>Next we have our constructors:<br />
<code><br />
        public Deck()<br />
        {<br />
            deckType = DeckType.User;<br />
        }</p>
<p>        public Deck(int id)<br />
        {<br />
            deckID = id;<br />
            deckType = DeckType.User;<br />
        }<br />
</code></p>
<p>Since this deck class is going to be a base type it will default to being a user deck, other deck types (waste, source, etc..) will implement the desk class. Next we will need some basic methods for maintaining the list of cards that are in the deck.</p>
<p>First we will need to be able to retrieve the number of cards in the deck:<br />
<code><br />
        public virtual int CardCount()<br />
        {<br />
            return cards.Count();<br />
        }</p>
<p>Get the last card(top) of the deck<br />
        public virtual Card GetLast()<br />
        {<br />
            return cards.Last();<br />
        }</p>
<p>Remove the last card<br />
        public virtual Card RemoveLast()<br />
        {<br />
            Card card = cards.Last();<br />
            cards.Remove(card);<br />
            return card;<br />
        }</p>
<p>And finally get a card<br />
        public virtual Card GetCard(int index)<br />
        {<br />
            return cards[index];<br />
        }<br />
</code></p>
<p>In the second part of the deck class we will look at Adding cards, handling input, and drawing the cards.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pearltechnology.com/xna-tutorial-series-1-golf-patience-solitaire-part-ii-%e2%80%93-deck-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JQGrid and a getRowData issue</title>
		<link>http://blog.pearltechnology.com/jqgrid-and-a-getrowdata-issue/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://blog.pearltechnology.com/jqgrid-and-a-getrowdata-issue/#comments</comments>
		<pubDate>Fri, 16 Dec 2011 16:24:46 +0000</pubDate>
		<dc:creator>Chad Ferguson</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>

		<guid isPermaLink="false">http://blog.pearltechnology.com/?p=1278</guid>
		<description><![CDATA[Recent work for a client has involved a large amount of work with the excellent Jquery plugin JQGrid. Per the clients requirements I needed to fire an event on row select that would execute another event that is stored in the object. Part of the JQGrid api is a function that allows you to retrieve [...]]]></description>
			<content:encoded><![CDATA[<p>Recent work for a client has involved a large amount of work with the excellent <a href="http://jquery.com/">Jquery</a> plugin <a href="http://www.trirand.com/blog/">JQGrid</a>. Per the clients requirements I needed to fire an event on row select that would execute another event that is stored in the object. Part of the JQGrid api is a function that allows you to retrieve the data associated with a row and do what you please with it.<br />
<code><br />
$(gridid).jqGrid('getRowData', rowid);<br />
</code><br />
Unfortunately this only returns the data that was actually being displayed by the grid and any other undisplayed objects are not returned. Since I had a complex object that would not be displayed in the grid but was needed for actions in the grid I had to find a way to retrieve the entire object that was used to populate the row. Another option is too use the the grid params and retrieve that data object.<br />
<code><br />
$(gridid).jqGrid('getGridParam', 'data');<br />
</code><br />
However, I quickly discovered that method only works with local data. So to solve my problem I had to leverage a nice Jquery function known as <a href="http://api.jquery.com/jQuery.data/">.Data()</a>. With this function I could store my grid data and associate it to the grid. Then using the the rowid of the selected row I could quickly find the full object that was used to create the row. So to do this I first had to assign the data, which is done via the jqgrid event &#8216;LoadComplete&#8217;. Then in my select row event I can retrieve that data and find my row object.<br />
<code><br />
function jqGridLoadComplete(data, gridid) {<br />
    $('#' + gridid).data("jqData", data.Rows);<br />
}<br />
function onJQRowSelect(rowid, status, callback, gridid) {<br />
    var alldata = $('#' + gridid).data("jqData");<br />
    var data = alldata[rowid - 1];<br />
}<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pearltechnology.com/jqgrid-and-a-getrowdata-issue/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XNA Tutorial Series 1: Golf (Patience) Solitaire Part I &#8211; Card Class</title>
		<link>http://blog.pearltechnology.com/xna-tutorial-series-1-golf-patience-solitaire-part-i-card-class/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://blog.pearltechnology.com/xna-tutorial-series-1-golf-patience-solitaire-part-i-card-class/#comments</comments>
		<pubDate>Tue, 22 Nov 2011 13:24:26 +0000</pubDate>
		<dc:creator>Chad Ferguson</dc:creator>
				<category><![CDATA[Application Development]]></category>

		<guid isPermaLink="false">http://blog.pearltechnology.com/?p=1237</guid>
		<description><![CDATA[Golf Solitaire as described by wikipedia:
Golf is a Patience game where players try to earn the lowest number of points (as in golf, the sport) over the course of nine deals (or &#8220;holes&#8221; to further use golfing teminology). It has a tableau of 35 face-up cards and a higher ratio of skill to luck than [...]]]></description>
			<content:encoded><![CDATA[<p><em>Golf Solitaire as described by wikipedia:<br />
Golf is a Patience game where players try to earn the lowest number of points (as in golf, the sport) over the course of nine deals (or &#8220;holes&#8221; to further use golfing teminology). It has a tableau of 35 face-up cards and a higher ratio of skill to luck than most other solitaire card games.</em></p>
<p>My attempts in this tutorial series will be able to keep the code reusable and hopefully build onto this series with other Card/Solitaire games. Also this tutorial assumes that you have basic XNA knowledge. </p>
<p><u><strong>XNA Tutorial Series 1: Golf (Patience) Solitaire Part I &#8211; Project Setup</strong></u></p>
<p>Start by creating a new XNA 4.0 Windows game project. In my sample I named the project &#8220;Patience&#8221; but you are free to name it whatever you like. Then in the main project right click the project and add a new folder called classes. This will be where we define our game logic.</p>
<p><img src="http://blog.pearltechnology.com/wp-content/uploads/2011/07/project.JPG" alt="project" title="project" width="212" height="305" class="aligncenter size-full wp-image-1240" /></p>
<p>Also in your Content Project right click and add  &#8220;Cards&#8221; and &#8220;Fonts&#8221; Directories. Where the actual game art will be stored. Right now that gives us the basis for starting our game. In the next tutorial we will focus on creating the Card class.</p>
<p>For this tutorial we will focus on the class that will handle the logic for one individual card. Start by right clicking on your classes folder and adding a new class called Card.cs. The first thing we will need to do is setup are using&#8217;s as follows:<br />
<code><br />
using System;<br />
using Microsoft.Xna.Framework;<br />
using Microsoft.Xna.Framework.Content;<br />
using Microsoft.Xna.Framework.Graphics;<br />
using Microsoft.Xna.Framework.Input;<br />
</code></p>
<p>Next set your class to be public.</p>
<p>Now we can begin by adding some Enums to our class. The first enum will deal with the suit of the cards:<br />
<code><br />
public enum CardSuit<br />
{<br />
             Clubs = 1,<br />
             Diamonds,<br />
             Hearts,<br />
             Spades<br />
}<br />
</code><br />
The next enum will be for the value of the cards:<br />
<code><br />
 public enum CardValue<br />
        {<br />
             Ace = 1,<br />
             Two,<br />
             Three,<br />
             Four,<br />
             Five,<br />
             Six,<br />
             Seven,<br />
             Eight,<br />
             Nine,<br />
             Ten,<br />
             Jack,<br />
             Queen,<br />
             King<br />
        }<br />
</code><br />
The final enum will be for indicating what color the card is:<br />
<code><br />
public enum CardColor<br />
        {<br />
             Black = 1,<br />
             Red<br />
        }<br />
</code></p>
<p>Now we can setup the individual properties that a Card will have, I will show the code first and then proceed to explain what each property is for:<br />
<code></p>
<p>public CardSuit Suit { get; set; }<br />
        public CardValue Value { get; set; }<br />
        public CardColor TheColor { get; set; }<br />
        public Boolean IsTurned { get; set; }<br />
        public Card ParentCard { get; set; }<br />
        public Card ChildCard { get; set; }<br />
        public int ZOrder { get; set; }<br />
        public String CardName { get; set; }<br />
        public Deck OwnerDeck { get; set; }<br />
        public Rectangle OriginRect { get; set; }<br />
        public static int CARD_WIDTH = 80;<br />
        public static int CARD_HEIGHT = 110;<br />
        Texture2D card = null;<br />
        Texture2D cardBack = null;<br />
        Rectangle rect;</p>
<p>        public Rectangle CardRectangle<br />
        {<br />
            get<br />
            {<br />
                return rect;<br />
            }<br />
            set<br />
            {<br />
                rect = value;<br />
            }<br />
        }<br />
</code></p>
<p>The first three will be used to set the enums(Suit, value, and color) for the specific card. IsTurned will be used to determine if the front or the back of the card should be drawn. ParentCard and ChildCard will be used for indicating what card is above and below the card on the screen. ZOrder is similar to the css property z-index and will be used for card drag and drop. Though this game does not have drag and drop capability we are adding the ZOrder property for future use. CardName will be a string that will indicate which artwork to use, it will be made up of concatenating the cards suit with a &#8220;-&#8221; and the cards value. If you choose to use cards other than the ones I provide, please be sure they follow this naming convention. OwnerDeck will refer to which deck the card is currently in (draw pile, plateau, waste, etc&#8230;) this refers to a class that we will develop in part 3 of this series. Teh we have the OriginRect this is a placeholder value so that we always know where the card came from, in case we ever need to return it to that spot. Then we have two static variables for storing the size of the card. Next we have two XNA textures that will store the card image and the back of the card image. Finally we have the rectangle where those card images will be drawn.</p>
<p>Next up is the constructor followed by a description:<br />
<code><br />
public Card(CardSuit suit, CardValue value, int z, ContentManager contentManager)<br />
        {<br />
            ZOrder = z;<br />
            ParentCard = null;<br />
            ChildCard = null;<br />
            OwnerDeck = null;</p>
<p>            LoadCard(suit, value, contentManager);<br />
        }<br />
</code></p>
<p>Since we are just declaring the card and not yet putting it in a deck we will be setting several of the properties to null, and then lastly we call another method to load the cards content based on the suit and value that we passed in.</p>
<p>The cards Load method is detailed next:<br />
<code><br />
 public void LoadCard(CardSuit suit, CardValue value, ContentManager contentManager)<br />
        {<br />
            if (suit == CardSuit.Clubs || suit == CardSuit.Spades)<br />
                TheColor = CardColor.Black;<br />
            else<br />
                TheColor = CardColor.Red;</p>
<p>            Suit = suit;<br />
            Value = value;</p>
<p>            //Set default pos and size<br />
            CardRectangle = new Rectangle(0, 0, CARD_WIDTH, CARD_HEIGHT);</p>
<p>            // Card background<br />
            cardBack = contentManager.Load("Cards/card_background");</p>
<p>            CardName = suit.ToString() + "_" + value.ToString();</p>
<p>            card = contentManager.Load("Cards/" + CardName);<br />
        }<br />
</code></p>
<p>Based on the suit we first determine the cards color, Clubs/Spades are black and Hearts/Diamonds are red. We set the cards suit and value from the passed in parameters and then we create the rectangle that will hold the card texture. Next we load the cards background picture into its texture, and then after determine the cards name we load the card image into its texture.</p>
<p>Finally we have the method that will draw the card to the screen:<br />
<code><br />
public void Draw(SpriteBatch theSpriteBatch)<br />
        {<br />
            if (IsTurned)<br />
            {<br />
                if (card != null)<br />
                    theSpriteBatch.Draw(card, CardRectangle, Color.White);<br />
            }<br />
            else<br />
            {<br />
                if (cardBack != null)<br />
                    theSpriteBatch.Draw(cardBack, CardRectangle, Color.White);<br />
            }<br />
        }<br />
</code><br />
Here we are determining if the card is face up or face down and drawing that particular image to the screen.</p>
<p>That is it right now for our card class. In the future it will be expanded more to handle different input types like drag and drop but for now clicking on the card is all that is necessary.  Also not the reason the card has no coordinates is because it&#8217;s draw location will be based on the location of it&#8217;s stack/deck. Stay tuned for the next part in the series where we will make a deck class.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pearltechnology.com/xna-tutorial-series-1-golf-patience-solitaire-part-i-card-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Microsoft Certification Prep Tips</title>
		<link>http://blog.pearltechnology.com/microsoft-certification-prep-tips/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://blog.pearltechnology.com/microsoft-certification-prep-tips/#comments</comments>
		<pubDate>Mon, 09 May 2011 16:47:15 +0000</pubDate>
		<dc:creator>Chad Ferguson</dc:creator>
				<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[70-500]]></category>
		<category><![CDATA[70-501]]></category>
		<category><![CDATA[70-502]]></category>
		<category><![CDATA[70-503]]></category>
		<category><![CDATA[70-504]]></category>
		<category><![CDATA[70-505]]></category>
		<category><![CDATA[70-506]]></category>
		<category><![CDATA[70-507]]></category>
		<category><![CDATA[70-508]]></category>
		<category><![CDATA[70-509]]></category>
		<category><![CDATA[70-510]]></category>
		<category><![CDATA[70-511]]></category>
		<category><![CDATA[70-512]]></category>
		<category><![CDATA[70-513]]></category>
		<category><![CDATA[70-514]]></category>
		<category><![CDATA[70-515]]></category>
		<category><![CDATA[70-516]]></category>
		<category><![CDATA[70-517]]></category>
		<category><![CDATA[70-518]]></category>
		<category><![CDATA[70-519]]></category>
		<category><![CDATA[70-520]]></category>
		<category><![CDATA[70-521]]></category>
		<category><![CDATA[70-522]]></category>
		<category><![CDATA[70-523]]></category>
		<category><![CDATA[70-524]]></category>
		<category><![CDATA[70-525]]></category>
		<category><![CDATA[70-526]]></category>
		<category><![CDATA[70-527]]></category>
		<category><![CDATA[70-528]]></category>
		<category><![CDATA[70-529]]></category>
		<category><![CDATA[70-530]]></category>
		<category><![CDATA[70-531]]></category>
		<category><![CDATA[70-532]]></category>
		<category><![CDATA[70-533]]></category>
		<category><![CDATA[70-534]]></category>
		<category><![CDATA[70-535]]></category>
		<category><![CDATA[70-536]]></category>
		<category><![CDATA[70-537]]></category>
		<category><![CDATA[70-538]]></category>
		<category><![CDATA[70-539]]></category>
		<category><![CDATA[70-540]]></category>
		<category><![CDATA[70-541]]></category>
		<category><![CDATA[70-542]]></category>
		<category><![CDATA[70-543]]></category>
		<category><![CDATA[70-544]]></category>
		<category><![CDATA[70-545]]></category>
		<category><![CDATA[70-546]]></category>
		<category><![CDATA[70-547]]></category>
		<category><![CDATA[70-548]]></category>
		<category><![CDATA[70-549]]></category>
		<category><![CDATA[70-550]]></category>
		<category><![CDATA[70-551]]></category>
		<category><![CDATA[70-552]]></category>
		<category><![CDATA[70-553]]></category>
		<category><![CDATA[70-554]]></category>
		<category><![CDATA[70-555]]></category>
		<category><![CDATA[70-556]]></category>
		<category><![CDATA[70-557]]></category>
		<category><![CDATA[70-558]]></category>
		<category><![CDATA[70-559]]></category>
		<category><![CDATA[70-560]]></category>
		<category><![CDATA[70-561]]></category>
		<category><![CDATA[70-562]]></category>
		<category><![CDATA[70-563]]></category>
		<category><![CDATA[70-564]]></category>
		<category><![CDATA[70-565]]></category>
		<category><![CDATA[70-566]]></category>
		<category><![CDATA[70-567]]></category>
		<category><![CDATA[70-568]]></category>
		<category><![CDATA[70-569]]></category>
		<category><![CDATA[70-570]]></category>
		<category><![CDATA[70-571]]></category>
		<category><![CDATA[70-572]]></category>
		<category><![CDATA[70-573]]></category>
		<category><![CDATA[70-574]]></category>
		<category><![CDATA[70-575]]></category>
		<category><![CDATA[70-576]]></category>
		<category><![CDATA[70-577]]></category>
		<category><![CDATA[70-578]]></category>
		<category><![CDATA[70-579]]></category>
		<category><![CDATA[70-580]]></category>
		<category><![CDATA[70-581]]></category>
		<category><![CDATA[70-582]]></category>
		<category><![CDATA[70-583]]></category>
		<category><![CDATA[70-584]]></category>
		<category><![CDATA[70-585]]></category>
		<category><![CDATA[70-586]]></category>
		<category><![CDATA[70-587]]></category>
		<category><![CDATA[70-588]]></category>
		<category><![CDATA[70-589]]></category>
		<category><![CDATA[70-590]]></category>
		<category><![CDATA[70-591]]></category>
		<category><![CDATA[70-592]]></category>
		<category><![CDATA[70-593]]></category>
		<category><![CDATA[70-594]]></category>
		<category><![CDATA[70-595]]></category>
		<category><![CDATA[70-596]]></category>
		<category><![CDATA[70-597]]></category>
		<category><![CDATA[70-598]]></category>
		<category><![CDATA[70-599]]></category>
		<category><![CDATA[certification]]></category>
		<category><![CDATA[MCITP]]></category>
		<category><![CDATA[MCP]]></category>
		<category><![CDATA[MCPD]]></category>
		<category><![CDATA[MCTS]]></category>

		<guid isPermaLink="false">http://blog.pearltechnology.com/?p=1218</guid>
		<description><![CDATA[In recent years I have luckily been very successful with passing a few of Microsoft&#8217;s certification exams. Like many others when I first attempted certification I went out and acquired the typical textbooks and practice exams, spent several months reading and re-reading, and took the practice exams to the point that I didn&#8217;t even have [...]]]></description>
			<content:encoded><![CDATA[<p>In recent years I have luckily been very successful with passing a few of Microsoft&#8217;s certification exams. Like many others when I first attempted certification I went out and acquired the typical textbooks and practice exams, spent several months reading and re-reading, and took the practice exams to the point that I didn&#8217;t even have to read the question before answering. The result: I failed. A lot of the preparatory textbooks out there just do not cut it when helping you to prepare for the exam. Even though exam requirements usually dictate that you should have anywhere from 1-5 years experience in the particular subject matter, the books always seem to be written for an audience that has 0 years of experience. Much of the time leaving you feeling like the book taught you nothing and the exam content was a lot more in-depth than expected. Plus on top of all of that the exam materials are usually written before the exam is released and does not always cover the required materials as exam content is subject to change. Additionally, some of the preparatory material is known for unfortunately having a long list of errata, which just doesn&#8217;t cut it when you are trying to prepare for an exam. </p>
<p>So that brings me to my solution which is simple and free, and no it is not braindumps which will just hurt you in the long run. Microsoft provides you all you need to prepare by giving you the outline. Utilizing the outline and MSDN it is relatively easy, though very time consuming, to essentially frame out your own book that will be current and error free. So for example lets take a look at the outline for exam <a href="http://www.microsoft.com/learning/en/us/exam.aspx?ID=70-573&#038;locale=en-us">70-573: Microsoft SharePoint 2010, Application Development</a>. The first section deals with interacting with the Sharepoint UI via .NET, more specifically in the first bullet point of utilizing the SPWeb and SPSite objects. What I will do is copy the contents of the outline in to my own html file and proceed to seek out links, preferabbly to the MSDN, detailing the content that the bullet point refers to. So for the example of the 1st bullet point in exam 70-573 the outline has as follows: (Content is subject to change at Microsoft&#8217;s discretion)<br /><strong><br />
This objective may include but is not limited to: creating sub webs, referencing SPFiles, manipulating property bag, when to call Update, referencing SPContext, SPSite, SPWeb,  SPSite.OpenWeb, SPWeb.Webs, feature activiation and deactivation</p>
<p>This objective does not include: trivial cases such as setting title and other loose properties of the objects<br />
</strong></p>
<p>I then proceed to build up my content links similar to what I show here:<br />
<br />
<strong>This objective may include but is not limited to:</strong> </p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms473633.aspx">Site<br />
		Architecture</a></li>
<li>
		<a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfile.aspx">SPFiles</a></li>
<li>
		<a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spcontext.aspx">SPContext</a></li>
<li>
		<a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsite.aspx">SPSite</a></li>
<li>
		<a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsite.features.aspx"><br />
		SPSite.Features</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms431062.aspx"><br />
		SPFeatureCollection</a></li>
<li>
		<a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.aspx">SPWeb</a></li>
<li>
		<a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.features.aspx"><br />
		SPWeb.Features</a></li>
<li>
		<a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.properties.aspx"><br />
		SPWeb.Properties</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms454879.aspx">SPSite.OpenWeb</a></li>
<li>
		<a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.webs.aspx">SPWeb.Webs</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms465759.aspx"><br />
		SPWebCollection</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ee557362.aspx"><br />
		Disposal</a></li>
</ul>
<p>Not only are you getting the content from the source that the exams are based off, but as you delve deeper and deeper into the MSDN you will get a more fuller and rewarding experience then most of the preparatory textbooks will provide. This has become a popular technique for preparation over the past few years, and sometimes you may find bloggers that will post their MSDN linked outlines online, but usually I prefer to create my own since they may have excluded content that they didnt neccesarily need for their own preperation. So hopefully this technique will help you some in your own preparation, and good luck.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pearltechnology.com/microsoft-certification-prep-tips/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Sharepoint 2010 Developer Dashboard</title>
		<link>http://blog.pearltechnology.com/sharepoint-2010-developer-dashboard/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://blog.pearltechnology.com/sharepoint-2010-developer-dashboard/#comments</comments>
		<pubDate>Mon, 14 Mar 2011 13:31:39 +0000</pubDate>
		<dc:creator>Chad Ferguson</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>

		<guid isPermaLink="false">http://blog.pearltechnology.com/?p=1029</guid>
		<description><![CDATA[Today I came across a cool hidden feature new to SharePoint 2010 known as the Developer Dashboard. The Developer Dashboard allows you to see the page requests and the amount of time it took for each individual piece of the page to load. Also you are able to see the database queries the page made, [...]]]></description>
			<content:encoded><![CDATA[<p>Today I came across a cool hidden feature new to SharePoint 2010 known as the Developer Dashboard. The Developer Dashboard allows you to see the page requests and the amount of time it took for each individual piece of the page to load. Also you are able to see the database queries the page made, the length of time it took to execute the query, and its call stack. Making this a great valuable tool for debugging SharePoint.</p>
<p><img src="http://blog.pearltechnology.com/wp-content/uploads/2011/03/dd1.JPG" alt="dd" title="dd" width="558" height="400" class="aligncenter size-full wp-image-1032" /></p>
<p>By default this wonderful tool is not available but can be easily added. To install the dashboard launch the SharePoint 2010 Management Shell and enter the following command:<br />
<code><br />
stsadm -o setproperty -pn developer-dashboard -pv ondemand<br />
</code></p>
<p>The ondemand option configures the dashboard to open only when you click the icon, other options are &#8220;on&#8221; for always on, and &#8220;off&#8221; to disable the dashboard. Once the command has successfuly installed the dashboard you will now have an icon in your portal like pictured below.</p>
<p><img src="http://blog.pearltechnology.com/wp-content/uploads/2011/03/icon.JPG" alt="icon" title="icon" width="303" height="179" class="aligncenter size-full wp-image-1036" /></p>
<p>Happy Debugging!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pearltechnology.com/sharepoint-2010-developer-dashboard/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Blackboard WebCT CE8 SSO in C#</title>
		<link>http://blog.pearltechnology.com/blackboard-webct-ce8-sso-in-c/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://blog.pearltechnology.com/blackboard-webct-ce8-sso-in-c/#comments</comments>
		<pubDate>Wed, 02 Mar 2011 14:54:46 +0000</pubDate>
		<dc:creator>Chad Ferguson</dc:creator>
				<category><![CDATA[Application Development]]></category>

		<guid isPermaLink="false">http://blog.pearltechnology.com/?p=1003</guid>
		<description><![CDATA[Recently I was tasked with developing a single-sign-on solution for accessing Blackboard&#8217;s WebCT CE8 via SharePoint. Blackboard provides examples and instructions for setting up an SSO in the document WebCT Automatic Signon Protocol which can be found if searched for; however it is all written with PHP, PERL, and Java developers in mind. To implement [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I was tasked with developing a single-sign-on solution for accessing <a href="http://www.blackboard.com/">Blackboard&#8217;s</a> WebCT CE8 via SharePoint. Blackboard provides examples and instructions for setting up an SSO in the document <strong>WebCT Automatic Signon Protocol</strong> which can be found if searched for; however it is all written with PHP, PERL, and Java developers in mind. To implement SSO with WebCT you are simply just building a URL that contains the information in the query string that is necessary to let blackboard know that the user was already authenticated by other means. This URL is not simple by any means, as it will need to contain a timestamp, URL, ID for WebCT, and a Message Authentication Code (MAC). As stated in the WebCT Automatic Signon Protocol the format of the automatic signon url is as follows:</p>
<pre name="code" language="html">
http://[host_and_port]/webct/public/autosignon?wuui=[uid]&#038;timestamp=[unix_epoch_time]&#038;url=[url]&#038;glcid=[glcid]&#038;mac=[mac]
</pre>
<p>Replacing the following the bracketed items with:<br />
[host_and_port] enter your WebCT server host and port number<br />
[uid] the userid for the user that is being auto signed in.<br />
[unix_epoch_time] the number of seconds since 1/1/1970, which we will calculate below<br />
[url] the page in WebCT that the user will be directed to ex. cobaltMainFrame.dowebct is used for the default page<br />
[glcid] this is an ID for the WebCT. Generally this is something you can get from your WebCT admin<br />
[mac] this is the Message Authentication Code(MAC) which is the summed ASCII values of the [uid], [unix_epoch_time], and [url]. That value is then converted to a string and then the WebCT Shared Secret* is appended to the value. That string is then encrytped using MD5 and then converted to hexadecimal.</p>
<p>*WebCT Shared Secret is a secret passphrase stored in the settings of WebCT that generally this is something you can get from your WebCT admin</p>
<p>Now that we know what needs to be constructed, we can get to a little coding to build up the URL.</p>
<p>The first piece we are going to need is that odd unix_epoch_time value. To get we are going to have to take the current UTC time and subtract the number of seconds since 1/1/1970</p>
<pre <pre name="code" language="c-sharp">
string timestamp = ((Int64)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString();
</pre>
<p>The second piece is then the MAC. For this we will want to write a function that will accept our [uid], [timestamp], [url], and the Shared Secret. Since we will be just using the sum of the ASCII values for [uid], [timestamp], [url] I will just be passing them in all as one string with out spaces. (i.e. [uid] + [timestamp] + [url])</p>
<p>The following code sample will require these Includes:</p>
<pre name="code" language="c-sharp">
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
</pre>
<pre name="code" language="c-sharp">
     static string getMd5Hash(string input, string secret)
     {
            // get ascii of all param values
            int asciiValue = 0;
            byte[] value;

            for (int i = 0; i < input.Length; i++)
            {
                value = Encoding.ASCII.GetBytes(input.ToString().Substring(i, 1));//get the characters ASCII value
                asciiValue += Convert.ToInt32(value[0].ToString());//add to total
            }

            MD5 md5Hash = MD5.Create();
            byte[] data = new byte[16];

            //Hash the asciiValue + the secret
            data = md5Hash.ComputeHash(Encoding.Default.GetBytes(asciiValue.ToString() + secret));
            StringBuilder builder = new StringBuilder();

            //convert to hexadecimal
            for (int i = 0; i < data.Length; i++)
                builder.Append(String.Format("{0,2:x}", data[i]).Replace(" ", "0"));

            return builder.ToString();
        }
</pre>
<p>You now have the necessary values to build your URL for implementing SSO with Blackboard.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pearltechnology.com/blackboard-webct-ce8-sso-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Jquery with Custom Html Helpers in MVC2</title>
		<link>http://blog.pearltechnology.com/using-jquery-with-custom-html-helpers-in-mvc2/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://blog.pearltechnology.com/using-jquery-with-custom-html-helpers-in-mvc2/#comments</comments>
		<pubDate>Tue, 11 Jan 2011 15:58:28 +0000</pubDate>
		<dc:creator>Chad Ferguson</dc:creator>
				<category><![CDATA[Application Development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Html Helpers]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[MVC2]]></category>

		<guid isPermaLink="false">http://blog.pearltechnology.com/?p=896</guid>
		<description><![CDATA[While preparing for an upcoming exam I was looking into the usage of Html Helpers with MVC2 and thought it may be simple to easily add extension methods for Jquery UI controls. I have had several sites that have utilized multiple Jquery UI DatePicker controls and it would be a great time saver to simply [...]]]></description>
			<content:encoded><![CDATA[<p>While preparing for an upcoming exam I was looking into the usage of Html Helpers with MVC2 and thought it may be simple to easily add extension methods for Jquery UI controls. I have had several sites that have utilized multiple Jquery UI DatePicker controls and it would be a great time saver to simply call a method to generate the control and its script tags. </p>
<p>First we will need to create a class for the Html Helper, I usually prefer to add a folder to my solution called Helpers. Both the class and the method will need to be static. In addition you will need to add a HtmlHelper parameter to the method that is preceded by the keyword <em>this</em>. This first parameter of the extension method indicates the class that the extension method extends, which in our case would be a input control.</p>
<p><code><br />
using System;<br />
using System.Web.Mvc;</p>
<p>public static class DatePickerExtensions<br />
    {<br />
        public static string DatePicker(this HtmlHelper helper, string id)<br />
        {</p>
<p>        }<br />
    }<br />
</code></p>
<p>Next within our DatePicker Method we will want to add the input control and the Jquery, and I found this easiest way to do this was to use TagBuilders. The TagBuilder Class is a utility that easily allows you to build html tags. We will be using two TagBuilders, one for generating our input box, and a second TagBuilder for the script tag. An overview of the TagBuilder class can be found <a href="http://www.asp.net/mvc/tutorials/using-the-tagbuilder-class-to-build-html-helpers-cs">here</a>. Any script tag will need to be written with the TagBuilders InnerHtml property, or it will be interpreted as text on the page. The resulting code is below:</p>
<p><code><br />
using System;<br />
using System.Web.Mvc;</p>
<p>namespace MvcApplication1.Helpers<br />
{<br />
    public static class DatePickerExtensions<br />
    {<br />
        public static string DatePicker(this HtmlHelper helper, string id)<br />
        {<br />
            var builder = new TagBuilder("input");<br />
            builder.GenerateId(id);<br />
            builder.MergeAttribute("type", "text");</p>
<p>            var scriptBuilder = new TagBuilder("script");<br />
            scriptBuilder.InnerHtml = "$(function() { $('#" + id + "').datepicker();});";<br />
            return builder.ToString(TagRenderMode.Normal) + scriptBuilder.ToString(TagRenderMode.Normal);<br />
        }<br />
    }<br />
}<br />
</code></p>
<p>Next to be able add the control easily on any page we will need to add the Namespace for our Helpers to the web.config file as shown below.</p>
<p><code><br />
&lt;pages&gt;<br />
      &lt;namespaces&gt;<br />
        &lt;add namespace="System.Web.Mvc" /&gt;<br />
        &lt;add namespace="System.Web.Mvc.Ajax" /&gt;<br />
        &lt;add namespace="System.Web.Mvc.Html" /&gt;<br />
        &lt;add namespace="System.Web.Routing" /&gt;<br />
        <strong>&lt;add namespace="MvcApplication1.Helpers"/&gt;</strong><br />
      &lt;/namespaces&gt;<br />
    &lt;/pages&gt;<br />
</code></p>
<p>Finally we can easily add our DatePicker control anywhere to our site with our new Extension.<br />
<code><br />
Date: &lt;%= Html.DatePicker("myDatePicker") %&gt;<br />
</code></p>
<p>This short tutorial assumes that your site is already set up for using JQuery, and the UI controls. Details for using Jquery can be found <a href="http://jqueryui.com/demos/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pearltechnology.com/using-jquery-with-custom-html-helpers-in-mvc2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework 4 GUID as an Entity Key</title>
		<link>http://blog.pearltechnology.com/entity-framework-4-guid-as-an-entity-key/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://blog.pearltechnology.com/entity-framework-4-guid-as-an-entity-key/#comments</comments>
		<pubDate>Wed, 13 Oct 2010 21:39:36 +0000</pubDate>
		<dc:creator>Chad Ferguson</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[EF4]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://blog.pearltechnology.com/?p=777</guid>
		<description><![CDATA[Recently for a client we decided to utilize SQL 2008 Filestreams for handling their library of documents. A requirement with Filestreams is that SQL needs to maintain the creation of the GUID for each item. Since we were using the Entity Framework 4 (EF4) for the data model we ran into a rather common problem [...]]]></description>
			<content:encoded><![CDATA[<p>Recently for a client we decided to utilize SQL 2008 Filestreams for handling their library of documents. A requirement with Filestreams is that SQL needs to maintain the creation of the GUID for each item. Since we were using the <a href="http://msdn.microsoft.com/en-us/data/aa937723.aspx">Entity Framework 4 (EF4)</a> for the data model we ran into a rather common problem in EF4, that it does not support using a GUID’s as an entity key. A <a href="https://connect.microsoft.com/VisualStudio/feedback/details/588796/using-a-guid-as-an-entitykey-in-entity-framework-4">known workaround</a> is to manually edit the edmx as XML and add StoreGeneratedPattern=&#8221;Identity&#8221; to the affected columns.</p>
<p><img class="size-full wp-image-778" src="http://blog.pearltechnology.com/wp-content/uploads/2010/10/EF4_1.JPG" alt="EF4_1" width="457" height="63" /></p>
<p>Unfortunately this is a step that will need to be reproduced each and every time a database refresh is done. So an approach that worked for us was to create a new EF4 model at runtime, injecting the required code into it.</p>
<p>To do this first you need to create a MetadataWorkspace (System.Data.Entity), which allows you to interact with model metadata.</p>
<pre name="code" language="csharp">MetadataWorkspace workspace = new MetadataWorkspace();</pre>
<p>Next you will need to read the existing metadata from your current model and replace the text with the change we manually added before. To do this we will query the executing assembly for the Store Schema Definition Language (SSDL) file which is the file we initially had to manually edit.  <em>You can locate the names of your SSDL, MSL, and CSDL in the web.config</em>.</p>
<pre name="code" language="csharp">Assembly edmAssembly = Assembly.GetExecutingAssembly();
StreamReader metaReader = new StreamReader(edmAssembly.GetManifestResourceStream("Models.ModelName.ssdl"));
var text = metaReader.ReadToEnd();
text = text.Replace("&lt;Property Name=\"RowGUID\" Type=\"uniqueidentifier\" Nullable=\"false\" /&gt;", "&lt;Property Name=\"RowGUID\" Type=\"uniqueidentifier\" Nullable=\"false\"  StoreGeneratedPattern=\"Identity\" /&gt;");</pre>
<p>Once we have a modified SSDL we can began to build a new EF4 model. This will require the other two components, the Conceptual Schema Definition Language (CSDL) and the Mapping Specification Language (MSL).</p>
<p>The MSL, SSDL, and CSDL did Snoop Dogg Come up with these names? <img src='http://blog.pearltechnology.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>To get the MSL and CSDL we can just read them in with MemoryStreams (System.IO) like so.</p>
<pre name="code" language="csharp">var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(text));
var sReaders = new[] { XmlReader.Create(ms) };
var mReaders = new[] { XmlReader.Create(edmAssembly.GetManifestResourceStream("Models.ModelName.msl")) };

var cReaders = new[] { XmlReader.Create(edmAssembly.GetManifestResourceStream("Models.ModelName.csdl")) };</pre>
<p>Now that we have streams of the 3 necessary files we can assemble them into the model. For the SSDL we use a StoreItemCollection (System.Data.Entity) to load the xml file. For the CSDL we use the EdmItemCollection (System.Data.Entity) and then we map those to files to the MSL using the StorageMappingItemCollection (System.Data.Mapping).</p>
<pre name="code" language="csharp">var sCollection = new StoreItemCollection(sReaders);
var cCollection = new EdmItemCollection(cReaders);
var csCollection = new StorageMappingItemCollection(cCollection, sCollection, mReaders);</pre>
<p>Now that we have our new EF4 model built we simply register it in the MetadataWorkspace.</p>
<pre name="code" language="csharp">workspace.RegisterItemCollection(sCollection);
workspace.RegisterItemCollection(csCollection);
workspace.RegisterItemCollection(cCollection);</pre>
<p>Finally we declare are data model context with the new workspace and our connection string.</p>
<pre name="code" language="csharp">DBModel _db = new DBModel(new EntityConnection(workspace, (SqlConnection) connectionString));</pre>
<p>We then have access to a new EF4 model at runtime that now has a GUID that can be an entity key. To be safe we then clean up any loose ends after committing the database changes.</p>
<pre name="code" language="csharp">ms.Close();
_db.Dispose();</pre>
<div>-Chad Ferguson</div>
<p><em><br />
</em><em> </em><em></em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.pearltechnology.com/entity-framework-4-guid-as-an-entity-key/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

