<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>maonet technotes &#187; CSLA</title>
	<atom:link href="http://maonet.wordpress.com/category/csla/feed/" rel="self" type="application/rss+xml" />
	<link>http://maonet.wordpress.com</link>
	<description>IOC(SM):MOC(RM):TDD(NU):SCC(TFS):ORM(L2S):JSL(Jq):CIS(CC)</description>
	<lastBuildDate>Thu, 31 Dec 2009 17:16:53 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='maonet.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/27569a47b055d3d0ff1d52cf3b0ce0d7?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>maonet technotes &#187; CSLA</title>
		<link>http://maonet.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://maonet.wordpress.com/osd.xml" title="maonet technotes" />
		<item>
		<title>IRepository</title>
		<link>http://maonet.wordpress.com/2009/02/11/irepository/</link>
		<comments>http://maonet.wordpress.com/2009/02/11/irepository/#comments</comments>
		<pubDate>Wed, 11 Feb 2009 19:07:44 +0000</pubDate>
		<dc:creator>Frank Mao</dc:creator>
				<category><![CDATA[CSLA]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Repository]]></category>

		<guid isPermaLink="false">http://maonet.wordpress.com/?p=464</guid>
		<description><![CDATA[I was trying to write a similar post as Mike did. Because I&#8217;m currently using LINQ DynamicQuery, so my IRepository looks like this:


    public interface IDynamicQueryable&#60;T&#62;
    {
        IEnumerable&#60;T&#62; FindAllByCriteria(string criteria);
        IEnumerable&#60;T&#62; FindAllByCriteria(Func&#60;T, bool&#62; criteria);
    }

    // Most simple repository implement this one.
    public interface IRepository&#60;T&#62; 
    {       
         [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=464&subd=maonet&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I was trying to write a <a href="http://mikehadlow.blogspot.com/2009/01/in-search-of-wild-repository.html">similar post as Mike did</a>. Because I&#8217;m currently using <a href="http://msdn2.microsoft.com/en-us/bb330936.aspx">LINQ DynamicQuery</a>, so my IRepository looks like this:</p>
<pre class="brush: csharp;">

    public interface IDynamicQueryable&lt;T&gt;
    {
        IEnumerable&lt;T&gt; FindAllByCriteria(string criteria);
        IEnumerable&lt;T&gt; FindAllByCriteria(Func&lt;T, bool&gt; criteria);
    }

    // Most simple repository implement this one.
    public interface IRepository&lt;T&gt; 
    {       
              T FindById(int id);
              T Insert(T data);
              T Update(T newData, T oldData);
              void Delete(T data);
     }

    // Some fancy entities implement this one instead.
    public interface IDynamicQueryableRepository&lt;T&gt; : IDynamicQueryable&lt;T&gt;, IRepository&lt;T&gt;{}
</pre>
<p>I spilt the dynamic part from IRepository, just trying not annoy developer create too many never used FindAll() method in their entities. And also I think this is closer to Interface segregation Principle (not really sure). But this indeed gave me flexibility to control the function diversity on different entities, e.g., some entities might never need list-editing/retrieval function.</p>
<p>I do like this LinqDynamicQuery very much and don&#8217;t mind to make my repository coupled to Func&lt;T, bool&gt; (what&#8217;s this indeed? And what&#8217; the difference than Expression&lt;Func&lt;T, bool&gt;&gt; shown in Fluent NHibernate&#8217;s IRepository?)  Here is a good example, if no DynamicQuery:</p>
<pre class="brush: csharp;">

    public interface ICityRepository : IDynamicQueryableRepository&lt;CityBO&gt;
    {
        IEnumerable&lt;CityBO&gt; FindAllByProvinceId(int provinceId);
        IEnumerable&lt;CityBO&gt; FindAllByCountryId(int countryId);
    }
</pre>
<p>By using DynamicQuery,</p>
<pre class="brush: csharp;">

    public class CityListFactory : BusinessListBaseServerFactory&lt;CityBOCollection, CityBO, ICityRepository&gt;, ICityListFactory
    {
        public CityBOCollection Fetch(CountryBO parent)
        {
            // Don't need FindAllByCountryId() any more.
            return Fetch(x =&gt; x.CountryId == parent.CountryId);
        }
        public CityBOCollection Fetch(ProvinceBO parent)
        {
            return Fetch(x =&gt; x.ProvinceId == parent.ProvinceId);
        }
    }
</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maonet.wordpress.com/464/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maonet.wordpress.com/464/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maonet.wordpress.com/464/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maonet.wordpress.com/464/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maonet.wordpress.com/464/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maonet.wordpress.com/464/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maonet.wordpress.com/464/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maonet.wordpress.com/464/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maonet.wordpress.com/464/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maonet.wordpress.com/464/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=464&subd=maonet&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maonet.wordpress.com/2009/02/11/irepository/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d41c3a25ca01f1e979e2bc86b8c4ed38?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">FMao</media:title>
		</media:content>
	</item>
		<item>
		<title>Extract Validation rules out from CSLA BO</title>
		<link>http://maonet.wordpress.com/2009/02/06/extract-validation-rules-out-from-csla-bo/</link>
		<comments>http://maonet.wordpress.com/2009/02/06/extract-validation-rules-out-from-csla-bo/#comments</comments>
		<pubDate>Fri, 06 Feb 2009 21:57:46 +0000</pubDate>
		<dc:creator>Frank Mao</dc:creator>
				<category><![CDATA[CSLA]]></category>

		<guid isPermaLink="false">http://maonet.wordpress.com/?p=455</guid>
		<description><![CDATA[The first priciple of SOLID rules is SRP, it would be nice if we can extract validataion rules out from BO. And I couldn&#8217;t belive it was so easy to do implement.
The classic way:

private void AddCustomRules()
        {
            // Custom validation
            ValidationRules.AddRule&#60;EmailBO&#62;(EmailRoleValidValues&#60;EmailBO&#62;, EmailRoleProperty, 1);

        }

The revised version:

// EmailBO
   protected override void AddBusinessRules()
   [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=455&subd=maonet&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>The first priciple of SOLID rules is SRP, it would be nice if we can extract validataion rules out from BO. And I couldn&#8217;t belive it was so easy to do implement.</p>
<p>The classic way:</p>
<pre class="brush: csharp;">
private void AddCustomRules()
        {
            // Custom validation
            ValidationRules.AddRule&lt;EmailBO&gt;(EmailRoleValidValues&lt;EmailBO&gt;, EmailRoleProperty, 1);

        }
</pre>
<p>The revised version:</p>
<pre class="brush: csharp;">
// EmailBO
   protected override void AddBusinessRules()
   {
      EmailRuleFactory.CreateOn(ValidationRules);
   }

public class EmailRuleFactory
{
   public static void CreateOn(ValidationRules rules)
   {
      rules.AddRule&lt;EmailBO&gt;(EmailRoleValidValues&lt;EmailBO&gt;, &quot;EmailRole&quot;, 1);
   }

   private static bool EmailRoleValidValues&lt;T&gt;(T target, Csla.Validation.RuleArgs e) where T : EmailBO
   {...}
 </pre>
<p>All the validation tests still passed!</p>
<p>Note: I had to expose protect <em>Parent</em> field from BusinessBase. And PropertyInfo is not available either, fortunately ValidationRules.AddRule() can still take string literal.</p>
<p>This might also be helpful is user wants to switch between different sets of valudation rule based on certain instance value.</p>
<p>We could do the same thing to AuthorizationRules which will be more meaningful. Security should definitely be built as a separated common service, instead of building into Domain Object.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maonet.wordpress.com/455/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maonet.wordpress.com/455/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maonet.wordpress.com/455/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maonet.wordpress.com/455/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maonet.wordpress.com/455/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maonet.wordpress.com/455/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maonet.wordpress.com/455/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maonet.wordpress.com/455/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maonet.wordpress.com/455/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maonet.wordpress.com/455/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=455&subd=maonet&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maonet.wordpress.com/2009/02/06/extract-validation-rules-out-from-csla-bo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d41c3a25ca01f1e979e2bc86b8c4ed38?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">FMao</media:title>
		</media:content>
	</item>
		<item>
		<title>Enable DataGrid Header-Clicking Sorting</title>
		<link>http://maonet.wordpress.com/2009/01/30/enable-datagrid-header-clicking-sorting/</link>
		<comments>http://maonet.wordpress.com/2009/01/30/enable-datagrid-header-clicking-sorting/#comments</comments>
		<pubDate>Fri, 30 Jan 2009 18:15:27 +0000</pubDate>
		<dc:creator>Frank Mao</dc:creator>
				<category><![CDATA[CSLA]]></category>
		<category><![CDATA[WinForm]]></category>

		<guid isPermaLink="false">http://maonet.wordpress.com/?p=438</guid>
		<description><![CDATA[Most search results  said the header-clicking-sorting feature comes internally with dotNet Framework. But for some reason I just could make this happen, until I read an old article on MSDN about custom data binding, which kept mentioning about Rocky. And the reason is very simple, programmer should bind a SortableBindingList&#60;T&#62; to dataGrid to make use [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=438&subd=maonet&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Most search results  said the header-clicking-sorting feature comes internally with dotNet Framework. But for some reason I just could make this happen, until I read an old article on MSDN about <a href="http://msdn.microsoft.com/en-us/library/ms993124.aspx">custom data binding</a>, which kept mentioning about Rocky. And the reason is very simple, programmer should bind a <strong>SortableBindingList&lt;T&gt; </strong>to dataGrid to make use of those internal sorting features.</p>
<p>Csla.EditableRootList has to be wrapped in Csla.SortedBindingList then to bind to dataGrid.</p>
<p>SortedBindingList has most of the functions embeded including: Add, Insert, Delete, but not Save. I need to convert SortedBingList back to EditableRootList by using it&#8217;s internal property: SourceList.</p>
<p>Rocky didn&#8217;t make SortedBindingList serializable <a href="http://forums.lhotka.net/forums/post/907.aspx">for some reason</a>. Anyway, the UI code is very simple:</p>
<pre class="brush: csharp;">

        public CountryBOCollection List
        {
            get
            {
                return (CountryBOCollection)
                  ((SortedBindingList)this.countryBOCollectionBindingSource.DataSource)
                      .SourceList;
            }
            set
            {
                this.countryBOCollectionBindingSource.DataSource
                    = new Csla.SortedBindingList(value);
            }
        }
</pre>
<p>I tried to move this type conversion to presenter, then I realized I need two lists in presenter: one sortable list for displaying and editing, one savable list just for saving. Presenter code is polluted just by this limitation in SortedBindingList. It looks much better by leaving type conversion still in UI, and who knows someday this limitation might go away?</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maonet.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maonet.wordpress.com/438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maonet.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maonet.wordpress.com/438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maonet.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maonet.wordpress.com/438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maonet.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maonet.wordpress.com/438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maonet.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maonet.wordpress.com/438/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=438&subd=maonet&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maonet.wordpress.com/2009/01/30/enable-datagrid-header-clicking-sorting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d41c3a25ca01f1e979e2bc86b8c4ed38?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">FMao</media:title>
		</media:content>
	</item>
		<item>
		<title>Csla.ObjectFactory III &#8211; What&#8217;s wrong with UpdateChildren()</title>
		<link>http://maonet.wordpress.com/2008/12/19/cslaobjectfactory-iii-whats-wrong-with-updatechildren/</link>
		<comments>http://maonet.wordpress.com/2008/12/19/cslaobjectfactory-iii-whats-wrong-with-updatechildren/#comments</comments>
		<pubDate>Sat, 20 Dec 2008 00:53:42 +0000</pubDate>
		<dc:creator>Frank Mao</dc:creator>
				<category><![CDATA[CSLA]]></category>
		<category><![CDATA[DDD]]></category>

		<guid isPermaLink="false">http://maonet.wordpress.com/?p=427</guid>
		<description><![CDATA[Derick Bailey&#8217;s post about Csla vs DDD brought out a simple but very interesting question :
Which one is correct?
Person.AddCertificate(), or Person.Certificates.Add()?
Almost the same? But it turns out the 2nd one is NOT &#8220;correct&#8221;, at least, not in DDD way.
That&#8217;s the problem in CSLA. Always thinking in table, data-centric design/dev. An extreme example, FieldManager.UpdateChildren().
How about save? [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=427&subd=maonet&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a href="http://www.avocadosoftware.com/csblogs/dredge/archive/2007/02/19/687.aspx">Derick Bailey&#8217;s post about Csla vs DDD</a> brought out a simple but very interesting question :</p>
<blockquote><p>Which one is correct?<br />
Person.AddCertificate(), or Person.Certificates.Add()?</p></blockquote>
<p>Almost the same? But it turns out the 2nd one is <strong><span style="color:#ff0000;">NOT</span></strong> &#8220;correct&#8221;, at least, not in DDD way.</p>
<p>That&#8217;s the problem in CSLA. Always thinking in table, data-centric design/dev. An extreme example, FieldManager.UpdateChildren().</p>
<p>How about save? Person.UpdateEmail() or Person.Email.Update(). [Email.Child_Update() in classic CSLA way.]</p>
<p>CSLA is not an ORM tool/framework, but BO carries all the dirty flags, in fact it&#8217;s DataPortal doing all the relationship maintenance work. RootBO.Save() is handling all the updates of its children, through FieldManager.UpdateChildren() jumping into each childBO&#8217;s internal private Child_XYZ methods. Handy, &#8220;clean&#8221;, but it&#8217;s not &#8220;correct&#8221;.This is the exactly same problem when I was trying to switch to the new Csla.ObjectFactory way: I had to keep an extra set of Protal methods in child BO, those child portal method,  to work with Parent BO&#8217;s FieldManager.UpdateChildren() method.</p>
<p>What if we ignore FieldManager completely? Just let Person.Save() directly call DataPortal.Update&lt;EmailBO&gt;(person.Email) ? Or DataPortal.Update&lt;TelephoneBOCollection&gt;(person.Telephones) ? Then child BO can still use  the general AbstractFactory which only have root level CRUD methods.</p>
<p>The direction Rocky made in ObjectFactory looks right, child CRUD should be done by root BO.  The thing is, it&#8217;s not backwards completable. It&#8217;s trying to retire FieldManager.UpdateChildren()!</p>
<p>The update route should be RootBO.Save -&gt; Root Factory.Update -&gt; Child Factory.Update, don&#8217;t call child BO&#8217;s internal Child_XYZ anymore.</p>
<p>Currently for legacy reason I still keep the following code in my ChildBO to bump calls from parent to child&#8217;s own factory, those UpdateChildren() in root BO can be alive for awhile, until I move them to root factory, which should be the newly strongly-typed customized UpdateChildren().</p>
<pre class="brush: csharp;">

private void Child_DeleteSelf(){ DataPortal.Delete(this);}

private void Child_Insert(IParent parent){
     this.ParentId = parent.Id;
     DataPortal.Update(this);
}

private void Child_Update(){
     var newBO = DataPortal.Update(this);
     DataMapper.Map(newBO, this);
}
</pre>
<p>It might just looks like a wrapper trick, but those DataPortal calls are actually in Factory class now which indeed is in an external true service layer.</p>
<p>In my app, it&#8217;s one AbstractFactory for all BOs, both root and child.</p>
<p>I do have a problem now, where should I put transaction scope attribute? It shouldn&#8217;t be a big deal, possible solutions:</p>
<ol>
<li> Create some extra methods in factory not in transaction Scope dedicated for child methods,</li>
<li>Unit of Work pattern?</li>
</ol>
<p>Look back Ryan&#8217;s ProjectTrackerHybrid code, all the child propertis are not registered! Which means they are not in fieldmanager at all. It&#8217;s ORM&#8217;s job to handle the realationship UpSet (Update/Insert).</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maonet.wordpress.com/427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maonet.wordpress.com/427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maonet.wordpress.com/427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maonet.wordpress.com/427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maonet.wordpress.com/427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maonet.wordpress.com/427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maonet.wordpress.com/427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maonet.wordpress.com/427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maonet.wordpress.com/427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maonet.wordpress.com/427/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=427&subd=maonet&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maonet.wordpress.com/2008/12/19/cslaobjectfactory-iii-whats-wrong-with-updatechildren/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d41c3a25ca01f1e979e2bc86b8c4ed38?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">FMao</media:title>
		</media:content>
	</item>
		<item>
		<title>Csla.ObjectFactory Part II &#8211; Difficulties on Child BO</title>
		<link>http://maonet.wordpress.com/2008/12/15/cslaobjectfactory-part-ii-difficulties-on-child-bo/</link>
		<comments>http://maonet.wordpress.com/2008/12/15/cslaobjectfactory-part-ii-difficulties-on-child-bo/#comments</comments>
		<pubDate>Mon, 15 Dec 2008 19:19:16 +0000</pubDate>
		<dc:creator>Frank Mao</dc:creator>
				<category><![CDATA[CSLA]]></category>

		<guid isPermaLink="false">http://maonet.wordpress.com/?p=419</guid>
		<description><![CDATA[I was wondering  why CslaFactory only needs to implement CRUD, no child methods at all. Other developers post the  same question on forum.
Rocky&#8217;s answer made sense, it your own Facotory&#8217;s responsibility to handle all those relationship. My specific problem on this is, FiledManager.UpdateChildren() is not available any more.
First, the FieldManager property in BO is protected, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=419&subd=maonet&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I was wondering  why CslaFactory only needs to implement CRUD, no child methods at all. Other developers post the  <a href="http://forums.lhotka.net/forums/thread/29029.aspx">same question</a> on forum.</p>
<p>Rocky&#8217;s answer made sense, it your own Facotory&#8217;s responsibility to handle all those relationship. My specific problem on this is, FiledManager.UpdateChildren() is not available any more.</p>
<p>First, the FieldManager property in BO is protected, this can be fixed by adding new method in our BaseBO to make it public. The root BO changed to CslaFactory then. But, next challenge is, this UpdateChild is not going through DataPortalSelector-&gt;DataPortal_XYZ route, it still uses Reflection to look up the &#8216;Child_XYZ&#8221; method right in your child BO, not in CslaFactory class at all!</p>
<p>You have to manage your own update route by looping through all the children from your root BO! Forget the powerful FieldManager.UpdateChildren().</p>
<p>Relationship is built in DAL. ?? When start using DTO, I know it is the dead weakness. The word around is pulling relationship up to Csla BO and rely on those magic UpdateChildren methods. Now, updateChildren is gone, I have to create a real business explicit UpdateChildren.</p>
<pre class="brush: csharp;">

    public class AbstractObjectFactory&lt;BO, TRepository, DTO&gt; : ObjectFactory, IBusinessBaseServerFactory&lt;BO&gt;
        where BO : MyBusinessBase&lt;BO&gt;
        where TRepository : IRepository&lt;DTO&gt;
        where DTO : class, new()
    {
        protected IRepository&lt;DTO&gt; _repository = StructureMap.ObjectFactory.GetInstance&lt;TRepository&gt;();

        public virtual BO NewBO()
        {
            return (BO)Activator.CreateInstance(typeof(BO), true);
            //            return new BO();
        }

        public virtual void InsertChildren(BO bo){}
        public virtual void UpdateChildren(BO bo){}
        public virtual void DeleteChildren(BO bo){}

        public virtual BO Create()
        {
            var obj = NewBO();
            MarkNew(obj);
            obj.GetValidationRules().CheckRules();
            return obj;
        }

        public virtual BO Insert(BO bo)
        {
            var data = _repository.Insert(bo.BuildDTO&lt;DTO&gt;());
            if (data == null) throw new DataException(&quot;Repository Insert return null.&quot;);
            bo.LoadFromDTO&lt;DTO&gt;(data);

            InsertChildren(bo);
            // FieldManagar().UpdateChildren(bo) is not through CslaFactory.
//            bo.GetFieldManagar().UpdateChildren(bo);

            return bo;
        }

...

    public class StakeholderFactory : AbstractObjectFactory&lt;StakeholderBO, IStakeholderRepository, StakeholderDTO&gt;
        , IStakeholderFactory
    {
        public override void InsertChildren(StakeholderBO bo)
        {
            // Update Alias Name Child
            var factory = new StakeholderAliasNameFactory();
            for (int i = 0; i &lt; bo.AliasNames.Count; i++)
            {
                bo.AliasNames[i] = factory.Insert(bo.AliasNames[i]);
            }
        }
</pre>
<p>This looks weird. And my solution of <a href="http://maonet.wordpress.com/2008/11/21/seperate-concern-between-parent-and-child/">mocking Parent for testing update Child</a> is useless then, because that assume root BO is calling FiledManager.UpdateChildren. One solution is to  re-write those update children code into my CslaFactory class. More coding, does it look more clear? I&#8217;m not sure. One of my root BO has 7+ children, I don&#8217;t think it&#8217;s worth to move.</p>
<p>Another quick dirty fix might be, still leave those Child_XYZ methods in Child BO for legacy purpose, inside put DataPortal_XYZ to redirect call to CslaFactory. This solution can keep parent update code same as before, still using UpdateChildren(), also the Child BO will look more like a switchable BO.</p>
<p>Enough, now I fully understand Ryan&#8217;s statement: Csla is great, but we need relationship.</p>
<p>Look how Ruby and NH dealing with relationship: has_many, belongs_to. Simple and clear.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maonet.wordpress.com/419/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maonet.wordpress.com/419/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maonet.wordpress.com/419/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maonet.wordpress.com/419/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maonet.wordpress.com/419/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maonet.wordpress.com/419/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maonet.wordpress.com/419/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maonet.wordpress.com/419/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maonet.wordpress.com/419/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maonet.wordpress.com/419/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=419&subd=maonet&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maonet.wordpress.com/2008/12/15/cslaobjectfactory-part-ii-difficulties-on-child-bo/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d41c3a25ca01f1e979e2bc86b8c4ed38?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">FMao</media:title>
		</media:content>
	</item>
		<item>
		<title>Csla.ObjectFactory</title>
		<link>http://maonet.wordpress.com/2008/12/10/cslaobjectfactory/</link>
		<comments>http://maonet.wordpress.com/2008/12/10/cslaobjectfactory/#comments</comments>
		<pubDate>Wed, 10 Dec 2008 18:57:32 +0000</pubDate>
		<dc:creator>Frank Mao</dc:creator>
				<category><![CDATA[CSLA]]></category>

		<guid isPermaLink="false">http://maonet.wordpress.com/?p=383</guid>
		<description><![CDATA[This is  a new feature from Csla 3.6, which is trying to make Csla more TDD friendly.
Benefits:
DataPortal_XYZ methods can be moved into your own ObjectFactory class, BO will look a little bit thinner. Yes, you can now make BO contructor to be public, ( in standard csla way BO&#8217;s ctor should be private), if you [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=383&subd=maonet&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This is <a href="http://www.lhotka.net/weblog/CSLANETObjectFactoryAttribute.aspx"> a new feature from Csla 3.6</a>, which is trying to make Csla more TDD friendly.</p>
<p>Benefits:</p>
<p>DataPortal_XYZ methods can be moved into your own ObjectFactory class, BO will look a little bit thinner. Yes, you can now make BO contructor to be public, ( in standard csla way BO&#8217;s ctor should be private), if you are tired of using Activator.CreateInstance.</p>
<p>Because now you have full control to this ObjectFactory, and this class is not static, you can mock it when unit-testing UI/Presenter. But, the default usage of ObjectFactory doesn&#8217;t support Interface. Fortunately,  Rocky allow you to create your own FactoryLoader, by setting it into your app.conifg to redirect:</p>
<blockquote><p>&lt;appSettings&gt;<br />
&lt;add key=&#8221;CslaObjectFactoryLoader&#8221; value=&#8221;YourNameSpace.YourFactoryLoader, YourAssembly&#8221; /&gt;</p></blockquote>
<p>Ryan Kelley is using this tech to create his GenericFactoryLoader in his ProjectTrackerHybrid demo.</p>
<p>We have lots of Stored Procedures to deal with, so create a base AbstactObjectFactory is very hard. So I changed Ryan&#8217;s GenericFactoryLoader to make it not taking generic interface.</p>
<p>Here is what I tried:</p>
<pre class="brush: csharp;">

        public virtual Type GetFactoryType(string factoryConnectionString)
        {
            if (factoryConnectionString == null)
                throw new ArgumentNullException(&quot;factoryConnectionString&quot;);

            parser.Parse(factoryConnectionString);

            var factoryTypeName = parser.FactoryType;

            // parser doesn't work , use csla default ObjectFactoryLoader
            if (string.IsNullOrEmpty(factoryTypeName))
                return new ObjectFactoryLoader().GetFactoryType(factoryConnectionString);

            return Type.GetType(factoryTypeName);
        }

        public virtual object GetFactory(string factoryName)
        {
            var factoryType = GetFactoryType(factoryName);
            if (factoryType.IsInterface)
                return StructureMap.ObjectFactory.GetInstance(factoryType);

            return new ObjectFactoryLoader().GetFactory(factoryName);

        }

[CslaFactory(&quot;Factory Type=MyFactory.ICityFactory&quot;)]
// Classic way to declare ObjectFactory
//    [CslaFactory(&quot;MyFactory.CityFactory, MyFactory&quot;)]
[Serializable()]
public class CityBO :BusinessBase&lt;CityBO&gt;
{...}
</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maonet.wordpress.com/383/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maonet.wordpress.com/383/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maonet.wordpress.com/383/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maonet.wordpress.com/383/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maonet.wordpress.com/383/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maonet.wordpress.com/383/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maonet.wordpress.com/383/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maonet.wordpress.com/383/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maonet.wordpress.com/383/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maonet.wordpress.com/383/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=383&subd=maonet&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maonet.wordpress.com/2008/12/10/cslaobjectfactory/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d41c3a25ca01f1e979e2bc86b8c4ed38?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">FMao</media:title>
		</media:content>
	</item>
		<item>
		<title>Should always ignoreArgument when AssertWasCalled</title>
		<link>http://maonet.wordpress.com/2008/11/28/should-always-ignoreargument-when-assertwascalled/</link>
		<comments>http://maonet.wordpress.com/2008/11/28/should-always-ignoreargument-when-assertwascalled/#comments</comments>
		<pubDate>Fri, 28 Nov 2008 21:30:53 +0000</pubDate>
		<dc:creator>Frank Mao</dc:creator>
				<category><![CDATA[CSLA]]></category>
		<category><![CDATA[MVP]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[test]]></category>
		<category><![CDATA[Rhino]]></category>

		<guid isPermaLink="false">http://maonet.wordpress.com/?p=326</guid>
		<description><![CDATA[I should have added this option in my test earlier, then I won&#8217;t waste 2+ hours today. The reason causing problem was very simple, AssertWasCalled() method in current verion RhinoMocks (3.5.0.1337 RC) doesn&#8217;t action consistently. I think it&#8217;s because comparing the object reference equalty. I had to add options=&#62;options.IgnoreArguments() to get around from this.
Here is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=326&subd=maonet&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I should have added this option in my test earlier, then I won&#8217;t waste 2+ hours today. The reason causing problem was very simple, AssertWasCalled() method in current verion RhinoMocks (3.5.0.1337 RC) doesn&#8217;t action consistently. I think it&#8217;s because comparing the object reference equalty. I had to add options=&gt;options.IgnoreArguments() to get around from this.</p>
<p>Here is a piece of my MVP + CLSA test. Struggled for a while with Property setter, thanks God, it isn&#8217;t that hard.</p>
<pre class="brush: csharp;">

    [TestFixture]
    public class When_initializing_view : EstablishContext
    {
        [Test]
        public void should_call_view_setter_if_id_exists()
        {
            // Arrange
            _mockOrganizationRepository.Expect(x =&gt; x.FindById(1)).Return(_stubOrganizationDTO);

            _mockView = MockRepository.GenerateMock&lt;IEditDetailsView&lt;OrganizationBO&gt;&gt;();

            _presenter = new EditDetailsPresenter&lt;OrganizationBO&gt;(_mockView);

            // Action
            _presenter.InitViewFor(1);

            // Assert
            _mockView.AssertWasCalled(x =&gt; x.CurrentBO = null,
                options =&gt;options.IgnoreArguments() );
        }
    }
</pre>
<p>I then created a generic EditDetailsPresenter, worked as I expected with one concern left: How to mock DataPortal directly. Currently I am still mocking repository. Ideally I should mock DataPortal instead, otherwise I have to make sure there is at least one BO is fully functional.</p>
<p>Mocking DataPortal is very hard, because those Fecth, Create, Update and Delete are all static methods, I had to create an adapter to wrap those static methods, then using StructreMap again inside adapter enable switching between DataPortal and mock DomainDAO, here is what I have tried:</p>
<ol>
<li>Create DomainDAO and IDomainDAO,
<pre class="brush: csharp;">
public class DomainDAO&lt;BO&gt; : IDomainDAO&lt;BO&gt;
{
public BO Fetch(object criteria)
{
return DataPortal.Fetch&lt;BO&gt;(criteria);
}

public BO Create()
{
return DataPortal.Create&lt;BO&gt;();
}

public BO Update(BO bo)
{
return DataPortal.Update&lt;BO&gt;(bo);
}

public void Delete(object criteria)
{
DataPortal.Delete&lt;BO&gt;(criteria);
}
}

public interface IDomainDAO&lt;T&gt;
{
T Fetch(object criteria);
T Create();
T Update(T bo);
void Delete(object criteria);
}
</pre>
</li>
<li>Create DAOManager to Get DomainDAO:
<pre class="brush: csharp;">
public static class DAOManager
{
public static IDomainDAO&lt;BO&gt; DomainDAO&lt;BO&gt;()
{
return ObjectFactory.GetInstance&lt;IDomainDAO&lt;BO&gt;&gt;();
}
}
</pre>
</li>
<li>Change classic factory method in BO from DataPortal to this new DAOManager.
<pre class="brush: csharp;">
public static OrganizationBO GetOrganizationBO(int stakeholderId)
{
return DAOManager.DomainDAO&lt;OrganizationBO&gt;().Fetch(new SingleCriteria&lt;OrganizationBO, int&gt;(stakeholderId));
//            return DataPortal.Fetch&lt;OrganizationBO&gt;(new SingleCriteria&lt;OrganizationBO, int&gt;(stakeholderId));
}
</pre>
</li>
<li>The presenter testing code can be changed to:
<pre class="brush: csharp;">

[SetUp]
public void SetUp()
{
_mockService = MockRepository.GenerateMock&lt;IDomainDAO&lt;OrganizationBO&gt;&gt;();
ObjectFactory.Inject&lt;IDomainDAO&lt;OrganizationBO&gt;&gt;(_mockService);
}

[TearDown]
public void TearDown()
{
ObjectFactory.ResetDefaults();
}

[TestFixture]
public class When_initializing_view : EstablishContext
{
        [Test]
        public void should_call_view_setter_if_id_exists()
        {
            // Arrange
            // We don't need to set return value here.
            _mockService.Expect(x =&gt; x.Fetch(new SingleCriteria&lt;OrganizationBO, int&gt;(68190)));

            _mockView = MockRepository.GenerateMock&lt;IEditDetailsView&lt;OrganizationBO&gt;&gt;();

            _presenter = new EditDetailsPresenter&lt;OrganizationBO&gt;(_mockView);

            // Action
            _presenter.InitViewFor(68190);

            // Assert
            _mockView.AssertWasCalled(x =&gt; x.CurrentBO = null,
                options =&gt; options.IgnoreArguments() );
        }

        [Test]
        public void should_set_error_msg_in_view_if_id_not_exists()
        {
            // Arrange
            Exception ex = new Exception(&quot;Data Not Found&quot;, new DataNotFoundException());
            _mockService.Expect(x =&gt; x.Fetch(new SingleCriteria&lt;OrganizationBO, int&gt;(1)))
                .IgnoreArguments()
                .Throw(new DataPortalException(&quot;DataPortal.Fetch failed.&quot;,
                    ex,
                    null)); // See, we don't have to mock BO here, unless you try to read BO through exception in UI.

            _mockView = MockRepository.GenerateMock&lt;IEditDetailsView&lt;OrganizationBO&gt;&gt;();

            _presenter = new EditDetailsPresenter&lt;OrganizationBO&gt;(_mockView);

            // Action
            _presenter.InitViewFor(1);

            // Assert
            _mockView.AssertWasCalled(x =&gt; x.ShowError(null),
                options =&gt; options.IgnoreArguments() );
        }
</pre>
</li>
</ol>
<p>Fetch can be done this way, but I can&#8217;t mock Save() because it&#8217;s deep in Csla, unless I can override BusinessBase.Save() which is another mission impossible (too many internal classes involved). To make Csla TDD friendly, let ask for TypeMock to save us out.</p>
<pre class="brush: csharp;">
 [TestFixture]
    public class When_view_firing_save_event : EstablishContext
    {
        [Test]
        public void should_set_success_msg_and_set_new_BO_in_view_if_save_new_bo_succeed()
        {
            // Arrange
            OrganizationBO orgBo = DataPortal.Create&lt;OrganizationBO&gt;();
            orgBo.Name = &quot;test Org&quot;;
            Assert.That(orgBo.IsValid, orgBo.GetValidationMessage());

            _mockView = MockRepository.GenerateMock&lt;IEditDetailsView&lt;OrganizationBO&gt;&gt;();
            _mockView.Stub(x =&gt; x.CurrentBO).Return(orgBo).Repeat.Any();

            _presenter = new EditDetailsPresenter&lt;OrganizationBO&gt;(_mockView);

            // This won't work, because BusinessBase.Save() is tightly coupled to DataPortal.
            //_mockService.Expect(x =&gt; x.Update(orgBo)).IgnoreArguments();

            // Use TypeMock to mock DataPortal.Update() inside BusinessBase.Save()
            using (RecordExpectations recorder = RecorderManager.StartRecording())
            {
                  // CAUTION: ALL calls here are mocked!!!
                  recorder.DefaultBehavior.IgnoreArguments();
                  recorder.ExpectAndReturn(DataPortal.Update(orgBo), orgBo);
            }

            // Action
            _mockView.Raise(x =&gt; x.RequestSave += null, this, EventArgs.Empty);

            // Assert
            _mockView.AssertWasCalled(x =&gt; x.CurrentBO = null,
                                      options =&gt; options.IgnoreArguments());

            _mockView.AssertWasCalled(x =&gt; x.ShowMessage(null),
                                      options =&gt; options.IgnoreArguments());

    }
</pre>
<p>We can remove DomainDAO then if using TypeMock to mock DataPortal.</p>
<p>The <a href="http://www.lhotka.net/weblog/CSLANETObjectFactoryAttribute.aspx">new ObjectFactory in CSLA 3.6</a> seems can make this mock easier, looks like your own ObjectFactory is not static class anymore, different than DataPortal. By creating your own IDataPortal or IObjectFactory, <a href="http://code.google.com/p/cslaptrackerfactory/source/browse/trunk/ProjectTrackerHybrid.Core/Framework/Factories/IBusinessBaseServerFactory.cs">as Ryan did</a>,  mocking those service layer objects should become possible. Someday I will look into this CSLA.ObjectFactory thing if we aren&#8217;t going to TypeMock. Rocky&#8217;s statement indicates this will be a lot of work:</p>
<blockquote><p>It is <em>very important</em> to realize that when using this factory model, the data portal does virtually nothing for you. It doesn&#8217;t automatically call MarkOld(), MarkNew() or MarkAsChild(). You assume <em>total responsibility</em> for creating and initializing the business object graph, and for setting the state of all objects in the graph.</p></blockquote>
<p>But it seems <a href="http://cslaptrackerfactory.googlecode.com/">Ryan&#8217;s ObjectFactroy sample code</a> already finished most of them. One thing doesn&#8217;t fit our situation is, we need IRepository&lt;&gt; changed to IDomainObjectRepository in Factory.</p>
<pre class="brush: csharp;">

        private readonly IRepository&lt;T&gt; _repository;
        public BusinessBaseServerFactory(IRepository&lt;T&gt; repository)
        {
            _repository = repository;
        }
</pre>
<p>So far, I think unless CSLA.ObjectFactory can provide an optional attribute something like &#8220;RepositoryType&#8221;, I have to create One ObjectFacotry per BO. Our libaray will become more messier.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maonet.wordpress.com/326/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maonet.wordpress.com/326/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maonet.wordpress.com/326/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maonet.wordpress.com/326/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maonet.wordpress.com/326/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maonet.wordpress.com/326/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maonet.wordpress.com/326/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maonet.wordpress.com/326/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maonet.wordpress.com/326/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maonet.wordpress.com/326/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=326&subd=maonet&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maonet.wordpress.com/2008/11/28/should-always-ignoreargument-when-assertwascalled/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d41c3a25ca01f1e979e2bc86b8c4ed38?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">FMao</media:title>
		</media:content>
	</item>
		<item>
		<title>Seperate concern between parent and child</title>
		<link>http://maonet.wordpress.com/2008/11/21/seperate-concern-between-parent-and-child/</link>
		<comments>http://maonet.wordpress.com/2008/11/21/seperate-concern-between-parent-and-child/#comments</comments>
		<pubDate>Sat, 22 Nov 2008 06:39:09 +0000</pubDate>
		<dc:creator>Frank Mao</dc:creator>
				<category><![CDATA[CSLA]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://maonet.wordpress.com/?p=315</guid>
		<description><![CDATA[Do we need to separate concern between parent object and its child? Say we have a stakeholder BO, which can have multiple email BOs, (an email BO collection). Then where should we place those specs/unit-tests for email BO?
Because emailBO is a child BO, the normal way to save it should be only through stakeholderBO.Save(). It&#8217;s [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=315&subd=maonet&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Do we need to separate concern between parent object and its child? Say we have a stakeholder BO, which can have multiple email BOs, (an email BO collection). Then where should we place those specs/unit-tests for email BO?</p>
<p>Because emailBO is a child BO, the normal way to save it should be only through stakeholderBO.Save(). It&#8217;s possible that stakeholderBO might still be work-in-progress, or having problem caused by other childBO, e.g., telephoneBO. Or more likely, it&#8217;s not finish yet. Can we still work on EmailBO without worry too much about it&#8217;s parent &#8211; StakeholderBO?</p>
<p>So seperate concern is necessary. We need an interface to implement design-by-contract.</p>
<p>Create an IStakeholder interface, mock it in emailBO unit-test. (Thanks to Rhino, we don&#8217;t need worry about data portal any more. ) But we need to explicitly call SetParent() in emailBOCollection to simulate the LoadProperty behavior in stakeholderBO.</p>
<p>The test code:</p>
<pre class="brush: csharp;">

            // Arrange
            var emailRepository = MockRepository.GenerateMock&lt;IEmailRepository&gt;();
            ObjectFactory.Inject&lt;IEmailRepository&gt;(emailRepository);

            EmailDTO OneValidTestDTO = new EmailDTO()
                                           {
                                               Address = &quot;2@d.c&quot;, EmailRole = &quot;Home&quot;,
                                               StakeholderId = 123, StakeholderEmailId = 456
                                           };

            emailRepository.Expect(x =&gt; x.Insert(null)).IgnoreArguments().Return(OneValidTestDTO);
            // or play the new inline constraints syntax
            emailRepository.Expect(x =&gt; x.Insert(Arg&lt;EmailDTO&gt;.Is.Anything)).Return(OneValidTestDTO); 

            IStakeholder mockStakeholderBO = MockRepository.GenerateMock&lt;IStakeholder&gt;();  

            // Action
            EmailBOCollection emails = EmailBOCollection.NewEmailBOCollection();

            // SetStakeholder is created in EmailBOCollection to call private SetParent through reflection.
            // This is optional because the second parm in DataPortal.UpdateChild() will be passed
            // to child_XYZ() as the parameter which is the real parent.
            // emails.SetStakeholder(mockStakeholderBO);   // IStakeholder should extend csla.IParent.

            var newEmail = emails.AddNew();
            // Make this new EmailBO valid.
            newEmail.Address = &quot;1@dc.com&quot;;
            newEmail.EmailRole = &quot;Home&quot;;

            Assert.That(emails[0].BrokenRulesCollection, Is.Empty, emails[0].BrokenRulesCollection.ToString());

            // this is to simulate the parent.Save() in the real world,
            DataPortal.UpdateChild(emails, mockStakeholderBO);
            // We don't want and can't call stakeholder.Save() here

            // Assert
            Assert.That(emails[0].StakeholderEmailId == OneValidTestDTO.StakeholderEmailId);
            Assert.That(emails[0].StakeholderId == OneValidTestDTO.StakeholderId);  

            // Reset to default
            ObjectFactory.ResetDefaults();
</pre>
<p>Unfortunately, SetParent(IParent) is a private method in IEditableObject and IEditableCollection. I had to create a public wrapper in my base class.</p>
<pre class="brush: csharp;">

        public void SetStakeholder(IParent parent)
        {
            object[] parm = new object[] { parent };

            var method = this.GetType().GetMethod(&quot;Csla.Core.IEditableCollection.SetParent&quot;, BindingFlags.Instance | BindingFlags.NonPublic);

            method.Invoke(this, parm);
        }
</pre>
<p>But, later I figured out it&#8217;s not necessary, only if I am doing some parent-related validation in emailBO, say, an Organization type stakeholder can not have home email role.</p>
<p>Dataportal.Update() method is key to simulate parent.Save(), this old (3.0) syntax works great in my mock/TDD solution to CSLA.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maonet.wordpress.com/315/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maonet.wordpress.com/315/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maonet.wordpress.com/315/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maonet.wordpress.com/315/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maonet.wordpress.com/315/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maonet.wordpress.com/315/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maonet.wordpress.com/315/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maonet.wordpress.com/315/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maonet.wordpress.com/315/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maonet.wordpress.com/315/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=315&subd=maonet&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maonet.wordpress.com/2008/11/21/seperate-concern-between-parent-and-child/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d41c3a25ca01f1e979e2bc86b8c4ed38?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">FMao</media:title>
		</media:content>
	</item>
		<item>
		<title>Static field disappears on WCF</title>
		<link>http://maonet.wordpress.com/2008/11/12/a-non-runlocal-dataportal_create-is-needed-for-wcf/</link>
		<comments>http://maonet.wordpress.com/2008/11/12/a-non-runlocal-dataportal_create-is-needed-for-wcf/#comments</comments>
		<pubDate>Wed, 12 Nov 2008 17:37:55 +0000</pubDate>
		<dc:creator>Frank Mao</dc:creator>
				<category><![CDATA[CSLA]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://maonet.wordpress.com/?p=286</guid>
		<description><![CDATA[I spent 10+ hours on this problem, &#8216;Specified cast is not valid&#8217; on a CSLA library deployed onto WCF host. I figured out this is caused by inherited properties in BO were lost. The propertyInfo list is different between server and client, one side (server) doesn&#8217;t contain those properties from baseBO.
More details, BO can be [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=286&subd=maonet&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I spent 10+ hours on this problem, &#8216;Specified cast is not valid&#8217; on a CSLA library deployed onto WCF host. I figured out this is caused by inherited properties in BO were lost. The propertyInfo list is different between server and client, one side (server) doesn&#8217;t contain those properties from baseBO.</p>
<p>More details, BO can be retrieved from WCF, change one of it&#8217;s property, save BO, then this problem occured. Debug turns out before saving, the client side still had a full list of properties including inherited ones, but after serilizing-deserilizing, the one transfered to server side magically lost those base properties should inherite from ancestor!</p>
<p>We know that by adding a dummy static field can fix the similar problem, but that only works in non-WCF mode. Why not in WCF mode? Somewhere CSLA and WCF/dotNet static fields doesn&#8217;t like each other, again.</p>
<p>I am tired of this kind of issues, fortunatelly, I found a work around.</p>
<p>Always keep a <strong>non-RunLocal</strong> DataPortal_Create method in BO, and create a NewYourBO() factory method calling this DataPortal_Create(). When you get this &#8216;Specified cast is not valid&#8217; problem, just try to add this NewYourBO factory method right before your fetch operation. For a collectionBO, it should be in GetYourBOCollection()</p>
<blockquote><p>internal static YourBOColleciton()<br />
{<br />
if (Csla.ApplicationContext.DataPortalProxy.Contains(&#8220;WcfProxy&#8221;)) YourBO.NewYourBO();<br />
return DataPortal.FetchChild&lt;YourBOCollection&gt;();<br />
}</p></blockquote>
<p>For a non-collection BO, it should be in GetYourBO():</p>
<blockquote><p>internal static GetYourBO()<br />
{<br />
if (Csla.ApplicationContext.DataPortalProxy.Contains(&#8220;WcfProxy&#8221;)) NewYourBO();<br />
return DataPortal.FetchChild&lt;YourBO&gt;();<br />
}</p></blockquote>
<p>Looks like my extra code are doing a initialize work, setting up on both server and client side to make sure both side have the full property list ready.</p>
<p>Someday I will come back with a explaination.</p>
<p>Most of my problemic BOs are child type. I tried using DataPortal_CreateChild instead of DataPortal_Create, it failed. Perhaps the CreateChild one doesn&#8217;t return anything to client side.</p>
<p>There is a similar problem when moving multi-level inheritance to WCF host. The properties in middle level also be lost when fetching data down to client side. Similar workaround is to call the local constructor right before retrieve.</p>
<blockquote><p>internal static GetYourBO()<br />
{<br />
if (Csla.ApplicationContext.DataPortalProxy.Contains(&#8220;WcfProxy&#8221;)) {<br />
new YourBO(); // to trigger static field in local contrustctor<br />
// Or Activator.CreateInstance(typeof(YourBO&lt;T&gt;), true);<br />
NewYourBO(); // to trigger static field in remote constructor<br />
}<br />
return DataPortal.FetchChild&lt;YourBO&gt;();<br />
}</p></blockquote>
<p><em><strong>Update:</strong></em></p>
<p><span style="color:#ff0000;">Bought <a href="http://www.lhotka.net/weblog/ExpertC2008BusinessObjectsAlphaBookAvailable.aspx">the newest eBook from Rocky</a></span>, the solution is in OnDeserialized. We had to added base.OnDeserialized(context) because we are doing multi-level inheritance. Thanks Kevin, Thanks Rocky.</p>
<blockquote><p>private static int _init; // This must be a private type, even protected type won&#8217;t work.<br />
protected CommentBOBase()<br />
{<br />
_init = 0;<br />
}</p>
<p>protected override void OnDeserialized(System.Runtime.Serialization.StreamingContext context)<br />
{<br />
base.OnDeserialized(context);<br />
_init = 0;<br />
}</p></blockquote>
<p>My experience is, we only need to add this piece of hacking code to those base classes with static fields declared. The inherited class doesn&#8217;t need to do this trick.</p>
<p>Related posts:</p>
<p>http://forums.lhotka.net/forums/thread/24472.aspx</p>
<p>http://forums.lhotka.net/forums/post/26822.aspx</p>
<p>http://forums.lhotka.net/forums/thread/26849.aspx</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maonet.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maonet.wordpress.com/286/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maonet.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maonet.wordpress.com/286/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maonet.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maonet.wordpress.com/286/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maonet.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maonet.wordpress.com/286/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maonet.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maonet.wordpress.com/286/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=286&subd=maonet&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maonet.wordpress.com/2008/11/12/a-non-runlocal-dataportal_create-is-needed-for-wcf/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d41c3a25ca01f1e979e2bc86b8c4ed38?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">FMao</media:title>
		</media:content>
	</item>
		<item>
		<title>When Parent-Child meets Inheritance</title>
		<link>http://maonet.wordpress.com/2008/11/04/when-parent-child-meets-inheritance/</link>
		<comments>http://maonet.wordpress.com/2008/11/04/when-parent-child-meets-inheritance/#comments</comments>
		<pubDate>Tue, 04 Nov 2008 16:56:58 +0000</pubDate>
		<dc:creator>Frank Mao</dc:creator>
				<category><![CDATA[CSLA]]></category>
		<category><![CDATA[Generic]]></category>

		<guid isPermaLink="false">http://maonet.wordpress.com/?p=279</guid>
		<description><![CDATA[The right way to do inheritance in CSLA BO should be always adding generic in base/ancester&#8217;s class declaration.
e.g., instead of
class Car :BusinessBase {}
we should
class Car&#60;T&#62; :BusinessBase where T: BusinessBase&#60;T&#62; {}
Note: You will encounter the famous &#8220;dummy&#8221; staic field problem of CSLA.
The benefits of this includes,

Don&#8217;t have to override base.Save().
The registered property in base will get [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=279&subd=maonet&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>The right way to do inheritance in CSLA BO should be always adding generic in base/ancester&#8217;s class declaration.</p>
<p>e.g., instead of</p>
<blockquote><p>class Car :BusinessBase {}</p></blockquote>
<p>we should</p>
<blockquote><p>class Car&lt;T&gt; :BusinessBase where T: BusinessBase&lt;T&gt; {}</p></blockquote>
<p>Note: You will encounter the famous <a href="http://forums.lhotka.net/forums/1/22068/ShowThread.aspx">&#8220;dummy&#8221; staic field problem of CSLA</a>.</p>
<p>The benefits of this includes,</p>
<ol>
<li>Don&#8217;t have to override base.Save().</li>
<li>The registered property in base will get the correct type of inheritor.</li>
<li>Child properties will always be aware the correct inheritor&#8217;s type T. (Maybe they shouldn&#8217;t)</li>
</ol>
<p>But, this will cause the child_insert() much harder to write if you have child properties in base Car BO. This is invalid:</p>
<blockquote><p>private void Child_Insert(<span style="color:#ff0000;">Car&lt;&gt;</span> parent)  {&#8230;}</p></blockquote>
<p>And this doesn&#8217;t work either:</p>
<blockquote><p>private void Child_Insert(object parent)  {<br />
// Only check one level inheritance, to do recursive check, see details in <a href="http://mikehadlow.blogspot.com/2006/08/reflecting-generics.html">this post</a>.</p>
<p>if (!(parent.GetType().BaseType.GetGenericTypeDefinition()== typeof(Car&lt;&gt;)))<br />
throw new NotSupportedException(&#8220;&#8230;.&#8221;);</p>
<p>// Set parent id  , this line won&#8217;t compile.<br />
LoadProperty&lt;int&gt;(CarIdProperty, ((<span style="color:#ff0000;">Car&lt;&gt;</span>)parent).CarId);</p>
<p>}</p></blockquote>
<p>I can add generic to those child BO, but that looks too ugly, like Tire&lt;T&gt;, Seat&lt;T&gt;, they should be general, same to all the Cars.</p>
<p>Another solution is, creating an ICar interface.</p>
<blockquote><p>private void Child_Insert(<span style="color:#ff0000;">ICar </span>parent)  {&#8230;}</p></blockquote>
<p>It looks strange, but actually this can make child BO code much eaisier to write.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maonet.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maonet.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maonet.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maonet.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maonet.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maonet.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maonet.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maonet.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maonet.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maonet.wordpress.com/279/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maonet.wordpress.com&blog=431779&post=279&subd=maonet&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maonet.wordpress.com/2008/11/04/when-parent-child-meets-inheritance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/d41c3a25ca01f1e979e2bc86b8c4ed38?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">FMao</media:title>
		</media:content>
	</item>
	</channel>
</rss>