<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://weblogs.asp.net/utility/FeedStylesheets/atom.xsl" media="screen"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><title type="html">The Technical Adventures of Adam Weigert</title><subtitle type="html" /><id>http://weblogs.asp.net/adweigert/atom.aspx</id><link rel="alternate" type="text/html" href="http://weblogs.asp.net/adweigert/default.aspx" /><link rel="self" type="application/atom+xml" href="http://weblogs.asp.net/adweigert/atom.aspx" /><generator uri="http://communityserver.org" version="3.0.20510.895">Community Server</generator><updated>2008-04-30T09:11:00Z</updated><entry><title>I &lt;3 PowerShell</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/adweigert/archive/2011/03/28/i-lt-3-powershell.aspx" /><id>http://weblogs.asp.net/adweigert/archive/2011/03/28/i-lt-3-powershell.aspx</id><published>2011-03-28T15:58:00Z</published><updated>2011-03-28T15:58:00Z</updated><content type="html">This blog author has moved to &lt;a href="http://iheartpowershell.com"&gt;iheartpowershell.com&lt;/a&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=7736065" width="1" height="1"&gt;</content><author><name>adweigert</name><uri>http://weblogs.asp.net/members/adweigert.aspx</uri></author><category term="powershell" scheme="http://weblogs.asp.net/adweigert/archive/tags/powershell/default.aspx" /><category term="asp.net" scheme="http://weblogs.asp.net/adweigert/archive/tags/asp.net/default.aspx" /></entry><entry><title>dynamic? I'll never use that ... or then again, maybe it could ...</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/adweigert/archive/2010/05/26/dynamic-i-ll-never-use-that-or-then-again-maybe-it-could.aspx" /><id>http://weblogs.asp.net/adweigert/archive/2010/05/26/dynamic-i-ll-never-use-that-or-then-again-maybe-it-could.aspx</id><published>2010-05-27T01:04:00Z</published><updated>2010-05-27T01:04:00Z</updated><content type="html">&lt;P mce_keep="true"&gt;So, I don't know about you, but I was highly skeptical of the dynamic keywork when it was announced. I thought to myself, oh great, just another move towards VB compliance.&lt;/P&gt;
&lt;P mce_keep="true"&gt;Well after seeing it being used in things like &lt;A title=DynamicXml href="http://www.gotnet.biz/Blog/post/Fluent-XML-Parsing-Using-CSharp-Dynamic-Type-Part-1.aspx" mce_href="http://www.gotnet.biz/Blog/post/Fluent-XML-Parsing-Using-CSharp-Dynamic-Type-Part-1.aspx"&gt;DynamicXml&lt;/A&gt; (which I use for this example) I then was working with a MVC&amp;nbsp;controller and wanted to move some things like operation timeout of an action to a configuration file. Thinking big picture, it'd be really nice to have configuration for all my controllers like that. Ugh, I don't want to have to create all those ConfigurationElement objects...&lt;/P&gt;
&lt;P mce_keep="true"&gt;So, I started thinking self, use what you know and do something cool ...&lt;/P&gt;
&lt;P mce_keep="true"&gt;Well after a bit of zoning out, self came up with use a dynamic object duh! I was thinking of a config like this ...&lt;/P&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;PRE class=csharpcode&gt;&lt;SPAN class=kwrd&gt;&amp;lt;&lt;/SPAN&gt;&lt;SPAN class=html&gt;controllers&lt;/SPAN&gt;&lt;SPAN class=kwrd&gt;&amp;gt;&lt;/SPAN&gt;
  &lt;SPAN class=kwrd&gt;&amp;lt;&lt;/SPAN&gt;&lt;SPAN class=html&gt;add&lt;/SPAN&gt; &lt;SPAN class=attr&gt;type&lt;/SPAN&gt;&lt;SPAN class=kwrd&gt;="MyApp.Web.Areas.ComputerManagement.Controllers.MyController, MyApp.Web"&lt;/SPAN&gt;&lt;SPAN class=kwrd&gt;&amp;gt;&lt;/SPAN&gt;
    &lt;SPAN class=kwrd&gt;&amp;lt;&lt;/SPAN&gt;&lt;SPAN class=html&gt;detail&lt;/SPAN&gt; &lt;SPAN class=attr&gt;timeout&lt;/SPAN&gt;&lt;SPAN class=kwrd&gt;="00:00:30"&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;/&amp;gt;&lt;/SPAN&gt;
  &lt;SPAN class=kwrd&gt;&amp;lt;/&lt;/SPAN&gt;&lt;SPAN class=html&gt;add&lt;/SPAN&gt;&lt;SPAN class=kwrd&gt;&amp;gt;&lt;/SPAN&gt;
&lt;SPAN class=kwrd&gt;&amp;lt;/&lt;/SPAN&gt;&lt;SPAN class=html&gt;controllers&lt;/SPAN&gt;&lt;SPAN class=kwrd&gt;&amp;gt;&lt;/SPAN&gt;&lt;/PRE&gt;
&lt;P mce_keep="true"&gt;So, I ended up with a couple configuration classes like this ...&lt;/P&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;PRE class=csharpcode&gt;blic &lt;SPAN class=kwrd&gt;abstract&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;class&lt;/SPAN&gt; DynamicConfigurationElement : ConfigurationElement
{
    &lt;SPAN class=kwrd&gt;protected&lt;/SPAN&gt; DynamicConfigurationElement()
    {
        &lt;SPAN class=kwrd&gt;this&lt;/SPAN&gt;.DynamicObject = &lt;SPAN class=kwrd&gt;new&lt;/SPAN&gt; DynamicConfiguration();
    }

    &lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; DynamicConfiguration DynamicObject
    {
        get;
        &lt;SPAN class=kwrd&gt;private&lt;/SPAN&gt; set;
    }

    &lt;SPAN class=kwrd&gt;protected&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;override&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;bool&lt;/SPAN&gt; OnDeserializeUnrecognizedAttribute(&lt;SPAN class=kwrd&gt;string&lt;/SPAN&gt; name, &lt;SPAN class=kwrd&gt;string&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;value&lt;/SPAN&gt;)
    {
        &lt;SPAN class=kwrd&gt;this&lt;/SPAN&gt;.DynamicObject.Add(name, &lt;SPAN class=kwrd&gt;value&lt;/SPAN&gt;);
        &lt;SPAN class=kwrd&gt;return&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;true&lt;/SPAN&gt;;
    }

    &lt;SPAN class=kwrd&gt;protected&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;override&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;bool&lt;/SPAN&gt; OnDeserializeUnrecognizedElement(&lt;SPAN class=kwrd&gt;string&lt;/SPAN&gt; elementName, XmlReader reader)
    {
        &lt;SPAN class=kwrd&gt;this&lt;/SPAN&gt;.DynamicObject.Add(elementName, &lt;SPAN class=kwrd&gt;new&lt;/SPAN&gt; DynamicXml((XElement)XElement.ReadFrom(reader)));
        &lt;SPAN class=kwrd&gt;return&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;true&lt;/SPAN&gt;;
    }
}

&lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;class&lt;/SPAN&gt; ControllerConfigurationElement : DynamicConfigurationElement
{
    [ConfigurationProperty(&lt;SPAN class=str&gt;"type"&lt;/SPAN&gt;, Options = ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey)]
    &lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;string&lt;/SPAN&gt; TypeName
    {
        get { &lt;SPAN class=kwrd&gt;return&lt;/SPAN&gt; (&lt;SPAN class=kwrd&gt;string&lt;/SPAN&gt;)&lt;SPAN class=kwrd&gt;this&lt;/SPAN&gt;[&lt;SPAN class=str&gt;"type"&lt;/SPAN&gt;]; }
    }

    &lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; Type Type
    {
        get { &lt;SPAN class=kwrd&gt;return&lt;/SPAN&gt; Type.GetType(&lt;SPAN class=kwrd&gt;this&lt;/SPAN&gt;.TypeName, &lt;SPAN class=kwrd&gt;true&lt;/SPAN&gt;); }
    }
}

&lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;class&lt;/SPAN&gt; ControllerConfigurationElementCollection : ConfigurationElementCollection
{
    &lt;SPAN class=kwrd&gt;protected&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;override&lt;/SPAN&gt; ConfigurationElement CreateNewElement()
    {
        &lt;SPAN class=kwrd&gt;return&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;new&lt;/SPAN&gt; ControllerConfigurationElement();
    }

    &lt;SPAN class=kwrd&gt;protected&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;override&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;object&lt;/SPAN&gt; GetElementKey(ConfigurationElement element)
    {
        &lt;SPAN class=kwrd&gt;return&lt;/SPAN&gt; ((ControllerConfigurationElement)element).Type;
    }
}&lt;/PRE&gt;
&lt;P mce_keep="true"&gt;And then had to create the meat of the DynamicConfiguration class which looks like this ...&lt;/P&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;PRE class=csharpcode&gt;&lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;class&lt;/SPAN&gt; DynamicConfiguration : DynamicObject
{
    &lt;SPAN class=kwrd&gt;private&lt;/SPAN&gt; Dictionary&amp;lt;&lt;SPAN class=kwrd&gt;string&lt;/SPAN&gt;, &lt;SPAN class=kwrd&gt;object&lt;/SPAN&gt;&amp;gt; properties = &lt;SPAN class=kwrd&gt;new&lt;/SPAN&gt; Dictionary&amp;lt;&lt;SPAN class=kwrd&gt;string&lt;/SPAN&gt;, &lt;SPAN class=kwrd&gt;object&lt;/SPAN&gt;&amp;gt;(StringComparer.CurrentCultureIgnoreCase);

    &lt;SPAN class=kwrd&gt;internal&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;void&lt;/SPAN&gt; Add&amp;lt;T&amp;gt;(&lt;SPAN class=kwrd&gt;string&lt;/SPAN&gt; name, T &lt;SPAN class=kwrd&gt;value&lt;/SPAN&gt;)
    {
        &lt;SPAN class=kwrd&gt;this&lt;/SPAN&gt;.properties.Add(name, &lt;SPAN class=kwrd&gt;value&lt;/SPAN&gt;);
    }

    &lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;override&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;bool&lt;/SPAN&gt; TryGetMember(GetMemberBinder binder, &lt;SPAN class=kwrd&gt;out&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;object&lt;/SPAN&gt; result)
    {
        var propertyName = binder.Name;

        result = &lt;SPAN class=kwrd&gt;null&lt;/SPAN&gt;;

        &lt;SPAN class=kwrd&gt;if&lt;/SPAN&gt; (&lt;SPAN class=kwrd&gt;this&lt;/SPAN&gt;.properties.ContainsKey(propertyName))
        {
            result = &lt;SPAN class=kwrd&gt;this&lt;/SPAN&gt;.properties[propertyName];
        }

        &lt;SPAN class=kwrd&gt;return&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;true&lt;/SPAN&gt;;
    }
}&lt;/PRE&gt;
&lt;P mce_keep="true"&gt;So all being said, I made a base controller class like a good little MVC-itizen ...&lt;/P&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;PRE class=csharpcode&gt;&lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;abstract&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;class&lt;/SPAN&gt; BaseController : Controller
{
    &lt;SPAN class=kwrd&gt;protected&lt;/SPAN&gt; BaseController()
        : &lt;SPAN class=kwrd&gt;base&lt;/SPAN&gt;()
    {
        var configuration = ManagementConfigurationSection.GetInstance();
            
        var controllerConfiguration = configuration.Controllers.ForType(&lt;SPAN class=kwrd&gt;this&lt;/SPAN&gt;.GetType());

        &lt;SPAN class=kwrd&gt;if&lt;/SPAN&gt; (controllerConfiguration != &lt;SPAN class=kwrd&gt;null&lt;/SPAN&gt;)
        {
            &lt;SPAN class=kwrd&gt;this&lt;/SPAN&gt;.Configuration = controllerConfiguration.DynamicObject;
        }
    }

    &lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; dynamic Configuration
    {
        get;
        &lt;SPAN class=kwrd&gt;private&lt;/SPAN&gt; set;
    }
}&lt;/PRE&gt;
&lt;P mce_keep="true"&gt;And used it like this ...&lt;/P&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;PRE class=csharpcode&gt;&lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;class&lt;/SPAN&gt; MyController : BaseController
{
    &lt;SPAN class=kwrd&gt;static&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;readonly&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;string&lt;/SPAN&gt; DefaultDetailTimeout = TimeSpan.MaxValue.ToString();

    &lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; MyController()
    {
        &lt;SPAN class=kwrd&gt;this&lt;/SPAN&gt;.DetailTimeout = TimeSpan.Parse(&lt;SPAN class=kwrd&gt;this&lt;/SPAN&gt;.Configuration.Detail.Timeout ?? DefaultDetailTimeout);
    }

    &lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; TimeSpan DetailTimeout
    {
        get;
        &lt;SPAN class=kwrd&gt;private&lt;/SPAN&gt; set;
    }
}&lt;/PRE&gt;
&lt;P mce_keep="true"&gt;And there I have an actual use for the dynamic keyword ... never thoguht I'd see the day when I first heard of it as I don't do much COM work ... oh dont' forget this little helper extension methods to find the controller configuration by the controller type.&lt;/P&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;PRE class=csharpcode&gt;&lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;static&lt;/SPAN&gt; ControllerConfigurationElement ForType&amp;lt;T&amp;gt;(&lt;SPAN class=kwrd&gt;this&lt;/SPAN&gt; ControllerConfigurationElementCollection collection)
{
    Contract.Requires(collection != &lt;SPAN class=kwrd&gt;null&lt;/SPAN&gt;);
    &lt;SPAN class=kwrd&gt;return&lt;/SPAN&gt; ForType(collection, &lt;SPAN class=kwrd&gt;typeof&lt;/SPAN&gt;(T));
}

&lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;static&lt;/SPAN&gt; ControllerConfigurationElement ForType(&lt;SPAN class=kwrd&gt;this&lt;/SPAN&gt; ControllerConfigurationElementCollection collection, Type type)
{
    Contract.Requires(collection != &lt;SPAN class=kwrd&gt;null&lt;/SPAN&gt;);
    Contract.Requires(type != &lt;SPAN class=kwrd&gt;null&lt;/SPAN&gt;);
    &lt;SPAN class=kwrd&gt;return&lt;/SPAN&gt; collection.Cast&amp;lt;ControllerConfigurationElement&amp;gt;().Where(element =&amp;gt; element.Type == type).SingleOrDefault();
}&lt;/PRE&gt;
&lt;P mce_keep="true"&gt;Sure, it isn't perfect and I'm sure I can tweak it over time, but I thought it was a pretty cool way to take advantage of the dynamic keyword functionality. Just remember, it only validates you did it right at runtime, which isn't that bad ... is it? And yes, I did make it case-insensitive so my code didn't have to look like my XML objects, tweak it to your liking if you dare to use this creation.&lt;/P&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=7507189" width="1" height="1"&gt;</content><author><name>adweigert</name><uri>http://weblogs.asp.net/members/adweigert.aspx</uri></author><category term="c#" scheme="http://weblogs.asp.net/adweigert/archive/tags/c_2300_/default.aspx" /><category term="dynamic" scheme="http://weblogs.asp.net/adweigert/archive/tags/dynamic/default.aspx" /></entry><entry><title>The WaitForAll Roadshow</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/adweigert/archive/2010/05/26/the-waitforall-roadshow.aspx" /><id>http://weblogs.asp.net/adweigert/archive/2010/05/26/the-waitforall-roadshow.aspx</id><published>2010-05-26T12:41:00Z</published><updated>2010-05-26T12:41:00Z</updated><content type="html">&lt;P mce_keep="true"&gt;OK, so I took for granted some imaginative uses of WaitForAll but lacking that, here is how I am using. First, I have a nice little class called Parallel that allows me to spin together a list of tasks (actions) and then use WaitForAll, so here it is, WaitForAll's 15 minutes of fame ...&lt;/P&gt;
&lt;P mce_keep="true"&gt;First Parallel that allows me to spin together several Action delegates to execute, well in parallel.&lt;/P&gt;
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;
&lt;P mce_keep="true"&gt;&lt;PRE&gt;public static class Parallel
{
    public static ParallelQuery&amp;lt;Action&amp;gt; Task(Action action)
    {
        return new Action[] { action }.AsParallel();
    }

    public static ParallelQuery&amp;lt;Action&amp;lt;T&amp;gt;&amp;gt; Task&amp;lt;T&amp;gt;(Action&amp;lt;T&amp;gt; action)
    {
        return new Action&amp;lt;T&amp;gt;[] { action }.AsParallel();
    }

    public static ParallelQuery&amp;lt;Action&amp;gt; Task(this ParallelQuery&amp;lt;Action&amp;gt; actions, Action action)
    {
        var list = new List&amp;lt;Action&amp;gt;(actions);
        list.Add(action);
        return list.AsParallel();
    }

    public static ParallelQuery&amp;lt;Action&amp;lt;T&amp;gt;&amp;gt; Task&amp;lt;T&amp;gt;(this ParallelQuery&amp;lt;Action&amp;lt;T&amp;gt;&amp;gt; actions, Action&amp;lt;T&amp;gt; action)
    {
        var list = new List&amp;lt;Action&amp;lt;T&amp;gt;&amp;gt;(actions);
        list.Add(action);
        return list.AsParallel();
    }
}
&lt;/PRE&gt;
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;
&lt;P mce_keep="true"&gt;Next, this is an example usage from an app I'm working on that just is rendering some basic computer information via WMI and performance counters. The WMI calls can be expensive given the distance and link speed of some of the computers it will be trying to communicate with. This is the actual MVC action from my controller to return the data for an individual computer.&lt;/P&gt;
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;&lt;PRE&gt;public PartialViewResult Detail(string computerName)
{
    var computer = this.Computers.Get(computerName);
    var perf = Factory.GetInstance&amp;lt;IPerformanceCounterProvider&amp;gt;();

    var detail = new ComputerDetailViewModel()
        {
            Computer = computer
        };

    try
    {
        var work = Parallel
            .Task(delegate 
            {
                // Win32_ComputerSystem
                var key = computer.Name + "_Win32_ComputerSystem";
                var system = this.Cache.Get&amp;lt;Win32_ComputerSystem&amp;gt;(key);

                if (system == null)
                {
                    using (var impersonation = computer.ImpersonateElevatedIdentity())
                    {
                        system = computer.GetWmiContext().GetInstances&amp;lt;Win32_ComputerSystem&amp;gt;().Single();
                    }

                    this.Cache.Set(key, system);
                }

                detail.TotalMemory = system.TotalPhysicalMemory;
                detail.Manufacturer = system.Manufacturer;
                detail.Model = system.Model;
                detail.NumberOfProcessors = system.NumberOfProcessors;
            })
            .Task(delegate 
            {
                // Win32_OperatingSystem
                var key = computer.Name + "_Win32_OperatingSystem";
                var os = this.Cache.Get&amp;lt;Win32_OperatingSystem&amp;gt;(key);

                if (os == null)
                {
                    using (var impersonation = computer.ImpersonateElevatedIdentity())
                    {
                        os = computer.GetWmiContext().GetInstances&amp;lt;Win32_OperatingSystem&amp;gt;().Single();
                    }

                    this.Cache.Set(key, os);
                }

                detail.OperatingSystem = os.Caption;
                detail.OSVersion = os.Version;
            })
            // Performance Counters
            .Task(delegate 
            {
                using (var impersonation = computer.ImpersonateElevatedIdentity())
                {
                    detail.AvailableBytes = perf.GetSample(computer, "Memory", "Available Bytes");
                }
            })
            .Task(delegate 
            {
                using (var impersonation = computer.ImpersonateElevatedIdentity())
                {
                    detail.TotalProcessorUtilization = perf.GetValue(computer, "Processor", "% Processor Time", "_Total");
                }
            }).WithExecutionMode(ParallelExecutionMode.ForceParallelism);

        &lt;STRONG&gt;if (!work.WaitForAll(TimeSpan.FromSeconds(15), task =&amp;gt; task()))
        {
            return PartialView("Timeout");
        }&lt;/STRONG&gt;
    }
    catch (Exception ex)
    {
        this.LogException(ex);
        return PartialView("Error.ascx");
    }

    return PartialView(detail);
}
&lt;/PRE&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=7506631" width="1" height="1"&gt;</content><author><name>adweigert</name><uri>http://weblogs.asp.net/members/adweigert.aspx</uri></author><category term="c#" scheme="http://weblogs.asp.net/adweigert/archive/tags/c_2300_/default.aspx" /><category term="LINQ" scheme="http://weblogs.asp.net/adweigert/archive/tags/LINQ/default.aspx" /><category term="ParallelQuery" scheme="http://weblogs.asp.net/adweigert/archive/tags/ParallelQuery/default.aspx" /><category term="Threading" scheme="http://weblogs.asp.net/adweigert/archive/tags/Threading/default.aspx" /><category term="PLINQ" scheme="http://weblogs.asp.net/adweigert/archive/tags/PLINQ/default.aspx" /></entry><entry><title>Reinventing the Paged IEnumerable, Weigert Style!</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/adweigert/archive/2010/05/25/reinventing-the-paged-ienumerable-weigert-style.aspx" /><id>http://weblogs.asp.net/adweigert/archive/2010/05/25/reinventing-the-paged-ienumerable-weigert-style.aspx</id><published>2010-05-25T20:16:00Z</published><updated>2010-05-25T20:16:00Z</updated><content type="html">&lt;P mce_keep="true"&gt;I am pretty sure someone else has done this, I've seen variations as PagedList&amp;lt;T&amp;gt;, but this is my style of a paged IEnumerable collection. I just store a reference to the collection and generate the paged data when the enumerator is needed, so you could technically add to a list that I'm referencing and the properties and results would be adjusted accordingly.&lt;/P&gt;
&lt;P mce_keep="true"&gt;I don't mind reinventing the wheel when I can add some of my own personal flare ...&lt;/P&gt;
&lt;P mce_keep="true"&gt;&lt;PRE&gt;// Extension method for easy use
public static PagedEnumerable&lt;T&gt; AsPaged&lt;T&gt;(this IEnumerable&lt;T&gt; collection, int currentPage = 1, int pageSize = 0)
{
    Contract.Requires(collection != null);
    Contract.Assume(currentPage &amp;gt;= 1);
    Contract.Assume(pageSize &amp;gt;= 0);

    return new PagedEnumerable&lt;T&gt;(collection, currentPage, pageSize);
}

public class PagedEnumerable&lt;T&gt; : IEnumerable&lt;T&gt;
{
    public PagedEnumerable(IEnumerable&lt;T&gt; collection, int currentPage = 1, int pageSize = 0)
    {
        Contract.Requires(collection != null);
        Contract.Assume(currentPage &amp;gt;= 1);
        Contract.Assume(pageSize &amp;gt;= 0);

        this.collection = collection;
        this.PageSize = pageSize;
        this.CurrentPage = currentPage;
    }

    IEnumerable&lt;T&gt; collection;

    int currentPage;
    public int CurrentPage
    {
        get 
        {
            if (this.currentPage &amp;gt; this.TotalPages)
            {
                return this.TotalPages;
            }

            return this.currentPage; 
        }
        set
        {
            if (value &amp;lt; 1)
            {
                this.currentPage = 1;
            }
            else if (value &amp;gt; this.TotalPages)
            {
                this.currentPage = this.TotalPages;
            }
            else
            {
                this.currentPage = value;
            }
        }
    }

    int pageSize;
    public int PageSize
    {
        get 
        {
            if (this.pageSize == 0)
            {
                return this.collection.Count();
            }

            return this.pageSize;
        }
        set
        {
            this.pageSize = (value &amp;lt; 0) ? 0 : value;
        }
    }

    public int TotalPages
    {
        get
        {
            return (int)Math.Ceiling(this.collection.Count() / (double)this.PageSize);
        }
    }

    public IEnumerator&lt;T&gt; GetEnumerator()
    {
        var pageSize = this.PageSize;
        var currentPage = this.CurrentPage;
        var startCount = (currentPage - 1) * pageSize;
            
        return this.collection.Skip(startCount).Take(pageSize).GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}
&lt;/PRE&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=7505494" width="1" height="1"&gt;</content><author><name>adweigert</name><uri>http://weblogs.asp.net/members/adweigert.aspx</uri></author><category term="c#" scheme="http://weblogs.asp.net/adweigert/archive/tags/c_2300_/default.aspx" /><category term="LINQ" scheme="http://weblogs.asp.net/adweigert/archive/tags/LINQ/default.aspx" /></entry><entry><title>PLINQ Adventure Land - WaitForAll</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/adweigert/archive/2010/05/23/plinq-adventure-land-waitforall.aspx" /><id>http://weblogs.asp.net/adweigert/archive/2010/05/23/plinq-adventure-land-waitforall.aspx</id><published>2010-05-23T17:28:00Z</published><updated>2010-05-23T17:28:00Z</updated><content type="html">&lt;P mce_keep="true"&gt;PLINQ is awesome for getting a lot of work done fast, but one thing I haven't figured out yet is how to start work with PLINQ but only let it execute for a maximum amount of time and react if it is taking too long. So, as I must admit I am still learning PLINQ, I created this extension in that ignorance. It behaves similar to ForAll&amp;lt;&amp;gt; but takes a timeout and returns false if the threads don't complete in the specified amount of time. Hope this helps someone else take PLINQ further, it definitely has helped for me ...&lt;/P&gt;
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;&lt;PRE&gt;public static bool WaitForAll&amp;lt;T&amp;gt;(this ParallelQuery&amp;lt;T&amp;gt; query, TimeSpan timeout, Action&amp;lt;T&amp;gt; action)
{
    Contract.Requires(query != null);
    Contract.Requires(action != null);

    var exception = (Exception)null;
    var cts = new CancellationTokenSource();
            
    var forAllWithCancellation = new Action(delegate
    {
        try
        {
            query.WithCancellation(cts.Token).ForAll(action);
        }
        catch (OperationCanceledException)
        {
            // NOOP
        }
        catch (AggregateException ex)
        {
            exception = ex;
        }
    });
            
    var mrs = new ManualResetEvent(false);
    var callback = new AsyncCallback(delegate { mrs.Set(); });
    var result = forAllWithCancellation.BeginInvoke(callback, null);
            
    if (mrs.WaitOne(timeout))
    {
        forAllWithCancellation.EndInvoke(result);

        if (exception != null)
        {
            throw exception;
        }

        return true;
    }
    else
    {
        cts.Cancel();
        return false;
    }
}&lt;/PRE&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=7500517" width="1" height="1"&gt;</content><author><name>adweigert</name><uri>http://weblogs.asp.net/members/adweigert.aspx</uri></author><category term="c#" scheme="http://weblogs.asp.net/adweigert/archive/tags/c_2300_/default.aspx" /><category term="LINQ" scheme="http://weblogs.asp.net/adweigert/archive/tags/LINQ/default.aspx" /><category term="ParallelQuery" scheme="http://weblogs.asp.net/adweigert/archive/tags/ParallelQuery/default.aspx" /><category term="Threading" scheme="http://weblogs.asp.net/adweigert/archive/tags/Threading/default.aspx" /></entry><entry><title>Overriding Inheritance for IIS 6.0 Virtual Directories</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/adweigert/archive/2010/02/09/overriding-inheritance-for-iis-6-0-virtual-directories.aspx" /><id>http://weblogs.asp.net/adweigert/archive/2010/02/09/overriding-inheritance-for-iis-6-0-virtual-directories.aspx</id><published>2010-02-09T14:46:00Z</published><updated>2010-02-09T14:46:00Z</updated><content type="html">&lt;P mce_keep="true"&gt;If you have an IIS site that has a mixture of ASP.NET 1.1 and 2.0 virtual directories below it, changing the root site ASP.NET settings could affect the virtual directory ASP.NET settings as well since IIS inherits except for explicit overrides. This little PowerShell script will take each setting and persist it to the virtual directory so you are able to freely change the root site settings without affecting the applications below it.&lt;/P&gt;
&lt;P mce_keep="true"&gt;Please remember to backup your IIS settings before you do this, just incase it has adverse affects on your IIS server.&lt;/P&gt;&lt;PRE&gt;&lt;P mce_keep="true"&gt;function Persist-IIsSettings ( $obj ) {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Write-Host $obj.Path&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; $obj.Properties.GetEnumerator() |% {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; $propertyName = $_.PropertyName&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; $value&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; = $obj.Get($propertyName)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if ( -not ($value -is [System.__ComObject]) ) {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; $obj.Put($propertyName, $value)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; $obj.SetInfo()&lt;/P&gt;

&lt;P mce_keep="true"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; $obj.Children |% { Persist-IIsSettings $_ }&lt;BR&gt;}&lt;/P&gt;

&lt;P mce_keep="true"&gt;Persist-IIsSettings ([ADSI]"IIS://localhost/W3SVC/1/ROOT")&lt;/P&gt;
&lt;/PRE&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=7340670" width="1" height="1"&gt;</content><author><name>adweigert</name><uri>http://weblogs.asp.net/members/adweigert.aspx</uri></author><category term="powershell" scheme="http://weblogs.asp.net/adweigert/archive/tags/powershell/default.aspx" /><category term="asp.net" scheme="http://weblogs.asp.net/adweigert/archive/tags/asp.net/default.aspx" /><category term="IIS" scheme="http://weblogs.asp.net/adweigert/archive/tags/IIS/default.aspx" /></entry><entry><title>ASP.NET PowerShell Data Source Control</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/adweigert/archive/2010/02/03/asp-net-powershell-data-source-control.aspx" /><id>http://weblogs.asp.net/adweigert/archive/2010/02/03/asp-net-powershell-data-source-control.aspx</id><published>2010-02-04T04:16:00Z</published><updated>2010-02-04T04:16:00Z</updated><content type="html">&lt;P mce_keep="true"&gt;Extending on the small proof-of-concept I mentioned &lt;A href="http://weblogs.asp.net/adweigert/archive/2010/02/02/asp-net-powershell-runspace-control.aspx" mce_href="http://weblogs.asp.net/adweigert/archive/2010/02/02/asp-net-powershell-runspace-control.aspx"&gt;yesterday&lt;/A&gt; I created this simple data source control that lets you bind a Repeater or DataGrid to it like an ObjectDataSource control but it executes a PowerShell script to retrieve the results.&lt;/P&gt;&lt;PRE mce_keep="true"&gt;&amp;lt;asp:PowerShellDataSource ID="EmployeesDataSource" runat="server"&amp;gt;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; [PSObject]"" | Add-Member NoteProperty "Title" "Software Engineer" -passThru | Add-Member NoteProperty "Name" "Mike Wolford" -passThru&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; [PSObject]"" | Add-Member NoteProperty "Title" "Software Evangelist" -passThru | Add-Member NoteProperty "Name" "Scott Root" -passThru&lt;BR&gt;&amp;lt;/asp:PowerShellDataSource&amp;gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&amp;lt;asp:Repeater runat="server" DataSourceID="EmployeesDataSource"&amp;gt;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;ItemTemplate&amp;gt;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;h4&amp;gt;&amp;lt;%# DataBinder.Eval(Container.DataItem, "Title") %&amp;gt;: &amp;lt;%# DataBinder.Eval(Container.DataItem, "Name") %&amp;gt;&amp;lt;/h4&amp;gt;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/ItemTemplate&amp;gt;&lt;BR&gt;&amp;lt;/asp:Repeater&amp;gt;&lt;/PRE&gt;
&lt;P mce_keep="true"&gt;If this is something that interests you, take a look over&amp;nbsp; at &lt;A href="http://aspower.codeplex.com/"&gt;http://aspower.codeplex.com/&lt;/A&gt;&lt;/P&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=7333618" width="1" height="1"&gt;</content><author><name>adweigert</name><uri>http://weblogs.asp.net/members/adweigert.aspx</uri></author><category term="powershell" scheme="http://weblogs.asp.net/adweigert/archive/tags/powershell/default.aspx" /><category term="asp.net" scheme="http://weblogs.asp.net/adweigert/archive/tags/asp.net/default.aspx" /><category term="DataSource" scheme="http://weblogs.asp.net/adweigert/archive/tags/DataSource/default.aspx" /></entry><entry><title>ASP.NET PowerShell Runspace Control</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/adweigert/archive/2010/02/02/asp-net-powershell-runspace-control.aspx" /><id>http://weblogs.asp.net/adweigert/archive/2010/02/02/asp-net-powershell-runspace-control.aspx</id><published>2010-02-03T04:16:00Z</published><updated>2010-02-03T04:16:00Z</updated><content type="html">&lt;P mce_keep="true"&gt;This is just a little concept project I am working on so I can run PowerShell scripts within my ASP.NET applications. As I am a server administrator, I love PowerShell + WMI, and bringing this power into ASP.NET my automation capabilities are being greatly simplified. I'll build on this solution as I play around with actually implementing this as a primary source of automation from support a Windows Server environment.&lt;/P&gt;
&lt;P mce_keep="true"&gt;I am aware of other projects/products that allow you to do similar things, I just needed something simple, and I don't want to code an entire page in PowerShell, just specific tasks.&lt;/P&gt;
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;A href="http://aspower.codeplex.com/"&gt;http://aspower.codeplex.com/&lt;/A&gt;&lt;/P&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=7332420" width="1" height="1"&gt;</content><author><name>adweigert</name><uri>http://weblogs.asp.net/members/adweigert.aspx</uri></author><category term="powershell" scheme="http://weblogs.asp.net/adweigert/archive/tags/powershell/default.aspx" /><category term="asp.net" scheme="http://weblogs.asp.net/adweigert/archive/tags/asp.net/default.aspx" /></entry><entry><title>LINQ: Expressive Html Tag Building</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/adweigert/archive/2009/01/01/linq-html-tag-builder-with-expressions.aspx" /><id>http://weblogs.asp.net/adweigert/archive/2009/01/01/linq-html-tag-builder-with-expressions.aspx</id><published>2009-01-02T03:31:00Z</published><updated>2009-01-02T03:31:00Z</updated><content type="html">&lt;p mce_keep="true"&gt;I hate building HTML tags in code, but it needs to be done. I just wanted to make it a little cleaner. So I came up with this method that utilizes LINQ expressions to generate the attributes for the tag. This is really only clean with simple tags, but I use it with my other tag building methods to keep them clean as well. I've seen others look for something like this and thought it'd be helpful posting it here. I haven't deeply tested this code but it shows the general concept and I'm sure it needs cleaned up a little. The following is an example calling the Tag method:&lt;/p&gt;  &lt;blockquote&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;   &lt;div class="csharpcode"&gt;     &lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;Tag( &lt;span class="str"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;The Technical Adventures of Adam Weigert&amp;quot;&lt;/span&gt;, href =&amp;gt; &lt;span class="str"&gt;&amp;quot;http://weblogs.asp.net/adweigert/&amp;quot;&lt;/span&gt; );&lt;/pre&gt;

    &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;Tag( &lt;span class="str"&gt;&amp;quot;div&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;LINQ Expressions Rock&amp;quot;&lt;/span&gt;, style =&amp;gt; &lt;span class="str"&gt;&amp;quot;font-size: 250%; font-weight: bold;&amp;quot;&lt;/span&gt;, id =&amp;gt; &lt;span class="str"&gt;&amp;quot;title&amp;quot;&lt;/span&gt; );&lt;/pre&gt;
  &lt;/div&gt;
&lt;/blockquote&gt;

&lt;p mce_keep="true"&gt;This is the actual method, I love how simple the LINQ expression makes building the attributes.&lt;/p&gt;

&lt;blockquote&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
  &lt;div class="csharpcode"&gt;
    &lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Tag( &lt;span class="kwrd"&gt;string&lt;/span&gt; tagName, &lt;span class="kwrd"&gt;string&lt;/span&gt; innerHtml, &lt;span class="kwrd"&gt;params&lt;/span&gt; Expression&amp;lt;Func&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;, &lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;&amp;gt;[] attributes )&lt;/pre&gt;

    &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;

    &lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    XElement tag = &lt;span class="kwrd"&gt;new&lt;/span&gt; XElement( XName.Get( tagName, &lt;span class="kwrd"&gt;string&lt;/span&gt;.Empty ) );&lt;/pre&gt;

    &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;    &lt;/pre&gt;

    &lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; ( attributes != &lt;span class="kwrd"&gt;null&lt;/span&gt; )&lt;/pre&gt;

    &lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;    {&lt;/pre&gt;

    &lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;        &lt;span class="kwrd"&gt;foreach&lt;/span&gt; ( var attribute &lt;span class="kwrd"&gt;in&lt;/span&gt; attributes )&lt;/pre&gt;

    &lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;        {&lt;/pre&gt;

    &lt;pre class="alt"&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt;            &lt;span class="kwrd"&gt;string&lt;/span&gt; attributeName = attribute.Parameters[ 0 ].Name;&lt;/pre&gt;

    &lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt;            &lt;span class="kwrd"&gt;string&lt;/span&gt; attributeValue = attribute.Compile()(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Empty);&lt;/pre&gt;

    &lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  11:  &lt;/span&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre&gt;&lt;span class="lnum"&gt;  12:  &lt;/span&gt;            tag.SetAttributeValue( XName.Get( attributeName, &lt;span class="kwrd"&gt;string&lt;/span&gt;.Empty ), attributeValue );&lt;/pre&gt;

    &lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  13:  &lt;/span&gt;        }&lt;/pre&gt;

    &lt;pre&gt;&lt;span class="lnum"&gt;  14:  &lt;/span&gt;    }&lt;/pre&gt;

    &lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  15:  &lt;/span&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre&gt;&lt;span class="lnum"&gt;  16:  &lt;/span&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; ( !&lt;span class="kwrd"&gt;string&lt;/span&gt;.IsNullOrEmpty( innerHtml ) )&lt;/pre&gt;

    &lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  17:  &lt;/span&gt;    {&lt;/pre&gt;

    &lt;pre&gt;&lt;span class="lnum"&gt;  18:  &lt;/span&gt;        tag.Add( XElement.Parse( &lt;span class="str"&gt;&amp;quot;&amp;lt;xml&amp;gt;&amp;quot;&lt;/span&gt; + innerHtml + &lt;span class="str"&gt;&amp;quot;&amp;lt;/xml&amp;gt;&amp;quot;&lt;/span&gt; ).Nodes() );&lt;/pre&gt;

    &lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  19:  &lt;/span&gt;    }&lt;/pre&gt;

    &lt;pre&gt;&lt;span class="lnum"&gt;  20:  &lt;/span&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre class="alt"&gt;&lt;span class="lnum"&gt;  21:  &lt;/span&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; tag.ToString();&lt;/pre&gt;

    &lt;pre&gt;&lt;span class="lnum"&gt;  22:  &lt;/span&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/blockquote&gt;

&lt;p&gt;Update: Used XElement instead, and better innerHtml handling. Thanks to everyone that helped improve this method.&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=6813335" width="1" height="1"&gt;</content><author><name>adweigert</name><uri>http://weblogs.asp.net/members/adweigert.aspx</uri></author></entry><entry><title>PowerShell: Install-Gac (GACUTIL for PowerShell)</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/adweigert/archive/2008/10/31/powershell-install-gac-gacutil-for-powershell.aspx" /><id>http://weblogs.asp.net/adweigert/archive/2008/10/31/powershell-install-gac-gacutil-for-powershell.aspx</id><published>2008-10-31T19:16:00Z</published><updated>2008-10-31T19:16:00Z</updated><content type="html">&lt;P mce_keep="true"&gt;So, I don't know about anyone else, but it is a pain to use GACUTIL on systems without the .NET SDK. So, I found out there is a .NET API for GACUTIL, so now I just wrapped it in PowerShell to make it easier to use. :)&lt;/P&gt;
&lt;BLOCKQUOTE&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;DIV class=csharpcode&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;   1:  &lt;/SPAN&gt;BEGIN {&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;   2:  &lt;/SPAN&gt;    $ErrorActionPreference = &lt;SPAN class=str&gt;"Stop"&lt;/SPAN&gt;&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;   3:  &lt;/SPAN&gt;    &lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;   4:  &lt;/SPAN&gt;    &lt;SPAN class=kwrd&gt;if&lt;/SPAN&gt; ( $null &lt;SPAN class=preproc&gt;-eq&lt;/SPAN&gt; ([AppDomain]::CurrentDomain.GetAssemblies() |? { $_.FullName &lt;SPAN class=preproc&gt;-eq&lt;/SPAN&gt; &lt;SPAN class=str&gt;"System.EnterpriseServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"&lt;/SPAN&gt; }) ) {&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;   5:  &lt;/SPAN&gt;        [System.Reflection.Assembly]::Load(&lt;SPAN class=str&gt;"System.EnterpriseServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"&lt;/SPAN&gt;) | Out-Null&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;   6:  &lt;/SPAN&gt;    }&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;   7:  &lt;/SPAN&gt;    &lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;   8:  &lt;/SPAN&gt;    $publish = New-Object System.EnterpriseServices.Internal.Publish&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;   9:  &lt;/SPAN&gt;}&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  10:  &lt;/SPAN&gt;PROCESS {&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  11:  &lt;/SPAN&gt;    $assembly = $null&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  12:  &lt;/SPAN&gt;    &lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  13:  &lt;/SPAN&gt;    &lt;SPAN class=kwrd&gt;if&lt;/SPAN&gt; ( $_ &lt;SPAN class=preproc&gt;-is&lt;/SPAN&gt; [string] ) {&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  14:  &lt;/SPAN&gt;        $assembly = $_&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  15:  &lt;/SPAN&gt;    } &lt;SPAN class=kwrd&gt;elseif&lt;/SPAN&gt; ( $_ &lt;SPAN class=preproc&gt;-is&lt;/SPAN&gt; [System.IO.FileInfo] ) {&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  16:  &lt;/SPAN&gt;        $assembly = $_.FullName&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  17:  &lt;/SPAN&gt;    } &lt;SPAN class=kwrd&gt;else&lt;/SPAN&gt; {&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  18:  &lt;/SPAN&gt;        &lt;SPAN class=kwrd&gt;throw&lt;/SPAN&gt; (&lt;SPAN class=str&gt;"The object type '{0}' is not supported."&lt;/SPAN&gt; -f $_.GetType().FullName)&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  19:  &lt;/SPAN&gt;    }&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  20:  &lt;/SPAN&gt;    &lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  21:  &lt;/SPAN&gt;    &lt;SPAN class=kwrd&gt;if&lt;/SPAN&gt; ( -not (Test-Path $assembly -type Leaf) ) {&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  22:  &lt;/SPAN&gt;        &lt;SPAN class=kwrd&gt;throw&lt;/SPAN&gt; &lt;SPAN class=str&gt;"The assembly '$assembly' does not exist."&lt;/SPAN&gt;&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  23:  &lt;/SPAN&gt;    }&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  24:  &lt;/SPAN&gt;    &lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  25:  &lt;/SPAN&gt;    &lt;SPAN class=kwrd&gt;if&lt;/SPAN&gt; ( [System.Reflection.Assembly]::LoadFile( $assembly ).GetName().GetPublicKey().Length &lt;SPAN class=preproc&gt;-eq&lt;/SPAN&gt; 0 ) {&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  26:  &lt;/SPAN&gt;        &lt;SPAN class=kwrd&gt;throw&lt;/SPAN&gt; &lt;SPAN class=str&gt;"The assembly '$assembly' must be strongly signed."&lt;/SPAN&gt;&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  27:  &lt;/SPAN&gt;    }&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  28:  &lt;/SPAN&gt;    &lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  29:  &lt;/SPAN&gt;    Write-Output &lt;SPAN class=str&gt;"Installing: $assembly"&lt;/SPAN&gt;&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  30:  &lt;/SPAN&gt;    &lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  31:  &lt;/SPAN&gt;    $publish.GacInstall( $assembly )&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  32:  &lt;/SPAN&gt;}&lt;/PRE&gt;&lt;/DIV&gt;&lt;/BLOCKQUOTE&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=6714380" width="1" height="1"&gt;</content><author><name>adweigert</name><uri>http://weblogs.asp.net/members/adweigert.aspx</uri></author><category term="powershell" scheme="http://weblogs.asp.net/adweigert/archive/tags/powershell/default.aspx" /><category term=".net" scheme="http://weblogs.asp.net/adweigert/archive/tags/.net/default.aspx" /></entry><entry><title>CodePlex: The Weigert Repository</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/adweigert/archive/2008/10/02/codeplex-the-weigert-repository.aspx" /><id>http://weblogs.asp.net/adweigert/archive/2008/10/02/codeplex-the-weigert-repository.aspx</id><published>2008-10-02T20:44:00Z</published><updated>2008-10-02T20:44:00Z</updated><content type="html">&lt;P mce_keep="true"&gt;I've been looking for a place to keep / manage all the snippets I develop or find and decided to use CodePlex for this. Feel free to use whatever you find useful.&lt;/P&gt;
&lt;P mce_keep="true"&gt;&lt;A href="http://www.codeplex.com/Weigert"&gt;http://www.codeplex.com/Weigert&lt;/A&gt;&lt;/P&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=6654334" width="1" height="1"&gt;</content><author><name>adweigert</name><uri>http://weblogs.asp.net/members/adweigert.aspx</uri></author></entry><entry><title>PowerShell: Oh Happy Days Are Here (Dynamically Compiling C# Code for Strongly Typed Objects within PowerShell)</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/adweigert/archive/2008/09/29/powershell-oh-happy-days-are-here-compiling-c-code-for-strongly-typed-objects-within-powershell.aspx" /><id>http://weblogs.asp.net/adweigert/archive/2008/09/29/powershell-oh-happy-days-are-here-compiling-c-code-for-strongly-typed-objects-within-powershell.aspx</id><published>2008-09-30T00:15:00Z</published><updated>2008-09-30T00:15:00Z</updated><content type="html">&lt;P mce_keep="true"&gt;Ever wanted to build native .NET objects to use while in a PowerShell script? Well I certainly have, and finally took the time to figure out how easy it is to actually do! Enjoy!&lt;/P&gt;
&lt;P mce_keep="true"&gt;
&lt;BLOCKQUOTE&gt;&lt;PRE&gt;function Compile-Code {
    param (
        [string[]] $code       = $(throw "The parameter -code is required.")
      , [string[]] $references = @()
      , [switch]   $asString   = $false
      , [switch]   $showOutput = $false
      , [switch]   $csharp     = $true
      , [switch]   $vb         = $false
    )
    
    $options    = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]";
    $options.Add( "CompilerVersion", "v3.5")
    
    if ( $vb ) {
        $provider = New-Object Microsoft.VisualBasic.VBCodeProvider $options
    } else {
        $provider = New-Object Microsoft.CSharp.CSharpCodeProvider $options
    }
    
    $parameters = New-Object System.CodeDom.Compiler.CompilerParameters
    
    @( "mscorlib.dll", "System.dll", "System.Core.dll", "System.Xml.dll", ([System.Reflection.Assembly]::GetAssembly( [PSObject] ).Location) ) + $references | Sort -unique |% { $parameters.ReferencedAssemblies.Add( $_ ) } | Out-Null
    
    $parameters.GenerateExecutable = $false
    $parameters.GenerateInMemory   = !$asString
    $parameters.CompilerOptions    = "/optimize"
    
    if ( $asString ) {
        $parameters.OutputAssembly = [System.IO.Path]::GetTempFileName()
    }
    
    $results = $provider.CompileAssemblyFromSource( $parameters, $code )
    
    if ( $results.Errors.Count -gt 0 ) {
        if ( $output ) {
            $results.Output |% { Write-Output $_ }
        } else {
            $results.Errors |% { Write-Error $_.ToString() }
        }
    } else {
        if ( $asString ) {
            $content = [System.IO.File]::ReadAllBytes( $parameters.OutputAssembly )
            $content = [Convert]::ToBase64String( $content )
            
            [System.IO.File]::Delete( $parameters.OutputAssembly );
            
            return $content
        } else {
            return $results.CompiledAssembly
        }        
    }
}&lt;/PRE&gt;&lt;/BLOCKQUOTE&gt;
&lt;P mce_keep="true"&gt;Example usage:&lt;/P&gt;
&lt;P mce_keep="true"&gt;
&lt;BLOCKQUOTE&gt;&lt;PRE&gt;Compile-Code -csharp -code @"
    using System;
    
    public class Foo {
        public Foo ( string message ) {
            Message = message;
        }
    
        public string Message { get; private set; }
        
        public void Bar() {
            Console.WriteLine( "Foo.Bar: {0}", Message );
        }
    }
"@

$foo = New-Object Foo "hello world"
$foo.Bar()&lt;/PRE&gt;&lt;/BLOCKQUOTE&gt;
&lt;P mce_keep="true"&gt;Update: Added ability to compile C# or VB.NEt code and also to return the bytes for the compiled assembly for loading at a later time.&lt;/P&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=6647740" width="1" height="1"&gt;</content><author><name>adweigert</name><uri>http://weblogs.asp.net/members/adweigert.aspx</uri></author><category term="powershell" scheme="http://weblogs.asp.net/adweigert/archive/tags/powershell/default.aspx" /><category term="c#" scheme="http://weblogs.asp.net/adweigert/archive/tags/c_2300_/default.aspx" /><category term=".net" scheme="http://weblogs.asp.net/adweigert/archive/tags/.net/default.aspx" /><category term="CodeDom" scheme="http://weblogs.asp.net/adweigert/archive/tags/CodeDom/default.aspx" /><category term="CodeDomProvider" scheme="http://weblogs.asp.net/adweigert/archive/tags/CodeDomProvider/default.aspx" /></entry><entry><title>PowerShell: Keeping Secrets for Batch Scripts</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/adweigert/archive/2008/08/27/powershell-keeping-secrets-for-batch-scripts.aspx" /><link rel="enclosure" type="application/x-zip-compressed" length="929" href="http://weblogs.asp.net/adweigert/attachment/6571947.ashx" /><id>http://weblogs.asp.net/adweigert/archive/2008/08/27/powershell-keeping-secrets-for-batch-scripts.aspx</id><published>2008-08-27T16:01:00Z</published><updated>2008-08-27T16:01:00Z</updated><content type="html">&lt;P mce_keep="true"&gt;As a system administrator, I write a lot of utility scripts, and I love using PowerShell. However, I cannot always use the local scheduler with a service account to run a script, sometimes I have to provide a username and password to an application or service. I hate storing them in plaintext, and while I don't fully like storing the encrypted text, key, and IV in the script, it is one step better than the plaintext solution. While the ultimate solution would be to have it stored as part of the user profile for the job, this is an issue when I don't have direct access to the production system to be able to run as the service account and I just need an encrypted file / text to later decrypt and use. &lt;/P&gt;
&lt;P mce_keep="true"&gt;So, I started working with ConvertTo/From-SecureString and hit a little problem. I discovered, via Reflector, that the ConvertTo-SecureString and ConvertFrom-SecureString use an IV that is specific to that instance of the PowerShell runtime. Thus, using it at a later time is no good for me. So, long story short, I cranked up Reflector, took a look at the commands, and created a script version that does exactly what I need. &lt;/P&gt;
&lt;P mce_keep="true"&gt;You will find the script attached.&lt;/P&gt;
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=6571947" width="1" height="1"&gt;</content><author><name>adweigert</name><uri>http://weblogs.asp.net/members/adweigert.aspx</uri></author><category term="powershell" scheme="http://weblogs.asp.net/adweigert/archive/tags/powershell/default.aspx" /><category term=".net" scheme="http://weblogs.asp.net/adweigert/archive/tags/.net/default.aspx" /><category term="cryptography" scheme="http://weblogs.asp.net/adweigert/archive/tags/cryptography/default.aspx" /></entry><entry><title>PowerShell: Adding the Using Statement</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/adweigert/archive/2008/08/27/powershell-adding-the-using-statement.aspx" /><id>http://weblogs.asp.net/adweigert/archive/2008/08/27/powershell-adding-the-using-statement.aspx</id><published>2008-08-27T15:56:00Z</published><updated>2008-08-27T15:56:00Z</updated><content type="html">&lt;P mce_keep="true"&gt;So, I happened to come across a need for the using statement from C#. I basically didn't want to use Try...Finally when I am so used to the short-hand using statement. Thank goodness I already have a &lt;A class="" title=Try...Catch...Finally href="http://weblogs.asp.net/adweigert/archive/2007/10/10/powershell-try-catch-finally-comes-to-life.aspx" mce_href="http://weblogs.asp.net/adweigert/archive/2007/10/10/powershell-try-catch-finally-comes-to-life.aspx"&gt;Try..Catch..Finally&lt;/A&gt; statement/function for PowerShell, I can just use that existing framework and make a using statement/function pretty easily.&lt;/P&gt;
&lt;BLOCKQUOTE style="FONT-FAMILY: courier,monospace"&gt;&lt;PRE&gt;function Using {
    param (
        [System.IDisposable] $inputObject = $(throw "The parameter -inputObject is required."),
        [ScriptBlock] $scriptBlock = $(throw "The parameter -scriptBlock is required.")
    )
    
    Try {
        &amp;amp;$scriptBlock
    } -Finally {
        if ($inputObject -ne $null) {
            if ($inputObject.psbase -eq $null) {
                $inputObject.Dispose()
            } else {
                $inputObject.psbase.Dispose()
            }
        }
    }
}

# Short example ... 
Using ($user = $sr.GetDirectoryEntry()) { 
  $user.displayName = $displayName 
  $user.SetInfo() 
} 
&lt;/PRE&gt;&lt;/BLOCKQUOTE&gt;
&lt;P mce_keep="true"&gt;Update: Take note on variable scope, variables in the using statement will not be available outside of it, this can make it tricky, but it should be easy enough to work with.&lt;/P&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=6571855" width="1" height="1"&gt;</content><author><name>adweigert</name><uri>http://weblogs.asp.net/members/adweigert.aspx</uri></author><category term="powershell" scheme="http://weblogs.asp.net/adweigert/archive/tags/powershell/default.aspx" /><category term=".net" scheme="http://weblogs.asp.net/adweigert/archive/tags/.net/default.aspx" /></entry><entry><title>PowerShell: Threading Enhancements FTW!</title><link rel="alternate" type="text/html" href="http://weblogs.asp.net/adweigert/archive/2008/04/30/powershell-threading-enhancements-ftw.aspx" /><link rel="enclosure" type="application/x-zip-compressed" length="1105" href="http://weblogs.asp.net/adweigert/attachment/6144660.ashx" /><id>http://weblogs.asp.net/adweigert/archive/2008/04/30/powershell-threading-enhancements-ftw.aspx</id><published>2008-04-30T13:11:00Z</published><updated>2008-04-30T13:11:00Z</updated><content type="html">&lt;P mce_keep="true"&gt;To build on the threading library I mentioned &lt;A class="" title="PowerShell: Threading for PowerShell v1.0" href="http://weblogs.asp.net/adweigert/archive/2008/04/29/powershell-threading-for-powershell-v1-0.aspx" target=_blank mce_href="http://weblogs.asp.net/adweigert/archive/2008/04/29/powershell-threading-for-powershell-v1-0.aspx"&gt;here&lt;/A&gt;, I've added some functionality to make it easier to communicate with the seperate thread. Still, keep in mind that PowerShell will only allow one pipeline to be executing in a runspace at any given time. So, these new functions can only be used while the thread is inactive. But, they provide power into setting up the thread to be run and communicating with the original runspace.&lt;/P&gt;
&lt;P mce_keep="true"&gt;The new functions are as follows:&lt;/P&gt;
&lt;P mce_keep="true"&gt;Get-ThreadVariable - Accesses available variables from within the thread.&lt;BR&gt;Set-ThreadVariable - Sets a variable for use within the thread.&lt;BR&gt;Invoke-ThreadExpression - Allows synchronous execution of a script block within the thread.&lt;/P&gt;
&lt;P mce_keep="true"&gt;I also updated the Join-Thread function to include an optional -timeout parameter so that you could return control back if the thread didn't complete in the desired time. I also updated the Running property to IsRunning and changed it so that it will only return true while the asynchronous invoke command is executing.&lt;/P&gt;
&lt;P mce_keep="true"&gt;With this new example you can do even more now, as shown here.&lt;/P&gt;&lt;PRE mce_keep="true"&gt;$thread = New-Thread&lt;BR&gt;Invoke-ThreadExpression $thread { function foo($bar) { echo "$bar!" } }&lt;BR&gt;Set-ThreadVariable $thread "name" "PowerShell Rocks"&lt;BR&gt;Start-Thread -thread $thread { $value = foo $name } | Out-Null&lt;BR&gt;Join-Thread $thread&lt;BR&gt;Get-ThreadVariable $thread "value"&lt;/PRE&gt;
&lt;P mce_keep="true"&gt;This should return "PowerShell Rocks!" when Get-ThreadVariable is called. I've already used this script to multi-thread our Exchange backup from a single script. It is working quite nicely (nice as in have cut our 8 hour backup down to 4 hours)&amp;nbsp;and I can already imagine several other wonderful places it will be used.&lt;/P&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=6144660" width="1" height="1"&gt;</content><author><name>adweigert</name><uri>http://weblogs.asp.net/members/adweigert.aspx</uri></author><category term="powershell" scheme="http://weblogs.asp.net/adweigert/archive/tags/powershell/default.aspx" /><category term=".net" scheme="http://weblogs.asp.net/adweigert/archive/tags/.net/default.aspx" /></entry></feed>