Esempio n. 1
0
        /// <summary>
        /// シリアライズ
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static byte[] Serialize <T>(this T value)
        {
            if (value.GetType().IsValueType)
            {
                switch (value)
                {
                case int _:
                case long _:
                case bool _:
                case char _:
                case short _:
                case ushort _:
                case uint _:
                case ulong _:
                case float _:
                case double _:
                    return(BitConverter.GetBytes((dynamic)value));

                case byte[] val:
                    return(val);

                default:
                    var size  = Marshal.SizeOf(value);
                    var bytes = new byte[size];
                    var ptr   = Marshal.AllocHGlobal(size);
                    Marshal.StructureToPtr(value, ptr, false);

                    Marshal.Copy(ptr, bytes, 0, size);

                    Marshal.FreeHGlobal(ptr);
                    return(bytes);
                }
            }

            switch (value)
            {
            case string s:
                return(Encoding.UTF8.GetBytes(s));

            default:
                return(Encoding.UTF8.GetBytes(XamlServices.Save(value)));
            }
        }
Esempio n. 2
0
        public void Write_NamedItems2()
        {
            // i1
            // - i2
            // -- i3
            // - i4
            // -- i3
            var obj  = new NamedItem2("i1");
            var obj2 = new NamedItem2("i2");
            var obj3 = new NamedItem2("i3");
            var obj4 = new NamedItem2("i4");

            obj.References.Add(obj2);
            obj.References.Add(obj4);
            obj2.References.Add(obj3);
            obj4.References.Add(obj3);

            Assert.AreEqual(ReadXml("NamedItems2.xml").Trim(), XamlServices.Save(obj), "#1");
        }
Esempio n. 3
0
        private void SetXamlSerializedPackagePartValue(object value, PackagePart part)
        {
            if (value == null)
            {
                return;
            }

            using (Stream stream = part.GetStream(FileMode.Create))
            {
                string partStr = XamlServices.Save(value);
                using (stream)
                {
                    using (StreamWriter writer = new StreamWriter(stream))
                    {
                        writer.Write(partStr);
                    }
                }
            }
        }
Esempio n. 4
0
 public void Evaluate(int SpreadMax)
 {
     FOutput.SliceCount = FError.SliceCount = _input.Pin.SliceCount;
     for (int i = 0; i < _input.Pin.SliceCount; i++)
     {
         if (FSet[i])
         {
             try
             {
                 FOutput[i] = XamlServices.Save(_input[i]);
                 FError[i]  = "";
             }
             catch (Exception e)
             {
                 FError[i] = e.Message;
             }
         }
     }
 }
Esempio n. 5
0
        public object DuplicateArityLoader(string xamlString)
        {
            var scSettings = new XamlSchemaContextSettings();

            scSettings.SupportMarkupExtensionsWithDuplicateArity = true;
            var              xsc       = new XamlSchemaContext(scSettings);
            var              xmlReader = XmlReader.Create(new StringReader(xamlString));
            XamlReader       reader    = new XamlXmlReader(xmlReader, xsc);
            XamlObjectWriter objWriter = new XamlObjectWriter(reader.SchemaContext);

            XamlServices.Transform(reader, objWriter);
            object root = objWriter.Result;

            if (root == null)
            {
                throw new NullReferenceException("Load returned null Root");
            }
            return(root);
        }
Esempio n. 6
0
        /// <summary>
        /// Initializes a new instance of the HomeScreenViewModel class that loads model content from the given Uri
        /// </summary>
        /// <param name="modelContentUri">Uri to the collection of AttractScreenImage models to be loaded</param>
        public HomeScreenViewModel(Uri modelContentUri)
            : base()
        {
            this.LoadModels(PackUriHelper.CreatePackUri(DefaultAttractScreenModelContent));
            this.CurrentImage = this.Images[this.currentIndex];

            this.experienceSelected = new RelayCommand <RoutedEventArgs>(this.OnExperienceSelected);

            using (Stream experienceModelsStream = Application.GetResourceStream(modelContentUri).Stream)
            {
                var experiences = XamlServices.Load(experienceModelsStream) as IList <ExperienceOptionModel>;
                if (null == experiences)
                {
                    throw new InvalidDataException();
                }

                this.Experiences = new ObservableCollection <ExperienceOptionModel>(experiences);
            }
        }
        //从[ActivityBuilder]对象得到[xaml]字串
        public static ActivityBuilder activityBuilderFromXaml(string xaml)
        {
            ActivityBuilder activityBuilder = null;

            System.IO.StringReader stringReader  = new System.IO.StringReader(xaml);
            XamlXmlReader          xamlXmlReader = new XamlXmlReader(stringReader);
            XamlReader             xamlReader    = ActivityXamlServices.CreateBuilderReader(xamlXmlReader);

            activityBuilder = XamlServices.Load(xamlReader) as ActivityBuilder;

            if (activityBuilder != null)
            {
                return(activityBuilder);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 8
0
        private T GetXamlSerializedPackagePartValue <T>(PackagePart part) where T : class
        {
            if (part == null)
            {
                return(null);
            }

            T obj = null;

            using (Stream stream = part.GetStream(FileMode.Open))
            {
                if (stream.Length == 0)
                {
                    return(null);
                }
                obj = (T)XamlServices.Load(stream);
            }
            return(obj);
        }
        /// <summary>
        /// Use the common dialog to save the settings to a file.
        /// </summary>
        /// <param name="fileName">settings file name to start with</param>
        /// <param name="settings">the settings to save</param>
        public static void SaveSettings(string fileName, Settings settings)
        {
            var saveFileDialog = new SaveFileDialog
            {
                FileName         = Path.GetFileName(fileName),
                InitialDirectory = Path.GetDirectoryName(fileName),
                DefaultExt       = DefaultFileExtension,
                Filter           = Properties.Resources.FileDialogFilter
            };

            if (saveFileDialog.ShowDialog() == false)
            {
                // User canceled the dialog.  Quietly return.
                return;
            }

            fileName = saveFileDialog.FileName;

            var settingsXmlString = XamlServices.Save(settings);

            try
            {
                using (var streamWriter = new StreamWriter(fileName))
                {
                    streamWriter.Write(settingsXmlString);
                }
            }
            catch (Exception e)
            {
                if (e is IOException || e is UnauthorizedAccessException)
                {
                    // Couldn't save for a reason we expect.  Show an error message.
                    var errorMessageText = string.Format(CultureInfo.CurrentCulture, Properties.Resources.SaveErrorMessage, fileName);
                    MessageBox.Show(
                        errorMessageText, Properties.Resources.ErrorMessageCaption, MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    throw;
                }
            }
        }
Esempio n. 10
0
        private void addFromAnotherCafeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "Qc File|*.qc";

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    using (ZipArchive zip = ZipFile.Open(openFileDialog.FileName, ZipArchiveMode.Read))
                    {
                        foreach (ZipArchiveEntry entry in zip.Entries)
                        {
                            if (entry.Name == "FLOW_NAMES")
                            {
                                VALUES_FROM_CAFE.FLOW_NAMES = (List <string>)XamlServices.Load(entry.Open());
                            }

                            if (VALUES_FROM_CAFE.FLOW_NAMES.Any())
                            {
                                foreach (var flow in VALUES_FROM_CAFE.FLOW_NAMES)
                                {
                                    if (!Flows_List.Items.Contains(flow))
                                    {
                                        Flows_List.Items.Add(flow);
                                        int count = Flows_List.Items.Count;
                                        Flow_Count_ListBox.Items.Add(count + ".");
                                        dataGridView.Rows.Add(flow);
                                    }
                                }

                                Flows_List.ClearSelected();
                                Flow_Empty_Label.Visible = false;
                            }
                            else
                            {
                                Flow_Empty_Label.Visible = true;
                            }
                        }
                    }
                }
            }
        }
Esempio n. 11
0
        /// <summary>
        ///     Initializes a new instance of the HomeScreenViewModel class that loads model content from the given Uri
        /// </summary>
        /// <param name="modelContentUri">Uri to the collection of AttractScreenImage models to be loaded</param>
        public HomeScreenViewModel(Uri modelContentUri)
        {
            experienceSelected = new RelayCommand <RoutedEventArgs>(OnExperienceSelected);

            var streamResourceInfo = Application.GetResourceStream(modelContentUri);

            if (streamResourceInfo != null)
            {
                using (Stream experienceModelsStream = streamResourceInfo.Stream)
                {
                    var experiences = XamlServices.Load(experienceModelsStream) as IList <ExperienceOptionModel>;
                    if (null == experiences)
                    {
                        throw new InvalidDataException();
                    }

                    Experiences = new ObservableCollection <ExperienceOptionModel>(experiences);
                }
            }
        }
Esempio n. 12
0
        public void Save_Variables()
        {
            var path     = $@"..\..\..\Activities\XAMLs\{nameof(Save_Variables)}.xaml";
            var expected = File.ReadAllText(path);

            var vs = new WorkflowVariables();

            vs.Variables.Add(new Variable {
                Type = typeof(int), VariableName = "i", Value = "123"
            });
            vs.Variables.Add(new Variable {
                Type = typeof(double), VariableName = "sum", Value = "1.0"
            });
            vs.Variables.Add(new Variable {
                Type = typeof(string), VariableName = "Message", Value = "Hello"
            });

            Assert.AreEqual(expected, XamlServices.Save(vs));
            var o = (WorkflowVariables)XamlServices.Parse(expected);
        }
        public void SerializeStringWithAttachedProperty()
        {
            string s = "Something";

            SetBar(s, 98);

            Assert.IsTrue(GetBar(s) == 98);
            Assert.IsTrue(AttachablePropertyServices.GetAttachedPropertyCount(s) == 1);

            var expected = @"<x:String AttachablePropertyServicesTests.Bar=""98"" xmlns=""clr-namespace:DrtXaml.Tests;assembly=DrtXaml"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">Something</x:String>";

            string generated = XamlServices.Save(s);

            Assert.AreEqual(expected, generated);

            //string result = (string)RoundTrip(s, expected);

            //Assert.IsTrue(result != null);
            //Assert.IsTrue(GetBar(result) == 98);
        }
Esempio n. 14
0
        private void Form_Load(object sender, RoutedEventArgs e)
        {
            con.Open();
            MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT product.*,typeproduct.typepName,typeunit.typenameUnit FROM product left join typeproduct on product.typepID=typeproduct.typepID left join typeunit on product.typeunitID=typeunit.typeunitID ORDER BY product.proID", con);
            DataSet          dt      = new DataSet();

            adapter.Fill(dt);
            dataGrid.ItemsSource    = dt.Tables[0].DefaultView;
            dataGrid.CanUserAddRows = false;
            con.Close();

            if (sendCount == "1")
            {
                dataGrid.Columns[3].CellStyle = (Style)XamlServices.Parse("<Style xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"  xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" TargetType=\"{x:Type DataGridCell}\"> <Setter Property=\"Background\" Value=\"Black\"></Setter></Style>");
            }
            else
            {
                dataGrid.Columns[2].CellStyle = (Style)XamlServices.Parse("<Style xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"  xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" TargetType=\"{x:Type DataGridCell}\"> <Setter Property=\"Background\" Value=\"Black\"></Setter></Style>");
            }
        }
        public string Save(object instance)
        {
            var sb = new StringBuilder();

            var xmlsettings = new XmlWriterSettings
            {
                NewLineOnAttributes = true,
                Indent = true,
                IndentChars = "\t",
                OmitXmlDeclaration = false,
                NewLineHandling = NewLineHandling.None,
            };

            var xmlwriter = XmlWriter.Create(sb, xmlsettings);

            var xamlschema = new XamarinFormsSchemaContext(new XamlSchemaContextSettings());
            var xxwriter = new XamlXmlWriter(xmlwriter, xamlschema);
            XamlServices.Save(xxwriter, instance);
            return sb.ToString();
        }
Esempio n. 16
0
        public void Binding()
        {
            string xaml = @"
<Button xmlns=""clr-namespace:A2v10.System.Xaml.Tests.Mock;assembly=A2v10.System.Xaml.Tests"" 
	Content=""Text"" Command=""{BindCmd Execute, CommandName='File'}"">
</Button>
";
            var    obj  = XamlServices.Parse(xaml, null);

            Assert.AreEqual(typeof(Button), obj.GetType());
            var btn = obj as Button;

            Assert.AreEqual("Text", btn.Content);

            var cmd = btn.GetBindingCommand("Command");

            Assert.AreEqual(typeof(BindCmd), cmd.GetType());
            Assert.AreEqual("Execute", cmd.Command.ToString());
            Assert.AreEqual("File", cmd.CommandName);
        }
Esempio n. 17
0
        public XamlParser(string path)
        {
            // load and store properties from xaml file
            m_parsedBuildRule = (Rule)XamlServices.Load(path);

            // NOTE:
            // There are MSBuild classes which support command line building,
            // argument switch encapsulation and more.  Code within VCToolTask,
            // a hidden interface, uses some these classes to generate command line
            // switches given project settings. As the VCToolTask class is a hidden
            // class and the MSBuild documentation is very sparse, we are going
            // with a small custom solution.  For reference see the
            // Microsoft.Build.Tasks.Xaml, Microsoft.Build.Framework.XamlTypes namespaces.

            // move the properties to a property name keyed dictionary for faster lookup
            ToolProperties = new Dictionary <string, PropertyWrapper>();
            ToolProperties = m_parsedBuildRule.Properties.ToDictionary(x => x.Name, x => (new PropertyWrapper(x.GetType(), x)));

            InitFunctionMap();
        }
Esempio n. 18
0
        public void QualifiedProperty()
        {
            string xaml = @"
<Page xmlns=""clr-namespace:A2v10.System.Xaml.Tests.Mock;assembly=A2v10.System.Xaml.Tests"">
	<Page.Toolbar>
		<Button Content=""{Bind Parent.Pager}""/>
	</Page.Toolbar>
</Page>
";
            var    obj  = XamlServices.Parse(xaml, null);

            Assert.AreEqual(typeof(Page), obj.GetType());
            var page = obj as Page;
            var tb   = page.Toolbar as Button;

            Assert.AreEqual(typeof(Button), tb.GetType());
            var bind = tb.GetBinding("Content");

            Assert.AreEqual("Parent.Pager", bind.Path);
        }
		public void Should_30_get_collections_by_iterator()
		{
			string original;
			var d = Dynamic(original = @"<SampleRoot Name='abc' xmlns='test'>
	<SampleRoot.Collection>
		<SampleItem FirstName='Bob' />
		<SampleItem FirstName='Alice' />
	</SampleRoot.Collection>
</SampleRoot>");
			// make sure it is good
			XamlServices.Parse(original);

			byte i = 0;
			foreach (var item in d.Collection)
			{
				AreEqual(i==0? "Bob":"Alice", item.FirstName);
				i++;
			}

		}
Esempio n. 20
0
        private static T ActivateInstanceFromXaml <T>(string xaml, string typeName)
        {
            var referencedAssembly = typeof(T).Assembly;
            var path    = new[] { new Uri(referencedAssembly.CodeBase).LocalPath };
            var context = new XamlSchemaContext();

            using (var xamlReader = new StringReader(xaml))
                using (var reader = new XamlXmlReader(xamlReader, context))
                    using (var writer = new BinaryXamlWriter(context, "test", new Version(), path))
                        using (var stream = new MemoryStream())
                        {
                            XamlServices.Transform(reader, writer);

                            writer.WriteAssembly(stream);
                            var bytes    = stream.ToArray();
                            var assembly = Assembly.Load(bytes);
                            var type     = assembly.ExportedTypes.Single(t => t.Name == typeName);
                            return((T)Activator.CreateInstance(type));
                        }
        }
        public void SimplePadding()
        {
            string xaml = @"
<Button xmlns=""clr-namespace:A2v10.System.Xaml.Tests.Mock;assembly=A2v10.System.Xaml.Tests"" 
	Content=""Text"" Padding=""11,22,33,44"">
</Button>
";
            var    obj  = XamlServices.Parse(xaml, null);

            Assert.AreEqual(typeof(Button), obj.GetType());
            var btn = obj as Button;

            Assert.AreEqual("Text", btn.Content);
            var p = btn.Padding;

            Assert.AreEqual(Length.FromString("11").Value, p.Top.Value);
            Assert.AreEqual(Length.FromString("22").Value, p.Right.Value);
            Assert.AreEqual(Length.FromString("33").Value, p.Bottom.Value);
            Assert.AreEqual(Length.FromString("44").Value, p.Left.Value);
        }
Esempio n. 22
0
        /// <summary>
        ///     Deserializes the active state of buttons in the toolbar.
        /// </summary>
        /// <param name="xamlData">A string containing the new state of the toolbar.</param>
        public virtual void DeserializeActiveButtons(string xamlData)
        {
            Assert.ValidateReference(xamlData);

            try
            {
                bool[] ActiveTable = (bool[])XamlServices.Parse(xamlData);
                for (int i = 0; i < AllButtons.Count && i < ActiveTable.Length; i++)
                {
                    AllButtons[i].Button.IsActive = ActiveTable[i];
                }
            }
            catch (Exception e)
            {
                if (e.Message == null) // To make the code analyzer happy. Since the doc of XamlServices.Parse() doesn't specify any exception other than NullException, this should safe, right?...
                {
                    throw;
                }
            }
        }
Esempio n. 23
0
        public void StaticResource_Style_ResourceOnLocal_NoBase()
        {
            string xaml    = @"
<Border xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <Border.Resources>
        <Style x:Key='b' TargetType='Button'>
            <Style.Resources>
                <x:String x:Key='s'>test</x:String>
            </Style.Resources>
            <Setter Property='Content' Value='{StaticResource s}'/>
        </Style>
    </Border.Resources>
    <Button Style='{StaticResource b}'/>
</Border>";
            Border border  = (Border)XamlServices.Parse(xaml);
            Button button  = (Button)border.Child;
            string content = (string)button.Content;

            Assert.AreEqual(content, "test");
        }
Esempio n. 24
0
        /// <summary>
        /// 設定ロード
        /// </summary>
        public void Load()
        {
            this.LoadDefault();
            if (!File.Exists(this._settingsFilePath))
            {
                Console.WriteLine("設定ファイルなし");
                return;
            }

            try {
                if (!(XamlServices.Load(this._settingsFilePath) is Dictionary <string, dynamic> settings))
                {
                    Console.WriteLine("設定ファイル読み込み失敗");
                    return;
                }

                this.Import(settings);
            } catch (XmlException ex) {
                Console.WriteLine($"設定ファイル読み込み失敗{ex}");
            }
        }
Esempio n. 25
0
        [Category(Categories.NotOnSystemXaml)]         // System.Xaml doesn't use typeconverters nor passes the value
        public void Read_CollectionWithContentWithConverter()
        {
            if (!Compat.IsPortableXaml)
            {
                Assert.Ignore("System.Xaml doesn't use typeconverters nor passes the value");
            }

            var xaml   = @"<CollectionParentItem xmlns='clr-namespace:MonoTests.Portable.Xaml;assembly=Portable.Xaml_test_net_4_0'><CollectionItem Name='Item1'/>SomeContent</CollectionParentItem>".UpdateXml();
            var parent = (CollectionParentItem)XamlServices.Load(new StringReader(xaml));

            Assert.IsNotNull(parent, "#1");
            Assert.IsInstanceOf <CollectionParentItem>(parent, "#2");
            Assert.AreEqual(2, parent.Items.Count, "#3");
            var item = parent.Items[0];

            Assert.IsNotNull(item, "#4");
            Assert.AreEqual("Item1", item.Name, "#5");
            item = parent.Items[1];
            Assert.IsNotNull(item, "#6");
            Assert.AreEqual("SomeContent", item.Name, "#7");
        }
Esempio n. 26
0
 public ActivityBuilder ReadXamlDefinition(StringBuilder xaml)
 {
     try
     {
         if (xaml != null && xaml.Length != 0)
         {
             using (var sw = new StringReader(xaml.ToString()))
             {
                 var xamlXmlWriterSettings = new XamlXmlReaderSettings();
                 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);
 }
        private void SaveObject(object element, XmlWriter writer)
        {
            if (element == null)
            {
                throw new ArgumentNullException(nameof(element));
            }

            if (IsSequenceType(element.GetType()))
            {
                throw new ArgumentException(
                          "Root serialized element must not be a sequence type", nameof(element));
            }

            var xamlWriter = new XamlXmlWriter(writer, schemaContext);

            XamlServices.Transform(
                new XamlObjectReader(element, xamlWriter.SchemaContext),
                xamlWriter, false);
            // Do not dispose XamlXmlWriter because it unconditionally closes the
            // base XmlWriter.
        }
Esempio n. 28
0
        public virtual object StandardXamlLoader(string xamlString)
        {
            var          xamlXmlReader = new XamlXmlReader(XmlReader.Create(new StringReader(xamlString)));
            XamlNodeList xamlNodeList  = new XamlNodeList(xamlXmlReader.SchemaContext);

            XamlServices.Transform(xamlXmlReader, xamlNodeList.Writer);

            NodeListValidator.Validate(xamlNodeList);

            XamlReader       reader    = xamlNodeList.GetReader();
            XamlObjectWriter objWriter = new XamlObjectWriter(reader.SchemaContext);

            XamlServices.Transform(reader, objWriter);
            object root = objWriter.Result;

            if (root == null)
            {
                throw new NullReferenceException("Load returned null Root");
            }
            return(root);
        }
Esempio n. 29
0
        /// <summary>
        /// 比較的きれいなXAMLを返す
        /// </summary>
        /// <returns></returns>
        public string ToCleanXAML()
        {
            StringBuilder xaml = new StringBuilder(XamlServices.Save(this));

            xaml = xaml.Replace("\"{x:Null}\"", "Null").Replace(" Enable=\"True\"", "").Replace(" Comment=\"\"", "");

            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\w*=Null");
            List <string> list = new List <string>();

            foreach (System.Text.RegularExpressions.Match item in regex.Matches(xaml.ToString()))
            {
                list.Add(item.Value);
            }

            foreach (var item in list.Distinct())
            {
                xaml = xaml.Replace(" " + item, string.Empty);
            }

            return(xaml.ToString());
        }
Esempio n. 30
0
        public void Write_ReadOnlyPropertyContainer()
        {
            var obj = new ReadOnlyPropertyContainer()
            {
                Foo = "x"
            };

            Assert.AreEqual(ReadXml("ReadOnlyPropertyContainer.xml").Trim(), XamlServices.Save(obj), "#1");

            var sw = new StringWriter();
            var xw = new XamlXmlWriter(sw, new XamlSchemaContext());
            var xt = xw.SchemaContext.GetXamlType(obj.GetType());

            xw.WriteStartObject(xt);
            xw.WriteStartMember(xt.GetMember("Bar"));
            xw.WriteValue("x");
            xw.WriteEndMember();
            xw.WriteEndObject();
            xw.Close();
            Assert.IsTrue(sw.ToString().IndexOf("Bar") > 0, "#2");                // it is not rejected by XamlXmlWriter. But XamlServices does not write it.
        }