<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>syamp's musings</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/syamp/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/syamp/feed.xml</link>
    <description />
    <lastBuildDate>Tue, 16 Apr 2019 05:32:24 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>WIX: Search for Install path from registry</title>
      <link>https://docs.microsoft.com/archive/blogs/syamp/wix-search-for-install-path-from-registry</link>
      <pubDate>Sun, 30 Sep 2012 20:20:25 GMT</pubDate>
      <dc:creator><![CDATA[syamp]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/syamp/2012/09/30/wix-search-for-install-path-from-registry/</guid>
      <description><![CDATA[Technorati Tags: .Net,Windows Installer    Hi There,   I am Syam Pinnaka, Dev in IAM services team...]]></description>
      <content:encoded><![CDATA[<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:f29f9bdb-1b19-42ba-9b3e-cc160d92a751" class="wlWriterSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;">Technorati Tags: <a href="https://technorati.com/tags/.Net" rel="tag">.Net</a>,<a href="https://technorati.com/tags/Windows+Installer" rel="tag">Windows Installer</a></div>    <p>Hi There, </p>  <p>I am Syam Pinnaka, Dev in IAM services team at Microsoft.</p>  <p>Windows Installer XML (WIX) is a great way to create windows installer packages. WIX makes it easy to create simple installer packages and its also possible to create an installer of any complexity with WIX. Today I would like to share a simple trick to set the installer path from a registry entry.</p>  <p>WIX has ‘RegistrySearch’ element which makes it possible to search for a registry element. After we find the required registry entry, we can set this path as a property value which can then be referenced as the install directory during the install.</p>  <p>Here is the code snippet to search the registry.</p>  <pre class="csharpcode">    &lt;Property Id=<span class="str">&quot;INSTALLFOLDER&quot;</span>&gt;
      &lt;RegistrySearch Id=<span class="str">'InstallPathRegistry'</span> Type=<span class="str">'raw'</span>
        Root=<span class="str">'HKLM'</span> Key=<span class="str">'SOFTWARE\Microsoft\my software'</span> Name=<span class="str">'InstallPath'</span> Win64=<span class="str">'no'</span>/&gt;&lt;!--Win64=<span class="str">'yes'</span>--&gt;
    &lt;/Property&gt;</pre>


<p>In the above code, HKLM is the root to start the search. ‘<span class="str">SOFTWARE\Microsoft\my software</span>’ is the key that’s searched. ‘InstallPath’ is the name of the subkey that’s being searched. Use Win64 value ‘No’ to search on x32 bit systems. Win64 value ‘Yes’ can be used for x64 bit systems.</p>

<p>It’s a common scenario to fail the installer if lets say the install path is not found. We can accomplish this using the below XML.</p>

<pre class="csharpcode">&lt;Condition Message=<span class="str">''</span>xxx<span class="str">' Install Folder not found'</span>&gt;INSTALLFOLDER&lt;/Condition&gt;</pre>


<p>Once after we find the correct install path, we would like to use it during the install. This can be achieved using the below XML.</p>

<pre class="csharpcode">        &lt;Directory Id=<span class="str">&quot;TARGETDIR&quot;</span> Name=<span class="str">&quot;SourceDir&quot;</span>&gt;
                &lt;Directory Id=<span class="str">&quot;INSTALLFOLDER&quot;</span> Name=<span class="str">&quot;My software&quot;</span> /&gt;
        &lt;/Directory&gt;</pre>


<p>Assuming that you have two .dlls to copy to the user computer and one registry entry to add, here is a sample XML which can be used with WIX. </p>

<pre class="csharpcode">&lt;?xml version=<span class="str">&quot;1.0&quot;</span> encoding=<span class="str">&quot;UTF-8&quot;</span>?&gt;
&lt;?define Version=<span class="str">&quot;01.01.00&quot;</span> ?&gt;

&lt;Wix xmlns=<span class="str">&quot;https://schemas.microsoft.com/wix/2006/wi&quot;</span>&gt;
    &lt;Product Id=<span class="str">&quot;*&quot;</span> Name=<span class="str">&quot;My software&quot;</span> Language=<span class="str">&quot;1033&quot;</span> Version=<span class="str">&quot;$(var.Version)&quot;</span> Manufacturer=<span class="str">&quot;Awesome Corporation&quot;</span> </pre>

<pre class="csharpcode">UpgradeCode=<span class="str">&quot;[[your guid here]]&quot;</span>&gt;
        &lt;Package InstallerVersion=<span class="str">&quot;200&quot;</span> Compressed=<span class="str">&quot;yes&quot;</span> InstallScope=<span class="str">&quot;perMachine&quot;</span> Platform=<span class="str">&quot;x86&quot;</span>/&gt; &lt;!--Platform=<span class="str">&quot;x64&quot;</span>--&gt;

    &lt;MajorUpgrade DowngradeErrorMessage=<span class="str">&quot;A newer version of 'My software' is already installed.&quot;</span> /&gt;
        &lt;MediaTemplate EmbedCab=<span class="str">&quot;yes&quot;</span> CabinetTemplate=<span class="str">&quot;media{0}.cab&quot;</span>/&gt;

    &lt;Property Id=<span class="str">&quot;INSTALLFOLDER&quot;</span>&gt;
      &lt;RegistrySearch Id=<span class="str">'InstallPathRegistry'</span> Type=<span class="str">'raw'</span>
        Root=<span class="str">'HKLM'</span> Key=<span class="str">'SOFTWARE\Microsoft\my software'</span> Name=<span class="str">'InstallPath'</span> Win64=<span class="str">'no'</span>/&gt;&lt;!--Win64=<span class="str">'yes'</span>--&gt;
    &lt;/Property&gt;
    &lt;Condition Message=<span class="str">''</span>xxx<span class="str">' Install Folder not found'</span>&gt;INSTALLFOLDER&lt;/Condition&gt;   
   
    &lt;Feature Id=<span class="str">&quot;my feature1&quot;</span> Title=<span class="str">&quot;my feature1&quot;</span> Level=<span class="str">&quot;1&quot;</span>&gt;
      &lt;ComponentGroupRef Id=<span class="str">&quot;feature1&quot;</span> /&gt;
    &lt;/Feature&gt;
    
  &lt;/Product&gt;

    &lt;Fragment&gt;
        &lt;Directory Id=<span class="str">&quot;TARGETDIR&quot;</span> Name=<span class="str">&quot;SourceDir&quot;</span>&gt;
                &lt;Directory Id=<span class="str">&quot;INSTALLFOLDER&quot;</span> Name=<span class="str">&quot;my application&quot;</span> /&gt;
        &lt;/Directory&gt;
    &lt;/Fragment&gt;

  &lt;Fragment&gt;
    &lt;ComponentGroup Id=<span class="str">&quot;MyApplicationBin&quot;</span> Directory=<span class="str">&quot;INSTALLFOLDER&quot;</span>&gt;
      &lt;Component Id=<span class="str">&quot;MyDll1&quot;</span> Guid=<span class="str">&quot;YOUR GUID1 HERE&quot;</span>&gt;
        &lt;File Id=<span class="str">&quot;mydll1.dll&quot;</span> KeyPath=<span class="str">&quot;yes&quot;</span> Source=<span class="str">&quot;Binaries\mydll1.dll&quot;</span> /&gt;
      &lt;/Component&gt;
      &lt;Component Id=<span class="str">&quot;MyDll2&quot;</span> Guid=<span class="str">&quot;YOUR GUID2 HERE&quot;</span>&gt;
        &lt;File Id=<span class="str">&quot;mydll2.dll&quot;</span> KeyPath=<span class="str">&quot;yes&quot;</span> Source=<span class="str">&quot;Binaries\mydll2.dll&quot;</span> /&gt;
      &lt;/Component&gt;
      &lt;Component Id=<span class="str">&quot;MyApplicationRegistryEntries&quot;</span> Guid=<span class="str">&quot;YOUR GUID3 HERE&quot;</span> Win64=<span class="str">&quot;no&quot;</span>&gt;&lt;!--Win64=<span class="str">&quot;yes&quot;</span>--&gt;
        &lt;RegistryKey Root=<span class="str">&quot;HKLM&quot;</span>
                      Key=<span class="str">'SOFTWARE\Microsoft\my application\[[your guid here]]'</span>
              Action=<span class="str">&quot;createAndRemoveOnUninstall&quot;</span>&gt;
          &lt;RegistryValue Type=<span class="str">&quot;string&quot;</span> Name=<span class="str">&quot;BinaryName&quot;</span> Value=<span class="str">&quot;mydll1.dll&quot;</span>/&gt;
        &lt;/RegistryKey&gt;
      &lt;/Component&gt;
    &lt;/ComponentGroup&gt;
  &lt;/Fragment&gt;
  
&lt;/Wix&gt;</pre>


<p>&#160;</p>

<p>Please note that the above XML is just to illustrate as to how the complete WIX XML will look like for this scenario. The above code is not tested so it may not work as desired if you try to use it as is.</p>

<p>Thanks for reading and happy installing.</p>]]></content:encoded>
    </item>
    <item>
      <title>FIM XPath using .Net client: Escape single quote</title>
      <link>https://docs.microsoft.com/archive/blogs/syamp/fim-xpath-using-net-client-escape-single-quote</link>
      <pubDate>Fri, 27 Jul 2012 15:42:53 GMT</pubDate>
      <dc:creator><![CDATA[syamp]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/syamp/2012/07/27/fim-xpath-using-net-client-escape-single-quote/</guid>
      <description><![CDATA[Technorati Tags: FIM,Xpath,.NetHi There, I am Syam Pinnaka, Dev in IAM services team at...]]></description>
      <content:encoded><![CDATA[<div class="wlWriterEditableSmartContent" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:0b5bc85e-f0c1-49fa-aa2a-5fc56b51a3eb" style="margin: 0px; padding: 0px; float: none; display: inline;">Technorati Tags: <a href="https://technorati.com/tags/FIM" rel="tag">FIM</a>,<a href="https://technorati.com/tags/Xpath" rel="tag">Xpath</a>,<a href="https://technorati.com/tags/.Net" rel="tag">.Net</a></div><p>Hi There, </p><p>I am Syam Pinnaka, Dev in IAM services team at Microsoft.</p><p>Forefront Identity Manager (FIM) supports querying its data using XPath. XPath queries can be constructed using standard XPath 2.0 specification. FIM XPath queries are a great way to query and fetch the required data from FIM but they can become tricky sometime as explained below.</p><p>Lets consider a simple xpath query to read a group with a display name. The xpath for this will look like below.</p><pre class="csharpcode">    <span class="str">"/Group[DisplayName = 'My Group1']"</span>;</pre><p>When querying programmatically, we typically would like to parameterize this query and so the query will like below.</p><pre class="csharpcode">    </pre><blockquote><pre class="csharpcode"> <span class="kwrd">string</span> group = <span class="str">"my group"</span>;</pre></blockquote><blockquote><pre class="csharpcode"><span class="str">"/Group[(DisplayName = '"</span> + group + <span class="str">"')]"</span>;</pre></blockquote><p>”group” is a variable which will contain the group name that you would like to query FIM for.</p><p>This query will work perfectly for most of the data values until the group that you are searching for contains a single quote. Example below.</p><pre class="csharpcode">    <span class="kwrd">string</span> group = <span class="str">"I have a single quote(')"</span>;
    <span class="str">"/Group[(DisplayName = '"</span> + group + <span class="str">"')]"</span>;</pre><p>Notice a single quote in group name, i.e. <span class="str">"I have a single quote(')" and xpath query will try to enclose this name with two additional quotes before the query is dispatched to FIM. Obviously this query will not fetch the group and fails with an exception saying ‘Cannot filter as requested’. That’s because the extra single quote (‘) in the display name will make the total number of single quotes in the xpath query as 3. The system will detect this condition and fail saying ‘Cannot filter as requested”. </span></p><p><span class="str">Its good to understand what the issue is but how do you fix\work around it? There could be multiple ways to work around this and here is what that has worked for me. Just enclose the display name with double quotes instead of single quotes. i.e. The xpath filter will need to look like this.</span></p><pre class="csharpcode">    <span class="str">"/Group[(DisplayName = \"I have a single quote(')\")]"</span>;</pre><p>We can parameterize the above query as shown below.</p><pre class="csharpcode">    <span class="kwrd">string</span> group = <span class="str">"I have a single quote(')"</span>;
    <span class="str">"/Group[(DisplayName = \""</span> + group + <span class="str">"\")]"</span></pre><pre class="csharpcode">Looks pretty simple, right? Well its only after I know the work around. :- )</pre><pre class="csharpcode">&nbsp;</pre><pre class="csharpcode">&nbsp;</pre><pre class="csharpcode">&nbsp;</pre><pre class="csharpcode">&nbsp;</pre><pre class="csharpcode">&nbsp;</pre>]]></content:encoded>
    </item>
    <item>
      <title>.Net List: set null on copy of list item isn’t reflected on original list</title>
      <link>https://docs.microsoft.com/archive/blogs/syamp/net-list-set-null-on-copy-of-list-item-isnt-reflected-on-original-list</link>
      <pubDate>Sat, 30 Jun 2012 09:44:53 GMT</pubDate>
      <dc:creator><![CDATA[syamp]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/syamp/2012/06/30/net-list-set-null-on-copy-of-list-item-isnt-reflected-on-original-list/</guid>
      <description><![CDATA[Technorati Tags: .Net List    Hi There, I am Syam Pinnaka, Dev in IAM services team at Microsoft.  I...]]></description>
      <content:encoded><![CDATA[<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:5f38496a-71dd-45a2-bce6-5fa0f8b7559e" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;">Technorati Tags: <a href="https://technorati.com/tags/.Net+List" rel="tag">.Net List</a></div>    <p>Hi There, I am Syam Pinnaka, Dev in IAM services team at Microsoft.</p>  <p>I was trying to fix a bug in my code about a week back and was stumbled upon this. Think it will be useful to others. The story goes like this.</p>  <p> I have a collection (List) of my custom objects and took a copy of one of the list items. example below.</p>  <div class="csharpcode">   <pre class="alt">    <span class="kwrd">class</span> myObject</pre>

  <pre>    {</pre>

  <pre class="alt">        <span class="kwrd">public</span> myObject(<span class="kwrd">int</span> id, <span class="kwrd">string</span> name)</pre>

  <pre>        {</pre>

  <pre class="alt">            <span class="kwrd">this</span>.id = id;</pre>

  <pre>            <span class="kwrd">this</span>.name = name;</pre>

  <pre class="alt">        }</pre>

  <pre>&#160;</pre>

  <pre class="alt">        <span class="kwrd">public</span> <span class="kwrd">int</span> id</pre>

  <pre>        {</pre>

  <pre class="alt">            get;</pre>

  <pre>            set;</pre>

  <pre class="alt">        }</pre>

  <pre>&#160;</pre>

  <pre class="alt">        <span class="kwrd">public</span> <span class="kwrd">string</span> name</pre>

  <pre>        {</pre>

  <pre class="alt">            get;</pre>

  <pre>            set;</pre>

  <pre class="alt">        }</pre>

  <pre>    }</pre>
</div>


<div class="csharpcode">
  <pre class="alt">            <span class="kwrd">static</span> List&lt;myObject&gt; items = <span class="kwrd">new</span> List&lt;myObject&gt;();</pre>

  <pre>&#160;</pre>

  <pre class="alt">            myObject first = <span class="kwrd">new</span> myObject(1, <span class="str">&quot;first&quot;</span>);</pre>

  <pre>            myObject second = <span class="kwrd">new</span> myObject(2, <span class="str">&quot;second&quot;</span>);</pre>

  <pre class="alt">&#160;</pre>

  <pre>            items.Add(first);</pre>

  <pre class="alt">            items.Add(second);</pre>

  <pre>&#160;</pre>

  <pre class="alt">            myObject firstCopy = items[0];</pre>
</div>


<p>After taking the copy, I try to make some changes to the copy and use it and finally set it to null.</p>

<div class="csharpcode">
  <pre class="alt">            firstCopy.id = firstCopy.id + 1000;</pre>

  <pre>            <span class="rem">//Use firstCopy, code stripped for brevity..</span></pre>

  <pre class="alt">            firstCopy = <span class="kwrd">null</span>;</pre>
</div>


<p>now what do you think will be there items[0]? If you think its null that’s incorrect. it will still have the modified value and is not set to null. We can see this by checking the object.</p>

<div class="csharpcode">
  <pre class="alt">            <span class="kwrd">foreach</span> (myObject item <span class="kwrd">in</span> items)</pre>

  <pre>            {</pre>

  <pre class="alt">                <span class="kwrd">if</span> (item != <span class="kwrd">null</span> )</pre>

  <pre>                    Console.WriteLine(<span class="str">&quot;In main: id = &quot;</span> + item.id + <span class="str">&quot;, name = &quot;</span> + item.name);</pre>

  <pre class="alt">                <span class="kwrd">else</span></pre>

  <pre>                    Console.WriteLine(<span class="str">&quot;In main: item is null&quot;</span>);</pre>

  <pre class="alt">            }</pre>
</div>


<p>The output is as below.</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/20/55/metablogapi/0825.image_086CF948.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-20-55-metablogapi/0825.image_5F00_086CF948.png"><img title="image" style="display: inline; background-image: none;" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/20/55/metablogapi/8244.image_thumb_75B7FF90.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-20-55-metablogapi/8244.image_5F00_thumb_5F00_75B7FF90.png" width="489" height="101" /></a></p>

<p>This is because the copy here is just a pointer to original list item and setting null on copy is like removing the reference and not release the original item. The only way to make the original item as null is to reference original item and set explicit null on that like below.</p>

<div class="csharpcode">
  <pre class="alt">      item[0] = <span class="kwrd">null</span>;</pre>
</div>


<p>This is a good learning for me and hope will be useful to others as well.</p>

<p>Thanks for reading and happy coding!</p>]]></content:encoded>
    </item>
    <item>
      <title>Set Connector Space Object Properties</title>
      <link>https://docs.microsoft.com/archive/blogs/syamp/set-connector-space-object-properties</link>
      <pubDate>Thu, 31 May 2012 17:09:33 GMT</pubDate>
      <dc:creator><![CDATA[syamp]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/syamp/2012/05/31/set-connector-space-object-properties/</guid>
      <description><![CDATA[Technorati Tags: .Net,FIM  Hi There, I am Syam Pinnaka, Dev in IAM services team at Microsoft.  Have...]]></description>
      <content:encoded><![CDATA[<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:756e98c0-3a32-432f-90a6-39fc6f05d63f" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;">Technorati Tags: <a href="https://technorati.com/tags/.Net" rel="tag">.Net</a>,<a href="https://technorati.com/tags/FIM" rel="tag">FIM</a></div>  <p>Hi There, I am Syam Pinnaka, Dev in IAM services team at Microsoft.</p>  <p>Have you ever wondered how to set an FIM connector space (CS) object Distinguished Name (DN) to a value that’s easy to read and use format? I had this question last week and the solution is easy.</p>  <p>Before I go into the solution to the above problem, its worth mentioning\recap “<strong>IMVSynchronization.Provision</strong>” method.</p>  <p>In FIM 2010 or latest versions <strong>IMVSynchronization.Provision</strong> method is used to handle changes to a metaverse object. Most notably to check if specific connector space object exists and if not, to create one. The triggering point for <strong>IMVSynchronization.Provision</strong> is when an import attribute flow changes attribute values to the metaverse object. <strong>IMVSynchronization.Provision</strong> is also triggered when a connector space object is projected, joined or disconnected to the metaverse object. </p>  <p>Typically relative distinguished name (RDN) and from that distinguished name (DN) is constructed in this method and set on the connector space object along with its other properties.</p>  <p>Assuming the connector space is from a SQL MA, the “<strong>IMVSynchronization.Provision” </strong>code will look like below<strong>.</strong></p>  <blockquote>   <pre class="csharpcode"><span class="kwrd">string</span> csEntryObjectType = <span class="kwrd">null</span>;
<span class="kwrd">if</span> (mventry.ObjectType == Constants.Common.Person)
    csEntryObjectType = Constants.Common.Person;
<span class="kwrd">else</span> <span class="kwrd">if</span> (mventry.ObjectType == Constants.Common.Computer)
    csEntryObjectType = Constants.Common.Computer;

csentry = managementAgent.Connectors.StartNewConnector(csEntryObjectType);
csentry[Constants.Common.IsDeleted].Value = Constants.Common.False; <span class="rem">//&quot;IsDeleted&quot; is a field in SQL table.</span>
csentry[Constants.Common.ObjectGUIDString].Value = mventry[Constants.Common.ObjectGUIDString].Value;
<span class="rem">//&quot;ObjectGUIDString&quot; is another field in SQL table.</span>
csentry.CommitNewConnector();</pre>
</blockquote>


<p><strong></strong> All this works perfect and connector space object will be created as desired. Now lets see how to set connector space (CS) object distinguished name (DN) to a value that’s easy to read and use. For this all that we need to do is construct that easy to use value and set it to DN property of the csentry. For example if we would like to set it to lets say ‘domain\alias’ format the code will look like below.</p>

<blockquote>
  <pre class="csharpcode"><span class="kwrd">string</span> csEntryObjectType = <span class="kwrd">null</span>;
<span class="kwrd">if</span> (mventry.ObjectType == Constants.Common.Person)
    csEntryObjectType = Constants.Common.Person;
<span class="kwrd">else</span> <span class="kwrd">if</span> (mventry.ObjectType == Constants.Common.Computer)
    csEntryObjectType = Constants.Common.Computer;

csentry = managementAgent.Connectors.StartNewConnector(csEntryObjectType);

<strong><span class="kwrd">string</span> RDN = mventry[Constants.Common.Domain].Value + Constants.Common.ForwardSlash + </strong></pre>
</blockquote>

<blockquote>
  <pre class="csharpcode"><strong>mventry[Constants.Common.AccountName].Value;
csentry.DN = managementAgent.EscapeDNComponent(RDN);</strong>

csentry[Constants.Common.IsDeleted].Value = Constants.Common.False; <span class="rem">//&quot;IsDeleted&quot; is a field in SQL table.</span>
csentry[Constants.Common.ObjectGUIDString].Value = mventry[Constants.Common.ObjectGUIDString].Value;
<span class="rem">//&quot;ObjectGUIDString&quot; is another field in SQL table.</span>
csentry.CommitNewConnector();
  </pre>
</blockquote>


<p>&#160;</p>

<p>Please note <strong>EscapeDNComponent</strong> in the above code. <strong>EscapeDNComponent</strong> works based on the management agent its called against and escapes Backslash ('\'). In order to work around the same, the above code uses a forwardSlash instead of backslash. </p>

<p>lDN can be set to any value as shown above and in some cases its advantageous to set it to a custom format.</p>

<p>Thanks for reading and happy syncing. :- )</p>

<p>&#160;</p>

<blockquote>
  <pre class="csharpcode">&#160;</pre>
</blockquote>

<pre class="csharpcode">&#160;</pre>

<pre class="csharpcode">&#160;</pre>
]]></content:encoded>
    </item>
    <item>
      <title>.Net 4.0 : Task Parallel Library</title>
      <link>https://docs.microsoft.com/archive/blogs/syamp/net-4-0-task-parallel-library</link>
      <pubDate>Fri, 30 Mar 2012 18:44:10 GMT</pubDate>
      <dc:creator><![CDATA[syamp]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/syamp/2012/03/30/net-4-0-task-parallel-library/</guid>
      <description><![CDATA[Hi There, I am Syam Pinnaka, Dev in IAM services team at Microsoft.  .Net has provided many...]]></description>
      <content:encoded><![CDATA[<p>Hi There, I am Syam Pinnaka, Dev in IAM services team at Microsoft.</p>  <p>.Net has provided many different ways of Asynchronous programming over various releases. The latest offering that comes with .Net 4.0 is Task Parallel Library (TPL). TPL comes with various benefits over other Async programming models like IAsyncResult or Event based models. The most notable benefits are as follows.</p>  <blockquote>   <ol>     <li>Ability to create parent to child tasks and create complex task hierarchy of dependent tasks.</li>      <li>Ability to Cancel or timeout tasks.</li>      <li>Ability to Wait for one or all tasks.</li>      <li>Continuation options for failed and succeeded tasks.</li>      <li>Ability to catch and handle exceptions.</li>   </ol>  </blockquote>  <p>Exception handling with Async programming is present with both IAsyncResult and Event based models but TPL makes this looks so natural that even a new programmer can start using without much difficulty. As always lets see some example code about how to start using Task Parallel Library.</p>  <p>Creating a task and getting the result is just a few lines of code.</p>  <pre class="csharpcode">        Task&lt;<span class="kwrd">int</span>&gt; t1 = <span class="kwrd">new</span> Task&lt;<span class="kwrd">int</span>&gt;(CalcSum, 5);
        t1.Start();
        Console.WriteLine(<span class="str">&quot;Sum = &quot;</span> + t1.Result);</pre>

<pre class="csharpcode">        <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">int</span> CalcSum(<span class="kwrd">object</span> arg)
        {
            <span class="kwrd">int</span> sum = 0, count = (<span class="kwrd">int</span>)arg;
            <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; count; i++)
                sum += i;

            Console.WriteLine(<span class="str">&quot;In CalcSum, Sum = &quot;</span> + sum);

            <span class="kwrd">return</span> sum;
        }</pre>


<pre class="csharpcode">&#160;</pre>

<p>Note in the above code that a new Task that returns an int is declared. The same can be applied to create a task that returns a void or a custom data type. </p>

<p>Assuming that the “CalcSum” returns a void, in order to&#160; compare “Task” with “QueueUserWorkItem” the below two lines of code are equivalent.</p>

<pre class="csharpcode">            ThreadPool.QueueUserWorkItem(CalcSum, 5);
            Task t2 = <span class="kwrd">new</span> Task(CalcSum, 5).Start();
</pre>

<p>Task has methods like .Wait, .ContinueWith and .RunSynchronously which will be handy in certain situations.</p>

<p>Task status can be found with .Status or .IsFaulted and .IsCompleted and .IsCanceled.</p>

<p>Exception if any during the task execution can be found using .Exception.</p>

<p>A method that needs special attention is .ContinueWith. This can be used to Continue a task when the parent task is completed or Failed or Cancelled. Example code would look like this.</p>

<pre class="csharpcode">            Task&lt;<span class="kwrd">int</span>&gt; t1 = <span class="kwrd">new</span> Task&lt;<span class="kwrd">int</span>&gt;(CalcSum, 5);
            t1.Start();
            t1.ContinueWith(task =&gt; Console.WriteLine(<span class="str">&quot;Fault: &quot;</span> + task.Exception, TaskContinuationOptions.OnlyOnFaulted);
</pre>

<pre class="csharpcode">&#160;</pre>

<p>Similarly <strong>.ContinueWhenAll</strong> can be used to continue a task when more than one task is completed. This concept can easily be used to build a hierarchy of dependent tasks with complex structure.</p>

<p>In addition to Task, .Net 4.0 TPL also provides three static methods which can be used to schedule lot of tasks with independent work. These constructs are as below.</p>

<ol>
  <li>System.Threading.Parallel.For; Example: Parallel.For(0, 100, i=&gt; DoSomething() ); </li>

  <li>System.Threading.Parallel.ForEach; Example: Parallel.ForEach(collection, item =&gt;DoSomething(item));</li>

  <li>System.Threading.Parallel.Invoke; Example: Parallel.Invoke( ()=&gt; DoSomething1(), ()=&gt; DoSomething2());</li>
</ol>

<p>I find both Task and Parallel very useful to address most of my common asynchronous needs without having to deal with Threading complexities. Hope you will find them useful too.</p>

<p>Thanks for reading and happy coding!</p>

<p>&#160;</p>
]]></content:encoded>
    </item>
    <item>
      <title>Managed Threading: QueueUserWorkItem with Callback</title>
      <link>https://docs.microsoft.com/archive/blogs/syamp/managed-threading-queueuserworkitem-with-callback</link>
      <pubDate>Wed, 29 Feb 2012 17:39:44 GMT</pubDate>
      <dc:creator><![CDATA[syamp]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/syamp/2012/02/29/managed-threading-queueuserworkitem-with-callback/</guid>
      <description><![CDATA[Technorati Tags: .Net,Asynchronous programming,Managed Threading  Hi There,   I am Syam Pinnaka, Dev...]]></description>
      <content:encoded><![CDATA[<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:275f35c9-683b-4954-8c92-f9019d70411e" class="wlWriterEditableSmartContent">Technorati Tags: <a href="https://technorati.com/tags/.Net" rel="tag">.Net</a>,<a href="https://technorati.com/tags/Asynchronous+programming" rel="tag">Asynchronous programming</a>,<a href="https://technorati.com/tags/Managed+Threading" rel="tag">Managed Threading</a></div>  <p>Hi There, </p>  <p>I am Syam Pinnaka, Dev in IAM services team at Microsoft. </p>  <p>Managed threading in .Net provide many different ways of creating threads and processing the tasks in separate threads and thus gain all the advantages that comes with multi threading. One way of creating a separate thread is by using “<strong>ThreadPool.QueueUserWorkItem</strong>” which has two overloads. First one takes the <strong>WaitCallback</strong> which takes the method to execute in the ThreadPool thread. Second one takes a WaitCallback along with a state object which can be used to provide the input information required for the ThreadPool thread. The first overload works fine if all the information required for the ThreadPool thread is present in the method itself or in the classes that it has access to. There could be a complex scenario where in you will need to provide some custom information to the ThreadPool thread like lets say the Callback to call after the ThreadPool thread completes its task. This post provides the information and example code required to handle this scenario. i.e. Provide custom information to the ThreadPool thread which includes a Callback reference and TheadPool thread uses to this Callback to notify the client when its work is completed. </p>  <p>Lets assume that we would like to handle a series of web page download requests using thread pool threads. Lets also assume that we would like each Threadpool thread to notify the client when its done downloading the web page. Lets see how we can handle this scenario using ThreadPool threads in an example. </p>  <p>Here is a simple class which downloads a web page given its Uri. </p>  <p>&#160;</p>  <pre class="csharpcode">    <span class="kwrd">class</span> WebPageDownloader
    {
        <span class="kwrd">public</span> WebPageDownloader() { }

        <span class="kwrd">public</span> <span class="kwrd">string</span> PageDownload(Uri pageUri)
        {
            WebRequest request = <span class="kwrd">null</span>;
            HttpWebResponse response = <span class="kwrd">null</span>;
            Stream dataStream = <span class="kwrd">null</span>;
            StreamReader reader = <span class="kwrd">null</span>;
            <span class="kwrd">string</span> responseFromServer = <span class="kwrd">string</span>.Empty;
            <span class="kwrd">try</span>
            {
                request = WebRequest.Create(pageUri);
                request.Credentials = CredentialCache.DefaultCredentials;
                response = (HttpWebResponse)request.GetResponse();
                <span class="rem">// Get the stream containing content returned by the server.</span>
                dataStream = response.GetResponseStream();
                <span class="rem">// Open the stream using a StreamReader for easy access.</span>
                reader = <span class="kwrd">new</span> StreamReader(dataStream);
                <span class="rem">// Read the content.</span>
                responseFromServer = reader.ReadToEnd();
            }
            <span class="kwrd">finally</span>
            {
                reader.Close();
                dataStream.Close();
                response.Close();
            }

            <span class="kwrd">return</span> responseFromServer;
        }
    }</pre>

<p></p>

<p>In order to make this as an ASync and execute the “<strong>PageDownload</strong>” in a separate thread, we can call <strong>ThreadPool.QueueUserWorkItem(new WaitCallback(PageDownload))</strong> . But we would like this new thread to notify the client when the download is complete by passing in the callback method information to this ThreadPool thread. Thats two pieces of information now that we need to pass in. 1) Page Uri to download and 2) Callback to notify the client. This would lead us to modify <strong>PageDownload </strong>method to take a custom object which can have both Uri and the callback. Return type will change to void from string as we now use the callback to return the downloaded web page. Our new PageDownload method looks like below.</p>

<pre class="csharpcode">        <span class="kwrd">private</span> <span class="kwrd">void</span> PageDownload(<span class="kwrd">object</span> state)
        {
            Uri pageUri = ((PageDownloadInfo)state).uri;
            EndDownloadCallback endDownloadCallback = ((PageDownloadInfo)state).endDownloadCallback;

            <span class="kwrd">if</span> (endDownloadCallback == <span class="kwrd">null</span>)
                <span class="kwrd">throw</span> <span class="kwrd">new</span> ArgumentNullException(<span class="str">&quot;endDownloadCallback&quot;</span>);

            WebRequest request = <span class="kwrd">null</span>;
            HttpWebResponse response = <span class="kwrd">null</span>;
            Stream dataStream = <span class="kwrd">null</span>;
            StreamReader reader = <span class="kwrd">null</span>;
            <span class="kwrd">string</span> responseFromServer = <span class="kwrd">string</span>.Empty;
            <span class="kwrd">try</span>
            {
                request = WebRequest.Create(pageUri);
                request.Credentials = CredentialCache.DefaultCredentials;
                response = (HttpWebResponse)request.GetResponse();
                <span class="rem">// Get the stream containing content returned by the server.</span>
                dataStream = response.GetResponseStream();
                <span class="rem">// Open the stream using a StreamReader for easy access.</span>
                reader = <span class="kwrd">new</span> StreamReader(dataStream);
                <span class="rem">// Read the content.</span>
                responseFromServer = reader.ReadToEnd();
            }
            <span class="kwrd">finally</span>
            {
                reader.Close();
                dataStream.Close();
                response.Close();
            }

            endDownloadCallback(responseFromServer);
        }</pre>

<p>Please note in the above code that we have created and using a new type called <strong>PageDownloadInfo </strong>to pass in the required input information. <strong>PageDownloadInfo</strong> looks like below.</p>

<pre class="csharpcode">    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Class to contain information about page to download.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="kwrd">internal</span> <span class="kwrd">class</span> PageDownloadInfo
    {
        <span class="kwrd">public</span> Uri uri;
        <span class="rem">/// &lt;summary&gt;</span>
        <span class="rem">/// Callback to use after the download completes.</span>
        <span class="rem">/// &lt;/summary&gt;</span>
        <span class="kwrd">public</span> EndDownloadCallback endDownloadCallback;

        <span class="kwrd">public</span> PageDownloadInfo(Uri pageUri, EndDownloadCallback callback)
        {
            uri = pageUri;
            endDownloadCallback = callback;
        }
    }</pre>

<p>We also need two other methods to initiate the ThreadPool thread to start downloading the web page asynchronously and another method to receive the callback. Those two would look something like below.</p>

<pre class="csharpcode">        <span class="kwrd">public</span> <span class="kwrd">void</span> StartDownloadPageAsync(Uri pageUri)
        {
            PageDownloadInfo pageInfo = <span class="kwrd">new</span> PageDownloadInfo(pageUri, <span class="kwrd">new</span> EndDownloadCallback(EndDownloadPage));
            ThreadPool.QueueUserWorkItem(<span class="kwrd">new</span> WaitCallback(PageDownload), pageInfo);
        }

        <span class="kwrd">public</span> <span class="kwrd">void</span> EndDownloadPage(<span class="kwrd">string</span> page)
        {
            PageDownloadedEventArgs downloadedPage = <span class="kwrd">new</span> PageDownloadedEventArgs();
            downloadedPage.Page = page;
            pageDownloaded(<span class="kwrd">this</span>, downloadedPage);
        }</pre>


<p>“<strong>StartDownloadPageAsync</strong>” is the Async call initiator. It creates a new ThreadPool thread using <strong>ThreadPool.QueueUserWorkItem</strong> by passing in <strong>PageDownload</strong> method and <strong>pageInfo</strong>. <strong>PageDownload</strong> method will be queued up with this call to download the web page and call the <strong>EndDownloadPage</strong> using the Callback provided in <strong>pageInfo.</strong></p>

<p>Note that <strong>EndDownloadPage</strong> has some code which in turn notifies its clients about downloaded page and its done using <strong>pageDownloaded</strong> event. <strong>pageDownloaded</strong> is a custom event that’s created to notify and provide the downloaded web page information to the client. </p>

<pre class="csharpcode">    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Event arguments to use with page downloaded event.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="kwrd">internal</span> <span class="kwrd">class</span> PageDownloadedEventArgs : EventArgs
    {
        <span class="kwrd">public</span> <span class="kwrd">string</span> Page { get; set; }
    }


        <span class="rem">/// &lt;summary&gt;</span>
        <span class="rem">/// Event to fire to trigger the download complete notificatio to clients.</span>
        <span class="rem">/// &lt;/summary&gt;</span>
        <span class="kwrd">public</span> <span class="kwrd">event</span> EventHandler&lt;PageDownloadedEventArgs&gt; pageDownloaded;</pre>


<p>&#160;</p>

<p>With all the above plumbing in place we now have a fully functional page download Class which can processes the incoming requests asynchronously. The clients can now subscribe to <strong>pageDownloaded</strong> event and make a call <strong>StartDownloadPageAsync</strong> to start downloading the page and get notified when its done.</p>

<p>Complete code looks like below and enjoy the full power of Managed threading. Happy coding!</p>

<pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.IO;
<span class="kwrd">using</span> System.Net;
<span class="kwrd">using</span> System.Threading;

<span class="kwrd">namespace</span> AsyncExercises
{
    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Declare the delegate to use when download completes.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name=&quot;page&quot;&gt;&lt;/param&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">delegate</span> <span class="kwrd">void</span> EndDownloadCallback(<span class="kwrd">string</span> page);

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Event arguments to use with page downloaded event.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="kwrd">internal</span> <span class="kwrd">class</span> PageDownloadedEventArgs : EventArgs
    {
        <span class="kwrd">public</span> <span class="kwrd">string</span> Page { get; set; }
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Class to contain information about page to download.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="kwrd">internal</span> <span class="kwrd">class</span> PageDownloadInfo
    {
        <span class="kwrd">public</span> Uri uri;
        <span class="rem">/// &lt;summary&gt;</span>
        <span class="rem">/// Callback to use after the download completes.</span>
        <span class="rem">/// &lt;/summary&gt;</span>
        <span class="kwrd">public</span> EndDownloadCallback endDownloadCallback;

        <span class="kwrd">public</span> PageDownloadInfo(Uri pageUri, EndDownloadCallback callback)
        {
            uri = pageUri;
            endDownloadCallback = callback;
        }
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Class that downloads a web page and returns the contents as a string.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="kwrd">class</span> WebPageDownloader
    {
        <span class="rem">/// &lt;summary&gt;</span>
        <span class="rem">/// Event to fire to trigger the download complete notificatio to clients.</span>
        <span class="rem">/// &lt;/summary&gt;</span>
        <span class="kwrd">public</span> <span class="kwrd">event</span> EventHandler&lt;PageDownloadedEventArgs&gt; pageDownloaded;

        <span class="rem">/// &lt;summary&gt;</span>
        <span class="rem">/// Constructor</span>
        <span class="rem">/// &lt;/summary&gt;</span>
        <span class="kwrd">public</span> WebPageDownloader()
        {
        }

        <span class="rem">/// &lt;summary&gt;</span>
        <span class="rem">/// Async download start, This will start a new thread and schedule page download task.</span>
        <span class="rem">/// &lt;/summary&gt;</span>
        <span class="rem">/// &lt;param name=&quot;pageUri&quot;&gt;&lt;/param&gt;</span>
        <span class="kwrd">public</span> <span class="kwrd">void</span> StartDownloadPageAsync(Uri pageUri)
        {
            PageDownloadInfo pageInfo = <span class="kwrd">new</span> PageDownloadInfo(pageUri, <span class="kwrd">new</span> EndDownloadCallback(EndDownloadPage));    
            ThreadPool.QueueUserWorkItem(<span class="kwrd">new</span> WaitCallback(PageDownload), pageInfo);
        }

        <span class="rem">/// &lt;summary&gt;</span>
        <span class="rem">/// Method that will be called by the thread pool thread when download completes.</span>
        <span class="rem">/// &lt;/summary&gt;</span>
        <span class="rem">/// &lt;param name=&quot;page&quot;&gt;&lt;/param&gt;</span>
        <span class="kwrd">public</span> <span class="kwrd">void</span> EndDownloadPage(<span class="kwrd">string</span> page)
        {
            PageDownloadedEventArgs downloadedPage = <span class="kwrd">new</span> PageDownloadedEventArgs();
            downloadedPage.Page = page;
            pageDownloaded(<span class="kwrd">this</span>, downloadedPage);
        }

        <span class="rem">/// &lt;summary&gt;</span>
        <span class="rem">/// Method which downloads the web page given its Uri and return the downloaded page using callback provided.</span>
        <span class="rem">/// &lt;/summary&gt;</span>
        <span class="rem">/// &lt;param name=&quot;state&quot;&gt;&lt;/param&gt;</span>
        <span class="kwrd">private</span> <span class="kwrd">void</span> PageDownload(<span class="kwrd">object</span> state)
        {
            Uri pageUri = ((PageDownloadInfo)state).uri;
            EndDownloadCallback endDownloadCallback = ((PageDownloadInfo)state).endDownloadCallback; 

            <span class="kwrd">if</span> (endDownloadCallback == <span class="kwrd">null</span>)
                <span class="kwrd">throw</span> <span class="kwrd">new</span> ArgumentNullException(<span class="str">&quot;endDownloadCallback&quot;</span>);

            WebRequest request = <span class="kwrd">null</span>;
            HttpWebResponse response = <span class="kwrd">null</span>;
            Stream dataStream = <span class="kwrd">null</span>;
            StreamReader reader = <span class="kwrd">null</span>;
            <span class="kwrd">string</span> responseFromServer = <span class="kwrd">string</span>.Empty;
            <span class="kwrd">try</span>
            {
                request = WebRequest.Create(pageUri);
                request.Credentials = CredentialCache.DefaultCredentials;
                response = (HttpWebResponse)request.GetResponse();
                <span class="rem">// Get the stream containing content returned by the server.</span>
                dataStream = response.GetResponseStream();
                <span class="rem">// Open the stream using a StreamReader for easy access.</span>
                reader = <span class="kwrd">new</span> StreamReader(dataStream);
                <span class="rem">// Read the content.</span>
                responseFromServer = reader.ReadToEnd();
            }
            <span class="kwrd">finally</span>
            {
                reader.Close();
                dataStream.Close();
                response.Close();
            }

            endDownloadCallback(responseFromServer);
        }
    }
}</pre>

<pre class="csharpcode">&#160;</pre>]]></content:encoded>
    </item>
    <item>
      <title>.Net : Asynchronous Programming Techniques – Part II</title>
      <link>https://docs.microsoft.com/archive/blogs/syamp/net-asynchronous-programming-techniques-part-ii</link>
      <pubDate>Fri, 13 Jan 2012 20:29:56 GMT</pubDate>
      <dc:creator><![CDATA[syamp]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/syamp/2012/01/13/net-asynchronous-programming-techniques-part-ii/</guid>
      <description><![CDATA[Hi There,   I am Syam Pinnaka, Dev in IAM services team at Microsoft.   As promised in my last post,...]]></description>
      <content:encoded><![CDATA[<p>Hi There, </p>  <p>I am Syam Pinnaka, Dev in IAM services team at Microsoft. </p>  <p>As promised in my last post, lets examine event based Asynchronous Programming Technique. </p>  <p>The key difference between IAsyncResult and Event based pattern is the way they notify the client when&#160; asynchronous call is completed. While using the IAsyncResult pattern, client will either wait on the call they made with “<em>BeginInvokeXXX</em>” or wait for the callback method to be called which it has supplied to the “<em>BeginInvokeXXX</em>” method. In event based pattern, client can subscribe to a completion event and then the client will be notified using this subscribed event when the Asynchronous call is completed. The event based Asynchronous class signature will look something similar to below.</p>  <pre class="csharpcode">        <span class="rem">/// &lt;summary&gt;</span>
        <span class="rem">/// Event for when writing to log file is completed.</span>
        <span class="rem">/// &lt;/summary&gt;</span>
        <span class="kwrd">public</span> <span class="kwrd">event</span> EventHandler CompletedWriting;</pre>


<p>Client can subscribe to this event as shown below.</p>

<pre class="csharpcode">            LogFileWriter logFileWriter = <span class="kwrd">new</span> LogFileWriter();
            logFileWriter.CompletedWriting += OnCompletedWriting;</pre>

<pre class="csharpcode">And call a method which operates Asynchronously.</pre>

<pre class="csharpcode">            logFileWriter.WriteLineAsync(charsToLog);</pre>

<p><font size="2" face="Consolas">The WriteLineAsync method which will look like below.</font> </p>

<pre class="csharpcode">        <span class="rem">/// &lt;summary&gt;</span>
        <span class="rem">/// WriteLineAsync to start write to file asychronously.</span>
        <span class="rem">/// &lt;/summary&gt;</span>
        <span class="rem">/// &lt;param name=&quot;line&quot;&gt;Text to write&lt;/param&gt;</span>
        <span class="kwrd">public</span> <span class="kwrd">void</span> WriteLineAsync(<span class="kwrd">string</span> line)
        {
            IAsyncResult result = writelineToLogfile.BeginInvoke(line, callback, state);
            result.AsyncWaitHandle.WaitOne();
            CompletedWriting(<span class="kwrd">this</span>, <span class="kwrd">null</span>);
        }</pre>


<p>Note in the above code that writelineToLogfile is a delegate to the actual method which does the writing work. When this call is completed, WaitOne will receive the signal to resume execution which will then call “CompletedWriting” to notify the client about Asynchronous call completion. This can also be done in “callback” argument method and thus “WaitOne” can be avoided. </p>

<p>Also note the second argument in CompletedWriting event which is null now. This argument can be used to pass back some useful information to the client when the Asynchronous call is completed. The CompletedWriting event declaration will need a change like below.</p>

<pre class="csharpcode">        <span class="kwrd">public</span> <span class="kwrd">event</span> EventHandler&lt;CompletedWritingEventArgs&gt; CompletedWriting;</pre>


<p>CompletedWritingEventArgs is a class derived from EventArgs as show below.</p>

<blockquote>
  <pre class="csharpcode">  <span class="kwrd">internal</span> <span class="kwrd">class</span> CompletedWritingEventArgs : EventArgs
  {
      <span class="kwrd">public</span> <span class="kwrd">double</span> BytesWritten;
  }</pre>
</blockquote>


<p>That’s all for now and all the best with your asynchronous programming designs and code!</p>

<p>&#160;</p>

<p> 
  <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:4091b12e-457c-46d7-b2da-90f5fc4a39b9" class="wlWriterEditableSmartContent">Technorati Tags: <a href="https://technorati.com/tags/.Net" rel="tag">.Net</a>,<a href="https://technorati.com/tags/Asynchronous+programming" rel="tag">Asynchronous programming</a></div>
</p>

<pre class="csharpcode">&#160;</pre>

<pre class="csharpcode">&#160;</pre>
]]></content:encoded>
    </item>
    <item>
      <title>.Net : Asynchronous Programming Techniques</title>
      <link>https://docs.microsoft.com/archive/blogs/syamp/net-asynchronous-programming-techniques</link>
      <pubDate>Fri, 30 Dec 2011 22:30:47 GMT</pubDate>
      <dc:creator><![CDATA[syamp]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/syamp/2011/12/30/net-asynchronous-programming-techniques/</guid>
      <description><![CDATA[Hi There,  I am Syam Pinnaka, Dev in IAM services team at Microsoft.   During the past two weeks, I...]]></description>
      <content:encoded><![CDATA[<p>Hi There,</p>  <p>I am Syam Pinnaka, Dev in IAM services team at Microsoft. </p>  <p>During the past two weeks, I was trying to explore the .Net Asynchronous programming and so thought I would share my learning. In general, there are two different ways of Asynchronous programming in .Net. 1) Using IAsyncResult 2) using event based Asynchronous pattern. Lets see how to use IAsyncResult in this blog post and I will try and cover Event based Asynchronous pattern in my next post.</p>  <p>Some functionality in .Net can be called from client application either synchronously or asynchronously. Webservice calls are a common example for this. Loading the high resolution&#160; images in a web page could be another good scenario for this. Whenever an asynchronous call is supported, these methods typically start with <strong>Begin</strong><em>Methodname</em> and <strong>End</strong><em>MethodName. </em><strong>Begin</strong><em>MethodName</em> typically have signature similar to its synchronous variant with two additional parameters <em>AsyncCallback</em> and <em>object state</em>. <em>AsyncCallback</em> can be used to pass in the callback method for when the asynchronous call is completed and object state is used to pass in some custom data to the asynchronous call. In case when multiple asynchronous calls are made, this <strong><em>state</em></strong> can be used to differentiate these various client calls. A typical begin signature and client call would look like below.</p>  <blockquote>   <pre class="csharpcode"><span class="kwrd">public</span> IAsyncResult BeginWriteLine(<span class="kwrd">string</span> line, AsyncCallback callback, <span class="kwrd">object</span> state) { ... }</pre>
  

  <pre class="csharpcode">&#160;</pre>

  <pre class="csharpcode">Client call: </pre>

  <pre class="csharpcode">IAsyncResult result = writelineToLogfile.BeginInvoke(line, callback, state);</pre>
</blockquote>


<p>The return value from the above call is <strong>IAsyncResult</strong> which can be used to track and wait for Asynchronous call to complete. <strong>IAsyncResult</strong> has <strong>IsCompleted </strong>property which will tell whether the Asynchronous call is completed or not. <strong>IsCompleted</strong> can also be used in scenario like Polling technique where in the client can keep checking the return value of <strong>IsCompleted</strong> until the Asynchronous call is completed. There is also <strong>AsyncWaitHandle</strong> property which gives us a <strong>WaitHandle</strong> object which can be used to wait for the Asynchronous operation to complete. <strong>WaitHandle</strong> can also be used in scenario when the client will need to wait until all Asynchronous calls or a specific set of Asynchronous calls are completed. Variations of with <strong>WaitAll</strong> or <strong>WaitAny</strong> can be used for this.</p>

<p>To retrieve the return value when the Asynchronous operation completes, Call the <strong>End</strong><em>MethodName</em> by passing in the IASyncResult as input. </p>

<p>To block the client application execution until the Asynchronous call is completed, use either 1)&#160; AsyncWaitHandle or&#160; 2) Call <strong>End</strong><em>MethodName. </em>End<em>MethodName</em> will block the application execution until the Asynchronous call is completed.</p>

<p>The client applications which do not need to wait until Asynchronous call is completed can either use 1) polling technique or 2) provide an EndCallback which will then be called when the Asynchronous operation is completed.</p>

<p>Best of all, .Net also provides a means by which any synchronous call can be made Asynchronous using <strong>delegates</strong>. This in itself is a good topic and I will try covering this in a separate blog post.</p>

<p>That’s it for now and I will cover Event based Asynchronous programming in my next post.</p>

<p>Happy coding and Happy new year 2012!</p>

<p>&#160;</p>

<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:12cc2e27-fdc5-4d5d-b25b-63802ba51f53" class="wlWriterEditableSmartContent">Technorati Tags: <a href="https://technorati.com/tags/.Net" rel="tag">.Net</a>,<a href="https://technorati.com/tags/Async+Programming" rel="tag">Async Programming</a></div>]]></content:encoded>
    </item>
    <item>
      <title>Restore a deleted AD object using C#</title>
      <link>https://docs.microsoft.com/archive/blogs/syamp/restore-a-deleted-ad-object-using-c</link>
      <pubDate>Sun, 04 Dec 2011 14:13:03 GMT</pubDate>
      <dc:creator><![CDATA[syamp]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/syamp/2011/12/04/restore-a-deleted-ad-object-using-c/</guid>
      <description><![CDATA[Hi There,     I am Syam Pinnaka, Developer in IAM Services team at Microsoft.     In the last...]]></description>
      <content:encoded><![CDATA[<blockquote>   <p>Hi There, </p>    <p>I am Syam Pinnaka, Developer in IAM Services team at Microsoft. </p>    <p>In the last post we have seen how to search for and find a deleted AD Object. In this post let’s see how to restored a deleted AD Object using “Restore-ADObject” Cmdlet and C#.</p>    <ol>     <li>Add a reference to below assemblies.        <pre class="csharpcode"><span class="kwrd">using</span> System.Management.Automation;
<span class="kwrd">using</span> System.Management.Automation.Runspaces;</pre>

      <p>Note: You can get the System.Management.Automation assembly from <a href="https://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=11310">here</a>.</p>
      </li>

    <li>Create an AD run space. 
      <pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> InitialSessionState iss = <span class="kwrd">null</span>;
<span class="kwrd">private</span> <span class="kwrd">static</span> Runspace myRunSpace = <span class="kwrd">null</span>;

iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(<span class="kwrd">new</span> <span class="kwrd">string</span>[] { <span class="str">&quot;activedirectory&quot;</span> });
myRunSpace = RunspaceFactory.CreateRunspace(iss);
myRunSpace.Open();</pre>
      </li>

    <li>Create Pipeline. 
      <pre class="csharpcode">Pipeline pipeLine = myRunSpace.CreatePipeline();</pre>
      </li>

    <li>Build “Get-ADObject” and “Restore-ADObject” commands. 
      <pre class="csharpcode"><span class="kwrd">string</span> filter = <span class="str">&quot;(ObjectClass -eq 'group') -and (&quot;</span> + attributeName + <span class="str">&quot; -like '&quot;</span> + attributeValue + <span class="str">&quot;'&quot;</span> 
+ <span class="str">&quot;) -and (isDeleted -eq 'TRUE')&quot;</span>;

<span class="kwrd">string</span> domain = “your-domain”;

Command myCommand = <span class="kwrd">new</span> Command(<span class="str">&quot;Get-ADObject&quot;</span>);
myCommand.Parameters.Add(<span class="str">&quot;Filter&quot;</span>, filter);
myCommand.Parameters.Add(<span class="str">&quot;Server&quot;</span>, domain);
myCommand.Parameters.Add(<span class="str">&quot;IncludeDeletedObjects&quot;</span>);

pipeLine.Commands.Add(myCommand);

Note: The above filter takes AD attributeName and attributeValue to search <span class="kwrd">for</span> an <span class="kwrd">object</span>. Also the above filter <span class="kwrd">is</span> targeted at searching <span class="kwrd">for</span> ‘groups’, <span class="kwrd">if</span> you want to find any <span class="kwrd">object</span>, you can removed <span class="kwrd">this</span> condition from the filter.

Command restoreCommand = <span class="kwrd">new</span> Command(<span class="str">&quot;Restore-ADObject&quot;</span>);
pipeLine.Commands.Add(restoreCommand);</pre>
      </li>

    <li>Run the command. 
      <pre class="csharpcode">Collection&lt;PSObject&gt; commandResults = pipeLine.Invoke();</pre>
    </li>

    <li>
      <pre class="csharpcode">Capture the results.<pre class="csharpcode"><span class="kwrd">foreach</span> (PSObject cmdlet <span class="kwrd">in</span> commandResults)
{
    <span class="kwrd">string</span> cmdletName = cmdlet.BaseObject.ToString();
    System.Diagnostics.Debug.Print(cmdletName);

    <span class="rem">//do whatever you want with the results.</span>
}
</pre></pre>
    </li>
  </ol>

  <pre class="csharpcode">That’s it and happy coding!</pre>

  <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:80d662b7-e730-4bd0-88bc-e2bb5673c422" class="wlWriterEditableSmartContent">Technorati Tags: <a href="https://technorati.com/tags/AD" rel="tag">AD</a>,<a href="https://technorati.com/tags/.NET" rel="tag">.NET</a>,<a href="https://technorati.com/tags/Cmdlet" rel="tag">Cmdlet</a></div>
  </blockquote>]]></content:encoded>
    </item>
    <item>
      <title>Search for and find a deleted AD object using C#</title>
      <link>https://docs.microsoft.com/archive/blogs/syamp/search-for-and-find-a-deleted-ad-object-using-c</link>
      <pubDate>Wed, 23 Nov 2011 11:56:00 GMT</pubDate>
      <dc:creator><![CDATA[syamp]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/syamp/2011/11/23/search-for-and-find-a-deleted-ad-object-using-c/</guid>
      <description><![CDATA[&#160;  Hi There,   I am Syam Pinnaka, Developer in IAM Services team at Microsoft. In one of my...]]></description>
      <content:encoded><![CDATA[<p>&#160;</p>  <p>Hi There, </p>  <p>I am Syam Pinnaka, Developer in IAM Services team at Microsoft. In one of my recent projects I had a requirement to search for and restore a deleted AD object. AD Cmdlets provides a means for this using “Get-ADObject” and “Restore-ADObject”. However if you wanted to use these Cmdlets from C# here is how you do it. </p>  <blockquote>   <ol>     <li>Add a reference to below assemblies.        <pre class="csharpcode"><span class="kwrd">using</span> System.Management.Automation;
<span class="kwrd">using</span> System.Management.Automation.Runspaces;</pre>

      <pre class="csharpcode">Note: You can get the System.Management.Automation assembly from <a href="https://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=11310"><u>here</u></a>.</pre>
      </li>

    <li>Create an AD run space. 
      <pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> InitialSessionState iss = <span class="kwrd">null</span>;
<span class="kwrd">private</span> <span class="kwrd">static</span> Runspace myRunSpace = <span class="kwrd">null</span>;

iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(<span class="kwrd">new</span> <span class="kwrd">string</span>[] { <span class="str">&quot;activedirectory&quot;</span> });
myRunSpace = RunspaceFactory.CreateRunspace(iss);
myRunSpace.Open();</pre>
      </li>

    <li>Create Pipeline. 
      <pre class="csharpcode">Pipeline pipeLine = myRunSpace.CreatePipeline();</pre>
      </li>

    <li>Build “Get-ADObject” command. 
      <pre class="csharpcode"><span class="kwrd">string</span> filter = <span class="str">&quot;(ObjectClass -eq 'group') -and (&quot;</span> + attributeName + <span class="str">&quot; -like '&quot;</span> + attributeValue + <span class="str">&quot;'&quot;</span> </pre>

      <pre class="csharpcode">+ <span class="str">&quot;) -and (isDeleted -eq 'TRUE')&quot;</span>;

<span class="kwrd">string</span> domain = “your-domain”;

Command myCommand = <span class="kwrd">new</span> Command(<span class="str">&quot;Get-ADObject&quot;</span>);
myCommand.Parameters.Add(<span class="str">&quot;Filter&quot;</span>, filter);
myCommand.Parameters.Add(<span class="str">&quot;Server&quot;</span>, domain);
myCommand.Parameters.Add(<span class="str">&quot;IncludeDeletedObjects&quot;</span>);

pipeLine.Commands.Add(myCommand);</pre>

      <p><font face="Consolas"><font size="2"><strong>Note</strong>: The above filter takes AD attributeName and attributeValue to search for an object. Also the above filter is targeted at searching for ‘groups’, if you want to find any object, you can removed this condition from the filter.</font></font></p>
      </li>

    <li>Run the command. 
      <pre class="csharpcode">Collection&lt;PSObject&gt; commandResults = pipeLine.Invoke();</pre>
      </li>

    <li>Capture the results 
      <pre class="csharpcode"><span class="kwrd">if</span> (commandResults.Count &gt; 1)
{
    <span class="kwrd">throw</span> <span class="kwrd">new</span> Exception(<span class="str">&quot;Found more than one deleted group with '&quot;</span> + attributeName + <span class="str">&quot;'='&quot;</span> </pre>

      <pre class="csharpcode">+ attributeValue + <span class="str">&quot;' in domain '&quot;</span> + domain + <span class="str">&quot;'&quot;</span>);
}

<span class="kwrd">foreach</span> (PSObject cmdlet <span class="kwrd">in</span> commandResults)
{
    <span class="kwrd">string</span> cmdletName = cmdlet.BaseObject.ToString();
    System.Diagnostics.Debug.Print(cmdletName);

    <span class="rem">//do whatever you want with the results.</span>
}</pre>
    </li>
  </ol>

  <p align="left"></p>

  <pre class="csharpcode"><font face="Segoe UI">That’s it and Happy coding! I will show you how to restore a deleted </font><font face="Segoe UI">AD object in my next post.</font></pre>

  <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:48bcc8d5-9d83-4e5f-ab44-9563ad4c54fa" class="wlWriterEditableSmartContent">Technorati Tags: <a href="https://technorati.com/tags/.NET" rel="tag">.NET</a>,<a href="https://technorati.com/tags/AD" rel="tag">AD</a></div>
  </blockquote>]]></content:encoded>
    </item>
  </channel>
</rss>