Exemplo n.º 1
0
        public void WriteObject(object obj)
        {
            var settings = new XmlWriterSettings();

            settings.Indent = true;
            settings.NewLineOnAttributes = true;

            this.BaseStream.Seek(0, SeekOrigin.Begin);

            var writer = XmlWriter.Create(this.BaseStream, settings);

            XamlServices.Save(writer, obj);
        }
Exemplo n.º 2
0
        public void Write_AttachedProperty()
        {
            var obj = new AttachedWrapper();

            Attachable.SetFoo(obj, "x");
            Attachable.SetFoo(obj.Value, "y");
            try {
                Assert.AreEqual(ReadXml("AttachedProperty.xml").Trim(), XamlServices.Save(obj), "#1");
            } finally {
                Attachable.SetFoo(obj, null);
                Attachable.SetFoo(obj.Value, null);
            }
        }
Exemplo n.º 3
0
        public static string ToXamlString(this ActivityBuilder ab)
        {
            // Serialize the workflow to XAML and store it in a string.
            StringBuilder sb = new StringBuilder();

            using (StringWriter tw = new StringWriter(sb))
                using (XamlWriter xw = ActivityXamlServices.CreateBuilderWriter(new XamlXmlWriter(tw, new XamlSchemaContext())))
                {
                    XamlServices.Save(xw, ab);
                    string serializedAB = sb.ToString();
                    return(serializedAB);
                }
        }
Exemplo n.º 4
0
 /// <summary>
 /// Serializes a specified ActivityBuilder object and write the result via specified TextWriter object.
 /// </summary>
 /// <param name="writer">The writer to write result.</param>
 /// <param name="builder">A specified ActivityBuilder object.</param>
 public void Serialize(TextWriter writer, ActivityBuilder builder)
 {
     using (XmlWriter xmlWriter = XmlWriter.Create(writer, GetXmlSettings()))
     {
         using (NoUIXamlXmlWriter xamlWriter = new NoUIXamlXmlWriter(xmlWriter, new XamlSchemaContext()))
         {
             using (XamlWriter activityWriter = ActivityXamlServices.CreateBuilderWriter(xamlWriter))
             {
                 XamlServices.Save(activityWriter, builder);
             }
         }
     }
 }
Exemplo n.º 5
0
        private static void Serialize(Stream writeStream, Activity activity)
        {
            XmlWriterSettings settings = new XmlWriterSettings {
                Indent      = true,
                IndentChars = "    "
            };

            using (XmlWriter writer = XmlWriter.Create(writeStream, settings))
            {
                XamlServices.Save(writer, activity);
                writer.Flush();
            }
        }
Exemplo n.º 6
0
        void RecordButton_Unchecked(object sender, RoutedEventArgs e)
        {
            RecordButton.Content = "Record";
            MouseHook.Stop();
            KeyboardHook.Stop();

            workflow = input.GetWorkflow();

            if (workflow.Activities.Any())
            {
                XamlServices.Save($@"{OutputDirName}\{DateTime.Now:yyyyMMdd-HHmmss}.xaml", workflow);
            }
        }
Exemplo n.º 7
0
        private static void Save(bool skipBackup)
        {
            // save before load cause loss the setting!
            if (!IsLoaded)
            {
                return;
            }
            lock (_settingValueHolder)
            {
                try
                {
                    // create temporary file
                    var tempfile = Path.Combine(App.ConfigurationDirectoryPath, Path.GetRandomFileName());
                    using (var fs = File.Open(tempfile, FileMode.Create, FileAccess.ReadWrite))
                    {
                        // sort by key
                        var sd = new SortedDictionary <string, object>(_settingValueHolder);
                        XamlServices.Save(fs, sd);
                    }
                    var backup = skipBackup ? null : BackupFilePath;

                    // File.Replace is too buggy to use.
                    // File.Replace(tempfile, App.ConfigurationFilePath, backup);
                    if (File.Exists(App.ConfigurationFilePath))
                    {
                        if (backup != null)
                        {
                            if (File.Exists(backup))
                            {
                                File.Delete(backup);
                            }
                            File.Move(App.ConfigurationFilePath, backup);
                        }
                        else
                        {
                            File.Delete(App.ConfigurationFilePath);
                        }
                    }
                    File.Move(tempfile, App.ConfigurationFilePath);
                }
                catch (IOException)
                {
                    // file error.
                }
                catch (UnauthorizedAccessException)
                {
                    // could not write.
                }
            }
        }
Exemplo n.º 8
0
        public void Write_ShouldSerializeObject()
        {
            if (!Compat.IsPortableXaml)
            {
                Assert.Ignore("This is not support in System.Xaml");
            }
            else
            {
                var instance = new ShouldSerializeInvisibleTest();
                var actual   = XamlServices.Save(instance);

                Assert.IsEmpty(actual);
            }
        }
Exemplo n.º 9
0
        public void Write_NumericValues_Max()
        {
            var obj = new NumericValues
            {
                DoubleValue  = double.MaxValue,
                DecimalValue = decimal.MaxValue,
                FloatValue   = float.MaxValue,
                ByteValue    = byte.MaxValue,
                IntValue     = int.MaxValue,
                LongValue    = long.MaxValue
            };

            Assert.AreEqual(ReadXml("NumericValues_Max.xml").Trim(), XamlServices.Save(obj), "#1");
        }
Exemplo n.º 10
0
        public void Write_NumericValues()
        {
            var obj = new NumericValues
            {
                DoubleValue  = 123.456,
                DecimalValue = 234.567M,
                FloatValue   = 345.678f,
                ByteValue    = 123,
                IntValue     = 123456,
                LongValue    = 234567
            };

            Assert.AreEqual(ReadXml("NumericValues.xml").Trim(), XamlServices.Save(obj), "#1");
        }
Exemplo n.º 11
0
        public void Write_PositionalParameters1()
        {
            // PositionalParameters can only be written when the
            // instance is NOT the root object.
            //
            // A single positional parameter can be written as an
            // attribute, but there are two in PositionalParameters1.
            //
            // A default constructor could be used to not use
            // PositionalParameters, but there isn't in this type.
            var obj = new PositionalParametersClass1("foo", 5);

            XamlServices.Save(obj);
        }
Exemplo n.º 12
0
        /// <summary>
        ///     Persist the user data to the Xaml file on the local disk.
        /// </summary>
        /// <param name="modelsToPersist">
        ///     All components in the App that implement <see cref="IPersistentApplicationStateObject" /> so
        ///     the implementation can go get the data to persist.
        /// </param>
        public async Task PersistAsync(IEnumerable <IPersistentApplicationStateObject> modelsToPersist)
        {
            var data         = new List <IPersistentApplicationStateObject>(modelsToPersist.ToList());
            var serialised   = XamlServices.Save(data);
            var fullFileName = await FullFileName();

            using (var file = new FileStream(fullFileName, FileMode.Create))
            {
                using (var writer = new StreamWriter(file))
                {
                    await writer.WriteAsync(serialised);
                }
            }
        }
Exemplo n.º 13
0
        public static string ToXamlString2 <T>(this ActivityBuilder <T> ab)
        {
            StringBuilder xaml = new StringBuilder();

            using (XmlWriter xmlWriter = XmlWriter.Create(xaml, new XmlWriterSettings {
                Indent = true, OmitXmlDeclaration = true
            }))
                using (XamlWriter xamlWriter = new XamlXmlWriter(xmlWriter, new XamlSchemaContext()))
                    using (XamlWriter xamlServicesWriter = ActivityXamlServices.CreateBuilderWriter(xamlWriter))
                    {
                        XamlServices.Save(xamlServicesWriter, ab);
                    }
            return(xaml.ToString());
        }
Exemplo n.º 14
0
        /// <summary>
        ///     Persist the user data to the Xaml file on the local disk.
        /// </summary>
        /// <param name="modelsToPersist">
        ///     All components in the App that implement <see cref="IPersistentApplicationStateObject" /> so
        ///     the implementation can go get the data to persist.
        /// </param>
        public void Persist(IEnumerable <IPersistentApplicationStateObject> modelsToPersist)
        {
            var data       = new List <IPersistentApplicationStateObject>(modelsToPersist.ToList());
            var serialised = XamlServices.Save(data);

            try
            {
                File.WriteAllText(FullFileName, serialised);
            }
            catch (IOException ex)
            {
                this.userMessageBox.Show(ex, "Unable to save recently used files.");
            }
        }
Exemplo n.º 15
0
        public void Should_complain_on_non_initialized_ver()
        {
            var xaml = XamlServices.Save(new Case4());

            Console.WriteLine(xaml);
            var ex = Record(delegate
            {
                xaml = new Case4Evolver().UpgradeDatabaseXaml(xaml);
            });

            Assert.IsNotNull(ex);
            Assert.IsInstanceOfType(ex, typeof(EvolverException));
            StringAssert.Contains(ex.Message, "There is no upgrade method for current schema version -1");
        }
      public void SaveActivityBuilder(ActivityBuilder builder, string path)
      {
          var actualpath = System.IO.Path.GetDirectoryName(path) + "\\wfReadytoUpdate.xaml";

          txtWorkflowSnapshot.Text = actualpath;
          using (var writer = File.CreateText(actualpath))
          {
              var xmlWriter = new XamlXmlWriter(writer, new XamlSchemaContext());
              using (var xamlWriter = ActivityXamlServices.CreateBuilderWriter(xmlWriter))
              {
                  XamlServices.Save(xamlWriter, builder);
              }
          }
      }
        /// <summary>
        /// Creates a new Workflow Designer instance with C# Expression Editor
        /// </summary>
        /// <param name="sourceFile">Workflow FileName</param>
        public static WorkflowDesigner NewInstance(string sourceFile = _defaultActivity)
        {
            if (string.IsNullOrWhiteSpace(sourceFile))
            {
                sourceFile = Path.Combine(AssemblyDirectory, _defaultActivity);
            }

            var expressionEditorService = new RoslynExpressionEditorService();

            ExpressionTextBox.RegisterExpressionActivityEditor(new CSharpValue <string>().Language, typeof(RoslynExpressionEditor), CSharpExpressionHelper.CreateExpressionFromString);

            var wfDesigner = new WorkflowDesigner();
            var dcs        = wfDesigner.Context.Services.GetService <DesignerConfigurationService>();

            dcs.TargetFrameworkName = new System.Runtime.Versioning.FrameworkName(".NETFramework", new Version(4, 6, 1));
            dcs.LoadingFromUntrustedSourceEnabled = true;
            wfDesigner.Context.Services.Publish <IExpressionEditorService>(expressionEditorService);

            //associates all of the basic activities with their designers
            new DesignerMetadata().Register();

            string temp = File.ReadAllText(Path.Combine(AssemblyDirectory, @"colors.xaml"));

            StringReader       reader    = new StringReader(temp);
            XmlReader          xmlReader = XmlReader.Create(reader);
            ResourceDictionary fontAndColorDictionary = (ResourceDictionary)System.Windows.Markup.XamlReader.Load(xmlReader);

            //var keys = GetColorKeys();

            //foreach (var key in keys)
            //{
            //    fontAndColorDictionary[key] = Brushes.Pink;
            //}

            Hashtable hashTable = new Hashtable();

            foreach (var key in fontAndColorDictionary.Keys)
            {
                hashTable.Add(key, fontAndColorDictionary[key]);
            }

            wfDesigner.PropertyInspectorFontAndColorData = XamlServices.Save(hashTable);

            //load Workflow Xaml
            wfDesigner.Load(sourceFile);
            //var g = wfDesigner.View as Grid;
            //g.Background = Brushes.Pink;
            return(wfDesigner);
        }
		public void Should_serialize_attached_property()
		{
			var root = new SampleRoot();
			AttachablePropertyServices.SetProperty(root, OseSchema.VersionProperty, 1.2m);
			AttachablePropertyServices.SetProperty(root, TestAttacher.SoundProperty, 15);
			var xaml = XamlServices.Save(root);
			var load = XamlServices.Parse(xaml);
			Trace.WriteLine(xaml);
			decimal val;
			AttachablePropertyServices.TryGetProperty(root, OseSchema.VersionProperty, out val);
			int snd;
			AttachablePropertyServices.TryGetProperty(root, TestAttacher.SoundProperty, out snd);
			Assert.AreEqual(1.2m, val);
			Assert.AreEqual(15, snd);
		}
Exemplo n.º 19
0
 public static string SerializeXaml <T>(T from)
 {
     try
     {
         using (var sw = new StringWriter())
         {
             XamlServices.Save(sw, from);
             return(sw.ToString());
         }
     }
     catch (Exception ex)
     {
         throw new SerializationException(string.Format("Error serializing object of type {0}", from.GetType().FullName), ex);
     }
 }
Exemplo n.º 20
0
        public void TestXaml()
        {
            var srcobj = new MyVectorClass
            {
                Point       = new Vector2(0.13f, 2),
                Position    = new Vector3(0.13f, 2, 145.2f),
                ScreenPos   = new Vector4(0.13f, 2, 145.2f, 0.0f),
                Orientation = new Quaternion(0.13f, 2, 145.2f, 1.0f),
                Transform   = new Matrix4x4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
            };
            var ser      = XamlServices.Save(srcobj);
            var deserobj = XamlServices.Parse(ser) as MyVectorClass;

            Assert.Equal(srcobj.ScreenPos, deserobj?.ScreenPos);
        }
Exemplo n.º 21
0
        public void Write_NamedItems()
        {
            // foo
            // - bar
            // -- foo
            // - baz
            var obj  = new NamedItem("foo");
            var obj2 = new NamedItem("bar");

            obj.References.Add(obj2);
            obj.References.Add(new NamedItem("baz"));
            obj2.References.Add(obj);

            Assert.AreEqual(ReadXml("NamedItems.xml").Trim(), XamlServices.Save(obj), "#1");
        }
        public static InArgument <CorrelationHandle> CreateReplyCorrelatesWith(InArgument <CorrelationHandle> requestCorrelatesWith)
        {
            VariableValue <CorrelationHandle> expression = requestCorrelatesWith.Expression as VariableValue <CorrelationHandle>;

            if (expression != null)
            {
                return(new InArgument <CorrelationHandle>(expression.Variable));
            }
            VisualBasicValue <CorrelationHandle> value3 = requestCorrelatesWith.Expression as VisualBasicValue <CorrelationHandle>;

            if (value3 != null)
            {
                return(new InArgument <CorrelationHandle>(new VisualBasicValue <CorrelationHandle>(value3.ExpressionText)));
            }
            return(new InArgument <CorrelationHandle>(XamlServices.Parse(XamlServices.Save(requestCorrelatesWith.Expression)) as Activity <CorrelationHandle>));
        }
Exemplo n.º 23
0
        public void XamlServicesSave_ShouldSerialiseToISO8601_GivenLocalisedDateTimeWithMilliseconds()
        {
            var usTimeZone        = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
            var localisedDateTime = TimeZoneInfo.ConvertTimeFromUtc(
                new DateTime(2015, 12, 30, 23, 50, 51, DateTimeKind.Utc),
                usTimeZone);
            var testData = new TestDateTimeDto {
                Created = localisedDateTime
            };

            testData.Created = testData.Created.AddMilliseconds(11);
            var result = XamlServices.Save(testData);

            Console.WriteLine(result);
            Assert.IsTrue(result.Contains("2015-12-30T15:50:51.011"));
        }
Exemplo n.º 24
0
        string XamlWrite(object objectGraph)
        {
            var sw       = new StringWriter(CultureInfo.CurrentCulture);
            var settings = new XmlWriterSettings
            {
                Indent             = true,
                IndentChars        = "\t",
                OmitXmlDeclaration = true,
            };

            using (var writer = XmlWriter.Create(sw, settings))
            {
                XamlServices.Save(writer, objectGraph);
            }
            return(sw.ToString());
        }
Exemplo n.º 25
0
        public static string ToXaml(Activity activity)
        {
            var          sBuilder = new StringBuilder();
            StringWriter tw       = new StringWriter(sBuilder);
            XamlWriter   xw       = ActivityXamlServices.CreateBuilderWriter(new XamlXmlWriter(tw, new XamlSchemaContext()));

            using (xw)
            {
                var activityBuilder =
                    new ActivityBuilder {
                    Implementation = activity
                };
                XamlServices.Save(xw, activityBuilder);
            }
            return(sBuilder.ToString());
        }
Exemplo n.º 26
0
    static void Main()
    {
        Item newItem = new Item("http://foo", "test1", 1.0);
        var  values  = new Dictionary <int, Item>();

        values.Add(1, newItem);
        var builder = new StringBuilder();

        XamlServices.Save(new StringWriter(builder), values);
        var data = builder.ToString();

        Console.WriteLine(data.ToString());
        var result = (Dictionary <int, Item>)XamlServices.Load(new StringReader(data));

        Console.WriteLine(result.ToString());
    }
Exemplo n.º 27
0
        public void RoundtripTest1()
        {
            StringBuilder sb   = new StringBuilder();
            Motorboat     boat = new SpeedBoat {
                MaxSpeed = 100
            };

            XamlServices.Save(XmlWriter.Create(sb), new VSContainer {
                Vehicle = boat
            });
            VSContainer c         = (VSContainer)XamlServices.Parse(sb.ToString());
            SpeedBoat   speedBoat = c.Vehicle as SpeedBoat;

            Assert.IsNotNull(speedBoat);
            Assert.AreEqual(speedBoat.MaxSpeed, 100);
        }
        public MainWindow()
        {
            InitializeComponent();

            using (var reader = new XamlXmlReader("./Button.xaml"))
                using (var writer = new XamlXmlWriter(new FileStream("./Test.xaml", FileMode.Create), reader.SchemaContext))
                {
                    while (reader.Read())
                    {
                        writer.WriteNode(reader);
                    }
                }

            using (var reader = new XamlObjectReader(new Button()))
                using (var writer = new XamlObjectWriter(reader.SchemaContext))
                {
                    while (reader.Read())
                    {
                        writer.WriteNode(reader);
                    }

                    var button = (Button)writer.Result;
                }

            using (var reader = new XamlXmlReader(new StringReader("<Button xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">This is a button</Button>")))
                using (var writer = new XamlObjectWriter(reader.SchemaContext))
                {
                    while (reader.Read())
                    {
                        writer.WriteNode(reader);
                    }

                    var button = (Button)writer.Result;
                }

            var button1 = (Button)XamlServices.Load("./Button.xaml");
            var button2 = XamlServices.Load(new XamlObjectReader(new Button()));
            var button3 = XamlServices.Load(new StringReader("<Button xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">This is a button</Button>"));
            var button4 = XamlServices.Parse("<Button xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">This is a button</Button>");

            XamlServices.Save("./Test2.xaml", new Button());

            //DispatcherObject methods, hidden from intellisense via the EditorBrowsableAttribute
            button1.CheckAccess();
            button1.VerifyAccess();
        }
Exemplo n.º 29
0
 /// <summary>
 /// Сохранить игровую конфигурацию
 /// </summary>
 /// <param name="programPath">Путь расположения исполняемого файла клиента</param>
 internal void Save()
 {
     try
     {
         using (var file = IsolatedStorageFile.GetUserStoreForAssembly())
         {
             using (var stream = new IsolatedStorageFileStream(ConfigFile, FileMode.Create, FileAccess.Write, file))
             {
                 XamlServices.Save(stream, this);
             }
         }
     }
     catch (Exception exc)
     {
         MessageBox.Show(exc.Message);
     }
 }
Exemplo n.º 30
0
        }//end

        //从[xaml]字串得到[ActivityBuilder]对象
        public static string xamlFromActivityBuilder(ActivityBuilder activityBuilder)
        {
            string xamlString = "";

            StringBuilder stringBuilder = new StringBuilder();

            System.IO.StringWriter stringWriter = new System.IO.StringWriter(stringBuilder);

            XamlSchemaContext xamlSchemaContext = new XamlSchemaContext();
            XamlXmlWriter     xamlXmlWriter     = new XamlXmlWriter(stringWriter, xamlSchemaContext);
            XamlWriter        xamlWriter        = ActivityXamlServices.CreateBuilderWriter(xamlXmlWriter);

            XamlServices.Save(xamlWriter, activityBuilder);
            xamlString = stringBuilder.ToString();

            return(xamlString);
        }