<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
 <title>Ramon Smits</title>
 <link href="https://www.ramonsmits.com/atom.xml" rel="self"/>
 <link href="https://www.ramonsmits.com/"/>
 <updated>2016-04-01T10:29:09+00:00</updated>
 <id>https://www.ramonsmits.com/</id>
 <author>
   <name>Ramon Smits</name>
   <email>ramon.smits@gmail.com</email>
 </author>
 
   <entry>
     <id>/2016/03/31/delete-all-queues-except-error-and-audit.html</id>
     <title>Deleting all NServiceBus MSMQ queues except error and audit</title>
     <link href="https://www.ramonsmits.com/2016/03/31/delete-all-queues-except-error-and-audit.html"/>
     <updated>2016-03-31T00:00:00+00:00</updated>
     <id>https://www.ramonsmits.com/2016/03/31/delete-all-queues-except-error-and-audit</id>
     <author>
       <name>Ramon Smits</name>
       <uri>https://www.ramonsmits.com</uri>
     </author>
     <content type="html">&lt;p&gt;&lt;a href=&quot;http://suhinini.blogspot.nl/2009/11/delete-all-msmq-queues-at-some-pc-with.html&quot;&gt;This post mentions how to delete all (private) MSMQ queues by using powershell&lt;/a&gt; and hints at using a regex to filter. It took me a few minutes to find out how to delete all queues except a few whitelisted ones. Specifically the queues used by ServiceControl to import data so it continious to operate.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;`[System.Messaging.MessageQueue]::GetPrivateQueuesByMachine(&quot;LOCALHOST&quot;) | % {&quot;.\&quot; + $_.QueueName} | ? {$_ -notmatch &quot;error|audit&quot;} | % {[System.Messaging.MessageQueue]::Delete($_); }`
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This script will delete all queues except:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;audit&lt;/li&gt;
  &lt;li&gt;audit.log&lt;/li&gt;
  &lt;li&gt;error&lt;/li&gt;
  &lt;li&gt;error.log&lt;/li&gt;
&lt;/ul&gt;
</content>
   </entry>
 
   <entry>
     <id>/2016/03/30/byte-array-utf8-bom-encoding-getstring.html</id>
     <title>Howto correctly process byte arrays with UTF8 BOM in c#</title>
     <link href="https://www.ramonsmits.com/2016/03/30/byte-array-utf8-bom-encoding-getstring.html"/>
     <updated>2016-03-30T00:00:00+00:00</updated>
     <id>https://www.ramonsmits.com/2016/03/30/byte-array-utf8-bom-encoding-getstring</id>
     <author>
       <name>Ramon Smits</name>
       <uri>https://www.ramonsmits.com</uri>
     </author>
     <content type="html">&lt;p&gt;A lot of developers are aware that sometimes files have a &lt;a href=&quot;https://en.wikipedia.org/wiki/Byte_order_mark&quot;&gt;byte order mark (BOM)&lt;/a&gt;. These can cause issues when developers do very simple imports like&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;var text = Encoding.UTF8.GetString(byteData);
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;If this byte array has a BOM then you will see this in the &lt;code class=&quot;highlighter-rouge&quot;&gt;text&lt;/code&gt; variable and that is usually not intended. Various hacks are applied like checking if the byte array starts with a UTF8 BOM and skip it or other various quirks and just ignoring the fact that the text data could be stored in a different encoding then UTF8.&lt;/p&gt;

&lt;h2 id=&quot;encoding&quot;&gt;Encoding&lt;/h2&gt;

&lt;p&gt;The issue here is that the byte array is encoded. The &lt;code class=&quot;highlighter-rouge&quot;&gt;GetString&lt;/code&gt; should only be used on fragments, not on complete documents. If you open a file or read a web page then these are streams. These streams are then often text and text can be encoded in ASCII, US-ASCII, UTF8, Windows-1252, etc. and how do you know? This is where the BOM is used with files because files do not have meta data (unless you use &lt;a href=&quot;https://support.microsoft.com/en-us/kb/105763&quot;&gt;NTFS Alternate Data Streams (ADS)&lt;/a&gt; but there are no standards for it).&lt;/p&gt;

&lt;p&gt;With web pages its different. There you have HTTP headers and we have access to the &lt;a href=&quot;https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17&quot;&gt;Content-Type&lt;/a&gt;. This identifies the type of data that is present after the body but also optionally has a &lt;code class=&quot;highlighter-rouge&quot;&gt;charset&lt;/code&gt; attribute. This stands for &lt;em&gt;Character Set&lt;/em&gt; and identifies which text encoding is used.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Content-Type: text/html; charset=ISO-8859-4
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;or&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Content-Type: application/json; charset=US-ASCII
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;There is no reason to have a UTF8 BOM when there is a Content-Type header identifying that the data is UTF8 encoding but browsers will detect the BOM and not render it.&lt;/p&gt;

&lt;h2 id=&quot;streamreader&quot;&gt;StreamReader&lt;/h2&gt;

&lt;p&gt;If you want to have a generic importer that knows how to correctly load a certain text encoding then don’t apply hacks to handle the BOM. Use the c# &lt;code class=&quot;highlighter-rouge&quot;&gt;System.IO.StreamReader&lt;/code&gt; to read text in the correct encoding. It supports most common BOM’s and using the StreamReader will result in not having the BOM in the converted string.&lt;/p&gt;

&lt;h2 id=&quot;read-byte-array-in-correct-encoding-with-optional-bom&quot;&gt;Read byte array in correct encoding with optional BOM&lt;/h2&gt;

&lt;p&gt;Maybe you want to be able to read data with or without a BOM or in an exotic encoding. The following function handles both.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;string GetString(byte[] data, string contentTypeValue, Encoding encoding)
{
  if(!string.IsNullOrEmpty(contentTypeValue))
  {
      var contentType = new ContentType(contentTypeValue);

      if(!string.IsNullOrEmpty(type.CharSet))
        encoding = Encoding.GetEncoding(type.CharSet)
  }

  using (var stream = new MemoryStream(data, false))
  using (var reader = new StreamReader(stream, encoding))
  {
    return reader.ReadToEnd();
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This function will check if a content type is available and if it has a charset attribute and use that value to initialize the StreamReader or use the encoding specified in the argument. It has no error checking. It also has mixed responsibilities as normally you would split this in two methods to and have a third that manages what would happen if there is a parsing error or an unsupported text encoding. This example would just blow up :-).&lt;/p&gt;
</content>
   </entry>
 
   <entry>
     <id>/2016/03/30/benchmark-msmq-performance.html</id>
     <title>Benchmark MSMQ Performance</title>
     <link href="https://www.ramonsmits.com/2016/03/30/benchmark-msmq-performance.html"/>
     <updated>2016-03-30T00:00:00+00:00</updated>
     <id>https://www.ramonsmits.com/2016/03/30/benchmark-msmq-performance</id>
     <author>
       <name>Ramon Smits</name>
       <uri>https://www.ramonsmits.com</uri>
     </author>
     <content type="html">&lt;p&gt;I came across an &lt;a href=&quot;https://support.microsoft.com/en-us/kb/186194&quot;&gt;MQBench.exe Measures Time to Deliver MSMQ Messages&lt;/a&gt; KB article to measure MSMQ performance. After downloading the &lt;a href=&quot;https://www.microsoft.com/en-us/download/details.aspx?id=94&quot;&gt;MQBench Command-Line Utility&lt;/a&gt; and locating the tool at &lt;code class=&quot;highlighter-rouge&quot;&gt;mqbench\MQBench\MSMQRelease\MSMQBench.exe&lt;/code&gt; I noticed that the examples in the KB article did not work. The queue location was incorrect and needed to read the &lt;a href=&quot;https://msdn.microsoft.com/en-us/library/ms700996(v=vs.85).aspx&quot;&gt;MSMQ Format names documentation&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The following example sends 100,000 messages of 2KB using 6 threads. So this means that the given number of messages is multiplied by the number of threads.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;MSMQBench.exe -sr 100000 2048 -t 6 -q .\PRIVATE$\msmqbench
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Please make sure that the &lt;em&gt;transactional&lt;/em&gt; queue exists as this tool will not create it for you. You will get the message &lt;code class=&quot;highlighter-rouge&quot;&gt;MQPathNameToFormatName failed, 3222142979l(0xc00e0003)&lt;/code&gt; if the queue does not exist.&lt;/p&gt;

&lt;p&gt;On my machine I got the following results:&lt;/p&gt;

&lt;p&gt;Using &lt;code class=&quot;highlighter-rouge&quot;&gt;-sr&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Total messages: 600000 Sent
Test time:      10.175 seconds
Benchmark:      58970 messages per second
Throughput:     120770326 bytes per second
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Using &lt;code class=&quot;highlighter-rouge&quot;&gt;-se&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Total messages: 600000 Sent
Test time:      41.215 seconds
Benchmark:      14558 messages per second
Throughput:     59629499 bytes per second
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;It seems that the &lt;code class=&quot;highlighter-rouge&quot;&gt;-s&lt;/code&gt; option has the &lt;em&gt;express&lt;/em&gt; and &lt;em&gt;recoverable&lt;/em&gt; options reversed. The &lt;em&gt;recoverable&lt;/em&gt; run is taking just 1/4th of the &lt;em&gt;express&lt;/em&gt; run.&lt;/p&gt;

&lt;p&gt;I tried testing with &lt;em&gt;non transactional queues&lt;/em&gt; but I got &lt;code class=&quot;highlighter-rouge&quot;&gt;MQSendMessage failed, 3222143015l(0xc00e0027)&lt;/code&gt; errors pretty soon and that required me to restart MSMQ.&lt;/p&gt;
</content>
   </entry>
 
   <entry>
     <id>/2014/05/05/sql-backup-to-azure.html</id>
     <title>Microsoft SQL Server backup to Azure</title>
     <link href="https://www.ramonsmits.com/2014/05/05/sql-backup-to-azure.html"/>
     <updated>2014-05-05T00:00:00+00:00</updated>
     <id>https://www.ramonsmits.com/2014/05/05/sql-backup-to-azure</id>
     <author>
       <name>Ramon Smits</name>
       <uri>https://www.ramonsmits.com</uri>
     </author>
     <content type="html">&lt;p&gt;We have been running a Microsoft SQL Server 2012 scheduled backup to Azure Storage Blobs for a couple of weeks. We have Microsoft SQL Server 2012 running on a Azure VM so it was logical to run our backup within Azure. SQL 2012 supports Azure blob storage but not in its Microsoft SQL Server Management Studio. You need to run the BACKUP statement and there is a good article on technet explaining this&lt;/p&gt;

&lt;p&gt;SQL Server Backup and Restore with Windows Azure Blob Storage Service
http://technet.microsoft.com/en-us/library/jj919148.aspx&lt;/p&gt;

&lt;p&gt;Mickaël MOTTET provides a tsql example in the comments that iterates through the available databases and runs the backup statement in a cursor. I used his example to create two stored procedures. One that does a regular backup  (BACKUP DATABASE) and a log backup (BACKUP LOG DATABASE).&lt;/p&gt;

&lt;h2 id=&quot;backup-log-database-errors-by-incorrect-recovery-model&quot;&gt;Backup log database errors by incorrect recovery model&lt;/h2&gt;

&lt;p&gt;This was al running fine for weeks but then I got log backup errors. We added a new database and its recovery model was set to ‘simple’. The solution was simple by setting the recovery model to ‘full’. Now the log backup was working again for all databases.&lt;/p&gt;

&lt;h2 id=&quot;full-recovery-model-not-always-needed&quot;&gt;Full recovery model not always needed&lt;/h2&gt;

&lt;p&gt;Except, there are lots of scenarios where you might not need the full recovery model as it also creates heavy load on your log files when you have a database that has a lot of writes while the data isn’t that important. Azure virtual machine disk IO isn’t that awesome at the moment (max 500IOPS/s).&lt;/p&gt;

&lt;p&gt;Mickaël MOTTET queried master.dbo.sysdatabases as to get a list of all databases:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;SELECT name 
FROM master.dbo.sysdatabases
WHERE dbid &amp;gt; 4
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This table does not contain the configured recovery model for the database. I changed his query to use another system database and query for the right recovery model:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;SELECT name
FROM master.sys.databases DB
WHERE database_id &amp;gt; 4 and recovery_model=1
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Now both the BACKUP DATABASE and BACKUP LOG DATABASE are working again.&lt;/p&gt;

&lt;p&gt;Here are the stored procedures that perform the backups. Both stored procedures are run from two scheduled jobs. I hope this helps a few :)&lt;/p&gt;

&lt;h2 id=&quot;database-backup-stored-procedure&quot;&gt;Database backup stored procedure&lt;/h2&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;CREATE PROCEDURE [dbo].[stp_backuptoazure]
(
	@storageAccount VARCHAR(255),
	@storageCatalog VARCHAR(255)
)
AS BEGIN

	DECLARE @credential VARCHAR(100) = @storageAccount + &#39;credential&#39;;
	DECLARE @storage VARCHAR(255) = &#39;https://&#39; + @storageAccount + &#39;.blob.core.windows.net/&#39; + @storageCatalog+ &#39;/&#39;;

	DECLARE @timestamp as varchar(50)
	SET @timestamp = REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(40), GETUTCDATE(), 120),&#39;-&#39;,&#39;_&#39;),&#39;:&#39;,&#39;_&#39;),&#39; &#39;,&#39;_&#39;);


	DECLARE @filename VARCHAR(255);
	DECLARE @databasename VARCHAR(50);
	DECLARE db_cursor CURSOR FOR  

	SELECT name 
	FROM master.dbo.sysdatabases
	WHERE dbid &amp;gt; 4
	ORDER BY name ASC; -- only users databases
 
	OPEN db_cursor   
	FETCH NEXT FROM db_cursor INTO @databasename;   
 
	WHILE @@FETCH_STATUS = 0   
	BEGIN   
 
	 SET @filename = @storage + @databasename + &#39;.&#39; + @timestamp + &#39;.bak&#39;;

	 BACKUP DATABASE @databasename
	 TO URL = @filename
	 WITH CREDENTIAL = @credential, COMPRESSION, FORMAT;

	 FETCH NEXT FROM db_cursor INTO @databasename;
	END   
 
	CLOSE db_cursor;
	DEALLOCATE db_cursor;

END
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h2 id=&quot;database-log-backup-stored-procedure&quot;&gt;Database log backup stored procedure&lt;/h2&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;CREATE PROCEDURE [dbo].[stp_backuptoazure_log]
(
	@storageAccount VARCHAR(255),
	@storageCatalog VARCHAR(255)
)
AS BEGIN

	DECLARE @credential VARCHAR(100) = @storageAccount + &#39;credential&#39;;
	DECLARE @storage VARCHAR(255) = &#39;https://&#39; + @storageAccount + &#39;.blob.core.windows.net/&#39; + @storageCatalog+ &#39;/&#39;;

	DECLARE @timestamp as varchar(50)
	SET @timestamp = REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(40), GETUTCDATE(), 120),&#39;-&#39;,&#39;_&#39;),&#39;:&#39;,&#39;_&#39;),&#39; &#39;,&#39;_&#39;);


	DECLARE @filename VARCHAR(255);
	DECLARE @databasename VARCHAR(50);
	DECLARE db_cursor CURSOR FOR  

	SELECT name
	FROM master.sys.databases DB
	WHERE database_id &amp;gt; 4 and recovery_model=1
	ORDER BY name ASC; -- only users databases with recovery model full
 
	OPEN db_cursor   
	FETCH NEXT FROM db_cursor INTO @databasename;   
 
	WHILE @@FETCH_STATUS = 0   
	BEGIN   
 
	 SET @filename = @storage + @databasename + &#39;.&#39; + @timestamp + &#39;.trn&#39;;

	 BACKUP LOG  @databasename
	 TO URL = @filename
	 WITH CREDENTIAL = @credential, COMPRESSION, FORMAT;

	 FETCH NEXT FROM db_cursor INTO @databasename;
	END   
 
	CLOSE db_cursor;
	DEALLOCATE db_cursor;

END
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

</content>
   </entry>
 
   <entry>
     <id>/2013/09/20/dell-precision-m6600-three-displays.html</id>
     <title>Dell Precision M6600 working with three monitors</title>
     <link href="https://www.ramonsmits.com/2013/09/20/dell-precision-m6600-three-displays.html"/>
     <updated>2013-09-20T00:00:00+00:00</updated>
     <id>https://www.ramonsmits.com/2013/09/20/dell-precision-m6600-three-displays</id>
     <author>
       <name>Ramon Smits</name>
       <uri>https://www.ramonsmits.com</uri>
     </author>
     <content type="html">&lt;p&gt;Work provides a nice  Dell Precision M6600 laptop workstation. It is a nice laptop and the dockingstation provides ports to connect additional displays. Our M6600 comes with the ATI Fire Pro M8900 chipset and I tried to connect two additional displays to get a triple display configuration consisting of the laptop display and two 22” monitors.&lt;/p&gt;

&lt;p&gt;I first connected both monitors with DVI as those cables just about anywhere in the office but could not get it working. It seems that when you use both DVI ports that it blocks the display of the notebook itself. The solution was to use the DisplayPort connection with a real DisplayPort connection on the monitor. I also tried to a DisplayPort to DVI cable but that had the exact same result as just using DVI.&lt;/p&gt;

&lt;p&gt;Now I have three displays active!&lt;/p&gt;
</content>
   </entry>
 
   <entry>
     <id>/2013/06/05/DateTime-and-TimeZone-explained.html</id>
     <title>DateTime and TimeZone explained</title>
     <link href="https://www.ramonsmits.com/2013/06/05/DateTime-and-TimeZone-explained.html"/>
     <updated>2013-06-05T00:00:00+00:00</updated>
     <id>https://www.ramonsmits.com/2013/06/05/DateTime-and-TimeZone-explained</id>
     <author>
       <name>Ramon Smits</name>
       <uri>https://www.ramonsmits.com</uri>
     </author>
     <content type="html">&lt;p&gt;I often see code where developers are using DateTime and are not really writing defensive code handle DateTime values. Usually a developer accepts a DateTime, assumes it is in his current time zone and do some calculations. Then days, weeks or months later the developers are notified of a strange issue for example when due to daylight savings time the clock goes back or forward.&lt;/p&gt;

&lt;p&gt;Some date time related issue examples:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Invoice specifications are not correct&lt;/li&gt;
  &lt;li&gt;Mails are send to early or to soon to international customers&lt;/li&gt;
  &lt;li&gt;Currency conversions are incorrect&lt;/li&gt;
  &lt;li&gt;Reports show an unexpected dip or peak&lt;/li&gt;
  &lt;li&gt;Scheduled tasks behave strange&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Then the bug hunting starts and after a long time a eureka moment happens and a developer notices it is because the system is not processing based on a fixed clock. It is nice to notice this as from then on a developers mind regarding date and time is changed forever in favor of mankind. The applied when a long time ago people we only using 2 digits to store years and the millennium was approaching and how leap days affects system behavior and reports.&lt;/p&gt;

&lt;p&gt;Thinking about this makes me also want to talk about time zones. This is what happens after a developer learns how to cope with utc and local time values. Usually a system runs in a certain time zone, the company expands internationally and nobody at accounting or sales realizes that when a invoice batch is ran at night that this will be happing mid day for a customer at the other side of the globe. Fun stuff happens here the same for invoice specifications.&lt;/p&gt;

&lt;p&gt;Some time zone related issue examples:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;An international customers day is different&lt;/li&gt;
  &lt;li&gt;It is strange for a customer to receive daily reports for generated reports for a period that overlaps two half days of the customer.&lt;/li&gt;
  &lt;li&gt;Notifications and reports send to an international customer will often contain difficult to read timestamps&lt;/li&gt;
  &lt;li&gt;An international customer expects to receive a report at 10:00 in the morning but now receives it at 11:00 or 9:00 due to a difference in daylight saving time rules.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This post hopefully makes you aware of common pitfalls. In future posts I will explain on how to address these issues and make a robust design for your system on how to handle such information.&lt;/p&gt;
</content>
   </entry>
 
   <entry>
     <id>/2013/05/02/multi-threaded-throttling-in-csharp.html</id>
     <title>Multi threaded throttling in csharp</title>
     <link href="https://www.ramonsmits.com/2013/05/02/multi-threaded-throttling-in-csharp.html"/>
     <updated>2013-05-02T00:00:00+00:00</updated>
     <id>https://www.ramonsmits.com/2013/05/02/multi-threaded-throttling-in-csharp</id>
     <author>
       <name>Ramon Smits</name>
       <uri>https://www.ramonsmits.com</uri>
     </author>
     <content type="html">&lt;p&gt;I had the need to limit the number of requests per second I was hitting a webserver. Packets were dropped by a firewall as the connections I was opening was done too often. I could not re-use the connections because of load-balancing and authentication requirements.&lt;/p&gt;

&lt;p&gt;My client is based on &lt;code class=&quot;highlighter-rouge&quot;&gt;Parallel.ForEach&lt;/code&gt; which means that .net automatically increases the number of worker threads until it somehow detects that increasing worker threads does not result in better performance. I started by limiting the maximum number of worker threads by passing a &lt;code class=&quot;highlighter-rouge&quot;&gt;ParallelOptions&lt;/code&gt; instance. This has the effect that the throughput is very dependant on the current system load, network conditions - and most imported - current hardware. Running it on another machine is a whole different execution environment. The solution was throttling of my work items throughput which is sometimes also referred as limiting. The requirement is simple and in my case I defined it as that my application was not allowed to process more then 10 items per second.&lt;/p&gt;

&lt;p&gt;I started ‘googling’ and landed on stackoverflow where most reactions referred to a token bucket in various implementations. I decided to stop reading as I only needed a hint, I wanted to implement the logic myself and token bucket was enough information for me. I translated this to&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;When a item needs processing decide if the throttle limit has not been reached, increment the current number or items and continue. If the throttle limit has been reached then wait until the throttle limit will be reset.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This basically resulted in the following implementation:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class Throttle
{
	private readonly object syncRoot = new object();
	private readonly int limit;
	private readonly TimeSpan duration;

	private int currentItems;
	private DateTime next = DateTime.MinValue;

	public Throttle(TimeSpan duration, int limit)
	{
		this.duration = duration;
		this.limit = limit;
	}

	public void Wait()
	{
		lock (syncRoot)
		{
			DateTime now = DateTime.UtcNow;

			if (next &amp;lt; now)
			{
				currentItems = 0;
				next = now + duration;
			}

			++currentItems;

			if (currentItems &amp;lt; limit) return;

			Thread.Sleep(next - now);
		}
	}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Example usage:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// Process a maximum of 10 items per second
var t = new Throttle(new TimeSpan(0, 0, 0, 1), 10);
var items = Enumerable.Range(0, 1000);
var start = Stopwatch.StartNew();
// Process 1000 items
Parallel.ForEach(items,i =&amp;gt;
		{
			t.Wait();
			Console.WriteLine(i);
		});
// Processing should at least have taken 100 (1000/10) seconds
Console.WriteLine(start.Elapsed);
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;I ran my implementation and it just works! I love it when you create a working piece of code within a few minutes.&lt;/p&gt;

&lt;p&gt;Well, it has a couple of minor issues like that all is synchronized by the lock statement and blocking of the thread. But I don’t mind that and it is good enough for my current purpose and frankly I would not know how to optimize it a lot more without adding much more code. The only thing I would think of would be to use &lt;code class=&quot;highlighter-rouge&quot;&gt;Stopwatch&lt;/code&gt; to lower the overhead of DateTime.UtcNow but this overhead is no where near the overhead created by calling &lt;code class=&quot;highlighter-rouge&quot;&gt;Thread.Sleep&lt;/code&gt; when the throttle limit has been reached.&lt;/p&gt;
</content>
   </entry>
 
   <entry>
     <id>/2013/04/08/receiving-salesforce-notifcations-with-nservicebus.html</id>
     <title>Receiving Salesforce notification with NServiceBus</title>
     <link href="https://www.ramonsmits.com/2013/04/08/receiving-salesforce-notifcations-with-nservicebus.html"/>
     <updated>2013-04-08T00:00:00+00:00</updated>
     <id>https://www.ramonsmits.com/2013/04/08/receiving-salesforce-notifcations-with-nservicebus</id>
     <author>
       <name>Ramon Smits</name>
       <uri>https://www.ramonsmits.com</uri>
     </author>
     <content type="html">&lt;h1 id=&quot;real-time-push-based-notifications&quot;&gt;Real-time push based notifications&lt;/h1&gt;
&lt;p&gt;A while ago I worked at a project that synced a set of entities with SalesForce. We wanted to do near real-time updates to/from SalesForce. We were already using NServiceBus and so we tried to design a solution that suited this environment.  Salesforce has the concept of objects but these could at best be seen as a form of active records. A record has an internal identifier and some other defaults like a modification timestamp.&lt;/p&gt;

&lt;h1 id=&quot;salesforce-api-contracts&quot;&gt;SalesForce API Contracts&lt;/h1&gt;
&lt;p&gt;Lets start with the standard model that salesforce offers. They provide pretty good wsdl’s that enable a contract first style of development. To get these wsdl contracts you need to go to&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Setup &amp;gt; App Setup &amp;gt; Develop &amp;gt; Api
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;/artifacts/wsdl.png&quot; alt=&quot;Exporting Enterprise WSDL&quot; /&gt;&lt;/p&gt;

&lt;p&gt;There you have a couple of contract types available of which only two are relevant:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Enterprise WSDL&lt;/li&gt;
  &lt;li&gt;Partner WSDL&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The supplied help is pretty self explanatory but just for reference I mention that the Enterprise schema can contain all custom objects that you design within Salesforce. This is what we use in our environment as it enables type-safe contract first development and that is what I will use in this post.&lt;/p&gt;

&lt;h1 id=&quot;generating-code&quot;&gt;Generating code&lt;/h1&gt;

&lt;p&gt;Here we get to the first problem as I wanted to generate code based on this wsdl without having to modify it each time it gets updated. This will not work with the ‘service reference’ style which &lt;code class=&quot;highlighter-rouge&quot;&gt;svcutil.exe&lt;/code&gt; offers. Not really a problem as we do not really need anything WCF related and makes our life much simpler. The remaining option is the ‘web reference’ style of communication. This uses the tool &lt;code class=&quot;highlighter-rouge&quot;&gt;wsdl.exe&lt;/code&gt; to generate code. The reason I mention these tools is that you want to have an easy way to update your contract and to version this in an assembly that you can share in your applications. This makes it possible to create a package build by your buildserver. This contract should not update ‘auto-magically’ as breaking it could result in either side (salesforce or your application) not being able to process data due to breaking changes. You can just ‘add web reference’ via the advanced button in the ‘add service reference’ dialog but let this be a warning!&lt;/p&gt;

&lt;p&gt;We generate the code by issuing the following command:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;wsdl.exe exported-enterprise.wsdl /n:SalesForceApi
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This generates a c# file &lt;code class=&quot;highlighter-rouge&quot;&gt;SforceService.cs&lt;/code&gt; containing a client to communicate with SalesForce.&lt;/p&gt;

&lt;h1 id=&quot;the-service-client&quot;&gt;The service client&lt;/h1&gt;

&lt;p&gt;In the supplied code you will find a static class with the name &lt;code class=&quot;highlighter-rouge&quot;&gt;SalesForceServiceFactory&lt;/code&gt;. This is a factory which creates a &lt;code class=&quot;highlighter-rouge&quot;&gt;SforceService&lt;/code&gt; instance and is needed as we need to do some handshake magic with SalesForce which basically returns a server that we must use for the current session and authenticate to that server by supplying our authenticated session identifier. It can be configured via a custom configuration section like the following:&lt;/p&gt;

&lt;p&gt;In the supplied code this class resides in the SalesForceApi project and which uses configuration via a custom configuration section:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;configuration&amp;gt;
	&amp;lt;configSections&amp;gt;
		&amp;lt;section name=&quot;SalesForceServiceFactoryConfig&quot; type=&quot;SalesForceApi.SalesForceServiceFactory+Config, SalesForceApi&quot; /&amp;gt;
	&amp;lt;/configSections&amp;gt;
	&amp;lt;SalesForceServiceFactoryConfig
		username=&quot;mycoolaccount@superduperdomain.com.test&quot;
		password=&quot;passwordissupersafe&quot;
		securityToken=&quot;TheSecurityToken&quot; /&amp;gt;
&amp;lt;/configuration&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Now we can do a simple test like the following:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;SalesForceApi.SforceService client = SalesForceServiceFactory.Create();
	
var customer = new SalesForceApi.Account
{
	AccountNumber = &quot;Smits001&quot;,
	Name = &quot;Ramon Smits&quot;,
	Website = &quot;http://ramonsmits.com&quot;,
};

var result = client.create(new SalesForceApi.sObject[] { customer });

if (!result[0].success) throw new InvalidOperationException(&quot;Failed to create account object.&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h1 id=&quot;updating-salesforce-based-on-nservicebus-events&quot;&gt;Updating SalesForce based on NServiceBus events&lt;/h1&gt;

&lt;p&gt;With the code above it now is pretty simple to update or insert a SalesForce object especially when these can be mapped one on one. You could have a message handler that handles both a &lt;code class=&quot;highlighter-rouge&quot;&gt;CustomerCreatedEvent&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;CustomerUpdatedEvent&lt;/code&gt; or just a more generic &lt;code class=&quot;highlighter-rouge&quot;&gt;CustomerSavedEvent&lt;/code&gt;. Both work, as SalesForce has an &lt;code class=&quot;highlighter-rouge&quot;&gt;.create&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;.update&lt;/code&gt; method or you can use the &lt;code class=&quot;highlighter-rouge&quot;&gt;.upsert&lt;/code&gt; method which combines both.&lt;/p&gt;

&lt;p&gt;When you use ‘fat events’ that contain the complete entity in a CQRS like fashoin then you don’t even need to query the database and just map the complete data from the event message to the SalesForce object and then voila you can now use a ‘eventual consistent’ style updating of SalesForce.&lt;/p&gt;

&lt;p&gt;In our solution we can’t always map one-on-one and sometimes data is a graph of objects in the form of an aggregate. This gets pretty complex as this requires you to ‘upsert’ several objects in one call with ‘external’ defined keys. You do not know the salesforce generated keys upfront as is the same when you do not want to work with identity insert on a sql server database. You generate your own keys known to your system and Salesforce has support for that but that is something for a future post.&lt;/p&gt;

&lt;h1 id=&quot;updating-our-service-based-on-salesforce-notifications&quot;&gt;Updating our service based on SalesForce notifications&lt;/h1&gt;

&lt;p&gt;The previous was pretty simple but now we are going to see how deep the rabbit hole goes. We want to receive notifications when objects in SalesForce are updated without requiring us to poll the SalesForce service. This needs some attention as you need to configure SalesForce to actually send these notifications. SalesForce really responds very fast with this routine and even faster when the system is ‘warm’ as in when the whole chain recently was used.&lt;/p&gt;

&lt;h2 id=&quot;outbound-messages&quot;&gt;Outbound messages&lt;/h2&gt;
&lt;p&gt;Basically we want to receive a notification when an object is written and the transaction is committed. A notification is an ‘outbound message’ and this defines the data contract of what will be send. You can define an outbound message at the following location:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Setup &amp;gt; App Setup &amp;gt; Create &amp;gt; Workflow &amp;amp; Approvals &amp;gt; Outbound Messages
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Here you can create a new outbound message. Just select the object that you want to (partially) receive and click next. In the next screen you can edit the outbound message by specifying which fields you want to send and which url to call when a notification is queued for transmission. Here I use a different object then account like for example the Contact and I only want to receive the following fields&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Id&lt;/li&gt;
  &lt;li&gt;AccountId&lt;/li&gt;
  &lt;li&gt;Birthdate&lt;/li&gt;
  &lt;li&gt;Email&lt;/li&gt;
  &lt;li&gt;CreatedData&lt;/li&gt;
  &lt;li&gt;SystemModstamp&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/artifacts/outbound-message.png&quot; alt=&quot;Building an outbound message&quot; /&gt;&lt;/p&gt;

&lt;p&gt;I’m only interested in this data here as this is relevant for this ‘amazing’ birthday discount offerings business process that I just came up with :-)&lt;/p&gt;

&lt;p&gt;Now that we have defined the outbound message we are now able to export the wsdl for this outbound message.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/artifacts/outbound-message-details.png&quot; alt=&quot;Building an outbound message&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;workflow-rule&quot;&gt;Workflow rule&lt;/h2&gt;

&lt;p&gt;Now we are at a crucial section! We defined the outbound message and now need to define a ‘trigger’ and it took me a while before I banged my head against the wall and screaming DOH! as my initial thought was that Salesforce would have this behavior by default. This trigger action detects if the modified objects should result in an outbound message and this is called a ‘workflow rule’ in SalesForce.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Setup &amp;gt; App Setup &amp;gt; Create &amp;gt; Workflow &amp;amp; Approvals &amp;gt; Workflow Rules
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Create a new rule and select the ‘Contact’ object and just define a rule that will always result in ‘true’. For example that a name field should not be null like you see in my screenshot.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/artifacts/rule.png&quot; alt=&quot;Create a new workflow rule&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Now add a workflow action and select ‘Select existing action’, search for ‘outbound message’, add your just created outbound messages and save it. Now when you add or edit contact object a notification will be queued by the workflow rule. You can verify this by browsing to:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Setup &amp;gt; Administration Setup &amp;gt; Monitoring &amp;gt; Outbound MessagesJups
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;There you should see the queued notification. If the notification is already delivered then you won’t see nothing here as it behaves like a queue.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/artifacts/queue.png&quot; alt=&quot;Outbound message queue&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;receiving-the-outbound-message&quot;&gt;Receiving the outbound message&lt;/h2&gt;

&lt;p&gt;Now that we have done the SalesForce part what remains is the NServiceBus side. What we do now is basically get the wsdl for the outbound message, generate code just like the client and make a web service that accepts that contract. We must use a different namespace as the Enterprise WSDL does not contain the outbound messages which is a real shame. If any SalesForce platform developer reads this post, please include ALL outbound message contracts in the Enterprise WSDL thank you!&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;svcutil /messageContract .\contactnotification.wsdl /n:*,SalesForceApi.Contacts
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;As you see we are now using &lt;code class=&quot;highlighter-rouge&quot;&gt;svcutil.exe&lt;/code&gt; instead of &lt;code class=&quot;highlighter-rouge&quot;&gt;wsdl.exe&lt;/code&gt; as this works for receiving messages. This will generate the file &lt;code class=&quot;highlighter-rouge&quot;&gt;contacts.cs&lt;/code&gt; containing the outbound message types. But now instead of using this code as a client we are going to use it as a contract to implement our web service.&lt;/p&gt;

&lt;p&gt;Now we need to create the message that we want to process in our own service.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class ContactSaveCommand
{
	public string Id { get; set; }
	public string AccountId { get; set; }
	public string Email { get; set; }
	public DateTime CreatedUtc { get; set; }
	public DateTime ModifiedUtc { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;To receive messages we need to create a service. I did that by created the following class&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(TransactionIsolationLevel = System.Transactions.IsolationLevel.Serializable)]
public class ContactNotificationService : NotificationPort
{
	readonly IBus bus;

	static readonly notificationsResponse1 ResultOk = new notificationsResponse1
	{
		notificationsResponse = new notificationsResponse
		{
			Ack = true
		}
	};

	public ContactNotificationService(IBus bus)
	{
		this.bus = bus;
	}

	[OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]
	public notificationsResponse1 notifications(notificationsRequest request)
	{
		foreach (var notificationItem in request.notifications.Notification)
		{
			Send(Convert(notificationItem.sObject));
		}

		return ResultOk;
	}

	private void Send(ContactSaveCommand cmd)
	{
		bus.Send(cmd);
	}

	private ContactSaveCommand Convert(global::Contact contact)
	{
		return new ContactSaveCommand
		{
			Id = contact.Id,
			AccountId = contact.AccountId,
			Email = contact.Email,
			CreatedUtc = contact.CreatedDate.Value,
			ModifiedUtc = contact.SystemModstamp.Value
		};
	}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This class can receive a &lt;code class=&quot;highlighter-rouge&quot;&gt;notificationsRequest&lt;/code&gt; message which can contain a batch of updates. I convert each message and send it separately but you could also use the message batching features of NServiceBus. Then you just convert the array. I don’t do this here as it was not required for our solution and although this results in a lot of seperate transactions the transactions are small and just result in the updating of one record.&lt;/p&gt;

&lt;p&gt;This class uses dependency injection (DI) to get a bus instance. Also, I did not use a *.svc file but used routing to bind a route to the service. The following code uses a Unity host factory but such factories are also available for Castle Windsor, Autofac, etc. and otherwise pretty easy to create yourself.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;var hostFactory = new UnityServiceHostFactory(container);
var routes = RouteTable.Routes;
routes.Add(new ServiceRoute(&quot;contact&quot;, hostFactory, typeof(ContactNotificationService)));
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;The code basically says, please create &lt;code class=&quot;highlighter-rouge&quot;&gt;ContactNotificationService&lt;/code&gt; via the &lt;code class=&quot;highlighter-rouge&quot;&gt;UnityServiceHostFactory&lt;/code&gt; when you receive a call on the path &lt;code class=&quot;highlighter-rouge&quot;&gt;/contact&lt;/code&gt;.&lt;/p&gt;

&lt;h1 id=&quot;issues-and-warnings&quot;&gt;Issues and warnings&lt;/h1&gt;

&lt;p&gt;There are a couple of issues that are not mentioned in depth in this post but really worth mentioning:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;You can model an aggregate but you will get your self in a world of pain as you will go through a rabbit hole of custom forms and all the nice stuff that salesforce offers will not be available when you go custom&lt;/li&gt;
  &lt;li&gt;SalesForce tries to deliver notifications for 24 hours and then the message is purged. You should probably have a back-up strategy for this&lt;/li&gt;
  &lt;li&gt;You will not receive messages when a object is deleted in SalesForce. You can solve this by
    &lt;ul&gt;
      &lt;li&gt;using logical deletes, or&lt;/li&gt;
      &lt;li&gt;by creating a trigger that inserts into a generic ‘deletedobjects’ table on which you create a seperate workflow rule and outbound message&lt;/li&gt;
      &lt;li&gt;run a scheduled task that queries salesforce for deleted objects (this is what we were using as this would also be the hook to make sure we received all updates in case of mayor downtime&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;AFAIK is that this solution does not comply to once and only once delivery, its not durable and not ordered. This is caused by the fact that the http transport does not offer these capabilities but also because SalesForce explicitly mentions that there is not just one queue. This probably means that there infrastructure does some round-robin delivery to a large set of notification queue servers that then try to delivery notifications and these servers are not synchronized and will have different loads resulting in different delivery ordering. This requires some investment at the receiving side for example:
    &lt;ul&gt;
      &lt;li&gt;delayed processing to allow ordering&lt;/li&gt;
      &lt;li&gt;compensating transactions when a ‘earlier’ notification is received&lt;/li&gt;
      &lt;li&gt;de-duplication of messages when a message is received multiple times&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;sourcecode&quot;&gt;Sourcecode&lt;/h1&gt;

&lt;p&gt;I made a demo solution which is available on github. I called the project &lt;a href=&quot;https://github.com/ramonsmits/sf2nsb&quot;&gt;SalesForce To NServiceBus &lt;/a&gt; (sf2nsb).&lt;/p&gt;

&lt;h1 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h1&gt;

&lt;p&gt;This post was scheduled for a while but I never got the time to finish it. Ohad of the NServiceBus champs program asked if anybody was familiar with using Salesforce with NServiceBus for (near) real-time updates and that made me write this article.
If this article was usefull for you then please mention so in the comments, follow me on twitter (ramonsmits).&lt;/p&gt;

&lt;h1 id=&quot;license&quot;&gt;License&lt;/h1&gt;

&lt;p&gt;The code is provided under Creative Commons v2.0 (CC BY 2.0) so please don’t forget to mention me when you use parts of it.&lt;/p&gt;

&lt;h1 id=&quot;further-reading&quot;&gt;Further reading&lt;/h1&gt;

&lt;p&gt;We try to model our system as Udi Dahan applies in his Advanced Distributed Systems Design (ADSD) course. This creates a couple of interesting issues as Salesforce is not really an environment that suits this methodology. Before you dive in any further I recommend that you watch and read the following:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;http://skillsmatter.com/podcast/home/events-diet&quot;&gt;Putting your events on a diet by Andreas Öhlund&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;http://www.udidahan.com/2012/12/10/service-oriented-api-implementations/&quot;&gt;Service-Oriented API implementations by Udi Dahan&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both of these give some food-for-thought regarding how to slice-and-dice your messages for processing notifications and make SOA flexible work for you while still having a a simple non cake layer architecture implementation.&lt;/p&gt;

</content>
   </entry>
 
   <entry>
     <id>/2013/03/27/namespace-using-statements-in-csharp.html</id>
     <title>Namespace using statements in csharp</title>
     <link href="https://www.ramonsmits.com/2013/03/27/namespace-using-statements-in-csharp.html"/>
     <updated>2013-03-27T00:00:00+00:00</updated>
     <id>https://www.ramonsmits.com/2013/03/27/namespace-using-statements-in-csharp</id>
     <author>
       <name>Ramon Smits</name>
       <uri>https://www.ramonsmits.com</uri>
     </author>
     <content type="html">&lt;p&gt;Namespaces in csharp is something that a lot of developers don’t get or simple never tried to figure out how they work or what can be done with the different ways of declaring namespaces.&lt;/p&gt;

&lt;p&gt;This post is about the style that I prefer and that I want to share with you. Lets start with the ‘usual’ way of declaring namespace using statements. I call this ‘outer’ as these are located outside the namespace scope.&lt;/p&gt;

&lt;pre class=&quot;brush: c#&quot;&gt;
	using System;
	using System.Transactions;
	using AwesomeApp.Contracts;
	using AwesomeApp.Model;

	namespace AwesomeApp
	{
	}
&lt;/pre&gt;

&lt;p&gt;This is what most developers do. Usually they are ordered with .net framework first, then other frameworks and then followed by internal dependencies or they are just sorted alphabetically.&lt;/p&gt;

&lt;p&gt;Then there is the other way of declaring them within the namespace scope and I call this ‘inner’ like the following example:&lt;/p&gt;

&lt;pre class=&quot;brush: c#&quot;&gt;
	namespace AwesomeApp
	{
		using System;
		using System.Transactions;
		using AwesomeApp.Contracts;
		using AwesomeApp.Model;
	}
&lt;/pre&gt;

&lt;p&gt;Now we are getting to something that A LOT of developers don’t know and that is that a lot of namespaces can be shortened.&lt;/p&gt;

&lt;pre class=&quot;brush: c#&quot;&gt;
	namespace AwesomeApp
	{
		using System;
		using System.Transactions;
		using Contracts; // AwesomeApp.Contracts
		using Model; // AwesomeApp.Model
	}
&lt;/pre&gt;

&lt;p&gt;I really like this shortening of namespaces but only for namespaces that can be shortened. This is where we get to the grand finale where we combine these various ways of ‘using’ (yes, intentional joke..) these conventions.&lt;/p&gt;

&lt;pre class=&quot;brush: c#&quot;&gt;
	using System.Transactions;

	namespace AwesomeApp
	{
		using System;
		using Contracts;
		using Model;
	}
&lt;/pre&gt;

&lt;p&gt;Personally, this is the crème de la crème regarding declaring namespaces in csharp&lt;/p&gt;
</content>
   </entry>
 
   <entry>
     <id>/2013/03/19/iis-url-rewrite-hostname-as-subfolder.html</id>
     <title>IIS url rewrite hostname to subfolder</title>
     <link href="https://www.ramonsmits.com/2013/03/19/iis-url-rewrite-hostname-as-subfolder.html"/>
     <updated>2013-03-19T00:00:00+00:00</updated>
     <id>https://www.ramonsmits.com/2013/03/19/iis-url-rewrite-hostname-as-subfolder</id>
     <author>
       <name>Ramon Smits</name>
       <uri>https://www.ramonsmits.com</uri>
     </author>
     <content type="html">&lt;p&gt;Say that you have several (thousand) static websites and you do not want to manage a seperate website within IIS. What can we do? Well, we can use url rewriting to rewrite the url and use the hostname to specify a subfolder.&lt;/p&gt;

&lt;h2 id=&quot;some-examples-with-the-rewrite-destination&quot;&gt;Some examples with the rewrite destination:&lt;/h2&gt;

&lt;p&gt;Two different domains:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;http://www.mydomain.com/favicon.ico =&amp;gt; c:\inetpub\wwwroot\mydomain.com\favicon.ico
http://otherdomain.com:8080/favicon.ico =&amp;gt; c:\inetpub\wwwroot\otherdomain.com\favicon.ico
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Same domain with and without www subdomain:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;http://www.mydomain.com/favicon.ico =&amp;gt; c:\inetpub\wwwroot\mydomain.com\favicon.ico
http://mydomain.com/favicon.ico =&amp;gt; c:\inetpub\wwwroot\mydomain.com\favicon.ico
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Different ports and protocols:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;https://mydomain.com/favicon.ico =&amp;gt; c:\inetpub\wwwroot\mydomain.com\favicon.ico
http://mydomain.com:8080/favicon.ico =&amp;gt; c:\inetpub\wwwroot\mydomain.com\favicon.ico
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h2 id=&quot;implementation-behavior&quot;&gt;Implementation behavior&lt;/h2&gt;

&lt;p&gt;The basic idea is to get the domain part from the host name and prefix this to the path. The hostname is stored in the &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;HTTP_HOST&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;/code&gt; variable. The problem is that this also has the port appended to it. It took me a while before I noticed that the port number was specified by IIS but after that finishing the rewrite action was easy.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Regular expression to retrieve the hostname without the port number:&lt;/p&gt;

    &lt;p&gt;^(www.)?(.*)(:[0-9]+)$&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Rewrite rule that prefixes the captured path (&lt;code class=&quot;highlighter-rouge&quot;&gt;R:0&lt;/code&gt;) with the captured hostname (&lt;code class=&quot;highlighter-rouge&quot;&gt;C:2&lt;/code&gt;)&lt;/p&gt;

    &lt;p&gt;{C:2}/{R:0}&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;solution&quot;&gt;Solution&lt;/h2&gt;

&lt;p&gt;Here is the actual &lt;code class=&quot;highlighter-rouge&quot;&gt;web.config&lt;/code&gt; containing the url rewrite configuration. Hope this helps!&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cp&quot;&gt;&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&amp;gt;&lt;/span&gt;
&lt;span class=&quot;nt&quot;&gt;&amp;lt;configuration&amp;gt;&lt;/span&gt;
  &lt;span class=&quot;nt&quot;&gt;&amp;lt;system.webServer&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;nt&quot;&gt;&amp;lt;rewrite&amp;gt;&lt;/span&gt;
      &lt;span class=&quot;nt&quot;&gt;&amp;lt;rules&amp;gt;&lt;/span&gt;
        &lt;span class=&quot;nt&quot;&gt;&amp;lt;rule&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;name=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;hostname2subfolder&quot;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&amp;gt;&lt;/span&gt;
          &lt;span class=&quot;c&quot;&gt;&amp;lt;!--See: http://ramonsmits.com/2013/03/19/iis-url-rewrite-hostname-as-subfolder --&amp;gt;&lt;/span&gt;
          &lt;span class=&quot;nt&quot;&gt;&amp;lt;match&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;url=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;.*&quot;&lt;/span&gt; &lt;span class=&quot;nt&quot;&gt;/&amp;gt;&lt;/span&gt;
          &lt;span class=&quot;nt&quot;&gt;&amp;lt;conditions&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;trackAllCaptures=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;false&quot;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;&amp;gt;&lt;/span&gt;
            &lt;span class=&quot;nt&quot;&gt;&amp;lt;add&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;input=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;{HTTP_HOST}&quot;&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;pattern=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;^(www\.)?(.+?)(:[0-9]+)?$&quot;&lt;/span&gt; &lt;span class=&quot;nt&quot;&gt;/&amp;gt;&lt;/span&gt;
          &lt;span class=&quot;nt&quot;&gt;&amp;lt;/conditions&amp;gt;&lt;/span&gt;
          &lt;span class=&quot;nt&quot;&gt;&amp;lt;action&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;type=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Rewrite&quot;&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;url=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;{C:2}/{R:0}&quot;&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;logRewrittenUrl=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;true&quot;&lt;/span&gt; &lt;span class=&quot;nt&quot;&gt;/&amp;gt;&lt;/span&gt;
        &lt;span class=&quot;nt&quot;&gt;&amp;lt;/rule&amp;gt;&lt;/span&gt;
      &lt;span class=&quot;nt&quot;&gt;&amp;lt;/rules&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;nt&quot;&gt;&amp;lt;/rewrite&amp;gt;&lt;/span&gt;
  &lt;span class=&quot;nt&quot;&gt;&amp;lt;/system.webServer&amp;gt;&lt;/span&gt;
&lt;span class=&quot;nt&quot;&gt;&amp;lt;/configuration&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h2 id=&quot;update-2013-04-11&quot;&gt;Update 2013-04-11&lt;/h2&gt;

&lt;p&gt;The regular expression did not work when no port was specified f.e. ramonsmits.com failed to match which results in url rewrite to not rewrite at all. I only tested the previous version through a load-balancer which redirected traffic to non default ports.&lt;/p&gt;
</content>
   </entry>
 
</feed>
