/// <summary>Loads a <see cref="T:System.IO.Stream" /> source for a XAML reader and writes its output as an object graph.</summary>
 /// <returns>The object graph that is written as output.</returns>
 /// <param name="stream">The stream to load as input.</param>
 /// <exception cref="T:System.ArgumentNullException">
 /// <paramref name="stream" /> is null.</exception>
 public object Load(Stream stream)
 {
     return(XamlServices.Load(stream));
 }
Exemplo n.º 2
0
        public void LoadStreamFailNull()
        {
            Stream s = null;

            XamlServices.Load(s);
        }
Exemplo n.º 3
0
        public void LoadXmlReaderFailNull()
        {
            XmlReader xr = null;

            XamlServices.Load(xr);
        }
Exemplo n.º 4
0
 public void Bug680385()
 {
     XamlServices.Load("Test/XmlFiles/CurrentVersion.xaml");
 }
Exemplo n.º 5
0
 public static Project Load(string filename)
 {
     return((Project)XamlServices.Load(filename));
 }
Exemplo n.º 6
0
        public string Compile(string xamlPath, string destinationPath, string[] assemblyNames)
        {
            // Part 0: load the XAML
            XamlSchemaContext schemaContext = new XamlSchemaContext();

            object xamlLoadedObject;

            using (var xamlReader = new XamlXmlReader(xamlPath))
            {
                var builderReader = ActivityXamlServices.CreateBuilderReader(xamlReader, schemaContext);
                xamlLoadedObject = XamlServices.Load(builderReader);
                builderReader.Close();
            }
            ActivityBuilder activityBuilder = (ActivityBuilder)xamlLoadedObject;

            Debug.Assert(activityBuilder.Name.Contains("."));

            string ns = activityBuilder.Name.Substring(0,
                                                       activityBuilder.Name.LastIndexOf("."));

            // Set up the assembly builder based on namespace of activity

            AssemblyBuilder ab =
                AppDomain.CurrentDomain.DefineDynamicAssembly(
                    new AssemblyName(ns)
            {
                Version = new Version(1, 0, 0, 0)
            },
                    AssemblyBuilderAccess.RunAndSave);

            AssemblyBuilder abFake =
                AppDomain.CurrentDomain.DefineDynamicAssembly(
                    new AssemblyName(ns)
            {
                Version = new Version(1, 0, 0, 0)
            },
                    AssemblyBuilderAccess.Run);

            ModuleBuilder mb     = ab.DefineDynamicModule(ns + ".dll", ns + ".dll");
            ModuleBuilder mbFake = abFake.DefineDynamicModule(ns + "dll");

            // Part 1: define the class
            TypeBuilder newClass    = BuildType(mb, activityBuilder, false);
            Type        createdType = newClass.CreateType();

            TypeBuilder newClassFake = BuildType(mbFake, activityBuilder, true);
            Type        fakeType     = newClassFake.CreateType();

            string       magicXaml    = GenerateXAML(activityBuilder, fakeType);
            MemoryStream stringStream = new MemoryStream(Encoding.Unicode.GetBytes(magicXaml));

            // Part 2: embed the XAML as a manifest
            string xamlResourceName = createdType.FullName + ".xaml";

            mb.DefineManifestResource(xamlResourceName, stringStream, ResourceAttributes.Public);

            // End: save the generated assembly
            ab.Save(ns + ".dll");
            File.Copy(ns + ".dll", Path.Combine(destinationPath, ns + ".dll"), true);
            File.Delete(ns + ".dll");
            return(ns + ".dll");
        }
Exemplo n.º 7
0
 private static UIElement CreateXamlContent(string fileName)
 {
     return((UIElement)XamlServices.Load(fileName));
 }
Exemplo n.º 8
0
 private static object Deserialize(Stream stream)
 {
     stream.Seek(0, SeekOrigin.Begin);
     return(XamlServices.Load(stream));
 }
Exemplo n.º 9
0
 public static Feature LoadFeature(String fullPath)
 {
     return(XamlServices.Load(fullPath) as Feature);
 }
Exemplo n.º 10
0
 /// <summary>
 /// Creates the instance from xaml.
 /// </summary>
 /// <param name="xaml">The stream of xaml to deserialize.</param>
 /// <returns>The deserialized object.</returns>
 /// <remarks>
 /// This exists as its own method to prevent the CLR's JIT compiler from failing
 /// to compile the CreateInstance method just because the PresentationFramework.dll
 /// may be missing (which it is on some shared web hosts).  This way, if the
 /// XamlSource attribute is never used, the PresentationFramework.dll never need
 /// be present.
 /// </remarks>
 private static T CreateInstanceFromXaml(Stream xaml)
 {
     return((T)XamlServices.Load(xaml));
 }
Exemplo n.º 11
0
 private static UserOptions Load(Stream stream)
 {
     return((UserOptions)XamlServices.Load(stream));
 }
Exemplo n.º 12
0
 public static T Compile <T>(Stream stream) where T : PdfXamlObject
 {
     return(XamlServices.Load(stream) as T);
 }
Exemplo n.º 13
0
        private static object LoadActivity(XamlNodeList xamlNodes)
        {
            XamlReader reader = ActivityXamlServices.CreateReader(xamlNodes.GetReader(), xamlNodes.Writer.SchemaContext);

            return(XamlServices.Load(reader));
        }
 public object Load(TextReader reader)
 {
     return(XamlServices.Load(reader));
 }
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            WorkflowServiceHost host = null;
            Stream stream;
            string str2;

            if (string.IsNullOrEmpty(constructorString))
            {
                throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.WorkflowServiceHostFactoryConstructorStringNotProvided));
            }
            if (baseAddresses == null)
            {
                throw System.ServiceModel.Activation.FxTrace.Exception.ArgumentNull("baseAddresses");
            }
            if (baseAddresses.Length == 0)
            {
                throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.BaseAddressesNotProvided));
            }
            if (!HostingEnvironment.IsHosted)
            {
                throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.Hosting_ProcessNotExecutingUnderHostedContext("WorkflowServiceHostFactory.CreateServiceHost")));
            }
            string virtualPath = VirtualPathUtility.Combine(AspNetEnvironment.Current.XamlFileBaseLocation, constructorString);

            if (this.GetServiceFileStreamOrCompiledCustomString(virtualPath, baseAddresses, out stream, out str2))
            {
                object obj2;
                using (stream)
                {
                    BuildManager.GetReferencedAssemblies();
                    XamlXmlReaderSettings settings = new XamlXmlReaderSettings {
                        ProvideLineInfo = true
                    };
                    XamlReader xamlReader = ActivityXamlServices.CreateReader(new XamlXmlReader(XmlReader.Create(stream), settings));
                    if (System.ServiceModel.Activation.TD.XamlServicesLoadStartIsEnabled())
                    {
                        System.ServiceModel.Activation.TD.XamlServicesLoadStart();
                    }
                    obj2 = XamlServices.Load(xamlReader);
                    if (System.ServiceModel.Activation.TD.XamlServicesLoadStopIsEnabled())
                    {
                        System.ServiceModel.Activation.TD.XamlServicesLoadStop();
                    }
                }
                WorkflowService service = null;
                if (obj2 is Activity)
                {
                    service = new WorkflowService {
                        Body = (Activity)obj2
                    };
                }
                else if (obj2 is WorkflowService)
                {
                    service = (WorkflowService)obj2;
                }
                if (service != null)
                {
                    if (service.Name == null)
                    {
                        string fileName      = VirtualPathUtility.GetFileName(virtualPath);
                        string namespaceName = string.Format(CultureInfo.InvariantCulture, "/{0}{1}", new object[] { ServiceHostingEnvironment.SiteName, VirtualPathUtility.GetDirectory(ServiceHostingEnvironment.FullVirtualPath) });
                        service.Name = XName.Get(XmlConvert.EncodeLocalName(fileName), namespaceName);
                        if ((service.ConfigurationName == null) && (service.Body != null))
                        {
                            service.ConfigurationName = XmlConvert.EncodeLocalName(service.Body.DisplayName);
                        }
                    }
                    host = this.CreateWorkflowServiceHost(service, baseAddresses);
                }
            }
            else
            {
                Type typeFromAssembliesInCurrentDomain = this.GetTypeFromAssembliesInCurrentDomain(constructorString);
                if (null == typeFromAssembliesInCurrentDomain)
                {
                    typeFromAssembliesInCurrentDomain = this.GetTypeFromCompileCustomString(str2, constructorString);
                }
                if (null == typeFromAssembliesInCurrentDomain)
                {
                    BuildManager.GetReferencedAssemblies();
                    typeFromAssembliesInCurrentDomain = this.GetTypeFromAssembliesInCurrentDomain(constructorString);
                }
                if (null != typeFromAssembliesInCurrentDomain)
                {
                    if (!TypeHelper.AreTypesCompatible(typeFromAssembliesInCurrentDomain, typeof(Activity)))
                    {
                        throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.TypeNotActivity(typeFromAssembliesInCurrentDomain.FullName)));
                    }
                    Activity activity = (Activity)Activator.CreateInstance(typeFromAssembliesInCurrentDomain);
                    host = this.CreateWorkflowServiceHost(activity, baseAddresses);
                }
            }
            if (host == null)
            {
                throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.CannotResolveConstructorStringToWorkflowType(constructorString)));
            }
            ((IDurableInstancingOptions)host.DurableInstancingOptions).SetScopeName(XName.Get(XmlConvert.EncodeLocalName(VirtualPathUtility.GetFileName(ServiceHostingEnvironment.FullVirtualPath)), string.Format(CultureInfo.InvariantCulture, "/{0}{1}", new object[] { ServiceHostingEnvironment.SiteName, VirtualPathUtility.GetDirectory(ServiceHostingEnvironment.FullVirtualPath) })));
            return(host);
        }
Exemplo n.º 16
0
        /// <summary>
        /// デシリアライズ
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static T Deserialize <T>(this byte[] bytes)
        {
            if (bytes == null)
            {
                return((dynamic)null);
            }
            if (typeof(T).IsValueType)
            {
                if (typeof(T) == typeof(int))
                {
                    return((dynamic)BitConverter.ToInt32(bytes, 0));
                }
                else if (typeof(T) == typeof(long))
                {
                    return((dynamic)BitConverter.ToInt64(bytes, 0));
                }
                else if (typeof(T) == typeof(bool))
                {
                    return((dynamic)BitConverter.ToBoolean(bytes, 0));
                }
                else if (typeof(T) == typeof(char))
                {
                    return((dynamic)BitConverter.ToChar(bytes, 0));
                }
                else if (typeof(T) == typeof(short))
                {
                    return((dynamic)BitConverter.ToInt16(bytes, 0));
                }
                else if (typeof(T) == typeof(ushort))
                {
                    return((dynamic)BitConverter.ToUInt16(bytes, 0));
                }
                else if (typeof(T) == typeof(uint))
                {
                    return((dynamic)BitConverter.ToUInt32(bytes, 0));
                }
                else if (typeof(T) == typeof(ulong))
                {
                    return((dynamic)BitConverter.ToUInt64(bytes, 0));
                }
                else if (typeof(T) == typeof(float))
                {
                    return((dynamic)BitConverter.ToSingle(bytes, 0));
                }
                else if (typeof(T) == typeof(double))
                {
                    return((dynamic)BitConverter.ToDouble(bytes, 0));
                }
                else if (typeof(T) == typeof(byte[]))
                {
                    return((dynamic)bytes);
                }
                else
                {
                    var size = bytes.Length;
                    var ptr  = Marshal.AllocHGlobal(size);

                    Marshal.Copy(bytes, 0, ptr, size);
                    var val = Marshal.PtrToStructure(ptr, typeof(T));
                    Marshal.FreeHGlobal(ptr);
                    return((dynamic)val);
                }
            }
            else
            {
                if (typeof(T) == typeof(string))
                {
                    return((dynamic)Encoding.UTF8.GetString(bytes));
                }
                else
                {
                    using (var sr = new StreamReader(new MemoryStream(bytes), Encoding.UTF8)) {
                        return((T)XamlServices.Load(sr));
                    }
                }
            }
        }
Exemplo n.º 17
0
//        [Obsolete]
//        public static T LoadFromXamlFile<T>(this string fileName)
//        {
//            return fileName.DeserializeFromXamlFile<T>();
//        }

        public static T DeserializeFromXamlFile <T>(this string fileName)
        {
            return((T)XamlServices.Load(fileName));
        }
Exemplo n.º 18
0
        public static ProjectFile Load(string file)
        {
            var p = XamlServices.Load(file) as ProjectFile;

            return(p);
        }
        public void OnItemsPasted(List <object> itemsToPaste, List <object> metaData, Point pastePoint, WorkflowViewElement pastePointReference)
        {
            if (this.ModelItem.ItemType == typeof(State))
            {
                WorkflowViewElement view = VisualTreeUtils.FindVisualAncestor <WorkflowViewElement>(this);
                if (view != null)
                {
                    StateContainerEditor container = (StateContainerEditor)DragDropHelper.GetCompositeView(view);
                    container.OnItemsPasted(itemsToPaste, metaData, pastePoint, pastePointReference);
                }

                return;
            }

            if (itemsToPaste.Count == 1 && itemsToPaste.First() is Transition)
            {
                if (metaData == null || metaData.Count != 1 || !(metaData.First() is string))
                {
                    ShowMessageBox(SR.PasteTransitionWithoutDestinationState);
                    return;
                }

                ModelItem destinationState = FindState(metaData.First() as string);

                if (destinationState == null)
                {
                    ShowMessageBox(SR.PasteTransitionWithoutDestinationState);
                    return;
                }

                this.PopulateVirtualizingContainer(destinationState);

                ModelItem[] selectedItems = this.Context.Items.GetValue <Selection>().SelectedObjects.ToArray();
                string      errorMessage;
                if (!CanPasteTransition(destinationState, out errorMessage, selectedItems))
                {
                    ShowMessageBox(errorMessage);
                    return;
                }

                Transition pastedTransition = itemsToPaste.First() as Transition;
                Fx.Assert(pastedTransition != null, "Copied Transition should not be null.");

                using (EditingScope es = (EditingScope)this.ModelItem.BeginEdit(System.Activities.Presentation.SR.PropertyChangeEditingScopeDescription))
                {
                    string displayName = pastedTransition.DisplayName;
                    bool   isFirst     = true;
                    foreach (ModelItem selectedItem in selectedItems)
                    {
                        if (!isFirst)
                        {
                            StringReader reader = new StringReader(XamlServices.Save(pastedTransition));
                            pastedTransition = (Transition)XamlServices.Load(reader);
                        }

                        ModelItem transitionModelItem = this.Context.Services.GetRequiredService <ModelTreeManager>().WrapAsModelItem(pastedTransition);
                        ModelItem sourceState         = selectedItem;
                        sourceState.Properties[StateDesigner.TransitionsPropertyName].Collection.Add(transitionModelItem);
                        transitionModelItem.Properties[TransitionDesigner.ToPropertyName].SetValue(destinationState);

                        if (isFirst)
                        {
                            this.ViewStateService.RemoveViewState(transitionModelItem, ConnectorLocationViewStateKey);
                            this.ViewStateService.RemoveViewState(transitionModelItem, SrcConnectionPointIndexStateKey);
                            this.ViewStateService.RemoveViewState(transitionModelItem, DestConnectionPointIndexStateKey);
                            isFirst = false;
                        }
                    }

                    es.Complete();
                }
            }
            else
            {
                List <ModelItem> modelItemsPasted = new List <ModelItem>();
                List <State>     states           = new List <State>();

                foreach (object obj in itemsToPaste)
                {
                    State state;
                    if (obj is FinalState)
                    {
                        state = new State()
                        {
                            DisplayName = DefaultFinalStateDisplayName, IsFinal = true
                        };
                    }
                    else
                    {
                        state = (State)obj;
                        if (state.DisplayName == null)
                        {
                            state.DisplayName = DefaultStateDisplayName;
                        }
                    }
                    states.Add(state);
                }

                RemoveDanglingTransitions(states);

                using (EditingScope es = (EditingScope)this.ModelItem.BeginEdit(
                           System.Activities.Presentation.SR.CollectionAddEditingScopeDescription))
                {
                    // Fix 157591 by storing the height and width of the container "before" the new states are added to the
                    // panel, and group the insertion inside one editing scope - such that Undo will also restore the
                    // size of the StateMachineContainer to pre-insert size.
                    StoreShapeSizeWithUndoRecursively(this.ModelItem);

                    foreach (State state in states)
                    {
                        ModelItem stateModelItem =
                            (this.ModelItem.ItemType == typeof(StateMachine)) ?
                            this.ModelItem.Properties[StateMachineDesigner.StatesPropertyName].Collection.Add(state) :
                            GetStateMachineModelItem(this.ModelItem).Properties[StateMachineDesigner.StatesPropertyName].Collection.Add(state);
                        modelItemsPasted.Add(stateModelItem);
                    }

                    es.Complete();
                }

                if (modelItemsPasted.Count > 0)
                {
                    // translate location view states to be in the coordinate system of the pasting target
                    Fx.Assert(this.ModelItem.ItemType == typeof(StateMachine), "Only StateMachine contain the StateContainerEditor.");

                    this.UpdateLocationViewStatesByMetaData(modelItemsPasted, metaData, this);

                    if (pastePoint.X > 0 && pastePoint.Y > 0)
                    {
                        if (pastePointReference != null)
                        {
                            pastePoint   = pastePointReference.TranslatePoint(pastePoint, this.panel);
                            pastePoint.X = pastePoint.X < 0 ? 0 : pastePoint.X;
                            pastePoint.Y = pastePoint.Y < 0 ? 0 : pastePoint.Y;
                        }
                        this.UpdateLocationViewStatesByPoint(modelItemsPasted, pastePoint);
                    }
                    // If paste point is not available, paste the items to the top left corner.
                    else
                    {
                        this.UpdateLocationViewStatesToAvoidOverlap(modelItemsPasted);
                    }
                }

                this.Dispatcher.BeginInvoke(() =>
                {
                    if (modelItemsPasted.Count > 0 && modelItemsPasted[0] != null)
                    {
                        Keyboard.Focus(modelItemsPasted[0].View as IInputElement);
                    }
                    this.Context.Items.SetValue(new Selection(modelItemsPasted));
                },
                                            DispatcherPriority.ApplicationIdle
                                            );
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Loads the factory configuration from the package.
        /// </summary>
        /// <param name="packageFilePath">The fully qualified path to the Code Factory package.</param>
        /// <returns>Package read result with either the error that occurred or the fully loaded factory configuration. </returns>
        public static PackageReadResult <VsFactoryConfiguration> LoadFactoryConfiguration(string packageFilePath)
        {
            _logger.DebugEnter();

            var result = new PackageReadResult <VsFactoryConfiguration> {
                HasError = false
            };

            if (string.IsNullOrEmpty(packageFilePath))
            {
                _logger.Information("No package file was provided, cannot load the factory configuration.");
                result.HasError = true;
                result.Error    = ConfigurationMessages.ConfigurationFileNotProvided;
                _logger.DebugExit();
                return(result);
            }

            try
            {
                if (!File.Exists(packageFilePath))
                {
                    _logger.Information(
                        $"The package file '{packageFilePath}' was not found, cannot load the factory configuration.");
                    result.HasError = true;
                    result.Error    = string.Format(ConfigurationMessages.PackageFileNotFound,
                                                    Path.GetFileName(packageFilePath));
                    _logger.DebugExit();
                    return(result);
                }

                var configUri =
                    PackUriHelper.CreatePartUri(
                        new Uri(string.Format(PACKAGE_CONFIG_VIRTUAL_FILEPATH, PACKAGE_CONFIG_FILE_NAME),
                                UriKind.Relative));

                using (var codeFactoryPackage = Package.Open(packageFilePath, FileMode.Open))
                {
                    Stream configStream = null;
                    VsFactoryConfiguration resultData = null;
                    try
                    {
                        if (!codeFactoryPackage.PartExists(configUri))
                        {
                            result.HasError = true;
                            result.Error    = string.Format(ConfigurationMessages.ConfigNotInPackage,
                                                            Path.GetFileName(packageFilePath));
                        }
                        else
                        {
                            var configPart = codeFactoryPackage.GetPart(configUri);

                            configStream = configPart.GetStream();
                            resultData   = XamlServices.Load(configStream) as VsFactoryConfiguration;
                        }
                    }
                    catch (InvalidOperationException partNotFoundError)
                    {
                        _logger.Error(
                            "The follow exception occurred while loading part of the code factory configuration.",
                            partNotFoundError);
                        result.HasError = true;
                        result.Error    = string.Format(ConfigurationMessages.ConfigNotInPackage,
                                                        Path.GetFileName(packageFilePath));
                    }

                    finally
                    {
                        configStream?.Dispose();
                    }

                    if (result.HasError)
                    {
                        return(result);
                    }

                    if (resultData != null)
                    {
                        result.Result = resultData;
                    }
                    else
                    {
                        result.HasError = true;
                        result.Error    = string.Format(ConfigurationMessages.FactoryConfigCouldNotBeloaded,
                                                        Path.GetFileName(packageFilePath));
                    }
                }
            }
            catch (Exception loadFactoryConfigurationError)
            {
                _logger.Error("The following unhandled exception occurred while loading the code factory configuration",
                              loadFactoryConfigurationError);
            }

            _logger.DebugExit();
            return(result);
        }
Exemplo n.º 21
0
        /// <summary>
        /// エフェクトをファイルから読み込みます。
        /// </summary>
        /// <remarks>
        /// エフェクトファイルは以下のファイルから検索されます。
        ///
        /// 1、{ディレクトリ名}/{エフェクト名}/{エフェクト名}.xaml
        /// 2、{ディレクトリ名}/{エフェクト名}/Effect.xaml
        /// 3、{ディレクトリ名}/{エフェクト名}.xaml
        /// </remarks>
        private static EffectObject LoadInternal(string basePath,
                                                 Dictionary <string, object> args)
        {
            try
            {
                // エフェクトファイルの検索
                var path = EnumeratePath(basePath)
                           .FirstOrDefault(_ => File.Exists(_));
                if (string.IsNullOrEmpty(path))
                {
                    throw new FileNotFoundException(
                              basePath + ": エフェクトが見つかりません。");
                }

                // エフェクト引数の置換
                byte[] bytes = null;
                if (args == null || !args.Any())
                {
                    bytes = File.ReadAllBytes(path);
                }
                else
                {
                    // ファイル中の変数を置き換えます。
                    var text = File.ReadAllText(path, Encoding.UTF8);
                    text = ReplaceTable(text, args);

                    bytes = Encoding.UTF8.GetBytes(text);
                }

                // xamlの読み込みを開始します。
                using (var stream = new MemoryStream(bytes))
                {
                    var settings = new XamlXmlReaderSettings
                    {
                        BaseUri    = new Uri(path), //, UriKind.Absolute),
                        CloseInput = false,
                    };
                    var context = new XamlSchemaContext(GetReferenceAssemblies());

                    var reader = new XamlXmlReader(stream, context, settings);
                    var obj    = XamlServices.Load(reader);

                    var result = obj as EffectObject;
                    if (result != null)
                    {
                        result.BasePath = Path.GetDirectoryName(path);
                        //result.Name = param.Name;
                    }

                    return(result);
                }
            }
            catch (Exception ex)
            {
                Log.ErrorException(ex,
                                   "'{0}': エフェクトの読み込みに失敗しました。", basePath);

                return(null);
                //throw ex;
            }
        }
Exemplo n.º 22
0
        public void EscapedValue()
        {
            var exception = (Exception)XamlServices.Load(new StringReader("<Exception xmlns=\"clr-namespace:System;assembly=mscorlib\" HelpLink=\"{}{123}\" />"));

            Assert.AreEqual("{123}", exception.HelpLink);
        }
Exemplo n.º 23
0
 public static MissionPack Load(string filename)
 {
     return((MissionPack)XamlServices.Load(filename));
 }
Exemplo n.º 24
0
 public void Bug680385()
 {
     XamlServices.Load(TestResourceHelper.GetFullPathOfResource("Test/XmlFiles/CurrentVersion.xaml"));
 }
Exemplo n.º 25
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.AssemblyResolve += FindAssem;

            if (args.Length > 1)
            {
                try
                {
                    if (args[0].Equals("-h"))
                    {
                        string message = "Usage: -r WorkflowFileName.Ext -a ArgumentFile.json \n" +
                                         "       -r \"Path\\WorkflowFileName.Ext\"  -a \"Path\\ArgumentFile.json\" \n" +
                                         "       -r \"Path\\WorkflowFileName.Ext\"  -x \"Path\\ArgumentFile.xaml\"";
                        Console.WriteLine(message); Console.ReadKey();
                        return;
                    }

                    if (args[0].Equals("-r"))
                    {
                        //run workflow
                        int    idx      = Array.IndexOf(args, "-r");
                        string FileName = args[idx + 1];
                        string wfText   = File.ReadAllText(FileName);

                        System.IO.StringReader stringReader = new System.IO.StringReader(wfText);

                        var settings = new ActivityXamlServicesSettings {
                            CompileExpressions = true
                        };
                        Activity root = System.Activities.XamlIntegration.ActivityXamlServices.Load(stringReader, settings);

                        Dictionary <string, object> WorkflowArguments = new Dictionary <string, object>();

                        idx = Array.IndexOf(args, "-a"); //json arguments
                        if (idx != -1)
                        {
                            string ArgumentFile = args[idx + 1];
                            WorkflowArguments = JsonConvert.DeserializeObject <Dictionary <string, object> >(File.ReadAllText(ArgumentFile));
                        }

                        idx = Array.IndexOf(args, "-x"); //xaml based argument serialization - allows for complex objects
                        if (idx != -1)
                        {
                            WorkflowArguments = (Dictionary <string, object>)XamlServices.Load(args[idx + 1]);
                        }

                        WorkflowApplication wfApp = new WorkflowApplication(root, WorkflowArguments);

                        WFTracking track = new WFTracking(new ConsoleLogger());
                        //Tracking Profile
                        TrackingProfile prof = new TrackingProfile();
                        prof.Name = "CustomTrackingProfile";
                        prof.Queries.Add(new WorkflowInstanceQuery {
                            States = { "*" }
                        });
                        prof.Queries.Add(new ActivityStateQuery {
                            States = { "*" }, Arguments = { "*" }
                        });
                        prof.Queries.Add(new CustomTrackingQuery()
                        {
                            Name = "*", ActivityName = "*"
                        });
                        prof.ImplementationVisibility = ImplementationVisibility.RootScope;
                        track.TrackingProfile         = prof;
                        track.WorkflowName            = Path.GetFileNameWithoutExtension(FileName);

                        wfApp.Extensions.Add(track);

                        wfApp.Extensions.Add(new EmailSetting());
                        //Requires the following environment variables to be set: Mail_MailServerAddress, Mail_ServerEmailAddress, Mail_ServerEmailPassword, Mail_ServerEmailAccount,

                        wfApp.Extensions.Add(new ConsoleLogger());

                        wfApp.Completed = (WorkflowApplicationCompletedEventArgs e) => {
                            if (e.Outputs != null && e.Outputs.Count > 0)
                            {
                                foreach (var kvp in e.Outputs)
                                {
                                    Console.WriteLine("Output --> {0} : {1}", kvp.Key, kvp.Value.ToString());
                                }
                            }
                            Console.WriteLine("Finished - Workflow Completion State {0} \nPress any key to continue", e.CompletionState);
                        };
                        wfApp.Run();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Could not open workflow: " + string.Join(" ", args) + "\nError" + e.ToString());
                }
                Console.WriteLine("Waiting... press key to exit");
                Console.ReadKey();
            }
        }
Exemplo n.º 26
0
 public void XamlServicesLoad()
 {
     Pattern.CreateByName(it =>
                          XamlServices.Load(it.IsPayloadOf <ObjectDataProvider>().Format <Xaml>()));
 }
Exemplo n.º 27
0
        public void LoadTextReaderFailNull()
        {
            TextReader tr = null;

            XamlServices.Load(tr);
        }
Exemplo n.º 28
0
 public T Load <T>(Stream data) => (T)XamlServices.Load(data);
Exemplo n.º 29
0
 public void LoadXmlReader()
 {
     Assert.IsTrue(XamlServices.Load(XmlReader.Create(new StringReader(Simple_XAML))) is HoldsOneElement,
                   "Load should return a HoldsOneElement");
 }
 /// <summary>Loads a <see cref="T:System.IO.Stream" /> source for a XAML reader and returns an object graph.</summary>
 /// <returns>The object graph that is returned.</returns>
 /// <param name="fileName">The file name to load and use as source.</param>
 /// <exception cref="T:System.ArgumentNullException">
 /// <paramref name="fileName" /> input is null.</exception>
 public object Load(string fileName)
 {
     return(XamlServices.Load(fileName));
 }