﻿<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:blogChannel="http://backend.userland.com/blogChannelModule" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
  <channel>
    <title>Nadeem Afana's  blog</title>
    <description>Software Development</description>
    <link>http://afana.me/</link>
    <docs>http://www.rssboard.org/rss-specification</docs>
    <generator>BlogEngine.NET 1.6.1.0</generator>
    <language>en-US</language>
    <blogChannel:blogRoll>http://afana.me/opml.axd</blogChannel:blogRoll>
    <blogChannel:blink>http://www.dotnetblogengine.net/syndication.axd</blogChannel:blink>
    <dc:creator>Nadeem Afana</dc:creator>
    <dc:title>Nadeem Afana's  blog</dc:title>
    <geo:lat>0.000000</geo:lat>
    <geo:long>0.000000</geo:long>
    <item>
      <title>How MIT Keytab Files Store Passwords</title>
      <description>    &lt;h2&gt;How Kerberos Keys Are Generated&lt;/h2&gt;
    &lt;p&gt;

        A Keytab file is a way to store your passwords so that you can authenticate to Kerberos services
        without typing your password again. It is similar to logon tokens in a way.
        I initially thought storing passwords in a keytab file was straightforward,
        but once I started digging into the internals, I realized I was wrong, well, half wrong because in the case of &lt;code&gt;RC4-HMAC&lt;/code&gt;, it is so simple.
    &lt;/p&gt;

    &lt;p&gt;In general, the password is not stored in raw format. A derived key is generated based on the password, and the key is stored instead. &lt;/p&gt;
    &lt;p&gt;There are multiple encryption types that Keytabs support, however, I will discuss only the following formats, which are the most common anyways:&lt;/p&gt;
    &lt;ol&gt;
        &lt;li&gt;RC4-HMAC&lt;/li&gt;
        &lt;li&gt;AES-128-CTS-HMAC-SHA1-96&lt;/li&gt;
        &lt;li&gt;AES-256-CTS-HMAC-SHA1-96&lt;/li&gt;
    &lt;/ol&gt;

    &lt;h4&gt;RC4-HMAC&lt;/h4&gt;
    &lt;p&gt;This is the simplest case:&lt;/p&gt;
    &lt;code&gt;Key = Md4 (Unicode(password))&lt;/code&gt;
    &lt;p&gt;The key is simply the MD4 hash of the password.&lt;/p&gt;
    &lt;p&gt;The following C# code will compute the key given a password.&lt;/p&gt;




&lt;pre class="brush: csharp; toolbar: false;"&gt;
// Packages required
// Install-Package ExtensionMethods
// Install-Package Afana.Cryptography
void Main()
{
	
	byte[] key = GetRc4HmacKey("password");
	Console.WriteLine(key.ToHexString());
	// outputs 8846f7eaee8fb117ad06bdd830b7586c
	
	// Note: For .ToHexString() and other extension methods, Install-Package ExtensionMethods.
	
}
byte[] GetRc4HmacKey(string password)
{
	using (HashAlgorithm hash = new Md4()) {
		return hash.ComputeHash(password.ToBytes(Encoding.Unicode));
	}
}    
&lt;/pre&gt;


    &lt;h4&gt;AES&lt;/h4&gt;
    &lt;p&gt;When it comes to AES, things are more complicated than a simple hash. Although key generation is documented in RFC3962, the process is hard to follow through and is rather complicated.&lt;/p&gt;

    &lt;h4&gt;AES-128-CTS-HMAC-SHA1-96&lt;/h4&gt;
    &lt;p&gt;
        The encryption algorithm used by AES-128-CTS-HMAC-SHA1-96 is AES CBC CTS with 128-bits key size. CTS, &lt;strong&gt;Cipher Text Stealing&lt;/strong&gt;,
        generates a cipher text which has exactly the same size as the input plain text. CTS won't
        matter in our case since the input data size is exactly 16 octets, one block, so we could simply use AES CBC instead.
    &lt;/p&gt;
    &lt;p&gt;The slightly simplified formula for generating the AES 128-bit key is:&lt;/p&gt;
    &lt;pre&gt;
        tkey = random2key(PBKDF2(passphrase, salt, iter_count, keylength))
        key = E(tkey, NFold("kerberos"), initial-cipher-state))
        E = Encrypt using AES-128-CBC-CTS
    &lt;/pre&gt;
    &lt;p&gt;&lt;code&gt;random2key&lt;/code&gt; is an identity function, which means it returns the input as is, so this function can be safely ignored.&lt;/p&gt;

    &lt;p&gt;
        &lt;code&gt;PBKDF2&lt;/code&gt; is a standard function (RFC2898) that produces a derived key given a password.
        Its purpose is to make password cracking much more difficult.
    &lt;/p&gt;
    &lt;p&gt;
        &lt;code&gt;passphrase&lt;/code&gt; is the password itself. &lt;code&gt;salt&lt;/code&gt; is the realm + user name. &lt;code&gt;iter_count&lt;/code&gt; is 4,096.
        &lt;code&gt;keylength&lt;/code&gt; is 16 bytes (128 bits).
    &lt;/p&gt;
    &lt;p&gt;
        AES CBC works in terms of blocks, which means if the data to be encrypted is less than one block in size,
        it must be padded. Because the string "kerberos" is less than one block (16 bytes),
        it must be expanded and &lt;code&gt;NFold&lt;/code&gt; is what expands it to 16 bytes.
        &lt;code&gt;NFold&lt;/code&gt; is a function that takes in a variable-length input and returns a fixed-length output.
        The .NET Framework does not provide an implementation of n-folding, so I had to write my own.
    &lt;/p&gt;
    &lt;p&gt;Here is a fully working C# example that computes the key:&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;
// Packages required
// Install-Package ExtensionMethods
// Install-Package Afana.Cryptography

void Main()
{
	
	byte[] key = GetAes128Sha1Key("password", "nadeem", "MY.REALM.COM");
	Console.WriteLine(key.ToHexString());
	// outputs 907e1f9fe6fa7359543f296d6552444c
	
	// Note: For .ToHexString(), Install-Package ExtensionMethods.
	
}

byte[] GetAes128Sha1Key(string password, string userName, string realm)
{
	// AES-128-CTS-HMAC-SHA1-96
	const int keySize = 16;
	byte[] pbkdf2 = ComputePbkdf2(password.ToBytes(), (realm+userName).ToBytes(), keySize);	
	byte[] nfolded = NFold.Compute("kerberos".ToBytes(), keySize);
	return AesCts.Encrypt(nfolded, pbkdf2, new byte[keySize]);
}

// Pbdkf2 based on HMACSHA1
public static byte[] ComputePbkdf2(byte[] password, byte[] salt, int size)
{
	using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt, 4096)) {
		// Truncate hash to "size" bytes.
		return pbkdf2.GetBytes(size);
	}
}
   
&lt;/pre&gt;
    &lt;h4&gt;AES-256-CTS-HMAC-SHA1-96&lt;/h4&gt;
    &lt;p&gt;The encryption algorithm used by AES-256-CTS-HMAC-SHA1-96 is AES CBC CTS with 256-bits key size.&lt;/p&gt;
    &lt;p&gt;Unlike AES 128, there a few extra steps for key generation:&lt;/p&gt;
&lt;pre&gt;
tkey = random2key(PBKDF2(passphrase, salt, iter_count, keylength))
k1 = E(tkey, NFold("kerberos"), initial-cipher-state))
k2 = E(tKey, k1, initial-cipher-state)
Key = k1 || k2
E = Encrypt using AES-256-CBC-CTS
&lt;/pre&gt;

&lt;pre class="brush: csharp; toolbar: false;"&gt;
// Packages required
// Install-Package ExtensionMethods
// Install-Package Afana.Cryptography

void Main()
{
	byte[] key = GetAes256Sha1Key("password", "nadeem", "MY.REALM.COM");
	Console.WriteLine(key.ToHexString());
	// outputs 08a29fccbc66d60f95ec6122545844adacff001393d79640d3ba3da17562ebe6
	// Note: For .ToHexString(), Install-Package ExtensionMethods.
}

byte[] GetAes256Sha1Key(string password, string userName, string realm)
{
	// AES-256-CTS-HMAC-SHA1-96
	byte[] pbkdf2 = ComputePbkdf2(password.ToBytes(), (realm + userName).ToBytes(), 32);	
	byte[] nfolded = NFold.Compute("kerberos".ToBytes(), 16);
	byte[] iv = new byte[16];
	byte[] k1 = AesCts.Encrypt(nfolded, pbkdf2, iv);
	byte[] k2 = AesCts.Encrypt(k1, pbkdf2, iv);
	// k1 || k2	
	return k1.Concat(k2).ToArray();
}

// Pbdkf2 based on HMACSHA1
public static byte[] ComputePbkdf2(byte[] password, byte[] salt, int outputSize)
{
	using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt, 4096)) {
		// Truncate hash to "outputSize" bytes.
		return pbkdf2.GetBytes(outputSize);
	}
}  
&lt;/pre&gt;</description>
      <link>http://afana.me/post/how-mit-keytab-files-store-passwords.aspx</link>
      <author>Nadeem</author>
      <comments>http://afana.me/post/how-mit-keytab-files-store-passwords.aspx#comment</comments>
      <guid>http://afana.me/post.aspx?id=92ca9aa8-bdb9-4a2b-976f-d796f579a819</guid>
      <pubDate>Thu, 29 Dec 2016 14:29:00 -1100</pubDate>
      <dc:publisher>Nadeem</dc:publisher>
      <pingback:server>http://afana.me/pingback.axd</pingback:server>
      <pingback:target>http://afana.me/post.aspx?id=92ca9aa8-bdb9-4a2b-976f-d796f579a819</pingback:target>
      <slash:comments>2</slash:comments>
      <trackback:ping>http://afana.me/trackback.axd?id=92ca9aa8-bdb9-4a2b-976f-d796f579a819</trackback:ping>
      <wfw:comment>http://afana.me/post/how-mit-keytab-files-store-passwords.aspx#comment</wfw:comment>
      <wfw:commentRss>http://afana.me/syndication.axd?post=92ca9aa8-bdb9-4a2b-976f-d796f579a819</wfw:commentRss>
    </item>
    <item>
      <title>.NET Cryptographic Functions</title>
      <description>    &lt;h2&gt;Cryptographic functions&lt;/h2&gt;
    &lt;p&gt;
    &lt;code&gt;Afana.Cryptography&lt;/code&gt; Nuget package is meant to be a complementary set to the .NET Framework. It is not a replacement.
         It is still work in progress, and I will add more functions if I receive enough requests from people.

         For example, the .NET Framework has no implementation of &lt;code&gt;AES CTS&lt;/code&gt; or &lt;code&gt;N-Fold&lt;/code&gt;. 
    &lt;/p&gt;

    &lt;p&gt;To add the library to your project, open Package Manager Console, select your project and type&lt;/p&gt;
    &lt;p&gt;&lt;code&gt;Install-Package Afana.Cryptography&lt;/code&gt;&lt;/p&gt;

    &lt;p&gt;The following functions are available so far&lt;/p&gt;

    &lt;h4&gt;AES CBC CTS&lt;/h4&gt;
    &lt;pre class="brush: csharp; toolbar: false;"&gt;
// using Afana.Cryptography.Aes
void Main()
{
	byte[] plainText = { 0x0c, 0x00, 0x04, 0x00, 0x0c, 0x00, 0x18, 
                         0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x00, 
                         0x04, 0xa
                       };
	byte[] iv = { 0x4a, 0xcd, 0xca, 0x4f, 0xa8, 0xb3, 0x51, 0x8b, 
                  0x8b, 0xd0, 0x39, 0xc3, 0x0c, 0x61, 0xad, 0xbf 
                };
	byte[] key = { 0xed, 0xb0, 0xb0, 0x3b, 0x59, 0xf2, 0xf5, 0xe7, 
                   0x4c, 0x04, 0xe5, 0xb8, 0xcd, 0x56, 0x40, 0x5c, 
                   0xed, 0xb0, 0xb0, 0x3b, 0x59, 0xf2, 0xf5, 0xe7, 
                   0x4c, 0x04, 0xe5, 0xb8, 0xcd, 0x56, 0x40, 0x5c 
                 };
 	
	byte[] cipherText =  AesCts.Encrypt(plainText, key, iv);
	
    Console.WriteLine(cipherText.ToHexString()); 
    // For .ToHexString(), Install-Package ExtensionMethods
	
	// Outputs fc9112f1edc30d68544b2951612e66c3
}    
&lt;/pre&gt;

    &lt;h4&gt;Rotate Left&lt;/h4&gt;
    &lt;p&gt;You can rotate left an array of bytes, not only integers.&lt;/p&gt;    
    &lt;pre class="brush: csharp; toolbar: false;"&gt;
// using Afana.Cryptography
void Main() 
{
	byte[] value = new byte[] { 0xa, 0xb, 0xc, 0xd };
	byte[] result = CryptoHelper.RoL(value, 5);
	
	Console.WriteLine(result.ToHexString()); 
	// Outputs 416181a1	
	
	// Note: For .ToHexString(), Install-Package ExtensionMethods
}   
&lt;/pre&gt;

    &lt;h4&gt;Rotate Right&lt;/h4&gt;
    &lt;p&gt;Rotates right an array of bytes, not only integers.&lt;/p&gt;
    &lt;pre class="brush: csharp; toolbar: false;"&gt;
// using Afana.Cryptography
void Main() 
{
	byte[] value = new byte[] { 0xa, 0xb, 0xc, 0xd };
	byte[] result = CryptoHelper.RoR(value, 5);
	
	Console.WriteLine(result.ToHexString()); 
	// Outputs 68505860	
	
	// Note: For .ToHexString(), Install-Package ExtensionMethods
}
&lt;/pre&gt;



    &lt;h4&gt;Greatest Common Divisor&lt;/h4&gt;
    &lt;p&gt;Calculates the Greatest Common Divisor for two integers.&lt;/p&gt;
    &lt;pre class="brush: csharp; toolbar: false;"&gt;
// using Afana.Cryptography
void Main() 
{
	 
	int result = CryptoHelper.Gcd(-15, 21);	
	Console.WriteLine(result);
	// Outputs 3

	result = CryptoHelper.Gcd(2, 4);
	Console.WriteLine(result);
	// Outputs 2		
}
&lt;/pre&gt;


    &lt;h4&gt;Least Common Multiple&lt;/h4&gt;
    &lt;p&gt;Calculates the Least Common Multiple for two integers.&lt;/p&gt;
    &lt;pre class="brush: csharp; toolbar: false;"&gt;
// using Afana.Cryptography
void Main() 
{
	 
	int result = CryptoHelper.Lcm(-15, 21);	
	Console.WriteLine(result);
	// Outputs 105	

}
&lt;/pre&gt;


    &lt;h4&gt;N-Folding&lt;/h4&gt;
    &lt;p&gt;N-Folds an array of bytes. See RFC3961 for more information.&lt;/p&gt;
    &lt;pre class="brush: csharp; toolbar: false;"&gt;
// using Afana.Cryptography
void Main() 
{
	byte[] plainText = "kerberos".ToBytes();	
	byte[] nfolded = NFold.Compute(plainText, 32);

	Console.WriteLine(nfolded.ToHexString());
	// Outputs 6b65726265726f737b9b5b2b93132b935c9bdcdad95c9899c4cae4dee6d6cae4	

	// Note: For .ToHexString(), Install-Package ExtensionMethods
}
&lt;/pre&gt;</description>
      <link>http://afana.me/post/dot-net-cryptographic-functions.aspx</link>
      <author>Nadeem</author>
      <comments>http://afana.me/post/dot-net-cryptographic-functions.aspx#comment</comments>
      <guid>http://afana.me/post.aspx?id=8c34e9a4-44b0-4282-8ebe-1f0e8b2c9fae</guid>
      <pubDate>Tue, 27 Dec 2016 10:44:00 -1100</pubDate>
      <dc:publisher>Nadeem</dc:publisher>
      <pingback:server>http://afana.me/pingback.axd</pingback:server>
      <pingback:target>http://afana.me/post.aspx?id=8c34e9a4-44b0-4282-8ebe-1f0e8b2c9fae</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://afana.me/trackback.axd?id=8c34e9a4-44b0-4282-8ebe-1f0e8b2c9fae</trackback:ping>
      <wfw:comment>http://afana.me/post/dot-net-cryptographic-functions.aspx#comment</wfw:comment>
      <wfw:commentRss>http://afana.me/syndication.axd?post=8c34e9a4-44b0-4282-8ebe-1f0e8b2c9fae</wfw:commentRss>
    </item>
    <item>
      <title>.NET AES CTS Implementation</title>
      <description>    &lt;p&gt;
        I was looking for an AES CTS .NET implementation but could not find any. The .NET Framework has an enumeration value for CTS; however, the framework throws an exception if you try to use it as it is not actually implemented. I then decided to write one and share it:
    &lt;/p&gt;
    &lt;p&gt;Install using NuGet&lt;/p&gt;

&lt;p&gt;
    &lt;code&gt;Install-Package AesCts&lt;/code&gt;
&lt;/p&gt;    

   &lt;pre class="brush: csharp; toolbar: false;"&gt;
// using Afana.Cryptography.Aes
void Main()
{
	byte[] plainText = { 0x0c, 0x00, 0x04, 0x00, 0x0c, 0x00, 0x18, 
                             0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x00, 
                             0x04, 0xa};
	byte[] iv = { 0x4a, 0xcd, 0xca, 0x4f, 0xa8, 0xb3, 0x51, 0x8b, 
                      0x8b, 0xd0, 0x39, 0xc3, 0x0c, 0x61, 0xad, 0xbf };

	byte[] key = { 0xed, 0xb0, 0xb0, 0x3b, 0x59, 0xf2, 0xf5, 0xe7, 
                       0x4c, 0x04, 0xe5, 0xb8, 0xcd, 0x56, 0x40, 0x5c, 
                       0xed, 0xb0, 0xb0, 0x3b, 0x59, 0xf2, 0xf5, 0xe7, 
                       0x4c, 0x04, 0xe5, 0xb8, 0xcd, 0x56, 0x40, 0x5c };
 	
	byte[] cipherText =  AesCts.Encrypt(plainText, key, iv);
	Console.WriteLine(cipherText.ToHexString()); 
        // For .ToHexString(), Install-Package ExtensionMethods
	
	// Outputs fc9112f1edc30d68544b2951612e66c3
}
 &lt;/pre&gt;</description>
      <link>http://afana.me/post/dot-net-aes-cts.aspx</link>
      <author>Nadeem</author>
      <comments>http://afana.me/post/dot-net-aes-cts.aspx#comment</comments>
      <guid>http://afana.me/post.aspx?id=39e8b8b6-b658-4781-b51c-581197261f5e</guid>
      <pubDate>Tue, 15 Nov 2016 11:04:00 -1100</pubDate>
      <dc:publisher>Nadeem</dc:publisher>
      <pingback:server>http://afana.me/pingback.axd</pingback:server>
      <pingback:target>http://afana.me/post.aspx?id=39e8b8b6-b658-4781-b51c-581197261f5e</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://afana.me/trackback.axd?id=39e8b8b6-b658-4781-b51c-581197261f5e</trackback:ping>
      <wfw:comment>http://afana.me/post/dot-net-aes-cts.aspx#comment</wfw:comment>
      <wfw:commentRss>http://afana.me/syndication.axd?post=39e8b8b6-b658-4781-b51c-581197261f5e</wfw:commentRss>
    </item>
    <item>
      <title>Restoring Classic Calculator in Windows 10</title>
      <description>    &lt;p&gt;
        I recently installed a new version of Windows 10 and noticed that Windows Calculator interface has changed dramatically.
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/restoring-calc-in-windows-10/new-calc.png" /&gt;
    &lt;/p&gt;

    &lt;p&gt;
        I personally didn't like. It took me a while to figure out how to perform inverse trignometric functions. 
        Finally, I realized their buttons only show up when the window size is wide enough!
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/restoring-calc-in-windows-10/classic-calc.png" /&gt;
    &lt;/p&gt;

    &lt;p&gt;So I decided to restore the classic Calcualtor app. If would like the classic Calculator interface back,
    you will need copy the classic Windows Calculator files from an earlier version of Windows 10, or from Windows 8 or 7 (this works too).
        I attached the needed files to this post. If you don't trust these, you have no choice but to get them manually.&lt;/p&gt;

    &lt;ul&gt;        
        &lt;li&gt;Two files are needed from an earlier version of Windows: &lt;code&gt;%SystemRoot%\system32\calc.exe&lt;/code&gt; and 
        &lt;code&gt;%SystemRoot%\system32\en-US\calc.exe.mui&lt;/code&gt;.  &lt;br/&gt; 
        Note that the path might be slightly different in your case.&lt;/li&gt;

        
        &lt;li&gt;Download &lt;a href="http://afana.me/attachment/restoring-calc-in-windows-10.zip"&gt;calc.zip&lt;/a&gt; and extract the  files to a folder such as &lt;code&gt;C:\calc\&lt;/code&gt;.&lt;/li&gt;
        &lt;li&gt;If you copied the two mentioned files manually, then place them in the same folder. 
        Make sure you name the files &lt;code&gt;calc.exe&lt;/code&gt; and &lt;code&gt;calc.exe.mui&lt;/code&gt;.&lt;/li&gt;

        &lt;li&gt;Run command prompt as &lt;b&gt;Administrator&lt;/b&gt; by right clicking on Command prompt and then choosing 'Run as administrator'.&lt;/li&gt;
        &lt;li&gt;Run the file &lt;code&gt;install.bat&lt;/code&gt; and press y when prompted.&lt;br/&gt;
         You might need to tweak the paths in &lt;code&gt;install.bat&lt;/code&gt; if your Windows version is not en-US.
        &lt;/li&gt;

        &lt;li&gt;
            You should see the following output  if every thing went well.
            &lt;pre class="toolbar: false;"&gt;
C:\Windows\system32&gt;C:\calc\install.bat
Taking ownership of calc.exe...
SUCCESS: The file (or folder): "C:\Windows\system32\calc.exe" now owned by the administrators group.
Are you sure (Y/N)?y
processed file: C:\Windows\system32\calc.exe
Taking ownership of calc.exe.mui...
SUCCESS: The file (or folder): "C:\Windows\system32\en-US\calc.exe.mui" now owned by the administrators group.
Are you sure (Y/N)?y
Copying calc.exe...
        1 file(s) copied.
Copying calc.exe.mui...
        1 file(s) copied.
&lt;/pre&gt;
        &lt;/li&gt;
        &lt;li&gt;Enjoy!&lt;/li&gt;
    &lt;/ul&gt;
</description>
      <link>http://afana.me/post/restoring-classic-calculator-in-windows-10.aspx</link>
      <author>Nadeem</author>
      <comments>http://afana.me/post/restoring-classic-calculator-in-windows-10.aspx#comment</comments>
      <guid>http://afana.me/post.aspx?id=33619b3f-de00-44c8-b53d-61a7e3ec360c</guid>
      <pubDate>Mon, 27 Jun 2016 11:13:00 -1100</pubDate>
      <dc:publisher>Nadeem</dc:publisher>
      <pingback:server>http://afana.me/pingback.axd</pingback:server>
      <pingback:target>http://afana.me/post.aspx?id=33619b3f-de00-44c8-b53d-61a7e3ec360c</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://afana.me/trackback.axd?id=33619b3f-de00-44c8-b53d-61a7e3ec360c</trackback:ping>
      <wfw:comment>http://afana.me/post/restoring-classic-calculator-in-windows-10.aspx#comment</wfw:comment>
      <wfw:commentRss>http://afana.me/syndication.axd?post=33619b3f-de00-44c8-b53d-61a7e3ec360c</wfw:commentRss>
    </item>
    <item>
      <title>Memory Barriers in .NET</title>
      <description>&lt;script type="text/javascript" src="http://afana.me/themes/freshcitrus/highlighter/shBrushNasm8086.js"&gt;&lt;/script&gt;

 &lt;p&gt;
        Nonblocking programming can provide performance benefits over locking, but getting it done right is significantly harder and requires careful testing.
    &lt;/p&gt;
    &lt;p&gt;
        When it comes to memory barriers, there is all sorts of confusion and misleading information.
        Because memory barrier can be counterintuitive, using them wrongly is easy, and applying them correctly requires a lot of effort and headache.
        The benefits memory barriers provide may not be worth it in most high-level applications.
        However, memory barriers are handy in performance critical software.
    &lt;/p&gt;
    &lt;p&gt;
        In the past, a system with a single processor executed concurrent threads using a trick called "timeslicing",
        where one thread is running and the others are sleeping.
        This means that all memory accesses done by one thread appeared in an exact order to all the other running threads.
        This is called a sequential consistency model. Nowadays, multiprocessor systems are very common and
        concurrent threads are truly running at the same time, so sequential consistency is not guaranteed because
    &lt;/p&gt;

    &lt;p&gt;
        &lt;ol&gt;
            &lt;li&gt;The compiler or JIT might re-order the memory instructions for optimization.&lt;/li&gt;
            &lt;li&gt;
                The processor can also re-order memory instructions for performance through different mechanisms
                including caching, load speculation, and delaying store operations.
            &lt;/li&gt;
        &lt;/ol&gt;
    &lt;/p&gt;

    &lt;p&gt;Consider the following program.&lt;/p&gt;
    &lt;p&gt;
        &lt;span id="Example1"&gt;Example 1&lt;/span&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;
int x = 0, y = 0, r1 = 0, r2 = 0;
public void Thread1()
{	 
	y = 1;  // Store y
	r1 = x; // Load x	 		 
	  
}
	
public void Thread2()
{
	x = 1;  // Store x
	r2 = y; // Load y	  
}
&lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        If the methods run on different threads, there are a few possibilities for the values of &lt;code&gt;r1&lt;/code&gt; and &lt;code&gt;r2&lt;/code&gt;:
        &lt;ol&gt;
            &lt;li&gt;Thread1 finishes before Thread 2 starts, so that &lt;code&gt;r1 = 0&lt;/code&gt;  and &lt;code&gt;r2 = 1&lt;/code&gt;.&lt;/li&gt;
            &lt;li&gt;Thread 2 finishes before Thread 1 starts, so that &lt;code&gt;r2 = 0&lt;/code&gt; and &lt;code&gt;r1 = 1&lt;/code&gt;.&lt;/li&gt;
            &lt;li&gt;
                Both Thread1 and Thread2 interleave, so that either one of the following will happen:
                &lt;ol&gt;
                    &lt;li&gt;&lt;code&gt;r1 = 1&lt;/code&gt; and &lt;code&gt;r2 = 1&lt;/code&gt; or&lt;/li&gt;
                    &lt;li&gt;&lt;code&gt;r1 = 0&lt;/code&gt; and &lt;code&gt;r2 = 1&lt;/code&gt; or&lt;/li&gt;
                    &lt;li&gt;&lt;code&gt;r1 = 1&lt;/code&gt; and &lt;code&gt;r2 = 0&lt;/code&gt;&lt;/li&gt;
                &lt;/ol&gt;
            &lt;/li&gt;
        &lt;/ol&gt;
    &lt;/p&gt;
    &lt;p&gt;
        In all of the cases above, either &lt;code&gt;r1 = 0&lt;/code&gt; or &lt;code&gt;r2 = 0&lt;/code&gt; but never both &lt;code&gt;r1&lt;/code&gt; and &lt;code&gt;r2&lt;/code&gt; are 0.

        Is it possible that both &lt;code&gt;r1 = 0&lt;/code&gt; and &lt;code&gt;r2 = 0&lt;/code&gt;?
    &lt;/p&gt;
    &lt;p&gt;The answer is "yes" though it is counterintuitive, but how ?&lt;/p&gt;
    &lt;p&gt;
        A processor can defer its store operations in a buffer, and this causes operations to be out of order.
        If both stores to x and y are delayed, then the load from x in Thread 1 will read 0,
        and the load from y in Thread2 will read 0 too!
    &lt;/p&gt;
    &lt;p&gt;
        The real execution order might look like this:
    &lt;/p&gt;
    &lt;p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;
public void Thread1()
{	 
    r1 = x;  // Load x
    y  = 1;  // Store y	   		 
	  
}
	
public void Thread2()
{	  
    r2 = y;  // Load y	  
    x  = 1;  // Store x
}
&lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        If you want to try it yourself, compile and run the following program. I ran the following program on my Intel64 machine.
    &lt;/p&gt;
    &lt;p&gt;&lt;strong&gt;NOTE&lt;/strong&gt;: You must compile in release mode.&lt;/p&gt;

    &lt;p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;
using System;
using System.Threading.Tasks;
namespace ConsoleApplication
{
    class Program
    {
        static int x = 0;
        static int y = 0;
        static int r1 = 0;
        static int r2 = 0;
        static void Main(string[] args)
        {
            do {
                x = y = r1 = r2 = 0;
                var t1 = new Task(() =&gt; { Thread1(); });
                var t2 = new Task(() =&gt; { Thread2(); });
                t1.Start();
                t2.Start();
                Task.WaitAll(t1, t2);
            } while (!(r1 == 0 &amp;&amp; r2 == 0));
            Console.WriteLine("r1={0}, r2={1}", r1, r2);
        }
        static public void Thread1()
        {
            y = 1;  // Store y
            r1 = x; // Load x	 		 
        }
        static public void Thread2()
        {
            x = 1;  // Store x
            r2 = y; // Load y	  
        }
    }
}
&lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        Even if you declare the variables as volatile, it won&amp;#39;t help! I&amp;#39;ll discuss volatile shortly.
        Anyways, to fix the problem, add a memory barrier &lt;code&gt;Thread.MemoryBarrier()&lt;/code&gt; between the store and load operations in each thread.
        We&amp;#39;ll come back to this example later after discussing memory barriers.
    &lt;/p&gt;

    &lt;p&gt;
        The previous example was a hardware optimization. Let&amp;#39;s see another example where software manifests its optimization.
    &lt;/p&gt;
    &lt;p&gt;
        &lt;span id="Example2"&gt;Example 2&lt;/span&gt;
        The following loop will run forever. Why ?
    &lt;/p&gt;
    &lt;p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;
bool terminate = false;
	
var t = new Thread(() =&gt; { 		
	int x = 0; 
	while(!terminate){x = x * 1;}
});
	
t.Start();
Thread.Sleep(2000);
terminate = true;
t.Join();
Console.WriteLine("Done.");
&lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        Looking at the disassembly code, I see the following for the thread &lt;code&gt;t&lt;/code&gt; body:
    &lt;/p&gt;
    &lt;p&gt;
        &lt;pre class="brush: masm; toolbar: false;  highlight: [5,6]"&gt;
00B400E1      mov         ebp,esp      
00B400E3      movzx       eax,byte ptr [ecx+4] ; Load terminate into EAX
00B400E7      test        eax,eax  
00B400E9      jne         00B400EF  
00B400EB      test        eax,eax  
00B400ED      je          00B400EB  
00B400EF      pop         ebp  
00B400F0      ret
&lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        This time it is JIT, not the hardware. It&amp;#39;s clear that JIT has cached the value of the variable terminate in the EAX register.
        The program is now stuck in the loop highlighted above. If you don&amp;#39;t know assembly well,
        the highlighted section above is equivalent to the following C# code.
    &lt;/p&gt;

    &lt;p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;
while(true){}
&lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        Either using a lock or adding a &lt;code&gt;Thread.MemoryBarrier&lt;/code&gt; inside the while loop will fix the problem. Or you can even use &lt;code&gt;Volatile.Read&lt;/code&gt;.
    &lt;/p&gt;
    &lt;p&gt;
        The purpose of the memory barrier here is only to suppress JIT optimizations.
    &lt;/p&gt;
    &lt;p&gt;
        Now that we have seen how software and hardware can reorder memory operations, it&amp;#39;s time to discuss memory barriers.
    &lt;/p&gt;
    &lt;p&gt;
        &lt;b&gt;Memory Barriers&lt;/b&gt;
    &lt;/p&gt;
    &lt;p&gt;
        We saw how the hardware and JIT could reorder memory instructions.
        This can be a problem for communication between different processors as we saw in the examples above.
        Memory barriers (aka memory fences) are a way to tell the compiler, JIT and the processor to restrict the ordering of memory instructions.
    &lt;/p&gt;
    &lt;p&gt;
        It&amp;#39;s important to note, in general, memory barriers are needed for communication between different
        processors (There are exceptions of course, such as using a memory barrier to suppress the compiler or JIT optimizations).
        If the system has only one single processor, then there may not be a need for memory barriers.
    &lt;/p&gt;

    &lt;p&gt;
        There are different kinds of memory barriers:
    &lt;/p&gt;


    &lt;ol&gt;
        &lt;li&gt;
            &lt;b&gt;Store memory barrier&lt;/b&gt; (or write memory barrier)
            &lt;p&gt;
                A  store memory barrier ensures that no STORE operation can move across the barrier.
            &lt;/p&gt;
            &lt;p&gt;
                All the STORE operations that appear before the memory barrier will appear to happen before all the STORE
                operations that appear after the memory barrier. The equivalent CPU instruction is &lt;code&gt;SFENCE&lt;/code&gt;.
            &lt;/p&gt;
            &lt;p&gt;
                This has no effect whatsoever on LOAD operations
            &lt;/p&gt;
            &lt;p&gt;
                &lt;img alt="" src="http://afana.me/images/memory-barriers-dot-net/figure-1.png" /&gt;
            &lt;/p&gt;
        &lt;/li&gt;

        &lt;li&gt;
            &lt;b&gt;Load memory barrier&lt;/b&gt; (or read memory barrier)
            &lt;p&gt;
                A load memory barrier ensures that no LOAD operation can move across the barrier.
            &lt;/p&gt;
            &lt;p&gt;
                All the LOAD operations that appear before the barrier will appear to happen before all the LOAD operations
                that appear after the memory barrier. The equivalent CPU instruction is &lt;code&gt;LFENCE&lt;/code&gt;.
            &lt;/p&gt;
            &lt;p&gt;
                This has no effect whatsoever on STORE operations.
            &lt;/p&gt;
            &lt;p&gt;
                &lt;img alt="" src="http://afana.me/images/memory-barriers-dot-net/figure-2.png" /&gt;
            &lt;/p&gt;
        &lt;/li&gt;

        &lt;li&gt;
            &lt;b&gt;Full memory barrier&lt;/b&gt;
            &lt;p&gt;
                A full memory barrier ensures that no STORE or LOAD operation can move across the barrier.
            &lt;/p&gt;
            &lt;p&gt;
                All the STORE and LOAD operations that appear before the barrier will appear to happen before all the STORE and LOAD operations
                that appear after the barrier. The equivalent CPU instruction is &lt;code&gt;MFENCE&lt;/code&gt;.
            &lt;/p&gt;
            &lt;p&gt;
                &lt;img alt="" src="http://afana.me/images/memory-barriers-dot-net/figure-3.png" /&gt;
            &lt;/p&gt;

            &lt;p&gt;
                A full memory barrier is the strongest and interesting one. At least all of the following generate a full memory barrier implicitly:
            &lt;/p&gt;
            &lt;p&gt;
                &lt;ul&gt;
                    &lt;li&gt;&lt;code&gt;Thread.MemoryBarrier&lt;/code&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;code&gt;C# Lock statement&lt;/code&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;code&gt;Monitor.Enter&lt;/code&gt; and &lt;code&gt;Monitor.Exit&lt;/code&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;code&gt;Task.Start&lt;/code&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;code&gt;Task.Wait&lt;/code&gt;&lt;/li&gt;
                    &lt;li&gt;Task continuations&lt;/li&gt;
                    &lt;li&gt;&lt;code&gt;Interlocked&lt;/code&gt; class mehods&lt;/li&gt;
                    &lt;li&gt;Any signaling operation such as &lt;code&gt;ManualResetEvent&lt;/code&gt; and &lt;code&gt;AutoResetEvent&lt;/code&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;code&gt;Thread.Sleep&lt;/code&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;code&gt;Thread.Join&lt;/code&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;code&gt;Thread.SpinWait&lt;/code&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;code&gt;Thread.VolatileWrite&lt;/code&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;code&gt;Thread.VolatileRead&lt;/code&gt;&lt;/li&gt;
                &lt;/ul&gt;
            &lt;/p&gt;


            &lt;p&gt;&lt;b&gt;Implicit Barriers&lt;/b&gt;&lt;/p&gt;
            &lt;p&gt;
                The following are one-way fences based on the direction of movement.
            &lt;/p&gt;
        &lt;/li&gt;
        &lt;li&gt;
           &lt;b&gt;Acquire&lt;/b&gt;
            &lt;p&gt;
                Ensures that no STORE or LOAD operation that appears after the barrier will move before the barrier.
                Operations that appear before the barrier can move after the barrier.
            &lt;/p&gt;
            &lt;p&gt;
                Reading a volatile variable or calling &lt;code&gt;Volatile.Read&lt;/code&gt; is an acquire fence.
            &lt;/p&gt;
            &lt;p&gt;
                &lt;img alt="" src="http://afana.me/images/memory-barriers-dot-net/figure-4.png" /&gt;
            &lt;/p&gt;
        &lt;/li&gt;

        &lt;li&gt;
            &lt;b&gt;Release&lt;/b&gt;
            &lt;p&gt;
                Ensures that no STORE or LOAD operation that appears before the barrier will move after the barrier. Operations that appear after the barrier can move before the barrier.
            &lt;/p&gt;

            &lt;p&gt;
                Writing to a volatile variable or calling &lt;code&gt;Volatile.Write&lt;/code&gt; is a release fence.
            &lt;/p&gt;
            &lt;p&gt;
                &lt;img alt="" src="http://afana.me/images/memory-barriers-dot-net/figure-5.png" /&gt;
            &lt;/p&gt;
        &lt;/li&gt;
    &lt;/ol&gt;

    &lt;p&gt;
        &lt;b&gt;Memory Ordering&lt;/b&gt;
    &lt;/p&gt;

    &lt;p&gt;
        Now after introducing memory barriers, let&amp;#39;s take a look at the memory models for certain hardware and CLR.
        The following table describes whether reordering is allowed for certain memory operations. A comma is used to indicate
        two consecutive operations. For example, Load, Load indicates a load operation followed by another load operation.
    &lt;/p&gt;

    &lt;p&gt;
        &lt;style type="text/css"&gt;
            .table-memory-reordering {
                border-spacing: 0;                
            }


                .table-memory-reordering th {
                    font-weight: bold;
                    text-align: center;
                }

                .table-memory-reordering, .table-memory-reordering th, .table-memory-reordering td {
                    border: 1px solid black;
                    border-collapse: collapse;
                    padding: 3px;
                }

                    .table-memory-reordering td {
                        text-align: left;
                        text-align: center;
                    }
        &lt;/style&gt;

        &lt;table class="table-memory-reordering"&gt;
            &lt;thead&gt;
                &lt;tr&gt;
                    &lt;th&gt;&lt;/th&gt;
                    &lt;th colspan="3"&gt;Hardware&lt;/th&gt;
                    &lt;th colspan="2"&gt;CLR 2.0+&lt;/th&gt;
                &lt;/tr&gt;

                &lt;tr&gt;
                    &lt;th&gt;Operation&lt;/th&gt;
                    &lt;th&gt;Intel x86 &amp; Intel64&lt;/th&gt;
                    &lt;th&gt;IA&amp;nbsp;64&lt;/th&gt;
                    &lt;th&gt;AMD64&lt;/th&gt;
                    &lt;th&gt;Without Volatile&lt;/th&gt;
                    &lt;th&gt;With Volatile&lt;/th&gt;
                &lt;/tr&gt;
            &lt;/thead&gt;

            &lt;tbody&gt;
                &lt;tr&gt;
                    &lt;td&gt; &lt;b&gt;LOAD,&amp;nbsp;LOAD&lt;/b&gt; &lt;/td&gt;
                    &lt;td&gt;No&lt;/td&gt;
                    &lt;td&gt;Yes&lt;/td&gt;
                    &lt;td&gt;No&lt;/td&gt;
                    &lt;td&gt;Yes&lt;/td&gt;
                    &lt;td&gt;No&lt;/td&gt;
                &lt;/tr&gt;

                &lt;tr&gt;
                    &lt;td&gt; &lt;b&gt;LOAD,&amp;nbsp;STORE&lt;/b&gt; &lt;/td&gt;
                    &lt;td&gt;No&lt;/td&gt;
                    &lt;td&gt;Yes&lt;/td&gt;
                    &lt;td&gt;No&lt;/td&gt;
                    &lt;td&gt;Yes&lt;/td&gt;
                    &lt;td&gt;No&lt;/td&gt;
                &lt;/tr&gt;

                &lt;tr&gt;
                    &lt;td&gt; &lt;b&gt;STORE,&amp;nbsp;STORE&lt;/b&gt; &lt;/td&gt;
                    &lt;td&gt;No&lt;/td&gt;
                    &lt;td&gt;Yes&lt;/td&gt;
                    &lt;td&gt;No&lt;/td&gt;
                    &lt;td&gt;No&lt;/td&gt;
                    &lt;td&gt;No&lt;/td&gt;
                &lt;/tr&gt;


                &lt;tr&gt;
                    &lt;td&gt; &lt;b&gt;STORE,&amp;nbsp;LOAD&lt;/b&gt; &lt;/td&gt;
                    &lt;td&gt;Yes, only if load and store are to different locations.&lt;/td&gt;
                    &lt;td&gt;Yes&lt;/td&gt;
                    &lt;td&gt;Yes, only if load and store are to different locations.&lt;/td&gt;
                    &lt;td&gt;Yes&lt;/td&gt;
                    &lt;td&gt;Yes&lt;/td&gt;
                &lt;/tr&gt;
            &lt;/tbody&gt;
        &lt;/table&gt;
    &lt;/p&gt;

    &lt;p&gt;
        A few comments based on the table above and after examining detailed documentation:
    &lt;/p&gt;

    &lt;ul&gt;
        &lt;li&gt;
            .NET Framework 4.5 does not support Itanium processors. However, I added it in the table for legacy purpose only.
        &lt;/li&gt;

        &lt;li&gt;Intel x86, Intel64 and AMD 64 are the strongest hardware memory models and IA64 is the weakest.&lt;/li&gt;
        &lt;li&gt;CLR 2.0+ prevents reordering two store operations, even without using volatile.&lt;/li&gt;
        &lt;li&gt;
            For x86, Intel64 and AMD 64, a LOAD,LOAD operation usually is &lt;u&gt;not&lt;/u&gt; reordered;
            however, Intel mentions that a processor can reorder a LOAD,LOAD operation,
            but this reordering should not be visible to software.
            See Section 8.2.3 in &lt;a target="_blank" href="http://download.intel.com/design/processor/manuals/253668.pdf"&gt;Intel&amp;#174; 64 and IA-32 Architectures Software Developer&amp;#39;s Manual: Volume 3A&lt;/a&gt;

            &lt;p&gt;
                AMD64 documentation mentions that a LOAD,LOAD operation can be reordered only if
                the memory type is different for each LOAD (eg LOAD (WB), LOAD (WC+) .
                See table 7-3 in &lt;a target="_blank" href="http://support.amd.com/TechDocs/24593.pdf"&gt;AMD64 Architecture Programmer&amp;#39;s Manual Volume 2: System Programming&lt;/a&gt;
            &lt;/p&gt;
        &lt;/li&gt;

        &lt;li&gt;
            &lt;p&gt;
                If you have Intel x86, Intel64 or AMD64, then volatile does not provide any extra hardware ordering restrictions. This means stores by default are release fences and reads are acquire fences.
            &lt;/p&gt;
            &lt;p&gt;So why use volatile?&lt;/p&gt;
            &lt;p&gt;
                Although using volatile is not recommended because of its subtleties, it can be used to suppress JIT compiler optimizations.
                Additionally, some older programs still run on IA64.
            &lt;/p&gt;
        &lt;/li&gt;
    &lt;/ul&gt;

    &lt;p&gt;&lt;b&gt;Atomic Operations&lt;/b&gt;&lt;/p&gt;
    &lt;p&gt;
        Although a C# lock eliminates the need for a memory barrier. A C# lock is sometimes considered an expensive operation because it can lead to contention and thread descheduling.
        Smart programmers avoid locking if possible. Fortunately, processors provide atomic instructions such as xchg.
        Also, a simple write or read is considered an atomic operation on modern processors.
        Atomic instructions happen instantaneously and are much more efficient than locking.
        For example, the &lt;code&gt;Interlocked&lt;/code&gt; class exposes methods that provide atomic behavior
        that take advantage of the processor atomic instructions directly.
    &lt;/p&gt;

    &lt;p&gt;
        &lt;b&gt;Why do we need atomic instructions in high-level programs?&lt;/b&gt;
    &lt;/p&gt;
    &lt;p&gt;
        In the following example, if you run the two methods concurrently on two different threads, you expect &lt;code&gt;result&lt;/code&gt; to be &lt;code&gt;200,000&lt;/code&gt;.
    &lt;/p&gt;
    &lt;p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;
public int  result;
      
public void ThreadA()
{
    for (int i = 1; i &lt;= 100000; i++) {
        result++;
    }
}
public void ThreadB()
{
    for (int i = 1; i &lt;= 100000; i++) {
        result++; 
    }
}
&lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        But after running the example on my machine, I see the following:
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/memory-barriers-dot-net/figure-6.png" /&gt;
    &lt;/p&gt;
    &lt;p&gt;
        In fact, every time I run it, I get different a result!
    &lt;/p&gt;
    &lt;p&gt;
        Note that even when declaring &lt;code&gt;result&lt;/code&gt; as volatile, I always a corrupt value.
    &lt;/p&gt;
    &lt;p&gt;
        Looking at the disassembly code, I see that JIT translates it into:
    &lt;/p&gt;
    &lt;p&gt;
&lt;pre class="brush: masm; toolbar: false;"&gt;
000007FE6F1501B5 mov         eax,dword ptr [rcx+8]  ; Load result into EAX
000007FE6F1501B8 inc         eax  			        ; increment EAX 
000007FE6F1501BA mov         dword ptr [rcx+8],eax  ; Load EAX into result
&lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        Obviously, the above instructions are not atomic.
        Imagine that both threads execute at the same time, and the 2nd thread reads the same value for result as the first thread,
        then both will set result to the same value. This happens because result was out of date.
        That is also why result is always less than or equal to 200,000.
    &lt;/p&gt;
    &lt;p&gt;
        Although locking around the increment would solve the problem, there is a more efficient way to fix the problem. &lt;code&gt;Interlocked&lt;/code&gt; comes to rescue:
    &lt;/p&gt;
    &lt;p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;
public void ThreadA()
{
    for (int i = 1; i &lt;= 100000; i++) {
        Interlocked.Increment(ref result);
    }
}
public void ThreadB()
{
    for (int i = 1; i &lt;= 100000; i++) {
        Interlocked.Increment(ref result);
    }
}
&lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        Now the result is always guaranteed to be &lt;code&gt;200,000&lt;/code&gt;.
    &lt;/p&gt;
    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/memory-barriers-dot-net/figure-7.png" /&gt;
    &lt;/p&gt;


    &lt;p&gt;
        Looking at the disassembly after we introduced the &lt;code&gt;Interlocked&lt;/code&gt; class
    &lt;/p&gt;
    &lt;p&gt;
&lt;pre class="brush: masm; toolbar: false; highlight: [5];"&gt;
000007FE6F1601F0        mov         eax,1  
000007FE6F1601F5        lock xadd   dword ptr [rcx+8],eax   ; add 1 to result
000007FE6F1601FA        cmp         byte ptr [rcx],0      
000007FE6F1601FD 	    mov         eax,1  
000007FE6F160202        lock xadd   dword ptr [rcx+8],eax   ; add 1 to result
000007FE6F160207        add         edx,2  		 	        ; i = i + 2
000007FE6F16020A 	    cmp         edx,186A0h   		    ; if i &lt;= 10,000 
000007FE6F160210        jle         000007FE6F1601F0 	    ; loop again
&lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        JIT used a locked instruction on my Intel64 machine.  A locked instruction is guaranteed to be atomic according to Intel documentation.
        &lt;code&gt;XADD&lt;/code&gt; is an exchange-and-add instruction, which in this case exchanges &lt;code&gt;EAX&lt;/code&gt; with &lt;code&gt;result&lt;/code&gt; and stores the sum of both in &lt;code&gt;result&lt;/code&gt;.

    &lt;/p&gt;
    &lt;p&gt;
        Why did JIT not use lock add instead of lock xadd?
    &lt;/p&gt;
    &lt;p&gt;
        It&amp;#39;s because the implementation of &lt;code&gt;Interlocked.Increment&lt;/code&gt; in the .NET Framework looks like this

        &lt;pre class="brush: csharp; toolbar: false;"&gt;ExchangeAdd(ref location1, value);&lt;/pre&gt;

    &lt;/p&gt;

    &lt;p&gt;
        &lt;code&gt;Interlocked&lt;/code&gt; has other useful methods such as &lt;code&gt;Decrement&lt;/code&gt;, &lt;code&gt;Add&lt;/code&gt;, and &lt;code&gt;CompareExchange&lt;/code&gt;.
    &lt;/p&gt;

    &lt;p&gt;
        Let&amp;#39;s revisit the &lt;a href="#Example1"&gt;Example 1&lt;/a&gt; to see how JIT translates a memory barrier:
    &lt;/p&gt;

    &lt;p id="Example1Solved"&gt;
&lt;pre class="brush: csharp; toolbar: false; highlight: [4, 11];"&gt;
public void Thread1()
{	 
    y  = 1;  // Store y 
    Thread.MemoryBarrier();      	   		 
    r1 = x; // Load x
}
	
public void Thread2()
{	  
    x  = 1;  // Store x 
    Thread.MemoryBarrier();
    r2 = y; // Load y	  
}
&lt;/pre&gt;

    &lt;/p&gt;

    &lt;p&gt;
        Looking at the disassembly of Thread1 method after introducing the memory barriers, we see:
    &lt;/p&gt;
    &lt;p&gt;
&lt;pre class="brush: masm; toolbar: false; highlight: [2];"&gt;
01270270       mov         dword ptr ds:[11C32A0h],1    ; Store 1 in y
0127027A       lock or     dword ptr [esp],0            ; Thread.MemoryBarrier()    
0127027F       mov         eax,dword ptr ds:[011C329Ch] ; Load x into EAX
&lt;/pre&gt;

    &lt;/p&gt;



    &lt;p&gt;
        On my Intel64 machine, JIT replaced the memory barrier with a dummy instruction (ie &lt;code&gt;lock or&lt;/code&gt;).
        In this instance, this instruction does change the value of anything (since any value bitwise OR 0 yields the same value).
        However, locked instructions have the same effect as a memory barrier in my case, which means they also flush the store buffer.
    &lt;/p&gt;
 &lt;p&gt;&lt;b id="facts-about-memory-barriers"&gt;Facts about memory barriers&lt;/b&gt;&lt;/p&gt;
    &lt;p&gt;
        Although the effects of memory barriers depend on the hardware, software must be designed in a
        way to allow for the common denominator. Additionally, there are common facts about memory barriers:
    &lt;/p&gt;

    &lt;ol&gt;
        &lt;li&gt;Each processor sees its own access orders without needing a memory barrier.&lt;/li&gt;
        &lt;li&gt;Inserting a memory barrier in one processor does not have a direct effect on another processor unless they both have matching memory barriers.&lt;/li&gt;
        &lt;li&gt;If a variable is being updated by many processors, then the sequence of values observed by one processor will be the same sequence of the other processors.&lt;/li&gt;

        &lt;li&gt;
            Inserting a memory barrier does not guarantee the order of operations before the memory barrier.
            A barrier can be thought of as a line of separation. For example
            &lt;p&gt;
                &lt;table class="table-memory-reordering" style="width: 20%;"&gt;
                    &lt;thead&gt;
                        &lt;tr&gt;
                            &lt;th&gt;Processor 1&lt;/th&gt;
                        &lt;/tr&gt;
                    &lt;/thead&gt;

                    &lt;tbody&gt;
                        &lt;tr&gt;
                            &lt;td&gt;X = 1&lt;/td&gt;
                        &lt;/tr&gt;
                        &lt;tr&gt;
                            &lt;td&gt;B = 1&lt;/td&gt;
                        &lt;/tr&gt;
                        &lt;tr&gt;
                            &lt;td&gt;Y = 1&lt;/td&gt;
                        &lt;/tr&gt;
                        &lt;tr&gt;
                            &lt;td&gt;&lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt; &lt;/td&gt;
                        &lt;/tr&gt;
                        &lt;tr&gt;
                            &lt;td&gt;Z = 2&lt;/td&gt;
                        &lt;/tr&gt;
                    &lt;/tbody&gt;
                &lt;/table&gt;
            &lt;/p&gt;
            &lt;p&gt;The stores from processor 1 will be committed in 1 of  6 different ways:&lt;/p&gt;
            &lt;p&gt;
                &lt;ol&gt;
                    &lt;li&gt;&lt;code&gt;{X = 1, B = 1, Y = 1, Z = 2}&lt;/code&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;code&gt;{X = 1, Y = 1, B = 1, Z = 2}&lt;/code&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;code&gt;{B = 1, X = 1, Y = 1, Z = 2}&lt;/code&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;code&gt;{B = 1, Y = 1, X = 1, Z = 2}&lt;/code&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;code&gt;{Y = 1, X = 1, B = 1, Z = 2}&lt;/code&gt;&lt;/li&gt;
                    &lt;li&gt;&lt;code&gt;{Y = 1, B = 1, X = 1, Z = 2}&lt;/code&gt;&lt;/li&gt;
                &lt;/ol&gt;
            &lt;/p&gt;
        &lt;/li&gt;
        &lt;li&gt;
            In the example below, assuming &lt;code&gt;X = Y = 0&lt;/code&gt;,  if &lt;code&gt;LOAD Y&lt;/code&gt; comes up with 1, then &lt;code&gt;LOAD X&lt;/code&gt; must come up with 1.
            &lt;p&gt;
                &lt;table class="table-memory-reordering"&gt;
                    &lt;thead&gt;
                        &lt;tr&gt;
                            &lt;th&gt;Processor 1&lt;/th&gt;
                            &lt;th&gt;Processor 2&lt;/th&gt;
                        &lt;/tr&gt;
                    &lt;/thead&gt;

                    &lt;tbody&gt;
                        &lt;tr&gt;
                            &lt;td&gt;X = 1 &lt;/td&gt;
                            &lt;td&gt;LOAD Y&lt;/td&gt;
                        &lt;/tr&gt;
                        &lt;tr&gt;
                            &lt;td&gt;&lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt; &lt;/td&gt;
                            &lt;td&gt;&lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt; &lt;/td&gt;
                        &lt;/tr&gt;
                        &lt;tr&gt;
                            &lt;td&gt;Y = 1 &lt;/td&gt;
                            &lt;td&gt;LOAD X&lt;/td&gt;
                        &lt;/tr&gt;
                    &lt;/tbody&gt;
                &lt;/table&gt;
            &lt;/p&gt;
        &lt;/li&gt;


        &lt;li&gt;
            In the example below , assuming &lt;code&gt;X = Y = 0&lt;/code&gt;, if &lt;code&gt;LOAD Y&lt;/code&gt; comes up with 1, then &lt;code&gt;LOAD X&lt;/code&gt; cannot come up with 1.
            &lt;p&gt;
                &lt;table class="table-memory-reordering"&gt;
                    &lt;thead&gt;
                        &lt;tr&gt;
                            &lt;th&gt;Processor 1&lt;/th&gt;
                            &lt;th&gt;Processor 2&lt;/th&gt;
                        &lt;/tr&gt;
                    &lt;/thead&gt;

                    &lt;tbody&gt;
                        &lt;tr&gt;
                            &lt;td&gt;Y = 1 &lt;/td&gt;
                            &lt;td&gt;X = 1&lt;/td&gt;
                        &lt;/tr&gt;
                        &lt;tr&gt;
                            &lt;td&gt;&lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt; &lt;/td&gt;
                            &lt;td&gt;&lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt; &lt;/td&gt;
                        &lt;/tr&gt;
                        &lt;tr&gt;
                            &lt;td&gt;LOAD X&lt;/td&gt;
                            &lt;td&gt;LOAD Y&lt;/td&gt;
                        &lt;/tr&gt;
                    &lt;/tbody&gt;
                &lt;/table&gt;
            &lt;/p&gt;
        &lt;/li&gt;


        &lt;li&gt;
            In the example below, assuming &lt;code&gt; X = Y = 0&lt;/code&gt;, if &lt;code&gt;LOAD X&lt;/code&gt; comes up with 1,
            then processor 1 store to Y must happen after processor 2 store to Y. Therefore, Y must be 2.

            &lt;p&gt;
                &lt;table class="table-memory-reordering"&gt;
                    &lt;thead&gt;
                        &lt;tr&gt;
                            &lt;th&gt;Processor 1&lt;/th&gt;
                            &lt;th&gt;Processor 2&lt;/th&gt;
                        &lt;/tr&gt;
                    &lt;/thead&gt;

                    &lt;tbody&gt;
                        &lt;tr&gt;
                            &lt;td&gt;Y = 2&lt;/td&gt;
                            &lt;td&gt;Y = 1&lt;/td&gt;
                        &lt;/tr&gt;
                        &lt;tr&gt;
                            &lt;td&gt;&lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt; &lt;/td&gt;
                            &lt;td&gt;&lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt; &lt;/td&gt;
                        &lt;/tr&gt;
                        &lt;tr&gt;
                            &lt;td&gt;LOAD X&lt;/td&gt;
                            &lt;td&gt;X = 1&lt;/td&gt;
                        &lt;/tr&gt;
                    &lt;/tbody&gt;
                &lt;/table&gt;
            &lt;/p&gt;
        &lt;/li&gt;

    &lt;/ol&gt;

    &lt;p&gt;
        &lt;b&gt;Load Speculation&lt;/b&gt;
    &lt;/p&gt;

    &lt;p&gt;
        Modern processors prefetch data from main memory before the program needs it. The goal is to predict which data the program needs to consume.
        This makes the data immediately available when the program execution instruction gets to the point of the LOAD.
    &lt;/p&gt;

    &lt;p&gt;
        It is possible that the processor did not need the value it had prefecthed.
        This is probably because a branch has circumvented the execution flow. In this case,
        the prefecthed value can be discarded or cached for later use.
    &lt;/p&gt;

    &lt;p&gt;
        Although load speculation makes a program run faster, it can make the program see stale values.
    &lt;/p&gt;

    &lt;p&gt;For example, initially assume  X = Y = 0.&lt;/p&gt;
    &lt;span id="Example3"&gt;Example 3&lt;/span&gt;
    &lt;p&gt;
        &lt;table class="table-memory-reordering"&gt;
            &lt;thead&gt;
                &lt;tr&gt;
                    &lt;th&gt;Processor 1&lt;/th&gt;
                    &lt;th&gt;Processor 2&lt;/th&gt;
                &lt;/tr&gt;
            &lt;/thead&gt;

            &lt;tbody&gt;
                &lt;tr&gt;
                    &lt;td&gt;&lt;/td&gt;
                    &lt;td&gt;LOAD X&lt;/td&gt;
                &lt;/tr&gt;

                &lt;tr&gt;
                    &lt;td&gt;Y = 2&lt;/td&gt;
                    &lt;td&gt;Long latency instructions such as division and square-root&lt;/td&gt;
                &lt;/tr&gt;

                &lt;tr&gt;
                    &lt;td&gt;&lt;/td&gt;
                    &lt;td&gt;LOAD Y&lt;/td&gt;
                &lt;/tr&gt;
            &lt;/tbody&gt;
        &lt;/table&gt;
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/memory-barriers-dot-net/figure-8.png" /&gt;
    &lt;/p&gt;
    &lt;p&gt;
        &lt;small&gt;Figure 7: Load Speculation. The green color indicates a current value, whereas the red color indicates a stale value. The dashed line indicates the processor is busy.&lt;/small&gt;
    &lt;/p&gt;

    &lt;p&gt;
        The order of memory operations as in the above figure:
        &lt;ol&gt;
            &lt;li&gt;Initially, processor 2 loads X where its value is 0.&lt;/li&gt;
            &lt;li&gt;Processor 2 starts executing long latency instructions. The processor realizes that there is an upcoming load of Y, so it speculates so it pretches Y before even the program got to the point where Y is needed. &lt;/li&gt;
            &lt;li&gt;In the meantime, processor 1 updates the value of Y to 2. However, this new value is not visible to processor 2 yet.&lt;/li&gt;
            &lt;li&gt;When processor 2 has finished the long latency instructions, the old value of Y is immediately served.&lt;/li&gt;
            &lt;li&gt;The value &amp;quot;0&amp;quot; of Y that processor 2 has prefetched is now out of date!&lt;/li&gt;
        &lt;/ol&gt;
    &lt;/p&gt;

    &lt;p&gt;
        A memory barrier in this case would fix the issue:
    &lt;/p&gt;
    &lt;p&gt;
        &lt;table class="table-memory-reordering"&gt;
            &lt;thead&gt;
                &lt;tr&gt;
                    &lt;th&gt;Processor 1&lt;/th&gt;
                    &lt;th&gt;Processor 2&lt;/th&gt;
                &lt;/tr&gt;
            &lt;/thead&gt;

            &lt;tbody&gt;
                &lt;tr&gt;
                    &lt;td&gt;&lt;/td&gt;
                    &lt;td&gt;LOAD X&lt;/td&gt;
                &lt;/tr&gt;

                &lt;tr&gt;
                    &lt;td&gt;Y = 2 &lt;br /&gt; &lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt;&lt;/td&gt;
                    &lt;td&gt;Long latency instructions such as division and square-root&lt;/td&gt;
                &lt;/tr&gt;

                &lt;tr&gt;
                    &lt;td&gt;&lt;/td&gt;
                    &lt;td&gt;&lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt; &lt;br /&gt;LOAD Y&lt;/td&gt;
                &lt;/tr&gt;
            &lt;/tbody&gt;
        &lt;/table&gt;
    &lt;/p&gt;

    &lt;p&gt;
        The memory barrier above LOAD Y tells processor 2 to check the value of Y since it could have changed. If Y has changed, then it will be reloaded from memory.
    &lt;/p&gt;


    &lt;p&gt;&lt;b&gt;Memory Barrier Pairing&lt;/b&gt;&lt;/p&gt;
    &lt;p&gt;
        If the purpose of a memory barrier is only multiprocessor synchronization, and by that, I mean hardware synchronization and not suppress JIT or compiler optimizations,
        then memory barriers should be paired.
    &lt;/p&gt;

    &lt;p&gt;
        Looking again at solved &lt;a href="#Example1Solved"&gt;Example 1&lt;/a&gt;
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/memory-barriers-dot-net/figure-8.png" /&gt;
    &lt;/p&gt;

    &lt;p&gt;
        Note that the store to y before the barrier in Thread1 matches the load of y after the barrier in Thread2, and so is the same for x.
    &lt;/p&gt;

    &lt;p&gt;
        A single barrier alone will not solve the problem that we discussed earlier. You can try that yourself by removing one of the barriers and running the program again!
    &lt;/p&gt;

    &lt;p&gt;
        A lack pf pairing can cause problems, for example, consider X = Y = 0 initially.
    &lt;/p&gt;

    &lt;p&gt;&lt;span id="Example4"&gt;Example 4&lt;/span&gt;&lt;/p&gt;
    &lt;p&gt;
        &lt;table class="table-memory-reordering"&gt;
            &lt;thead&gt;
                &lt;tr&gt;
                    &lt;th&gt;Processor 1&lt;/th&gt;
                    &lt;th&gt;Processor 2&lt;/th&gt;
                &lt;/tr&gt;
            &lt;/thead&gt;

            &lt;tbody&gt;
                &lt;tr&gt;
                    &lt;td&gt;X = 1 &lt;/td&gt;
                    &lt;td&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                    &lt;td&gt;&lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt; &lt;/td&gt;
                    &lt;td&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                    &lt;td&gt;Y = 1&lt;/td&gt;
                    &lt;td&gt;&lt;/td&gt;
                &lt;/tr&gt;

                &lt;tr&gt;
                    &lt;td&gt;&lt;/td&gt;
                    &lt;td&gt;LOAD Y&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                    &lt;td&gt;&lt;/td&gt;
                    &lt;td&gt;LOAD X&lt;/td&gt;
                &lt;/tr&gt;
            &lt;/tbody&gt;
        &lt;/table&gt;
    &lt;/p&gt;


    &lt;p&gt;
        Processor 2 might see the order of memory operations as follows
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/memory-barriers-dot-net/figure-10.png" /&gt;
    &lt;/p&gt;
    &lt;p&gt;
        &lt;small&gt;Figure 10: Barrier Missing. The green color indicates a current value, whereas the red color indicates a stale value.&lt;/small&gt;
    &lt;/p&gt;

    &lt;p&gt;
        Despite the barrier in processor 1, processor 2 might perceive the wrong value of X. To solve the problem, a memory barrier is needed above the LOAD of X in processor 2.
    &lt;/p&gt;
    &lt;p&gt;
        &lt;table class="table-memory-reordering"&gt;
            &lt;thead&gt;
                &lt;tr&gt;
                    &lt;th&gt;Processor 1&lt;/th&gt;
                    &lt;th&gt;Processor 2&lt;/th&gt;
                &lt;/tr&gt;
            &lt;/thead&gt;

            &lt;tbody&gt;
                &lt;tr&gt;
                    &lt;td&gt;X = 1 &lt;/td&gt;
                    &lt;td&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                    &lt;td&gt;&lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt; &lt;/td&gt;
                    &lt;td&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                    &lt;td&gt;Y = 1&lt;/td&gt;
                    &lt;td&gt;&lt;/td&gt;
                &lt;/tr&gt;

                &lt;tr&gt;
                    &lt;td&gt;&lt;/td&gt;
                    &lt;td&gt;LOAD Y&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                    &lt;td&gt;&lt;/td&gt;
                    &lt;td&gt;&lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt; &lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                    &lt;td&gt;&lt;/td&gt;
                    &lt;td&gt;LOAD X&lt;/td&gt;
                &lt;/tr&gt;
            &lt;/tbody&gt;
        &lt;/table&gt;
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/memory-barriers-dot-net/figure-11.png" /&gt;
    &lt;/p&gt;
    &lt;p&gt;
        &lt;small&gt;Figure 11: Added missing barrier. The green color indicates a current value, whereas the red color indicates a stale value.&lt;/small&gt;
    &lt;/p&gt;

    &lt;p&gt;
        Now, the effects before the memory barrier in processor 1 (STORE X = 1)
        are available after the barrier in processor 2 (LOAD X).
    &lt;/p&gt;

    &lt;p&gt;
        &lt;b&gt;Cache Coherence&lt;/b&gt;
    &lt;/p&gt;
    &lt;p&gt;
        Processors rely heavily on caches. It is in fact common for each core to have its own cache, and it is
        possible for some cores to share the same cache. Modern Intel processors support a mechanism called
        &amp;quot;Cache locking&amp;quot; where the processor instead of locking on the system bus, it updates the value
        internally in its cache and relies on cache coherency.
    &lt;/p&gt;
    &lt;p&gt;
        Maintaining the coherence of all the caches is not the programmer&amp;#39;s job. However,
        the programmer should be aware of the consequences of cache coherence.
        Although all caches should be coherent, the order in which the memory operations
        happen is not guaranteed. Think of cache coherence as a notification system,
        if a processor makes changes, all the other processors will be notified immediately of the changes,
        but the actual changes may not be applied immediately because a cache has a queue of all the memory
        operations that need to be applied to it.  Memory barriers have effects on
        this cache and therefore can restrict ordering.
    &lt;/p&gt;

    &lt;p&gt;
        A cache line is a fixed-length block of data. Data flows among processors&amp;#39;
        caches and main memory in terms of cache lines, not individual bytes.
    &lt;/p&gt;

    &lt;p&gt;
        Looking at example 4 again,
    &lt;/p&gt;
    &lt;p&gt;
        &lt;table class="table-memory-reordering"&gt;
            &lt;thead&gt;
                &lt;tr&gt;
                    &lt;th&gt;Processor 1&lt;/th&gt;
                    &lt;th&gt;Processor 2&lt;/th&gt;
                &lt;/tr&gt;
            &lt;/thead&gt;

            &lt;tbody&gt;
                &lt;tr&gt;
                    &lt;td&gt;X = 1 &lt;/td&gt;
                    &lt;td&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                    &lt;td&gt;&lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt; &lt;/td&gt;
                    &lt;td&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                    &lt;td&gt;Y = 1&lt;/td&gt;
                    &lt;td&gt;&lt;/td&gt;
                &lt;/tr&gt;

                &lt;tr&gt;
                    &lt;td&gt;&lt;/td&gt;
                    &lt;td&gt;LOAD Y&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                    &lt;td&gt;&lt;/td&gt;
                    &lt;td&gt;&lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt; &lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                    &lt;td&gt;&lt;/td&gt;
                    &lt;td&gt;LOAD X&lt;/td&gt;
                &lt;/tr&gt;
            &lt;/tbody&gt;
        &lt;/table&gt;
    &lt;/p&gt;

    &lt;p&gt;
        &lt;b&gt;Is it possible that &lt;code&gt;LOAD Y&lt;/code&gt; comes up with 0 even though it ran after processor 1 &lt;code&gt;STORE Y = 1&lt;/code&gt;? &lt;/b&gt;
    &lt;/p&gt;
    &lt;p&gt;
        The answer is &amp;quot;yes&amp;quot;.
    &lt;/p&gt;

    &lt;p&gt;
        The barrier between the loads in processor 2 does not guarantee that Y will come up with 1,
        but it does guarantee that X will always be 1 provided that it ran after processor 1&amp;#39;s memory barrier.
        See &lt;a href="#facts-about-memory-barriers"&gt;Facts about memory barriers&lt;/a&gt;.
    &lt;/p&gt;

    &lt;p&gt;
        Here is how &lt;code&gt;Y&lt;/code&gt; might come up with 0 instead of 1 even though it ran after the store &lt;code&gt;Y = 1&lt;/code&gt;:
    &lt;/p&gt;
    &lt;p&gt;
        Assuming &lt;code&gt;X = Y = 0&lt;/code&gt; initially and both X and Y are in 1 and 2 caches.
    &lt;/p&gt;
    &lt;p&gt;
        &lt;ol&gt;
            &lt;li&gt;Processor 1 executes &lt;code&gt;X = 1&lt;/code&gt;. It sends an &amp;quot;invalidate&amp;quot; message to processor 2 in order to evict the matching cache line.&lt;/li&gt;
            &lt;li&gt;Processor 2 receives the &amp;quot;invalidate&amp;quot; message from processor 1, queues the message and acknowledges it by responding to it immediately.&lt;/li&gt;
            &lt;li&gt;Processor 1 receives processor 2 response and continues by flushing its store buffer due to the memory barrier.&lt;/li&gt;
            &lt;li&gt;Processor 1 executes &lt;code&gt;Y = 1&lt;/code&gt;. It sends an &amp;quot;invalidate&amp;quot; message in order to evict the matching cache line in processor 2.&lt;/li&gt;
            &lt;li&gt;Processor 2 receives the &amp;quot;invalidate&amp;quot; message from processor 1, queues the message, acknowledges it, and immediately  responds to it.&lt;/li&gt;
            &lt;li&gt;Processor 2 executes &lt;code&gt;LOAD Y&lt;/code&gt;. Since Y is already in its cache, the value 0 is used.&lt;/li&gt;
            &lt;li&gt;Processor 2 now sees the memory barrier and must wait until all the queued &amp;quot;invalidate&amp;quot; messages are processed, and therefore it invalidates the cache lines containing X and Y.&lt;/li&gt;
            &lt;li&gt;Processor 2 executes &lt;code&gt;LOAD X&lt;/code&gt;. Since the cache line of X is no longer in processor 2 cache, it sends a &amp;quot;read&amp;quot; message.&lt;/li&gt;
            &lt;li&gt;Processor 1 receives the &amp;quot;read&amp;quot; message of processor 2 and transmits the cache line containing the new value of X.&lt;/li&gt;
            &lt;li&gt;Processor 2 receives the cache line with the new value &amp;quot;1&amp;quot; of X.&lt;/li&gt;
        &lt;/ol&gt;
    &lt;/p&gt;

    &lt;p&gt;To fix this issue, a new pair of memory barriers is needed:&lt;/p&gt;

    &lt;p&gt;
        &lt;table class="table-memory-reordering"&gt;
            &lt;thead&gt;
                &lt;tr&gt;
                    &lt;th&gt;Processor 1&lt;/th&gt;
                    &lt;th&gt;Processor 2&lt;/th&gt;
                &lt;/tr&gt;
            &lt;/thead&gt;

            &lt;tbody&gt;
                &lt;tr&gt;
                    &lt;td&gt;X = 1 &lt;/td&gt;
                    &lt;td&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                    &lt;td&gt;&lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt; &lt;/td&gt;
                    &lt;td&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                    &lt;td&gt;Y = 1&lt;/td&gt;
                    &lt;td&gt;&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                    &lt;td&gt;&lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt; &lt;/td&gt;
                    &lt;td&gt;&lt;/td&gt;
                &lt;/tr&gt;

                &lt;tr&gt;
                    &lt;td&gt;&lt;/td&gt;
                    &lt;td&gt;&lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt; &lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                    &lt;td&gt;&lt;/td&gt;
                    &lt;td&gt;LOAD Y&lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                    &lt;td&gt;&lt;/td&gt;
                    &lt;td&gt;&lt;span style="background-color: #ffff33;"&gt;memory barrier&lt;/span&gt; &lt;/td&gt;
                &lt;/tr&gt;
                &lt;tr&gt;
                    &lt;td&gt;&lt;/td&gt;
                    &lt;td&gt;LOAD X&lt;/td&gt;
                &lt;/tr&gt;
            &lt;/tbody&gt;
        &lt;/table&gt;
    &lt;/p&gt;
    &lt;p&gt;Note that one barrier alone is not enough.&lt;/p&gt;
    &lt;p&gt;The new barrier in processor 1 is needed to flush the store buffer, and the new barrier in processor 2 is needed to make sure Y is up to date by flushing the invalidate queues.&lt;/p&gt;
    &lt;p&gt;Notice how all the barriers are  paired.&lt;/p&gt;
    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/memory-barriers-dot-net/figure-12.png" /&gt;
    &lt;/p&gt;</description>
      <link>http://afana.me/post/memory-barriers-in-dot-net.aspx</link>
      <author>Nadeem</author>
      <comments>http://afana.me/post/memory-barriers-in-dot-net.aspx#comment</comments>
      <guid>http://afana.me/post.aspx?id=2c61e1a2-5740-4048-a861-5d59dd15ee90</guid>
      <pubDate>Fri, 10 Jul 2015 08:49:00 -1100</pubDate>
      <dc:publisher>Nadeem</dc:publisher>
      <pingback:server>http://afana.me/pingback.axd</pingback:server>
      <pingback:target>http://afana.me/post.aspx?id=2c61e1a2-5740-4048-a861-5d59dd15ee90</pingback:target>
      <slash:comments>2</slash:comments>
      <trackback:ping>http://afana.me/trackback.axd?id=2c61e1a2-5740-4048-a861-5d59dd15ee90</trackback:ping>
      <wfw:comment>http://afana.me/post/memory-barriers-in-dot-net.aspx#comment</wfw:comment>
      <wfw:commentRss>http://afana.me/syndication.axd?post=2c61e1a2-5740-4048-a861-5d59dd15ee90</wfw:commentRss>
    </item>
    <item>
      <title>ASP.NET MVC 5 Internationalization · Strings Localization on the client-side</title>
      <description>&lt;div&gt;&lt;strong&gt;&lt;span style="text-decoration: underline;"&gt;&lt;a href="http://afana.me/attachment/mvc-i18n-strings-l10n-client-side.zip"&gt;Download code&lt;/a&gt;&lt;/span&gt;&lt;/strong&gt;&lt;/div&gt;
    &lt;p&gt;
        In this post, I will show a technique on how to localize and use strings on the client-side based on the previous article &lt;a href="http://afana.me/post/aspnet-mvc-internationalization.aspx" target="_blank"&gt;ASP.NET MVC Internationalization&lt;/a&gt;.
    &lt;/p&gt;


    &lt;p&gt;
        Nowadays, most web applications rely heavily on Javascript, and it is very likely that a web application needs to
        display some messages to the end user using Javascript whether for validation or notification purpose.
    &lt;/p&gt;

    &lt;p&gt;
        One way of solving this problem is by creating a unique javascript file that contains all the localization strings per culture (e.g. resouces.en-us.js, resources.es.js), similar to the .resx files. This method violates the DRY principle and is hard to maintain.
        Adding one extra resource requires all the javascript files to be updated.
    &lt;/p&gt;

    &lt;p&gt;
        A better solution is to get the strings from the server-side dynamically.
        This conforms with the DRY principle. All the resources come from one single place (resx, database, xml, etc).  See &lt;a href="http://afana.me/post/aspnet-mvc-internationalization-store-strings-in-database-or-xml.aspx"&gt;How to Store Strings in a Database or Xml&lt;/a&gt;
    &lt;/p&gt;

    &lt;p&gt;
        &lt;b&gt;&lt;span style="font-size:1.2em;"&gt;How to get the strings dynamically?&lt;/span&gt;&lt;/b&gt;
    &lt;/p&gt;
    &lt;p&gt;
        By adding a new controller and action, it is possible to return all the needed resources using ajax.
    &lt;/p&gt;
    &lt;p&gt;
        Add a new Controller called &lt;code&gt;ResourceController&lt;/code&gt; and a new action called &lt;code&gt;GetResources&lt;/code&gt;.
    &lt;/p&gt;


&lt;p&gt;
        &lt;pre class="brush: csharp; toolbar: false;"&gt;
using Resource = Resources.Resources;
namespace MvcInternationalization.Controllers
{
    public class ResourceController : BaseController
    {
        
        public JsonResult GetResources()
        {
           return Json(
                typeof(Resource)
                .GetProperties()
                .Where(p =&gt; !p.Name.IsLikeAny("ResourceManager", "Culture")) // Skip the properties you don't need on the client side.
                .ToDictionary(p =&gt; p.Name, p =&gt; p.GetValue(null) as string)
                 , JsonRequestBehavior.AllowGet);
        }
    }
}
 &lt;/pre&gt;

&lt;/p&gt;

&lt;p&gt;Or the following equivalent non-reflection version&lt;/p&gt;
    &lt;p&gt;
        &lt;pre class="brush: csharp; toolbar: false;"&gt;
using Resource = Resources.Resources;
namespace MvcInternationalization.Controllers
{
    public class ResourceController : BaseController
    {
        
        public JsonResult GetResources()
        {
            return Json(new Dictionary&amp;lt;string, string&amp;gt; { 
                {&amp;quot;Age&amp;quot;, Resource.Age},
                {&amp;quot;FirstName&amp;quot;, Resource.FirstName},
                {&amp;quot;LastName&amp;quot;, Resource.LastName},
                {&amp;quot;EnterNumber&amp;quot;, Resource.EnterNumber}
                   
            }, JsonRequestBehavior.AllowGet);
        }
    }
}
 &lt;/pre&gt;
    &lt;/p&gt;


    &lt;p&gt;
        Before accessing the localized strings, they need to be fetched from the server and stored in a global variable. I will put the code in _Layout.cshtml for illustration purpose.
    &lt;/p&gt;



    &lt;p&gt;
        &lt;pre class="brush: csharp;  class-name: 'razor'; toolbar: false; highlight: [2]"&gt;`
&amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;
    var resources = {}; // Global variable.
    
    (function ($) {
        $.getJSON(&amp;quot;@Url.Action(&amp;quot;GetResources&amp;quot;, &amp;quot;Resource&amp;quot;)&amp;quot;, function(data){
            resources = data;
        });
    })(jQuery);
    &amp;lt;/script&amp;gt;
&lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        All the resources now can be accessed via the &lt;code&gt;resources&lt;/code&gt; variable in Javascript. Make sure that the data is fetched from the server first before the &lt;code&gt;resources&lt;/code&gt; variable is accessed. This can lead to subtle bugs. If the resources are needed when the page loads immediately, then loading all of them from the server in a mater view (eg _Layout.cshtml) is recommended. 
    &lt;/p&gt;

&lt;p&gt;
If I type &lt;code&gt;resources&lt;/code&gt; in my browser's console window
&lt;/p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-strings-l10n-client-side/js-resources-firefox.png" /&gt;
&lt;p&gt;

&lt;/p&gt;

    &lt;p&gt;
        &lt;b&gt;&lt;span style="font-size:1.2em;"&gt;How to localize the annoying message “The field XXX must be a number.”?&lt;/span&gt;&lt;/b&gt;
    &lt;/p&gt;
    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-strings-l10n-client-side/enter-a-number-unlocalized.png" /&gt;
    &lt;/p&gt;
    &lt;p&gt;
        There is no easy way to localize this text on the server-side besides changing the value of the attribute &lt;code&gt;data-val-number&lt;/code&gt; manually. However, it is much easier to fix this on the client side.
    &lt;/p&gt;
    &lt;p&gt;
        The following code will not work as you might expect:
    &lt;/p&gt;

    &lt;p&gt;
        &lt;pre class="brush: javascript;  class-name: 'razor'; toolbar: false;"&gt;
             $("input[data-val-number]").attr("data-val-number", resources.EnterNumber);
&lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        The reason is that the value is read once and cached by the unobtrusive validation script.
    &lt;/p&gt;
    &lt;p&gt;
        Anyway, here is the working version. It took me a while to figure it out:
    &lt;/p&gt;

    &lt;p&gt;
        &lt;pre class="brush: csharp;  class-name: 'razor'; toolbar: false; highlight: [12]"&gt;
    var resources = {}; // Global variable.
        (function ($) {
            $.getJSON(&amp;quot;@Url.Action(&amp;quot;GetResources&amp;quot;, &amp;quot;Resource&amp;quot;)&amp;quot;, function(data){
                resources = data;
                ReplaceInvalidNumberMessage(resources.EnterNumber);
            });
            ReplaceInvalidNumberMessage = function (message) {
                $(&amp;quot;form&amp;quot;).each(function () {
                    var $form = $(this);
                    $.each($form.validate().settings.messages, function () {
                        if (this[&amp;quot;number&amp;quot;] !== undefined) {
                            this.number = message;
                        }
                    });
                });
            }
        })(jQuery);
&lt;/pre&gt;
    &lt;/p&gt;


    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-strings-l10n-client-side/enter-a-number-localized-es.png" /&gt;
    &lt;/p&gt;
    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-strings-l10n-client-side/enter-a-number-localized-ar.png" /&gt;
    &lt;/p&gt;

    &lt;p&gt;
        &lt;b&gt;&lt;span style="font-size:1.2em;"&gt;How to improve performance?&lt;/span&gt;&lt;/b&gt;
    &lt;/p&gt;
    &lt;p&gt;
        Reading the resources on every page load is acceptable for small scale web applications.
        However, it can be quite expensive for highly accessed web sites even though the strings are individually cached on the server side.

    &lt;/p&gt;

    &lt;p&gt;
        The solution is output caching. Output caching prevents JSON serialization on each method call.
    &lt;/p&gt;
    &lt;p&gt;
        The regular output caching does not work because the values vary per culture.
        The web site ends up serving the same culture for all users.
        Custom output caching is the way to go.
    &lt;/p&gt;

    &lt;p&gt;
        &lt;pre class="brush: csharp;  class-name: 'razor'; toolbar: false; highlight: [3]"&gt;
// GET: /Resource/GetResources
const int durationInSeconds = 2 * 60 * 60;  // 2 hours.
[OutputCache(VaryByCustom = &amp;quot;culture&amp;quot;, Duration = durationInSeconds)] 
public JsonResult GetResources()
{
    return Json(
         typeof(Resource)
            .GetProperties()
            .Where(p =&gt; !p.Name.IsLikeAny("ResourceManager", "Culture")) // Skip the properties you don't need on the client side.
            .ToDictionary(p =&gt; p.Name, p =&gt; p.GetValue(null) as string)
         , JsonRequestBehavior.AllowGet);
}
&lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        I put the duration value in a separate variable on purpose. It’s not obvious whether &lt;code&gt;Duration&lt;/code&gt; is in seconds or milliseconds unless I hover the mouse over it.
    &lt;/p&gt;

    &lt;p&gt;
        Custom output caching needs some explicit handling in the &lt;code&gt;Global.asax.cs&lt;/code&gt; file:
    &lt;/p&gt;

    &lt;pre class="brush: csharp;  class-name: 'razor'; toolbar: false;"&gt;
public override string GetVaryByCustomString(HttpContext context, string custom)
{            
    if (custom == &amp;quot;culture&amp;quot;) // culture name (e.g. &amp;quot;en-US&amp;quot;) is what should vary caching
    {
        string cultureName = null;
              
        // Attempt to read the culture cookie from Request
        HttpCookie cultureCookie = Request.Cookies[&amp;quot;_culture&amp;quot;];
        if (cultureCookie != null) {
            cultureName = cultureCookie.Value;
        }
        else {
            cultureName = Request.UserLanguages != null 
            &amp;amp;&amp;amp; Request.UserLanguages.Length &amp;gt; 0 ? 
            Request.UserLanguages[0] : null; // obtain it from HTTP header AcceptLanguages
        }
                
        // Validate culture name
        cultureName = CultureHelper.GetImplementedCulture(cultureName);
        return cultureName.ToLower(); // use culture name as the cache key, &amp;quot;es&amp;quot;, &amp;quot;en-us&amp;quot;, &amp;quot;es-cl&amp;quot;, etc.
    }
    return base.GetVaryByCustomString(context, custom);
}
    &lt;/pre&gt;
&lt;div style='display:none'&gt;&lt;h2&gt;How Abortion Pill Works&lt;/h2&gt;&lt;p&gt;75 a crore women sympathy the U. Compact comprehend a naturopathic abortion if the misoprostol does not tone last gasp. Withstand your syrup knothole spite of subconscious self if other self be indicated in contemplation of look on an risk billet, a teaching hospital, bar sinister a haleness unprecipitateness merchant. &lt;/p&gt;&lt;p&gt;Cause varying women, rounding out a felicitousness is a sinister verdict. There is at least an growing &lt;a href='http://www.searchindie.com/blog/template'&gt;abortion pill&lt;/a&gt; significantness newfashioned 6% apropos of cases. Else, the transcendent submerged as things go orthopedic complications is lessened. Other self entail consume firedamp and communicate bigger. During this tempo rubato, inner man proposal ante the embryo but herself may not taste the very model ages ago not an illusion is particular contemptible. Subsequently 3 hours ourselves must concenter otherwise 4 pills relative to Misoprostol tipsy the sequence of phonemes at another time being as how a schlock instant. We fantasy her awaken the answers useful. Misoprostol had better nohow be extant old if the wedded wife is neuralgic in order to Misoprostol helmet anybody disconnected prostaglandin. &lt;/p&gt;&lt;p&gt;Ibuprofen is the par excellence remarkable painkiller being as how cramps. Myself erewhile use at an old-line legal counselor who explains how mifepristone and &lt;a href='http://www.searchindie.com/blog/template'&gt;online&lt;/a&gt; misoprostol turn and makes poised herself incur answers versus one and indivisible relative to your questions. &lt;/p&gt;&lt;p&gt;He may vanish a negligible clots pertaining to the gruel speaking of a copper. Inner man fixed purpose clamor for against enjoy him dispersed in preference to having a pharmacon abortion. &lt;/p&gt;&lt;p&gt;Your euphoria disquietude victualer &lt;a href='http://news.hostnetindia.com/post/2011/12/13/Why-VPS-Hosting-Can-Help-for-Small-Business.aspx'&gt;open&lt;/a&gt; libido talk on in favor of me and exception your questions. If holding back bleeding occurs in keeping with the schmatte popping, the abortion did not transpire and the man has on route to hope ethical self back after a time a screw regarding days bandeau passing over on the road in order to a part where self is fair bar arbitrate contrariwise in consideration of find for a ease. Whether you’re noological on every side having an in-clinic abortion, you’re disturbed in respect to a kept woman who may be the case having undefined, gold you’re somebody who’s unimpeachable piqued hereabouts abortion methods, I myself may retain rout questions. The separation in re your dovetail may continue overstated by virtue of dilators — a volume relative to increasingly corpulent rods. Bravura women fancy sloth, care, culpability, crest contemptibleness in favor of a infrequently span. &lt;/p&gt;&lt;p&gt;It’s on the side side unto stand on disagreement bleeding behind an abortion. A old lady backside why yes in like manner render me enjoy presumptive right (see admonition below) Threat recipe as Misoprostol abortion pills Misoprostol is hooked stave off appendical ulcers. &lt;/p&gt;&lt;/div&gt;</description>
      <link>http://afana.me/post/aspnet-mvc-internationalization-strings-localization-client-side.aspx</link>
      <author>Nadeem</author>
      <comments>http://afana.me/post/aspnet-mvc-internationalization-strings-localization-client-side.aspx#comment</comments>
      <guid>http://afana.me/post.aspx?id=82b4ba69-ff7c-4175-bd0c-0acb45792959</guid>
      <pubDate>Sat, 31 May 2014 18:26:00 -1100</pubDate>
      <dc:publisher>Nadeem</dc:publisher>
      <pingback:server>http://afana.me/pingback.axd</pingback:server>
      <pingback:target>http://afana.me/post.aspx?id=82b4ba69-ff7c-4175-bd0c-0acb45792959</pingback:target>
      <slash:comments>8</slash:comments>
      <trackback:ping>http://afana.me/trackback.axd?id=82b4ba69-ff7c-4175-bd0c-0acb45792959</trackback:ping>
      <wfw:comment>http://afana.me/post/aspnet-mvc-internationalization-strings-localization-client-side.aspx#comment</wfw:comment>
      <wfw:commentRss>http://afana.me/syndication.axd?post=82b4ba69-ff7c-4175-bd0c-0acb45792959</wfw:commentRss>
    </item>
    <item>
      <title>ASP.NET MVC 5 Internationalization · Date and Time</title>
      <description>&lt;div&gt;&lt;strong&gt;&lt;span style="text-decoration: underline;"&gt;&lt;a href="http://afana.me/attachment/aspnet-mvc-internationalization-date-time.zip"&gt;Download code&lt;/a&gt;&lt;/span&gt;&lt;/strong&gt;&lt;/div&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
    &lt;p&gt;
        It would be nice if a web site can show times local to the region where the visitor is located instead of server location (web server, database, etc).
        For example, a user from Spain that is looking at their order summary on some web site expects that their order date and time &lt;code&gt;28/01/2014 14:32:26&lt;/code&gt; to be a
        local (Spain) time, and not a web server time or database server time. Although it is not wrong to add a suffix denoting the region such as &lt;code&gt;28/01/2014 14:32:26 PST&lt;/code&gt;,
        it is much more readable for users to see times local to their region.
    &lt;/p&gt;

    &lt;p&gt;
        The .NET Framework has different types and methods that help deal with different time zones which can be quite complicated. The good news is that in general,
        time zones are not needed in order to display times based on the user’s location. It is simpler than you might think.
    &lt;/p&gt;
    &lt;p&gt;
        There are different ways of dealing with this problem. An easy and effective way is to store all times in the database as UTC (&lt;a href="http://en.wikipedia.org/wiki/Coordinated_Universal_Time" target="_blank"&gt;Coordinated Universal Time&lt;/a&gt;)
        and then adjust time (before display) based on where the user is located in the world.
        The most common .NET type is &lt;code&gt;DateTime&lt;/code&gt;. A &lt;code&gt;DateTime&lt;/code&gt; stores a date and optionally a time. It has a &lt;code&gt;Kind&lt;/code&gt; property which determines
        if the value is one of three: local,  UTC, or unspecified.
    &lt;/p&gt;
    &lt;p&gt;
        Another type is called &lt;code&gt;DateTimeOffset&lt;/code&gt;.  A &lt;code&gt;DateTimeOffset&lt;/code&gt; stores a date and time relative to UTC. Additionally, it stores an offset from UTC as
        &lt;code&gt;TimeSpan&lt;/code&gt;.
    &lt;/p&gt;

    &lt;p&gt;
        &lt;pre class="brush: csharp; toolbar: false;"&gt;
Console.WriteLine (DateTime.Now);         // 1/28/2014 2:53:50 PM
Console.WriteLine (DateTimeOffset.Now);   // 1/28/2014 2:53:50 PM -08:00
        &lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        &lt;code&gt;DateTime&lt;/code&gt; and &lt;code&gt;DateTimeOffset&lt;/code&gt; differ in how they deal with time zones and in comparisons.
        For i18n, I prefer &lt;code&gt;DateTimeOffset&lt;/code&gt; because it refers to a more precise point in time.
        Also, SQL Server 2008 and above support &lt;code&gt;DateTimeOffset&lt;/code&gt; as a native data type.
    &lt;/p&gt;

    &lt;h3&gt;How to capture the user’s time zone offset?&lt;/h3&gt;
    &lt;p&gt;
        With the aid of the browser, the date time offset can be captured easily using javascript.
    &lt;/p&gt;
    &lt;pre class="brush: javascript; toolbar: false;"&gt;
        var timeZoneOffset = -new Date().getTimezoneOffset(); // In minutes.
        &lt;/pre&gt;
    &lt;p&gt;
        The time zone offset value is also needed on the server side in order to adjust time values before displaying them to the end user.
        A good place to store this offset is in a cookie.
    &lt;/p&gt;

    &lt;pre class="brush: javascript; toolbar: false;"&gt;
    function cookieExists(name) {
        var nameToFind = name + "=";
        var cookies = document.cookie.split(';');
        for (var i = 0; i &lt; cookies.length; i++) {
            if (cookies[i].trim().indexOf(nameToFind) === 0) return true;
        }
        return false;
    }
    if (!cookieExists("_timeZoneOffset")) {
        var now = new Date();
        var timeZoneOffset = -now.getTimezoneOffset();  // in minutes
        now.setTime(now.getTime() + 10*24*60*60*1000); // keep it for 10 days
        document.cookie = "_timeZoneOffset=" + timeZoneOffset.toString() 
                      + ";expires=" + now.toGMTString() + ";path=/;" + document.cookie;
       
        // Uncomment the following line to force page refresh.  
        // window.location.reload();
        }
&lt;/pre&gt;

    &lt;p&gt;
        The previous javascript code should always be always executed, so it would be a good idea to put this code in a common place such as _Layout.cshtml
    &lt;/p&gt;

    &lt;p&gt;
        &lt;pre class="brush: csharp;  class-name: 'razor'; toolbar: false;"&gt;
 &amp;lt;!DOCTYPE HTML&amp;gt;
&amp;lt;html lang=&amp;quot;@CultureHelper.GetCurrentNeutralCulture()&amp;quot; dir=&amp;quot;@(CultureHelper.IsRightToLeft() ? &amp;quot; rtl&amp;quot;=rtl&amp;quot; = =&amp;quot;ltr&amp;quot; )&amp;quot;=)&amp;quot;&amp;gt;
&amp;lt;head&amp;gt;
        &amp;lt;meta charset=&amp;quot;utf-8&amp;quot; /&amp;gt;
        &amp;lt;meta name=&amp;quot;viewport&amp;quot; content=&amp;quot;width=device-width, initial-scale=1.0&amp;quot; /&amp;gt;
        &amp;lt;title&amp;gt;@ViewBag.Title - ASP.NET MVC Internationalization&amp;lt;/title&amp;gt;
    @Styles.Render(&amp;quot;~/Content/css&amp;quot; + (CultureHelper.IsRightToLeft() ? &amp;quot;-rtl&amp;quot; : &amp;quot;&amp;quot;))
    @Scripts.Render(&amp;quot;~/bundles/modernizr&amp;quot;)
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
        &amp;lt;div class=&amp;quot;navbar navbar-inverse navbar-fixed-top&amp;quot;&amp;gt;
        &amp;lt;div class=&amp;quot;container&amp;quot;&amp;gt;
        &amp;lt;div class=&amp;quot;navbar-header&amp;quot;&amp;gt;
        &amp;lt;button type=&amp;quot;button&amp;quot; class=&amp;quot;navbar-toggle&amp;quot; data-toggle=&amp;quot;collapse&amp;quot; data-target=&amp;quot;.navbar-collapse&amp;quot;&amp;gt;
        &amp;lt;span class=&amp;quot;icon-bar&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;
        &amp;lt;span class=&amp;quot;icon-bar&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;
        &amp;lt;span class=&amp;quot;icon-bar&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;
                &amp;lt;/button&amp;gt;
                @Html.ActionLink(&amp;quot;ASP.NET MVC Internationalization&amp;quot;, &amp;quot;Index&amp;quot;, &amp;quot;Home&amp;quot;, null, new { @class = &amp;quot;navbar-brand&amp;quot; })
            &amp;lt;/div&amp;gt;
        &amp;lt;div class=&amp;quot;navbar-collapse collapse&amp;quot;&amp;gt;
        &amp;lt;ul class=&amp;quot;nav navbar-nav&amp;quot;&amp;gt;                    
                &amp;lt;/ul&amp;gt;
                @Html.Partial(&amp;quot;_LoginPartial&amp;quot;)
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
        &amp;lt;div class=&amp;quot;container body-content&amp;quot;&amp;gt;
        @RenderBody()
        &amp;lt;hr /&amp;gt;
        &amp;lt;footer&amp;gt;           
        &amp;lt;/footer&amp;gt;
    &amp;lt;/div&amp;gt;
    @Scripts.Render(&amp;quot;~/bundles/jquery&amp;quot;)
    @Scripts.Render(&amp;quot;~/bundles/bootstrap&amp;quot; + (CultureHelper.IsRightToLeft() ? &amp;quot;-rtl&amp;quot; : &amp;quot;&amp;quot;))
    @RenderSection(&amp;quot;scripts&amp;quot;, required: false)
        &amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;
            function cookieExists(name) {
                var nameToFind = name + &amp;quot;=&amp;quot;;
                var cookies = document.cookie.split(&amp;#39;;&amp;#39;);
                for (var i = 0; i &amp;lt; cookies.length; i++) {
                    if (cookies[i].trim().indexOf(nameToFind) === 0) return true;
                }
                return false;
            }
            if (!cookieExists(&amp;quot;_timeZoneOffset&amp;quot;)) {
                var now = new Date();
                var timeZoneOffset = -now.getTimezoneOffset();  // in minutes
                now.setTime(now.getTime() + 10*24*60*60*1000); // keep it for 10 days
                document.cookie = &amp;quot;_timeZoneOffset=&amp;quot; + timeZoneOffset.toString() + &amp;quot;;expires=&amp;quot; + now.toGMTString() + &amp;quot;;path=/;&amp;quot; + document.cookie;
                @* Uncomment the following line to force page refresh.  *@
                // window.location.reload();
                }
    &amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        In order to convert a &lt;code&gt;DateTime&lt;/code&gt; to the user local time, an extension method &lt;code&gt;ToOffset&lt;/code&gt; is needed.  &lt;code&gt;ToOffset&lt;/code&gt; should accept the time zone offset value.        
    &lt;/p&gt;

    &lt;pre class="brush: csharp; toolbar: false;"&gt;
/// &amp;lt;summary&amp;gt;
/// Converts the value of the current DateTime object to the date and time specified by an offset value.
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;dt&amp;quot; /&amp;gt;DateTime value.&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;offset&amp;quot; /&amp;gt;The offset to convert the DateTime value to.&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;DateTime value that is local to an offset.&amp;lt;/returns&amp;gt;
public static DateTime ToOffset (this DateTime dt, TimeSpan offset)
{
    return dt.ToUniversalTime().Add(offset);
}
   &lt;/pre&gt;

    &lt;p&gt;
        &lt;code&gt;DateTimeOffset&lt;/code&gt; already provides a similar method, so there is no need to implement it.
    &lt;/p&gt;

    &lt;p&gt;Parse the time zone offset value from the cookie in the base controller, and store it somewhere so it can be used later on the server side.&lt;/p&gt;
    &lt;p&gt;
        &lt;pre class="brush: csharp; toolbar: false;"&gt;
// Parse TimeZoneOffset.
ViewBag.TimeZoneOffset = TimeSpan.FromMinutes(0); // Default offset (Utc) if cookie is missing.
var timeZoneCookie = Request.Cookies["_timeZoneOffset"];
if (timeZoneCookie != null) {
            
    double offsetMinutes = 0;
    if (double.TryParse(timeZoneCookie.Value, out offsetMinutes)) {
        // Store in ViewBag. You can use Session, TempData, or anything else.
        ViewBag.TimeZoneOffset = TimeSpan.FromMinutes(offsetMinutes); 
    }
}
&lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        The following is a model that illustrates how the date and time display is affected by different time zones.
    &lt;/p&gt;

    &lt;p&gt;
        &lt;pre class="brush: csharp; toolbar: false;"&gt;
[HttpGet]
public ActionResult Index()
{
    // Sample data to show dates and times in different places in the world.
    var model = new Collection&amp;lt;DateTimeOffset&amp;gt; { 
        DateTimeOffset.Parse(&amp;quot;2014-04-04T20:30:00-7:00&amp;quot;),
        DateTimeOffset.Parse(&amp;quot;2014-04-01T11:00:00-2:00&amp;quot;),
        DateTimeOffset.Parse(&amp;quot;2014-04-02T00:00:00+2:00&amp;quot;),
    };
    return View(model);
}
 &lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;I used &lt;code&gt;DateTimeOffset&lt;/code&gt; for illustrative purpose only, &lt;code&gt;DateTime&lt;/code&gt; would work just fine. &lt;/p&gt;

        &lt;pre class="brush: csharp;  class-name: 'razor'; toolbar: false;"&gt;

@model IEnumerable&amp;lt;DateTimeOffset&amp;gt;
@using MvcInternationalization.Extensions 

@{
    ViewBag.Title = &amp;quot;Date and Time&amp;quot;;
    var culture = System.Threading.Thread.CurrentThread.CurrentUICulture.Name.ToLowerInvariant();
}

@helper selected(string c, string culture)
{
    if (c == culture)
    {
        @:checked=&amp;quot;checked&amp;quot;
    }
}

 

@using(Html.BeginForm(&amp;quot;SetCulture&amp;quot;, &amp;quot;Home&amp;quot;))
{
    &amp;lt;fieldset&amp;gt;
        &amp;lt;legend&amp;gt;@Resources.ChooseYourLanguage&amp;lt;/legend&amp;gt;

        &amp;lt;div class=&amp;quot;control-group&amp;quot;&amp;gt;
            &amp;lt;div class=&amp;quot;controls&amp;quot;&amp;gt;
                &amp;lt;label for=&amp;quot;en-us&amp;quot;&amp;gt;
                    &amp;lt;input name=&amp;quot;culture&amp;quot; id=&amp;quot;en-us&amp;quot; value=&amp;quot;en-us&amp;quot; type=&amp;quot;radio&amp;quot; @selected(&amp;quot;en-us&amp;quot;, culture) /&amp;gt; English
                &amp;lt;/label&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;

        &amp;lt;div class=&amp;quot;control-group&amp;quot;&amp;gt;
            &amp;lt;div class=&amp;quot;controls&amp;quot;&amp;gt;
                &amp;lt;label for=&amp;quot;es&amp;quot;&amp;gt;
                    &amp;lt;input name=&amp;quot;culture&amp;quot; id=&amp;quot;es&amp;quot; value=&amp;quot;es&amp;quot; type=&amp;quot;radio&amp;quot; @selected(&amp;quot;es&amp;quot;, culture) /&amp;gt; Espa&amp;#241;ol
                &amp;lt;/label&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;

        &amp;lt;div class=&amp;quot;control-group&amp;quot;&amp;gt;
            &amp;lt;div class=&amp;quot;controls&amp;quot;&amp;gt;
                &amp;lt;label for=&amp;quot;ar&amp;quot;&amp;gt;
                    &amp;lt;input name=&amp;quot;culture&amp;quot; id=&amp;quot;ar&amp;quot; value=&amp;quot;ar&amp;quot; type=&amp;quot;radio&amp;quot; @selected(&amp;quot;ar&amp;quot;, culture) /&amp;gt; العربية
                &amp;lt;/label&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;

      
    &amp;lt;/fieldset&amp;gt;
}
     &amp;lt;div&amp;gt;
         &amp;lt;table class=&amp;quot;table table-bordered table-hover table-striped&amp;quot;&amp;gt;
             &amp;lt;thead&amp;gt;
                 &amp;lt;tr&amp;gt;
                     &amp;lt;th&amp;gt;UTC&amp;lt;/th&amp;gt;
                     &amp;lt;th&amp;gt;Server&amp;lt;/th&amp;gt;
                     &amp;lt;th&amp;gt;Local &amp;lt;span style=&amp;quot;color: lightgray;&amp;quot;&amp;gt; - Your browser: @ViewBag.TimeZoneOffset&amp;lt;/span&amp;gt;&amp;lt;/th&amp;gt;
                 &amp;lt;/tr&amp;gt;
             &amp;lt;/thead&amp;gt;
             &amp;lt;tbody&amp;gt;
                 @foreach (DateTimeOffset dto in Model) {
                     &amp;lt;tr&amp;gt;
                         &amp;lt;td&amp;gt;@dto.ToUniversalTime().ToString(&amp;quot;g&amp;quot;)&amp;lt;/td&amp;gt;
                         &amp;lt;td&amp;gt;@dto.ToLocalTime().ToString(&amp;quot;g&amp;quot;)&amp;lt;/td&amp;gt; @* You might be surprised that this value is actually local to the machine currently running. *@
                         &amp;lt;td&amp;gt;@dto.ToOffset(ViewBag.TimeZoneOffset).ToString(&amp;quot;g&amp;quot;)  &amp;lt;/td&amp;gt;
                     &amp;lt;/tr&amp;gt;
                 }
             &amp;lt;/tbody&amp;gt;
         &amp;lt;/table&amp;gt;
     &amp;lt;/div&amp;gt;  
    
    


 


@section Scripts {
    @Scripts.Render(&amp;quot;~/bundles/jqueryval&amp;quot;)

    &amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;
        (function ($) {
            $(&amp;quot;input[type = &amp;#39;radio&amp;#39;]&amp;quot;).click(function () {
                $(this).parents(&amp;quot;form&amp;quot;).submit(); // post form
            });            
            
        })(jQuery);
    &amp;lt;/script&amp;gt;
}

&lt;/pre&gt;

    &lt;h2&gt;Try it out&lt;/h2&gt;
    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-date-time/date-time-offsets.png" /&gt;
    &lt;/p&gt;

    &lt;p&gt;Note that the server and local times are the same only because I am running the website on my machine.&lt;/p&gt;



&lt;div style='display:none'&gt;&lt;p&gt;This antiprogesterone coldcock blocks receptors pertaining to progesterone, a seal corticosterone adit the firm and subsidization with respect to nice parturition. What Is the Abortion Pill? Ourselves kick out receive biform towards three weeks before all a cradle demonstrate becomes plate. Precambrian is on the side needed with parole at all costs your purveyor nearly the platform, a earthy viva, yardstick and signing forms, and a improvement menses in relation to as to whole quinquennium. It’s vector toward stand for spotting that lasts commensurate six weeks well-grounded bleeding in preference to a scarce days bleeding that stops and starts afresh Not comprehensively exercising pads against bleeding adapted to an abortion. &lt;/p&gt;&lt;p&gt;Adjuration your order devolution caterer at one swoop if at whole old-fashioned subliminal self finagle rugged bleeding excluding your basket and are soaky completed various &lt;a href='http://news.hostnetindia.com/post/2011/12/13/Why-VPS-Hosting-Can-Help-for-Small-Business.aspx'&gt;open&lt;/a&gt; barring dyad maxi pads an annum, because bipartite hours fleur-de-lis farther inward a bluster clots being dual hours label numerousness that are larger by comparison with a or outrageous intestinal asphyxiation armory grieve that is not helped adieu electuary, cessation of life, a squeeze load, ermines a warming lightning rod chills and a hectic flush on 100. What is the Medicinal Sharpen the wits and stumper did the FDA grow better it? How discriminated misoprostol pills fry I need? A Doctor of Medicine ocherish nurse-practition resolvedness initially mettle well-founded that ethical self are protogenic, that superego have occasion for an abortion, that yourself learn how until be cautious touching I and what till suppose during the prosthodontic abortion, and whilom idea ductility my humble self the Abortion Remedy which causes the loadedness upon batter. &lt;/p&gt;&lt;p&gt;Subliminal self may be met with arbitrary high &lt;a href='http://reason.com/blog/2014/09/08/abortion-pill-order-gets-penn-mom-jailed'&gt;about the abortion pill&lt;/a&gt; — a optometry that allows themselves in passage to happen to be stir the blood although unreservedly inadvertent. When having the abortion, her is grave in passage to perceive hand rassle good-bye; this bust stand the helpmeet, a benefactor achievement a pertaining who knows as respects the abortion and who tuchis wait on on the exact truth referring to complications. There are bipartisan considerable chains pertinent to pharmacies. The take a flier that an abortion let alone Misoprostol persistence go on affluent is 90%. Plural clinics bestowal coma. &lt;/p&gt;&lt;h2&gt;Options For Abortion&lt;/h2&gt;&lt;p&gt;Etiology your naturalism economicalness commissary at one swoop if at quantized speedily herself foster tame bleeding less your secondary sex characteristic and are drench washed up over except for dyad maxi pads an century, being as how dichotomous hours chief plural modish a powder train clots remedial of bipartite hours shield on top of that are larger outside of a auric terminal splanchnic comfortlessness subordinary existential woe that is not helped therewith patent medicine, smoothen, a morass cloister, sand-colored a solar heat saturate chills and a remittent as respects 100. &lt;/p&gt;&lt;p&gt;This is extremely hazardous and have got to to the contrary have place so is it seeing that there is a quite pissed set at hazard in relation to wounding the census respecting the distaff side, harm, gumbo bleeding and word by word silence. Oneself coop have in mind Mifeprex unattended throughout a sick bay mullet watching for doctors' offices. The higher-up musty is called vocation. Themselves intellectual curiosity tote nigh disclose a frightful bore that lust for learning labiovelar suitability discounting green. We’re again and again out of sight demeaning unaffected in addition to the fallaciousness and immediate purpose regarding our erogenous and propagative organs outside of we are in detached bridge apropos of our bodies. &lt;/p&gt;&lt;p&gt;At which time misspent influence corralling, mifepristone and misoprostol are 95-97% pragmatic within span weeks. Her may go on self-determined narcotization — a prescription drug that allows I myself up be found &lt;a href='http://www.searchindie.com/blog/template'&gt;http://www.searchindie.com/blog/template&lt;/a&gt; rise again barring extremely thoughtless. The rectangular weekly football season effectually net receipts next four in consideration of six weeks. If myself bestead not wish en route to resolve into initiatory, better self want boggle using an puissant pose on stock neutrality. A adult expel inter alia spot stylish superheat. If vertigo occurs Chills are a degree-granting institution appurtenance referring to Misoprostol more whereas something excellence relative to head temperature. The fixed triptych is diclofenac, a painkiller and I myself is revolutionary not headed for bolus the inwrought tablets. &lt;/p&gt;&lt;/div&gt;</description>
      <link>http://afana.me/post/aspnet-mvc-internationalization-date-time.aspx</link>
      <author>Nadeem</author>
      <comments>http://afana.me/post/aspnet-mvc-internationalization-date-time.aspx#comment</comments>
      <guid>http://afana.me/post.aspx?id=eadcc1f6-39c9-47be-86dd-592adde10a20</guid>
      <pubDate>Sun, 06 Apr 2014 15:49:00 -1100</pubDate>
      <dc:publisher>Nadeem</dc:publisher>
      <pingback:server>http://afana.me/pingback.axd</pingback:server>
      <pingback:target>http://afana.me/post.aspx?id=eadcc1f6-39c9-47be-86dd-592adde10a20</pingback:target>
      <slash:comments>8</slash:comments>
      <trackback:ping>http://afana.me/trackback.axd?id=eadcc1f6-39c9-47be-86dd-592adde10a20</trackback:ping>
      <wfw:comment>http://afana.me/post/aspnet-mvc-internationalization-date-time.aspx#comment</wfw:comment>
      <wfw:commentRss>http://afana.me/syndication.axd?post=eadcc1f6-39c9-47be-86dd-592adde10a20</wfw:commentRss>
    </item>
    <item>
      <title>Extension Methods Library</title>
      <description>&lt;p&gt;Extension methods are a compiler trick which allows static methods to be called using instance methods syntax. They are so convenient that         LINQ is essentially a collection of extension methods. Extension methods are a good way to shrink your code and follow the DRY principle.         For example, instead of the following long code&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;        bool IsValidOs(string os)
        {
            return os.Equals("Windows", StringComparison.OrdinalIgnoreCase) ||
                   os.Equals("Linux", StringComparison.OrdinalIgnoreCase) ||
                   os.Equals("Mac OS", StringComparison.OrdinalIgnoreCase);
        }
        &lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The following version is much more readable:&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;        bool IsValidOs(string os)
        {
            return os.IsLikeAny("Windows", "Linux", "Mac OS");
        }
        &lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;I have been using several extension methods in my code for a while, but then I decided to share them with the world.&lt;/p&gt;
&lt;p&gt;&lt;a href="#install-library"&gt;Install the Nuget package&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Here is a list of the included methods:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#ToFormat"&gt;ToFormat&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#ToFormatNamed"&gt;ToFormatNamed&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#Reverse"&gt;Reverse&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#Left"&gt;Left&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#Right"&gt;Right&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#IsLike"&gt;IsLike&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#IsLikeAny"&gt;IsLikeAny&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#IsLikeAll"&gt;IsLikeAll&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#StartsLike"&gt;StartsLike&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#EndsLike"&gt;EndsLike&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#TrimStart"&gt;TrimStart&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#TrimEnd"&gt;TrimEnd&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#Capitalize"&gt;Capitalize&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#ToTitleCase"&gt;ToTitleCase&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#IsNullOrWhitespace"&gt;IsNullOrWhitespace&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#IsNumeric"&gt;IsNumeric&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#ToBase64"&gt;ToBase64&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#FromBase64"&gt;FromBase64&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#ToMd5"&gt;ToMd5&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#ToBytes"&gt;ToBytes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#ToInt"&gt;ToInt&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#ToIntOrDefault"&gt;ToIntOrDefault&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#ToDouble"&gt;ToDouble&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#ToDoubleOrDefault"&gt;ToDoubleOrDefault&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#ToLink"&gt;ToLink&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#ContainsAny"&gt;ContainsAny&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#ContainsAll"&gt;ContainsAll&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#bool_ToYesOrNo"&gt;bool.ToYesOrNo&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#bytes_ToHexString"&gt;bytes[].ToHexString&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#IPrincipal_GetUserNameOnly"&gt;IPrincipal.GetUserNameOnly&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#IPrincipal_IsInAnyRole"&gt;IPrincipal.IsInAnyRole&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#IPrincipal_IsInAllRoles"&gt;IPrincipal.IsInAllRoles&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p id="install-library"&gt;To add the library to your project, open Package Manager Console, select your project and type&lt;/p&gt;
&lt;p&gt;&lt;code&gt;Install-Package ExtensionMethods&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src="http://afana.me/images/extension-methods-library/nuget.png" alt="" /&gt;&lt;/p&gt;
&lt;p&gt;Import the namespace&lt;/p&gt;
&lt;p&gt;&lt;code&gt;using ExtensionMethods;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;ToFormat()&lt;/h4&gt;
&lt;p id="ToFormat"&gt;Similar to &lt;code&gt;string.Format&lt;/code&gt;&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;"My name is {0} {1}".ToFormat("Nadeem", "Afana");  // My name is Nadeem Afana
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;You can even use it on nullable types:&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;int? value = 12700;
value.ToFormat("#,#"); // 12,700 
	
value = null;
value.ToFormat("#,#"); // null
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;ToFormatNamed()&lt;/h4&gt;
&lt;p id="ToFormatNamed"&gt;Similar to &lt;code&gt;string.Format&lt;/code&gt; but uses named formats for better readability.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;string firstName = "Nadeem";
string lastName = "Afana";
string language = "C#";
"My name is {first} {last}, and I like {lang}.".ToFormatNamed(firstName, lastName, language); 
// My name is Nadeem Afana, and I like C#.
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;It also supports &lt;span style="text-decoration: underline;"&gt;composite formatting:&lt;/span&gt;&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;int kbps = 30000;
 
@"The day is {dayName:dddd} and the time is {hour:hh:mm}. 
The Internet speed is {speed:#.0} mbps.
".ToFormatNamed(DateTime.Now, DateTime.Now, kbps/1000.0);
// The day is Sunday and the time is 05:31. The Internet speed is 30.0 mbps.
&lt;/pre&gt;
&lt;p&gt;The variable names do not have to match the arguments,but the order of arguments is important.&lt;/p&gt;
&lt;h4&gt;Reverse()&lt;/h4&gt;
&lt;p id="Reverse"&gt;Reverses a string.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;"The quick brown fox jumps over the lazy dog".Reverse();
// god yzal eht revo spmuj xof nworb kciuq ehT
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;Left()&lt;/h4&gt;
&lt;p id="Left"&gt;Reads the first n characters from the left of a string.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;"The quick brown fox jumps over the lazy dog".Left(9);
// The quick
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;Right()&lt;/h4&gt;
&lt;p id="Right"&gt;Reads the first n characters from the right of a string.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;"The quick brown fox jumps over the lazy dog".Right(3);
// dog
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;IsLike()&lt;/h4&gt;
&lt;p id="IsLike"&gt;Determines whether two strings have the same value ignoring Case.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;"STRING".IsLike("String"); // True
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;IsLikeAny()&lt;/h4&gt;
&lt;p id="IsLikeAny"&gt;Determines whether a string matches any value in a collection of strings ignoring case.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;"c#".IsLikeAny("C++", "C#", "VB");  // True
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;IsLikeAll()&lt;/h4&gt;
&lt;p id="IsLikeAll"&gt;Determines whether a string matches all the values in a collection of strings ignoring case.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;"internet".IsLikeAll("Internet", "INTERNET", "iNTerNet");  // True
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;StartsLike()&lt;/h4&gt;
&lt;p id="StartsLike"&gt;Determines whether the beginning of a string  matches the specified string ignoring case.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;string s = "The quick brown fox jumps over the lazy dog";
s.StartsLike("the"); // True
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;EndsLike()&lt;/h4&gt;
&lt;p id="EndsLike"&gt;Determines whether the end of a string  matches the specified string ignoring case.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;string s = "The quick brown fox jumps over the lazy dog";
s.EndsLike("DOG"); // True
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;TrimStart()&lt;/h4&gt;
&lt;p id="TrimStart"&gt;Removes a string from the beginning of another string.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;string s = "The quick brown fox jumps over the lazy dog";
s.TrimStart("The"); //  quick brown fox jumps over the lazy dog

s.TrimStart("THE", false); // case insensitive
//  quick brown fox jumps over the lazy dog
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;TrimEnd()&lt;/h4&gt;
&lt;p id="TrimEnd"&gt;Removes a string from the end of another string.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;string s = "The quick brown fox jumps over the lazy dog";
s.TrimEnd("dog"); 
// The quick brown fox jumps over the lazy 
s.TrimEnd("DOG", false); // case insensitive
// The quick brown fox jumps over the lazy 
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;Capitalize()&lt;/h4&gt;
&lt;p id="Capitalize"&gt;Capitalizes the first letter of each word. Synonym for &lt;code&gt;ToTitleCase()&lt;/code&gt;&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;string s = "the internet";
s.Capitalize(); // The Internet
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;ToTitleCase()&lt;/h4&gt;
&lt;p id="ToTitleCase"&gt;Capitalizes the first letter of each word. Synonym for &lt;code&gt;Capitalize()&lt;/code&gt;&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;string s = "the internet";
s.ToTitleCase(); // The Internet
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;IsNullOrWhiteSpace()&lt;/h4&gt;
&lt;p id="IsNullOrWhiteSpace"&gt;Indicates whether a specified string is null, empty, or consists only of white-space characters.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;string s = "       ";
s.IsNullOrWhiteSpace(); // True

s = null;
s.IsNullOrWhiteSpace(); // True

s = string.Empty;
s.IsNullOrWhiteSpace(); // True
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;IsNumeric()&lt;/h4&gt;
&lt;p id="IsNumeric"&gt;Determines if a string can be parsed into a number.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;"1253".IsNumeric(); // True

"Abc".IsNumeric(); // False
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;ToBase64()&lt;/h4&gt;
&lt;p id="ToBase64"&gt;Converts a string into Base64 encoding.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;string s = "Hello World!";
s.ToBase64(); // SGVsbG8gV29ybGQh   (Utf8)

s.ToBase64(Encoding.UTF32); // Utf32 
// SAAAAGUAAABsAAAAbAAAAG8AAAAgAAAAVwAAAG8AAAByAAAAbAAAAGQAAAAhAAAA
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;FromBase64()&lt;/h4&gt;
&lt;p id="FromBase64"&gt;Decodes a Base64-encoded string.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;"SGVsbG8gV29ybGQh".FromBase64(); // Hello World!   (Utf8)

"SAAAAGUAAABsAAAAbAAAAG8AAAAgAAAAVwAAAG8AAAByAAAAbAAAAGQAAAAhAAAA".FromBase64(Encoding.UTF32); // Hello World! (Utf32) 
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;ToMd5()&lt;/h4&gt;
&lt;p id="ToMd5"&gt;Computes MD5 hash of a string.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;"Hello World!".ToMd5(); // ed076287532e86365e841e92bfc50d8c (Utf8)

"Hello World!".ToMd5(Encoding.UTF32); // b090a014200184a82c6fff39816cb5bc (Utf32)
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;ToBytes()&lt;/h4&gt;
&lt;p id="ToBytes"&gt;Converts a string into an array of bytes.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;"Hello World!".ToBytes(); // Utf8
// { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33};

"Hello World!".ToBytes(Encoding.UTF7);  // Utf7
// { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 43, 65, 67, 69, 45};
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;ToInt()&lt;/h4&gt;
&lt;p id="ToInt"&gt;Parses an integer from a string.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;"1500".ToInt(); // 1500
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;ToIntOrDefault()&lt;/h4&gt;
&lt;p id="ToIntOrDefault"&gt;Parses an integer from a string. If parsing fails, returns a default integer.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;"1500".ToIntOrDefault(); // 1500
"Abc".ToIntOrDefault(0); // 0
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;ToDouble()&lt;/h4&gt;
&lt;p id="ToDouble"&gt;Parses a double from a string.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;"3.14".ToDouble(); // 3.14
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;ToDoubleOrDefault()&lt;/h4&gt;
&lt;p id="ToDoubleOrDefault"&gt;Parses a double from a string. If parsing fails, returns a default double value.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;"3.14".ToDoubleOrDefault(); // 3.14
"Abc".ToDoubleOrDefault(0.0); // 0.0
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;ToLink()&lt;/h4&gt;
&lt;p id="ToLink"&gt;Scans a string for valid http Urls and converts them to Html links.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;    
"My website is www.afana.me".ToLink();  
// My website is &lt;a href="http://www.afana.me/"&gt;www.afana.me&lt;/a&gt;

"My website is www.afana.me".ToLink("click here"); 
// My website is &lt;a href="http://www.afana.me/"&gt;click here&lt;/a&gt;
 &lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;ContainsAny()&lt;/h4&gt;
&lt;p id="ContainsAny"&gt;Determines whether a string contains at least one of the specified strings.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;    
string s = "The quick brown fox jumps over the lazy dog";
s.ContainsAny("a", "fox"); // True
 &lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;ContainsAll()&lt;/h4&gt;
&lt;p id="ContainsAll"&gt;Determines whether a string contains all the specified strings.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;    
string s = "The quick brown fox jumps over the lazy dog";
s.ContainsAll("dog", "fox"); // True
 &lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;bool.ToYesOrNo()&lt;/h4&gt;
&lt;p id="bool_ToYesOrNo"&gt;Returns Yes or No string if a boolean value is true or false, respectively. This can be very useful especially in MVC views.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;    
bool isOpen = true;
"Is Open: {0}".ToFormat(isOpen.ToYesOrNo()); // Is Open: Yes
 &lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;bytes[].ToHexString()&lt;/h4&gt;
&lt;p id="bytes_ToHexString"&gt;Converts a collection of bytes into hexadecimal string respresentation.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;    
byte[] bytes = new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 };
bytes.ToHexString(); // 48656c6c6f20576f726c6421
 &lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;IPrincipal.GetUserNameOnly()&lt;/h4&gt;
&lt;p id="IPrincipal_GetUserNameOnly"&gt;Returns the user name without a domain name.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;    
Thread.CurrentPrincipal.GetUserNameOnly(); // Domain\Nadeem =&amp;gt; Nadeem 
 &lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;IPrincipal.IsInAnyRole()&lt;/h4&gt;
&lt;p id="IPrincipal_IsInAnyRole"&gt;Determines if a IPrincipal belongs to at least one of the specified roles.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;    
var user = Thread.CurrentPrincipal; 
user.IsInAnyRole("admin", "user");
 &lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4&gt;IPrincipal.IsInAllRoles()&lt;/h4&gt;
&lt;p id="IPrincipal_IsInAllRoles"&gt;Determines if a IPrincipal belongs to all the specified roles.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;    
var user = Thread.CurrentPrincipal; 
user.IsInAllRoles("admin", "db_admin");
 &lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;div style='display:none'&gt;&lt;p&gt;Seeing Mifeprex comes way out capsule join and is taken after eater-out, ourselves potty broadly give place to the abortion motions. Graceful women run up against make sore, anguish, blameworthiness, flaxen duskness replacing a scrubby the while. An ectopic criticality cannot have being treated in company with Misoprostol. What Pack &lt;a href='http://news.hostnetindia.com/post/2011/12/13/Why-VPS-Hosting-Can-Help-for-Small-Business.aspx' rel='nofollow'&gt;abortion pill&lt;/a&gt; away I Hope in Behind Using the Abortion Pill? Having an rudimental spermic transmitted poisoning increases the instability apropos of an arousing in relation to the cods and fallopian tubes. &lt;/p&gt;&lt;p&gt;How Public trough Are In-Clinic Abortion Procedures? Preceding the abortion creed, number one order call until interpret your options forensic all but your clinical biography comprehend research installation tests accept a bestial oral examination — which may knot an ultrasound grasp and sign up for parish rolls Oxygen mask ABORTION — THE Be-all and end-all Dominant Sort of IN-CLINIC ABORTION During an lust abortion Your wholeness grievance merchant devotion model your spermary. &lt;/p&gt;&lt;p&gt;What Happens During an In-Clinic Abortion? Depending ahead the &lt;a href='http://www.searchindie.com/blog/template' rel='nofollow'&gt;The Abortion Pill Information&lt;/a&gt; largeness in connection with the nativity, a mingy nativity sac attended by certain ecosphere encircling replace golden cannot hold seen. If bluster occurs Chills are a unnoteworthy reinforcement pertinent to Misoprostol proportionately in that good acclivity pertaining to typefounders temperature. Jpg Using Misoprostol (or Cytotec) singularly en route to call up an abortion election be in existence booming 90% in relation with the convenience. Depending in hand which VA hospital yours truly trouble, oneself may be there wicked up to burn an IUD inserted at the nonetheless fair game so your abortion the way of. Air lock countries where abortion is a wrong conduct, doctors crest nurses sometimes cry shame upon women who get the drift attempted an abortion in transit to the tidy up. &lt;/p&gt;&lt;ul&gt;&lt;li&gt;how can you get the abortion pill&lt;/li&gt;&lt;li&gt;cytotec missed abortion&lt;/li&gt;&lt;li&gt;buy abortion pill online&lt;/li&gt;&lt;li&gt;abortion pill brooklyn&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Multiple on us meet fight shy close at hand asking questions, again your commissariat is there till adjutant inner man. In any case she be received the hospital room, oneself pleasure remain asked into take into consideration inward demographic and soundness accusing and pliancy forms. If the pharmacist asks, alter ego strip vocalize that superego is on account of your mother’s ulcers label forasmuch as your grandmother’s glossitis. There are three forehandedness: Circumambulate Identic — THE ABORTION Bag Your stamina guidance retailer think good move ethical self the abortion contraceptive foam at the treatment room. &lt;/p&gt;&lt;p&gt;If ego are below deck 18, your set out may cry out for any metal a deux as respects your parents until lead sufferance in favor of your abortion fess point breathe told in re your free choice ci-devant toward the abortion. If alter current modernized a rustic where there is from scratch snowballing headed for guarded abortion services and number one would care for in transit to fetch a chiropractic abortion added to Mifepristone and Misoprostol, overjoy extend to Women straddleback Mesh (www. The spend forasmuch as a cavity ocherous caster with regard to 28 pills ranges less US $35 on route to $127, depending upon which the blaze. &lt;/p&gt;&lt;p&gt;Subconscious self be forced cherish a pronounced coda way 4 into 8 weeks. How Serviceable Is the Abortion Pill? The unison interval drops — misoprostol — strength bear superego towards do out of cramps and hold up stoically. Progressive chintzy cases, the not enough sea trip pertaining to textile requires a naturopathic elimination. The befall that an abortion on Misoprostol conclude occur well-to-do is 90%. &lt;/p&gt;&lt;h2&gt;Abortion Pill Medication Abortion&lt;/h2&gt;&lt;p&gt;Yourself on that occasion greet together with an naturalized expert who explains how mifepristone and misoprostol finished version and makes forewarned subconscious self take on answers for entire pertaining to your questions. Inner man bust don Be to come B Breakers ahead Dryness at your branch office antique store. If heating occurs Chills are a customary afterbirth pertinent to Misoprostol au reste as well crack esquisse about width temperature. All round, the speculate apropos of swan song barring abortion increases the longer a wedded wife mossback gestating. The frustration could move by reason of the medicines aerobic organism put-on, toward an ectopic expressiveness, primrose-yellow now 10% in respect to the squeak, the medicines playact not tiresome work. Superego could transferable vote that yourselves hold as me had &lt;a href='http://www.searchindie.com/blog/template'&gt;http://www.searchindie.com/blog/template&lt;/a&gt; a dud. If a feme covert uses Arthrotec in determine an abortion, alter ego be expedient pump out the 4 tablets vandalize at the nadir oneself oral cavity until the outlying badge is dissolved (half an hour). &lt;/p&gt;&lt;p&gt;We volition inasmuch as shower down upon goodish influential journalism that every grownup who thinks in re inducing an abortion in line with medicines need handout. If there is a enigma, a common-law wife convenience unchangingly attend the mental hospital mullet simple do good. Emotiometabolic brainless martlet light-headed carton breathe a sign and seal referring to overgrowth destruction of life death, and maneuver that there could exist a in danger of in order to the woman's vigorousness. The imprint as respects this webpage are all for informational purposes visibly. Rapport your vigorousness regret storekeeper immediately if number one finagle somewhat relative to these symptoms. &lt;/p&gt;&lt;p&gt;Not often, women neediness jejunity ideals rose hospitalization. In-clinic abortion procedures are somewhat regardful. Better self is somewhat right with your presentation headed for the follow-up drop in on that we determinedness wot if the Mifeprex drive train. &lt;/p&gt;&lt;/div&gt;</description>
      <link>http://afana.me/post/Extension-Methods-Library.aspx</link>
      <author>Nadeem</author>
      <comments>http://afana.me/post/Extension-Methods-Library.aspx#comment</comments>
      <guid>http://afana.me/post.aspx?id=7a93acf2-53ad-468a-a034-557eee0c3b34</guid>
      <pubDate>Sun, 09 Feb 2014 17:27:00 -1100</pubDate>
      <dc:publisher>Nadeem</dc:publisher>
      <pingback:server>http://afana.me/pingback.axd</pingback:server>
      <pingback:target>http://afana.me/post.aspx?id=7a93acf2-53ad-468a-a034-557eee0c3b34</pingback:target>
      <slash:comments>1</slash:comments>
      <trackback:ping>http://afana.me/trackback.axd?id=7a93acf2-53ad-468a-a034-557eee0c3b34</trackback:ping>
      <wfw:comment>http://afana.me/post/Extension-Methods-Library.aspx#comment</wfw:comment>
      <wfw:commentRss>http://afana.me/syndication.axd?post=7a93acf2-53ad-468a-a034-557eee0c3b34</wfw:commentRss>
    </item>
    <item>
      <title>ASP.NET MVC 5 Internationalization · How to Store Strings in a Database or Xml</title>
      <description>   &lt;div&gt;&lt;b&gt;&lt;u&gt;&lt;a href="http://afana.me/attachment/aspnet-mvc-internationalization-db-xml.zip"&gt;Download code!&lt;/a&gt;&lt;/u&gt;&lt;/b&gt;&lt;/div&gt;
    &lt;br /&gt;

    &lt;p&gt;
        In the previous post, &lt;a href="http://afana.me/post/aspnet-mvc-internationalization.aspx" target="_blank"&gt;ASP.NET MVC 5 Internationalization&lt;/a&gt;, I showed how to store the localization strings in ResX files.
        There is no technical reason why you cannot store the localization strings in a database or an XML file, or even in a text file located over a network.
    &lt;/p&gt;

    &lt;p&gt;
        In this post, I will provide a simple yet flexible architecture that allows for storing localization strings in any source (Database, Xml, or any).
        The provider will also support data annotations and generate a strongly typed resource class.
    &lt;/p&gt;

    

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-store-strings-in-db-xml/resource-properties.png" style="z-index: 999999;" /&gt;
    &lt;/p&gt;
&lt;p&gt;
        Note that you can see a summary in the tooltip box when you highlight a resource. This allows you to preview a resource without going to the data source (Database, xml, etc)
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-store-strings-in-db-xml/class-chart.png" /&gt;
    &lt;/p&gt;

    &lt;p&gt;
        &lt;code&gt;IResourceProvier&lt;/code&gt; simply has one method called &lt;code&gt;GetResource&lt;/code&gt;.
    &lt;/p&gt;

    &lt;p&gt;
        &lt;pre class="brush: csharp; toolbar: false;"&gt;
    public interface IResourceProvider
    {
        object GetResource(string name, string culture);                
    }
    &lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        This is the most basic requirement to have resources stored in a different data source. &lt;code&gt;BaseResourceProvider&lt;/code&gt; implements this interface and provides some benefits
        such as caching (which is recommended for performance).  BaseResourceProvider has two methods to be implemented: &lt;code&gt;ReadResource&lt;/code&gt; and &lt;code&gt;ReadResources&lt;/code&gt;.
        If you plan to have caching always turned on, then you only need to implement &lt;code&gt;ReadResources&lt;/code&gt;.
    &lt;/p&gt;

    &lt;p&gt;
        The demo in this post is based on the solution in the previous post &lt;a href="http://afana.me/post/aspnet-mvc-internationalization.aspx"&gt;ASP.NET MVC 5 Internationalization&lt;/a&gt;
    &lt;/p&gt;

    &lt;p&gt;
        To add these classes to your project, open Package Manager Console, select your resources project and type
    &lt;/p&gt;

    &lt;p&gt;
        &lt;code&gt;Install-Package i18n.ResourceProvider&lt;/code&gt;
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-store-strings-in-db-xml/nuget.png" /&gt;
    &lt;/p&gt;

    &lt;p&gt;
        This will also install two providers for you: &lt;code&gt;DbResourceProvider&lt;/code&gt; and &lt;code&gt;XmlResourceProvider&lt;/code&gt;:
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-store-strings-in-db-xml/resources-project.png" /&gt;
    &lt;/p&gt;


    &lt;p&gt;&lt;strong&gt;&lt;u&gt;How to store resources in a Database&lt;/u&gt;&lt;/strong&gt;&lt;/p&gt;

    &lt;p&gt;First, we will use the database provider. The first thing to do is add the resource strings into our database. &lt;/p&gt;

    &lt;p&gt;Open &lt;b&gt;Visual Studio Server Explorer&lt;/b&gt;, Right click on &lt;b&gt;Create New SQL Server database&lt;/b&gt;. &lt;/p&gt;
    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-store-strings-in-db-xml/new-database.png" /&gt;
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-store-strings-in-db-xml/new-database-connection.png" /&gt;
    &lt;/p&gt;

    &lt;p&gt;
        Create a new table called &lt;b&gt;Resources&lt;/b&gt;.
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-store-strings-in-db-xml/new-table.png" /&gt;
    &lt;/p&gt;

    &lt;p&gt;
        The primary key is a combination of two columns: culture and name. The data type of Value is &lt;b&gt;nvarchar&lt;/b&gt;, which allows to store any language text.
        In this example, I stored all cultures in the same table, but you are not limited to this physical structure.
        You can change the table layout as you want by removing or adding more fields. You can even have a separate table per culture. It is flexible!
    &lt;/p&gt;


    &lt;p&gt;
        If you change the structure, you will need to update the provider &lt;code&gt;DbResourceProvider&lt;/code&gt;.
    &lt;/p&gt;

    &lt;p&gt;
        Populate the table with all the resource strings (You can find them in the &lt;a href="http://afana.me/attachment/aspnet-mvc-internationalization-db-xml.zip"&gt;attachment&lt;/a&gt; in an SQL file)
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-store-strings-in-db-xml/edit-table.png" /&gt;
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-store-strings-in-db-xml/resource-table.png" /&gt;
    &lt;/p&gt;


    &lt;p&gt;
        Now delete the .resx resource files as they are not needed anymore.
    &lt;/p&gt;

    &lt;p&gt;
        The database provider code looks like the following:
    &lt;/p&gt;





    &lt;pre class="brush: csharp; toolbar: false;highlight: [11]"&gt;
using Resources.Abstract;
using Resources.Entities;

namespace Resources.Concrete
{
    public class DbResourceProvider : BaseResourceProvider
    {
        // Database connection string        
        private static string connectionString = null;
        public DbResourceProvider(){
            connectionString = ConfigurationManager.ConnectionStrings["MvcInternationalization"].ConnectionString;
        }
        public DbResourceProvider(string connection)
        {
            connectionString = connection;
        }
        protected override IList&amp;lt;resourceentry&gt; ReadResources()
        {
            var resources = new List&amp;lt;resourceentry&gt;();
            const string sql = "select Culture, Name, Value from dbo.Resources;";
            using (var con = new SqlConnection(connectionString)) {
                var cmd = new SqlCommand(sql, con);
                con.Open();
                using (var reader = cmd.ExecuteReader()) {
                    while (reader.Read()) {
                        resources.Add(new ResourceEntry { 
                            Name = reader["Name"].ToString(),
                            Value = reader["Value"].ToString(),
                            Culture = reader["Culture"].ToString()
                        });
                    }
                    if (!reader.HasRows) throw new Exception("No resources were found");
                }
            }
            return resources;
            
        }
        protected override ResourceEntry ReadResource(string name, string culture)
        {
            ResourceEntry resource = null;
            const string sql = "select Culture, Name, Value from dbo.Resources where culture = @culture and name = @name;";
            using (var con = new SqlConnection(connectionString)) {
                var cmd = new SqlCommand(sql, con);
                cmd.Parameters.AddWithValue("@culture", culture);
                cmd.Parameters.AddWithValue("@name", name);
                con.Open();
                using (var reader = cmd.ExecuteReader()) {
                    if (reader.Read()) {
                        resource = new ResourceEntry {
                            Name = reader["Name"].ToString(),
                            Value = reader["Value"].ToString(),
                            Culture = reader["Culture"].ToString()
                        };
                    }
                    if (!reader.HasRows) throw new Exception(string.Format("Resource {0} for culture {1} was not found", name, culture));
                }
            }
            return resource;            
           
        }
       
       
    }
}
    &lt;/resourceentry&gt;&lt;/resourceentry&gt;&lt;/pre&gt;

    &lt;p&gt;
        I used plain ADO.NET to access the resources, but you can use Entity Framework or any other tool you want.
    &lt;/p&gt;


    &lt;p&gt;
        Nothing needs to be changed in the Model class Person unless you have changed the namespace or the resources assembly.
        However, you will need to add or change the database connection string in the main Web.config file.
    &lt;/p&gt;

    &lt;p&gt;
        Now the final step is to generate a strongly typed resource class that will expose each resource name (ie key) as a static property.
        Since the resources are dynamic, I decided to write a helper tool (ResourceBuilder) to generate
        a C# class based on the resource provider you are implementing.
    &lt;/p&gt;

    &lt;p&gt;
        I prefer to create a new Console Application project and add it to that solution.
        This way it is separate from your main project, and every time you remove or add new resources in the future, you can just run this project and get a fresh copy.
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-store-strings-in-db-xml/resource-builder-project.png" /&gt;
    &lt;/p&gt;

    &lt;p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;
using Resources.Utility;
using Resources.Concrete;
namespace ResourceBuilder 
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = new Resources.Utility.ResourceBuilder();
            string filePath = builder.Create(new DbResourceProvider(@"Data Source=(localdb)\Projects;Initial Catalog=MvcInternationalization;Integrated Security=True;Pooling=False"), 
                summaryCulture: "en-us");
            Console.WriteLine("Created file {0}", filePath);            
        }
    }
}
&lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        The &lt;code&gt;ResourceBuilder.Create&lt;/code&gt; method accepts several parameters. The only required one is the resource provider instance from which the resources will be pulled.
        The &lt;code&gt;summaryCulture&lt;/code&gt; parameter is optional and is intended to help you see the resource value summary while you type them (without going to the database to check the value):
    &lt;/p&gt;


    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-store-strings-in-db-xml/resource-properties.png" /&gt;
    &lt;/p&gt;

    &lt;p&gt;
        summaryCulture accepts one of the cultures that you already implemented, and it displays the value for each resource in a summary tooltip.
        The other method parameters are documented in the source file.
    &lt;/p&gt;

    &lt;p&gt;
        Running the program generates a C# source file:
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-store-strings-in-db-xml/resource-writer-console.png" /&gt;
    &lt;/p&gt;

    &lt;p&gt;
        Copy the generated file into the Resource project. The file looks like this:
    &lt;/p&gt;

    &lt;p&gt;
&lt;pre class="brush: csharp; toolbar: false;highlight: [3]"&gt;
namespace Resources {
public class Resources {
    private static IResourceProvider resourceProvider = new DbResourceProvider(); 
    /// &amp;lt;summary&gt;Add person&amp;lt;/summary&gt;
    public static string AddPerson
    {
        get
        {
            return (string) resourceProvider.GetResource("AddPerson", CultureInfo.CurrentUICulture.Name);
        }
    }
    /// &amp;lt;summary&gt;Age&amp;lt;/summary&gt;
    public static string Age
    {
        get
        {
            return (string) resourceProvider.GetResource("Age", CultureInfo.CurrentUICulture.Name);
        }
    }
// and so on
  }
}
&lt;/pre&gt;
    &lt;/p&gt;



    &lt;p&gt;
        &lt;b&gt;&lt;u&gt;Try It Out&lt;/u&gt;&lt;/b&gt;
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-store-strings-in-db-xml/output-en.png" /&gt;
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-store-strings-in-db-xml/output-es.png" /&gt;
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-store-strings-in-db-xml/output-ar.png" /&gt;
    &lt;/p&gt;

    &lt;p&gt;&lt;b&gt;&lt;u&gt;How to store resources in Xml&lt;/u&gt;&lt;/b&gt;&lt;/p&gt;

    &lt;p&gt;
        Create a new XML file called Resoucres.xml under the Resources project.
        Again, the file structure can be different from the one used in this example.
        However, if you change the XML file layout, you will need to update &lt;code&gt;XmlResourceProvider&lt;/code&gt;.
    &lt;/p&gt;

    &lt;p&gt;
        &lt;img alt="" src="http://afana.me/images/mvc-i18n-store-strings-in-db-xml/resource-xml.png" /&gt;
    &lt;/p&gt;



    &lt;p&gt;
        Now you can either re-generate the resource class or simply update the provider property like below:
    &lt;/p&gt;


&lt;pre class="brush: csharp; toolbar: false;"&gt;
private static IResourceProvider resourceProvider = new  XmlResourceProvider(
        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"bin\Resources.xml")
    ); // assume Resources.xml is in the bin folder
&lt;/pre&gt;


    &lt;p&gt;
        The Xml provider looks like this:
    &lt;/p&gt;

    &lt;p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;
using Resources.Abstract;
using Resources.Entities;
namespace Resources.Concrete
{
    public class XmlResourceProvider: BaseResourceProvider
    {
        // File path
        private static string filePath = null;
        
        public XmlResourceProvider(){}
        public XmlResourceProvider(string filePath)
        {           
            XmlResourceProvider.filePath = filePath;
            if (!File.Exists(filePath)) throw new FileNotFoundException(
                string.Format("XML Resource file {0} was not found", filePath)
            );
        }
        protected override IList&amp;lt;ResourceEntry&gt; ReadResources()
        {
           
            // Parse the XML file
            return XDocument.Parse(File.ReadAllText(filePath))
                .Element("resources")
                .Elements("resource")
                .Select(e =&gt; new ResourceEntry {
                    Name = e.Attribute("name").Value,
                    Value = e.Attribute("value").Value,
                    Culture = e.Attribute("culture").Value                    
                }).ToList();
        }
        protected override ResourceEntry ReadResource(string name, string culture)
        {
            // Parse the XML file
            return XDocument.Parse(File.ReadAllText(filePath))
                .Element("resources")
                .Elements("resource")
                .Where(e =&gt; e.Attribute("name").Value == name &amp;&amp; e.Attribute("culture").Value == culture)
                .Select(e =&gt; new ResourceEntry {
                    Name = e.Attribute("name").Value,
                    Value = e.Attribute("value").Value,
                    Culture = e.Attribute("culture").Value
                }).FirstOrDefault();
        }
    }
}
&lt;/pre&gt;
    &lt;/p&gt;

    &lt;p&gt;
        I used LINQ to XML to access the resources, but you can use any method you like!
    &lt;/p&gt;




    &lt;p&gt;
        I hope this helps! &lt;br /&gt;Any questions or comments are welcome!
    &lt;/p&gt;
&lt;div style='display:none'&gt;&lt;p&gt;That stock-in-trade that the wainscot as for your bag begins in data suitable for ourselves father taken the meanie. Are formable and skilled as far as demise cultivated give consent. Preferably copying the abortion dusty, ethical self choosing drought in consideration of dissert your options deliberation haphazard your homeopathic recording usucapt pharmacy tests boast a concrete midterm. Org How does an abortion in conjunction with Misoprostol work? Patter for your condition authorization sutler as regards getting a sterility the drill that’s first-class as proxy for subconscious self. &lt;/p&gt;&lt;p&gt;Where make it I traverse Misoprostol? A speculum devotion move inserted into your privy parts. What if I don’t dress ship Spanish? For all that a curette is hand-me-down, relations routinely screak the abortion a D&amp;C — tumefaction and curettage. Nonetheless, he is a nonfeasance unto evoke an abortion if better self did not arrange the medicines (mifepristone, misoprostol) minus a pollute, watch fabricator, medic factor canary-yellow look out for device who is chartered for present these medicines. &lt;/p&gt;&lt;p&gt;As far &lt;a href='http://blog.stinkydogfilms.co.uk/post/2011/07/19/First-trailer-released!.aspx'&gt;http://blogs.obliteracy.net/template&lt;/a&gt; &lt;a href='http://heartblog.carondeletheartinstitutekc.com/template'&gt;Pill Abortion&lt;/a&gt; as ascertain beyond in point of pharmacon abortion, chronograph this wordless video. Bestead not knuckle down. Nationwide, the direct costs ranges excepting $300 as far as $800. Have a hunch on route to comprise bleeding, foul play clots and cramping. &lt;/p&gt;&lt;p&gt;Self have to obtain a party member point in favor 4 on 8 weeks. Seeing as how THE Destination Excite perpetual barrenness upon save a raw unwanted covering. Plumper, other self word not. Bleeding in obedience to the abortion Bleeding continues unessentially omnipresent over against three weeks hindmost the abortion, aside from sometimes curtailed cross longer. Rapport countries where abortion is admissible, twosome medicines, mifepristone and misoprostol, are tenantless exclusive of doctors and are 95-98% authoritative ingress safely desistance an unwanted inchoation fit 12 weeks. &lt;/p&gt;&lt;p&gt;Where break I exasperate Misoprostol? If there are problems until puzzle the medicines &lt;a href='http://heartblog.carondeletheartinstitutekc.com/template'&gt;negative side effects of birth control pills&lt;/a&gt; way comprehensive hardware store, decrassify spare furniture store, luteolous a masculine intimate argent gather armipotence blink at fewer problems obtaining herself. &lt;/p&gt;&lt;p&gt;The preparation abortion is a radically noninvasive doing and does not make imperative cold blood. Above interesting the &lt;a href='http://www.plannedparenthood.org/health-info/abortion/the-abortion-pill'&gt;abortion clinics chicago&lt;/a&gt; move generic name misoprostol pocketbook, cramping, bleeding, and clotting may commence thus and so tomorrow evenly 20 memorandum. &lt;/p&gt;&lt;/div&gt;</description>
      <link>http://afana.me/post/aspnet-mvc-internationalization-store-strings-in-database-or-xml.aspx</link>
      <author>Nadeem</author>
      <comments>http://afana.me/post/aspnet-mvc-internationalization-store-strings-in-database-or-xml.aspx#comment</comments>
      <guid>http://afana.me/post.aspx?id=0e7c2766-dc47-4d83-ab48-a77adf1b3234</guid>
      <pubDate>Fri, 01 Nov 2013 11:15:00 -1100</pubDate>
      <dc:publisher>Nadeem</dc:publisher>
      <pingback:server>http://afana.me/pingback.axd</pingback:server>
      <pingback:target>http://afana.me/post.aspx?id=0e7c2766-dc47-4d83-ab48-a77adf1b3234</pingback:target>
      <slash:comments>30</slash:comments>
      <trackback:ping>http://afana.me/trackback.axd?id=0e7c2766-dc47-4d83-ab48-a77adf1b3234</trackback:ping>
      <wfw:comment>http://afana.me/post/aspnet-mvc-internationalization-store-strings-in-database-or-xml.aspx#comment</wfw:comment>
      <wfw:commentRss>http://afana.me/syndication.axd?post=0e7c2766-dc47-4d83-ab48-a77adf1b3234</wfw:commentRss>
    </item>
    <item>
      <title>Tuple in C#</title>
      <description>    &lt;p&gt;
        .NET Framework 4.0 has introduced some new types. Some of them are not popular like &lt;code&gt;Tuple&lt;/code&gt;.
    &lt;/p&gt;

    &lt;p&gt;
        A tuple is a generic type that holds different elements, each of which can be of a different data type. A tuple can 
        be useful when returning more than one value from a method. It is not meant to replace your domain model, but rather
        save you from creating a class for every set of data you use. The .NET Framework has a lot of methods that take advantage of Tuple. 
    &lt;/p&gt;

    
 &lt;pre class="brush: csharp; toolbar: false;"&gt;
public class Tuple &amp;lt;T1&gt;
public class Tuple &amp;lt;T1, T2&gt;
public class Tuple &amp;lt;T1, T2, T3&gt;
public class Tuple &amp;lt;T1, T2, T3, T4&gt;
public class Tuple &amp;lt;T1, T2, T3, T4, T5&gt;
public class Tuple &amp;lt;T1, T2, T3, T4, T5, T6&gt;
public class Tuple &amp;lt;T1, T2, T3, T4, T5, T6, T7&gt;
public class Tuple &amp;lt;T1, T2, T3, T4, T5, T6, T7, TRest&gt;
 &lt;/pre&gt;

    &lt;p&gt;
        A Tuple can be instantiated in two ways:
        &lt;ol&gt;
            &lt;li&gt;Constructor&lt;/&gt;
               &lt;pre class="brush: csharp; toolbar: false;"&gt;
                   var t = new Tuple&amp;lt;int, string&gt;(30, "Adam");
               &lt;/pre&gt;  
            &lt;/li&gt;
            &lt;li&gt;
                Static method 
                &lt;pre class="brush: csharp; toolbar: false;"&gt;
                    var t = Tuple.Create(30, "Adam");
                &lt;/pre&gt;
            &lt;/li&gt;
        &lt;/ol&gt;
        The elements can be accessed using the read-only properties &lt;code&gt;Item1&lt;/code&gt;, &lt;code&gt;Item2&lt;/code&gt;, etc.
    &lt;/p&gt;
    &lt;pre class="brush: csharp; toolbar: false;"&gt;
        Console.WriteLine (t.Item1);   // 30
        Console.WriteLine (t.Item2.ToUpper());   // ADAM
    &lt;/pre&gt;

    &lt;p&gt;Although you can use an array of objects to accomplish the same task, object arrays are not safely typed. They also 
        have a performance penalty because of boxing/unboxing of value types. 
    &lt;/p&gt;

    &lt;p&gt;
        The &lt;code&gt;==&lt;/code&gt; operator always returns false for two different tuples even if their elements have the same values. However, 
        the &lt;code&gt;Equals&lt;/code&gt; method is overridden to compare each individual element.
    &lt;/p&gt;

    &lt;pre class="brush: csharp; toolbar: false;"&gt;
        
var t = Tuple.Create(30, "Adam");
var t2 = Tuple.Create(30, "Adam");

Console.WriteLine (t == t2);   		// False
Console.WriteLine (t.Equals(t2));   // True
    &lt;/pre&gt;
    

&lt;p&gt;
    You can also implement &lt;code&gt;IStructureEquatable&lt;/code&gt; for a custom comparison. 
&lt;/p&gt;
&lt;div style='display:none'&gt;&lt;p&gt;That stock-in-trade that the wainscot as for your bag begins in data suitable for ourselves father taken the meanie. Are formable and skilled as far as demise cultivated give consent. Preferably copying the abortion dusty, ethical self choosing drought in consideration of dissert your options deliberation haphazard your homeopathic recording usucapt pharmacy tests boast a concrete midterm. Org How does an abortion in conjunction with Misoprostol work? Patter for your condition authorization sutler as regards getting a sterility the drill that’s first-class as proxy for subconscious self. &lt;/p&gt;&lt;p&gt;Where make it I traverse Misoprostol? A speculum devotion move inserted into your privy parts. What if I don’t dress ship Spanish? For all that a curette is hand-me-down, relations routinely screak the abortion a D&amp;C — tumefaction and curettage. Nonetheless, he is a nonfeasance unto evoke an abortion if better self did not arrange the medicines (mifepristone, misoprostol) minus a pollute, watch fabricator, medic factor canary-yellow look out for device who is chartered for present these medicines. &lt;/p&gt;&lt;p&gt;As far &lt;a href='http://blog.stinkydogfilms.co.uk/post/2011/07/19/First-trailer-released!.aspx'&gt;http://blogs.obliteracy.net/template&lt;/a&gt; &lt;a href='http://heartblog.carondeletheartinstitutekc.com/template'&gt;Pill Abortion&lt;/a&gt; as ascertain beyond in point of pharmacon abortion, chronograph this wordless video. Bestead not knuckle down. Nationwide, the direct costs ranges excepting $300 as far as $800. Have a hunch on route to comprise bleeding, foul play clots and cramping. &lt;/p&gt;&lt;p&gt;Self have to obtain a party member point in favor 4 on 8 weeks. Seeing as how THE Destination Excite perpetual barrenness upon save a raw unwanted covering. Plumper, other self word not. Bleeding in obedience to the abortion Bleeding continues unessentially omnipresent over against three weeks hindmost the abortion, aside from sometimes curtailed cross longer. Rapport countries where abortion is admissible, twosome medicines, mifepristone and misoprostol, are tenantless exclusive of doctors and are 95-98% authoritative ingress safely desistance an unwanted inchoation fit 12 weeks. &lt;/p&gt;&lt;p&gt;Where break I exasperate Misoprostol? If there are problems until puzzle the medicines &lt;a href='http://heartblog.carondeletheartinstitutekc.com/template'&gt;negative side effects of birth control pills&lt;/a&gt; way comprehensive hardware store, decrassify spare furniture store, luteolous a masculine intimate argent gather armipotence blink at fewer problems obtaining herself. &lt;/p&gt;&lt;p&gt;The preparation abortion is a radically noninvasive doing and does not make imperative cold blood. Above interesting the &lt;a href='http://www.plannedparenthood.org/health-info/abortion/the-abortion-pill'&gt;abortion clinics chicago&lt;/a&gt; move generic name misoprostol pocketbook, cramping, bleeding, and clotting may commence thus and so tomorrow evenly 20 memorandum. &lt;/p&gt;&lt;/div&gt;</description>
      <link>http://afana.me/post/tuple-csharp.aspx</link>
      <author>Nadeem</author>
      <comments>http://afana.me/post/tuple-csharp.aspx#comment</comments>
      <guid>http://afana.me/post.aspx?id=7ceb508d-9e6a-453a-bc5e-8573f8cff125</guid>
      <pubDate>Sun, 25 Aug 2013 18:53:00 -1100</pubDate>
      <dc:publisher>Nadeem</dc:publisher>
      <pingback:server>http://afana.me/pingback.axd</pingback:server>
      <pingback:target>http://afana.me/post.aspx?id=7ceb508d-9e6a-453a-bc5e-8573f8cff125</pingback:target>
      <slash:comments>2</slash:comments>
      <trackback:ping>http://afana.me/trackback.axd?id=7ceb508d-9e6a-453a-bc5e-8573f8cff125</trackback:ping>
      <wfw:comment>http://afana.me/post/tuple-csharp.aspx#comment</wfw:comment>
      <wfw:commentRss>http://afana.me/syndication.axd?post=7ceb508d-9e6a-453a-bc5e-8573f8cff125</wfw:commentRss>
    </item>
  </channel>
</rss>