The Luddite Developer

Friday, 21st September 2012

Visual Studio 2012 Install : Setup completed: however not all features installed correctly – KB2504637 Package Failed

Filed under: Uncategorized — theludditedeveloper @ 4:18 PM
Tags: ,

21-Sep-2012. Got RTM version of VS2012 Professional downloaded from MSDN.

Installing on Windows 7 – Windows v6.1 (Build 7601: Service Pack 1)

Setup completed: however not all features installed correctly

KB2504637 Package Failed.

KB 2504637  appears to refere to the System.Net.dll in the .net 4 framework for multi targeting. As such the impact of the error being reported during the install in unknown. Check out the Micorsoft KB link below:

http://support.microsoft.com/kb/2504637

There are several complaints out there regarding this probelem, but the response so far has been – ‘unable to reproduce’

Further Examples can be found at the following URLs:

http://social.msdn.microsoft.com/Forums/en-US/vssetup/thread/91b13baa-6b6e-43a5-932b-0ce94a1652ce

https://connect.microsoft.com/VisualStudio/feedback/details/753274/error-for-kb2504637-when-installing-vs2012-rc-premium

Log is:

=========================================================================================

The file below is a .xlsx Excel file containing the installation log for Visual Studio 2012

dd_vs_professional_20120921102231

=========================================================================================

Tuesday, 25th January 2011

Innovative Approach to Overcome Unit Test Failures

Filed under: Unit Testing — theludditedeveloper @ 4:01 PM
Nowadays, software productivity seems to take an important place in the software development process. More and more software development groups starting to understand the importance of delivering the product to the market as fast as they can. Many of them are using methodologies and productivity tools to speed up the process.

 One of the major obstacles in getting to the delivery date ready, is the time you waste when automatic tests start to fail. You usually can’t predict when it will happen, and how long would it take for your team to fix it. This makes it hard to estimate how much time you need in order to complete developing a certain feature.

Much more frustrating is the exhausting process a developer needs to go through in order to fix something which used to work just several days ago. If you have no clue of the latest changes which caused your unit test to fail, you would normally start a debug session in order to find the problem. Some developers might check the source control system and review the latest changes, trying to guess the latest change set that caused the failure, then run the unit test with and without the change, in order to conclude whether it is the one to blame. In both cases, the developer usually spends several hours until finding the source of the problem.

Developers that suffer from the problem mentioned above may be interested in the following Unit Testing Tool which helps developers to overcome unit test failures, and thus save valuable development time.

WiseTester

WiseTester

WiseTester helps .NET teams to overcome unit test failures by providing IDE-Based Unit Test Analysis and Source Control Based Unit Test Analysis. When a certain unit test fails, either on the developer’s machine or on the build server, WiseTester can find the exact code changes that caused the failure, saving the time of debugging the code in order to find the problem.

The ideology of the WiseTester is that when a developer gets a notification that one of his unit tests failed, the notification should come together with the exact code changes which caused the failure, before he even starts any debugging.

The IDE-Based Unit Test Analysis is based on information collected from the Visual Studio during the development sessions, and can point the problematic code changes which caused a certain failure up to the code line resolution. In the following screenshot we can see a problematic code change which caused a certain unit test to fail, and was detected by the WiseTester among all the other code changes made in the same development session.

WiseTester detected the exact code line which caused the failure

WiseTester detected the exact code line which caused the failure

 The Source Control Based Unit Test Analysis is based on information coming from the Source Control system, and can point the change set which caused a certain failure, even if it had been committed by another  team member. The following screenshot displays a Unit Test Analysis result which found the developer responsible for breaking the unit test.

WiseTester detected the change set which broke the unit test

WiseTester detected the change set which broke the unit test

Developers usually think about whether the added value of a certain solution is worth the time needed to integrate this solution into the development environment. WiseTester takes that into account, providing a quick setup and a one step integration. No code changes nor migrations are required in order to integrate the solution.

One Step to Add a Solution to the Watchlist

One Step to Add a Solution to the Watchlist

Thanks go to Lior Peleg for writing this article for the TheLudditeDeveloper blog.

Friday, 30th July 2010

Silverlight Navigation Project (VS2008) – Question

Filed under: Silverlight — theludditedeveloper @ 3:29 PM
Tags: , ,
Silverlight-Navigation-Project

Silverlight-Navigation-Project


I have created a minimal project to illustrate the problem. I am using VS2008 SP1 and Silverlight 3.

I created a Silverlight Navigation Project, Added a Product Model, A SingleProductView, and a ProductViewModel.

I added 2 new Pages Review.xaml and Cart.xaml.

Review.xaml uses the SingleProductView to display the product details and an [add to cart] button which when clicked should add the product to the Shopping Cart and then navigate to the Cart.xaml page.

The problem I have is in the SingleViewModel.

The SingleViewModel contains a button (btnAddToCart), which should add the product details to the cart (will be a database populated using a web service call) and then it should navigate to the Cart Page (Cart.xaml)


<UserControl x:Class="SL3NavTest01.SingleProductView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:local="clr-namespace:SL3NavTest01"
    xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
    d:DesignWidth="950" d:DesignHeight="800">
    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel Orientation="Horizontal" VerticalAlignment="Top">
            <Image   Source="/SL3NavTest01;Component/Assets/Images/VS2010Ultimate.jpg" Stretch="None" Height="200" Width="200"
											HorizontalAlignment="Center" VerticalAlignment="Center"/>
            <StackPanel Margin="20,0,0,0">
                <TextBlock Text="{Binding Name, Mode=TwoWay}" TextWrapping="Wrap" Margin="0,30,40,0"
									FontFamily="Verdana" FontSize="18" Foreground="Black" FontWeight="Bold" />
                <StackPanel Orientation="Horizontal" Margin="0,30,0,0">
                    <TextBlock Text="Price: " FontFamily="Verdana" FontSize="16"
										Foreground="Black" FontWeight="Normal" />
                    <TextBlock Text="{Binding Price, Mode=TwoWay}"
										FontFamily="Verdana" FontSize="16" Foreground="Black" FontWeight="Normal" />
                </StackPanel>
                    <Button x:Name="btnAddToCart" Width="75" Margin="0,30,0,0" Content="Add To Cart"
                     Click="btnAddToCart_Click"/>
            </StackPanel>
        </StackPanel>
    </Grid>
</UserControl>


Imports System.Windows.Browser
Partial Public Class SingleProductView
    Inherits UserControl

    Public Sub New()
        InitializeComponent()
    End Sub

    Private Sub btnAddToCart_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        '
        '   The project has been simplified so as to only include the structure and context of where the
        '   problem exists.
        '
        '
        '   On clicking this button the code should:
        '
        '   1.  Add Product to Shopping Cart (via Web Service)
        '   2.  Then navigate to the Shopping Cart Page (\views\Cart.xaml)
        '
        '
        '   Code to add product to shopping cart (I can do this part!)
        '   ----------------------------------------------------------
        '
        '
        '
        '   Code to navigate to Cart.xaml (This is the problem!!!)
        '   ------------------------------------------------------
        '
        '
        '
        '   I can't find a syntax that would do the equivalent of the following:
        '   ContentFrame.Navigate(New Uri("/Cart", UriKind.Relative))
        '
        '   This is my solution:
        '   I know the view is used on the "Review" page and I want to navigate to the "Cart" page.
        '   Also required Imports System.Windows.Browser
        '
        Dim strNav As String = HtmlPage.Document.DocumentUri.ToString
        strNav = Replace(strNav, "Review", "Cart")
        HtmlPage.Window.Navigate(New Uri(strNav, UriKind.Absolute))
        '
        '   It may be that I should use a Hyperlink button, but I am uncertain as to how I would be able
        '   to Add the Product to the Shopping Cart first then Navigate to the Cart.xaml Page.
        '
        '   I realize that this is not stricly MVVM, but I am looking to get the simple solution working
        '   first.
        '
        '   Feel free to provide references to the "correct/best practice" way to do this.
        ''
    End Sub
End Class

Found this thread
http://forums.silverlight.net/forums/t/2684.aspx
which has been read 99,870+ times (may suggest the tiniest of gaps in silverlight functionality or documentation).

My solution is as follows:

        Dim strNav As String = HtmlPage.Document.DocumentUri.ToString
        strNav = Replace(strNav, “Review”, “Cart”)
        HtmlPage.Window.Navigate(New Uri(strNav, UriKind.Absolute))

requires

Imports System.Windows.Browser

I have attached the original simplified project solution zip file so that you can try out various solutions

 SL3NavTest01.zip

Download SL3NavTest01.zip.doc and rename to SL3NavTest01.zip and see what you can come up with.

SL3NavTest01TestPage.html should be used as the start page.

The Luddite Developer.

Thursday, 22nd July 2010

Silverlight Security – Code Obfuscation – Part Two

Filed under: Silverlight — eran @ 6:59 PM

Seems like many .NET developers nowadays are concerned with deploying their apps without applying any form of protection on them beforehand.
As mentioned in a previous post silverlight code must be downloaded to the client machine, this makes it possible to recover the original source code using tools such as ILDasm & .NET Reflector.

Most of us, when we think of obfuscating silverlight apps, refer to a form of obfuscation called ‘symbol renaming’ which means changing the names of classes, methods & variables to meaningless names. The result is a much harder code to read, that makes it more difficult for someone to follow the semantic meaning of the internal structures included in the obfuscated assembly.

This doesn’t come without a price, often due to usage of reflection API either directly by the programmer who wrote the assembly or indirectly by the .NET class library relying on reflection API (e.g. xml serialization, web services) the code would break.
In addition symbol renaming makes it more difficult to understand exception stack trace information collected from production environments as original method names are no longer available. The image below demonstrates how an exception stack trace may look like:

Obfuscated call stack

Developers searching for non-invasive solutions, one that doesn’t suffer from the flaws mentioned above may be interested to look at CliSecure .NET Obfuscator, this is a code protection solution that offers new forms of obfuscation that are effective, easy to configure and integrate with your existing silverlight apps or others still under development  (support for windows phone 7 included).

CliSecure .NET Obfuscator site

On top of symbol renaming CliSecure .NET obfuscator introduces advanced forms of control flow obfuscation and a new obfuscation technique called ‘method call obfuscation’.

Control flow obfuscation aims to destroy existing code patterns and transforms them to different ones that are much harder to follow, the image below shows how a simple for loop would look like after using this method.

Control flow obfuscation demonstrated

Even more interesting is to see the IL representation of the method as shown in .NET reflector, it appears that .NET reflector fails translating the byte code to C# or any other .NET language:

Method call obfuscation hides calls to external library calls, either ones that reference the .NET class library or ones that reference other assemblies developed internally. External calls normally survive symbol renaming as method binding occurs during run time using the method name, however using this method binding is attempted using the method token, an internal token stored within the metadata section that can be used to resolve methods calls.

Method call obfuscation code snippet

As seen in the image below the call to Console.WriteLine is replaced with a call to a delegate method that hides the original call. This method effectively breaks the application code flow, making it harder to browse through the code flow using standard reflection tools.

Wednesday, 28th April 2010

Which versions of Silverlight 3 components do I need for VS2008 SP1 and VS2010?

Filed under: Silverlight,Uncategorized — theludditedeveloper @ 8:34 PM
Which Versions of Silverlight 3 Components are required for VS2010

Which Versions of Silverlight 3 Components are required for VS2010

Running on a XP SP3 system.

I want to keep developing applications using VS2008 SP1, Expression Studio 3 and Silverlight 3.  I don’t want to break anything.

I would like to download and start using VS2010 again without breaking anything.

I noticed the following installation issue regarding VS2010 and Silverlight 3 SDK.

http://blogs.msdn.com/amyd/archive/2009/10/21/visual-studio-2010-and-silverlight-3-sdk.aspx

Visual Web Developer in Visual Studio 2010 has support in box for Silverlight 3 development and includes the Silverlight 3 developer runtime and Silverlight 3 SDK build 3.0.40818.

Silverlight 3 Tools for Visual Studio 2008 and Expression Blend 3 included SDK build 3.0.40624.

Silverlight 3 SDK build 3.0.40818 cannot be installed on machine where build 3.0.40624 is already installed. If you install Visual Studio 2010 on a machine that already has build 3.0.40624 installed, Visual Studio 2010 will indicate that the Silverlight 3 SDK failed to install, however you will still be able to do Silverlight development on Visual Studio 2010 with build 3.0.40624.

Silverlight 3 SDK build 3.0.40818 contains the following updates:

  • Remove dependency on .NET 3.5 and allow build when only .NET 4 is installed
  • Support for use of non-unicode characters in xap name
  • Improvements to refactoring and intellisense

To get build 3.0.40818of the Silverlight 3 SDK, uninstall Silverlight 3 SDK build 3.0.40624 from Add/Remove Programs and then install Silverlight 3 SDK build 3.0.40818 from: http://go2.microsoft.com/fwlink/?LinkID=157102.

———————————————————————————————————

I checked my own system using the Add/Remove Programs utility and found the following:

Currently Installed Program Version
Microsoft Silverlight 3.0.50106.0
Microsoft Silverlight 2 SDK 2.0.31005.0
Microsoft Silverlight 3 SDK 3.0.40624.0
Microsoft Silverlight 3 Toolkit – July 2009 3.0.30702.0037
Microsoft Silverlight 3 Tools for Visual Studio 2008 SP1 –ENU 9.0.30730.126

I found that I can get the following Downloads:

Download URL
Microsoft Silverlight 3 Toolkit – Nov 2009 http://silverlight.codeplex.com/releases/view/36060
Microsoft Silverlight 3 SDK version 3.0.40818 http://www.microsoft.com/downloads/details.aspx?FamilyID=1ea49236-0de7-41b1-81c8-a126ff39975b&displaylang=en
Microsoft Silverlight 3 Tools for Visual Studio 2008 SP1 –ENU http://www.microsoft.com/downloads/details.aspx?familyid=9442B0F2-7465-417A-88F3-5E7B5409E9DD&displaylang=en

 

Questions

  1. I do not develop for Silverlight 2, can this be safely uninstalled?
  2. In what order do I need to remove installed programs/versions and in what order do I need to install new versions?
  3. If I uninstall the Silverlight 3 Toolkit – July 2009, will this break existing applications using this toolkit?
  4. Can the Silverlight 3 Toolkit – July 2009 and Silverlight 3 Toolkit – Nov 2009 be safely installed side by side?
  5. Is there a general rule for what can and cannot be installed side by side with the various Silverlight components?
  6. I already have the current version for Microsoft Silverlight 3 Tools for Visual Studio 2008 SP1 –ENU installed.  Will it need to be re-installed?

Thanks in advance for any replies.

Thursday, 15th October 2009

Scott Hanselman and Daniel Crenna (aka Dimebrain) advise NBC that all they need for Monday Night Football is a Vado or a Flip Mino

OK this is just a bit of fun as I respect the work that these guys do and the information they put out there for we poor mortals.

Scott Hanselman Vado

Dimebrain-Flip

I have been traveling around the country over the summer taking videos of my son at his various track meets.  I created a website and decided to add a video gallery using silverlight.  The intention was to provide a similer experience as provided by the BBC iPlayer.  In particular, I wanted viewers to be able to view the videos in Full Screen mode with one click.  I use a Panasonic SDR-S15 Camcorder, Sony Vegas Movie Studio to edit and Expression 3 to Encode at 1Mb/s.

Iam sure that the Vado HD and the Flip Mino HD perform really well in the environments used by both Scott and Daniel, but it really is a matter of horses for courses.

The Panasonic is a great little camera, lightweight, SDHC memory, and most importantly for me 10 x optical zoom.  When editing these videos and encoding them for the web one very quickly realises that if you do not have the desired quality on the original then you are not going to get the desired results on the end product.  If you check the Video Gallery then you will notice that the movies get better over time as I learn more.  Most importantly, use a tripod for these high zoom shots.

My next camera will definitely be HD and I will look to get better than 10 x zoom.  I am afraid that I can envisage an $1100 camera (UK prices really suck by the way) and I am absolutely certain that NBC will be paying a lot more than $1100 for the cameras that they use for Monday Night Football.

My point is, do not let Scott and Daniel talk you out of getting the camera you need.  If you need a Smith & Wesson 45, the most powerful hand camcorder ever made then make your day.

Friday, 9th October 2009

Silverlight, WCF, Security And Things You Might Not Know

Filed under: Uncategorized — theludditedeveloper @ 11:33 AM
Tags: , , ,

Silverlight-Security-WCF

On 24-Jul-2009, I wrote an article entitled Where are the guides to Security Best Practices in Silverlight? , and followed this up with an article entitled Silverlight Security – Part One – Code Obfuscation.  Since then of I have been keeping an eye open for any new articles that tackled this very important subject.

Today, I found an article by Robbe Morris over at eggheadcafe.com entitled Silverlight, WCF, Security And Things You Might Not Know.

This article covers many of the security steps that you will want to implement in any Silverlight / WCF application.

Monday, 28th September 2009

Have you got lost in the maze of tutorials available for Silverlight and WPF?

Filed under: Uncategorized — theludditedeveloper @ 8:24 PM
Tags: , , , , , , , , ,
Silverlight Confusion

Silverlight Confusion

 

I was looking for a tool that would allow me to organize links to all the articles that I have read.

I would like to add notes about each of the articles to tell me what important feature or technique is being explained. The notes would also tell me where to find the projects I installed or implemented on my own development systems.

I would also like to be able to index the articles by tags and categories and order the articles, videos, or tutorials in a way that will help me learn the subject in detail without missing anything out. Maybe something like a learning tree.

So for instance in Silverlight, you may have:

Silverlight Tutorial Part 1 (of 8): Creating “Hello World” with Silverlight 2 and VS 2008 by Scott Guthrie, here.

Find on my computer here:
C:\Documents and Settings\Luddite\My Documents\Visual Studio 2008\Projects\Silverlight\MSDiggSample_VB

Jesse Liberty has started Project Turing, here.

This project uses RIA Services which is currently in beta, I will want to come back to this when RIA Services has been officially released.

Brad Abrams has a series on BusinessApps for Silverlight 3 RTM and .NET RIA Services (and now Azure), here.

The articles are numerous and varied and some way of keeping things up to date, allowing you to replace articles that have become obsolete, or replace articles which you have found to do a better job.

Can anyone recommend a good product that would help with this.

Scot Hanselman recommends Evernote, not for this, but I was wondering if something like Evernote would fit the bill…

Friday, 14th August 2009

UK Developers are being overcharged by 67% for Microsoft Expression Studio 3

Filed under: Uncategorized — theludditedeveloper @ 3:22 PM
Tags: , , , ,
UK Developers are being overcharged by 67% for Expression Studio 3

UK Developers are being overcharged by 67% for Expression Studio 3

In a previous post, I mentioned that  the Microsoft Upgrade offer for Expression Studio 3 was available to those who held a license for Visual Studio 2005 or later.  In the US that means the Upgrade is available for $349 and the full product is available for $599. Both prices exclude tax.

If you live in the UK (or anywhere in the EC) you will almost certainly be overcharged to the tune of 67%

The UK Price is

£394.61

This excludes VAT of

£51.47

Price Excluding Tax (VAT) is

£343.14

Exchange Rate is £1 = $1.70

 

Dollar Price (Excl Tax) in UK is

$583.34

Dollar Price in US is

$349.00

UK developers are being overcharged

67%

 

Expression 3 Upgrade Offer for Visual Studio Developers

Expression 3 Upgrade Offer for Visual Studio Developers

 

Click on the image above, or click here to verify the situation for yourself.

This is the type of situation that the UK government and the EU parliament should be addressing.  Users do not need or even want IE unbundled from the Windows operating system.

Monday, 10th August 2009

Using the Background Worker Process for Long Running Processes in WPF and Silverlight

Using the Background Worker Process for Long Running Processes in WPF and Silverlight

Using the Background Worker Process for Long Running Processes in WPF and Silverlight

In a previous article WPF DataBinding using Visual Basic (VB.NET), a problem was encountered when trying to keep the User Interface active during Long Running Processes as a result of a button click.  Either the whole system would hang until the process was completed or the program would crash.

This hang-up is due to the fact that both the Long Running Process and the UI are using the same thread.  The solution is to run the Long Running Process in a separate thread.  The BackgroundWorker component, gives you the ability to execute Long Running Processes in the background asynchronously, on a separate thread from the application’s main UI thread.

I have just started a project which is going to have quite a few of these Long Running Processes and so what I need is a simple implementation of the Background Worker  process which I can expand as required.

The implementation consists of a WPF page with a start button, a cancel button and three labels to let the user know what is happening before, during and after the Long Running Process has been started by the start button.


<Page x:Class="BackGroundWorkerExample"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="BackGroundWorkerExample"
    x:Name="BackGroundWorkerExample"  WindowTitle="WPF Luddite Test Bed: Background Worker Example" Width="1024" Height="768">
    <StackPanel>
        <Button x:Name="btnStartBackgroundProcess" Width="300" Height="30" Margin="0 20 0 0"
            Content="Start Background Process">
        </Button>
        <Label x:Name="lblStartedCompleted" Content="" Width="500" Height="30" Margin="0 20 0 0">
        </Label>
        <Label x:Name="lblCounter" Content="" Width="500" Height="30" Margin="0 20 0 0">
        </Label>
        <Label x:Name="lblPercentCompleted" Content="" Width="500" Height="30" Margin="0 20 0 0">
        </Label>
        <Button x:Name="btnCancelBackgroundProcess" Width="300" Height="30" Margin="0 20 0 0"
            Content="Cancel Background Process" IsEnabled="False">
        </Button>

    </StackPanel>
</Page>

The following steps will be required in the code behind:

1.  Define a new BackgroundWorker, create an instance and do some setup.

2. Define the LongRunningProcess – must not reference the User Interface (UI).

3. Define a subroutine to handle the BackgroundWorker DoWork event.

4. Define a subroutine to handle the BackgroundWorker ProgressChanged event.

5. Define a subroutine to handle the BackgroundWorker RunWorkerCompleted event.

6. Define a subroutine to handle the event caused by the Start button being clicked.

7. Define a subroutine to handle the event caused by the Cancel button being clicked.


Imports System.ComponentModel

Partial Public Class BackGroundWorkerExample

    '
    '   Define a new backgroung worker.
    '
    Private WithEvents bw As New BackgroundWorker()
    '
    ' Create new instance of BackGroundWorker and do some setup
    '
    Public Sub New()

        InitializeComponent()

        bw.WorkerSupportsCancellation = True
        bw.WorkerReportsProgress = True

    End Sub

    Private Function LongRunningProcess() As String
        '
        '   The LongRunngProcess should NOT refer to any UI objects.
        '
        Dim iteration As Integer = CInt(100000000 / 100)
        Dim cnt As Long = 0

        For i As Long = 0 To 100000000
            '
            '   Bring the LongRunningProcess to an orderly termination if the Cancel button is clicked.
            '   - see further comments in routine that handles the btnCancelBackgroundProcess_Click event.
            '
            If bw.CancellationPending Then
                Return ""
            End If

            cnt = cnt + 1

            '
            '   Report Progress:
            '   When you need the background operation to report on its progress,
            '   you can call the ReportProgress method to raise the ProgressChanged event.
            '   The ReportProgress Method permits up to 2 parameters (ProgressChangedEventArgs):
            '       Paramater 1. Is of type Integer and is defined as "percentProgress"
            '       Paremeter 2. Is of type Object and is defined as "userState"
            '       I see no reason why you can't return any information you want as long as you conform to the
            '       parameter types integer and object.
            '
            '   In a simple example like this, if the ReportProgress method was called for every iteration of i
            '   then the system would probably hang the user interface and run out of memory. Therefore, in this instance, we
            '   only report back on every 10,000 iterations.
            '
            If (i Mod 10000 = 0) _
                And (bw IsNot Nothing) _
                AndAlso bw.WorkerReportsProgress Then
                '
                '   Call ReportProgress
                '
                bw.ReportProgress(i \ iteration, cnt)
            End If

        Next

        Return cnt.ToString()

    End Function

    Private Sub backgroundWorker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bw.DoWork
        '
        ' call long running process and get result
        '
        e.Result = Me.LongRunningProcess()
        '
        ' Cancel if cancel button was clicked.
        '
        If bw.CancellationPending Then
            e.Cancel = True ' This sets the Cancelled property of the RunWorkerCompletedEventArgs
            Return
        End If

    End Sub

    Private Sub backgroundWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bw.ProgressChanged
        '
        '   Use the ProgressChanged Sub to give user feedback via the UI.
        '
        ' Update UI with values contained in ProgressChangedEventArgs e.ProgressPercentage and e.UserState.
        '
        Me.lblPercentCompleted.Content = CStr(e.ProgressPercentage) & "% Completed."
        lblCounter.Content = CStr(e.UserState)
        ''
    End Sub

    Private Sub backgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles bw.RunWorkerCompleted
        '
        ' Back on primary thread, can access ui controls
        '
        If e.Cancelled Then
            Me.lblStartedCompleted.Content = "Process Cancelled."
        Else
            Me.lblStartedCompleted.Content = "Background Process Completed. "
        End If
        '
        Me.btnStartBackgroundProcess.IsEnabled = True
        Me.btnCancelBackgroundProcess.IsEnabled = False
        ''
    End Sub

    Private Sub btnStartBackgroundProcess_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnStartBackgroundProcess.Click
        '
        lblStartedCompleted.Content = "Background Process Started..."
        Me.btnStartBackgroundProcess.IsEnabled = False
        Me.btnCancelBackgroundProcess.IsEnabled = True
        '
        ' Calls DoWork on secondary thread
        '
        bw.RunWorkerAsync()
        '
        ' RunWorkerAsync returns immediately.
        ''
    End Sub

    Private Sub btnCancelBackgroundProcess_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCancelBackgroundProcess.Click
        '
        '   There are several points to note when cancelling a process:
        '
        '   1. The WorkerSupportsCancellation property must have been initialised to true.
        '
        '   2. The CancelAsync method does not immediately cancel the process, but instead sets the
        '      CancellationPending property to True.  It is the therefore important that the LongRunningProcess
        '      periodically checks the CancellationPending property and if True the process should be
        '      terminated in an orderly manner.
        '
        '   3. The CancellationPending property of the background worker process should also be checked by the
        '      routine handling the DoWork method after the LongRunningProcess has completed.
        '      If the CancellationPending Property is true then the DoWork routine should set Cancel
        '      property of the DoWorkEventArgs to True.
        '      CancelAsync() method.  This should be checked by the routine which is handling the RunWorkerCompleted
        '      event.
        '
        '   4. It is good practice to ensure theat the Cancel button is only enabled when the LongRunningProcess
        '      is actually running.  Therefore the button should be disabled by default, only enabled when the
        '      process is started, and disable again when the process is completed or cancelled.
        '
        bw.CancelAsync()
        '
        btnCancelBackgroundProcess.IsEnabled = False
        '
    End Sub

End Class

Hope this helps.

Next Page »

The Rubric Theme Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.