From: Daniel C. \(kzu\) <dca...@us...> - 2004-10-21 20:42:17
|
Update of /cvsroot/mvp-xml/Design/v1/src/CustomTools/XsdToClasses In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv28388/v1/src/CustomTools/XsdToClasses Added Files: ICodeExtension.cs Processor.cs Schema.cs Schema.txt Schema.xml Schema.xsd Schema.xsx XsdToClasses.cs Log Message: --- NEW FILE: Schema.xsx --- <?xml version="1.0" encoding="utf-8"?> <!--This file is auto-generated by the XML Schema Designer. It holds layout information for components on the designer surface.--> <XSDDesignerLayout layoutVersion="2" viewPortLeft="4099" viewPortTop="0" zoom="100"> <Code_XmlElement left="4445" top="423" width="5292" height="1773" selected="0" zOrder="0" index="0" expanded="1"> <Extension_XmlElement left="4472" top="2704" width="5239" height="2223" selected="0" zOrder="1" index="0" expanded="1" /> </Code_XmlElement> </XSDDesignerLayout> --- NEW FILE: XsdToClasses.cs --- #region Usage /* Usage: * Add an .xsd file to the project and set: * Custom Tool: XsdCodeGen */ #endregion Usage #region using using System; using System.CodeDom; using System.ComponentModel; using System.ComponentModel.Design; using System.Xml.Schema; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.CodeDom.Compiler; using System.Text; using System.Collections; #endregion namespace Mvp.Xml.Design.CustomTools { /// <summary> /// Processes XSD files and generates the corresponding classes. /// </summary> [Guid("2A9EF75D-26B5-4670-B7C6-F7AA63926439")] [CustomTool("XsdToClasses", "Microsoft IPE Classes Generator", true)] [ComVisible(true)] [VersionSupport("7.1")] [VersionSupport("7.0")] [CategorySupport(CategorySupportAttribute.CSharpCategory)] [CategorySupport(CategorySupportAttribute.VBCategory)] public class XsdToClasses : CustomTool { #region GenerateCode /// <summary> /// Generates the output. /// </summary> protected override byte[] GenerateCode(string inputFileName, string inputFileContent) { string code = ""; try { // Process the file. CodeNamespace ns = Processor.Process(inputFileName, FileNameSpace); // Generate code for it. CodeGeneratorOptions opt = new CodeGeneratorOptions(); opt.BracingStyle = "C"; StringWriter sw = new StringWriter(); GetCodeWriter().GenerateCodeFromNamespace(ns, sw, opt); // Finaly assign it to the result to return. code = sw.ToString(); } catch(Exception e) { code = String.Format("#error Couldn't generate code!\n/*\n{0}\n*/", e); } // Convert to bytes. return System.Text.Encoding.ASCII.GetBytes(code); } #endregion GenerateCode #region Registration and Installation /// <summary> /// Registers the generator. /// </summary> [ComRegisterFunction] public static void RegisterClass(Type type) { CustomTool.Register(typeof(XsdToClasses)); } /// <summary> /// Unregisters the generator. /// </summary> [ComUnregisterFunction] public static void UnregisterClass(Type t) { CustomTool.UnRegister(typeof(XsdToClasses)); } #endregion Registration and Installation } } --- NEW FILE: ICodeExtension.cs --- using System; namespace Mvp.Xml.Design.CustomTools { /// <summary> /// Interface for extension types that wish to participate in the /// WXS code generation process. /// </summary> public interface ICodeExtension { /// <summary> /// Extension points for code customization. /// </summary> /// <param name="code">The namespace being generated.</param> /// <param name="schema">The source schema.</param> void Process(System.CodeDom.CodeNamespace code, System.Xml.Schema.XmlSchema schema); } } --- NEW FILE: Schema.txt --- System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileNotFoundException: File or assembly name Microsoft.ApplicationBlocks.IPE, or one of its dependencies, was not found. File name: "Microsoft.ApplicationBlocks.IPE" at System.Reflection.Assembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase) at Microsoft.ApplicationBlocks.IPE.Transformations.ReflectionHelper.LoadType(String className, Boolean callingAssembly) at Microsoft.ApplicationBlocks.IPE.Transformations.Configuration.EngineItemValidator.Validate(Object objectToValidate, Object fullLoadedConfig, XPathNavigator document) at Microsoft.ApplicationBlocks.IPE.Transformations.Configuration.ConfigurationManager.ValidateObject(Object current, Type currentType, IpeConfiguration fullConfig, XPathNavigator document) at Microsoft.ApplicationBlocks.IPE.Transformations.Configuration.ConfigurationManager.ValidateObject(Object current, Type currentType, IpeConfiguration fullConfig, XPathNavigator document) at Microsoft.ApplicationBlocks.IPE.Transformations.Configuration.ConfigurationManager.ValidateObject(Object current, Type currentType, IpeConfiguration fullConfig, XPathNavigator document) at Microsoft.ApplicationBlocks.IPE.Transformations.Configuration.ConfigurationManager.ValidateObject(Object current, Type currentType, IpeConfiguration fullConfig, XPathNavigator document) at Microsoft.ApplicationBlocks.IPE.Transformations.Configuration.ConfigurationManager.ValidateObject(Object current, Type currentType, IpeConfiguration fullConfig, XPathNavigator document) at Microsoft.ApplicationBlocks.IPE.Transformations.Configuration.ConfigurationManager.PerformValidation() at Microsoft.ApplicationBlocks.IPE.Transformations.RuntimeFactory.CreateEngine(Stream stream, IServiceProvider parentProvider) at Microsoft.ApplicationBlocks.IPE.Transformations.RuntimeFactory.CreateEngine(String configuration, IServiceProvider parentProvider) at Microsoft.ApplicationBlocks.IPE.Transformations.RuntimeFactory.CreateEngine(String configuration) at Microsoft.ApplicationBlocks.IPE.Transformations.Design.IsolatedRunner..ctor(String configFile) === Pre-bind state information === LOG: DisplayName = Microsoft.ApplicationBlocks.IPE, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c2890f7f3ab20b71 (Fully-specified) LOG: Appbase = E:\DiscoDany\Clarius\Microsoft\Redmond\Wizards\src\Microsoft.ApplicationBlocks.IPE.Wizards\bin\Debug LOG: Initial PrivatePath = NULL Calling assembly : Microsoft.ApplicationBlocks.IPE.Tests.Assets, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c2890f7f3ab20b71. === LOG: Publisher policy file is not found. LOG: Host configuration file not found. LOG: Using machine configuration file from C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\config\machine.config. LOG: Post-policy reference: Microsoft.ApplicationBlocks.IPE, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c2890f7f3ab20b71 LOG: Attempting download of new URL file:///E:/DiscoDany/Clarius/Microsoft/Redmond/Wizards/src/Microsoft.ApplicationBlocks.IPE.Wizards/bin/Debug/Microsoft.ApplicationBlocks.IPE.DLL. LOG: Attempting download of new URL file:///E:/DiscoDany/Clarius/Microsoft/Redmond/Wizards/src/Microsoft.ApplicationBlocks.IPE.Wizards/bin/Debug/Microsoft.ApplicationBlocks.IPE/Microsoft.ApplicationBlocks.IPE.DLL. LOG: Attempting download of new URL file:///E:/DiscoDany/Clarius/Microsoft/Redmond/Wizards/src/Microsoft.ApplicationBlocks.IPE.Wizards/bin/Debug/Microsoft.ApplicationBlocks.IPE.EXE. LOG: Attempting download of new URL file:///E:/DiscoDany/Clarius/Microsoft/Redmond/Wizards/src/Microsoft.ApplicationBlocks.IPE.Wizards/bin/Debug/Microsoft.ApplicationBlocks.IPE/Microsoft.ApplicationBlocks.IPE.EXE. --- End of inner exception stack trace --- Server stack trace: at System.Reflection.RuntimeConstructorInfo.InternalInvoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean isBinderDefault) at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) at System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, StackCrawlMark& stackMark) at System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo) at System.AppDomain.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes) at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes) at System.Runtime.Remoting.Messaging.StackBuilderSink.PrivateProcessMessage(MethodBase mb, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs) at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes) at Microsoft.ApplicationBlocks.IPE.Transformations.Design.DesignDomain..ctor(DTE ide, String configFile, ProjectItem current) at Microsoft.ApplicationBlocks.IPE.Transformations.Design.EngineRunner.GenerateCode(String inputFileName, String inputFileContent) --- NEW FILE: Processor.cs --- #region using using System; using System.CodeDom; using System.CodeDom.Compiler; using System.IO; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Xml.XPath; #endregion using namespace Mvp.Xml.Design.CustomTools { /// <summary> /// Processes WXS files and builds code for them. /// </summary> /// <remarks>This tool can be used externally too, that's why /// it's public and separated from the VS Custom Tool code.</remarks> public sealed class Processor { #region Ctor and Fields private static XPathExpression Extensions; static Processor() { XPathNavigator nav = new XmlDocument().CreateNavigator(); // Select all extension types. Extensions = nav.Compile(String.Format( "/xs:schema/xs:annotation/xs:appinfo/{0}:{1}/{0}:{2}/@{3}", Schema.Prefix, Schema.ElementNames.Code, Schema.ElementNames.Extension, Schema.AttributeNames.Type)); // Create and set namespace resolution context. XmlNamespaceManager nsmgr = new XmlNamespaceManager(nav.NameTable); nsmgr.AddNamespace("xs", XmlSchema.Namespace); nsmgr.AddNamespace(Schema.Prefix, Schema.Namespace); Extensions.SetContext(nsmgr); } private Processor() {} #endregion Ctor and Fields #region Process /// <summary> /// Processes the schema. /// </summary> /// <param name="xsdFile">The full path to the WXS file to process.</param> /// <param name="targetNamespace">The namespace to put generated classes in.</param> /// <returns>The CodeDom tree generated from the schema.</returns> public static CodeNamespace Process(string xsdFile, string targetNamespace) { // Load the XmlSchema and its collection. XmlSchema xsd; using (FileStream fs = new FileStream(xsdFile, FileMode.Open)) { xsd = XmlSchema.Read(fs, null); xsd.Compile(null); } #region Import types XmlSchemas schemas = new XmlSchemas(); schemas.Add(xsd); // Create the importer for these schemas. XmlSchemaImporter importer = new XmlSchemaImporter(schemas); // System.CodeDom namespace for the XmlCodeExporter to put classes in. CodeNamespace ns = new CodeNamespace(targetNamespace); XmlCodeExporter exporter = new XmlCodeExporter(ns); // Iterate schema top-level elements and export code for each. foreach (XmlSchemaElement element in xsd.Elements.Values) { // Import the mapping first. XmlTypeMapping mapping = importer.ImportTypeMapping( element.QualifiedName); // Export the code finally. exporter.ExportTypeMapping(mapping); } #endregion Import types #region Execute extensions XPathNavigator nav = new XPathDocument(xsdFile).CreateNavigator(); XPathNodeIterator it = nav.Select(Extensions); while (it.MoveNext()) { Type t = Type.GetType(it.Current.Value, true); // Is the type an ICodeExtension? Type iface = t.GetInterface(typeof(ICodeExtension).Name); if (iface == null) { throw new ArgumentException(SR.Gral_TypeMustImplementInterface( t, typeof(ICodeExtension))); } ICodeExtension ext = (ICodeExtension) Activator.CreateInstance(t); // Run it! ext.Process(ns, xsd); } #endregion Execute extensions #region Make each type serializable foreach (CodeTypeDeclaration td in ns.Types) { AddSerializable(td); } #endregion Make each type serializable return ns; } #endregion Proces #region Add SerializableAttribute private static void AddSerializable(CodeTypeDeclaration type) { type.CustomAttributes.Add( new CodeAttributeDeclaration(typeof(SerializableAttribute).FullName)); foreach (CodeTypeMember m in type.Members) { if (m is CodeTypeDeclaration) AddSerializable((CodeTypeDeclaration) m); } } #endregion Add SerializableAttribute } } --- NEW FILE: Schema.xml --- <?xml version="1.0" encoding="utf-8" ?> <IpeConfiguration xmlns="urn:schemas-microsoft-com:ipe-configuration" xmlns:t="urn:schemas-microsoft-com:ipe-task"> <Transformation Name="GenerateSchemaClass"> <Parameters> <Parameter Name="SchemaLocation" Type="System.String" Multiplicity="0" DefaultValue="..\..\Schema.xsd" /> <Parameter Name="TargetNamespace" Type="System.String" Multiplicity="0" DefaultValue="Mvp.Xml.Design.CustomTools" /> <Parameter Name="XmlPrefix" Type="System.String" Multiplicity="0" DefaultValue="pag" /> </Parameters> <Tasks> <Task Type="Microsoft.ApplicationBlocks.IPE.Tests.Assets.Xsd2Cs.Generator, Microsoft.ApplicationBlocks.IPE.Tests.Assets, Version=1.0.0.0" /> <Task Type="Microsoft.ApplicationBlocks.IPE.Tasks.SolutionItemCodeDom, Microsoft.ApplicationBlocks.IPE, Version=1.0.0.0" t:OutputKey="CodeDom" t:Target="Schema.cs" /> </Tasks> </Transformation> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Microsoft.ApplicationBlocks.IPE.Tests.Assets" /> <!-- Design domain location is the output folder, i.e. bin\Debug|Release --> <codeBase version="1.0.0.0" href="%IPE%\bin\Microsoft.ApplicationBlocks.IPE.Tests.Assets.dll"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Microsoft.ApplicationBlocks.IPE" /> <!-- Design domain location is the output folder, i.e. bin\Debug|Release --> <codeBase version="1.0.0.0" href="%IPE%\bin\Microsoft.ApplicationBlocks.IPE.dll"/> </dependentAssembly> </assemblyBinding> </runtime> </IpeConfiguration> --- NEW FILE: Schema.xsd --- <?xml version="1.0" encoding="utf-8" ?> <xs:schema id="Schema" targetNamespace="http://www.microsoft.com/practices" elementFormDefault="qualified" xmlns="http://www.microsoft.com/practices" xmlns:mstns="http://www.microsoft.com/practices" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="Code"> <xs:complexType> <xs:sequence> <xs:element name="Extension"> <xs:complexType> <xs:simpleContent> <xs:restriction base="xs:string"> <xs:attribute name="Type" type="xs:string" /> <xs:attribute name="Location" type="xs:string" /> </xs:restriction> </xs:simpleContent> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> --- NEW FILE: Schema.cs --- //------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a tool. // Runtime Version: 1.1.4322.573 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> //------------------------------------------------------------------------------ namespace Mvp.Xml.Design.CustomTools { /// <remaks/> public sealed class Schema { /// <remaks/> public const string Namespace = "http://www.microsoft.com/practices"; /// <remaks/> public const string Prefix = "pag"; private Schema() { } /// <remaks/> /// <summary>Holds elements that are valid in the schema.</summary> public sealed class ElementNames { /// <remaks/> public const string Code = "Code"; /// <remaks/> public const string Extension = "Extension"; private ElementNames() { } } /// <summary>Holds attributes that are valid in the schema.</summary> /// <remaks/> public sealed class AttributeNames { /// <remaks/> public const string Type = "Type"; /// <remaks/> public const string Location = "Location"; private AttributeNames() { } } } } |