<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>C# Coding / .Net Technologies</title>
	<atom:link href="https://dotnetgalactics.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://dotnetgalactics.wordpress.com</link>
	<description></description>
	<lastBuildDate>Wed, 18 Sep 2019 08:50:57 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<site xmlns="com-wordpress:feed-additions:1">8335553</site><cloud domain='dotnetgalactics.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>https://secure.gravatar.com/blavatar/08864b99450f4a4d1a90a8a0abae999175b897464d986939c36be4af6752f940?s=96&#038;d=https%3A%2F%2Fs2.wp.com%2Fi%2Fwebclip.png</url>
		<title>C# Coding / .Net Technologies</title>
		<link>https://dotnetgalactics.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="https://dotnetgalactics.wordpress.com/osd.xml" title="C# Coding / .Net Technologies" />
	<atom:link rel='hub' href='https://dotnetgalactics.wordpress.com/?pushpress=hub'/>
	<item>
		<title>Basic use-case for Task Unwrap</title>
		<link>https://dotnetgalactics.wordpress.com/2019/09/18/basic-use-case-for-task-unwrap/</link>
					<comments>https://dotnetgalactics.wordpress.com/2019/09/18/basic-use-case-for-task-unwrap/#respond</comments>
		
		<dc:creator><![CDATA[DotNet Galactics]]></dc:creator>
		<pubDate>Wed, 18 Sep 2019 08:00:54 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">http://dotnetgalactics.wordpress.com/?p=685</guid>

					<description><![CDATA[Introduction Recently, after months without using .Net/C#, I was enhancing an existing .Net/C# WPF application leveraging the .Net Task Parallel Library (TPL). But naively applying the JavaScript Promises patterns I had used in the previous months I was bitten by a strange issue which forced me to use the quite exotic Unwrap extension method. This &#8230; <a href="https://dotnetgalactics.wordpress.com/2019/09/18/basic-use-case-for-task-unwrap/" class="more-link">Continue reading <span class="screen-reader-text">Basic use-case for Task&#160;Unwrap</span> <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<h3>Introduction</h3>
<p>Recently, after months without using .Net/C#, I was enhancing an existing .Net/C# WPF application leveraging the .Net Task Parallel Library (TPL).</p>
<p>But naively applying the JavaScript Promises patterns I had used in the previous months I was bitten by a strange issue which forced me to use the quite exotic Unwrap extension method.</p>
<p>This article describes the issue, explains its cause, provides a fix with Unwrap, and finally provides a more modern version with the C# 5.0 async/await paradigm.<br />
A simple workflow in JavaScript with Promises</p>
<p>Here is a JavaScript implementation of a simple workflow with 3 steps, the second one simulating a delayed processing with setTimeout, using the Promise API:</p>
<pre class="brush: jscript; title: ; notranslate">
function doFirstThing() {
	return new Promise(resolve =&gt; {
		console.log(&quot;First thing done&quot;)
		resolve()
	})
}

function doSecondThing() {
	return new Promise(resolve =&gt; {
		setTimeout(() =&gt; {
			console.log(&quot;Second thing done&quot;)
			resolve()
		}, 1000)
	})
}

function doThirdThing() {
	return new Promise(resolve =&gt; {
		console.log(&quot;Third thing done&quot;)
		resolve()
	})
}

doFirstThing().then(doSecondThing).then(doThirdThing)
</pre>
<p>Here is the result once run with Node:</p>
<pre class="brush: jscript; title: ; notranslate">
$ node test.js
First thing done
Second thing done
Third thing done
</pre>
<h3>A C# implementation with Tasks</h3>
<p>Here is the same workflow implemented with C# using .Net TPL:</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.Threading.Tasks;

namespace Test
{
    class Program
    {
        static Task DoFirstThing()
        {
            return Task.Run(() =&gt; Console.WriteLine(&quot;First thing done&quot;));
        }

        static Task DoSecondThing()
        {
            return Task.Delay(1000).ContinueWith(_ =&gt; Console.WriteLine(&quot;Second thing done&quot;));
        }

        static Task DoThirdThing()
        {
            return Task.Run(() =&gt; Console.WriteLine(&quot;Third thing done&quot;));
        }

        static void Main(string[] args)
        {
            DoFirstThing().ContinueWith(_ =&gt; DoSecondThing()).ContinueWith(_ =&gt; DoThirdThing());

            Console.ReadLine();
        }
    }
}
</pre>
<p>Note that contrary to JavaScript Promises .Net Tasks are not started/scheduled automatically when created, hence the need to explicitly call Run.</p>
<p>Here is the result:</p>
<pre class="brush: csharp; title: ; notranslate">
First thing done
Third thing done
Second thing done
</pre>
<p>As you see the third step is executed before the second one!</p>
<p>This is because ContinueWith creates a new Task wrapping the provided treatment which only consists in calling DoSecondThing (which itself creates the second task) which returns immediately.</p>
<p>ContinueWith won’t consider the resulting Task, contrary to Promise.then which handles the case of returning a Promise in a specific manner: the Promise returned by then will be resolved only when the underlying Promise will.<br />
Unwrap to the rescue</p>
<p>To retrieve the JavaScript Promises behavior we need to explicitly tell the TPL we want to consider the underlying Task using Unwrap (implemented as an extension method provided by the TaskExtensions class):</p>
<pre class="brush: csharp; title: ; notranslate">
DoFirstThing().ContinueWith(_ =&gt; DoSecondThing()).Unwrap().ContinueWith(_ =&gt; DoThirdThing());
</pre>
<p>Result is now consistent with JavaScript:</p>
<pre class="brush: csharp; title: ; notranslate">
First thing done
Second thing done
Third thing done
</pre>
<h3>A more modern way with await</h3>
<p>C# 5.0 adds some syntactic sugar to ease the use of the TPL with the await operator:</p>
<pre class="brush: csharp; title: ; notranslate">
await DoFirstThing();
await DoSecondThing();
await DoThirdThing();
</pre>
<p>await internally calls Unwrap and waits on the underlying Task as expected, and yields the same result.</p>
<p>Note that await can only be used in an async method.</p>
<h3>Conclusion</h3>
<p>Mapping between languages and frameworks is not always obvious but fortunately nowadays all seem to copycat each other and they end offering the same paradigms and APIs like the async/await duo you use almost in the same manner in both C# and JavaScript.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://dotnetgalactics.wordpress.com/2019/09/18/basic-use-case-for-task-unwrap/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">685</post-id>
		<media:content url="https://1.gravatar.com/avatar/1d7d62b588110334c6955b86c785ccd099201a5fe47fde4546fcff7d08cc0f9d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetgalactics</media:title>
		</media:content>
	</item>
		<item>
		<title>Check if a password meet the current password policy</title>
		<link>https://dotnetgalactics.wordpress.com/2010/06/15/check-if-a-password-meet-the-current-password-policy/</link>
					<comments>https://dotnetgalactics.wordpress.com/2010/06/15/check-if-a-password-meet-the-current-password-policy/#comments</comments>
		
		<dc:creator><![CDATA[DotNet Galactics]]></dc:creator>
		<pubDate>Tue, 15 Jun 2010 13:15:39 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<guid isPermaLink="false">http://dotnetgalactics.wordpress.com/?p=651</guid>

					<description><![CDATA[In this post I will demonstrate how to verify if a given password meet the current Windows password policy. We will use the NetValidatePasswordPolicy API for that. Instead of using C# pinvoke approach, we will call the API through Managed C++ then call the managed C++ DLL with C#. This approach will be much more cleaner &#8230; <a href="https://dotnetgalactics.wordpress.com/2010/06/15/check-if-a-password-meet-the-current-password-policy/" class="more-link">Continue reading <span class="screen-reader-text">Check if a password meet the current password&#160;policy</span> <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>In this post I will demonstrate how to verify if a given password meet the current Windows password policy.</p>
<p>We will use the <em>NetValidatePasswordPolicy</em> API for that.</p>
<p>Instead of using C# pinvoke approach, we will call the API through Managed C++ then call the managed C++ DLL with C#. This approach will be much more cleaner and readable.</p>
<p>First, we create our Managed C++ DLL which contains our validation method :</p>
<pre class="brush: cpp; title: ; notranslate">
using namespace System;

namespace pwdval
{
    public ref class srPasswordValidator
    {
        public :int ValidatePassword(System::String ^paramPassword)
        {
            pin_ptr&lt;const wchar_t&gt; wchDomain = PtrToStringChars(paramPassword);

            size_t convertedCharsPassword = 0;
            size_t sizeInBytesPassword = ((paramPassword-&gt;Length + 1) * 2);
            errno_t errPassword = 0;
            char    *chPassword = (char *)malloc(sizeInBytesPassword);

            errPassword = wcstombs_s(&amp;convertedCharsPassword,
                                    chPassword, sizeInBytesPassword,
                                    wchDomain, sizeInBytesPassword);

            if (errPassword != 0)
                throw gcnew Exception(&quot;Password could not be converted&quot;);

            // first, find out the required buffer size, in wide characters
            int nPasswordSize = MultiByteToWideChar(CP_ACP, 0, chPassword, -1, NULL, 0);

            LPWSTR wPassword = new WCHAR[nPasswordSize];

            // call again to make the conversion
            MultiByteToWideChar(CP_ACP, 0, chPassword, -1, wPassword, nPasswordSize);

            NET_API_STATUS stat;
            NET_VALIDATE_PASSWORD_CHANGE_INPUT_ARG InputArg = {0};
            NET_VALIDATE_OUTPUT_ARG* pOutputArg = NULL;
            wchar_t* wzServer = 0;

            //wchar_t wzPwd = chPassword;
            InputArg.ClearPassword = wPassword;
            InputArg.PasswordMatch = TRUE;
            stat = NetValidatePasswordPolicy(wzServer, NULL, NetValidatePasswordChange, &amp;InputArg, (void**)&amp;pOutputArg);

            NET_API_STATUS intStatus = pOutputArg-&gt;ValidationStatus;

            NetValidatePasswordPolicyFree((void**)&amp;pOutputArg);
            delete []wPassword;

            return intStatus;
        }

    };
}
</pre>
<p>This method returns an integer that we will convert to an Enum</p>
<pre class="brush: csharp; title: ; notranslate">
enum enmResult
        {
            // &lt;summary&gt; 2234 - This operation is not allowed on this special group. &lt;/summary&gt;
            SpeGroupOp = 2234,
            // &lt;summary&gt; 2235 - This user is not cached in user accounts database session cache. &lt;/summary&gt;
            NotInCache = 2235,
            // &lt;summary&gt; 2236 - The user already belongs to this group. &lt;/summary&gt;
            UserInGroup = 2236,
            // &lt;summary&gt; 2237 - The user does not belong to this group. &lt;/summary&gt;
            UserNotInGroup = 2237,
            // &lt;summary&gt; 2238 - This user account is undefined. &lt;/summary&gt;
            AccountUndefined = 2238,
            // &lt;summary&gt; 2239 - This user account has expired. &lt;/summary&gt;
            AccountExpired = 2239,
            // &lt;summary&gt; 2240 - The user is not allowed to log on from this workstation. &lt;/summary&gt;
            InvalidWorkstation = 2240,
            // &lt;summary&gt; 2241 - The user is not allowed to log on at this time. &lt;/summary&gt;
            InvalidLogonHours = 2241,
            // &lt;summary&gt; 2242 - The password of this user has expired. &lt;/summary&gt;
            PasswordExpired = 2242,
            // &lt;summary&gt; 2243 - The password of this user cannot change. &lt;/summary&gt;
            PasswordCantChange = 2243,
            // &lt;summary&gt; 2244 - This password cannot be used now. &lt;/summary&gt;
            PasswordHistConflict = 2244,
            // &lt;summary&gt; 2245 - The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements. &lt;/summary&gt;
            PasswordTooShort = 2245
        }
</pre>
<p>You can find the complete enum definition in the sources downloadable at the end of the post.</p>
<p>Here is now hows we use the DLL to validate a password :</p>
<pre class="brush: csharp; title: ; notranslate">
        private object pwValidator;

        public PwdVal()
        {
            foreach (string curModule in Directory.GetFiles(ModuleSearchPath, &quot;srPasswordValidator.dll&quot;))
            {
                try
                {
                    Assembly objAssembly = Assembly.LoadFile(curModule);
                    System.Type objType = objAssembly.GetType(&quot;pwdval.srPasswordValidator&quot;);

                    if ((objType != null))
                    {
                        pwValidator = Activator.CreateInstance(objType);

                        break;
                    }
                }
                catch (Exception ex)
                {
                    pwValidator = null;
                }
            }
        }

        private string ModuleSearchPath
        {
            get { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); }
        }

        public bool ValidatePassword(string paramPassword, ref string paramReason)
        {
            try
            {
                if (pwValidator == null)
                {
                    paramReason = &quot;Could not validate the password - pwValidator is NULL&quot;;
                    return false;
                }

                object obj = pwValidator.GetType().GetMethod(&quot;ValidatePassword&quot;).Invoke(pwValidator, new object[] { paramPassword });

                if (obj == null)
                {
                    paramReason = &quot;Could not validate the password - obj is NULL&quot;;
                    return false;
                }

                int val = Int32.Parse(obj.ToString());

                enmResult intResult = (enmResult)val;

                paramReason = intResult.ToString();

                return intResult == enmResult.Success;
            }
            catch (Exception ex)
            {
                paramReason = ex.Message;
                return false;
            }
        }
</pre>
<p>You can download sources and sample here : <a title="http://dl.free.fr/q04LOHSpM" href="http://dl.free.fr/q04LOHSpM">http://dl.free.fr/q04LOHSpM</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://dotnetgalactics.wordpress.com/2010/06/15/check-if-a-password-meet-the-current-password-policy/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">651</post-id>
		<media:content url="https://1.gravatar.com/avatar/1d7d62b588110334c6955b86c785ccd099201a5fe47fde4546fcff7d08cc0f9d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetgalactics</media:title>
		</media:content>
	</item>
		<item>
		<title>Accessing 64 bit registry from a 32 bit process</title>
		<link>https://dotnetgalactics.wordpress.com/2010/05/10/accessing-64-bit-registry-from-a-32-bit-process/</link>
					<comments>https://dotnetgalactics.wordpress.com/2010/05/10/accessing-64-bit-registry-from-a-32-bit-process/#comments</comments>
		
		<dc:creator><![CDATA[DotNet Galactics]]></dc:creator>
		<pubDate>Mon, 10 May 2010 14:03:48 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<guid isPermaLink="false">http://dotnetgalactics.wordpress.com/?p=649</guid>

					<description><![CDATA[As you may know, Windows is virtualizing some parts of the registry under 64 bit. So if you try to open, for example, this key : &#8220;HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\90&#8221;, from a 32 bit C# application running on a 64 bit system, you will be redirected to : &#8220;HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server\90&#8221; Why ? Because Windows uses &#8230; <a href="https://dotnetgalactics.wordpress.com/2010/05/10/accessing-64-bit-registry-from-a-32-bit-process/" class="more-link">Continue reading <span class="screen-reader-text">Accessing 64 bit registry from a 32 bit&#160;process</span> <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>As you may know, Windows is virtualizing some parts of the registry under 64 bit.</p>
<p>So if you try to open, for example, this key : &#8220;HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\90&#8221;, from a 32 bit C# application running on a 64 bit system, you will be redirected to : &#8220;HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server\90&#8221;</p>
<p>Why ? Because Windows uses the Wow6432Node registry entry to present a separate view of HKEY_LOCAL_MACHINE\SOFTWARE for 32 bit applications that runs on a 64 bit systems.</p>
<p>If you want to explicitly open the 64 bit view of the registry, here is what you have to perform :</p>
<p><strong>You are using VS 2010 and version 4.x of the .NET framework</strong></p>
<p>It&#8217;s really simple, all you need to do is, instead of doing :</p>
<pre class="brush: csharp; title: ; notranslate">
//Will redirect you to the 32 bit view
RegistryKey sqlsrvKey = Registry.LocalMachine.OpenSubKey(@&quot;SOFTWARE\Microsoft\Microsoft SQL Server\90&quot;);
</pre>
<p>do the following :</p>
<pre class="brush: csharp; title: ; notranslate">
RegistryKey localMachineX64View = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey sqlsrvKey = localMachineX64View.OpenSubKey(@&quot;SOFTWARE\Microsoft\Microsoft SQL Server\90&quot;);
</pre>
<p><strong>Prior versions of the .NET framework</strong></p>
<p>For the prior versions of the framework, we have to use P/Invoke and call the function RegOpenKeyExW with parameter KEY_WOW64_64KEY</p>
<pre class="brush: csharp; title: ; notranslate">
        enum RegWow64Options
        {
            None = 0,
            KEY_WOW64_64KEY = 0x0100,
            KEY_WOW64_32KEY = 0x0200
        }

        enum RegistryRights
        {
            ReadKey = 131097,
            WriteKey = 131078
        }

        /// &lt;summary&gt;
        /// Open a registry key using the Wow64 node instead of the default 32-bit node.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;parentKey&quot;&gt;Parent key to the key to be opened.&lt;/param&gt;
        /// &lt;param name=&quot;subKeyName&quot;&gt;Name of the key to be opened&lt;/param&gt;
        /// &lt;param name=&quot;writable&quot;&gt;Whether or not this key is writable&lt;/param&gt;
        /// &lt;param name=&quot;options&quot;&gt;32-bit node or 64-bit node&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        static RegistryKey _openSubKey(RegistryKey parentKey, string subKeyName, bool writable, RegWow64Options options)
        {
            //Sanity check
            if (parentKey == null || _getRegistryKeyHandle(parentKey) == IntPtr.Zero)
            {
                return null;
            }

            //Set rights
            int rights = (int)RegistryRights.ReadKey;
            if (writable)
                rights = (int)RegistryRights.WriteKey;

            //Call the native function &gt;.&lt;
            int subKeyHandle, result = RegOpenKeyEx(_getRegistryKeyHandle(parentKey), subKeyName, 0, rights | (int)options, out subKeyHandle);

            //If we errored, return null
            if (result != 0)
            {
                return null;
            }

            //Get the key represented by the pointer returned by RegOpenKeyEx
            RegistryKey subKey = _pointerToRegistryKey((IntPtr)subKeyHandle, writable, false);
            return subKey;
        }

        /// &lt;summary&gt;
        /// Get a pointer to a registry key.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;registryKey&quot;&gt;Registry key to obtain the pointer of.&lt;/param&gt;
        /// &lt;returns&gt;Pointer to the given registry key.&lt;/returns&gt;
        static IntPtr _getRegistryKeyHandle(RegistryKey registryKey)
        {
            //Get the type of the RegistryKey
            Type registryKeyType = typeof(RegistryKey);
            //Get the FieldInfo of the 'hkey' member of RegistryKey
            System.Reflection.FieldInfo fieldInfo =
            registryKeyType.GetField(&quot;hkey&quot;, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            //Get the handle held by hkey
            SafeHandle handle = (SafeHandle)fieldInfo.GetValue(registryKey);
            //Get the unsafe handle
            IntPtr dangerousHandle = handle.DangerousGetHandle();
            return dangerousHandle;
        }

        /// &lt;summary&gt;
        /// Get a registry key from a pointer.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;hKey&quot;&gt;Pointer to the registry key&lt;/param&gt;
        /// &lt;param name=&quot;writable&quot;&gt;Whether or not the key is writable.&lt;/param&gt;
        /// &lt;param name=&quot;ownsHandle&quot;&gt;Whether or not we own the handle.&lt;/param&gt;
        /// &lt;returns&gt;Registry key pointed to by the given pointer.&lt;/returns&gt;
        static RegistryKey _pointerToRegistryKey(IntPtr hKey, bool writable, bool ownsHandle)
        {
            //Get the BindingFlags for private contructors
            System.Reflection.BindingFlags privateConstructors = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
            //Get the Type for the SafeRegistryHandle
            Type safeRegistryHandleType = typeof(Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid).Assembly.GetType(&quot;Microsoft.Win32.SafeHandles.SafeRegistryHandle&quot;);
            //Get the array of types matching the args of the ctor we want
            Type[] safeRegistryHandleCtorTypes = new Type[] { typeof(IntPtr), typeof(bool) };
            //Get the constructorinfo for our object
            System.Reflection.ConstructorInfo safeRegistryHandleCtorInfo = safeRegistryHandleType.GetConstructor(
            privateConstructors, null, safeRegistryHandleCtorTypes, null);
            //Invoke the constructor, getting us a SafeRegistryHandle
            Object safeHandle = safeRegistryHandleCtorInfo.Invoke(new Object[] { hKey, ownsHandle });

            //Get the type of a RegistryKey
            Type registryKeyType = typeof(RegistryKey);
            //Get the array of types matching the args of the ctor we want
            Type[] registryKeyConstructorTypes = new Type[] { safeRegistryHandleType, typeof(bool) };
            //Get the constructorinfo for our object
            System.Reflection.ConstructorInfo registryKeyCtorInfo = registryKeyType.GetConstructor(
            privateConstructors, null, registryKeyConstructorTypes, null);
            //Invoke the constructor, getting us a RegistryKey
            RegistryKey resultKey = (RegistryKey)registryKeyCtorInfo.Invoke(new Object[] { safeHandle, writable });
            //return the resulting key
            return resultKey;
        }

        [DllImport(&quot;advapi32.dll&quot;, CharSet = CharSet.Auto)]
        public static extern int RegOpenKeyEx(IntPtr hKey, string subKey, int ulOptions, int samDesired, out int phkResult);
</pre>
<p>Then we can open our registry key like this :</p>
<pre class="brush: csharp; title: ; notranslate">
RegistryKey sqlsrvKey = _openSubKey(Registry.LocalMachine, @&quot;SOFTWARE\Microsoft\Microsoft SQL Server\90&quot;, false, RegWow64Options.KEY_WOW64_64KEY);
</pre>
<p>As you can see, the framework 4 make our life easier <img src="https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://dotnetgalactics.wordpress.com/2010/05/10/accessing-64-bit-registry-from-a-32-bit-process/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">649</post-id>
		<media:content url="https://1.gravatar.com/avatar/1d7d62b588110334c6955b86c785ccd099201a5fe47fde4546fcff7d08cc0f9d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetgalactics</media:title>
		</media:content>
	</item>
		<item>
		<title>Serialization &#038; Deserialization of immutable objects</title>
		<link>https://dotnetgalactics.wordpress.com/2010/04/19/serialization-deserialization-of-immutable-objects/</link>
					<comments>https://dotnetgalactics.wordpress.com/2010/04/19/serialization-deserialization-of-immutable-objects/#respond</comments>
		
		<dc:creator><![CDATA[DotNet Galactics]]></dc:creator>
		<pubDate>Mon, 19 Apr 2010 13:29:14 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Serialization]]></category>
		<guid isPermaLink="false">http://dotnetgalactics.wordpress.com/?p=637</guid>

					<description><![CDATA[Introduction When developping our applications we can experience than some reference types have the same behavior than value types. As a matter of fact there is no more references to the copied object . It&#8217;s the case for  System.String and System.Nullable&#60;T&#62; which are called immutable object because when affecting new value to these variables a &#8230; <a href="https://dotnetgalactics.wordpress.com/2010/04/19/serialization-deserialization-of-immutable-objects/" class="more-link">Continue reading <span class="screen-reader-text">Serialization &#38; Deserialization of immutable&#160;objects</span> <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<blockquote><p><strong>Introduction</strong></p>
<p>When developping our applications we can experience than some reference types have the same behavior than value types. As a matter of fact there is no more references to the copied object . It&#8217;s the case for  System.String and System.Nullable&lt;T&gt; which are called immutable object because when affecting new value to these variables a perfect copy is created to set the new value.</p>
<p>Immutable objects have many advantages :</p>
<ul>
<li>No side effect</li>
<li>Thread safe</li>
<li>Perfect key of map (because of their unchanging Hashcode)</li>
<li>A simple copy of the reference represent a implementation of the Cloneable interface</li>
<li>&#8230;</li>
</ul>
<p>What&#8217;s happen when we want to persist these object, by disconnecting them around your system? As a matter of fact, when the object is immutable it is difficult to rebuilt the instance because of its only &#8220;getters&#8221; and readonly attributes.</p></blockquote>
<p><strong>Let&#8217;s see a possible solution by constructing an immutable class Person.</strong></p>
<pre class="brush: csharp; title: ; notranslate">
/// &lt;summary&gt;
    /// Immutable class Person
    /// &lt;/summary&gt;
    [DataContract]
    public class Person
    {
        private static readonly DataContractSerializer dcSerializer = new DataContractSerializer(typeof(Person));

        [DataMember]
        private readonly string m_Name;

        public Person(string name)
        {
            this.m_Name = name;
        }

        public String Name
        {
            get
            {
                return this.m_Name;
            }
        }
}
</pre>
<p>To proceed we&#8217;ll be using <span style="color:#ff0000;">DataContractSerializer </span>class to perform with <span style="color:#33cccc;">DataContract</span> &amp; readonly attribute as <span style="color:#33cccc;">DataMember </span>: It serializes and deserializes an instance of a type into an XML stream or document using a supplied data contract. This class cannot be inherited (source msdn).</p>
<pre class="brush: csharp; title: ; notranslate">
public String ObjectToXML()
{
      using (MemoryStream m = new MemoryStream())
      {
           dcSerializer.WriteObject(m, this);
           m.Position = 0;

           using (StreamReader reader = new StreamReader(m))
           {
                 return reader.ReadToEnd();
            }
      }
}

public static Person XmlToObject(String xmlStream)
{
       using (MemoryStream m = new MemoryStream())
       using (StreamWriter writer = new StreamWriter(m))
       {
            writer.Write(xmlStream);
            writer.Flush();
            m.Position = 0;
            return dcSerializer.ReadObject(m) as Person;
       }
}
</pre>
<p>And you can use it as following code :</p>
<pre class="brush: csharp; title: ; notranslate">
Person p = new Person(&quot;Zizou&quot;);
String serializedZizou = p.ObjectToXml();
Person ObjectP = Person.XmlToObject(serializedZizou);
String name = ObjectP.Name;
</pre>
<p>Enjoy! <img src="https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://dotnetgalactics.wordpress.com/2010/04/19/serialization-deserialization-of-immutable-objects/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">637</post-id>
		<media:content url="https://1.gravatar.com/avatar/1d7d62b588110334c6955b86c785ccd099201a5fe47fde4546fcff7d08cc0f9d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetgalactics</media:title>
		</media:content>
	</item>
		<item>
		<title>How to execute code in another AppDomain that the current one</title>
		<link>https://dotnetgalactics.wordpress.com/2010/04/06/how-to-execute-code-in-another-appdomain-that-the-current-one/</link>
					<comments>https://dotnetgalactics.wordpress.com/2010/04/06/how-to-execute-code-in-another-appdomain-that-the-current-one/#respond</comments>
		
		<dc:creator><![CDATA[DotNet Galactics]]></dc:creator>
		<pubDate>Tue, 06 Apr 2010 13:42:14 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<guid isPermaLink="false">http://dotnetgalactics.wordpress.com/?p=620</guid>

					<description><![CDATA[Introduction When an assembly has been loaded in an Application Domain, the embeded code can be executed. This code can be executed in the current Application Domain or in another one, we will see how to proceed by differents way. For all the following examples we will use a namespace MyNameSpace containing 2 classes : &#8230; <a href="https://dotnetgalactics.wordpress.com/2010/04/06/how-to-execute-code-in-another-appdomain-that-the-current-one/" class="more-link">Continue reading <span class="screen-reader-text">How to execute code in another AppDomain that the current&#160;one</span> <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<blockquote><p>Introduction</p>
<p>When an assembly has been loaded in an Application Domain, the embeded code can be executed.</p>
<p>This code can be executed in the current Application Domain or in another one, we will see how to proceed by differents way.</p></blockquote>
<p><strong>For all the following examples we will use a namespace MyNameSpace containing 2 classes :  ObjectRemote &amp; Program.</strong></p>
<pre class="brush: csharp; title: ; notranslate">
 // This namespace contains code to be called.
 namespace MyNameSpace
 {
   public class ObjectRemote : System.MarshalByRefObject
   {
     public ObjectRemote ()
     {
       System.Console.WriteLine(&quot;Hello, World! (ObjectRemote Constructor)&quot;);
     }
   }
   class Program
   {
     static void Main()
     {
       System.Console.WriteLine(&quot;Hello, World! (Main method)&quot;);
     }
   }
}
</pre>
<p><strong>I) Loading assembly in the current AppDomain</strong></p>
<p>To reach some code from another application you can load your assembly in the current AppDomain or create a new AppDomain and load your assembly inside.</p>
<p>The following example shows how to load an assembly in the current AppDomain :</p>
<pre class="brush: csharp; title: ; notranslate">
static void main()
{
  //Load the assembly into the current AppDomain
 System.Reflection.Assembly newAssembly = System.Reflection.Assembly.LoadFrom(@&quot;c:\MyNameSpace.exe&quot;)

 //Instanciate ObjectRemote:
 newAssembly.CreateInstance(&quot;MyNameSpace.ObjectRemote&quot;);
}
</pre>
<p><strong>II)Loading assembly in another AppDomain</strong></p>
<p>When using this approach, you have to use <strong>ExecuteAssembly </strong>method of AppDomain class to reach the default entry point or <strong>CreateInstanceFrom</strong> method to create an instance of the ObjectRemote.</p>
<pre class="brush: csharp; title: ; notranslate">
static void main()
{
//Load the assembly into another AppDomain and call the default entry point
System.AppDomain newAppDomain = new System.AppDomain.CreateDomain(&quot;&quot;);
NewAppDomain .ExecuteAssembly(@&quot;c:\MyNameSpace.exe&quot;)

//Create an instance of ObjectRemote
NewAppDomain.CreateInstanceFrom(@&quot; :\MyNameSpace.exe&quot;,&quot; MyNameSpace.ObjectRemote&quot;);
}
</pre>
<p>Enjoy <img src="https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://dotnetgalactics.wordpress.com/2010/04/06/how-to-execute-code-in-another-appdomain-that-the-current-one/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">620</post-id>
		<media:content url="https://1.gravatar.com/avatar/1d7d62b588110334c6955b86c785ccd099201a5fe47fde4546fcff7d08cc0f9d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetgalactics</media:title>
		</media:content>
	</item>
		<item>
		<title>IoC Pattern</title>
		<link>https://dotnetgalactics.wordpress.com/2010/03/10/ioc-pattern/</link>
					<comments>https://dotnetgalactics.wordpress.com/2010/03/10/ioc-pattern/#comments</comments>
		
		<dc:creator><![CDATA[DotNet Galactics]]></dc:creator>
		<pubDate>Wed, 10 Mar 2010 17:11:53 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<guid isPermaLink="false">http://dotnetgalactics.wordpress.com/?p=608</guid>

					<description><![CDATA[Introduction: IoC (inversion of control) is a design pattern used to uncouple classes to avoid strong dependencies between them. As a matter of fact every system does not make assumptions about what other systems do or should do, so no side effect when replacing a system by another one. Let&#8217;s have a first example showing &#8230; <a href="https://dotnetgalactics.wordpress.com/2010/03/10/ioc-pattern/" class="more-link">Continue reading <span class="screen-reader-text">IoC Pattern</span> <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction:</strong></p>
<blockquote><p>IoC (inversion of control) is a design pattern used to uncouple classes to avoid strong dependencies between them.<br />
As a matter of fact every system does not make assumptions about what other systems do or should do, so no side effect when replacing a system by another one.</p></blockquote>
<p>Let&#8217;s have a first example showing classes having strong dependencies between them. Here we have a main class Singer, which let us know the song style and what formation it is.</p>
<pre class="brush: csharp; title: ; notranslate">
public class Song
{
  public string GetStyle()
  {
      return &quot;Rock n Roll !&quot;;
  }
}

public class LineUp
{
  public string GetFormation()
  {
      return &quot;Trio&quot;;
  }
}

public class Singer
{
  Song song;
  LineUp lineUp;

  public Singer()
  {
      song = new Song();
      lineUp = new LineUp();
  }

  public string Sing()
  {
      return &quot;Singer sings &quot; + song.GetStyle() + &quot; and it is a &quot; +  lineUp.GetFormation();
  }
}
</pre>
<p>here&#8217;s the Main method :</p>
<pre class="brush: csharp; title: ; notranslate">
Singer singer = new Singer();
Console.WriteLine(singer.Sing());
</pre>
<p>As result we have : singer sings Rock n Roll ! and it is a Trio<br />
But what would we do if we want to hear another song?? Hearing the same one is good but at the end it could break your tears!!</p>
<p>Implementation of interfaces to replaces instanciate classes (Song, LineUp), and by this way uncoupling main class Singer with the others.</p>
<pre class="brush: csharp; title: ; notranslate">
public interface ISong
{
  public string GetStyle();
}

public interface ILineUp
{
  public string GetFormation();
}

public class Song : ISong
{
  public string ISong.GetStyle()
  {
      return &quot;Hip Hop !&quot;;
  }
}

public class LineUp : ILineUp
{
  public string ILineUp.GetFormation()
  {
      return &quot;Solo&quot;;
  }
}

public class Singer
{
  ISong _isong;
  ILineUp _ilineup;

  public string Singer(ISong is, ILineUp il)
  {
      _isong = is;
      _ilineup = il;
  }

  public string Sing()
  {
      return Singer sings &quot; + _isong.GetStyle() + &quot;it is a &quot; +  _ilineup.GetFormation();
  }
}
</pre>
<p>here&#8217;s the Main method : Now if we want to here another artist, we just have to<br />
instanciate so many class that we want</p>
<pre class="brush: csharp; title: ; notranslate">
//Creating dependencies
Song oldsong = new Song();
LineUp oldlineUp = new LineUp();
//Injection of dependencies
Singer singer = new Singer(oldsong,oldlineup);
Console.WriteLine(singer.Sing());

//Creating dependencies
Song newsong = new Song();
LineUp newlineUp = new LineUp();
//Injection of dependencies
Singer singer = new Singer(newsong,newlineup);
Console.WriteLine(singer.Sing());
</pre>
<p>Thanks for reading !!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://dotnetgalactics.wordpress.com/2010/03/10/ioc-pattern/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">608</post-id>
		<media:content url="https://1.gravatar.com/avatar/1d7d62b588110334c6955b86c785ccd099201a5fe47fde4546fcff7d08cc0f9d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetgalactics</media:title>
		</media:content>
	</item>
		<item>
		<title>How to provide a Parallel.For loop in C#2.0</title>
		<link>https://dotnetgalactics.wordpress.com/2009/11/19/how-to-provide-a-parallel-for-loop-in-c2-0-2/</link>
					<comments>https://dotnetgalactics.wordpress.com/2009/11/19/how-to-provide-a-parallel-for-loop-in-c2-0-2/#comments</comments>
		
		<dc:creator><![CDATA[DotNet Galactics]]></dc:creator>
		<pubDate>Thu, 19 Nov 2009 10:49:06 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<guid isPermaLink="false">http://dotnetgalactics.wordpress.com/?p=599</guid>

					<description><![CDATA[Introduction: As you have seen in this article Parallel.For loop in C#4.0 invokes a given instruction, passing in arguments : an Integer type &#8220;from inclusive&#8221; an Integer type &#8220;to exclusive&#8221; a delegate for the action to be done This is done on multiple threads. In this article we will see a way to implement a &#8230; <a href="https://dotnetgalactics.wordpress.com/2009/11/19/how-to-provide-a-parallel-for-loop-in-c2-0-2/" class="more-link">Continue reading <span class="screen-reader-text">How to provide a Parallel.For loop in&#160;C#2.0</span> <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction:</strong></p>
<blockquote><p>As you have seen in <a href="https://dotnetgalactics.wordpress.com/category/c4-0-tips/">this article</a> Parallel.For loop in C#4.0 invokes a given instruction, passing in arguments :</p>
<ul>
<li>an Integer type &#8220;from inclusive&#8221;</li>
<li>an Integer type  &#8220;to exclusive&#8221;</li>
<li>a delegate for the action to be done</li>
</ul>
<p>This is done on multiple threads.<br />
In this article we will see a way to implement a static For method in C#2.0 having the same behavior.</p></blockquote>
<p><strong>First of all, let&#8217;s implementing our delegate which will be passed in parameter of our For static method.</strong></p>
<pre class="brush: csharp; title: ; notranslate">
public delegate void DelegateFor(int i);
public delegate void DelegateProcess();
</pre>
<p><strong>Now the For static method</strong></p>
<pre class="brush: csharp; title: ; notranslate">
public class Parallel
{
   public static void For(int from, int to, DelegateFor delFor)
   {
      //step or chunck will be done as 4 by 4
      int step = 4;
      int count = from - step;
      int processCount = Environment.ProcessorCount;

      //Now let's take the next chunk 
      DelegateProcess process = delegate()
      {
         while (true)
         {
            int iter = 0;
            lock (typeof(Parallel))
            {
               count += step;
               cntMem = count;
            }
            for (int i = iter ; i &lt; iter  + step; i++)
            {
              if (i &gt;= to)
                return;
                delFor(i);
            }
         }
      };

     //IAsyncResult array to launch Thread(s)
     IAsyncResult[] asyncResults = new IAsyncResult[processCount];
     for (int i = 0; i &lt; processCount; ++i)
     {
         asyncResults[i] = process.BeginInvoke(null, null);
     }
     //EndInvoke to wait for all threads to be completed
     for (int i = 0; i &lt; threadCount; ++i)
     {
        process.EndInvoke(asyncResults[i]);
     }
  }
}
</pre>
<p>Don&#8217;t forget that a bigger step would perform the process by reducing lock waiting time. <strong>In consequence we would increase parallelism which is not a good idea because of the context changing between a thread and another one which consumes resources</strong>.</p>
<p><strong>Do the call like this</strong></p>
<pre class="brush: csharp; title: ; notranslate">
class Program
{
  public static void Main(string[] args)
  {
     Parallel.For(0, 100, delegate (int i)
     {
        Console.WriteLine(i + &quot; &quot; + TID);
     });

     Console.Read();
   }

   public static string TID
   {
     get
     {
       return &quot;TID = &quot; +     System.Threading.Thread.CurrentThread.ManagedThreadId.ToString();
      }
   }
}
</pre>
<p><strong>Or using lambda exression in C#3.0</strong> <img src="https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<pre class="brush: csharp; title: ; notranslate">
public static void Main(string[] args)
{
  Parallel.For(0, 100, (int i) =&gt; Console.WriteLine(i + &quot; &quot; + TID));
  Console.Read();
}
</pre>
<p>Thanks for reading !!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://dotnetgalactics.wordpress.com/2009/11/19/how-to-provide-a-parallel-for-loop-in-c2-0-2/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">599</post-id>
		<media:content url="https://1.gravatar.com/avatar/1d7d62b588110334c6955b86c785ccd099201a5fe47fde4546fcff7d08cc0f9d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetgalactics</media:title>
		</media:content>
	</item>
		<item>
		<title>.Net 4.0 : Overview on Parallel class</title>
		<link>https://dotnetgalactics.wordpress.com/2009/11/18/net-4-0-overview-on-parallel-class/</link>
					<comments>https://dotnetgalactics.wordpress.com/2009/11/18/net-4-0-overview-on-parallel-class/#respond</comments>
		
		<dc:creator><![CDATA[DotNet Galactics]]></dc:creator>
		<pubDate>Wed, 18 Nov 2009 16:20:56 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<guid isPermaLink="false">http://dotnetgalactics.wordpress.com/?p=569</guid>

					<description><![CDATA[Introduction: In the .Net 4.0 we can find a new class Parallel containing many static methods to help us in parallel programing. System.Threading.Parallel provides one For static method which will be the main point of this article. As a matter of fact at the end of this article you&#8217;ll find a link redirecting you in &#8230; <a href="https://dotnetgalactics.wordpress.com/2009/11/18/net-4-0-overview-on-parallel-class/" class="more-link">Continue reading <span class="screen-reader-text">.Net 4.0 : Overview on Parallel&#160;class</span> <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction:</strong></p>
<blockquote><p>In the .Net 4.0 we can find a new class Parallel containing many static methods to help us in parallel programing. System.Threading.Parallel provides one For static method which will be the main point of this article.<br />
As a matter of fact at the end of this article you&#8217;ll find a link redirecting you in one where we explain you how to implement this static method in C# .Net 2.0!!</p></blockquote>
<p><strong><span style="color:#00ccff;">Loop For in a C# 2.0 bloc code</span></strong></p>
<pre class="brush: csharp; title: ; notranslate">
public static void MethodWithoutParallel()
{
      List&lt;string&gt;lstInForLoop = new List&lt;string&gt;();
      for(int i =0;&lt;20;i++)
      {
            lstInForLoop.Add(i.ToString());
            //simulate a heavy instruction
            Thread.SpinWait(10);
       }
}
</pre>
<p><strong><span style="color:#00ccff;">Loop Parallel.For in a C#4.0 bloc code</span></strong></p>
<pre class="brush: csharp; title: ; notranslate">
public static void MethodWithParallel()
{
      List&lt;string&gt;lstInParallelLoop = new List&lt;string&gt;();
      Parallel.For(0, 20, (int i) =&gt;
      {
             lstInParallelLoop.Add(i.ToString());
             //simulate a heavy instruction
             Thread.SpinWait(10);
      });
}
</pre>
<p><strong><span style="color:#00ccff;">Now let&#8217;s compare the timing of these two methods</span></strong></p>
<pre class="brush: csharp; title: ; notranslate">
class Program
{
   public static void Main(string[] args)
   {
      DateTime startTime;
      TimeSpan duration;

      startTime = DateTime.Now;
      MethodWithParallel();
      duration = DateTime.Now - startTime;
      Console.WriteLine(&quot;MethodWithParallel done in {0}&quot;, duration.TotalMilliseconds + &quot; ms&quot;);

      startTime = DateTime.Now;
      MethodWithoutParallel ();
      duration = DateTime.Now - startTime;
      Console.WriteLine(&quot;MethodWithoutParallel  done in {0}&quot;, duration.TotalMilliseconds + &quot; ms&quot;);

      Console.Read();
    }
}
</pre>
<p><strong><span style="color:#ff6600;">Output</span></strong></p>
<figure data-shortcode="caption" id="attachment_573" aria-describedby="caption-attachment-573" style="width: 311px" class="wp-caption alignnone"><a href="https://dotnetgalactics.wordpress.com/wp-content/uploads/2009/11/img1.jpg"><img data-attachment-id="573" data-permalink="https://dotnetgalactics.wordpress.com/2009/11/18/net-4-0-overview-on-parallel-class/img1/" data-orig-file="https://dotnetgalactics.wordpress.com/wp-content/uploads/2009/11/img1.jpg" data-orig-size="311,39" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="img1" data-image-description="" data-image-caption="&lt;p&gt;output_1&lt;/p&gt;
" data-large-file="https://dotnetgalactics.wordpress.com/wp-content/uploads/2009/11/img1.jpg?w=311" class="size-full wp-image-573" title="img1" src="https://dotnetgalactics.wordpress.com/wp-content/uploads/2009/11/img1.jpg?w=1100" alt=""   srcset="https://dotnetgalactics.wordpress.com/wp-content/uploads/2009/11/img1.jpg 311w, https://dotnetgalactics.wordpress.com/wp-content/uploads/2009/11/img1.jpg?w=150&amp;h=19 150w, https://dotnetgalactics.wordpress.com/wp-content/uploads/2009/11/img1.jpg?w=300&amp;h=38 300w" sizes="(max-width: 311px) 100vw, 311px" /></a><figcaption id="caption-attachment-573" class="wp-caption-text">with Thread.SpinWait method</figcaption></figure>
<p>Running in parallel performs processing time by half !!!<br />
There are endeed dependencies on your hardware (according to the number of cores etc&#8230;)</p>
<p>However, let&#8217;s remove the Thread.SpinWait static method and run our loops again.</p>
<p><strong><span style="color:#ff6600;">Output</span></strong></p>
<figure data-shortcode="caption" id="attachment_574" aria-describedby="caption-attachment-574" style="width: 281px" class="wp-caption alignnone"><a href="https://dotnetgalactics.wordpress.com/wp-content/uploads/2009/11/img2.jpg"><img data-attachment-id="574" data-permalink="https://dotnetgalactics.wordpress.com/2009/11/18/net-4-0-overview-on-parallel-class/img2/" data-orig-file="https://dotnetgalactics.wordpress.com/wp-content/uploads/2009/11/img2.jpg" data-orig-size="281,32" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="img2" data-image-description="" data-image-caption="&lt;p&gt;output2&lt;/p&gt;
" data-large-file="https://dotnetgalactics.wordpress.com/wp-content/uploads/2009/11/img2.jpg?w=281" class="size-full wp-image-574" title="img2" src="https://dotnetgalactics.wordpress.com/wp-content/uploads/2009/11/img2.jpg?w=1100" alt=""   srcset="https://dotnetgalactics.wordpress.com/wp-content/uploads/2009/11/img2.jpg 281w, https://dotnetgalactics.wordpress.com/wp-content/uploads/2009/11/img2.jpg?w=150&amp;h=17 150w" sizes="(max-width: 281px) 100vw, 281px" /></a><figcaption id="caption-attachment-574" class="wp-caption-text">without Thread.SpinWait method</figcaption></figure>
<p>The loop for inside <span style="color:#008080;">MethodWithoutParallel </span>performs better than the Parallel.For loop inside <span style="color:#008080;">MethodWithParallel</span>. It makes evidence that it must not be systematically used.<br />
First of all, always find out where are the expensive instructions and if they can be perform thanks to a little step (or chunk) in your loop.</p>
<p>Now let&#8217;s have a look on <a href="https://dotnetgalactics.wordpress.com/2009/11/18/how-to-provide-a-parallel-for-loop-in-c2-0"> how to provide a Parallel.For loop in C#2.0</a></p>
<p>Enjoy :)!!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://dotnetgalactics.wordpress.com/2009/11/18/net-4-0-overview-on-parallel-class/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">569</post-id>
		<media:content url="https://1.gravatar.com/avatar/1d7d62b588110334c6955b86c785ccd099201a5fe47fde4546fcff7d08cc0f9d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetgalactics</media:title>
		</media:content>

		<media:content url="https://dotnetgalactics.wordpress.com/wp-content/uploads/2009/11/img1.jpg" medium="image">
			<media:title type="html">img1</media:title>
		</media:content>

		<media:content url="https://dotnetgalactics.wordpress.com/wp-content/uploads/2009/11/img2.jpg" medium="image">
			<media:title type="html">img2</media:title>
		</media:content>
	</item>
		<item>
		<title>The Yield keyword</title>
		<link>https://dotnetgalactics.wordpress.com/2009/11/13/the-yield-keyword/</link>
					<comments>https://dotnetgalactics.wordpress.com/2009/11/13/the-yield-keyword/#comments</comments>
		
		<dc:creator><![CDATA[DotNet Galactics]]></dc:creator>
		<pubDate>Fri, 13 Nov 2009 15:42:21 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<guid isPermaLink="false">http://dotnetgalactics.wordpress.com/?p=557</guid>

					<description><![CDATA[Introduction: Yield keyword is used in an iterator block to provide a value to the enumerator object or notice the end of an iteration. It is very important to know that an iterator block is not a block of code which will be executed. It is a block which will be interpreted by compilator to &#8230; <a href="https://dotnetgalactics.wordpress.com/2009/11/13/the-yield-keyword/" class="more-link">Continue reading <span class="screen-reader-text">The Yield keyword</span> <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction:</strong></p>
<blockquote><p>Yield keyword is used in an iterator block to provide a value to the enumerator object or notice the end of an iteration.</p></blockquote>
<pre class="brush: csharp; title: ; notranslate">
yield return &lt;expression&gt;;
yield break;
</pre>
<p>It is very important to know that an iterator block <strong>is not a block of code which will be executed. It is a block which will be interpreted by compilator to generate some code</strong>. There will have a deeper article about iterators.</p>
<p><strong>Let&#8217;s have a look on the following code:</strong></p>
<pre class="brush: csharp; title: ; notranslate">
public IEnumerable GetInt(IEnumerable&lt;int&gt; integers)
{
     var listInt = new List&lt;int&gt;();
     foreach (int item in integers)
     {
         //Simulate a long operation.
         Thread.Sleep(5000);
         listInt.Add(item);
     }
     return listInt;
}
</pre>
<p>As you can read it, we simulate a heavy operation with a Thread.Sleep method. A collection is implemented to collect all typed values,at the end, this collection and its content is returned.</p>
<p>So, in this case we will meet Thread.Sleep method as much that the number of iteration in a Test method call!</p>
<p><strong>Now let&#8217;s use Yield keyword:</strong></p>
<pre class="brush: csharp; title: ; notranslate">
public IEnumerable GetInt(IEnumerable&lt;int&gt; integers)
{
      foreach (int item in integers)
      {
          //Simulate a long operation.
          Thread.Sleep(5000);
           yield return item;
      }
}
</pre>
<p>As you can read it, we simulate a heavy operation with a Thread.Sleep method but no collection class is implemented.</p>
<p><strong>Here&#8217;s how would be the call method:</strong></p>
<pre class="brush: csharp; title: ; notranslate">
public void Test()
{
      int[] tabInt = new int[] { 1, 2, 3, 4, 5, 6 };
      foreach (int item in GetInt(tabInt))
      {
          if (item &gt; 4)
          {
              Console.WriteLine(item);
              break;
          }
      }
}
</pre>
<p>We will not have to wait for the end of the iteration inside iterator of GetInt method. The current value is analysed and transmited to the current object inside the foreach of the call method Test.</p>
<p>When the condition is verified (item&gt;4) we get out of the foreach loop.<br />
In this case we won&#8217;t meet Thread.Sleep method as much that the number of iterations! No more waiting for the end of the block code iteration of GetInt method!</p>
<p>Thanks for reading <img src="https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://dotnetgalactics.wordpress.com/2009/11/13/the-yield-keyword/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">557</post-id>
		<media:content url="https://1.gravatar.com/avatar/1d7d62b588110334c6955b86c785ccd099201a5fe47fde4546fcff7d08cc0f9d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetgalactics</media:title>
		</media:content>
	</item>
		<item>
		<title>How using Delegates &#038; Events instead of Parent Property</title>
		<link>https://dotnetgalactics.wordpress.com/2009/11/12/how-using-delegates-events-instead-of-parent-property/</link>
					<comments>https://dotnetgalactics.wordpress.com/2009/11/12/how-using-delegates-events-instead-of-parent-property/#respond</comments>
		
		<dc:creator><![CDATA[DotNet Galactics]]></dc:creator>
		<pubDate>Thu, 12 Nov 2009 16:04:23 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Delegate]]></category>
		<guid isPermaLink="false">http://dotnetgalactics.wordpress.com/?p=549</guid>

					<description><![CDATA[Introduction: In a WinForm application we can use as much encapsulated UserControls as we want. But what would happen if one of these UserControl must communicate with another one? Here we will have a look on 2 way to give our solution : Using Parent property of a control Using delegates and event programming The &#8230; <a href="https://dotnetgalactics.wordpress.com/2009/11/12/how-using-delegates-events-instead-of-parent-property/" class="more-link">Continue reading <span class="screen-reader-text">How using Delegates &#38; Events instead of Parent&#160;Property</span> <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction:</strong></p>
<blockquote><p>In a WinForm application we can use as much encapsulated UserControls as we want. But what would happen if one of these UserControl must communicate with another one?</p></blockquote>
<p>Here we will have a look on 2 way to give our solution :</p>
<ol>
<li>Using Parent property of a control</li>
<li>Using delegates and event programming</li>
</ol>
<p>The 2nd way is much better because more portable, readable and maintainable!</p>
<p>In this exemple a WinForm will contain a usercontrol (UserControl1) which contains another usercontrol (UserControl2). UserControl2 contains a comboBox having a collection of colors. Choosing a color in this comboBox will change the color of the WinForm control.</p>
<p><strong>Using Parent property of a control</strong></p>
<pre class="brush: csharp; title: ; notranslate">
public partial class UserControl2 : UserControl
{
    private void comboBox1_SelectedIndexChanged(object s, EventArgs e)
    {
       #region Using Parent class (bad way)
       switch (this.comboBox1.SelectedIndex)
       {
            case 0:
              //1rst Parent is GroupBox
              //2nd Parent is UserControl1
              //3rd Parent is Form
              Parent.Parent.Parent.BackColor = Color.Blue;
            break;
            case 1:
              Parent.Parent.Parent.BackColor = Color.Red;
            break;
        }
       #endregion
}
</pre>
<p><strong>Using delegates and event programming</strong></p>
<p>Declaration of our delegate, event and method caling the event</p>
<pre class="brush: csharp; title: ; notranslate">
public delegate void ColorChanger(Color color);
public partial class UserControl2 : UserControl
{
    public event ColorChanger ColorChangerExecuter;
    public UserControl2()
    {
            InitializeComponent();
    }

    public void OnChangedSelectIndex(Color color)
    {
        if (this.ColorChangerExecuter != null)
            this.ColorChangerExecuter(color);
    }

</pre>
<p>The other way of implementing comboBox1_SelectedIndexChanged method</p>
<pre class="brush: csharp; title: ; notranslate">
private void comboBox1_SelectedIndexChanged(object s, EventArgs e)
{
    #region Using Delegate with Event (better way)
    switch (this.comboBox1.SelectedIndex)
    {
        case 0:
               this.OnChangedSelectIndex(Color.Blue);
               break;
        case 1:
               this.OnChangedSelectIndex(Color.Red);
               break;
    }
    #endregion
</pre>
<p>And the call in the WinForm class</p>
<pre class="brush: csharp; title: ; notranslate">
public partial class Form1 : Form
{
   UserControl2 uc2 = new UserControl2();
   public Form1()
   {
       InitializeComponent();
       uc2 = this.userControl11.userControl2;
       uc2.ColorChangerExecuter+=new
                            ColorChanger(uc2_ColorChangerExecuter);
  }

 private void uc2_ColorChangerExecuter(Color color)
 {
     this.BackColor = color;
 }
}
</pre>
<p>A listener has been created, and whatever happen to the comboBox, as we have implemented an event for this control, it will be automatically passed to the WinForm container.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://dotnetgalactics.wordpress.com/2009/11/12/how-using-delegates-events-instead-of-parent-property/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">549</post-id>
		<media:content url="https://1.gravatar.com/avatar/1d7d62b588110334c6955b86c785ccd099201a5fe47fde4546fcff7d08cc0f9d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dotnetgalactics</media:title>
		</media:content>
	</item>
	</channel>
</rss>
