Example #1
0
        private void GenerateXAMLVisualTree(string xaml)
        {
            using (MemoryStream ms = new MemoryStream(xaml.Length))
            {
                using (StreamWriter sw = new StreamWriter(ms))
                {
                    try
                    {
                        sw.Write(xaml);
                        sw.Flush();

                        ms.Seek(0, SeekOrigin.Begin);

                        // Load the Xaml
                        object content = ActivityXamlServices.Load(ms);
                    }
                    catch (XamlParseException x)
                    {
                        Debug.WriteLine("XAML Parse error: Line:{0}, Position:{1}, Error: {2}", new object[] { x.LineNumber, x.LinePosition, x.Message });
                        this.statusInfo.Content = x.Message;
                        this._validXaml         = false;
                    }
                    catch (Exception ex)
                    {
                        // Generic message
                        this.statusInfo.Content = ex.Message;
                        this._validXaml         = false;
                    }
                }
            }
        }
Example #2
0
        public bool Initialize(string workflowCode)
        {
            if (string.IsNullOrEmpty(workflowCode))
            {
                return(false);
            }
            //throw new OperationException("WorkflowCode is null.");

            string workflowXaml;

            using (var mgr = (IXamlManager <BPWorkflow>)IoC.Instance.Resolve <IBaseManager <BPWorkflow> >())
            {
                var wf = mgr.Get(workflowCode);
                if (wf == null)
                {
                    //throw new OperationException("Workflow с кодом '{0}' не существует!", workflowCode);
                    return(false);
                }
                workflowXaml = mgr.GetXaml(workflowCode);
            }

            if (string.IsNullOrEmpty(workflowXaml))
            {
                //throw new DeveloperException("Получили пустой workflow.");
                return(false);
            }

            using (var reader = new StringReader(workflowXaml))
                _activity = (DynamicActivity)ActivityXamlServices.Load(reader);
            return(true);
        }
Example #3
0
        private static ActivityBuilder StartUpdate(string name)
        {
            // Create the XamlXmlReaderSettings.
            XamlXmlReaderSettings readerSettings = new XamlXmlReaderSettings()
            {
                // In the XAML the "local" namespace referes to artifacts that come from
                // the same project as the XAML. When loading XAML if the currently executing
                // assembly is not the same assembly that was referred to as "local" in the XAML
                // LocalAssembly must be set to the assembly containing the artifacts.
                // Assembly.LoadFile requires an absolute path so convert this relative path
                // to an absolute path.
                LocalAssembly = Assembly.LoadFile(
                    Path.GetFullPath(Path.Combine(mapPath, "NumberGuessWorkflowActivities_v1.dll")))
            };

            string        path       = Path.Combine(definitionPath, name);
            XamlXmlReader xamlReader = new XamlXmlReader(path, readerSettings);

            // Load the workflow definition into an ActivityBuilder.
            ActivityBuilder wf = XamlServices.Load(
                ActivityXamlServices.CreateBuilderReader(xamlReader))
                                 as ActivityBuilder;

            // PrepareForUpdate makes a copy of the workflow definition in the
            // ActivityBuilder that is used for comparison when the update
            // map is created.
            DynamicUpdateServices.PrepareForUpdate(wf);

            return(wf);
        }
Example #4
0
        static void LoadFileByFile()
        {
            ActivityXamlServicesSettings settings = new ActivityXamlServicesSettings
            {
                CompileExpressions = true
            };

            //String stFilePath = Directory.GetCurrentDirectory();
            var stFilePath = "C:\\Work\\Projects\\TestCoreWF\\WorkflowConsoleApplication1\\Workflow1.xaml";

            string       xamlString = System.IO.File.ReadAllText(stFilePath);
            StringReader stReader   = new StringReader(xamlString);

            var ActivityFromFile = ActivityXamlServices.Load(new StringReader(xamlString), settings);
            Dictionary <string, object> inputs = new Dictionary <string, object>();

            inputs.Add("x", 50);
            inputs.Add("Path", "C:\\Work\\BUGS\\INC000000286049_Wrong_Portfolio_Position\\");

            var Ret = System.Activities.WorkflowInvoker.Invoke(ActivityFromFile, inputs);

            System.Console.WriteLine(Ret["Out"]);
            //System.Console.ReadLine();
            Console.ReadLine();
        }
Example #5
0
        static void Main(string[] args)
        {            
            List<int> numbers = GetInputFromUser(args);

            if (numbers != null)
            {
                Console.WriteLine("Input values:");
                foreach (int i in numbers)
                {
                    Console.WriteLine("\tValue = " + i);
                }
                Console.WriteLine();

                IDictionary<string, object> results;

                // Create the dynamic activity in two different ways and run it.
                // Using code.
                Activity act1 = CreateAverageCalculationWorkflow();
                results = WorkflowInvoker.Invoke(act1, new Dictionary<string, object> { { "Numbers", numbers } });
                Console.WriteLine("The average calculated using the code activity is = " + results["Average"]);

                // Using XAML.  The XAML may be created via the graphical designer.
                // If included in a visual studio project, its Build Action should be set to None.
                Activity act2 = ActivityXamlServices.Load(@"FindAverage.xaml");
                results = WorkflowInvoker.Invoke(act2, new Dictionary<string, object> { { "Numbers", numbers } });
                Console.WriteLine("The average calculated using the XAML activity is = " + results["Average"]);
            }

            Console.WriteLine();
            Console.WriteLine("Press Enter to exit...");
            Console.ReadLine();   
        }
        /// <summary>
        /// Creates a new Workflow Application instance and executes the Current Workflow
        /// </summary>
        private void CmdWorkflowRun(object sender, ExecutedRoutedEventArgs e)
        {
            //get workflow source from designer
            CustomWfDesigner.Instance.Flush();
            MemoryStream workflowStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(CustomWfDesigner.Instance.Text));

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

            DynamicActivity activityExecute = ActivityXamlServices.Load(workflowStream, settings) as DynamicActivity;

            //configure workflow application
            consoleExecutionLog.Text = String.Empty;
            consoleOutput.Text       = String.Empty;
            _executionLog            = new CustomTrackingParticipant();
            _wfApp = new WorkflowApplication(activityExecute);
            _wfApp.Extensions.Add(_executionLog);
            _wfApp.Completed = WfExecutionCompleted;

            //execute
            _wfApp.Run();

            //enable timer for real-time logging
            _timer.Start();
        }
Example #7
0
        /// <summary>
        /// 2-phase initialization to parse parameters
        /// </summary>
        /// <returns></returns>
        public bool Initialize()
        {
            XamlXmlReader reader = new XamlXmlReader(_filename, new XamlXmlReaderSettings {
                LocalAssembly = typeof(MainViewModel).Assembly
            });

            _workflow = ActivityXamlServices.Load(reader);

            var argumentViewModel = new ArgumentCollectorViewModel(_workflow as DynamicActivity);

            if (argumentViewModel.HasArguments)
            {
                IUIVisualizer uiVisualizer = Resolve <IUIVisualizer>();
                if (uiVisualizer.ShowDialog("WorkflowArgumentsView", argumentViewModel) == false)
                {
                    return(false);
                }
            }

            _inputs = argumentViewModel.CollectArguments();

            //_inputs.Add("img",typeof(Image<Bgr,Byte>));
            //_inputs.Add("gimg", typeof(Image<Gray, Byte>));

            return(true);
        }
Example #8
0
        protected override void LoadAndExecute()
        {
            MemoryStream    ms            = new MemoryStream(ASCIIEncoding.Default.GetBytes(this.workflowDesigner.Text));
            DynamicActivity workflowToRun = ActivityXamlServices.Load(ms) as DynamicActivity;

            WorkflowInspectionServices.CacheMetadata(workflowToRun);

            this.workflowApplication = new WorkflowApplication(workflowToRun);

            this.workflowApplication.Extensions.Add(this.output);

            this.workflowApplication.Completed            = this.WorkflowCompleted;
            this.workflowApplication.OnUnhandledException = this.WorkflowUnhandledException;
            this.workflowApplication.Aborted = this.WorkflowAborted;

            this.workflowApplication.Extensions.Add(this.InitialiseVisualTrackingParticipant(workflowToRun));

            try
            {
                this.running = true;
                this.workflowApplication.Run();
            }
            catch (Exception e)
            {
                this.output.WriteLine(ExceptionHelper.FormatStackTrace(e));
                StatusViewModel.SetStatusText(Resources.ExceptionInDebugStatus, this.workflowName);
            }
        }
Example #9
0
        static void Main(string[] args)
        {
            if (2 != args.Length)
            {
                Console.WriteLine("Usage -- ViewStateCleaningWriter <infile> <outfile>");
                return;
            }
            try
            {
                XmlReader       xmlReader  = XmlReader.Create(args[0]);
                XamlXmlReader   xamlReader = new XamlXmlReader(xmlReader);
                ActivityBuilder ab         = XamlServices.Load(ActivityXamlServices.CreateBuilderReader(xamlReader)) as ActivityBuilder;

                XmlWriterSettings writerSettings = new XmlWriterSettings {
                    Indent = true
                };
                XmlWriter     xmlWriter  = XmlWriter.Create(File.OpenWrite(args[1]), writerSettings);
                XamlXmlWriter xamlWriter = new XamlXmlWriter(xmlWriter, new XamlSchemaContext());
                XamlServices.Save(new ViewStateCleaningWriter(ActivityXamlServices.CreateBuilderWriter(xamlWriter)), ab);

                Console.WriteLine("{0} written without viewstate information", args[1]);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception encountered {0}", ex);
            }
        }
Example #10
0
        private void CommandRun_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
        {
            InOutTextBlock.Text = string.Empty;

            // In order for the current Workflow to be started without a glitch, you need to save it to a file,
            // upload the file to another Workflow and start it already
            if (String.IsNullOrEmpty(_runningWorkflowTemporaryFileName))
            {
                var currentPath = Directory.GetCurrentDirectory();
                _runningWorkflowTemporaryFileName = System.IO.Path.Combine(currentPath, "RunningWorkflow.xaml");
            }
            _wd.Save(_runningWorkflowTemporaryFileName);
            var runningWorkflow = ActivityXamlServices.Load(_runningWorkflowTemporaryFileName);

            using (var textWriter = new StringWriter())
            {
                Console.SetOut(textWriter);

                var wi = new WorkflowInvoker(runningWorkflow);
                wi.Invoke();

                var textOutput = textWriter.ToString();
                if (!string.IsNullOrEmpty(textOutput))
                {
                    MessageBox.Show(textOutput, "Output of the program:");
                }
            }
        }
Example #11
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 #12
0
        void InvokeOnClient(ObjectChangedEventArgs objectChangedEventArgs, ObjectChangedWorkflow objectChangedWorkflow, object targetObjectKey)
        {
            Activity activity   = ActivityXamlServices.Load(new StringReader(objectChangedWorkflow.Xaml));
            var      dictionary = ObjectChangedStartWorkflowService.Dictionary(targetObjectKey, objectChangedEventArgs.PropertyName, objectChangedEventArgs.OldValue);

            WorkflowInvoker.Invoke(activity, dictionary);
        }
Example #13
0
        internal static Activity GetActivityFromXamlResource(TestXamls xamlName)
        {
            var asm        = typeof(TestHelper).Assembly;
            var xamlStream = asm.GetManifestResourceStream($"{asm.GetName().Name}.TestXamls.{xamlName}.xaml");

            return(ActivityXamlServices.Load(xamlStream));
        }
Example #14
0
        public static Activity Load(string path, string fallbackPath)
        {
            string activityDefinition = null;

            if (!cache.ContainsKey(path))
            {
                string definitionPath = File.Exists(path) ? path : fallbackPath;

                if (!File.Exists(definitionPath))
                {
                    throw new FileNotFoundException(String.Format("Could not load activity definition from either {0} or {1}.", path, fallbackPath));
                }

                using (StreamReader sr = new StreamReader(definitionPath))
                {
                    activityDefinition = sr.ReadToEnd();
                }

                cache[path] = activityDefinition;
            }

            Stream   stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(activityDefinition));
            Activity wf     = ActivityXamlServices.Load(stream, new ActivityXamlServicesSettings {
                CompileExpressions = true
            });

            return(wf);
        }
Example #15
0
        private static void RunFromXaml()
        {
            Console.WriteLine("Host: About to run workflow - Thread:{0}",
                              System.Threading.Thread.CurrentThread.ManagedThreadId);

            try
            {
                String fullFilePath =
                    @"..\..\..\ActivityLibrary\HostingDemoWorkflow.xaml";
                Activity activity = ActivityXamlServices.Load(fullFilePath);
                //activity is a DynamicActivity
                if (activity == null)
                {
                    throw new NullReferenceException(String.Format(
                                                         "Unable to deserialize {0}", fullFilePath));
                }

                IDictionary <String, Object> output = WorkflowInvoker.Invoke(
                    activity, new Dictionary <String, Object>
                {
                    { "ArgNumberToEcho", 1001 },
                });

                Console.WriteLine("Host: Workflow completed - Thread:{0} - {1}",
                                  System.Threading.Thread.CurrentThread.ManagedThreadId,
                                  output["Result"]);
            }
            catch (Exception exception)
            {
                Console.WriteLine("Host: Workflow exception:{0}:{1}",
                                  exception.GetType(), exception.Message);
            }
        }
        public void Run()
        {
            this.workflowDesigner.Flush();
            MemoryStream ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(this.workflowDesigner.Text));

            DynamicActivity activityToRun = ActivityXamlServices.Load(ms) as DynamicActivity;

            this.workflowApplication = new WorkflowApplication(activityToRun);

            this.workflowApplication.Extensions.Add(this.output);
            this.workflowApplication.Completed            = this.WorkflowCompleted;
            this.workflowApplication.Aborted              = this.WorkflowAborted;
            this.workflowApplication.OnUnhandledException = this.WorkflowUnhandledException;
            StatusViewModel.SetStatusText(Resources.RunningStatus, this.workflowName);

            try
            {
                this.running = true;
                this.workflowApplication.Run();
            }
            catch (Exception e)
            {
                this.output.WriteLine(ExceptionHelper.FormatStackTrace(e));
                StatusViewModel.SetStatusText(Resources.ExceptionStatus, this.workflowName);
                this.running = false;
            }
        }
Example #17
0
        //从[ActivityBuilder]移除[ViewState]
        public static string removeViewState(ActivityBuilder activityBuilder)
        {
            string xamlString = "";

            XmlWriterSettings writerSettings = new XmlWriterSettings {
                Indent = true
            };

            StringBuilder stringBuilder = new StringBuilder();


            XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, writerSettings);

            XamlXmlWriter xamlXmlWriter = new XamlXmlWriter(xmlWriter, new XamlSchemaContext());

            XamlWriter xamlWriter = ActivityXamlServices.CreateBuilderWriter(xamlXmlWriter);

            viewStateXamlWriter wfViewStateControl = new viewStateXamlWriter(xamlWriter);

            XamlServices.Save(wfViewStateControl, activityBuilder);

            xamlString = stringBuilder.ToString();

            return(xamlString);
        }
Example #18
0
        private ActivityBuilder ReadXamlDefinition()
        {
            var xamlStr = RootActivity.ToString();

            try
            {
                if (xamlStr.Length != 0)
                {
                    using (var sw = new StringReader(xamlStr))
                    {
                        var xamlXmlWriterSettings = new XamlXmlReaderSettings
                        {
                            LocalAssembly = System.Reflection.Assembly.GetAssembly(typeof(VirtualizedContainerService))
                        };
                        var xw   = ActivityXamlServices.CreateBuilderReader(new XamlXmlReader(sw, new XamlSchemaContext(), xamlXmlWriterSettings));
                        var load = XamlServices.Load(xw);
                        return(load as ActivityBuilder);
                    }
                }
            }
            catch (Exception e)
            {
                Dev2Logger.Error("Error loading XAML: ", e, GlobalConstants.WarewolfError);
            }
            return(null);
        }
Example #19
0
        public StringBuilder GetXamlDefinition(ActivityBuilder builder)
        {
            var text = new StringBuilder();

            try
            {
                if (builder != null)
                {
                    var sb = new StringBuilder();
                    using (var sw = new StringWriter(sb))
                    {
                        var xamlXmlWriterSettings = new XamlXmlWriterSettings {
                            AssumeValidInput = true
                        };
                        var xamlSchemaContext = new XamlSchemaContext();
                        var xw = ActivityXamlServices.CreateBuilderWriter(new XamlXmlWriter(sw, xamlSchemaContext, xamlXmlWriterSettings));
                        XamlServices.Save(xw, builder);
                        text = sb.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "");
                    }
                }
                text = SanitizeXaml(text);
            }
            catch (Exception e)
            {
                Dev2Logger.Error("Error loading XAML: ", e, GlobalConstants.WarewolfError);
            }
            return(text);
        }
Example #20
0
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // create stream with textbox contents
                StringBuilder data   = new StringBuilder();
                Stream        stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(txtXaml.Text));

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

                // show results
                txtResults.Text  = "Workflow Executed";
                txtResults.Text += "\r\nReturned data:";
                if (results.Count > 0)
                {
                    foreach (string key in results.Keys)
                    {
                        txtResults.Text += string.Format("\r\n    {0} : {1}", key, results[key]);
                    }
                }
                else
                {
                    txtResults.Text += "\r\n    <no data returned>";
                }
            }
            catch (Exception ex)
            {
                txtResults.Text = string.Format("Error executing the Xaml. Exception type: {0}\r\nDetails:\r\n--------\r\n{1}", ex.GetType().FullName, ex.ToString());
            }
        }
Example #21
0
        private void CommandRun_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
        {
            InOutTextBlock.Text = string.Empty;

            // Для того чтобы текущее Workflow безглючно запускалось, нужно сохранить его в файл,
            // загрузить файл в другое Workflow и уже запускать
            if (String.IsNullOrEmpty(_runningWorkflowTemporaryFileName))
            {
                var currentPath = Directory.GetCurrentDirectory();
                _runningWorkflowTemporaryFileName = System.IO.Path.Combine(currentPath, "RunningWorkflow.xaml");
            }
            _wd.Save(_runningWorkflowTemporaryFileName);
            var runningWorkflow = ActivityXamlServices.Load(_runningWorkflowTemporaryFileName);

            using (var textWriter = new StringWriter())
            {
                Console.SetOut(textWriter);

                var wi = new WorkflowInvoker(runningWorkflow);
                wi.Invoke();

                var textOutput = textWriter.ToString();
                if (!string.IsNullOrEmpty(textOutput))
                {
                    MessageBox.Show(textOutput, "Вывод программы:");
                }
            }
        }
Example #22
0
        protected override void StartInternal()
        {
            DynamicActivity activity;

            using (var stream = new MemoryStream(Encoding.Default.GetBytes(WorkflowDesigner.Text)))
            {
                activity = ActivityXamlServices.Load(stream) as DynamicActivity;
            }

            if (activity == null)
            {
                return;
            }

            WorkflowInspectionServices.CacheMetadata(activity);

            workflowApplication = new WorkflowApplication(activity);

            workflowApplication.Extensions.Add(OutputWriter);
            workflowApplication.Extensions.Add(InitialiseVisualTrackingParticipant(activity));

            workflowApplication.Completed            += Completed;
            workflowApplication.OnUnhandledException += OnUnhandledException;
            workflowApplication.Aborted += Aborted;

            try
            {
                workflowApplication.Run();
                OnRunningStateChanged(new WorkflowExecutingStateEventArgs(true));
            }
            catch (Exception e)
            {
                OutputWriter.WriteLine(e.StackTrace);
            }
        }
Example #23
0
        /// <summary>
        /// Loads the specified xaml definition.
        /// </summary>
        /// <param name="xamlDefinition">The xaml definition.</param>
        /// <param name="xamlStream">The xaml stream.</param>
        /// <param name="workflowPool">The workflow pool.</param>
        /// <param name="workflowActivity">The workflow activity.</param>
        /// <exception cref="System.ArgumentNullException">xamlDefinition</exception>
        public void Load(StringBuilder xamlDefinition, ref Stream xamlStream, ref Queue <PooledServiceActivity> workflowPool, ref Activity workflowActivity)
        {
            if (xamlDefinition == null || xamlDefinition.Length == 0)
            {
                throw new ArgumentNullException("xamlDefinition");
            }

            // Travis.Frisinger : 13.11.2012 - Remove bad namespaces
            // ReSharper disable ConditionIsAlwaysTrueOrFalse
            if (GlobalConstants.runtimeNamespaceClean)
            // ReSharper restore ConditionIsAlwaysTrueOrFalse
            {
                xamlDefinition = new Dev2XamlCleaner().CleanServiceDef(xamlDefinition);
            }
            // End Mods


            int generation = 0;

            using (xamlStream = xamlDefinition.EncodeForXmlDocument())
            {
                workflowActivity = ActivityXamlServices.Load(xamlStream);
                xamlStream.Seek(0, SeekOrigin.Begin);
                workflowPool.Clear();

                generation++;

                for (int i = 0; i < GlobalConstants._xamlPoolSize; i++)
                {
                    Activity activity = ActivityXamlServices.Load(xamlStream);
                    xamlStream.Seek(0, SeekOrigin.Begin);
                    workflowPool.Enqueue(new PooledServiceActivity(generation, activity));
                }
            }
        }
Example #24
0
 public Activity LoadFromSource(IApplicationHost host)
 {
     if (Type == WorkflowType.File)
     {
         String fullPath = GetWorkflowFullPath(host);
         using (var sr = new StreamReader(fullPath))
         {
             Definition = sr.ReadToEnd();
             sr.BaseStream.Seek(0, SeekOrigin.Begin);
             using (var xr = ActivityXamlServices.CreateReader(sr.BaseStream))
             {
                 var root = ActivityXamlServices.Load(xr);
                 RuntimeActivity.Compile(GetHashedName(), root);
                 return(root);
             }
         }
     }
     else if (Type == WorkflowType.ClrType)
     {
         return(System.Activator.CreateInstance(Assembly, Name).Unwrap() as Activity);
     }
     else if (Type == WorkflowType.Definition)
     {
         using (var sr = new StringReader(Definition))
         {
             Activity root = ActivityXamlServices.Load(sr) as Activity;
             Cached = RuntimeActivity.Compile(GetHashedName(), root);
             return(root);
         }
     }
     else
     {
         throw new NotImplementedException($"WorkflowDefinition. Invalid WorkflowType. Type={Type.ToString()}");
     }
 }
Example #25
0
        private Activity getActivityWithoutDebugSymbol(string path)
        {
            //去除DebugSymbol.Symbol信息,否则拖动代码片断到新建立的XAML文档时无法运行
            var       xamlContent = File.ReadAllText(path);
            XDocument xd          = XDocument.Parse(xamlContent);
            XElement  element     = xd.XPathSelectElement("//*[local-name()='DebugSymbol.Symbol']");

            if (element != null)
            {
                element.SetValue(string.Empty);
            }
            using (MemoryStream stream = new MemoryStream())
            {
                XmlWriterSettings xws = new XmlWriterSettings();
                xws.OmitXmlDeclaration = true;
                xws.Indent             = true;

                using (XmlWriter writer = XmlWriter.Create(stream, xws))
                {
                    xd.WriteTo(writer);
                    writer.Flush();
                    stream.Position = 0;
                    var activity = ActivityXamlServices.Load(stream);
                    return(activity);
                }
            }
        }
Example #26
0
        /// <summary>
        /// Validates well-formedness of the Xaml
        /// </summary>
        /// <exception cref="System.IO.FileNotFoundException">If the <code>inputFile</code> was not found</exception>
        private void ValidateXaml()
        {
            XmlReader     xmlReader  = null;
            XamlXmlReader xamlReader = null;

            try
            {
                log.Debug("Validating XAML.");

                xmlReader  = XmlReader.Create(inputFile);
                xamlReader = new XamlXmlReader(xmlReader);
                ActivityBuilder activity = XamlServices.Load(ActivityXamlServices.CreateBuilderReader(xamlReader)) as ActivityBuilder;

                log.Info("XAML successfully validated.");
            }
            catch (XamlException)
            {
                // Only notify user
                log.Warn("XAML could not be validated. This may also be caused by Custom Activities or WorkflowServices.");
            }
            finally
            {
                // Cleanup
                if (xmlReader != null)
                {
                    xmlReader.Close();
                }
                if (xamlReader != null)
                {
                    xamlReader.Close();
                }
            }
        }
Example #27
0
        public void XamlWorkflowWithInputsOutputs()
        {
            var xamlString = @"
            <Activity x:Class=""WFTemplate""
                      xmlns=""http://schemas.microsoft.com/netfx/2009/xaml/activities""
                      xmlns:s=""clr-namespace:System;assembly=mscorlib""
                      xmlns:s1=""clr-namespace:System;assembly=System""
                      xmlns:sa=""clr-namespace:CoreWf;assembly=CoreWf""
                      xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
                <x:Members>
                    <x:Property Name=""myOutput"" Type=""OutArgument(x:Int32)"" />
                    <x:Property Name=""myInput"" Type=""InArgument(x:Int32)"" />
                </x:Members>
                <Assign>
                    <Assign.To>
                        <OutArgument x:TypeArguments=""x:Int32"">[myOutput]</OutArgument>
                    </Assign.To>
                    <Assign.Value>
                        <InArgument x:TypeArguments=""x:Int32"">[myInput]</InArgument>
                    </Assign.Value>
                </Assign>
            </Activity>";
            var settings   = new ActivityXamlServicesSettings {
                CompileExpressions = true
            };
            var activity = ActivityXamlServices.Load(GenerateStreamFromString(xamlString), settings);
            var inputs   = new Dictionary <string, object>();

            inputs.Add("myInput", 1);
            var outputs = WorkflowInvoker.Invoke(activity, inputs);

            Assert.Equal(1, outputs.Count);
            Assert.True(outputs.ContainsKey("myOutput"));
            Assert.Equal(1, (int)outputs["myOutput"]);
        }
Example #28
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                // Use calculator by simulating clicks.
                String digitOne  = this.comboBox1.SelectedItem.ToString();
                String digitTwo  = this.comboBox2.SelectedItem.ToString();
                String operation = this.comboBox3.SelectedItem.ToString();

                WorkflowInvoker invoker   = new WorkflowInvoker(ActivityXamlServices.Load(@"calc.uiwf"));
                var             arguments = new Dictionary <string, object>();
                arguments.Add("digitOne", digitOne);
                arguments.Add("digitTwo", digitTwo);
                arguments.Add("op", operation);

                IDictionary <string, object> outArgs = invoker.Invoke(arguments);

                String sResult = (String)outArgs["calcResult"];
                this.textBox1.Text = sResult;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "ERROR: " + ex.Message);
            }
        }
        /// <summary>
        ///     Acquires a composite PooledServiceActivity that holds a reference to the underlying activity, once you are done
        ///     working
        ///     with the activity you must return it to the pool via PushActivity.
        /// </summary>
        /// <returns></returns>
        public PooledServiceActivity PopActivity()
        {
            PooledServiceActivity result;

            lock (_poolGuard)
            {
                if (_workflowPool.Count == 0)
                {
                    if (_xamlStream == null)
                    {
                        result = new PooledServiceActivity(_generation, _workflowActivity);
                    }
                    else
                    {
                        Activity activity = ActivityXamlServices.Load(_xamlStream);
                        _xamlStream.Seek(0, SeekOrigin.Begin);
                        result = new PooledServiceActivity(_generation, activity);
                    }
                }
                else
                {
                    result = _workflowPool.Dequeue();
                }
            }

            return(result);
        }
Example #30
0
        public static string Serialize(object ab, bool writeLogFile = false)
        {
            if (ab == null)
            {
                throw new NullReferenceException("ActivityBuilder parameter is null");
            }

            // Serialize the workflow to XAML and store it in a string.
            var sb = new System.Text.StringBuilder();
            var tw = new System.IO.StringWriter(sb);
            var xw = ActivityXamlServices.CreateBuilderWriter(new XamlXmlWriter(tw, new XamlSchemaContext()));

            XamlServices.Save(xw, ab);
            string serializedAB = sb.ToString();

            if (writeLogFile == true)
            {
                // Serialize the workflow to XAML and save it to a file.
                var        sw  = System.IO.File.CreateText(@"C:\add.xaml");
                XamlWriter xw2 = ActivityXamlServices.CreateBuilderWriter(new XamlXmlWriter(sw, new XamlSchemaContext()));
                XamlServices.Save(xw2, ab);
                sw.Close();
            }

            return(serializedAB);
        }