public void ManageNamespace(XamlReader reader) { switch (reader.NodeType) { case XamlNodeType.NamespaceDeclaration: tempNamespaceList.Add(reader.Namespace.Prefix, new NamespaceDeclaration( XamlBuildTaskServices.UpdateClrNamespaceUriWithLocalAssembly(reader.Namespace.Namespace, this.localAssemblyName), reader.Namespace.Prefix)); break; case XamlNodeType.StartObject: case XamlNodeType.StartMember: case XamlNodeType.GetObject: if (tempNamespaceList != null) { namespaceStack.Push(tempNamespaceList); tempNamespaceList = new Dictionary <string, NamespaceDeclaration>(); } break; case XamlNodeType.EndMember: case XamlNodeType.EndObject: namespaceStack.Pop(); break; default: break; } }
bool GetAppDomainAndExecute() { AppDomain appDomain = null; try { appDomain = CreateNewAppDomain(); bool ret = ExecuteInternal(appDomain); return(ret); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } XamlBuildTaskServices.LogException(this.Log, e.Message); return(false); } finally { if (appDomain != null) { AppDomain.Unload(appDomain); } } }
protected override XamlType GetXamlType(string xamlNamespace, string name, params XamlType[] typeArguments) { XamlType xamlType = base.GetXamlType(xamlNamespace, name, typeArguments); if (xamlType == null || xamlType.IsUnknown) { xamlNamespace = XamlBuildTaskServices.UpdateClrNamespaceUriWithLocalAssembly(xamlNamespace, this.localAssemblyName, this.realAssemblyName); xamlType = base.GetXamlType(xamlNamespace, name, typeArguments); } else if (!xamlType.UnderlyingType.Assembly.ReflectionOnly && xamlType.UnderlyingType.Assembly != typeof(object).Assembly) { // Types from XamlLanguage are live; but we want the ROL equivalent, so that we can validate // against expected member types. We do this by looking it up via its clr-namespace form. // Note this means that the resulting XamlType will only have its clr-namespace, not the XAML2006 namespace. IList <string> namespaces = xamlType.GetXamlNamespaces(); Fx.Assert(namespaces.Contains(XamlLanguage.Xaml2006Namespace) && xamlType.TypeArguments == null, "This should only happen for XamlLanguage types, none of which are generic"); string clrNamespace = namespaces[namespaces.Count - 1]; XamlType rolType = base.GetXamlType(clrNamespace, xamlType.UnderlyingType.Name); if (rolType != null) { xamlType = rolType; } } return(xamlType); }
PropertyData LoadProperty(XamlReader xamlReader) { if (xamlReader == null) { throw FxTrace.Exception.ArgumentNull("xamlReader"); } PropertyData property = new PropertyData(); while (xamlReader.Read()) { if (xamlReader.NodeType == XamlNodeType.StartMember) { XamlMember member = xamlReader.Member; switch (member.Name) { case "Name": property.Name = ReadValueAsString(xamlReader.ReadSubtree()); break; case "Type": property.Type = ReadPropertyType(xamlReader.ReadSubtree()); break; case "Attributes": foreach (AttributeData attribute in ReadAttributesCollection(xamlReader.ReadSubtree())) { property.Attributes.Add(attribute); } break; case "Modifier": string propertyModifier = ReadValueAsString(xamlReader.ReadSubtree()); property.Visibility = XamlBuildTaskServices.GetMemberVisibility(propertyModifier); break; default: // Ignore AttachedProperties on property if (!member.IsAttachable) { throw FxTrace.Exception.AsError(LogInvalidOperationException(xamlReader, SR.UnknownPropertyMember(member.Name))); } break; } } } if (string.IsNullOrEmpty(property.Name)) { throw FxTrace.Exception.AsError(LogInvalidOperationException(xamlReader, SR.PropertyNameRequired)); } if (property.Type == null) { throw FxTrace.Exception.AsError(LogInvalidOperationException(xamlReader, SR.PropertyTypeRequired(property.Name))); } return(property); }
// Read the actual parameter info, i.e. the type of the paramter and its value. // The first element could be a V or an SO. private static void ReadParamInfo(XamlReader reader, XamlType type, NamespaceTable namespaceTable, string rootNamespace, AttributeParameterData paramInfo) { reader.Read(); bool readNext = false; do { readNext = false; if (reader.NodeType == XamlNodeType.StartObject && reader.Type == XamlLanguage.Array) { paramInfo.IsArray = true; XamlReader xamlArrayReader = reader.ReadSubtree(); xamlArrayReader.Read(); while (readNext || xamlArrayReader.Read()) { readNext = false; if (xamlArrayReader.NodeType == XamlNodeType.StartMember && xamlArrayReader.Member.Name == "Type") { xamlArrayReader.Read(); if (xamlArrayReader.NodeType == XamlNodeType.Value) { XamlType arrayType = XamlBuildTaskServices.GetXamlTypeFromString(xamlArrayReader.Value as string, namespaceTable, xamlArrayReader.SchemaContext); if (arrayType.UnderlyingType != null) { paramInfo.Type = xamlArrayReader.SchemaContext.GetXamlType(arrayType.UnderlyingType.MakeArrayType()); } else { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.AttributeParameterTypeUnknown(arrayType))); } } } else if (xamlArrayReader.NodeType == XamlNodeType.StartObject) { AttributeParameterData arrayEntry = new AttributeParameterData(); ReadParamInfo(xamlArrayReader.ReadSubtree(), null, namespaceTable, rootNamespace, arrayEntry); paramInfo.AddArrayContentsEntry(arrayEntry); readNext = true; } } } else if (reader.NodeType == XamlNodeType.StartObject || reader.NodeType == XamlNodeType.Value) { paramInfo.IsArray = false; string paramVal; object paramObj = null; XamlType paramType; GetParamValueType(reader.ReadSubtree(), type, namespaceTable, rootNamespace, out paramVal, out paramType, out paramObj); paramInfo.TextValue = paramVal; paramInfo.Type = paramType; paramInfo.Value = paramObj; } } while (readNext || reader.Read()); }
XamlType ReadPropertyType(XamlReader xamlReader) { while (xamlReader.Read()) { if (xamlReader.NodeType == XamlNodeType.Value && xamlReader.Value is string) { return(XamlBuildTaskServices.GetXamlTypeFromString((string)xamlReader.Value, this.namespaceTable, xamlReader.SchemaContext)); } } return(null); }
// Parses a XAML QName to a CLR Type Name (and the corresponding ROL type, if available) private static Tuple <string, Type> ParseParameterValueTypeName(string paramValue, string rootNamespace, XamlSchemaContext schemaContext, NamespaceTable namespaceTable) { XamlType xamlType = XamlBuildTaskServices.GetXamlTypeFromString(paramValue, namespaceTable, schemaContext); string clrTypeName; if (!XamlBuildTaskServices.TryGetClrTypeName(xamlType, rootNamespace, out clrTypeName)) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.TypeNameUnknown(XamlBuildTaskServices.GetFullTypeName(xamlType)))); } return(Tuple.Create(clrTypeName, xamlType.UnderlyingType)); }
public override bool Execute() { AppDomain appDomain = null; try { ValidateRequiredDev11Properties(); appDomain = XamlBuildTaskServices.CreateAppDomain("CompilationPass2AppDomain_" + Guid.NewGuid(), BuildTaskPath); CompilationPass2TaskInternal wrapper = (CompilationPass2TaskInternal)appDomain.CreateInstanceAndUnwrap( Assembly.GetExecutingAssembly().FullName, typeof(CompilationPass2TaskInternal).FullName); PopulateBuildArtifacts(wrapper); bool ret = wrapper.Execute(); ExtractBuiltArtifacts(wrapper); if (!ret) { foreach (LogData logData in wrapper.LogData) { XamlBuildTaskServices.LogException( this.Log, logData.Message, logData.FileName, logData.LineNumber, logData.LinePosition); } } return(ret); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } XamlBuildTaskServices.LogException(this.Log, e.Message); return(false); } finally { if (appDomain != null) { AppDomain.Unload(appDomain); } } }
private void ValidateUnknown(XamlMember member) { if (member == XamlLanguage.UnknownContent) { ValidationError(SR.MemberUnknownContect(GetXamlTypeName(_stack.TopFrame.Type))); } else if (member.IsUnknown) { bool retryAttachable = false; XamlType declaringType = member.DeclaringType; if (_stack.Depth == 1 && declaringType.IsUnknown && !string.IsNullOrEmpty(this.rootNamespace) && this.definedType != null && declaringType.Name == this.definedType.Name) { // Need to handle the case where the namespace of a member on the document root // is missing the project root namespace string clrNs; if (XamlBuildTaskServices.TryExtractClrNs(declaringType.PreferredXamlNamespace, out clrNs)) { clrNs = string.IsNullOrEmpty(clrNs) ? this.rootNamespace : this.rootNamespace + "." + clrNs; if (clrNs == this.definedType.Namespace) { declaringType = SchemaContext.GetXamlType(this.definedType); retryAttachable = true; } } } XamlMember typeMember = declaringType.GetMember(member.Name); if (typeMember == null && retryAttachable) { typeMember = declaringType.GetAttachableMember(member.Name); } if (typeMember == null || typeMember.IsUnknown) { if (member.IsAttachable) { ValidationError(SR.UnresolvedAttachableMember(GetXamlTypeName(member.DeclaringType) + "." + member.Name)); } else if (member.IsDirective) { ValidationError(SR.UnresolvedDirective(member.PreferredXamlNamespace + ":" + member.Name)); } else { // Skip if declaring type is unknown as the member unknown error messages become redundant. if (declaringType != null && !declaringType.IsUnknown) { ValidationError(SR.UnresolvedMember(member.Name, GetXamlTypeName(declaringType))); } } } } }
private void ThrowTypeValidationError(XamlType type) { string typeName, assemblyName, ns; if (XamlBuildTaskServices.GetTypeNameInAssemblyOrNamespace(type, this.localAssemblyName, this.realAssemblyName, out typeName, out assemblyName, out ns)) { ValidationError(SR.UnresolvedTypeWithAssemblyName(ns + "." + typeName, assemblyName)); } else { ValidationError(SR.UnresolvedTypeWithNamespace(typeName, ns)); } }
public override IList <string> GetXamlNamespaces() { if (namespaces == null) { namespaces = new List <string>(); IList <string> originalNamespaces = base.GetXamlNamespaces(); foreach (var ns in originalNamespaces) { namespaces.Add(XamlBuildTaskServices.UpdateClrNamespaceUriWithLocalAssembly(ns, this.localAssemblyName, this.realAssemblyName)); } } return(namespaces); }
bool ExecuteExtensions() { ResolveAssemblyHelper resolveAssemblyHelper = new ResolveAssemblyHelper(XamlBuildTaskServices.GetReferences(this.References)); AppDomain.CurrentDomain.AssemblyResolve += resolveAssemblyHelper.ResolveLocalProjectReferences; bool extensionExecutedSuccessfully = true; try { IEnumerable <IXamlBuildTypeInspectionExtension> extensions = XamlBuildTaskServices.GetXamlBuildTaskExtensions <IXamlBuildTypeInspectionExtension>( this.XamlBuildTaskTypeInspectionExtensionNames, this.BuildLogger, this.MSBuildProjectDirectory); foreach (IXamlBuildTypeInspectionExtension extension in extensions) { try { extensionExecutedSuccessfully &= extension.Execute(this.BuildContextForExtensions); } catch (FileNotFoundException e) { throw FxTrace.Exception.AsError(new LoggableException(SR.ExceptionThrownInExtension(extension.ToString(), e.GetType().ToString(), SR.AssemblyNotFound(ResolveAssemblyHelper.FileNotFound)))); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } throw FxTrace.Exception.AsError(new LoggableException(SR.ExceptionThrownInExtension(extension.ToString(), e.GetType().ToString(), e.Message))); } } if (!this.BuildLogger.HasLoggedErrors && extensionExecutedSuccessfully) { foreach (string file in this.BuildContextForExtensions.GeneratedFiles) { this.GeneratedCodeFiles.Add(file); } } } finally { AppDomain.CurrentDomain.AssemblyResolve -= resolveAssemblyHelper.ResolveLocalProjectReferences; } return(extensionExecutedSuccessfully); }
IList <XamlType> UpdateTypeArgs(IList <XamlType> typeArgs, XamlSchemaContext xsc) { if (typeArgs != null) { IList <XamlType> updatedTypeArgs = new List <XamlType>(); foreach (var typeArg in typeArgs) { IList <XamlType> typeArgTypeArgs = UpdateTypeArgs(typeArg.TypeArguments, xsc); string typeArgXmlns = XamlBuildTaskServices.UpdateClrNamespaceUriWithLocalAssembly(typeArg.PreferredXamlNamespace, this.localAssemblyName); updatedTypeArgs.Add(new XamlType(typeArgXmlns, typeArg.Name, typeArgTypeArgs, xsc)); } return(updatedTypeArgs); } return(typeArgs); }
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; } }
internal static bool TryExtractClrNs(string @namespace, out string clrNs) { int nsIndex, assemblyIndex; if (XamlBuildTaskServices.IsClrNamespaceUri(@namespace, out nsIndex, out assemblyIndex)) { clrNs = (assemblyIndex == -1) ? @namespace.Substring(nsIndex).TrimEnd(' ', ';') : @namespace.Substring( nsIndex, assemblyIndex - XamlBuildTaskServices.ClrNamespaceUriAssemblyPart.Length - nsIndex - 1).TrimEnd(' ', ';'); return(true); } else { clrNs = null; return(false); } }
bool ReuseAppDomainAndExecute() { AppDomain appDomain = null; bool createdNewAppDomain = false; try { try { appDomain = GetInProcessAppDomain(out createdNewAppDomain); bool ret = ExecuteInternal(appDomain); return(ret); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (createdNewAppDomain) { XamlBuildTaskServices.LogException(this.Log, e.Message); return(false); } else { if (inProcessAppDomain != null) { AppDomain.Unload(inProcessAppDomain); inProcessAppDomain = null; } return(GetAppDomainAndExecute()); } } } finally { if (Log != null) { Log.MarkAsInactive(); } } }
void PopulateBuildArtifacts(PartialClassGenerationTaskInternal wrapper) { IList <ITaskItem> applicationMarkup = null; if (this.ApplicationMarkup != null) { applicationMarkup = this.ApplicationMarkup .Select(i => new DelegatingTaskItem(i) as ITaskItem).ToList(); } wrapper.ApplicationMarkup = applicationMarkup; wrapper.BuildLogger = this.Log; wrapper.References = this.References .Select(i => new DelegatingTaskItem(i) as ITaskItem).ToList(); IList <string> sourceCodeFiles = null; if (this.SourceCodeFiles != null) { sourceCodeFiles = new List <string>(this.SourceCodeFiles.Length); foreach (ITaskItem taskItem in this.SourceCodeFiles) { sourceCodeFiles.Add(taskItem.ItemSpec); } } wrapper.SourceCodeFiles = sourceCodeFiles; wrapper.Language = this.Language; wrapper.AssemblyName = this.AssemblyName; wrapper.OutputPath = this.OutputPath; wrapper.RootNamespace = this.RootNamespace; wrapper.GeneratedSourceExtension = this.GeneratedSourceExtension; wrapper.IsInProcessXamlMarkupCompile = this.IsInProcessXamlMarkupCompile; wrapper.MSBuildProjectDirectory = this.MSBuildProjectDirectory; wrapper.XamlBuildTaskTypeGenerationExtensionNames = XamlBuildTaskServices.GetXamlBuildTaskExtensionNames(this.XamlBuildTypeGenerationExtensionNames); if (this.XamlBuildTypeInspectionExtensionNames != null && this.XamlBuildTypeInspectionExtensionNames.Length > 0) { wrapper.MarkupCompilePass2ExtensionsPresent = true; } wrapper.SupportExtensions = this.supportExtensions; }
private void ThrowGenericTypeValidationError(XamlType type) { IList <XamlType> unresolvedLeafTypeList = new List <XamlType>(); XamlBuildTaskServices.GetUnresolvedLeafTypeArg(type, ref unresolvedLeafTypeList); if (unresolvedLeafTypeList.Count > 1 || !unresolvedLeafTypeList.Contains(type)) { string fullTypeName = GetXamlTypeName(type); ValidationError(SR.UnresolvedGenericType(fullTypeName)); foreach (XamlType xamlType in unresolvedLeafTypeList) { ThrowTypeValidationError(xamlType); } } else { ThrowTypeValidationError(type); } }
XamlNodeList ReadXamlNodes(string xamlFileName) { XamlNodeList nodeList = new XamlNodeList(this.SchemaContext); try { XamlXmlReaderSettings settings = new XamlXmlReaderSettings { AllowProtectedMembersOnRoot = true, ProvideLineInfo = true }; using (StreamReader streamReader = new StreamReader(xamlFileName)) { XamlReader reader = new XamlXmlReader(XmlReader.Create(streamReader, new XmlReaderSettings { XmlResolver = null }), this.SchemaContext, settings); XamlServices.Transform(reader, nodeList.Writer); } } catch (XmlException e) { XamlBuildTaskServices.LogException(this.BuildLogger, e.Message, xamlFileName, e.LineNumber, e.LinePosition); return(null); } catch (XamlException e) { XamlBuildTaskServices.LogException(this.BuildLogger, e.Message, xamlFileName, e.LineNumber, e.LinePosition); return(null); } if (nodeList.Count > 0) { return(nodeList); } else { return(null); } }
bool ProcessDirective(XamlReader reader, ClassData classData, NamedObject currentObject, bool isRootElement, XamlNodeList strippedXamlNodes, out bool readNextNode) { Fx.Assert(reader.NodeType == XamlNodeType.StartMember, "Current node should be a Start Member Node"); XamlMember member = reader.Member; bool directiveRecognized = false; readNextNode = false; switch (member.Name) { case "Name": // Unlike all the other directives that we process, x:Name should be written // to the stripped output. strippedXamlNodes.Writer.WriteStartMember(member); string objectName = ReadAtom(reader, XamlLanguage.Name.Name); if (!objectName.StartsWith(XamlBuildTaskServices.SerializerReferenceNamePrefix, StringComparison.Ordinal)) { currentObject.Name = objectName; classData.NamedObjects.Add(currentObject); } strippedXamlNodes.Writer.WriteValue(objectName); strippedXamlNodes.Writer.WriteEndMember(); directiveRecognized = true; break; case "Class": if (isRootElement) { string fullClassName = ReadAtom(reader, XamlLanguage.Class.Name); SetClassName(fullClassName, classData); directiveRecognized = true; } break; case "ClassModifier": if (isRootElement) { string classModifier = ReadAtom(reader, XamlLanguage.ClassModifier.Name); classData.IsPublic = XamlBuildTaskServices.IsPublic(classModifier); directiveRecognized = true; } break; case "FieldModifier": string fieldModifier = ReadAtom(reader, XamlLanguage.FieldModifier.Name); currentObject.Visibility = XamlBuildTaskServices.GetMemberVisibility(fieldModifier); directiveRecognized = true; break; case "Code": string codeSnippet = ReadAtom(reader, XamlLanguage.Code.Name); classData.CodeSnippets.Add(codeSnippet); directiveRecognized = true; break; case "Members": foreach (PropertyData property in ReadProperties(reader.ReadSubtree())) { classData.Properties.Add(property); } if (!classData.RequiresCompilationPass2) { foreach (PropertyData property in classData.Properties) { if (property.Type.IsUnknown) { classData.RequiresCompilationPass2 = true; break; } } } directiveRecognized = true; readNextNode = true; break; case "ClassAttributes": foreach (AttributeData attribute in ReadAttributesCollection(reader.ReadSubtree())) { classData.Attributes.Add(attribute); } directiveRecognized = true; readNextNode = true; break; } if (directiveRecognized == true && readNextNode == false) { reader.Read(); Fx.Assert(reader.NodeType == XamlNodeType.EndMember, "Current node should be a XamlEndmember"); } return(directiveRecognized); }
XamlNodeList RewriteRootNode(XamlNodeList strippedXamlNodes, string name, string @namespace) { // Rewrite the root node to have the name of class declared via x:Class (rather than the base class) // Also, for any properties on the root object that are declared in this class, need to rewrite the // namespace to include the root namespace, if there is one. string oldNamespace = null; if (!string.IsNullOrEmpty(this.rootNamespace)) { oldNamespace = @namespace; if (!string.IsNullOrEmpty(@namespace)) { @namespace = this.rootNamespace + "." + @namespace; } else { @namespace = this.rootNamespace; } } string namespaceName = string.Format(CultureInfo.InvariantCulture, "{0}{1};{2}{3}", XamlBuildTaskServices.ClrNamespaceUriNamespacePart, @namespace, XamlBuildTaskServices.ClrNamespaceUriAssemblyPart, this.localAssemblyName); XamlReader reader = strippedXamlNodes.GetReader(); XamlSchemaContext xsc = reader.SchemaContext; XamlNodeList newStrippedXamlNodes = new XamlNodeList(xsc); XamlWriter writer = newStrippedXamlNodes.Writer; int depth = 0; XamlType rootXamlType = null; while (reader.Read()) { switch (reader.NodeType) { case XamlNodeType.StartObject: case XamlNodeType.GetObject: depth++; break; case XamlNodeType.EndObject: depth--; break; } if (reader.NodeType == XamlNodeType.StartObject && depth == 1) { rootXamlType = new XamlType(namespaceName, name, null, xsc); writer.WriteStartObject(rootXamlType); } else if (reader.NodeType == XamlNodeType.StartMember && depth == 1 && reader.Member.IsUnknown && reader.Member.DeclaringType != null && reader.Member.DeclaringType.Name == rootXamlType.Name) { string clrNs; XamlMember member = reader.Member; if (XamlBuildTaskServices.TryExtractClrNs(member.PreferredXamlNamespace, out clrNs) && clrNs == oldNamespace) { // This is a member defined on the document root type, but missing the project root namespace. Fix it. XamlMember newMember = new XamlMember(member.Name, rootXamlType, member.IsAttachable); Fx.Assert(rootXamlType != null, "First StartObject should already have been processed"); writer.WriteStartMember(newMember); } else { writer.WriteNode(reader); } } else { writer.WriteNode(reader); } } writer.Close(); return(newStrippedXamlNodes); }
AppDomain CreateNewAppDomain() { return(XamlBuildTaskServices.CreateAppDomain("PartialClassAppDomain_" + Guid.NewGuid(), BuildTaskPath)); }
bool ProcessMarkupItem(ITaskItem markupItem, CodeDomProvider codeDomProvider) { string markupItemFileName = markupItem.ItemSpec; XamlBuildTaskServices.PopulateModifiers(codeDomProvider); XamlNodeList xamlNodes = ReadXamlNodes(markupItemFileName); if (xamlNodes == null) { return(false); } ClassData classData = ReadClassData(xamlNodes, markupItemFileName); string outputFileName = GetFileName(markupItemFileName); string codeFileName = Path.ChangeExtension(outputFileName, GetGeneratedSourceExtension(codeDomProvider)); string markupFileName = Path.ChangeExtension(outputFileName, GeneratedSourceExtension + XamlBuildTaskServices.XamlExtension); classData.EmbeddedResourceFileName = Path.GetFileName(markupFileName); classData.HelperClassFullName = this.HelperClassFullName; // Check if code file with partial class exists classData.SourceFileExists = UserProvidedFileExists(markupItemFileName, codeDomProvider); // Store the full type name as metadata on the markup item string rootNamespacePrefix = null; string namespacePrefix = null; string typeFullName = null; if (this.Language.Equals("VB") && !String.IsNullOrWhiteSpace(classData.RootNamespace)) { rootNamespacePrefix = classData.RootNamespace + "."; } if (!String.IsNullOrWhiteSpace(classData.Namespace)) { namespacePrefix = classData.Namespace + "."; } if (rootNamespacePrefix != null) { if (namespacePrefix != null) { typeFullName = rootNamespacePrefix + namespacePrefix + classData.Name; } else { typeFullName = rootNamespacePrefix + classData.Name; } } else { if (namespacePrefix != null) { typeFullName = namespacePrefix + classData.Name; } else { typeFullName = classData.Name; } } markupItem.SetMetadata("typeName", typeFullName); // Execute extensions here to give them a chance to mutate the ClassData before we generate code. if (this.SupportExtensions) { if (!ExecuteExtensions(classData, markupItem)) { return(false); } } // Generate code file CodeCompileUnit codeUnit = new ClassGenerator(this.BuildLogger, codeDomProvider, this.Language).Generate(classData); WriteCode(codeDomProvider, codeUnit, codeFileName); this.GeneratedCodeFiles.Add(codeFileName); // Generate resource file if (!string.IsNullOrEmpty(this.AssemblyName)) { // Generate xaml "implementation" file XmlWriterSettings xmlSettings = new XmlWriterSettings { Indent = true, IndentChars = " ", CloseOutput = true }; using (XmlWriter xmlWriter = XmlWriter.Create(File.Open(markupFileName, FileMode.Create), xmlSettings)) { XamlXmlWriterSettings xamlSettings = new XamlXmlWriterSettings() { CloseOutput = true }; // Process EmbeddedResourceXaml to remove xml:space="preserve" // due to a bug in XamlXmlWriter. XamlXmlWriter throws // if there are duplicate xml:space attributes. // It is ok to remove the xml:space attribute // as the XamlXmlWriter would add it in the next step // if needed. RemoveXamlSpaceAttribute(classData); using (XamlReader reader = classData.EmbeddedResourceXaml.GetReader()) { using (XamlXmlWriter xamlWriter = new XamlXmlWriter(xmlWriter, reader.SchemaContext, xamlSettings)) { XamlServices.Transform(reader, xamlWriter); } } } this.GeneratedResources.Add(markupFileName); } if (classData.RequiresCompilationPass2) { this.RequiresCompilationPass2 = true; } else { if (!this.SupportExtensions) { if (!ValidateXaml(xamlNodes, markupItemFileName)) { this.RequiresCompilationPass2 = true; } } else { // skip validation if we are doing in-proc compile // OR if we have pass 2 extensions hooked up // as we anyway need to run pass 2 in that case if (!this.IsInProcessXamlMarkupCompile && !this.MarkupCompilePass2ExtensionsPresent) { if (!ValidateXaml(xamlNodes, markupItemFileName)) { this.RequiresCompilationPass2 = true; } } } } return(true); }
private string GetXamlTypeName(XamlType type) { return(XamlBuildTaskServices.GetTypeName(type, this.localAssemblyName, this.realAssemblyName)); }
void PopulateBuildArtifacts(CompilationPass2TaskInternal wrapper) { if (!this.supportExtensions) { IList <string> applicationMarkup = new List <string>(this.ApplicationMarkup.Length); foreach (ITaskItem taskItem in this.ApplicationMarkup) { applicationMarkup.Add(taskItem.ItemSpec); } wrapper.ApplicationMarkup = applicationMarkup; } wrapper.SupportExtensions = this.supportExtensions; wrapper.BuildLogger = this.Log; wrapper.References = this.References .Select(i => new DelegatingTaskItem(i) as ITaskItem).ToList(); wrapper.LocalAssemblyReference = this.LocalAssemblyReference; wrapper.AssemblyName = this.AssemblyName; wrapper.RootNamespace = this.RootNamespace; wrapper.Language = this.Language; wrapper.OutputPath = this.OutputPath; wrapper.IsInProcessXamlMarkupCompile = this.IsInProcessXamlMarkupCompile; wrapper.MSBuildProjectDirectory = this.MSBuildProjectDirectory; IList <string> sourceCodeFiles = null; if (this.SourceCodeFiles != null) { sourceCodeFiles = new List <string>(this.SourceCodeFiles.Length); foreach (ITaskItem taskItem in this.SourceCodeFiles) { sourceCodeFiles.Add(taskItem.ItemSpec); } } wrapper.SourceCodeFiles = sourceCodeFiles; if (this.supportExtensions) { wrapper.XamlBuildTaskTypeInspectionExtensionNames = XamlBuildTaskServices.GetXamlBuildTaskExtensionNames(this.XamlBuildTypeInspectionExtensionNames); // Here we create a Dictionary of Type Full Name and corresponding TaskItem // This is passed to the extensions which enables them to look up // metadata about a type like file name. IDictionary <string, ITaskItem> applicationMarkupWithTypeName = null; if (this.ApplicationMarkupWithTypeName != null) { applicationMarkupWithTypeName = new Dictionary <string, ITaskItem>(); } foreach (ITaskItem taskItem in this.ApplicationMarkupWithTypeName) { string typeName = taskItem.GetMetadata("typeName"); if (!String.IsNullOrWhiteSpace(typeName)) { applicationMarkupWithTypeName.Add(typeName, new DelegatingTaskItem(taskItem)); } } wrapper.ApplicationMarkupWithTypeName = applicationMarkupWithTypeName; } }
public override bool Execute() { bool retVal; try { XDocument projectDocument = XDocument.Load(this.CurrentProject); if (projectDocument != null) { XElement projectElement = projectDocument.Element(XName.Get("Project", MSBuildNamespace)); if (projectElement != null) { RemoveItemsByName(projectElement, this.ApplicationMarkupTypeName); RemoveItemsByName(projectElement, "Reference"); RemoveItemsByName(projectElement, "ProjectReference"); if (this.supportExtensions) { AddNewResourceItems(projectElement, this.GeneratedResourcesFiles); } AddNewItems(projectElement, "Compile", this.SourceCodeFiles); AddNewItems(projectElement, "ReferencePath", this.ReferencePaths); RemovePropertyByName(projectElement, "OutputType"); RemovePropertyByName(projectElement, "AssemblyName"); AddNewProperties(projectElement, new ProjectProperty[] { new ProjectProperty() { Name = "OutputType", Value = "Library" }, new ProjectProperty() { Name = "AssemblyName", Value = this.AssemblyName }, new ProjectProperty() { Name = "Utf8Output", Value = "true", Condition = "'$(Utf8Output)' == ''" } }); } } string randomName = Path.GetRandomFileName(); randomName = Path.ChangeExtension(randomName, ""); string filename = Path.ChangeExtension(randomName, ".tmp_proj"); projectDocument.Save(filename); Hashtable globalProperties = new Hashtable(); globalProperties["IntermediateOutputPath"] = this.OutputPath; globalProperties["AssemblyName"] = this.AssemblyName; globalProperties["OutputType"] = "Library"; retVal = base.BuildEngine.BuildProjectFile(filename, new string[] { this.CompileTargetName }, globalProperties, null); File.Delete(filename); return(retVal); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } // Log unknown errors that do not originate from the task. // Assumes that all known errors are logged when the exception is thrown. XamlBuildTaskServices.LogException(this.Log, e.Message); retVal = false; } return(retVal); }
public bool Execute() { try { if (this.ApplicationMarkup == null || this.ApplicationMarkup.Count == 0) { return(true); } if (!CodeDomProvider.IsDefinedLanguage(this.Language)) { throw FxTrace.Exception.Argument("Language", SR.UnrecognizedLanguage(this.Language)); } if (this.SupportExtensions) { this.xamlBuildTypeGenerationExtensions = XamlBuildTaskServices.GetXamlBuildTaskExtensions <IXamlBuildTypeGenerationExtension>( this.XamlBuildTaskTypeGenerationExtensionNames, this.BuildLogger, this.MSBuildProjectDirectory); } AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(XamlBuildTaskServices.ReflectionOnlyAssemblyResolve); bool retVal = true; // We load the assemblies for the real builds // For intellisense builds, we load them the first time only if (!IsInProcessXamlMarkupCompile || this.LoadedAssemblyList == null) { if (this.References != null) { try { this.LoadedAssemblyList = XamlBuildTaskServices.Load(this.References, IsInProcessXamlMarkupCompile); } catch (FileNotFoundException e) { XamlBuildTaskServices.LogException(this.BuildLogger, e.Message, e.FileName, 0, 0); retVal = false; } } } CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider(this.Language); ProcessHelperClassGeneration(codeDomProvider); foreach (ITaskItem app in ApplicationMarkup) { string inputMarkupFile = app.ItemSpec; try { retVal &= ProcessMarkupItem(app, codeDomProvider); } catch (LoggableException e) { if (Fx.IsFatal(e)) { throw; } XamlBuildTaskServices.LogException(this.BuildLogger, e.Message, e.Source, e.LineNumber, e.LinePosition); retVal = false; } catch (FileLoadException e) { if (Fx.IsFatal(e)) { throw; } XamlBuildTaskServices.LogException(this.BuildLogger, SR.AssemblyCannotBeResolved(XamlBuildTaskServices.FileNotLoaded), inputMarkupFile, 0, 0); retVal = false; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } XamlBuildTaskServices.LogException(this.BuildLogger, e.Message, inputMarkupFile, 0, 0); retVal = false; } } // Add the files generated from extensions if (this.SupportExtensions) { if (retVal) { foreach (string fileName in this.BuildContextForExtensions.GeneratedFiles) { this.GeneratedCodeFiles.Add(fileName); } foreach (string fileName in this.BuildContextForExtensions.GeneratedResourceFiles) { this.GeneratedResources.Add(fileName); } } } return(retVal); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } // Log unknown errors that do not originate from the task. // Assumes that all known errors are logged when the exception is thrown. if (!(e is LoggableException)) { XamlBuildTaskServices.LogException(this.BuildLogger, e.Message); } return(false); } }
public bool Execute() { try { if ((!this.SupportExtensions) && ((this.ApplicationMarkup == null) || this.ApplicationMarkup.Count == 0)) { return(true); } else if (this.ApplicationMarkupWithTypeName == null || this.ApplicationMarkupWithTypeName.Count == 0) { return(true); } IList <Assembly> loadedAssemblyList = null; if (this.References != null) { loadedAssemblyList = XamlBuildTaskServices.Load(this.References, false); } Assembly localAssembly = null; if (LocalAssemblyReference != null) { try { localAssembly = XamlBuildTaskServices.Load(LocalAssemblyReference); loadedAssemblyList.Add(localAssembly); } catch (FileNotFoundException e) { XamlBuildTaskServices.LogException(this.BuildLogger, e.Message, e.FileName, 0, 0); return(false); } } AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(XamlBuildTaskServices.ReflectionOnlyAssemblyResolve); XamlNsReplacingContext wxsc = new XamlNsReplacingContext(loadedAssemblyList, localAssembly.GetName().Name, this.AssemblyName); bool foundValidationErrors = false; if (!this.SupportExtensions) { foreach (string app in ApplicationMarkup) { try { if (!ProcessMarkupItem(app, wxsc, localAssembly)) { foundValidationErrors = true; } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } XamlBuildTaskServices.LogException(this.BuildLogger, e.Message, app, 0, 0); return(false); } } } else { foreach (ITaskItem app in this.ApplicationMarkupWithTypeName.Values) { string inputMarkupFile = app.ItemSpec; try { if (!ProcessMarkupItem(inputMarkupFile, wxsc, localAssembly)) { foundValidationErrors = true; } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } XamlBuildTaskServices.LogException(this.BuildLogger, e.Message, inputMarkupFile, 0, 0); return(false); } } if (!foundValidationErrors) { foundValidationErrors = !ExecuteExtensions(); if (!foundValidationErrors) { foundValidationErrors = this.BuildLogger.HasLoggedErrors; } } } return(!foundValidationErrors); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } // Log unknown errors that do not originate from the task. // Assumes that all known errors are logged when the exception is thrown. XamlBuildTaskServices.LogException(this.BuildLogger, e.Message); return(false); } }