<?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>CleanCode NZ</title>
	<atom:link href="http://www.cleancode.co.nz/feed" rel="self" type="application/rss+xml" />
	<link>http://www.cleancode.co.nz</link>
	<description>Web Application Development  and Engineering</description>
	<lastBuildDate>Thu, 10 May 2012 23:30:09 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Sending Emails in Biztalk</title>
		<link>http://www.cleancode.co.nz/blog/1021/sending-emails-biztalk</link>
		<comments>http://www.cleancode.co.nz/blog/1021/sending-emails-biztalk#comments</comments>
		<pubDate>Wed, 18 Apr 2012 23:09:48 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[BizTalk]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=1021</guid>
		<description><![CDATA[Biztalk is all about automation, while getting email notices from your system can be helpful and give you peace of mind about system status. There are basically two ways to send emails in Biztalk, one way is using SMTP adaptor through static port as you have figured out which is not different from other standard [...]]]></description>
			<content:encoded><![CDATA[<p>Biztalk is all about automation, while getting email notices from your system can be helpful and give you peace of mind about system status. There are basically two ways to send emails in Biztalk, one way is using SMTP adaptor through static port as you have figured out  which is not different from other standard adapters like FILE or WCF-SQL, another way is using dynamic port.<span id="more-1021"></span></p>
<p>The difference  of static port and dynamic port:</p>
<p>Sending Emails through Static port: </p>
<p>Recipient: fixed address, sending email messages to ONE email address<br />
Construction: through Biztalk Administration console, not hard coded, configurable for  To,CC,Subject etc, you can choose to send messages as email body or attachments, and send port is agnostic to your code<br />
Usage : sending error messages to development etc<br />
How to: Just configure a static one way port  using SMTP as type, PassThruTransmit as send pipeline, configuration of SMTP adaptor is all straight forward. Multipart messages will be packaged into multiple attachments if Attach All Parts is selected.</p>
<p>Sending Emails through Dynamic port:</p>
<p>Recipient: programmable addresses, you can get addresses from a Biztalk message<br />
Construction: Through programming, you will have more control on construction of email<br />
Usage: sending emails to customers etc<br />
How to: here are steps of using dynamic port to send emails in Biztalk, names are just for demonstration purposes only</p>
<p>1. Create a send pipeline : SendPipeline1.btp</p>
<p>Drag MIME/SMIME encoder and drop it at Encode section of pipeline<br />
Accept the default settings for MIME/SMIME encoder<br />
SendPipeline1.btp will be used by the dynamic port</p>
<p>2. In orchestration Create MultipartType1<br />
MessagePart_1 as the body, type could be your message type, or system one like System.Xml.XmlDocument, or System.String, here I use System.Xml.XmlDocument<br />
One of the use of multi part message in Biztalk is sending different parts of a message as attachments in email, so you can add as many MessagePart as you like to MultipartType1, depends on need, you can also just have one.<br />
As an example I have MessagePart_2 using System.String</p>
<p>3. As an example I have InMSG using  type System.Xml.XmlDocument, it must be the same type as MessagePart_1 as it will be assigned to MessagePart_1, this is supposed to be your internal Biztalk message.</p>
<p>4. I have multipartMessage as MultipartType1, this message is going to be sent out in an email</p>
<p>5. A Construct Message Shape with a Message Assignment in it</p>
<p>Messages Constructed : multiPartMessage<br />
Expression of message assignment:</p>
<pre class="brush: csharp; title: ; notranslate">
multipartMessage.MessagePart_1= InMSG;
multipartMessage.MessagePart_2=&quot;This is message part2 as a string&quot;;
multipartMessage(SMTP.Subject) =&quot;Email From Dynamic Port&quot;;
multipartMessage(SMTP.From) =&quot;noreply@yourdomain.com&quot;;
multipartMessage(SMTP.SMTPHost) =&quot;yoursmypserver.com&quot;;
multipartMessage.MessagePart_2(MIME.FileName) = &quot;Attachment_Name&quot;;
multipartMessage(SMTP.SMTPAuthenticate) =0;
</pre>
<p>As an example InMSG is assigned to MessagePart_1 this is the email body, other parts of email, here is MessagePart_2, will be attachments of email, and use MIME.FileName to set the attachment name.</p>
<p>6. Create a port with name : Send_SMTP_Port</p>
<p>Binding : Dynamic<br />
Communication Direction: Send<br />
Send Pipeline: SendPipeline1<br />
Note that it is using SendPipeline1 we created earlier</p>
<p>7. Program the To address of Send_SMTP_Port in an Expression Shape after above Construct Message shape</p>
<pre class="brush: csharp; title: ; notranslate">
Send_SMTP_Port(Microsoft.XLANGs.BaseTypes.Address)=&quot;mailto:youremailadd@youremailprovider.com&quot;;
</pre>
<p>8. A send shape and link it with Send_SMTP_Port  Operation_1</p>
<p>Message: multipartMessage<br />
Operation: Send_SMTP_Port.Operation_1.Request</p>
<p>9. That is all, as Send_SMTP_Port is a dynamic port, you cannot change anything though Administration Console and it is all hard coded in the orchestration</p>
<p>10. What is the difference of message type with System.Xml.XmlDocument and System.String</p>
<p>If type is System.Xml.XmlDocument the message will be accepted as IT IS, if it is a pure text, then it will just be text.<br />
On the other hand if it is System.String, the serialization of it will be wrapped by string node. So the MessagePart_2 is like </p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;string&gt;This is message part2 as a string &lt;/string&gt;
</pre>
<p>So this tells us we had better use XmlDocument for body part to avoid Xml wrapping, and the message itself will be presented as IT IS.</p>
<p>There is also a custom serializer to RawString example you can get from Microsoft.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/1021/sending-emails-biztalk/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using DateTime in WCF-SQL Biztalk</title>
		<link>http://www.cleancode.co.nz/blog/1014/datetime-wcfsql-biztalk</link>
		<comments>http://www.cleancode.co.nz/blog/1014/datetime-wcfsql-biztalk#comments</comments>
		<pubDate>Fri, 13 Apr 2012 03:46:29 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[BizTalk]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=1014</guid>
		<description><![CDATA[When you pass xs:datetime to Sql server as parameter in Biztalk, most likely you will get an error of The input data for the field/parameter &#8220;xxxx&#8221; is invalid according to the expected SqlDbType DateTime The details of the error is: The adapter failed to transmit message going to send port with URL &#8220;mssql://.//xxxxx?&#8221;. It will [...]]]></description>
			<content:encoded><![CDATA[<p>When you pass xs:datetime to Sql server as parameter in Biztalk, most likely you will get an error of The input data for the field/parameter &#8220;xxxx&#8221; is invalid according to the expected SqlDbType DateTime<span id="more-1014"></span></p>
<p>The details of the error is:</p>
<p>The adapter failed to transmit message going to send port  with URL &#8220;mssql://.//xxxxx?&#8221;. It will be retransmitted after the retry interval specified for this Send Port. Details:&#8221;Microsoft.ServiceModel.Channels.Common.XmlReaderParsingException: The input data for the field/parameter &#8220;xxx&#8221; is invalid according to the expected SqlDbType DateTime. &#8212;> System.FormatException: The string &#8217;4/01/2012 3:30:00 p.m.&#8217; is not a valid AllXsd value.<br />
   at System.Xml.Schema.XsdDateTime..ctor(String text, XsdDateTimeFlags kinds)<br />
   at System.Xml.XmlConvert.ToDateTime(String s, XmlDateTimeSerializationMode dateTimeOption)<br />
   at Microsoft.Adapters.Sql.MetadataHelper.ConvertXmlValueToDotNetObject(String xmlString, String fieldParameterName, SqlDbType sqlDbType, Int32 maxLength, Int32 precision)<br />
   &#8212; End of inner exception stack trace &#8212;</p>
<p>Server stack trace:<br />
   at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)<br />
   at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)<br />
   at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)<br />
   at System.ServiceModel.Channels.ServiceChannel.EndRequest(IAsyncResult result)</p>
<p>Exception rethrown at [0]:<br />
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)<br />
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&#038; msgData, Int32 type)<br />
   at System.ServiceModel.Channels.IRequestChannel.EndRequest(IAsyncResult result)<br />
   at Microsoft.BizTalk.Adapter.Wcf.Runtime.WcfClient`2.RequestCallback(IAsyncResult result)&#8221;.</p>
<p>When orchestration has problems talking to wcf-sql adapter, it does not raise exceptions, the messages will be dehydrated. The above error is extracted from system event viewer, with Biztalk Server as event source and task category</p>
<p>Biztalk mapper allows linking datetime type field from source to destination datetime field, you can also link a string source field to datetime in destination, either case, sql server might complain the format about date time that is fed in, it is very frustrating that you pass a generic xs:datetime to sql server and get denied. </p>
<p>To make sql happy about date time parameters you need to convert datetime parameters into a string with hardcoded format.</p>
<p>You can use a script functoids to convert your datetime source field into string, then pass this string to a datetime parameter of the request message for your sql operation.</p>
<p>Inline c# script is </p>
<pre class="brush: csharp; title: ; notranslate">
public  string ToSqlDateTime(DateTime value)
{
            return value.ToString(&quot;s&quot;);
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/1014/datetime-wcfsql-biztalk/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Biztalk Property Promotion</title>
		<link>http://www.cleancode.co.nz/blog/1004/biztalk-property-promotion</link>
		<comments>http://www.cleancode.co.nz/blog/1004/biztalk-property-promotion#comments</comments>
		<pubDate>Wed, 11 Apr 2012 03:42:58 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[BizTalk]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=1004</guid>
		<description><![CDATA[Property promotion does two things : promote the property into a key/value store, write the value of promoted property to the data store 1.Property schema Promoted properties must be defined in a property schema Other type of schemas ml schema, envelop schema and property schema 2. Custom property schema When you quickly promote a property [...]]]></description>
			<content:encoded><![CDATA[<p>Property promotion does two things : promote the property into a key/value store, write the value of promoted property to the data store<span id="more-1004"></span></p>
<p>1.Property schema</p>
<p>Promoted properties must be defined in a property schema</p>
<p>Other type of schemas <img src='http://www.cleancode.co.nz/wp-includes/images/smilies/icon_mad.gif' alt=':x' class='wp-smiley' /> ml schema, envelop schema and property schema</p>
<p>2. Custom property schema<br />
When you quickly promote a property it will be created for you</p>
<p>3. Global property schema</p>
<p>They are used by message context fields, if you promote property to global property schema you might end up overriding its value</p>
<p>4. Property schema base  </p>
<p>When it is MessageContextPropertyBase the property can hold data outside of a message, like a message context field,  doing this you can carry data without changing message schema by adding fields to it.</p>
<p>One typical scenario is how to keep data in envelop in detaching pipeline: </p>
<p>Promote fields in envelop into custom property schema and mark them as  MessageContextPropertyBase as their propter schema base </p>
<p>Do not promote them into Global property schema to avoid overwriting system values</p>
<p>These fields can be used as extensions to the message body instead of being thrown away</p>
<p>But in the case of using envelop in send pipeline, promoting property to global property schema is very useful, normally there is no way to populate fields in the envelop of send pipeline, but if you promote fields in envelop of send pipeline it will actually copy message context data into envelop in send pipeline.</p>
<p>5. Scope of promoted property</p>
<p>It is global to Biztalk Server Administration management console, therefor can be used as port filters</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/1004/biztalk-property-promotion/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Reusable Schema In Biztalk</title>
		<link>http://www.cleancode.co.nz/blog/999/reusable-schema-biztalk</link>
		<comments>http://www.cleancode.co.nz/blog/999/reusable-schema-biztalk#comments</comments>
		<pubDate>Tue, 10 Apr 2012 01:15:20 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[BizTalk]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=999</guid>
		<description><![CDATA[The reusability of schema can be achieved through schema import and definition of simple and complex types, here is a very simple guide line as how to and what to do in terms of reusable schema design in Biztalk 1.Schema Import, Include, and Redefine The schema that is to be imported must have targeted name [...]]]></description>
			<content:encoded><![CDATA[<p>The reusability of schema can be achieved through schema import and definition of simple and complex types, here is a very simple guide line as how to and what to do in terms of reusable schema design in Biztalk<span id="more-999"></span></p>
<p>1.Schema Import, Include, and Redefine</p>
<p>The schema that is to be imported must have targeted name space</p>
<p>The schema that is to be included or redfined must have  targeted name space and the targeted name space must be same as the host</p>
<p>2. How to create simple type</p>
<p>Add a child element</p>
<p>At the data type of this element, enter a new name, this new name will be name for new simple type, and base data type for this new type will be one of those simple types already defined</p>
<p>If an existing type is selected for this child element, it will define this new child element with an existing simple type, rather than creating a new simple type</p>
<p>3. How to create complex type</p>
<p>Add a child record</p>
<p>At the data type of this record, enter a new name, this new name will be name for new complex type, and any further elements added to this record will be added to the new complex type too</p>
<p>If an existing type is selected for this child record, it will define this new child record with an existing complex type, rather than creating a new complex type</p>
<p>4. Base data type and Data type</p>
<p>If data type of new element is set , then the new element is of the set data type</p>
<p>If Base data type of new element is set, then the new element is of a new anonymous type that is derived from base data type with variations allowed </p>
<p>5. How to Reference  an imported root</p>
<p>Only root level element of imported schema can be referenced, the referenced element has no data type defined, which makes it visible for reference </p>
<p>6. How to use namespace in xpath</p>
<p>You can either reference the namespace<br />
/*[local-name()='Root' and namespace-uri()='http://NameSpace']/Head/BatchID<br />
Or just use local-name in a namespace agnostic way<br />
/*[local-name()='Root']/Head/BatchID</p>
<p>7. A final example</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-16&quot; ?&gt;
- &lt;xs:schema xmlns=&quot;http://Test.SchemaTest&quot; xmlns:b=&quot;http://schemas.microsoft.com/BizTalk/2003&quot; xmlns:ns0=&quot;http://Test.SchemaTest2&quot; targetNamespace=&quot;http://Test.SchemaTest&quot; xmlns:xs=&quot;http://www.w3.org/2001/XMLSchema&quot;&gt;
&lt;xs:include schemaLocation=&quot;.\SchemaTest3.xsd&quot; /&gt;
&lt;xs:redefine schemaLocation=&quot;.\SchemaTest4.xsd&quot; /&gt;
&lt;xs:import schemaLocation=&quot;.\SchemaTest2.xsd&quot; namespace=&quot;http://Test.SchemaTest2&quot; /&gt;
- &lt;xs:annotation&gt;
- &lt;xs:appinfo&gt;
- &lt;b:references&gt;
&lt;b:reference targetNamespace=&quot;http://Test.SchemaTest2&quot; /&gt;
&lt;/b:references&gt;
&lt;/xs:appinfo&gt;
&lt;/xs:annotation&gt;
- &lt;xs:element name=&quot;Root&quot;&gt;
- &lt;xs:complexType&gt;
- &lt;xs:sequence&gt;
&lt;xs:element ref=&quot;ns0:Root2&quot; /&gt;
&lt;xs:element ref=&quot;Root3&quot; /&gt;
&lt;xs:element ref=&quot;Root4&quot; /&gt;
&lt;xs:element name=&quot;Record&quot; type=&quot;ns0:Type2&quot; /&gt;
&lt;xs:element name=&quot;Field&quot; type=&quot;ns0:Type3Simple&quot; /&gt;
&lt;xs:element ref=&quot;ns0:Root2&quot; /&gt;
&lt;/xs:sequence&gt;
&lt;/xs:complexType&gt;
&lt;/xs:element&gt;
&lt;/xs:schema&gt;
</pre>
<p>Have fun</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/999/reusable-schema-biztalk/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>No valid adapters installed</title>
		<link>http://www.cleancode.co.nz/blog/992/no-valid-adapters-installed</link>
		<comments>http://www.cleancode.co.nz/blog/992/no-valid-adapters-installed#comments</comments>
		<pubDate>Sun, 01 Apr 2012 23:17:24 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[BizTalk]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=992</guid>
		<description><![CDATA[In BiztTalk 2010 applications talk to sql database through WCF-SQL adapter which is part of BizTalk Adapter Pack 2010, in regards to installation of these WCF based database adapters, it could prove to be very difficult to get them to work in development. I tried the installation on two of windows 7 based development pcs [...]]]></description>
			<content:encoded><![CDATA[<p>In BiztTalk 2010 applications talk to sql database through WCF-SQL adapter which is part of  BizTalk Adapter Pack 2010, in regards to installation of these WCF based database adapters, it could prove to be very difficult to get them to work in development.<span id="more-992"></span></p>
<p>I tried the installation on two of windows 7 based development pcs and neither of them worked initially, and errors I got is:</p>
<p>Within a BizTalk project , Add- Add generated items- Consume Adapter Service then<br />
<div id="attachment_993" class="wp-caption alignnone" style="width: 612px"><a href="http://www.cleancode.co.nz/wp-content/uploads/NoValidAdapters.png"><img src="http://www.cleancode.co.nz/wp-content/uploads/NoValidAdapters.png" alt="" title="NoValidAdapters" width="602" height="355" class="size-full wp-image-993" /></a><p class="wp-caption-text">No Valid Adapters VS2010</p></div></p>
<p>No valid adapters installed on the machine.<br />
Microsoft.ServiceModel.Channels.Tools.MetadataSearchBrowse.MachineConfigException: No valid adapters installed on the machine.<br />
   at Microsoft.ServiceModel.Channels.Tools.MetadataSearchBrowse.MetadataPanel.EnumerateAllAvailableBindings(String bindingExtensionName, String bindingConfiguration)<br />
   at Microsoft.ServiceModel.Channels.Tools.MetadataSearchBrowse.MetadataPanel..ctor(MetadataUserControl usercontrol, AdapterProperties properties, String bindingExtensionName, String bindingConfiguration, String uri)</p>
<p>There might be because of one of following issues if you get stuck here :</p>
<p>1.WCF LOB and Adapter Pack</p>
<p>Adapters are provided by adapter pack, but for adapter pack to work, you need to install WCF LOB SDK, initially you might not even get ‘Consume Adapter Service’ under ‘Add Generated Items’, this add-in is installed by WCF LOB SDK.  </p>
<p>So the right step should be :</p>
<p>First Install WCF LOB Adapter SDK 2010<br />
Second install Microsoft BizTalk Adapter Pack 2_0 evaluation </p>
<p>I am using x86 versions.</p>
<p>2. No valid adapters installed</p>
<p>The installation kit of above does not register adapters in config file on windows 7, you will have to do it manually yourself.</p>
<p>Some say that the new adapters registered in .Net v2, actually they have not been registered in any version of .net on my development pcs</p>
<p>All you need to do is:</p>
<p>Register new bindings in machine.config under C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config</p>
<pre class="brush: xml; title: ; notranslate">
&lt;bindingExtensions&gt;
     &lt;add name=&quot;sqlBinding&quot; type=&quot;Microsoft.Adapters.Sql.SqlAdapterBindingCollectionElement, Microsoft.Adapters.Sql, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot; /&gt;
     &lt;add name=&quot;sapBinding&quot; type=&quot;Microsoft.Adapters.SAP.SAPAdapterBindingSection, Microsoft.Adapters.SAP, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot; /&gt;
     &lt;add name=&quot;oracleDBBinding&quot; type=&quot;Microsoft.Adapters.OracleDB.OracleDBAdapterBindingSection, Microsoft.Adapters.OracleDB, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot; /&gt;
      &lt;add name=&quot;siebelBinding&quot; type=&quot;Microsoft.Adapters.Siebel.SiebelAdapterBindingSection, Microsoft.Adapters.Siebel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot; /&gt;
      &lt;add name=&quot;oracleEBSBinding&quot; type=&quot;Microsoft.Adapters.OracleEBS.OracleEBSBindingCollectionElement, Microsoft.Adapters.OracleEBS, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot; /&gt;
&lt;/bindingExtensions&gt;

&lt;client&gt;
       &lt;endpoint binding=&quot;sqlBinding&quot; contract=&quot;IMetadataExchange&quot; name=&quot;mssql&quot; /&gt;
	&lt;endpoint binding=&quot;sapBinding&quot; contract=&quot;IMetadataExchange&quot; name=&quot;sap&quot; /&gt;
	&lt;endpoint binding=&quot;oracleDBBinding&quot; contract=&quot;IMetadataExchange&quot; name=&quot;oracledb&quot; /&gt;
	&lt;endpoint binding=&quot;siebelBinding&quot; contract=&quot;IMetadataExchange&quot; name=&quot;siebel&quot; /&gt;
	&lt;endpoint binding=&quot;oracleEBSBinding&quot; contract=&quot;IMetadataExchange&quot; name=&quot;oracleebs&quot; /&gt;
	&lt;metadata&gt;
		&lt;policyImporters&gt;
		&lt;/policyImporters&gt;
		&lt;wsdlImporters&gt;
		&lt;/wsdlImporters&gt;
	&lt;/metadata&gt;
&lt;/client&gt;
</pre>
<p>A  few gotchas :</p>
<p>1. Make sure the version you entered in machine.config is the same as the version you installed, to check the version of installed dlls, in C:\Windows\assembly, looking for Microsoft.Adapters.Sql etc, if you have not installed Adapter Pack, you will not be able to find these adapter dlls<br />
2. When you manually modify the machine.config, you might have done through copy and paste the configuration changes into your machine.config from a web page, make sure the quotes and comma are right  when you paste them into machine.config.</p>
<p>Update 20/04/2012:</p>
<p>Installationof Biztalk Server 2010 Adaptors Pack on Windows Web Server 2008 R2 64bit does not register bindings of adaptors either, you will have to same modifiction of machine.config.</p>
<p>In a server condition, when you try to config a depoloyed sqlbinding adaptor, the error is:<br />
binding not found: sqlBinding<br />
<div id="attachment_1028" class="wp-caption alignnone" style="width: 621px"><a href="http://www.cleancode.co.nz/wp-content/uploads/noSqlBinding.png"><img src="http://www.cleancode.co.nz/wp-content/uploads/noSqlBinding-e1334869343834.png" alt="noSqlBinding" title="noSqlBinding" width="611" height="149" class="size-full wp-image-1028" /></a><p class="wp-caption-text">noSqlBinding</p></div></p>
<p>And machine config file is at<br />
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config</p>
<p>It does not need restart of server</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/992/no-valid-adapters-installed/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Auto build for .NET using NANT</title>
		<link>http://www.cleancode.co.nz/blog/982/auto-build-net-nant</link>
		<comments>http://www.cleancode.co.nz/blog/982/auto-build-net-nant#comments</comments>
		<pubDate>Tue, 14 Feb 2012 23:12:00 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Software Engineering]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=982</guid>
		<description><![CDATA[This is hands on example of using nant to build a .net solution, including the tricky deployment project type, auto versioning of assembly files and deployment project file. 1. Install NANT Download NANT, and unzip it, copy the folder to Program Files Add nant bin path to system path: My computer, Properties, Advanced System Settings, [...]]]></description>
			<content:encoded><![CDATA[<p>This is hands on example of using nant to build a .net solution, including the tricky deployment project type, auto versioning of assembly files and deployment project file. <span id="more-982"></span></p>
<p>1. Install NANT<br />
Download NANT, and unzip it, copy the folder to Program Files</p>
<p>Add nant bin path to system path: My computer, Properties, Advanced System Settings, Environment Variables, System Variables, Path, Edit, append &#8216;;C:\Program Files\nant-0.91\bin&#8217;</p>
<p>2. Create build file under the project folder  in the names like Yourprojectname.build<br />
In this way, nant will find *.build file automatically. All you need to do when doing a build is in cmd mode, cd to your project folder, then enter nant, all will be done</p>
<p>3. The build file is a xml file</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;project name=&quot;yourprojectname&quot; default=&quot;build&quot;&gt;
…
&lt;/ project &gt;
</pre>
<p>The root is project node, next level nodes are called <target>, here the default attribute is called build which means if you have not told nant which target to run, then nant will run build target as default.</p>
<p>4. Build target</p>
<pre class="brush: xml; title: ; notranslate">
&lt;target name=&quot;build&quot; depends=&quot;deploymentbuild&quot;&gt;
…
&lt;/target&gt;
</pre>
<p>This defines build target, where depends attribute means deploymentbuild needs to be run and successful before build target is run<br />
Through this you can split a build into many previous steps like running scripts, creating folders, running tests …</p>
<p>5. A few basic nant commands in build file</p>
<p>6. Define variables, they are called properties, placed just under project </p>
<pre class="brush: xml; title: ; notranslate">
&lt;property name=&quot;version.major&quot; value=&quot;1&quot; /&gt;
&lt;property name=&quot;version.minor&quot; value=&quot;0&quot; /&gt;
&lt;property name=&quot;version.build&quot; value=&quot;0&quot; /&gt;
&lt;property name=&quot;version.revision&quot; value=&quot;2&quot; /&gt;

&lt;property name=&quot;project.root&quot; value=&quot;D:\yourprojectfolder&quot; /&gt;
&lt;property name=&quot;build.root&quot; value=&quot;${project.root}\Releases&quot; /&gt;
</pre>
<p>To use the variable</p>
<pre class="brush: xml; title: ; notranslate">
&lt;property name=&quot;project.fullversion&quot; value=&quot;${version.major}.${version.minor}.${version.build}.${version.revision}&quot; dynamic=&quot;true&quot; /&gt;
</pre>
<p>7. To build a solution of Visual Studio</p>
<pre class="brush: xml; title: ; notranslate">
&lt;target name=&quot;buildcompile&quot; depends=&quot;version&quot;&gt;
    &lt;echo message=&quot;#### TARGET - build compile ####&quot;/&gt;
	&lt;solution configuration=&quot;debug&quot;
		solutionfile=&quot;yourprojectsolution.sln&quot; /&gt;
   &lt;/target&gt;
</pre>
<p>Build it in release mode</p>
<pre class="brush: xml; title: ; notranslate">
&lt;target name=&quot;releasebuild&quot; depends=&quot;buildcompile&quot;&gt;
	&lt;echo message=&quot;#### TARGET - release ####&quot;/&gt;
         &lt;solution configuration=&quot;release&quot;
	solutionfile=&quot;yourprojectsolution.sln&quot; /&gt;
   &lt;/target&gt;
</pre>
<p>8. To build a deployment project</p>
<p>If your solution has deployment project, above build does not generate setup.exe for your deployment project, it does not build vdproj, you will need to run this</p>
<pre class="brush: xml; title: ; notranslate">
&lt;!-- must build the dependency first (code project), before building the MSI deployment project --&gt;
&lt;exec program=&quot;${ide.dir}\Devenv.exe&quot; commandline='&quot;${solution}&quot; /rebuild &quot;Release&quot; /project &quot;${MSIprojectfile}&quot; /out &quot;${project.root}\release.log&quot;'/&gt;
</pre>
<p>This is also example of how to run an exe with arguments.</p>
<p>Here are my variables settings</p>
<pre class="brush: xml; title: ; notranslate">
&lt;property name=&quot;ide.dir&quot; value=&quot;C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE&quot; /&gt;
&lt;property name=&quot;solution&quot; value=&quot;yoursolutionfile.sln&quot; /&gt;
&lt;property name=&quot; MSIprojectfile &quot; value=&quot;${project.root}\ MSIproject \ MSIprojectfile.vdproj&quot; /&gt;
</pre>
<p>9. Delete a folder</p>
<pre class="brush: xml; title: ; notranslate">
&lt;delete dir=&quot;${build.dir}&quot; failonerror=&quot;false&quot; /&gt;
</pre>
<p>10. Create a folder</p>
<pre class="brush: xml; title: ; notranslate">
&lt;mkdir dir=&quot;${build.dir}&quot; /&gt;
</pre>
<p>11. Copy files</p>
<pre class="brush: xml; title: ; notranslate">
&lt;copy file=&quot;${project.root}\Releases\xxxx\bin\setup.exe&quot; tofile=&quot;${build.dir}\setup.exe&quot; /&gt;
&lt;copy todir=&quot;${build.dir}\Resources&quot;&gt;
&lt;fileset basedir=&quot;${project.root}\Releases\xxxx\Resources&quot;&gt;
 &lt;include name=&quot;*.*&quot; /&gt;
&lt;/fileset&gt;
&lt;/copy&gt;
</pre>
<p>12. Auto versioning<br />
Have you seen buildcompile depending on version, where is it and what it is for? We all want that this auto build toll can do auto versioning as the solution might have a dozen projects, it is pretty much a nuisance to go there to change versions manually.<br />
While there is no built versioning command in nant, I did one myself, here is it. There might be other versions on internet at the time of my research, but most of them did not work.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;target name=&quot;version&quot;&gt;
		&lt;script language=&quot;C#&quot;&gt;
			&lt;references&gt;
					&lt;include name=&quot;System.dll&quot;/&gt;
			&lt;/references&gt;
			&lt;imports&gt;
				&lt;import namespace=&quot;System.Text.RegularExpressions&quot;/&gt;
			&lt;/imports&gt;
          &lt;code&gt;
		  &lt;![CDATA[

				public static void ScriptMain(Project project)
                {

					NAnt.Core.Tasks.EchoTask echo = new NAnt.Core.Tasks.EchoTask();
	                echo.Project = project;

					UpdateAssemblyVersion(project.Properties[&quot;projectassemblyfile&quot;], project.Properties[&quot;project.fullversion&quot;],echo);
					UpdateProductVersion(project.Properties[&quot;msiprojectfile&quot;], project.Properties[&quot;product.fullversion&quot;]);

  }

public static void UpdateAssemblyVersion(string filename,string version, NAnt.Core.Tasks.EchoTask echo)
				{

echo.Message = String.Format(&quot;Updating Assembly file: {0} and project new version:{1}&quot;, filename,version);
     echo.Execute();

StreamReader reader = new StreamReader(filename);
string contents = reader.ReadToEnd();
  reader.Close();

echo.Message = String.Format(&quot;contenst: {0}&quot;, contents);
 echo.Execute();

 Regex expressionForAssemblyVersion = new Regex(@&quot;(\[assembly:\s+AssemblyVersion\(&quot;&quot;)(?:[\d\.]+)(&quot;&quot;\)\])&quot;);

contents = expressionForAssemblyVersion.Replace(contents, &quot;${1}&quot; + version+&quot;${2}&quot;);

Regex expressionAssemblyFileVersionAttribute = new Regex(@&quot;(\[assembly:\s+AssemblyFileVersionAttribute\(&quot;&quot;)(?:[\d\.]+)(&quot;&quot;\)\])&quot;);

contents = expressionAssemblyFileVersionAttribute.Replace(contents, &quot;${1}&quot; + version+&quot;${2}&quot;);

 StreamWriter writer = new StreamWriter(filename, false);
  writer.Write(contents);
   writer.Close();

echo.Message = String.Format(&quot;next text: {0}&quot;, contents);
  echo.Execute();

}

public static void UpdateProductVersion(string setupFileName,string productVersion)
{
	string setupFileContents;

	//read in the .vdproj file
	using (StreamReader sr = new StreamReader(setupFileName))
	{
		setupFileContents = sr.ReadToEnd();
	}

	if (!string.IsNullOrEmpty(setupFileContents))
	{
 	Regex expression1 = new Regex(@&quot;(&quot;&quot;ARPCOMMENTS&quot;&quot; = &quot;&quot;8:.*Build )(?:[\d\.]+)&quot;);

	Regex expression2 = new Regex(@&quot;(&quot;&quot;ProductCode&quot;&quot; = &quot;&quot;8:{)(?:[\d\w-]+)&quot;);
	Regex expression3 = new Regex(@&quot;(&quot;&quot;PackageCode&quot;&quot; = &quot;&quot;8:{)(?:[\d\w-]+)&quot;);
	Regex expression4 = new Regex(@&quot;(&quot;&quot;ProductVersion&quot;&quot; = &quot;&quot;8:)(?:[\d\.]+)&quot;);

	setupFileContents = expression1.Replace(setupFileContents, &quot;${1}&quot;+productVersion);

	setupFileContents = expression2.Replace(setupFileContents,&quot;${1}&quot;+Guid.NewGuid().ToString().ToUpper());
	setupFileContents = expression3.Replace(setupFileContents,&quot;${1}&quot;+Guid.NewGuid().ToString().ToUpper());
	setupFileContents = expression4.Replace(setupFileContents,&quot;${1}&quot;+productVersion);

	using (TextWriter tw = new StreamWriter(setupFileName, false))
	{
		tw.WriteLine(setupFileContents);
	}
	}
	}

	]]&gt;
        &lt;/code&gt;

	&lt;/script&gt;

   &lt;/target&gt;
</pre>
<p>There are two functions I developed  UpdateAssemblyVersion and UpdateProductVersion, the first one is for normal assembly.cs, the other function is for vdproj file</p>
<pre class="brush: xml; title: ; notranslate">
&lt;property name=&quot; projectassemblyfile &quot; value=&quot;${project.root}\xxxxx\AssemblyInfo.cs&quot; /&gt;
&lt;property name=&quot; msiprojectfile &quot; value=&quot;${project.root}\xxxxx\yyyyyy. vdproj &quot; /&gt;
</pre>
<p>I am sure you have found other useful commands, you can share them here if you want, the purpose of this article is to provide you an example that can get you going right now rather than a complete tutorial.</p>
<p>Have fun</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/982/auto-build-net-nant/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dynamic configurable and resuable Linq</title>
		<link>http://www.cleancode.co.nz/blog/969/dynamic-configurable-resuable-linq</link>
		<comments>http://www.cleancode.co.nz/blog/969/dynamic-configurable-resuable-linq#comments</comments>
		<pubDate>Tue, 07 Feb 2012 07:21:41 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=969</guid>
		<description><![CDATA[How to get past of writing static linq statements? Or how to include the parameters in your linq query? Or write your linq dynamically in order for it to be configurable and reusable? 1.Relationships and differences of delegate, expression and func Func, input is int, and output is int too, the last generic is output [...]]]></description>
			<content:encoded><![CDATA[<p>How to get past of writing static linq statements? Or how to include the parameters in your linq query? Or write your linq dynamically in order for it to be configurable and reusable?<span id="more-969"></span> </p>
<p>1.Relationships and differences of delegate, expression and func</p>
<pre class="brush: csharp; title: ; notranslate">
	   delegate int del(int i);

        private void button2_Click(object sender, EventArgs e)
        {

            del myDelegate = x =&gt; x * x;
            int j = myDelegate(5); //j = 25

            Func&lt;int, int&gt; myFunc = x =&gt; x*x ;

            j = myFunc(5);

            Expression&lt;del&gt; myET = x =&gt; x * x;

            del  myETFunc = myET.Compile();

            j = myETFunc(5);

            Expression&lt;Func&lt;int, int&gt;&gt; myExp = x =&gt; x * x;

            Func&lt;int, int&gt; myExpFunc = myExp.Compile();

            j = myExpFunc(5);

        }
</pre>
<p>Func<int, int>, input is int, and output is int too, the last generic is output type, the original type is:</p>
<pre class="brush: csharp; title: ; notranslate">
public delegate TResult Func&lt;in T, out TResult&gt;(T arg)
</pre>
<p>As an extreme, there is a type like this:</p>
<pre class="brush: csharp; title: ; notranslate">

public delegate TResult Func&lt;in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, out TResult&gt;(
	T1 arg1,
	T2 arg2,
	T3 arg3,
	T4 arg4,
	T5 arg5,
	T6 arg6,
	T7 arg7,
	T8 arg8,
	T9 arg9
)
</pre>
<p>2. Dynamic Linq</p>
<pre class="brush: csharp; title: ; notranslate">
   private void button3_Click(object sender, EventArgs e)
   {
            Entities db = new Entities();

            Log log = db.Logs.Where(p =&gt; p.log_code == 1).FirstOrDefault();

            log = db.Logs.Where(FuncWhere(1)).FirstOrDefault();

            log = db.Logs.Where(ExpressionFuncWhere(1)).FirstOrDefault();
    }

        private Func&lt;Log, bool&gt; FuncWhere(int logcode)
        {
            Func&lt;Log, bool&gt; exp = p =&gt; p.log_code == logcode;

            return exp;
        }

        private Expression&lt;Func&lt;Log, bool&gt;&gt; ExpressionFuncWhere(int logcode)
        {
            Expression&lt;Func&lt;Log, bool&gt;&gt; exp = p =&gt; p.log_code == logcode;

            return exp;
        }
 </pre>
<p>3. Expression or Func</p>
<p>Using Expression<T> you are explicitly creating an expression tree &#8211; this means that you can deal with the code that makes up the query as if it were data.</p>
<p>4. Find the delegate type from system.linq </p>
<p>As an example of where implementation</p>
<pre class="brush: csharp; title: ; notranslate">
public static IQueryable&lt;TSource&gt; Where&lt;TSource&gt;(
this IQueryable&lt;TSource&gt; source, Expression&lt;Func&lt;TSource, bool&gt;&gt; predicate);
</pre>
<p>Where is an extension method.</p>
<p>Type inference from this key word for the data set where is applied on.  </p>
<p>Be aware of overloads</p>
<p>In System.Linq. Queryable, there are all sorts of Linq methods you can customize or make them dynamic according to your program needs, methods like : sum, orderby,selectmany etc</p>
<p>5. Expression Trees or not</p>
<p>When you need to combine query variables you might want to build your expression tree programmatically using expression tree, there is not an easy way, but I find it comfortable to just code my lambda in a static way.</p>
<pre class="brush: csharp; title: ; notranslate">
  private void button1_Click(object sender, EventArgs e)
        {
            Entities db = new Entities();

            Log log = db.Logs.Where(p =&gt; p.log_code ==1 &amp;&amp; p.log_text.Contains(&quot;Error&quot;) ).FirstOrDefault();

            log = db.Logs.Where(FuncCombinedWhere(1,&quot;Error&quot;)).FirstOrDefault();

        }
        private Func&lt;Log, bool&gt; FuncCombinedWhere(int logcode, string textseearch)
        {
            Func&lt;Log, bool&gt; exp = p =&gt; false;

            if (logcode != 0 &amp;&amp; !string.IsNullOrEmpty(textseearch))
            {
                exp = p =&gt; p.log_code == logcode &amp;&amp; p.log_text.Contains(textseearch);
            }
            else if (logcode != 0)
            {
                exp = p =&gt; p.log_code == logcode;
            }
            else if (!string.IsNullOrEmpty(textseearch))
            {
                exp = p =&gt; p.log_text.Contains(textseearch);

            }

            return exp;

        }
</pre>
<p>6. Reuse Linq through IQueryable<T> type</p>
<pre class="brush: csharp; title: ; notranslate">
public IQueryable&lt;Log&gt; AllErrorLog()
{
 return from log in db.Logs.where(p=&gt;p.log_level==1) select log;
}
</pre>
<p>AllErrorLog() can be used for contructing other queries.</p>
<p>Have fun.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/969/dynamic-configurable-resuable-linq/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Name space programming in Javascript</title>
		<link>http://www.cleancode.co.nz/blog/959/namespace-programming-javascript</link>
		<comments>http://www.cleancode.co.nz/blog/959/namespace-programming-javascript#comments</comments>
		<pubDate>Fri, 13 Jan 2012 00:46:56 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=959</guid>
		<description><![CDATA[We all start javascript programming in a procedure way, the functions and variables defined in the way everything are global, global variables are evil some even claim, on the other hand when scripts getting bigger, and object programming concept is being used more and more, you are facing with a daunting task of maintaining and [...]]]></description>
			<content:encoded><![CDATA[<p>We all start javascript programming in a procedure way, the functions and variables defined in the way everything are global, global variables are evil some even claim, on the other hand  when scripts getting bigger, and object programming concept is being used more and more, you are facing with a daunting task of maintaining and refactoring your existing scripts, developing new code is also getting more and more difficult. To organize the code into classes  is the right way to go down, further than that how about modules or  name spaces in javascript? The answer is yes.<span id="more-959"></span></p>
<p>Here is an example of procedural style of javascript where we all began with</p>
<pre class="brush: jscript; title: ; notranslate">
function foo()
{
};
function bar()
{
}
foo();
</pre>
<p>There is no name space concept in javascript, all we are going to do is to organize our code in a way that looks like a namespace that we are used to in other typed programming languages like java and .net, it is actually one global object.   </p>
<p>Basically there are two ways we can achieve this. One way is creating a literal object that</p>
<pre class="brush: jscript; title: ; notranslate">
  var ns1 = {
            foo: function () { },
            bar: function () { },
            v1: 'foo'
        };

        ns1.foo();

        var v2 = ns1.v1;
</pre>
<p>Another way is using a top level object with constructor(not literal)</p>
<pre class="brush: jscript; title: ; notranslate">
  var ns2 = new function() {

              this.foo = function () { };

              this.bar = function () { };

              this.v1 ='foo';
          };

          ns2.foo();

          var v3 = ns2.v1;

          alert(v3);
</pre>
<p>I prefer the second way than the first one, as object literal has more restrictive syntax than a function block, they are separated by commas and assigned values through ‘:’, like a json string which sometime might be diffuclt to read. the second way is also easier to wrap up your old procedure code into a name space by just including the block under a big function which is a global object served as name space (ns2)</p>
<p>All the functions that need to be exposed have to use &#8216;this&#8217; keyword to give a clear indication of scope within the object aka namespace.</p>
<p>Please take a notice of new keyword of ns2, without this, it is treated like a function, you basically cannot reference a function using dot annotation, in javascript even though you can do something like this </p>
<pre class="brush: jscript; title: ; notranslate">
   var ns3 = function () {

             this.foo = function () { alert('foofun') };

             this.bar = function () { };

             this.v1 = 'foo';
         };

         var ns3instance = new ns3();

         ns3instance.foo();

       //  ns3.foo(); // XXXX, it is not a function
</pre>
<p>So you will have to create an instance of ns3, it is hardly anything like the namespace we expected</p>
<p>There is another concept in javascript ‘self executing function’ which we do not find any equivalent in object oriented programming languages, but it is everywhere in functional programming languages like clojure or lisps</p>
<pre class="brush: jscript; title: ; notranslate">
     var ns4 = (function () {

             var pub = {};

             pub.foo = function () {

                 alert('ns4');
                 alert(this);

             };

             return pub;
         } ());

         ns4.foo();
</pre>
<p>Personally I would not go this way, as syntax is very hard to understand, one other thing is when you use ‘this’ keyword within self executing function, this always points to ‘window’, not the object itself, to me it does not have good modulation.</p>
<p>What I have shown is namespace.funcion() which is not exactly what we want for full scale object oriented programming. What we want is namespace.class references, here is the one, using foo as an object rather than function. and your modularised object oriented javascript programming starts from here.</p>
<pre class="brush: jscript; title: ; notranslate">
    var ns5 = new function () {

            this.foo = function () {

                alert('ns5');
                alert(this)
            };

        };

 var o = new ns5.foo();
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/959/namespace-programming-javascript/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Regex Gotchas</title>
		<link>http://www.cleancode.co.nz/blog/950/regex-gotchas</link>
		<comments>http://www.cleancode.co.nz/blog/950/regex-gotchas#comments</comments>
		<pubDate>Tue, 10 Jan 2012 01:24:40 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=950</guid>
		<description><![CDATA[Here I am going to show you how to understand a few confusing usages of regex in c#, like double quotes in pattern, find and replace, wrapping up with a real world example of version number replacing in automated build process. 1. Two ways of using regex for match,replace,etc, there is no difference using them [...]]]></description>
			<content:encoded><![CDATA[<p>Here I am going to show you how to understand a few confusing usages of regex in c#, like double quotes in pattern, find and replace, wrapping up with a real world example of version number replacing in automated build process.<span id="more-950"></span></p>
<p>1. Two ways of using regex for match,replace,etc, there is no difference using them either way as far as I am concerned:</p>
<p>1.1. Using Static Regex Class</p>
<pre class="brush: csharp; title: ; notranslate">
Match m = Regex.Match(&quot;abracadabra&quot;, &quot;(a|b|r)+&quot;);
string newString=Regex.Replace(&quot;  abra  &quot;, @&quot;^\s*(.*?)\s*$&quot;, &quot;$1&quot;);
</pre>
<p>1.2. Instantiated Regex Object</p>
<pre class="brush: csharp; title: ; notranslate">
string text = &quot;abracadabra1abracadabra2abracadabra3&quot;;
string pat = @&quot;
    (		# start the first group
      abra	# match the literal 'abra'
      (		# start the second (inner) group
      cad	# match the literal 'cad'
      )?	# end the second (optional) group
    )		# end the first group
    +		# match one or more occurences
    &quot;;
// use 'x' modifier to ignore comments
Regex r = new Regex(pat, &quot;x&quot;);

Match m = r.Match(text);
</pre>
<p>Regex.Replace needs to be assigned to get to the string that is replaced. </p>
<p>2. Double quote “ in pattern</p>
<p>Two ways of using double quote in pattern, the thrid way is bit of unusual but it does not do any harm.  </p>
<pre class="brush: csharp; title: ; notranslate">
// string literal
Regex expression1 = new Regex(@&quot;&quot;&quot;([\d\.]+)&quot;&quot;&quot;);
// escaped string
Regex expression11 = new Regex(&quot;\&quot;[\\d\\.]\&quot;&quot;);
// basically the same as first one
Regex expression111 = new Regex(@&quot;\&quot;&quot;([\d\.]+)\&quot;&quot;&quot;);
</pre>
<p>Double quote in string literal is double double quote “” or escape it with &#8220;\&#8221;.</p>
<p>3. Capture and Replace</p>
<p>There are two types of capture , one is non-capturing capture using (?:pattern) , the other one is using round brackets(pattern), to construct new string using “$1 “ to reference the first pattern match. Using &#8220;$1&#8243;+another string is very tricky, as when another string starts with a number then $referencenumber will point to none existing capture therefore &#8220;$1&#8243; will give you literal. Here is an example, you want to concatenate capture with string &#8220;123.456&#8243;, its not going to happen, all you get is &#8220;$1123.456&#8243;. to get around it you need &#8220;${1}&#8221; + &#8220;123.456&#8243;.</p>
<pre class="brush: csharp; title: ; notranslate">

// this gives you capture+ new version
str = expression1.Replace(str, &quot;$1&quot;+&quot;new version&quot; );
</pre>
<p>4. A useful example</p>
<p>When doing automated release, you will have the release tool like NAnt to do version replacement for you, the task is to extract the version number out and replace it with new one using regex</p>
<pre class="brush: csharp; title: ; notranslate">

   string setupFileContents = @&quot;&quot;&quot;ARPCOMMENTS&quot;&quot; = &quot;&quot;8:xxx Build 3.5.2000&quot;&quot;&quot;;

    Regex expression1 = new Regex(@&quot;(&quot;&quot;ARPCOMMENTS&quot;&quot; = &quot;&quot;8:.*Build )(?:[\d\.]+)&quot;);

    setupFileContents = expression1.Replace(setupFileContents, &quot;$1 &quot;+&quot;new version no&quot; );
</pre>
<p>Have fun and hope this clears some confusion for you and makes you more confident when using regex.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/950/regex-gotchas/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Customization of Spring Security Authentication</title>
		<link>http://www.cleancode.co.nz/blog/937/customization-spring-security-authentication</link>
		<comments>http://www.cleancode.co.nz/blog/937/customization-spring-security-authentication#comments</comments>
		<pubDate>Sat, 05 Nov 2011 04:38:52 +0000</pubDate>
		<dc:creator>CleanCodeNZ</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.cleancode.co.nz/?p=937</guid>
		<description><![CDATA[Normally we do application authentication against a database or authenticating through web services or even more complicated a mix of them. With this in mind, I start to investigate how to use spring security to achieve authentication in these scenarios. We have nice in memory authentication examples from its document, as following: But highly unlikely [...]]]></description>
			<content:encoded><![CDATA[<p>Normally we do application authentication against a database or authenticating through web services or even more complicated a mix of them. With this in mind, I start to investigate how to use spring security to achieve authentication in these scenarios.<span id="more-937"></span></p>
<p>We have nice in memory authentication examples from its document, as following:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;authentication-manager&gt;
    &lt;authentication-provider&gt;
      &lt;user-service&gt;
        &lt;user name=&quot;jimi&quot; password=&quot;jimispassword&quot; authorities=&quot;ROLE_USER, ROLE_ADMIN&quot; /&gt;
        &lt;user name=&quot;bob&quot; password=&quot;bobspassword&quot; authorities=&quot;ROLE_USER&quot; /&gt;
      &lt;/user-service&gt;
    &lt;/authentication-provider&gt;
  &lt;/authentication-manager&gt;
</pre>
<p>But highly unlikely your system only got a few known hardcoded users, we also have other out of box authentication providers to use, like LDAP or OpenId, which still let me wondering how to have more control on authentication.</p>
<p>There is an out of box authentication against database, but it needs the creation and existence of tables exactly in its desired schema, which is not very useful as well, plus if we want authenticate through web service,we are still stuck.</p>
<p>I know from my experience with other languages that the answer lies in customization of AuthenticationProvider. But I kept getting the suggestions of extension of UserDetailService, and I had a closer look of the UserDetailService interface it only has one function</p>
<pre class="brush: java; title: ; notranslate">
public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
    }
</pre>
<p>This by the looks of it, only loads a user detail through user name, how can we authentication a user with user name and password? </p>
<p>One more frustration is that you can not even find any example out there telling you how to extend AuthenticationProvider, and most of examples of are telling you how to implement UserDetailService, What the hack this has got to do with authentication? Do we need to implement both AuthenticationProvider and UserDetailService to provide a proper authentication mechanism?</p>
<p>Here are the messages that are missing from Spring Security Document and there are paths wandering through AuthenticationProvider and UserDetailService.</p>
<p>You definitely need to customize AuthenticationProvider, which is the base class and starting point of making your own authentication, out of box LDAP and OpenId providers are implementations of it, then why we do not get told how to implement AuthenticationProvider? The answer is you hardly need to go down to that level of class hierarchy, you can get away with UserDetailService, sorry if I have confused you, but am not kidding.</p>
<p>Have a check of AbstractUserDetailsAuthenticationProvider, it is an extension of AuthenticationProvider, and it has an interesting method:</p>
<pre class="brush: java; title: ; notranslate">
protected abstract UserDetails retrieveUser(java.lang.String username,
                                            UsernamePasswordAuthenticationToken authentication)
                                     throws AuthenticationException
</pre>
<p>Is not UserDetails what UserDetailService provides? So another option is you can extend AbstractUserDetailsAuthenticationProvider instead of grand dad AuthenticationProvider, it is your choice, but still I have yet shown you why UserDetailService is so popular</p>
<p><strong>You can just implement UserDetailService to customize your authentication process either from a database or from web service, because it is provided by an out of box AuthenticationProvider implementation: DaoAuthenticationProvider</strong> which is a conceret class of  AbstractUserDetailsAuthenticationProvider and relies on UserDetailService to provide user name and password to compare them with user inputs to achieve authentication.</p>
<p>To put another way, even we only provide a user name to the UserDetailService, that leaves the UserDetailService implementation to return UserDetails that has user password, then DaoAuthenticationProvider will be responsible to check the credentials coming from login form with UserDetails, and take it from there.</p>
<p>To find the right spot of customization is important, and a sign of elegance of software development.</p>
<p>One last piece of puzzle, why from nowhere is DaoAuthenticationProvider mentioned? Or when you first saw its name you reckon it has anything to do with data access like database? All it is because it is the DEFAULT AuthenticationProvider when you config the authentication-provider node in security.xml, if you do not mention any AuthenticationProvider, then Spring Security assuems you use DaoAuthenticationProvider,</p>
<p>So if use:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;authentication-manager&gt;
    &lt;authentication-provider&gt;
      &lt;user-service&gt;
        &lt;user name=&quot;jimi&quot; password=&quot;jimispassword&quot; authorities=&quot;ROLE_USER, ROLE_ADMIN&quot; /&gt;
        &lt;user name=&quot;bob&quot; password=&quot;bobspassword&quot; authorities=&quot;ROLE_USER&quot; /&gt;
      &lt;/user-service&gt;
    &lt;/authentication-provider&gt;
  &lt;/authentication-manager&gt;
</pre>
<p>It is using DaoAuthenticationProvider, if you use</p>
<pre class="brush: xml; title: ; notranslate">
&lt;authentication-manager&gt;
		&lt;authentication-provider user-service-ref=&quot;cleancodeUserService&quot; &gt;
		&lt;/authentication-provider&gt;
	&lt;/authentication-manager&gt;
&lt;beans:bean id=&quot;cleancodeUserService&quot; class=&quot;com.cleancode.springmvc1.users.UserServiceImpl&quot;/&gt;
</pre>
<p>It is using DaoAuthenticationProvider too, even it is not in your config, as it is default.</p>
<p>It is time to show you some examples of how all these are done</p>
<p>Example 1 Customization of AuthenticationProvider:</p>
<p>Implementation of AuthenticationProvider, just presented as a prof of concept, not that I encourage you to start from this level. </p>
<pre class="brush: java; title: ; notranslate">
public class CleanCodeAuthenticationProvider implements AuthenticationProvider{

	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {

		List&lt;GrantedAuthority&gt; AUTHORITIES = new ArrayList&lt;GrantedAuthority&gt;();
		AUTHORITIES.add(new SimpleGrantedAuthority(&quot;ROLE_USER&quot;));
		if (authentication.getName().equals(authentication.getCredentials()))
			return new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials(), AUTHORITIES);
		else
			return null;

	}

	public boolean supports(Class&lt;? extends Object&gt; authentication) {
		return authentication.equals(UsernamePasswordAuthenticationToken.class);

	}

}
</pre>
<p>where authentication.getName().equals(authentication.getCredentials() is just an example, you can go off to somewhere else to get user according to its name and compare the password with authentication.getCredentials().</p>
<p>And security.xml is like</p>
<pre class="brush: xml; title: ; notranslate">
&lt;authentication-manager&gt;
		&lt;authentication-provider ref=&quot;customAuthenticationProvider&quot; &gt;
		&lt;/authentication-provider&gt;
	&lt;/authentication-manager&gt;
	&lt;beans:bean id=&quot;customAuthenticationProvider&quot; class=&quot;com.cleancode.springmvc1.users.CleanCodeAuthenticationProvider&quot;/&gt;
</pre>
<p>Example 2: Customization of UserDetailsService</p>
<pre class="brush: java; title: ; notranslate">
public class UserServiceImpl implements UserDetailsService {

    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {

    	List&lt;GrantedAuthority&gt; AUTHORITIES = new ArrayList&lt;GrantedAuthority&gt;();

    	if(username.equals(&quot;rod&quot;))
    	{

    		AUTHORITIES.add(new SimpleGrantedAuthority(&quot;supervisor&quot;));
    		AUTHORITIES.add(new SimpleGrantedAuthority(&quot;user&quot;));
    		AUTHORITIES.add(new SimpleGrantedAuthority(&quot;teller&quot;));
    		return new User(&quot;rod&quot;,
    				&quot;4efe081594ce25ee4efd9f7067f7f678a347bccf2de201f3adf2a3eb544850b465b4e51cdc3fcdde&quot;,
    				 AUTHORITIES);

    	} else if (username.equals(&quot;scott&quot;)){

    		AUTHORITIES.add(new SimpleGrantedAuthority(&quot;user&quot;));
    		return new User(&quot;scott&quot;,
    				&quot;fb1f9e48058d30dc21c35ab4cf895e2a80f2f03fac549b51be637196dfb6b2b7276a89c65e38b7a1&quot;,
    				 AUTHORITIES);
    	}
    	else
    	{
    		throw new UsernameNotFoundException(&quot;User not found: &quot; + username);
    	}

    }
}
</pre>
<p>Here I am using hardcoded user names and passwords as an example, the thing is you can go to a database or web service to retrieve user details(including password) with user name, then pass the user name and password to User constructor, the password will be used later in the chain by DaoAuthenticationProvider</p>
<p>Security.xml</p>
<pre class="brush: xml; title: ; notranslate">
  &lt;beans:bean id=&quot;encoder&quot; class=&quot;org.springframework.security.crypto.password.StandardPasswordEncoder&quot;/&gt;

  &lt;!--
    Usernames/Passwords are
        rod/koala
        scott/wombat
    --&gt;
 	&lt;authentication-manager&gt;
		&lt;authentication-provider user-service-ref=&quot;cleancodeUserService&quot; &gt;
			&lt;password-encoder ref=&quot;encoder&quot;/&gt;
		&lt;/authentication-provider&gt;
	&lt;/authentication-manager&gt;
	&lt;beans:bean id=&quot;cleancodeUserService&quot; class=&quot;com.cleancode.springmvc1.users.UserServiceImpl&quot;/&gt;
</pre>
<p>You can see you do not need to point  DaoAuthenticationProvider as AuthenticationProvider, password-encoder is another feature provided by DaoAuthenticationProvider. </p>
<p>http config is not presented here.</p>
<p>Have fun.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cleancode.co.nz/blog/937/customization-spring-security-authentication/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced
Object Caching 775/885 objects using disk: basic

Served from: www.cleancode.co.nz @ 2012-05-19 20:48:44 -->
