public List <RecordingIlEmitter.RecordedInstruction> Compile( XamlDocument doc, IXamlType contextType, IXamlMethodBuilder <TBackendEmitter> populateMethod, IXamlMethodBuilder <TBackendEmitter> buildMethod, IXamlTypeBuilder <TBackendEmitter> namespaceInfoBuilder, Func <string, IXamlType, IXamlTypeBuilder <TBackendEmitter> > createClosure, string baseUri, IFileSource fileSource) { var rootGrp = (XamlValueWithManipulationNode)doc.Root; var rootType = rootGrp.Type.GetClrType(); var context = CreateRuntimeContext(doc, contextType, namespaceInfoBuilder, baseUri, rootType); var populateInstructions = CompilePopulate( fileSource, rootGrp.Manipulation, createClosure, populateMethod.Generator, context); if (buildMethod != null) { CompileBuild(fileSource, rootGrp.Value, null, buildMethod.Generator, context, populateMethod); } namespaceInfoBuilder?.CreateType(); return(populateInstructions); }
void CloseTab_Executed(object sender, ExecutedRoutedEventArgs args) { if (sender == this) { XamlDocument document = null; if (args.Parameter != null) { document = args.Parameter as XamlDocument; } else if (this.DocumentsView.SelectedView != null) { document = this.DocumentsView.SelectedView.XamlDocument; } if (document != null) { if (document.NeedsSave) { MessageBoxResult result = MessageBox.Show("The document " + document.Filename + " has not been saved. Would you like to save it before closing?", "Save Document", MessageBoxButton.YesNoCancel); if (result == MessageBoxResult.Yes) { document.Save(); } if (result == MessageBoxResult.Cancel) { return; } } this.DocumentsView.XamlDocuments.Remove(document); } } }
public string Convert(string workflowXaml) { XamlDocument document = xamlParser.Parse(workflowXaml); ClassCode classCode = classGenerator.Generate(document); return(classCodeToCSharp.Convert(classCode)); }
public static XamlDocument Parse(TextReader reader, Dictionary <string, string> compatibilityMappings = null) { var xr = XmlReader.Create(reader, new XmlReaderSettings { IgnoreWhitespace = true, DtdProcessing = DtdProcessing.Ignore }); xr = new CompatibleXmlReader(xr, compatibilityMappings ?? new Dictionary <string, string>()); var root = XDocument.Load(xr, LoadOptions.SetLineInfo).Root; var doc = new XamlDocument { Root = new ParserContext(root).Parse() }; foreach (var attr in root.Attributes()) { if (attr.Name.NamespaceName == "http://www.w3.org/2000/xmlns/" || (attr.Name.NamespaceName == "" && attr.Name.LocalName == "xmlns")) { var name = attr.Name.NamespaceName == "" ? "" : attr.Name.LocalName; doc.NamespaceAliases[name] = attr.Value; } } return(doc); }
public bool SaveAs(XamlDocument document) { if (_SaveDialog == null) { _SaveDialog = new SaveFileDialog(); _SaveDialog.AddExtension = true; _SaveDialog.DefaultExt = ".xaml"; _SaveDialog.Filter = "XAML file|*.xaml|All files|*.*"; } _SaveDialog.FileName = document.Filename; if ((bool)_SaveDialog.ShowDialog()) { if (document.SaveAs(_SaveDialog.FileName)) { return(true); } MessageBox.Show("The file could not be saved as " + _SaveDialog.FileName + "."); return(false); } return(false); }
public ClassCode Generate(XamlDocument document) { var result = new ClassCode { Name = document.Name, CodeBlocks = new List <Code>(), UsingNamespaces = new List <string>(), Namespace = document.Namespace }; IEnumerable <XElement> children = document.Elements; foreach (var child in children) { string name = child.Name.LocalName; switch (name) { case "Members": result.CodeBlocks.AddRange(GetProperties(child)); break; case "TextExpression.NamespacesForImplementation": result.UsingNamespaces.AddRange(GetNamespaces(child)); break; case "Sequence": result.CodeBlocks.Add(methodGenerator.Generate(child)); break; } } customMethodAlocator.Allocate(result.CodeBlocks); return(result); }
private bool Register(XamlDocument document, DocumentNodePath nodePath) { if (document != null && this.GetWatcher(document).Register(nodePath) && !this.chainUpdate.Contains(document)) { this.chainUpdate.Enqueue(document); } return(true); }
public XamlDocumentEditor(XamlDocument xaml) { InitializeComponent(); Xaml = xaml; LoadFromFile(Xaml); codeEditor.Buddy = numbers; }
/// <summary> /// T Build(IServiceProvider sp); /// </summary> public IXamlMethodBuilder <TBackendEmitter> DefineBuildMethod(IXamlTypeBuilder <TBackendEmitter> typeBuilder, XamlDocument doc, string name, bool isPublic) { var rootGrp = (XamlValueWithManipulationNode)doc.Root; return(typeBuilder.DefineMethod(rootGrp.Type.GetClrType(), new[] { _configuration.TypeMappings.ServiceProvider }, name, isPublic, true, false)); }
private void ParseArgs(string[] args) { if (args == null) { return; } for (int i = 0; i < args.Length; i++) { string arg = args[i]; if (arg == "-i") { // Handle the include command. This allows us to add dlls and static resources to the editor string nextArg = (i < args.Length - 1) ? args[i + 1] : null; if (nextArg != null) { try { if (nextArg.StartsWith("pack://")) { XamlResources.Add(nextArg); } else if (System.IO.File.Exists(nextArg)) { if (nextArg.EndsWith(".xaml", StringComparison.InvariantCultureIgnoreCase)) { XamlResources.Add(nextArg); } else if (nextArg.EndsWith(".dll", StringComparison.InvariantCultureIgnoreCase)) { Assembly.LoadFile(nextArg); string dir = System.IO.Path.GetDirectoryName(nextArg); AssemblySearchDirs.Add(dir); } } } catch (Exception ex) { Console.WriteLine(ex); Debug.Fail("Could not load: " + args + " " + nextArg); } } i++; continue; } if (System.IO.File.Exists(arg)) { XamlDocument doc = XamlDocument.FromFile(arg); XamlDocuments.Add(doc); } } }
public static DocumentNode GetExpressionFromString(string text, XamlDocument document, DocumentNode parentNode, Type propertyType, out IList <XamlParseError> errors) { if (parentNode != null) { IType type = document.TypeResolver.GetType(propertyType); return(XamlParser.ParseValue((IDocumentRoot)document, parentNode, type, text, out errors)); } errors = (IList <XamlParseError>)null; return((DocumentNode)null); }
public bool Save(XamlDocument document) { if (document.UsingTemporaryFilename) { return(SaveAs(document)); } else { return(document.Save()); } }
void SaveAs_Executed(object sender, ExecutedRoutedEventArgs args) { if (sender == this) { if (this.DocumentsView.SelectedView != null) { XamlDocument document = this.DocumentsView.SelectedView.XamlDocument; SaveAs(document); } } }
public static IProjectItem CreateDesignDataFile(Type type, string dataSourceName, IProjectContext projectContext, bool isDesignTimeCreatable) { string path1 = Path.Combine(Path.GetDirectoryName(projectContext.ProjectPath), DataSetContext.SampleData.DataRootFolder); string str = dataSourceName ?? type.Name; string path2_1 = str + ".xaml"; string path2 = Path.Combine(path1, path2_1); int num = 1; while (File.Exists(path2)) { string path2_2 = str + num.ToString((IFormatProvider)CultureInfo.InvariantCulture) + ".xaml"; path2 = Path.Combine(path1, path2_2); ++num; } string path3 = Path.GetTempFileName() + ".xaml"; IProjectContext projectContext1 = projectContext; if (!isDesignTimeCreatable) { projectContext1 = (IProjectContext)(projectContext as TypeReflectingProjectContext) ?? (IProjectContext) new TypeReflectingProjectContext(projectContext); } DocumentContext documentContext = new DocumentContext(projectContext1, (IDocumentLocator) new DocumentLocator(path2), false); IType type1 = documentContext.TypeResolver.GetType(type); DocumentNode node = new DesignDataGenerator(type1, (IDocumentContext)documentContext).Build(); try { using (StreamWriter text = File.CreateText(path3)) { using (XamlDocument xamlDocument = new XamlDocument((IDocumentContext)documentContext, (ITypeId)type1, (ITextBuffer) new SimpleTextBuffer(), DocumentEncodingHelper.DefaultEncoding, (IXamlSerializerFilter) new DefaultXamlSerializerFilter())) new XamlSerializer((IDocumentRoot)xamlDocument, (IXamlSerializerFilter) new DefaultXamlSerializerFilter()).Serialize(node, (TextWriter)text); } BuildTaskInfo buildTaskInfo = new BuildTaskInfo(DocumentContextHelper.DesignDataBuildTask, (IDictionary <string, string>) new Dictionary <string, string>()); DocumentCreationInfo creationInfo = new DocumentCreationInfo() { BuildTaskInfo = buildTaskInfo, TargetFolder = path1, TargetPath = path2, SourcePath = path3, CreationOptions = CreationOptions.SilentlyOverwrite | CreationOptions.SilentlyOverwriteReadOnly | CreationOptions.DoNotSelectCreatedItems | CreationOptions.DoNotSetDefaultImportPath }; return(((IProject)projectContext.GetService(typeof(IProject))).AddItem(creationInfo)); } finally { try { File.Delete(path3); } catch { } } }
private ThemeContentProvider.SystemThemeContentProvider GetCachedThemeContent(Dictionary <ThemeContentProvider.PlatformSpecificDocumentReference, ThemeContentProvider.SystemThemeContentProvider> themeCache, ThemeManager manager, IProjectContext projectContext, DocumentReference reference, IAssembly themeAssembly, string themeAssemblyPath, ITextBufferService textBufferService) { ThemeContentProvider.PlatformSpecificDocumentReference key = new ThemeContentProvider.PlatformSpecificDocumentReference(reference, projectContext != null ? projectContext.TargetFramework : (FrameworkName)null); ThemeContentProvider.SystemThemeContentProvider themeContentProvider; if (!themeCache.TryGetValue(key, out themeContentProvider)) { Encoding encoding; ITextBuffer textBuffer = themeAssembly != null?ThemeManager.LoadResource(themeAssembly, themeAssemblyPath, textBufferService, out encoding) : ThemeContentProvider.LoadReference(reference, textBufferService, out encoding); IDocumentLocator documentLocator = DocumentReferenceLocator.GetDocumentLocator(reference); IDocumentContext userContext = projectContext == null ? (IDocumentContext)null : (IDocumentContext) new DocumentContext(projectContext, documentLocator); XamlDocument theme = manager.GetTheme(documentLocator, themeAssembly != null, userContext, textBuffer, encoding); if (theme != null) { bool flag1 = false; try { if (projectContext != null) { if (!projectContext.IsCapabilitySet(PlatformCapability.IsWpf)) { if (themeAssembly != null) { bool flag2 = false; foreach (IAssembly assembly in (projectContext.Platform.Metadata as PlatformTypes).DefaultAssemblyReferences) { if (assembly == themeAssembly) { flag2 = true; break; } } if (flag2) { flag1 = true; AnimationEditor.ConvertFromToAnimations(theme.RootNode); } } } } } catch { if (flag1) { theme = manager.GetTheme(documentLocator, themeAssembly != null, userContext, textBuffer, encoding); } } themeContentProvider = new ThemeContentProvider.SystemThemeContentProvider(this.designerContext, theme); themeCache[key] = themeContentProvider; } } return(themeContentProvider); }
public override ModelItem SetValue(object value) { using (SceneEditTransaction editTransaction = this.CreateEditTransaction()) { ModelItem modelItem = value as ModelItem; if (modelItem != null) { ISceneNodeModelItem sceneNodeModelItem = value as ISceneNodeModelItem; value = sceneNodeModelItem == null?modelItem.GetCurrentValue() : (object)sceneNodeModelItem.SceneNode.DocumentNode; } string text = value as string; if (text != null) { bool flag = true; if (text.StartsWith("{", StringComparison.Ordinal)) { if (text.StartsWith("{}", StringComparison.Ordinal)) { text = text.Substring(2); } else { XamlDocument document = (XamlDocument)this.parent.SceneNode.ViewModel.XamlDocument; DocumentNode parentNode = this.parent.SceneNode.DocumentNode; if (parentNode.DocumentRoot == null) { parentNode = document.RootNode; } IList <XamlParseError> errors; DocumentNode expressionFromString = XamlExpressionSerializer.GetExpressionFromString(text, document, parentNode, this.PropertyType, out errors); if (errors == null || errors.Count == 0) { flag = false; value = (object)expressionFromString; } } } if (flag) { value = (object)this.parent.SceneNode.DocumentContext.CreateNode((ITypeId)this.property.PropertyType, (IDocumentNodeValue) new DocumentNodeStringValue(text)); } } if (value != null && !(value is DocumentNode) && this.parent.SceneNode.ProjectContext.GetType(value.GetType()) == null) { throw new InvalidOperationException(string.Format((IFormatProvider)CultureInfo.CurrentCulture, ExceptionStringTable.TypeIsNotResolveableWithinProject, new object[1] { (object)value.GetType().FullName })); } this.parent.SceneNode.SetValue((IPropertyId)this.property, value); editTransaction.Commit(); } return(this.Value); }
public XamlDocument GetTheme(IDocumentLocator documentLocator, bool isFromAssemblyTheme, IDocumentContext userContext, ITextBuffer textBuffer, Encoding encoding) { XamlDocument xamlDocument = null; if (textBuffer != null && (isFromAssemblyTheme || File.Exists(documentLocator.Path))) { IDocumentContext documentContext = (userContext != null ? userContext : this.ProvideDocumentContext(documentLocator)); XamlParserResults.Parse(documentContext, PlatformTypes.ResourceDictionary, textBuffer); xamlDocument = new XamlDocument(documentContext, PlatformTypes.Object, textBuffer, encoding, new DefaultXamlSerializerFilter()); } return(xamlDocument); }
public static DocumentNode GetExpressionFromString(string text, DocumentNode parentNode, Type propertyType, out IList <XamlParseError> errors) { if (parentNode != null) { XamlDocument document = parentNode.DocumentRoot as XamlDocument; if (document != null) { return(XamlExpressionSerializer.GetExpressionFromString(text, document, parentNode, propertyType, out errors)); } } errors = (IList <XamlParseError>)null; return((DocumentNode)null); }
public ResolvedView ResolveView(string xaml) { _resolvedClass = null; _xaml = XDocumentXamlParser.Parse(xaml, new Dictionary <string, string> { { XamlNamespaces.Blend2008, XamlNamespaces.Blend2008 } }); _compiler.Transform(_xaml); _xaml.Root.Visit(this); _xaml.Root.VisitChildren(this); return(_resolvedClass); }
private void CloseInternal(bool notifyItemsChanged) { this.View = (SceneView)null; if (this.resourceDictionary != null) { this.resourceDictionary.TypesChanged -= new EventHandler(this.DocumentChanged); this.resourceDictionary.RootNodeChanged -= new EventHandler(this.DocumentChanged); this.resourceDictionary = (XamlDocument)null; } if (!notifyItemsChanged) { return; } this.OnItemsChanged(); }
public static string GetStringFromExpression(DocumentNode expression, DocumentNode parentNode) { if (parentNode != null) { XamlDocument xamlDocument = parentNode.DocumentRoot as XamlDocument; if (xamlDocument != null && xamlDocument.DocumentContext != null) { string str = XamlSerializer.SerializeValue((IDocumentRoot)xamlDocument, (IXamlSerializerFilter) new DefaultXamlSerializerFilter(), expression, CultureInfo.CurrentCulture); if (str != null) { return(str); } } } return(string.Empty); }
private void Parse(bool IsExplicit) { ClearDispatcherTimer(); if (XamlDocument != null && !CodeCompletionPopup.IsOpenSomewhere) { if (XamlDocument.SourceText != null) { bool parseSuccess = false; parseSuccess = (bool)this.ContentArea.InvokeScript("ParseXaml", new object[] { XamlDocument.SourceText }); if (parseSuccess) { IsValidXaml = true; ErrorText = null; ErrorLineNumber = 0; ErrorLinePosition = 0; if (Kaxaml.Properties.Settings.Default.EnableAutoBackup) { XamlDocument.SaveBackup(); } DelayedSnapshot(); } else { ErrorText = (string)this.ContentArea.InvokeScript("GetLastErrorMessage", null); ErrorLineNumber = int.Parse((string)this.ContentArea.InvokeScript("GetLastErrorLineNumber", null)); ErrorLinePosition = int.Parse((string)this.ContentArea.InvokeScript("GetLastErrorLinePos", null)); ErrorText = ErrorText.Replace("\r", ""); ErrorText = ErrorText.Replace("\n", ""); ErrorText = ErrorText.Replace("\t", ""); // get rid of everything after "Line" if it is in the last 30 characters int pos = ErrorText.LastIndexOf("[Line"); if (pos > 0 && pos > (ErrorText.Length - 50)) { ErrorText = ErrorText.Substring(0, pos); } IsValidXaml = false; } } } }
public void Compile(XamlDocument doc, IXamlTypeBuilder <TBackendEmitter> typeBuilder, IXamlType contextType, string populateMethodName, string createMethodName, string namespaceInfoClassName, string baseUri, IFileSource fileSource) { var rootGrp = (XamlValueWithManipulationNode)doc.Root; Compile(doc, contextType, DefinePopulateMethod(typeBuilder, doc, populateMethodName, true), createMethodName == null ? null : DefineBuildMethod(typeBuilder, doc, createMethodName, true), _configuration.TypeMappings.XmlNamespaceInfoProvider == null ? null : typeBuilder.DefineSubType(_configuration.WellKnownTypes.Object, namespaceInfoClassName, false), (name, bt) => typeBuilder.DefineSubType(bt, name, false), baseUri, fileSource); }
private bool Unregister(XamlDocument document, DocumentNode node) { if (document != null) { IXamlSubscription watcher = this.GetWatcher(document); bool flag = watcher.Unregister(node); if (watcher.IsEmpty) { watcher.Update(); watcher.Dispose(); this.watchers.Remove(document); } else if (flag && !this.chainUpdate.Contains(document)) { this.chainUpdate.Enqueue(document); } } return(true); }
protected override void OnDrop(DragEventArgs e) { string[] filenames = (string[])e.Data.GetData("FileDrop", true); if ((null != filenames) && (filenames.Length > 0)) { XamlDocument first = null; foreach (string f in filenames) { string ext = System.IO.Path.GetExtension(f).ToLower(); if (ext.Equals(".png") || ext.Equals(".jpg") || ext.Equals(".jpeg") || ext.Equals(".bmp") || ext.Equals(".gif")) { // get a relative version of the file name string rfilename = f.Replace(DocumentsView.SelectedDocument.Folder + "\\", ""); // create and insert the xaml string xaml = Kaxaml.Properties.Settings.Default.PasteImageXaml; xaml = xaml.Replace("$source$", rfilename); this.DocumentsView.SelectedView.TextEditor.InsertStringAtCaret(xaml); } else { XamlDocument doc = XamlDocument.FromFile(f); if (doc != null) { DocumentsView.XamlDocuments.Add(doc); if (first == null) { first = doc; } } } } if (first != null) { DocumentsView.SelectedDocument = first; } } }
public void Compile(XamlDocument doc, IXamlType contextType, IXamlMethodBuilder <TBackendEmitter> populateMethod, IXamlMethodBuilder <TBackendEmitter> buildMethod, IXamlTypeBuilder <TBackendEmitter> namespaceInfoBuilder, Func <string, IXamlType, IXamlTypeBuilder <TBackendEmitter> > createClosure, Func <string, IXamlType, IEnumerable <IXamlType>, IXamlTypeBuilder <TBackendEmitter> > createDelegateType, string baseUri, IFileSource fileSource) { var rootGrp = (XamlValueWithManipulationNode)doc.Root; var rootType = rootGrp.Type.GetClrType(); var context = CreateRuntimeContext(doc, contextType, namespaceInfoBuilder, baseUri, rootType); CompilePopulate(fileSource, rootGrp.Manipulation, createClosure, createDelegateType, populateMethod.Generator, context); if (buildMethod != null) { CompileBuild(fileSource, rootGrp.Value, null, createDelegateType, buildMethod.Generator, context, populateMethod); } namespaceInfoBuilder?.CreateType(); }
private IXamlSubscription GetWatcher(XamlDocument document) { IXamlSubscription xamlSubscription; if (!this.watchers.TryGetValue(document, out xamlSubscription)) { SceneView view = this.FindView(document.DocumentContext); if (view != null) { xamlSubscription = (IXamlSubscription) new XamlProjectSubscription.XamlSceneSubscription(view.ViewModel, this, this.sceneSearch); this.watchers.Add(document, xamlSubscription); } else { xamlSubscription = (IXamlSubscription) new XamlProjectSubscription.XamlDocumentSubscription(document, this, this.documentSearch); this.watchers.Add(document, xamlSubscription); } } return(xamlSubscription); }
public void Transform(XamlDocument doc, bool strict = true) { var ctx = CreateTransformationContext(doc, strict); var root = doc.Root; ctx.RootObject = new XamlRootObjectNode((XamlAstObjectNode)root); foreach (var transformer in Transformers) { ctx.VisitChildren(ctx.RootObject, transformer); root = ctx.Visit(root, transformer); } foreach (var simplifier in SimplificationTransformers) { root = ctx.Visit(root, simplifier); } doc.Root = root; }
public static void TestLoading(string xaml) { Debug.WriteLine("Load using builtin XamlReader:"); ExampleClass.nextUniqueIndex = 0; TestHelperLog.logBuilder = new StringBuilder(); object officialResult = XamlReader.Load(new XmlTextReader(new StringReader(xaml))); string officialLog = TestHelperLog.logBuilder.ToString(); Assert.IsNotNull(officialResult, "officialResult is null"); Debug.WriteLine("Load using own XamlParser:"); ExampleClass.nextUniqueIndex = 0; TestHelperLog.logBuilder = new StringBuilder(); XamlDocument doc = XamlParser.Parse(new StringReader(xaml)); Assert.IsNotNull(doc, "doc is null"); object ownResult = doc.RootInstance; string ownLog = TestHelperLog.logBuilder.ToString(); Assert.IsNotNull(ownResult, "ownResult is null"); TestHelperLog.logBuilder = null; // compare: string officialSaved = XamlWriter.Save(officialResult); string ownSaved = XamlWriter.Save(ownResult); Debug.WriteLine("Official saved:"); Debug.WriteLine(officialSaved); Debug.WriteLine("Own saved:"); Debug.WriteLine(ownSaved); Assert.AreEqual(officialSaved, ownSaved); Debug.WriteLine("Official log:"); Debug.WriteLine(officialLog); Debug.WriteLine("Own log:"); Debug.WriteLine(ownLog); // compare logs: Assert.AreEqual(officialLog, ownLog); }
private async void LoadFromFile(XamlDocument xaml) { if (!File.Exists(xaml.FileName)) { throw new FileNotFoundException(); } using (var reader = File.OpenText(xaml.FileName)) { codeEditor.Text = await reader.ReadToEndAsync(); } numbers.Visible = false; numbers.Clear(); for (var i = 1; i < codeEditor.Lines.Length; i++) { numbers.AppendText(i.ToString() + Environment.NewLine); } numbers.Visible = true; }