Cottleston Pie

Fernando Felman’s thoughts on software development

Archive for the ‘VS2005’ Category

Microsoft Visual Studio 2003 uses the .Net 2.0

Visual Studio extensions for Windows SharePoint Services v1.1

Posted by Fernando Felman on February 12, 2008

Funny, just as I publish the how to install VSeWSS on a workstation, the good guys from Redmond announced the new version. Main changes that I’m keen to investigate: bug fixes and features support. You can download the new version from here which now also comes with a user guide. Just like the previous version, you should install this new extensions on a local SharePoint machine. That is, unless you feel like hacking it. 🙂

And while we’re on the subject of MOSS, check out Javed Sikander’s video on OBA Composition Reference Toolkit on Channel 9. I’d really like to see where this thing is going to be in, say, another 2-3 months. I think it really has the potential of bringing forward the biggest advantage of MOSS which, in opinion, is a rich platform for custom collaboration solutions. This toolkit is a huge step towards implementing the concepts I’m used to see from the patterns & practices group to match the SharePoint development world. Very cool.

Advertisements

Posted in Moss, VS2005 | Leave a Comment »

How to install the SharePoint 2007 VS 2005 Extensions on a Workstation

Posted by Fernando Felman on February 11, 2008

SharePoint 2007, or MOSS, is a server product and as such it can only be installed on the Windows Server family platform. I can understand that, it makes sense. What I can’t understand and doesn’t make any sense at all is that I’m not allowed to install the development tools on my new shiny Vista.

The recommendation for MOSS development was always to get a VM to run W2k3 with MOSS and Visual Studio. That’s all fine when you’ve to develop and do cycles of compile-deploy-debug, but what if you want to load an existing web part project with the visual studio installed on your workstation?

If you try to install the Visual Studio 2005 Extensions for Windows SharePoint Services 3.0 Tools (VSeWSS) on a workstation you’d probably fail and get the following error: “This product can only be installed if Windows SharePoint Services 3.0 has been installed first”. So the only thing we’ve to do is to hack the installer into thinking MOSS is installed. How difficult can it be, right?

Before continuing into opening the Regedit tool, be aware that mocking around with the Windows registry is not supported, not recommended and generally considered bad manners.

Now open the regedit and create the following keys and the string value:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\12.0]

"Sharepoint"="Installed"

That’s it! You have fooled the installer into running on a workstation. Easy. I also recommend adding the core SharePoint assemblies into the CAG using gacutil. Those assemblies can be found by default in any ShaerPoint machine under the folder: C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI.

If you’re feeling adventurous enough and want to get the full remote debugging experience, try out this excellent Martin Vollmer’s post.

Posted in .Net v2, Moss, VS2005 | 33 Comments »

HOW TO: Check the Type of a COM Object (System.__ComObject) with Visual C# .NET

Posted by Fernando Felman on February 5, 2008

This one is a favourite of mine since I tried to resolve it in the past with no success.

The problem at hand is that we have a COM object o returned from Excel interop and we have to figure out what underlying interface it implements. If you try to use GetType() you’ll get a __ComObject which does not provide any helpful information as to what underlying types are implemented by the object.

The following KB article sheds some light: http://support.microsoft.com/kb/320523. The suggested way in the article is to manually cast the object to any known type using the as directive and if a valid object is returned – that type is implemented by the object. This solution will work, but it’s utterly ugly and requires vast amounts of typing in order to support all the possible types. I needed to implement something similar without using manual casting, essentially I needed a method that receives a COM object (of the type __ComObject, assuming it was created by the Excel interop) and returns the underlying interface supported by that object.

First I thought to somehow ask the object to provide me with a list of implemented interfaces. Something like the System.Type.GetInterfaces method. The problem is that the type of the object does not expose any useful information and the object itself has no typed class, so that proved to be futile.

Then I thought that instead of getting the implemented types from the object, I can query all the existing types one by one. Sure, it’s not as pretty as the previous path but that’s actually how COM works by design. Every COM class implements the IUknown interface which supports the QueryInterface method used to get a pointer to where an interface is implemented in the class. The idea is that all the information about what methods are supported by the interfaces and what interfaces are implemented by a type should be acquired in advance and coded into the caller (IDL, TLB and h files comes in mind). There was no true run-time reflection in the old COM days.

.NET supports COM by means of interoperability proxies. I won’t get into too many details, but basically you get .NET objects typed as __ComObject mapping COM instances and .NET interfaces with some unique attributes mapping COM interfaces. More to the point, you get the System.Runtime.InteropServices.Marshal class to handle all bunch of COM and interop operations such as calling the QueryInterface method on a .NET object mapped to a COM instance.

So now we know that we can query interop interfaces against the object. Sweet. But in order to do that we need the Interface ID, or iid, which is the GUID identifying an interface in COM. Oh, and we need that for each end every COM interface implemented by the Excel interop. Not sweet. OK, but we’re in .NET world now (thanks to the System.Runtime.InteropServices namespace) which has great support for runtime reflection. How difficult would it be to enumerate all the COM interfaces implemented by the Excel interop? Not too difficult really, we can use the System.Reflection.Assembly class to get a handler to the Excel interop assembly and from there it’s relatively easy going.

So let’s conclude what we need:

  1. Get all the COM interface types exposed by the Excel interop assembly.
  2. Fetch the Interface ID of each type and use it on QueryInterface to test whether an interface is implemented by the object (if a valid pointer is returned, the interface is implemented by the object).

This doesn’t sound too complicated. Obviously there are some syntax and plumbing issues to address, but the concept is rather simple. Good, let’s implement it:

GetExcelTypeForComObject method

Namespaces:
using Excel = Microsoft.Office.Interop.Excel;
using interop = System.Runtime.InteropServices;

Note that in many cases a wrapped COM object implements many interfaces, so breaking after the first implemented interface is found might not do it for you…

Posted in .Net v2, Samples, vs2003, VS2005 | 20 Comments »

Redirecting the appSettings content to a user-specific file

Posted by Fernando Felman on April 26, 2007

It happens a lot in the development process: the settings in the configuration files differ in the development, staging and production environments and each time you switch environment you’ve to update the app.config. Since you can only save one such app.config, the file version in the VSS quickly gets filled with inconsistent values. Apparently, there is a nice solution to that issue: use the user.config to save user-specific settings.

I found it by sheer luck while reading a very interesting article (Web Projects and Source Control Integration in Visual Studio .NET) in which the appendix A: “Setting Up Dynamic URL Web References”explains how to redirect the appSetting to a user specific file to create dynamic web references. I then did some search on that feature and came across this Q&A posted by Raghavendra Prabhu: http://blogs.msdn.com/rprabhu/articles/433979.aspx.

To redirect the appSettings node from the app.config to the user.config, you’ve to add the following setting to the app.config:
<appSettings file="user.config">

And here’s the funny thing, I knew about the user.config and how the Profiles mechanism in ASP.NET 2 uses it to store user specific settings, but I never did the connection of how it can be used in the development process. Silly really, it’s quite obvious once you think about it. Thanks Microsoft for opening my eyes! 🙂

Posted in .Net v2, VS2005 | Tagged: | Leave a Comment »

Implementing multi-threading in WinForms using the BackgroundWorker class

Posted by Fernando Felman on April 4, 2007

I’ve been asked how to implement multi-threading in .Net 2 quite a few times. The last time was specifically for multi-threading in WinForms and that is the focus of this post. Note that the techniques discussed in this post can be easily adopted to any .Net 2 application (and not just WinForms).
In a multi threaded environment you will have one thread handling the GUI controls and one or more worker threads performing time-consuming operations. The requirements of a multi-threaded solution (regarding the worker thread/s) will be:

  1. The ability to start a worker thread (a logical operation) in an asynchronous manner
  2. The ability to get status notifications from the worker thread and communicate the updated status to the user
  3. The ability to terminate the worker thread by request of the user
  4. The ability to handle errors that occurred in the worker thread during its operation

Starting from .Net 2 we can use the BackgroundWorker class (from the System.ComponentModel namespace) which handles many of the tedious plumbing tasks for us. The BackgroundWorker class support asynchronous activation, status updates, worker termination and the wrapping of any error thrown by the worker thread. This class can be used in any .Net 2 environment (and not just WinForms environments).

In this post I’ll walkthrough a multi-threaded WinForms application. Please download the sample application source code from the CodePlex project Release page. We will create an application to find prime numbers: the user will insert the limit to search and the application will find all prime numbers in that limit. The user should see a status bar progressing for each number tested and a list of prime numbers that will be filled during the process. The user should also be able to cancel the operation at any time.
findprimenumbers.png

Setting up the BackgroundWorker component
OK, let’s start by creating a C# Windows Application. In designer of the form, add the BackgroundWorker component from the “Components” category:
backgroundworker-component.png

The component is added to the bottom section of the designer (where all the non-graphical components are displayed). Click it and change the following properties in the “Asynchronous” section:
WorkerReportsProgress: True – this allows us to send progress notifications
WorkerSupportsCancellation: True – this allows us to cancel the operation at will
backgroundworker-properties.png
Switch to the events view of the property editor and double-click on all the events:
backgroundworker-events.png

We now accomplished all the plumbing tasks of the multi-threaded application. We’ve an asynchronous activator that will notify progress and can be stopped. Now we’ve to add the logic of the application – that is, finding prime numbers and attaching the worker to GUI controls.

In the form there are some controls so the user can interact with the application: a number field, a start/stop button, a progress bar and a logger text box. We now have to use those controls with the worker.

Starting an Asynchronous task: using the RunWorkerAsync method and DoWork event
The background task is handled in the DoWork event. The handler for this event will be called from a new worker thread so the task you perform there will not clutch the GUI. To start doing the work just call the RunWorkerAsync. You can also pass an optional initiate state which will be wrapped up and served in the argument of the DoWork event handler:
this.wrkPrimeNumbers.RunWorkerAsync(maxNumToTest);

Calling the RunWorkAsync will create a new worker thread (so the GUI thread won’t be cluttered) which will execute the DoWork event handler: private void wrkPrimeNumbers_DoWork(object sender, DoWorkEventArgs e)
Note how the initiate state we passed to the RunWorkAsync method is served in the event’s argument:
int limit = (int)e.Argument;

It is important to notice that the argument received in this handler is used further on in the flow. I’ll touch this in the appropriate phases, but for now it’s important to remember that this argument may hold information that will be used when the task is completed. One such property is the result. I use the result property to save the number of prime numbers found in the range:
e.Result = foundPrimeNumbers;

Updating work progress: using the ReportProgress method and the ProgressChanged event
Right now the DoWork event handler is doing some time-consuming work without cluttering the GUI. Now we’ve to notify the user about the progress of the work. This is done in the ProgressUpdate evet. In order to notify about the progress you should call the ReportProgress method from the DoWork event handler:
wrkPrimeNumbers.ReportProgress(progressPercentage, currPrimeNumber);

The progress percentage is always passed and you can also pass an optional state (I use this optional state to send the prime number when one is found). This call will execute the ProgressChanged event handler:
private void wrkPrimeNumbers_ProgressChanged(object sender, ProgressChangedEventArgs e)

And here’s the great thing: the code in the event handler is executed using the GUI thread so it’s safe to update the GUI controls without changing threads (no mode InvodeRequired!). Like in the case of the DoWork, the event handler is served with the state:
this.pgbTestedNumbers.Value = e.ProgressPercentage;

Since the event handler is executed from the GUI thread, it’s safe to update the progress bar without switching thread contexts.

Note: the ReportProgress method will work only when the WorkerReportsProgress attribute of the BackgroundWorker class is set to true. We did that in the designer.

Handling completion: using the RunWorkerCompleted event
Now we’ve an asynchronous task working in the background and notifying the user of its progress. When the task is done it will raise the RunWorkerCompleted event. And again, the great thing about this event is that it’s called using the GUI thread, so it’s safe to update the GUI controls:
private void wrkPrimeNumbers_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

It’s important to understand that this event will always be called when the task is done. The argument of this event contains data regarding the 3 different ways the task has finished:

  • Result: used when the task completed normally. This property contains the result of the of the task. Notice that if the task did not completed normally, accessing this property will throw an exception.
  • Cancelled: used to determine whether the user cancelled the task
  • Error: used when the task failed due to an error. This property contains the exception that caused the task to fail.

The Result and Cancelled properties are set manually in the DoWork event handler and the Error is set by the component when an exception is thrown. This means that you shouldn’t surround the DoWork code with try..catch if you want the error to bubble all the way to the RunWorkerCompleted handler.

Checking working status: using the IsBusy property
Let’s now add the cancelling feature: we want to give the user the ability to cancel the task if it takes too much time. But before we do that, we have to know if we’re busy handling a task or if we’re idle. This should help us decide whether to start a new asynchronous task or to cancel the current one.

This is easily done without the need to query the threading system, all you need to do is check the IsBusy property of the BackgroundWorker class. Too easy, eh? 🙂

I used that property in the Click handler of the start / stop button to decide what action to do:

if (!wrkPrimeNumbers.IsBusy)
// start a new task
else
// stop the current task

Cancelling on-going work: using the CancelAsync method and CancellationPending property
Cancelling an event is done by calling the CancelAsync method. This method can be called from any thread, so it’s OK to call it from the Click handler of the start / stop button. The method will set a property in the worker object so the DoWork event handler will have the ability to act on that.

The CancelAsync method will set the CancellationPending property of the BackgroundWorker class. This property should be periodically checked by the DoWork event handler, and when it’s set to true the handler should cancel its work by: setting the Cancel property of the argument to true and exiting the function. Here’s how I did that in my sample:

if (wrkPrimeNumbers.CancellationPending)
{
// user canceled
e.Cancel = true;
break;
}

As we mentioned previously, the cancel property of the DoWork argument is forwarded to the Cancelled property of the RunWorkerCompleted event handler.

Note: the CancelletionPending property will only be updated when the WorkerSupportsCancellation attribute of the BackgroundWorker class is set to true. We did that in the designer.

So that’s it! We completed our application and we did that without once querying the System.Threading namespace. The BackgroundWorker component wrapped everything for us in a nice Method / Event / Property flow. How great is that?

Epilogue: using the BackgroundWorker class with .Net 1.1
If you’re using .Net 1.1 you’re probably reading this post with both anger and despair.There’s no BackgroundWorker class and you’ve to handle all the plumbing by yourself. But wait, how great would it be to use a .Net 1.1 class with the same features?
Well, in that case, you’d better notice that Juval Löwy published a great step-by-step implementation of the BackgroundWorker class for .Net 1.1: http://www.devx.com/codemag/Article/20639/0/page/1.

Have fun!

Read the rest of this entry »

Posted in .Net v2, Samples, VS2005 | 10 Comments »

Visual Studio keyboard shortcuts every developer should know

Posted by Fernando Felman on March 16, 2007

VS has many keyboard shortcuts. Some may say even too many of them. So many that it might intimidate developers to learn and remember. Well, I thought to come up with the most crucial ones, the ones that perform actions that I know many developers use only with the mouse. So here they are: VS keyboard shortcuts to actions you are using every day, but most of you are using with the mouse (and I’m not listing the very obvious everybody knows).

Try to remember at least the highlighted ones – you’ll be amazed how much you’ll use it.

  • Outlining:
    • Ctrl-M, Ctrl-M: Toggle Outlining Expansion
    • Ctrl-M, Ctrl-O: Collapse to Definitions
    • Ctrl-M, Ctrl-L: Toggle All Outlining
  • Editing tools (refactoring, snippets):
    • Ctrl-K, Ctrl-S: Surround with
    • Ctrl-K, Ctrl-X: Insert snippet
    • Ctrl-Shift-V: Clipboard cycling
  • Find & Replace:
    • Ctrl-I: Incremental Search
    • Ctrl-Shift-F: Find in Files
    • Ctrl-Shift-H: Replace in Files
  • Misc:
    • Ctrl- -: Navigate Backward
    • Alt-Shift-F10: Show smart tag
    • Ctrl-K, Ctrl-I: Tool tip info (mimics the mouse hover tool tip)
    • Ctrl-J : List Members (IntelliSense)
    • Ctrl-Space: Auto complete word (IntelliSense or auto complete)
    • Ctrl-Shift-Space: Parameters Info

Posted in VS2005 | 5 Comments »

Projex, exercising with WinForms

Posted by Fernando Felman on March 9, 2007

I did quite a bit of SharePoint related projects and I learned that one of the most important things you’ve to know when you’re coding a SharePoint Web Part is the Web Control Lifecycle: what events are being called by the infrastructure, when are they called and on which conditions. To that model you’ve to aggregate the SharePoint-specific lifecycle, such as when the Web Part Communication events are being fired and how does that relate to the regular Web Control lifecycle.

So I can say I know about Web Controls quite a bit. But what about WinForm Controls? I wanted to upgrade my knowledge in the WinForms technology to know more about creating Windows Controls, considerations and restrictions I should be aware of, etc. I wanted to investigate the following key aspects in a Widows Control: how does data binding works (and not just how to use it), what are the best practices for coding controls and what internal methods should I be familiar with.

There’s only one good way to learn all of that: experiencing… So I give you my open source, free to use Projex application. This application allows you to create drawings based on a shape I call the Webex, a spider-web shape combined of two points and a mutual anchor point.
Here is how a single Webex looks like:
Simple Webex

And here are some sample of what the application allows you to do (click to enlarge):
Canvax Sample 4 Canvax Sample 3 Canvax Sample 2

The code is constructed in the following way:

  • ProjectXWin: The Windows application. This application has 2 namespaces:
    • Drawing: contains the Pointex and the Webex classes. Both are mathematical representations of a drawing object and aren’t bound to any Control (so you can use them in any displaying technology, including a windows control).
      • Pointex: represents a single Point with anchoring-aware capabilities. I coded this class to encapsulate the anchoring functionality so when the user moves or resizes the drawing area (the window displaying the drawing), the Pointexes will move to their anchored locations causing the drawing to shrink or grow.
      • Webex: a single spider-web drawing represented in an abstract mathematical way. I coded this class to encapsulate the logic of calculating the lines and the resizing functionality for a single Webex.
    • Windows: contains the WinForm controls. This namespace contains many User Controls representing the various value-editors I needed (like Color selector, Pointex editor, etc.) and also have these 2 Custom Controls:
      • WebexPainter: this control display a single Webex. It was coded to facilitate the task of painting a Webex in the form and binding it to its editors.
      • Canvax: a container for multiple WebexPainters. I coded this class to allow the Webex painters to share the same drawing canvas (the same Graphics object).
  • TestProjex: the unit test project implement in MSTest . I usually use NUnit and I wanted to experience with the Microsoft unit test platform to see which is more suitable for me and my team.

Hope you’ll find this project interesting!
Enjoy, and remember that you can leave comments both on the project main page and on the relevant discussion group.

Posted in .Net v2, VS2005 | Leave a Comment »