Procedimiento para hospedar varias versiones de un flujo de trabajo en paraleloHow to: Host Multiple Versions of a Workflow Side-by-Side

WorkflowIdentity proporciona una manera para que los desarrolladores de aplicaciones de flujo de trabajo asocien un nombre y una versión con una definición de flujo de trabajo, y para que esta información se asocie a una instancia de flujo de trabajo persistente.WorkflowIdentity provides a way for workflow application developers to associate a name and a version with a workflow definition, and for this information to be associated with a persisted workflow instance. Los desarrolladores de aplicaciones de flujo de trabajo pueden usar esta información de identidad para habilitar escenarios como la ejecución en paralelo de varias versiones de una definición de flujo de trabajo; además esta información proporciona la piedra angular para otras funcionalidades como la actualización dinámica.This identity information can be used by workflow application developers to enable scenarios such as side-by-side execution of multiple versions of a workflow definition, and provides the cornerstone for other functionality such as dynamic update. Este paso del tutorial demuestra cómo usar WorkflowIdentity para hospedar varias versiones de un flujo de trabajo simultáneamente.This step in the tutorial demonstrates how to use WorkflowIdentity to host multiple versions of a workflow at the same time.

Nota

Para descargar una versión completada o ver un tutorial en vídeo del tutorial, consulte Windows Workflow Foundation (WF45)-Introducción tutorial.To download a completed version or view a video walkthrough of the tutorial, see Windows Workflow Foundation (WF45) - Getting Started Tutorial.

En este temaIn this topic

En este paso del tutorial, las actividades de WriteLine en el flujo de trabajo se modifican para proporcionar información adicional y se agrega una nueva actividad WriteLine.In this step of the tutorial, the WriteLine activities in the workflow are modified to provide additional information, and a new WriteLine activity is added. Una copia del ensamblado original de flujo de trabajo queda almacenada y la aplicación de host se actualiza de tal modo que puede ejecutar tanto el flujo de trabajo original como el actualizado al mismo tiempo.A copy of the original workflow assembly is stored, and the host application is updated so that it can run both the original and the updated workflows at the same time.

Nota

Antes de seguir los pasos de este tema, ejecute la aplicación, inicie varios flujos de trabajo de cada tipo y realice uno o dos intentos con cada uno.Before following the steps in this topic, run the application, start several workflows of each type, and making one or two guesses for each one. Estos flujos de trabajo persistentes se usan en este paso y en el paso siguiente, cómo: Actualiza la definición de una instanciade flujo de trabajo en ejecución.These persisted workflows are used in this step and the following step, How to: Update the Definition of a Running Workflow Instance.

Nota

Cada paso del tutorial de introducción depende de los pasos anteriores.Each step in the Getting Started tutorial depends on the previous steps. Si no completó los pasos anteriores, puede descargar una versión completada del tutorial en Windows Workflow Foundation (WF45)-Introducción tutorial.If you did not complete the previous steps you can download a completed version of the tutorial from Windows Workflow Foundation (WF45) - Getting Started Tutorial.

Para hacer una copia del proyecto NumberGuessWorkflowActivitiesTo make a copy of the NumberGuessWorkflowActivities project

  1. Abra la solución WF45GettingStartedTutorial en Visual Studio 2012 si no está abierta.Open the WF45GettingStartedTutorial solution in Visual Studio 2012 if it is not open.

  2. Presione CTRL+MAYÚS+B para compilar la solución.Press CTRL+SHIFT+B to build the solution.

  3. Cierre la solución WF45GettingStartedTutorial .Close the WF45GettingStartedTutorial solution.

  4. Abra el Explorador de Windows y navegue hasta la carpeta donde se encuentran el archivo de solución del tutorial y las carpetas de proyecto.Open Windows Explorer and navigate to the folder where the tutorial solution file and the project folders are located.

  5. Cree una nueva carpeta denominada PreviousVersions en la misma carpeta que NumberGuessWorkflowHost y NumberGuessWorkflowActivities.Create a new folder named PreviousVersions in the same folder as NumberGuessWorkflowHost and NumberGuessWorkflowActivities. Esta carpeta se usa para guardar los ensamblados que contienen las distintas versiones de los flujos de trabajo usados en los pasos de tutorial posteriores.This folder is used to contain the assemblies that contain the different versions of the workflows used in the subsequent tutorial steps.

  6. Vaya a la carpeta NumberGuessWorkflowActivities\bin\debug (o bin\release según la configuración del proyecto).Navigate to the NumberGuessWorkflowActivities\bin\debug folder (or bin\release depending on your project settings). Copie NumberGuessWorkflowActivities. dll y péguelo en la carpeta PreviousVersionsCopy NumberGuessWorkflowActivities.dll and paste it into the PreviousVersions folder.

  7. Cambie el nombre de NumberGuessWorkflowActivities. dll de la carpeta PreviousVersions a NumberGuessWorkflowActivities_v1. dll.Rename NumberGuessWorkflowActivities.dll in the PreviousVersions folder to NumberGuessWorkflowActivities_v1.dll.

    Nota

    En los pasos de este tema se muestra una manera de administrar los ensamblados usados para contener varias versiones de los flujos de trabajo.The steps in this topic demonstrate one way to manage the assemblies used to contain multiple versions of the workflows. También se pueden usar otros métodos, como el nombre seguro de los ensamblados y su registro en la memoria caché global de ensamblados.Other methods such as strong naming the assemblies and registering them in the global assembly cache could also be used.

  8. Cree una nueva carpeta denominada NumberGuessWorkflowActivities_du en la misma carpeta que NumberGuessWorkflowHost, NumberGuessWorkflowActivitiesy la carpeta PreviousVersions recién agregada, y copie todos los archivos y subcarpetas de la carpeta NumberGuessWorkflowActivities en la nueva carpeta NumberGuessWorkflowActivities_duCreate a new folder named NumberGuessWorkflowActivities_du in the same folder as NumberGuessWorkflowHost, NumberGuessWorkflowActivities, and the newly added PreviousVersions folder, and copy all of the files and subfolders from the NumberGuessWorkflowActivities folder into the new NumberGuessWorkflowActivities_du folder. Esta copia de seguridad del proyecto para la versión inicial de las actividades se usa en cómo: Actualiza la definición de una instanciade flujo de trabajo en ejecución.This backup copy of the project for the initial version of the activities is used in How to: Update the Definition of a Running Workflow Instance.

  9. Vuelva a abrir la solución WF45GettingStartedTutorial en Visual Studio 2012.Re-open the WF45GettingStartedTutorial solution in Visual Studio 2012.

Para actualizar los flujos de trabajoTo update the workflows

En esta sección, se actualizan las definiciones de flujo de trabajo.In this section, the workflow definitions are updated. Se actualizan las dos actividades de WriteLine que proporcionan informes sobre los intentos del usuario, y se agrega una nueva actividad WriteLine que proporciona información adicional sobre el juego una vez se ha adivinado el número.The two WriteLine activities that give feedback on the user's guess are updated, and a new WriteLine activity is added that provides additional information about the game once the number is guessed.

Para actualizar el flujo de trabajo StateMachineTo update the StateMachine workflow

  1. En Explorador de soluciones, en el proyecto NumberGuessWorkflowActivities , haga doble clic en StateMachineNumberGuessWorkflow. Xaml.In Solution Explorer, under the NumberGuessWorkflowActivities project, double-click StateMachineNumberGuessWorkflow.xaml.

  2. Haga doble clic en la transición adivinar incorrectamente en el equipo de estado.Double-click the Guess Incorrect transition on the state machine.

  3. Actualice Text de WriteLine del extremo izquierdo en la actividad If.Update the Text of the left-most WriteLine in the If activity.

    Guess & " is too low."
    
    Guess + " is too low."
    
  4. Actualice Text de WriteLine del extremo derecho en la actividad If.Update the Text of the right-most WriteLine in the If activity.

    Guess & " is too high."
    
    Guess + " is too high."
    
  5. Vuelva a la vista de equipo de estado general en el diseñador de flujo de trabajo haciendo clic en StateMachine en la pantalla de la ruta de navegación en la parte superior del diseñador de flujo de trabajo.Return to the overall state machine view in the workflow designer by clicking StateMachine in the breadcrumb display at the top of the workflow designer.

  6. Haga doble clic en la transición adivinar corrección en el equipo de estado.Double-click the Guess Correct transition on the state machine.

  7. Arrastre una actividad WriteLine de la sección primitivas del cuadro de herramientas y colóquela en la etiqueta colocar actividad de acción aquí de la transición.Drag a WriteLine activity from the Primitives section of the Toolbox and drop it on the Drop Action activity here label of the transition.

  8. Escriba la siguiente expresión en el cuadro de propiedad Text.Type the following expression into the Text property box.

    Guess & " is correct. You guessed it in " & Turns & " turns."
    
    Guess + " is correct. You guessed it in " + Turns + " turns."
    

Para actualizar el flujo de trabajo del diagrama de flujoTo update the Flowchart workflow

  1. En Explorador de soluciones, en el proyecto NumberGuessWorkflowActivities , haga doble clic en FlowchartNumberGuessWorkflow. Xaml.In Solution Explorer, under the NumberGuessWorkflowActivities project, double-click FlowchartNumberGuessWorkflow.xaml.

  2. Actualice Text de la actividad WriteLine del extremo izquierdo.Update the Text of the left-most WriteLine activity.

    Guess & " is too low."
    
    Guess + " is too low."
    
  3. Actualice Text de la actividad WriteLine del extremo derecho.Update the Text of the right-most WriteLine activity.

    Guess & " is too high."
    
    Guess + " is too high."
    
  4. Arrastre una actividad WriteLine de la sección primitivas del cuadro de herramientas y colóquela en el punto de colocación de True la acción del nivel superior FlowDecision.Drag a WriteLine activity from the Primitives section of the Toolbox and drop it on the drop point of the True action of the topmost FlowDecision. La actividad WriteLine se agrega al diagrama de flujo y se vincula a la acción True de FlowDecision.The WriteLine activity is added to the flowchart and linked to the True action of the FlowDecision.

  5. Escriba la siguiente expresión en el cuadro de propiedad Text.Type the following expression into the Text property box.

    Guess & " is correct. You guessed it in " & Turns & " turns."
    
    Guess + " is correct. You guessed it in " + Turns + " turns."
    

Para actualizar el flujo de trabajo secuencialTo update the Sequential workflow

  1. En Explorador de soluciones, en el proyecto NumberGuessWorkflowActivities , haga doble clic en SequentialNumberGuessWorkflow. Xaml.In Solution Explorer, under the NumberGuessWorkflowActivities project, double-click SequentialNumberGuessWorkflow.xaml.

  2. Actualice Text de WriteLine del extremo izquierdo en la actividad If.Update the Text of the left-most WriteLine in the If activity.

    Guess & " is too low."
    
    Guess + " is too low."
    
  3. Actualice Text de la actividad WriteLine del extremo derecho en la actividad If.Update the Text of the right-most WriteLine activity in the If activity.

    Guess & " is too high."
    
    Guess + " is too high."
    
  4. Arrastre una actividad WriteLine de la sección primitivas del cuadro de herramientas y colóquela después de la actividad While para que WriteLine sea la actividad final de la actividad raíz Sequence .Drag a WriteLine activity from the Primitives section of the Toolbox and drop it after the DoWhile activity so that the WriteLine is the final activity in the root Sequence activity.

  5. Escriba la siguiente expresión en el cuadro de propiedad Text.Type the following expression into the Text property box.

    Guess & " is correct. You guessed it in " & Turns & " turns."
    
    Guess + " is correct. You guessed it in " + Turns + " turns."
    

Para actualizar WorkflowVersionMap para que incluya las versiones anteriores del flujo de trabajoTo update WorkflowVersionMap to include the previous workflow versions

  1. Haga doble clic en WorkflowVersionMap.CS (o WorkflowVersionMap. VB) en el proyecto NumberGuessWorkflowHost para abrirlo.Double-click WorkflowVersionMap.cs (or WorkflowVersionMap.vb) under the NumberGuessWorkflowHost project to open it.

  2. Agregue las siguientes instrucciones using (o Imports) al principio del archivo con las demás instrucciones using (o Imports).Add the following using (or Imports) statements to the top of the file with the other using (or Imports) statements.

    Imports System.Reflection
    Imports System.IO
    
    using System.Reflection;
    using System.IO;
    
  3. Agregue tres nuevas identidades de flujo de trabajo justo debajo de las tres declaraciones de identidad de flujo de trabajo existentes.Add three new workflow identities just below the three existing workflow identity declarations. Estas nuevas identidades de flujo de trabajo de v1 se usarán para proporcionar la definición de flujo de trabajo correcta a los flujos de trabajo iniciados antes de que se realizaran las actualizaciones.These new v1 workflow identities will be used provide the correct workflow definition to workflows started before the updates were made.

    'Current version identities.
    Public StateMachineNumberGuessIdentity As WorkflowIdentity
    Public FlowchartNumberGuessIdentity As WorkflowIdentity
    Public SequentialNumberGuessIdentity As WorkflowIdentity
    
    'v1 Identities.
    Public StateMachineNumberGuessIdentity_v1 As WorkflowIdentity
    Public FlowchartNumberGuessIdentity_v1 As WorkflowIdentity
    Public SequentialNumberGuessIdentity_v1 As WorkflowIdentity
    
    // Current version identities.
    static public WorkflowIdentity StateMachineNumberGuessIdentity;
    static public WorkflowIdentity FlowchartNumberGuessIdentity;
    static public WorkflowIdentity SequentialNumberGuessIdentity;
    
    // v1 identities.
    static public WorkflowIdentity StateMachineNumberGuessIdentity_v1;
    static public WorkflowIdentity FlowchartNumberGuessIdentity_v1;
    static public WorkflowIdentity SequentialNumberGuessIdentity_v1;
    
  4. En el constructor WorkflowVersionMap, actualice la propiedad Version de las tres identidades de flujo de trabajo actuales a 2.0.0.0.In the WorkflowVersionMap constructor, update the Version property of the three current workflow identities to 2.0.0.0.

    'Add the current workflow version identities.
    StateMachineNumberGuessIdentity = New WorkflowIdentity With
    {
        .Name = "StateMachineNumberGuessWorkflow",
        .Version = New Version(2, 0, 0, 0)
    }
    
    FlowchartNumberGuessIdentity = New WorkflowIdentity With
    {
        .Name = "FlowchartNumberGuessWorkflow",
        .Version = New Version(2, 0, 0, 0)
    }
    
    SequentialNumberGuessIdentity = New WorkflowIdentity With
    {
        .Name = "SequentialNumberGuessWorkflow",
        .Version = New Version(2, 0, 0, 0)
    }
    
    map.Add(StateMachineNumberGuessIdentity, New StateMachineNumberGuessWorkflow())
    map.Add(FlowchartNumberGuessIdentity, New FlowchartNumberGuessWorkflow())
    map.Add(SequentialNumberGuessIdentity, New SequentialNumberGuessWorkflow())
    
    // Add the current workflow version identities.
    StateMachineNumberGuessIdentity = new WorkflowIdentity
    {
        Name = "StateMachineNumberGuessWorkflow",
        // Version = new Version(1, 0, 0, 0),
        Version = new Version(2, 0, 0, 0)
    };
    
    FlowchartNumberGuessIdentity = new WorkflowIdentity
    {
        Name = "FlowchartNumberGuessWorkflow",
        // Version = new Version(1, 0, 0, 0),
        Version = new Version(2, 0, 0, 0)
    };
    
    SequentialNumberGuessIdentity = new WorkflowIdentity
    {
        Name = "SequentialNumberGuessWorkflow",
        // Version = new Version(1, 0, 0, 0),
        Version = new Version(2, 0, 0, 0)
    };
    
    map.Add(StateMachineNumberGuessIdentity, new StateMachineNumberGuessWorkflow());
    map.Add(FlowchartNumberGuessIdentity, new FlowchartNumberGuessWorkflow());
    map.Add(SequentialNumberGuessIdentity, new SequentialNumberGuessWorkflow());
    

    El código que agrega las versiones actuales de los flujos de trabajo al diccionario usa las versiones actuales a las que se hace referencia en el proyecto, por lo que no es necesario actualizar el código que inicializa las definiciones de flujo de trabajo.The code in that adds the current versions of the workflows to the dictionary uses the current versions that are referenced in the project, so the code that initializes the workflow definitions does not need to be updated.

  5. Agregue el código siguiente en el constructor justo después del código que agrega las versiones actuales al diccionario.Add the following code in the constructor just after the code that adds the current versions to the dictionary.

    'Initialize the previous workflow version identities.
    StateMachineNumberGuessIdentity_v1 = New WorkflowIdentity With
    {
        .Name = "StateMachineNumberGuessWorkflow",
        .Version = New Version(1, 0, 0, 0)
    }
    
    FlowchartNumberGuessIdentity_v1 = New WorkflowIdentity With
    {
        .Name = "FlowchartNumberGuessWorkflow",
        .Version = New Version(1, 0, 0, 0)
    }
    
    SequentialNumberGuessIdentity_v1 = New WorkflowIdentity With
    {
        .Name = "SequentialNumberGuessWorkflow",
        .Version = New Version(1, 0, 0, 0)
    }
    
    // Initialize the previous workflow version identities.
    StateMachineNumberGuessIdentity_v1 = new WorkflowIdentity
    {
        Name = "StateMachineNumberGuessWorkflow",
        Version = new Version(1, 0, 0, 0)
    };
    
    FlowchartNumberGuessIdentity_v1 = new WorkflowIdentity
    {
        Name = "FlowchartNumberGuessWorkflow",
        Version = new Version(1, 0, 0, 0)
    };
    
    SequentialNumberGuessIdentity_v1 = new WorkflowIdentity
    {
        Name = "SequentialNumberGuessWorkflow",
        Version = new Version(1, 0, 0, 0)
    };
    

    Estas identidades de flujo de trabajo están asociadas a las versiones iniciales de las definiciones de flujo de trabajo correspondientes.These workflow identities are associated with the initial versions of the corresponding workflow definitions.

  6. A continuación, cargue el ensamblado que contiene la versión inicial de las definiciones de flujo de trabajo, y cree y agregue las definiciones de flujo de trabajo al diccionario.Next, load the assembly that contains the initial version of the workflow definitions, and create and add the corresponding workflow definitions to the dictionary.

    'Add the previous version workflow identities to the dictionary along with
    'the corresponding workflow definitions loaded from the v1 assembly.
    'Assembly.LoadFile requires an absolute path so convert this relative path
    'to an absolute path.
    Dim v1AssemblyPath As String = "..\..\..\PreviousVersions\NumberGuessWorkflowActivities_v1.dll"
    v1AssemblyPath = Path.GetFullPath(v1AssemblyPath)
    Dim v1Assembly As Assembly = Assembly.LoadFile(v1AssemblyPath)
    
    map.Add(StateMachineNumberGuessIdentity_v1,
        v1Assembly.CreateInstance("NumberGuessWorkflowActivities.StateMachineNumberGuessWorkflow"))
    
    map.Add(SequentialNumberGuessIdentity_v1,
        v1Assembly.CreateInstance("NumberGuessWorkflowActivities.SequentialNumberGuessWorkflow"))
    
    map.Add(FlowchartNumberGuessIdentity_v1,
        v1Assembly.CreateInstance("NumberGuessWorkflowActivities.FlowchartNumberGuessWorkflow"))
    
    // Add the previous version workflow identities to the dictionary along with
    // the corresponding workflow definitions loaded from the v1 assembly.
    // Assembly.LoadFile requires an absolute path so convert this relative path
    // to an absolute path.
    string v1AssemblyPath = @"..\..\..\PreviousVersions\NumberGuessWorkflowActivities_v1.dll";
    v1AssemblyPath = Path.GetFullPath(v1AssemblyPath);
    Assembly v1Assembly = Assembly.LoadFile(v1AssemblyPath);
    
    map.Add(StateMachineNumberGuessIdentity_v1,
        v1Assembly.CreateInstance("NumberGuessWorkflowActivities.StateMachineNumberGuessWorkflow") as Activity);
    
    map.Add(SequentialNumberGuessIdentity_v1,
        v1Assembly.CreateInstance("NumberGuessWorkflowActivities.SequentialNumberGuessWorkflow") as Activity);
    
    map.Add(FlowchartNumberGuessIdentity_v1,
        v1Assembly.CreateInstance("NumberGuessWorkflowActivities.FlowchartNumberGuessWorkflow") as Activity);
    

    En el ejemplo siguiente se muestra la lista completa para la clase WorkflowVersionMap actualizada.The following example is the complete listing for the updated WorkflowVersionMap class.

    Public Module WorkflowVersionMap
        Dim map As Dictionary(Of WorkflowIdentity, Activity)
    
        'Current version identities.
        Public StateMachineNumberGuessIdentity As WorkflowIdentity
        Public FlowchartNumberGuessIdentity As WorkflowIdentity
        Public SequentialNumberGuessIdentity As WorkflowIdentity
    
        'v1 Identities.
        Public StateMachineNumberGuessIdentity_v1 As WorkflowIdentity
        Public FlowchartNumberGuessIdentity_v1 As WorkflowIdentity
        Public SequentialNumberGuessIdentity_v1 As WorkflowIdentity
    
        Sub New()
            map = New Dictionary(Of WorkflowIdentity, Activity)
    
            'Add the current workflow version identities.
            StateMachineNumberGuessIdentity = New WorkflowIdentity With
            {
                .Name = "StateMachineNumberGuessWorkflow",
                .Version = New Version(2, 0, 0, 0)
            }
    
            FlowchartNumberGuessIdentity = New WorkflowIdentity With
            {
                .Name = "FlowchartNumberGuessWorkflow",
                .Version = New Version(2, 0, 0, 0)
            }
    
            SequentialNumberGuessIdentity = New WorkflowIdentity With
            {
                .Name = "SequentialNumberGuessWorkflow",
                .Version = New Version(2, 0, 0, 0)
            }
    
            map.Add(StateMachineNumberGuessIdentity, New StateMachineNumberGuessWorkflow())
            map.Add(FlowchartNumberGuessIdentity, New FlowchartNumberGuessWorkflow())
            map.Add(SequentialNumberGuessIdentity, New SequentialNumberGuessWorkflow())
    
            'Initialize the previous workflow version identities.
            StateMachineNumberGuessIdentity_v1 = New WorkflowIdentity With
            {
                .Name = "StateMachineNumberGuessWorkflow",
                .Version = New Version(1, 0, 0, 0)
            }
    
            FlowchartNumberGuessIdentity_v1 = New WorkflowIdentity With
            {
                .Name = "FlowchartNumberGuessWorkflow",
                .Version = New Version(1, 0, 0, 0)
            }
    
            SequentialNumberGuessIdentity_v1 = New WorkflowIdentity With
            {
                .Name = "SequentialNumberGuessWorkflow",
                .Version = New Version(1, 0, 0, 0)
            }
    
            'Add the previous version workflow identities to the dictionary along with
            'the corresponding workflow definitions loaded from the v1 assembly.
            'Assembly.LoadFile requires an absolute path so convert this relative path
            'to an absolute path.
            Dim v1AssemblyPath As String = "..\..\..\PreviousVersions\NumberGuessWorkflowActivities_v1.dll"
            v1AssemblyPath = Path.GetFullPath(v1AssemblyPath)
            Dim v1Assembly As Assembly = Assembly.LoadFile(v1AssemblyPath)
    
            map.Add(StateMachineNumberGuessIdentity_v1,
                v1Assembly.CreateInstance("NumberGuessWorkflowActivities.StateMachineNumberGuessWorkflow"))
    
            map.Add(SequentialNumberGuessIdentity_v1,
                v1Assembly.CreateInstance("NumberGuessWorkflowActivities.SequentialNumberGuessWorkflow"))
    
            map.Add(FlowchartNumberGuessIdentity_v1,
                v1Assembly.CreateInstance("NumberGuessWorkflowActivities.FlowchartNumberGuessWorkflow"))
        End Sub
    
        Public Function GetWorkflowDefinition(identity As WorkflowIdentity) As Activity
            Return map(identity)
        End Function
    
        Public Function GetIdentityDescription(identity As WorkflowIdentity) As String
            Return identity.ToString()
        End Function
    End Module
    
    public static class WorkflowVersionMap
    {
        static Dictionary<WorkflowIdentity, Activity> map;
    
        // Current version identities.
        static public WorkflowIdentity StateMachineNumberGuessIdentity;
        static public WorkflowIdentity FlowchartNumberGuessIdentity;
        static public WorkflowIdentity SequentialNumberGuessIdentity;
    
        // v1 identities.
        static public WorkflowIdentity StateMachineNumberGuessIdentity_v1;
        static public WorkflowIdentity FlowchartNumberGuessIdentity_v1;
        static public WorkflowIdentity SequentialNumberGuessIdentity_v1;
    
        static WorkflowVersionMap()
        {
            map = new Dictionary<WorkflowIdentity, Activity>();
    
            // Add the current workflow version identities.
            StateMachineNumberGuessIdentity = new WorkflowIdentity
            {
                Name = "StateMachineNumberGuessWorkflow",
                // Version = new Version(1, 0, 0, 0),
                Version = new Version(2, 0, 0, 0)
            };
    
            FlowchartNumberGuessIdentity = new WorkflowIdentity
            {
                Name = "FlowchartNumberGuessWorkflow",
                // Version = new Version(1, 0, 0, 0),
                Version = new Version(2, 0, 0, 0)
            };
    
            SequentialNumberGuessIdentity = new WorkflowIdentity
            {
                Name = "SequentialNumberGuessWorkflow",
                // Version = new Version(1, 0, 0, 0),
                Version = new Version(2, 0, 0, 0)
            };
    
            map.Add(StateMachineNumberGuessIdentity, new StateMachineNumberGuessWorkflow());
            map.Add(FlowchartNumberGuessIdentity, new FlowchartNumberGuessWorkflow());
            map.Add(SequentialNumberGuessIdentity, new SequentialNumberGuessWorkflow());
    
            // Initialize the previous workflow version identities.
            StateMachineNumberGuessIdentity_v1 = new WorkflowIdentity
            {
                Name = "StateMachineNumberGuessWorkflow",
                Version = new Version(1, 0, 0, 0)
            };
    
            FlowchartNumberGuessIdentity_v1 = new WorkflowIdentity
            {
                Name = "FlowchartNumberGuessWorkflow",
                Version = new Version(1, 0, 0, 0)
            };
    
            SequentialNumberGuessIdentity_v1 = new WorkflowIdentity
            {
                Name = "SequentialNumberGuessWorkflow",
                Version = new Version(1, 0, 0, 0)
            };
    
            // Add the previous version workflow identities to the dictionary along with
            // the corresponding workflow definitions loaded from the v1 assembly.
            // Assembly.LoadFile requires an absolute path so convert this relative path
            // to an absolute path.
            string v1AssemblyPath = @"..\..\..\PreviousVersions\NumberGuessWorkflowActivities_v1.dll";
            v1AssemblyPath = Path.GetFullPath(v1AssemblyPath);
            Assembly v1Assembly = Assembly.LoadFile(v1AssemblyPath);
    
            map.Add(StateMachineNumberGuessIdentity_v1,
                v1Assembly.CreateInstance("NumberGuessWorkflowActivities.StateMachineNumberGuessWorkflow") as Activity);
    
            map.Add(SequentialNumberGuessIdentity_v1,
                v1Assembly.CreateInstance("NumberGuessWorkflowActivities.SequentialNumberGuessWorkflow") as Activity);
    
            map.Add(FlowchartNumberGuessIdentity_v1,
                v1Assembly.CreateInstance("NumberGuessWorkflowActivities.FlowchartNumberGuessWorkflow") as Activity);
        }
    
        public static Activity GetWorkflowDefinition(WorkflowIdentity identity)
        {
            return map[identity];
        }
    
        public static string GetIdentityDescription(WorkflowIdentity identity)
        {
            return identity.ToString();
        }
    }
    

Para compilar y ejecutar la aplicaciónTo build and run the application

  1. Presione CTRL+MAYÚS+B para compilar la aplicación y, a continuación, CTRL+F5 para iniciarla.Press CTRL+SHIFT+B to build the application, and then CTRL+F5 to start.

  2. Para iniciar un nuevo flujo de trabajo, haga clic en nuevo juego.Start a new workflow by clicking New Game. La versión del flujo de trabajo se muestra debajo de la ventana de estado y refleja la versión actualizada del WorkflowIdentity asociado.The version of the workflow is displayed under the status window and reflects the updated version from the associated WorkflowIdentity. Anote el valor de InstanceId para poder ver el archivo de seguimiento del flujo de trabajo cuando se complete y, a continuación, escriba números hasta que se termine el juego.Make a note of the InstanceId so you can view the tracking file for the workflow when it completes, and then enter guesses until the game is complete. Observe cómo el intento del usuario aparece en la información que se muestra en la ventana de estado en función de las actualizaciones de las actividades WriteLine.Note how the user's guess is displayed in the information displayed in the status window based on the updates to the WriteLine activities.

    Please enter a number between 1 and 10
    5 is too high.
    Please enter a number between 1 and 10
    3 is too high.
    Please enter a number between 1 and 10
    1 is too low.
    Please enter a number between 1 and 10
    Congratulations, you guessed the number in 4 turns.
    

    Nota

    Se muestra el texto actualizado de las actividades WriteLine, pero no se muestra el resultado de la actividad final WriteLine que se agregó en este tema.The updated text from the WriteLine activities is displayed, but the output of the final WriteLine activity that was added in this topic is not. Esto se debe a que el controlador PersistableIdle actualiza la ventana de estado.That is because the status window is updated by the PersistableIdle handler. Debido a que el flujo de trabajo se completa y no queda inactivo después de la actividad final, no se llama al controlador PersistableIdle.Because the workflow completes and does not go idle after the final activity, the PersistableIdle handler is not called. Sin embargo, el controlador Completed muestra un mensaje similar en la ventana de estado.However, a similar message is displayed in the status window by the Completed handler. Si se desea, se puede agregar un código al controlador Completed para extraer el texto de StringWriter y mostrarlo en la ventana de estado.If desired, code could be added to the Completed handler to extract the text from the StringWriter and display it to the status window.

  3. Abra el explorador de Windows y navegue hasta la carpeta NumberGuessWorkflowHost\bin\debug (o bin\release según la configuración del proyecto) y abra el archivo de seguimiento con el Bloc de notas correspondiente al flujo de trabajo completado.Open Windows Explorer and navigate to the NumberGuessWorkflowHost\bin\debug folder (or bin\release depending on your project settings) and open the tracking file using Notepad that corresponds to the completed workflow. Si no tome nota de InstanceId, puede identificar el archivo de seguimiento correcto mediante la información de fecha de modificación en el explorador de Windows.If you did not make a note of the InstanceId, you can identify the correct tracking file by using the Date modified information in Windows Explorer.

    Please enter a number between 1 and 10
    5 is too high.
    Please enter a number between 1 and 10
    3 is too high.
    Please enter a number between 1 and 10
    1 is too low.
    Please enter a number between 1 and 10
    2 is correct. You guessed it in 4 turns.
    

    La salida de WriteLine actualizada se encuentra en el archivo de seguimiento, incluida la salida de WriteLine que se agregó en este tema.The updated WriteLine output is contained within the tracking file, including the output of the WriteLine that was added in this topic.

  4. Vuelva a la aplicación para adivinar números y seleccione uno de los flujos de trabajo iniciado antes de que se realizaran las actualizaciones.Switch back to the number guessing application and select one of the workflows that was started before the updates were made. Puede identificar la versión del flujo de trabajo seleccionado actualmente si examina la información de versión que aparece debajo de la ventana de estado.You can identify the version of the currently selected workflow by looking at the version information that is displayed below the status window. Escriba los números y observe que las actualizaciones de estado coinciden con el resultado de la actividad WriteLine de la versión anterior y no incluyen el intento del usuario.Enter some guesses and note that the status updates match the WriteLine activity output from the previous version, and do not include the user's guess. Esto se debe a que estos flujos de trabajo usan la definición de flujo de trabajo anterior que no tiene las actualizaciones WriteLine.That is because these workflows are using the previous workflow definition that does not have the WriteLine updates.

    En el paso siguiente, cómo: Actualizar la definición de una instanciade flujo de trabajo en ejecución, las instancias de flujo de trabajo en ejecución v1 se actualizan para que contengan v2 la nueva funcionalidad como instancias.In the next step, How to: Update the Definition of a Running Workflow Instance, the running v1 workflow instances are updated so they contain the new functionality as the v2 instances.