Subscribe: Wes' Puzzling Blog
Added By: Feedage Forager Feedage Grade B rated
Language: English
application  button  code  find  host  mef  net  new object  new  object  outlook  solution  system  write host  write 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Wes' Puzzling Blog

Wes' Puzzling Blog

... trying to solve the puzzles of .NET


MEF Preview 9 released

Wed, 24 Feb 2010 17:27:00 GMT

MEF preview 9 has been released on codeplex

The only changes are some bug fixes for the .Net version and a couple additions to the SL version.

  • We brought back PackageCatalog but redesigned it under the name DeploymentCatalog and put it in System.ComponentModel.Composition.Initilization.dll
  • We renamed PartCreator to ExportFactory and put it in System.ComponentModel.Composition.Initilization.dll
  • Renamed type PartInitializer to CompositionInitializer
  • Renamed method CompositionHost.InitializeContainer to CompositionHost.Initialize

This drop contains a MEF.sln which loads in VS2008 and builds MEF against .Net 3.5 and MEFSL.sln which loads in VS2008 and builds MEF againts SL3. The API's are pretty much what we are shipping in .Net 4.0 and SL4 SDK respectively. However if you need a .Net 4 version of MEF we suggest that you install the RC version of .Net 4 and if you need an SL4 version of MEF you install the Silverlight 4 beta SDK.

As aways if you have issues or questions related to MEF feel free to post them in our dicsussion forums at

For some more detailed explanations of the changes in this preview have a look at Mike Taulty's post

MEF preview 5 released

Wed, 08 Apr 2009 02:20:17 GMT

My team released the 5th source code preview of MEF (Managed Extensibility Framework). You can get the latest bits at MEF preview 5. A summary of the changes can be found on in the release notes but I will copy them here for convenience. If you have questions or concerns feel free to join the discussion. Namespace changes System.ComponentModel.Composition – For part authors. This namespace contains the import and export attributes as well as other APIs that part authors are likely to use. System.ComponentModel.Composition.Hosting – For hosters. This namespace contains the CompositionContainer, catalog implementations, and other APIs that hosters are likely to use. Part discovery changes CompositionOptionsAttribute and DiscoveryMode have been removed. PartNotDiscoverableAttribute replaces [CompositionOptions(DiscoveryMode = DiscoveryMode.Never)] PartCreationPolicyAttribute can be used to specify part creation policy (Replaces CompositionOptionsAttribute.CreationPolicy) By default, exports on a base class will not be included in the exports for a derived class. The PartExportsInheritedAttribute can be applied to a base class to specify that exports on that class will be included in derived classes. NOTE: If this attribute is used, and both the base and derived class have export attributes applied to them, there will be multiple exports created for the same class. Also note that whatever metadata is applied to the export on the base class can’t be added to or overridden by the derived class Collection imports ImportManyAttribute should now be used on collection imports (in the future, an ImportAttribute will not be interpreted as a collection import even if it is applied to a collection type). Array imports are now supported. Typed Imports/Exports Imports and Exports now match on type as well as contract. Exporters of string contracts such as [Export(“Foo”)] must now specify the type they expect to be imported as well. e.g. [Export(“Foo”, typeof(string))] Method exports Method exports can now be imported as custom delegates in addition to Action<…> and Func<…> delegates Directory Catalog The directory watching functionality has been removed. The Refresh() method has been added to explicitly update the catalog with new assemblies in the directory. Removal of Caching / new infrastructure The old caching infrastructure has been removed. We’ve added a general purpose API that allows the implementation of catalog caching as well as supporting builders of custom programming models. The APIs are members of the static class System.ComponentModel.Composition.ReflectionModel.ReflectionModelServices. In the future we plan to ship a sample that shows how these APIs can be used to create cached catalogs. New sample application MEF Studio – a designer hosting sample. Common compilation errors to expect when migrating previous code bases System.ComponentModel.Composition.Container does not exist -> Add reference to System.ComponentModel.Composition.Hosting namespace CompositionContainer does not contain method AddPart or Compose -> Need to start using CompositionBatch, or one of the helper extension methods ComposeParts or ComposeExportedObjects CompositionOptionsAttribute does not exist -> For CreationPolicy use PartCreationPolicyAttribute INotifyImportCompleted does not exist -> Use IPartImportsSatisfiedNotification interface and change method from ImportCompleted to OnImportsSatisfied [...]

Should MEF support non-shared components?

Mon, 10 Nov 2008 19:16:00 GMT

Hamilton has posted about the question of whether or not MEF should support non-shared as well as shared components (non-shared==factory and shared==singleton in our current public bits). In an ideal world we would love to support both but currently every solution we've come up with to support non-shared components has issues. We could pick a solution that we feel properly balances the advantages and disadvantages but that would require us to foresee exactly how the world is going to use MEF. While we believe we could pick a reasonable balance there is fear that we would pick the wrong balance for the majority of our future users. Therefore one approach to combat this is to not support non-shared components, at least in V1, and see what usage patterns reveal themselves in the wild and target that balance in V2.

Do you feel that it would be a mistake for the MEF team to only support shared/singleton components in V1? Keep in mind that there are patterns, as Hamilton pointed out, to still support non-shared/factory if you needed that support in V1.

MEF CTP2 released with source code.

Wed, 10 Sep 2008 05:28:21 GMT

My team released MEF CTP2 on codeplex at, this time with source code. We also created a number of documents (i.e. wiki pages) and samples that demonstrate how to use MEF.

What problems does MEF solve?

MEF presents a simple solution for the runtime extensibility problem. Until now, any application that wanted to support a plugin model needed to create its own infrastructure from scratch. Those plugins would often be application-specific and could not be reused across multiple implementations.
  • MEF provides a standard way for the host application to expose itself and consume external extensions. Extensions, by their nature, can be reused amongst different applications. However, an extension could still be implemented in a way that is application-specific. Extensions themselves can depend on one another and MEF will make sure they are wired together in the correct order (another thing you won't have to worry about).
  • MEF offers a set of discovery approaches for your application to locate and load available extensions.
  • MEF allows tagging extensions with additional metadata which facilitates rich querying and filtering

[MEF Overview]

By all means please provide us with what you like and\or dislike about MEF at Discussions.

First Managed Extensibility Framework (MEF) bits released

Thu, 05 Jun 2008 05:07:39 GMT

Today was a big day for my team because we released the bits for the first CTP of the Managed Extensibility Framework (MEF).

MEF is a framework that allows developers to declare what they need (i.e. Imports) and what they provide (i.e. Exports) and then automatically wire up everything at run-time. While that may be a slight over simplification it is the basic idea and can lead to a very loosely coupled system which can easily be extended and evolve overtime.

The primary goal of this CTP is to get the bits into people’s hands early to gather feedback from the community and feed it back into the product. We have already gotten some good feedback in response to Krzysztof’s blog post about MEF, and some of that feedback has already made its way into the CTP. Rest assured that there are still community asks that we are still actively working hard on.

Keep in mind these bits are very early and you should not get hung up on the names and exact shape of the API’s because they are likely to change. What we would really like is feedback on the basic concepts and any scenarios you feel MEF would be useful for but needs some fine tuning.

To get your hands dirty download the bits and have a look at the sample applications and docs. If you have questions or feedback by all means don’t hesitate to stop by our forum.

Expect so see some more posts from me and some of my teammates (Mitch, David, Krzysztof) on MEF in the coming months.


Opening files from the VS "Quick find combo"

Thu, 27 Mar 2008 04:25:30 GMT

Ctrl+/ is quickly becoming one of my favorite and most used hotkey in Visual Studio. Pressing it will jump you to the "Quick find Combo" with a ">" already type in for you (which means interpret the text as a VS command).

If you are like me you hate hunting through the Solution Explorer looking for files, especially on large solutions, you might be interested in the Ctrl+/ | ">of " command. 

As Robert Prouse explains:

Here is a cool Visual Studio feature that almost nobody knows about. If you want to open up a file in your solution, but can’t be bothered to dig down through your projects and folders to find it, try this,

  1. Click in the Find box in the toolbar,
  2. Type >of followed by a space, then begin the name of the file you are looking for.
  3. An auto-complete drop down will appear as you type filtering all the files in all your projects in your solution. Continue typing until the list is short enough to fine the one you want. Select it and hit enter.
  4. The file will open in the editor.


[Quickly Find/Open a File in Visual Studio]

The best part of this auto complete drop down is that it actually gives you a flat list view of all the files in the solution which is just plain cool :)

As if that wasn't enough Aaron Lerch posted The Talented Mr. Edit.GoToFindCombo which lists some other cool features of the "Quick find combo".

Job openings on the .NET Framework Core Team

Sun, 16 Mar 2008 21:19:38 GMT

We have been incubating ideas about building a simple extensibility framework for some time. Now, as plans for the next version of the .NET Framework crystallize a bit more, we decided to productize the project. As a result, we have opened a job position (and most probably will be opening more) on the .NET Framework team. If you are interested, please see details here and send me an email at “kcwalina at”

So, what is this extensibility framework? Initially, it will be a low level core .NET Framework feature to make it easy for applications to expose extensibility points and consume extensions. Think about what for example FxCop has to do define rule contracts and load rule implemented by the community. These are the basics, and we can talk about the broader and longer term vision when you come to Redmond for an interview :-)

This is a technical Program Manager position in Redmond, WA, and it’s basically exactly the job I did when I joined Microsoft. Besides working on the Framework features, all Program Managers on the core team have opportunities to work on API design and architecture projects.

[Job Openings on the .NET Framework Core Team]

I'm a developer on Kyzysztof's team and we are looking for a few good people for PM and Dev positions so by all means if you are interested in extensibility and API design please apply.

2008 Scripting Games - My solutions

Mon, 10 Mar 2008 06:23:56 GMT

Here are my solutions to the 2008 Scripting Games scripting competition. This is a rather large post but I decided one post would be better than posting them all individually, this way they will all be in one place when I want to find them later. I had fun and I learned a lot of new cool things about Powershell while working through the problems. If you are trying to learn Powershell I would definitely recommend working through them to force yourself to learn the details. Disclaimer: These script samples are by no means perfect but they are the unedited solutions that I submitted so they do solve the problems. They are provided as-is and you should use them at your own risk. Powershell beginner division Event 1: Pairing Off Official SolutionMy Solution:# first char in card is A, 1, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K # second char in card is H - Hearts, S - Spades, C - Clubs, D - Diamonds $cards = @("7S", "5H", "7D", "7C", "KC"); $numPairs = 0; for ($i = 0; $i -lt $cards.Length; $i++) { for ($j = $i + 1; $j -lt $cards.Length; $j++) { if ($cards[$i][0] -eq $cards[$j][0]) { $numPairs++; } } } Write-Host $numPairs; Event 2: True Type Official SolutionMy Solution:$fonts = Get-Item "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Fonts" $truetypes = $fonts.Property | where { $_ -match "\(TrueType\)" } Write-Host "TrueType Fonts:" $truetypes Write-Host Write-Host "TrueType: $($trueTypes.Count)" Write-Host "Total: $($fonts.ValueCount)" Event 3: Let’s Get Together Official SolutionMy Solution:$firstLines = dir "C:\Scripts\*.txt" | % { Get-Content $_ -totalCount 1 } $firstlines | Out-File -encoding ASCII "c:\scripts\newfile.txt" Event 4: Count Yourself InOfficial SolutionMy Solution:$c=0 Get-Content $MyInvocation.MyCommand.Definition | % { $c += $_.Length } $c Event 5: What’s the DifferenceOfficial SolutionMy Solution:param([DateTime] $d) $t = [DateTime]::Today $ts = $d - $t $ms = ($d.Month - $t.Month) + 12 * ($d.Year - $t.Year); Write-Host ("Days: " + $ts.Days) Write-Host ("Months: " + $ms) if ($d.Day -lt $t.Day) { $ms--; } $ts = $d - $t.AddMonths($ms) Write-Host ("Months/Days: " + $ms + " / " + $ts.Days) Event 6: Coffee BreakOfficial SolutionMy Solution:$cfile = (Get-Content "C:\Scripts\coffee.txt") $orders = @{} foreach($o in $cfile) { $d, $c = $o.Split(" ") $orders[$d] += [int]$c; } $orders.Remove("Office"); $orders.GetEnumerator() | % { Write-Host ($_.Name + " " + $_.Value) } Event 7: Squashing BugsOfficial SolutionMy Solution:foreach ($i in Get-ChildItem C:\Scripts -recurse) { if (($i.CreationTime -lt ($(Get-Date).AddDays(-10))) -and ($i.Extension -eq ".txt")) { Copy-Item $i.FullName C:\old $i.Name $x = $x + 1 } } "" "Total Files: " + $x Event 8: Random GuessOfficial SolutionMy Solution:$r = New-Object System.Random $low = 1 $high = 50 [int]$num = $r.Next($low, $high) $guess = $guesses = 0 while ($num -ne $guess) { Write-Host -NoNewline "Guess a number between $low and $high : " [int]$guess = Read-Host if ($guess -lt $num) { Write-Host "Too Low!" $low = $guess } else { if($guess -gt $num) { Write-Host "Too High!" $high = $guess } } $guesses++ } Write-Host "Random number was $num" Write-Host "Total guesses: $guesses" Event 9: Pool PartyOfficial SolutionMy Solution:$adOpenStatic = 3 $adLockOptimistic = 3 $objConnection = New-Object -comobject ADODB.Connection $objRecordset = New-Object -comobject ADODB.Recordset $objConnection.Open("Provider=Microsoft.Jet.OLEDB.4.0; Data Source= c:\scripts\pool.mdb") $objRecordset.Open("Select * from SwimmingPool", $objConnection,$adOpenStatic,$adLockOptimistic) do { Write-Host (" Name: " + $objRecordset.Fields.Item("Customer").Value) [int]$length = $objRecordset.Fields.Item("[...]

2008 Scripting Games

Sun, 17 Feb 2008 05:27:21 GMT

It’s the third annual Scripting Games, the biggest scripting competition of the year! As a matter of fact, it’s most likely the biggest scripting competition ever. (The fact that it may be the only scripting competition is beside the point.)

The games have already begun on Feb 15 but you have until 8 AM Feb 20 to submit the solutions for the first two events.

If you want to force yourself to learn Powershell (or Perl or VBScript) then I would suggest having a look. Even though I'm not eligible for prizes because I'm a Microsoft employee, I plan on participating to help fill in the gaps of my Powershell skills. I may also try to post my solutions (after the deadline of course :)).

All Outlook object model calls run on the main thread

Tue, 05 Feb 2008 06:12:52 GMT

While writing an Outlook addin, lots of people feel that they should try to help with Outlook performance by running their addin code on a background thread. While this can help in some scenarios it can actually make things worse in others, particularly if the addin is interacting primarily with the Outlook Object Model (OOM). The OOM is run in a single threaded apartment COM server, therefore every COM call is executed on the main thread of outlook.exe.

If an addin is interacting with the OOM from another apartment (i.e. on a background thread or another process) all the calls have to be marshaled to and from the server apartment (i.e. the main thread) which causes some extra overhead. This overhead is why working on a background thread could actually make performance worse and it does not exist if the addin is executing in the same apartment.

Like most things, it is a balancing act and one needs to find the proper balance for their particular situation. Just remember the key to performance is "Measure, Measure, Measure..."

Issues with the XmlSerializer in medium trust environments

Mon, 14 Jan 2008 06:35:08 GMT

In my last post I briefly mentioned that CodeHTMLer had issues running in a medium trust environment. The simple web application front end I created kept failing before it ever got started. It keep hitting a SecurityException nested in an InvalidOperationException which looks something like: [Exception: System.InvalidOperationException: There was an error reflecting type 'CodeHtmler.Languages'. ---> System.Security.SecurityException: Request failed.   at System.Reflection.CustomAttribute._CreateCaObject(...)   at System.Reflection.CustomAttribute.CreateCaObject(...)   at System.Reflection.CustomAttribute.GetCustomAttributes(...)   at System.Reflection.CustomAttribute.GetCustomAttributes(...)   at System.Reflection.RuntimePropertyInfo.GetCustomAttributes(...)   at System.Xml.Serialization.XmlAttributes..ctor(...)   at System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(...)   at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(...)The action that failed was:InheritanceDemandThe type of the first permission that failed was:System.Security.PermissionSetThe Zone of the assembly that failed was:MyComputer CodeHTMLer uses the XmlSerializer to read and write the language definitions and it appeared to be what was causing this exceptions to be thrown. I spent a good deal of time trying to figure out why this wasn't working because every thing I read online said the XmlSerializer should actually work in medium trust. After a while of debugging I finally figured out that the problem was caused by some custom attributes.[XmlAttribute] [Editor(typeof(HtmlColorEditor), typeof(System.Drawing.Design.UITypeEditor))] public string Color {...} Apparently when the XmlSerializer is walking through the custom attributes it runs into the EditorAttribute and then tries to get the type of my custom editor HtmlColorEditor which has UITypeEditor in it's inheritance chain. However UITypeEditor for some reason demands a FullTrust permission set for Inheritance, which is problematic in a medium trust environment. To verify for certain that this was the issue I removed those editor attributes and then the XML serialization worked as expected under medium trust. Those editor attributes are used by the PropertyGrid, which is my lame way of providing UI to edit the language definitions, so I didn't want to remove them permanently but I also wanted the serialization to work in a medium trust environment. To allow for both the PropertyGrid and the medium trust serialization to work I decided to use the sgen tool to generate the serialization classes statically when I knew I had FullTrust permissions, instead of dynamically at runtime like the generic XmlSerializer class does. The output of sgen was another assembly, CodeHtmler.XmlSerializers.dll which I then needed to reference and switch the code from using the more general XmlSerializer(typeof(Languages)) to the specific class  LanguagesSerializer(). This was cool because it allowed me to accomplish what I wanted but it in turn forced me to now release two separate assemblies, CodeHtmler.dll and CodeHtmler.XmlSerializers.dll. Wouldn't it be nice if I could get away with just one assembly. It turns out that sgen has this /keep option that will tell it not to delete the temp code files used to build the new assembly. This was great because now I can just take the generated source code for the LanguagesSerializer class and build it as part of my CodeHtmler.dll assembly. Here is the command line I used to do this: sgen CodeHtmler.dll /keep /force /type:CodeHtmler.Languages There is a little bit of the chicken and egg problem here because I needed the CodeHtmler.dll to generate the serialization code and I needed seri[...]

Added CodeHTMLer project at codeplex

Mon, 14 Jan 2008 05:31:00 GMT

In order to help better manage changes to CodeHTMLer I finally added the project on codeplex at

I made a couple of small code updates after I put it up on codeplex:
- Added a new language property DivInlineFont to define the font to use when not using pre tags.
- Added a language definition for F# (thanks to Harry at Blogging in F#)
- Fixed the CodeHTMLer library so it runs in a medium trust environment (needed this because I just moved web hosts and the new one runs in medium trust level, more about the details later).

Thus far codeplex seems pretty cool but I guess I will only be able to realize its full collaboration potential when I actually have more contributors than just myself.

Fun with C# functions

Sun, 11 Nov 2007 21:26:10 GMT

Dustin Campbell has an interesting series on C# functions on his Did it with .NET blog.

  1. Fibonacci Numbers, Caching and Closures
  2. What's in a Closure?
  3. Using Automatic Memoization
  4. A Higher Calling
  5. The Art of Currying
  6. Building Functions from Functions, part 1: Partial Application
  7. Building Functions from Functions, part 2: Function Composition


Some interesting stuff that ties together a number of C# 2.0 and 3.0 feature sets. Definitely worth a read. Thanks Dustin and keep them coming.

Failure creating an Outlook application object on Vista

Mon, 05 Nov 2007 05:56:34 GMT

While creating a Outlook application object from another process in C# like:

outlook = new Microsoft.Office.Interop.Outlook.Application();

or powershell

PS> $outlook = new-object -com Outlook.Application

or straight up COM via CoCreateInstance on Vista it's possible to receive the following error:

Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80080005

Error 0x80080005 (CO_E_SERVER_EXEC_FAILURE) is sort of a generic COM error message that occurs for many reasons while calling CoCreateInstance. One reason someone could receive this error is because the client process and the server process (outlook.exe in this case) are running at different integrity levels. By default it doesn't appear that COM likes talking across two different processes that are running at different integrity levels. There supposedly is a way to implement the COM server in such a way to support it but currently the Outlook COM server doesn't support it.

People who develop their applications on Vista using Visual Studio, which runs at integrity level high by default, will run into this issue often when Outlook is already running. By default Outlook runs at integrity level medium and if the client application is run from Visual Studio it will inherit the high integrity level and thus there will be an integrity level mismatch.

To fix this one needs to make the integrity levels match so either start the client application outside Visual Studio at the normal medium integrity level or run Outlook at the high integrity level (i.e. as Administrator). However it is not recommended to run Outlook at integrity level high all the time. Another way to deal with this is to ensure Outlook is not already running so COM will start the process at the correct integrity level of the client process that created the application object.

I don't know of any way to detect this exact situation programmatically but process explorer works well for manually checking the integrity levels of processes.

Why does my Outlook event seem to stop working?

Wed, 04 Jul 2007 06:53:32 GMT

Imagine we have some code in an Outlook addin that looks similar to code below. Does anyone see anything wrong with it? It simply places a button on the menu bar and shows a message box when the button is clicked. The code works for sometime but then all of a sudden the button mysteriously stops working. What gives? 

using Office = Microsoft.Office.Core;
using Outlook = Microsoft.Office.Interop.Outlook;
void SetupCommandBar(Outlook.Application application)
    Office.CommandBar menu = application.ActiveExplorer().CommandBars.ActiveMenuBar;

    Office.CommandBarButton button = menu.Controls.Add(Office.MsoControlType.msoControlButton,
        Type.Missing, Type.Missing, Type.Missing, true) as Office.CommandBarButton;

    button.Caption = "Click Me!";
    button.Click += new Office._CommandBarButtonEvents_ClickEventHandler(button_Click);
void button_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault)
    System.Windows.Forms.MessageBox.Show("Clicked Button!");

The button stops working due to the mystical powers of the .Net garbage collector. If we look closely we notice that the button object is locally scoped in the SetupCommandBar function, thus once we execute that function the button object is free to be cleaned up. However, until the button object is actually destroyed by the garbage collector the button click event will fire and the button will work. Due to the non-deterministic nature of the garbage collector we have no idea how long the button will work. In my simple testing it seemed to work for a little while but if you want to speed up the process add a call go GC.Collect in the button_Click callback.

The easiest fix for this problem is to change the scope of the button object to be a member variable of enclosing class. By doing this we ensure that the button object stays alive and works until we are ready for it to stop working.

Powershell script to find strings and highlight them in the output

Fri, 23 Mar 2007 06:11:04 GMT

After reading about Brad's find script I starting thinking about how cool it would be if I could highlight the search pattern in the output. So I wrote my own custom Find-String script to highlight the results. Find-String.ps1 # Find-String.ps1 # Wrapper around dir | select-string which will highlight the pattern in the results param ( [string] $pattern = "" , [string] $filter = "*.*" , [switch] $recurse = $false , [switch] $caseSensitive = $false) if ($pattern -eq $null -or $pattern -eq "") { Write-Error "Please provide a search pattern!" ; return } $regexPattern = $pattern if($caseSensitive -eq $false) { $regexPattern = "(?i)$regexPattern" } $regex = New-Object System.Text.RegularExpressions.Regex $regexPattern # Write the line with the pattern highlighted in red function Write-HostAndHighlightPattern([string]$inputText) { $index = 0 while($index -lt $inputText.Length) { $match = $regex.Match($inputText, $index) if($match.Success -and $match.Length -gt 0) { Write-Host $inputText.SubString($index, $match.Index - $index) -nonewline Write-Host $match.Value.ToString() -ForegroundColor Red -nonewline $index = $match.Index + $match.Length } else { Write-Host $inputText.SubString($index) -nonewline $index = $inputText.Length } } } # Do the actual find in the files Get-ChildItem -recurse:$recurse -filter:$filter | Select-String -caseSensitive:$caseSensitive -pattern:$pattern | foreach { Write-Host "$($_.FileName)($($_.LineNumber)): " -nonewline Write-HostAndHighlightPattern $_.Line Write-Host } Sample Output PS> ./Find-String new-objectFind-String.ps1(13): $regex = New-Object System.Text.RegularExpressions.Regex $regexPatternGet-ApptsUsingEWS.ps1(55): $responseXml = [xml](new-object System.IO.StreamReader $responseStream).ReadToEnd()Get-ApptsUsingOOM.ps1(6): $outlook = New-Object -ComObject Outlook.Applicationgetappts.ps1(51): $responseXml = [xml](new-object System.IO.StreamReader $responseStream).ReadToEnd()printAppts.ps1(6): $outlook = New-Object -ComObject Outlook.Application   For reference here are some other find scripts around the blogsphere: Brad Wilson, Ian Griffith and Keith Hill.[...]

Retrieving your Outlook appointments for a given date range

Wed, 21 Mar 2007 06:43:28 GMT

Before we dive into the code sample lets take a quick look at what it means for an appointment to fall into a given date range. When you compare an appointment with a given date range (or any two time intervals) there are the 6 possible outcomes displayed in the diagram above. Usually as a first attempt people write a comparison that looks like:[Start] >= RangeStart AND [End] <= RangeEnd If you examine that comparison closely you will notice that it will only retrieve appointments of type 1. This maybe fine for most applications, like getting all appointments for a given week because there usually aren't any appointments spanning over the range edges. However, if you want to be more precise and include any appointments that overlap with a given date range (i.e. type 1, 2, 3, 4) you can use the following comparison:[End] >= RangeStart AND [Start] <= RangeEnd This type of restriction will help when you have smaller date/time ranges such as a few hours or a day. In general, unless you specifically only want type 1 appointments, I would recommend using this restriction which finds any appointments that overlap with the given date/time range. Since Walter has already provided a VBA, WebDAV, and CDO code sample on how to find appointments within a specific time frame, I figured I would provide some Powershell code samples. Powershell script to retrieve appointments using the Outlook Object Model for a given date range. Keep in mind in order to get all the appointments, including any instances of recurring appointments, you need to get the items collection on the calendar folder and then Sort by the "[Start]" property and set IncludeRecurrences to true. Once you have done this the Count property on the items collection is bogus because there could potentially be an infinite number of recurring appointments. So to traverse this collection you need to use the enumerator (i.e. foreach) or use the Find/FindNext methods on the collection.# Get-ApptsUsingOOM.ps1 # Powershell script to retrieve all appointments for a given date range using the Outlook Object Model param ( [DateTime] $rangeStart = [DateTime]::Now , [DateTime] $rangeEnd = [DateTime]::Now.AddDays(7)) $outlook = New-Object -ComObject Outlook.Application # Ensure we are logged into a session $session = $outlook.Session $session.Logon() $olFolderCalendar = 9 $apptItems = $session.GetDefaultFolder($olFolderCalendar).Items $apptItems.Sort("[Start]")$apptItems.IncludeRecurrences = $true $restriction = "[End] >= '{0}' AND [Start] <= '{1}'" -f $rangeStart.ToString("g"), $rangeEnd.ToString("g") foreach($appt in $apptItems.Restrict($restriction)) { "{0:MM/dd hh:mm tt} - {1:MM/dd hh:mm tt} : {2}" -f [DateTime]$appt.Start, [DateTime]$appt.End, $appt.Subject } $outlook = $session = $null; Powershell script to retrieve appointments using Exchange Web Services for a given date range For simplicity I built the soap message manually and submitted the request, but you could easily generate the web service proxy classes using wsdl.exe like I did in another example if you don't wish to build the soap message yourself.# GetApptsUsingEWS.ps1 # Powershell script to retrieve all appointments for a given date range using Exchange Web Services param ( [DateTime] $rangeStart = [DateTime]::Now , [DateTime] $rangeEnd = [DateTime]::Now.AddDays(7) , [System.Net.NetworkCredential] $credentials = (Get-Credential).GetNetworkCredential()) # Remember to set your exchange server address $exchangeServerAddress = "http://

Reflector 5 Released

Wed, 21 Feb 2007 05:28:49 GMT

Lutz released Reflector for .NET 5.0

If you do any .NET development and you don't use Reflector for .NET then you are missing out. Scott posted a brief review of the new version. I think I'm most excited about the new analyze feature, it should come in handy.

Reflector for .NET
Reflector for .NET Add-Ins

Image File Execution Options

Fri, 09 Feb 2007 03:28:04 GMT

Every now and than while debugging I need to either determine when a dll/module is loaded or need to attach a debugger to a process at startup that is started outside a debugger. I know there are settings that exist to do this but I always seem to forget exactly what they are. So for future reference here the registry entries.


Force a break while debugging when a dll/module is loaded

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\]

Force a process to start under the Visual Studio Debugger

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\]


Useful links:

Junfeng - Image File Execution Options
Greggm - Breaking when a module loads
Greggm - Inside 'Image File Execution Options' debugging
Oldnewthing - Beware the Image File Execution Options key

Powershell version of cmd set

Thu, 08 Feb 2007 20:24:00 GMT

If you are like me and are just so used to typing set to list and set environment variables then you might find this script useful.

if (test-path alias:set) { remove-item alias:set > $null }
function set
	[string]$var = $args
	if ($var -eq "")
		get-childitem env: | sort-object name
		if ($var -match "^(\S*?)\s*=\s*(.*)$")
			set-item -force -path "env:$($matches[1])" -value $matches[2];		
			write-error "ERROR Usage: VAR=VALUE"

Just add this script to your Powershell profile and you will be all set :)

PS: If anyone is interested I updated the Powershell Language definitions for CodeHTMLer, it now highlights more of the built-in stuff such as cmdlets and variables.