Example #1
0
 private void TabItem_GotFocus_RefreshXamlBox(object sender, RoutedEventArgs e)
 {
     if (_workflowDesigner.Text != null)
     {
         _workflowDesigner.Flush();
         xamlTextBox.Text = _workflowDesigner.Text;
     }
 }
Example #2
0
 private void menuSave_Click(object sender, RoutedEventArgs e)
 {
     if (String.IsNullOrEmpty(currentXamlPath))
     {
         menuSaveAs_Click(sender, e);
     }
     else
     {
         wd.Flush();
         SaveXamlFile(currentXamlPath, wd.Text);
         isModified = false;
         UpdateTitle();
     }
 }
Example #3
0
        public void OpenWorkflow(int workflowID)
        {
            Workflow = SystemService.GetDynObjectByID("Workflow", workflowID);
            if (Workflow != null)
            {
                _designer   = new WorkflowDesigner();
                _undoEngine = _designer.Context.Services.GetService <UndoEngine>();
                _undoEngine.UndoUnitAdded += delegate(object ss, UndoUnitEventArgs ee)
                {
                    _designer.Flush();
                    CanUndo = true;
                };

                DesignerView    = _designer.View;
                PropertyContent = _designer.PropertyInspectorView;
                _designer.Text  = Workflow["Definition"].ToString();
                _designer.Load();
                WorkflowName = Workflow["WorkflowName"].ToString();
                EditState    = "modify";
                CanUndo      = false;
                CanRedo      = false;
                DeleteCommand.RaiseCanExecuteChanged();
            }
            else
            {
                MessageBox.Show("所选的工作流在数据库中不存在,请检查!");
            }
        }
Example #4
0
        private void btnRun_Click(object sender, RoutedEventArgs e)
        {
            AutoResetEvent syncEvent = new AutoResetEvent(false);

            var writer = new StringWriter();

            // Run workflow
            wd.Flush();

            Activity dataWorkflow = ActivityXamlServices.Load(new StringReader(wd.Text));

            // Create the WorkflowApplication using the desired
            // workflow definition.
            WorkflowApplication wfApp = new WorkflowApplication(dataWorkflow);

            // Handle the desired lifecycle events.
            wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs eventarg)
            {
                MessageBox.Show($"Task Finished!\n---- Output ----\n{ writer.ToString() }");
                syncEvent.Set();
            };

            wfApp.Extensions.Add(writer);

            // Start the workflow.
            wfApp.Run();

            // Wait for Completed to arrive and signal that
            // the workflow is complete.
            syncEvent.WaitOne();
        }
Example #5
0
        public WorkflowDesignerViewModel()
        {
            (new DesignerMetadata()).Register();
            _workflowToolboxControl = new ToolboxControl()
            {
                Categories = WorkflowToolbox.LoadToolbox()
            };

            _designer   = new WorkflowDesigner();
            _undoEngine = _designer.Context.Services.GetService <UndoEngine>();
            _undoEngine.UndoUnitAdded += delegate(object ss, UndoUnitEventArgs ee)
            {
                _designer.Flush();
                CanUndo = true;
            };
            DesignerView    = _designer.View;
            PropertyContent = _designer.PropertyInspectorView;
            _designer.Text  = "<Activity mc:Ignorable=\"sap\" x:Class=\"WorkflowInvokerSample.流程图\" xmlns=\"http://schemas.microsoft.com/netfx/2009/xaml/activities\" xmlns:av=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" xmlns:mv=\"clr-namespace:Microsoft.VisualBasic;assembly=System\" xmlns:mva=\"clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities\" xmlns:s=\"clr-namespace:System;assembly=mscorlib\" xmlns:s1=\"clr-namespace:System;assembly=System\" xmlns:s2=\"clr-namespace:System;assembly=System.Xml\" xmlns:s3=\"clr-namespace:System;assembly=System.Core\" xmlns:s4=\"clr-namespace:System;assembly=System.ServiceModel\" xmlns:sad=\"clr-namespace:System.Activities.Debugger;assembly=System.Activities\" xmlns:sap=\"http://schemas.microsoft.com/netfx/2009/xaml/activities/presentation\" xmlns:scg=\"clr-namespace:System.Collections.Generic;assembly=mscorlib\" xmlns:scg1=\"clr-namespace:System.Collections.Generic;assembly=System\" xmlns:scg2=\"clr-namespace:System.Collections.Generic;assembly=System.ServiceModel\" xmlns:scg3=\"clr-namespace:System.Collections.Generic;assembly=System.Core\" xmlns:sd=\"clr-namespace:System.Data;assembly=System.Data\" xmlns:sl=\"clr-namespace:System.Linq;assembly=System.Core\" xmlns:st=\"clr-namespace:System.Text;assembly=mscorlib\" xmlns:w=\"clr-namespace:WorkflowInvokerSample\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">\r\n  <x:Members>\r\n    <x:Property Name=\"WorkflowInstanceID\" Type=\"InArgument(x:Int32)\" />\r\n    <x:Property Name=\"ExchangeParams\" Type=\"InOutArgument(scg:Dictionary(x:String, x:Object))\" />\r\n    <x:Property Name=\"FirstActor\" Type=\"InArgument(x:String)\" />\r\n    <x:Property Name=\"LastActor\" Type=\"InOutArgument(x:String)\" />\r\n  </x:Members>\r\n  <sap:VirtualizedContainerService.HintSize>654,676</sap:VirtualizedContainerService.HintSize>\r\n  <mva:VisualBasic.Settings>Assembly references and imported namespaces for internal implementation</mva:VisualBasic.Settings>\r\n  <Flowchart DisplayName=\"流程图\" sad:XamlDebuggerXmlReader.FileName=\"C:\\Users\\Administrator\\Downloads\\WorkflowInvokerSample\\WorkflowInvokerSample\\流程图.xaml\" sap:VirtualizedContainerService.HintSize=\"614,636\">\r\n    <sap:WorkflowViewStateService.ViewState>\r\n      <scg:Dictionary x:TypeArguments=\"x:String, x:Object\">\r\n        <x:Boolean x:Key=\"IsExpanded\">False</x:Boolean>\r\n        <av:Point x:Key=\"ShapeLocation\">270,2.5</av:Point>\r\n        <av:Size x:Key=\"ShapeSize\">60,75</av:Size>\r\n        <av:PointCollection x:Key=\"ConnectorLocation\">300,77.5 300,107.5 300,189</av:PointCollection>\r\n      </scg:Dictionary>\r\n    </sap:WorkflowViewStateService.ViewState>\r\n    <Flowchart.StartNode>\r\n      <x:Null />\r\n    </Flowchart.StartNode>\r\n  </Flowchart>\r\n</Activity>";
            _designer.Load();
            WorkflowName = "新建工作流";
            CanUndo      = false;
            CanRedo      = false;
            EditState    = "add";

            OpenCommand   = new DelegateCommand <object>(OpenWorkflowListWindow);
            AddCommand    = new DelegateCommand <object>(Add);
            DeleteCommand = new DelegateCommand <object>(Delete, CanDeleteWorkflowExecute);
            SaveCommand   = new DelegateCommand <object>(Save);
            UndoCommand   = new DelegateCommand <object>(Undo);
            RedoCommand   = new DelegateCommand <object>(Redo);
            DebugCommand  = new DelegateCommand <object>(Debug);
        }
        private void WorkflowDesigner_ModelChanged(object sender, EventArgs e)
        {
            WorkflowDesigner designer = sender as WorkflowDesigner;

            if (designer != null)
            {
                designer.Flush();
                _ruleConfigContext.EditingRule.Text = designer.Text;
            }
        }
Example #7
0
        private Activity GetActivity()
        {
            //get workflow source from designer
            _wfDesigner.Flush();
            var workflowStream = new MemoryStream(Encoding.UTF8.GetBytes(_wfDesigner.Text));

            var settings = new ActivityXamlServicesSettings()
            {
                CompileExpressions = true
            };

            return(ActivityXamlServices.Load(workflowStream, settings));
        }
Example #8
0
        private Activity GetRuntimeActivity()
        {
            _workflowDesigner.Flush();
            var stringReader = new StringReader(_workflowDesigner.Text);
            var root         = ActivityXamlServices.Load(stringReader);

            WorkflowInspectionServices.CacheMetadata(root);
            var list = WorkflowInspectionServices.GetActivities(root).GetEnumerator();

            list.MoveNext();
            var runtimeActivity = list.Current;

            return(runtimeActivity);
        }
Example #9
0
        //加载流程
        void loadWorkflowFromFile(string workflowFilePathName)
        {
            desienerPanel.Content = null;
            // propertyPanel.Content = null;


            designer = new WorkflowDesigner();


            try
            {
                designer.Load(workflowFilePathName);

                modelService = designer.Context.Services.GetService <ModelService>();

                rootModelItem = modelService.Root;

                undoEngine = designer.Context.Services.GetService <UndoEngine>();

                undoEngine.UndoUnitAdded += delegate(object ss, UndoUnitEventArgs ee)
                {
                    designer.Flush();                            //调用Flush使designer.Text得到数据
                    desigeerActionList.Items.Add(string.Format("{0}  ,   {1}", DateTime.Now.ToString(), ee.UndoUnit.Description));
                };

                designerView = designer.Context.Services.GetService <DesignerView>();



                designerView.WorkflowShellBarItemVisibility = ShellBarItemVisibility.Arguments    //如果不使用Activity做根,无法出现参数选项
                                                              | ShellBarItemVisibility.Imports
                                                              | ShellBarItemVisibility.MiniMap
                                                              | ShellBarItemVisibility.Variables
                                                              | ShellBarItemVisibility.Zoom
                ;

                desienerPanel.Content = designer.View;

                //propertyPanel.Content = designer.PropertyInspectorView;

                propertyGrid.setWfDesigner(designer);

                //this.xamlTextBox.Text = designer.Text;
            }
            catch (SystemException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }  //end
        private void Execute(Boolean slow)
        {
            // Valider l'activité créé dynamiquement
            Activity        activity = XamlHelper.GetActivity(Text);
            DynamicActivity d        = (DynamicActivity)activity;

            if (d.Implementation == null)
            {
                return;
            }

            if (_type == WorkflowType.Activiy)
            {
                // Pour avoir un tracking visual, il faut un mapping.
                // Le mapping n'est possible que si le designer est chargé à partir d'un fichier.
                // Afin de palier à ce problème, on enregistre le fichier dans un répertoire temporaire et on recharge
                String path = Path.GetTempFileName();
                _designer.Flush();
                _designer.Save(path);
                ResetDesigner();
                _designer.Load(path);

                _host = new WorkflowApplication(activity);

                Tracking = new VisualTracking(_designer, slow);

                // Ajout des extension
                _host.Extensions.Add(_visualTracking);
                _host.Extensions.Add(_output);

                _host.Completed = (e) =>
                {
                    //This is to remove the final debug adornment
                    Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Render, new Action(ClearDebug));
                    _host = null;
                    _stopCommand.RaiseCanExecuteChanged();
                };

                // Invoquer le workdflow
                _host.Run();
                _stopCommand.RaiseCanExecuteChanged();
            }
            else
            {
                throw new NotImplementedException("L'hébergement de service n'est pas supporté actuellement!");
            }
        }
Example #11
0
        public void ExecuteNew(object parameter)
        {
            WorkflowDesignerObj = new WorkflowDesigner();

            WorkflowDesignerObj.ModelChanged += new EventHandler(workflowDesigner_ModelChanged);

            if (File.Exists(TemplateXaml))
            {
                WorkflowDesignerObj.Load(TemplateXaml);
            }
            else
            {
                WorkflowDesignerObj.Load(new Sequence());
            }

            WorkflowDesignerObj.Flush();
        }
Example #12
0
        private void WorkflowSourceChanged(TreeViewItem treeViewItem)
        {
            _workflowDesigner.Flush();
            var content = _workflowDesigner.Text;

            DebugInfo.Text = content;

            var xElement = treeViewItem.DataContext as XElement;

            if (xElement == null)
            {
                MessageBox.Show("Related treeview item does not contain xml format data.");
                return;
            }
            var activity = Utilities.GetActivityFromContentString(content);

            if (activity == null)
            {
                MessageBox.Show("We receive invalid data[" + content + "]");
                return;
            }
            var name        = activity.GetType().GetProperty(Constants.NAME).GetValue(activity, null) as string;
            var description = activity.GetType().GetProperty("Description").GetValue(activity, null) as string;

            activity.GetType().GetProperty("Authors").SetValue(activity, _currentWindowsUser);
            if (!string.IsNullOrEmpty(name))
            {
                xElement.SetAttributeValue(Constants.NAME, name);
            }
            if (!string.IsNullOrEmpty(description))
            {
                xElement.SetAttributeValue("Description", description);
            }

            xElement.SetAttributeValue(Constants.CONTENT, content);

            var sRoot = DBFactory.GetData().Save(xElement);

            if (!sRoot)
            {
                MessageBox.Show("update Tree item Failed. ");
                return;
            }
            Dispatcher.BeginInvoke(new Action(() => UpdateRelatedTreeViewItem(treeViewItem, xElement)));
        }
        public void Run()
        {
            if (IsExecuting)
            {
                return;
            }

            WorkflowDesigner.Flush();

            if (WorkflowType == WorkflowType.Activity)
            {
                executer = new ActivityRunner(WorkflowDesigner.Text, outputTextWriter);
            }
            else
            {
                executer = new WorkflowServiceRunner(WorkflowDesigner.Text, outputTextWriter);
            }

            executer.ExecutingStateChanged += OnExecuterRunningStateChanged;
            executer.Start();
        }
        private void AddDesigner()
        {
            ScrollViewer designerScrollViewer = new ScrollViewer {
                HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled
            };

            this.wd = new WorkflowDesigner();

            Grid.SetRow(designerScrollViewer, 0);
            Grid.SetColumn(designerScrollViewer, 0);

            LoadWorkflow();
            if (workflow != null)
            {
                this.wd.Load(workflow);
                wd.Flush();
                designerScrollViewer.Content = wd.View;
                wd.View.IsEnabled            = false;
                designerScrollViewer.ScrollToTop();
                MainLayout.Children.Add(designerScrollViewer);
            }
        }
Example #15
0
        //run
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            textBox.Text = "Workflow Start\r\n";
            try
            {
                wd.Flush();
                // create stream with textbox contents
                StringBuilder data   = new StringBuilder();
                Stream        stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(wd.Text));

                // invoke workflow
                Activity wf = ActivityXamlServices.Load(stream);
                IDictionary <string, object> results = WorkflowInvoker.Invoke(wf);

                //textBox.Text = wd.Text;
                // show results
                //textBox.Text = "Workflow Executed";
                //textBox.Text += "\r\nReturned data:";
                if (results.Count > 0)
                {
                    foreach (string key in results.Keys)
                    {
                        textBox.Text += string.Format("{0} : {1}\r\n", key, results[key]);
                    }
                }
                else
                {
                    //textBox.Text += "<no data returned>\r\n";
                }
            }
            catch (Exception ex)
            {
                textBox.Text += string.Format("Error executing the Xaml. Exception type: {0}\r\nDetails:\r\n--------\r\n{1}\r\n", ex.GetType().FullName, ex.ToString());
            }
            textBox.Text += "Workflow End\r\n";
        }
Example #16
0
 public void Start()
 {
     WorkflowDesigner.Flush();
     StartInternal();
 }
        //Run the Workflow with the tracking participant
        public void RunWorkflow()
        {
            WorkflowDesigner.Save(WorkflowFilePath);
            WorkflowDesigner.Flush();

            AddWorkflowDesigner();

            WorkflowInvoker instance = new WorkflowInvoker(GetRuntimeExecutionRoot());

            resumeRuntimeFromHost = new AutoResetEvent(false);

            Dictionary <string, Activity> activityIdToWfElementMap = BuildActivityIdToWfElementMap(wfElementToSourceLocationMap);

            #region Set up the Custom Tracking
            const String all = "*";
            SimulatorTrackingParticipant simTracker = new SimulatorTrackingParticipant()
            {
                TrackingProfile = new TrackingProfile()
                {
                    Name    = "CustomTrackingProfile",
                    Queries =
                    {
                        new CustomTrackingQuery()
                        {
                            Name         = all,
                            ActivityName = all
                        },
                        new WorkflowInstanceQuery()
                        {
                            // Limit workflow instance tracking records for started and completed workflow states
                            States ={ WorkflowInstanceStates.Started,              WorkflowInstanceStates.Completed, WorkflowInstanceStates.Idle },
                        },
                        new ActivityStateQuery()
                        {
                            // Subscribe for track records from all activities for all states
                            ActivityName = all,
                            States       = { all },

                            // Extract workflow variables and arguments as a part of the activity tracking record
                            // VariableName = "*" allows for extraction of all variables in the scope
                            // of the activity
                            Variables =
                            {
                                { all }
                            }
                        }
                    }
                }
            };

            simTracker.ActivityIdToWorkflowElementMap = activityIdToWfElementMap;

            #endregion

            //As the tracking events are received
            simTracker.TrackingRecordReceived += (trackingParticpant, trackingEventArgs) =>
            {
                if (trackingEventArgs.Activity != null)
                {
                    System.Diagnostics.Debug.WriteLine(
                        String.Format("<+=+=+=+> Activity Tracking Record Received for ActivityId: {0}, record: {1} ",
                                      trackingEventArgs.Activity.Id,
                                      trackingEventArgs.Record
                                      )
                        );

                    ShowDebug(wfElementToSourceLocationMap[trackingEventArgs.Activity]);

                    this.Dispatcher.Invoke(DispatcherPriority.SystemIdle, (Action)(() =>
                    {
                        //Textbox Updates
                        tx.AppendText(trackingEventArgs.Activity.Id + " " + trackingEventArgs.Activity.DisplayName + " " + ((ActivityStateRecord)trackingEventArgs.Record).State + "\n");
                        tx.AppendText("Instance ID: " + ((ActivityStateRecord)trackingEventArgs.Record).InstanceId + "\n");
                        tx.AppendText("Activity: " + ((ActivityStateRecord)trackingEventArgs.Record).Activity.Name + "\n");
                        tx.AppendText("Level: " + ((ActivityStateRecord)trackingEventArgs.Record).Level + "\n");
                        tx.AppendText("Time: " + ((ActivityStateRecord)trackingEventArgs.Record).EventTime + "\n");
                        tx.AppendText("******************\n");
                        //  textLineToSourceLocationMap.Add(i, wfElementToSourceLocationMap[trackingEventArgs.Activity]);
                        //  i = i + 2;

                        //Add a sleep so that the debug adornments are visible to the user
                        System.Threading.Thread.Sleep(500);
                    }));
                }
            };

            instance.Extensions.Add(simTracker);
            ThreadPool.QueueUserWorkItem(new WaitCallback((context) =>
            {
                //Start the Runtime
                instance.Invoke();// new TimeSpan(1,0,0));

                //This is to remove the final debug adornment
                this.Dispatcher.Invoke(DispatcherPriority.Render
                                       , (Action)(() =>
                {
                    this.WorkflowDesigner.DebugManagerView.CurrentLocation = new SourceLocation(WorkflowFilePath, 1, 1, 1, 10);
                }));
            }));
        }
 public VisualMapping(WorkflowDesigner designer)
 {
     _designer = designer;
     _designer.Flush();
 }
Example #19
0
 private bool IsDirty()
 {
     wd.Flush();
     return(lastSavedXaml != wd.Text || mustSave);
 }
Example #20
0
        private void LoadDesignerAndWorkflow(string fileName = null)
        {
            isLoadingXaml = true;
            Encrypt       = false;
            mustSave      = false;

            if (wd != null)
            {
                MainLayout.Children.Remove(this.wd.View);
                MainLayout.Children.Remove(this.wd.PropertyInspectorView);
                this.wd.ModelChanged -= wd_ModelChanged;
                this.wd = null;
            }
            //Create an instance of WorkflowDesigner class.
            this.wd = new WorkflowDesigner();

            DesignerConfigurationService configService = this.wd.Context.Services.GetService <DesignerConfigurationService>();

            configService.TargetFrameworkName = new FrameworkName(".NETFramework", new Version(4, 5));
            configService.LoadingFromUntrustedSourceEnabled = true;

            this.wd.ModelChanged += new EventHandler(wd_ModelChanged);

            //Place the designer canvas in the middle column of the grid.
            Grid.SetRow(this.wd.View, 1);
            Grid.SetColumn(this.wd.View, 2);

            AddPropertyInspector();

            if (string.IsNullOrEmpty(fileName))
            {
                this.wd.Load(new Sequence());
                wd.Flush();
                lastSavedXaml = wd.Text;
                mustSave      = true;
            }
            else
            {
                password = null;
                string errorMessage = null;
                if (XamlFileProviderFactory.IsXamlFileEncrypted(fileName))
                {
                    if (!GetPassword())
                    {
                        errorMessage = string.Format("The file '{0}' is protected and requires the correct password to open.", xamlFile);
                    }
                    else
                    {
                        Encrypt = true;
                    }
                }

                if (string.IsNullOrEmpty(errorMessage))
                {
                    try
                    {
                        IXamlFileProvider provider = XamlFileProviderFactory.GetXamlFileProvider(fileName, password);
                        provider.LoadXamlFile(fileName, password);
                        this.wd.Load(provider.XamlDocument);
                        wd.Flush();
                        lastSavedXaml = wd.Text;
                    }
                    catch (Exception ex)
                    {
                        errorMessage = ex.Message;
                        if (errorMessage == "The encrypted string was not in a valid format.")
                        {
                            errorMessage = "The password you specified was incorrect.";
                        }
                        errorMessage = string.Format("The following error occurred while trying to open '{0}' : \n\n{1}", xamlFile, errorMessage);
                    }
                }
                if (!string.IsNullOrEmpty(errorMessage))
                {
                    xamlFile = string.Empty;
                    ShowErrorMessage(errorMessage, "Failed to load file");
                    this.wd.Load(new Sequence());
                    password = null;
                    mustSave = true;
                    Encrypt  = false;
                }
            }

            busyGettingPassword = true;
            Protect.GetBindingExpression(System.Windows.Controls.Primitives.ToggleButton.IsCheckedProperty).UpdateTarget();
            busyGettingPassword = false;

            //Add the designer canvas to the grid.
            MainLayout.Children.Add(this.wd.View);

            StatusBarText.Text = "";
            ToggleDocumentHasChangesVisual(mustSave);

            isLoadingXaml = false;
        }