void GenerateCodeCore(AssemblyBuilder assemblyBuilder) { if (assemblyBuilder == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assemblyBuilder"); } CodeCompileUnit codeCompileUnit = parser.GetCodeModel(); // Bail if we have nothing we need to compile // if (codeCompileUnit == null) { return; } // Add the code unit and then add all the assemblies // assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit); if (parser.AssemblyDependencies != null) { foreach (Assembly assembly in parser.AssemblyDependencies) { assemblyBuilder.AddAssemblyReference(assembly); } } }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { base.GenerateCode(assemblyBuilder); WXMLModel model = null; using (XmlReader xr = new XmlTextReader(_fileName)) { model = WXMLModel.LoadFromXml(xr); } IRepositoryProvider prov = WmsDefinitionManager.GetRepositoryProvider(); foreach (CodeCompileUnit unit in prov.CreateCompileUnits(model)) { assemblyBuilder.AddCodeCompileUnit(this, unit); } string fn = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(assemblyBuilder.GetTempFilePhysicalPath("dll"))); AssemblyLoadEventHandler d = null; d = delegate(object sender, AssemblyLoadEventArgs args) { if (args.LoadedAssembly.ManifestModule.Name.StartsWith(fn)) { prov.SetRepositoryAssembly(args.LoadedAssembly); AppDomain.CurrentDomain.AssemblyLoad -= d; } }; AppDomain.CurrentDomain.AssemblyLoad += d; }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { assemblyBuilder.AddAssemblyReference(typeof(SimpleWeb).Assembly); assemblyBuilder.AddAssemblyReference(typeof(SimpleTemplateBase).Assembly); assemblyBuilder.AddCodeCompileUnit(this, GeneratedCode); assemblyBuilder.GenerateTypeFactory(String.Format(CultureInfo.InvariantCulture, "{0}.{1}", Host.DefaultNamespace, "Foot")); }
/// <summary> /// Generates source code for the virtual path of the build provider, and adds the source code to a specified assembly builder. /// </summary> /// <param name="assemblyBuilder">The assembly builder that references the source code generated by the build provider.</param> public override void GenerateCode(AssemblyBuilder assemblyBuilder) { using (DalGenerator gen = new DalGenerator(this.VirtualPath, true)) { assemblyBuilder.AddCodeCompileUnit(this, gen.Generate()); //CodeHelper.BuildCodeTreeFromMapFile(this.VirtualPath, true)); } }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { try { this.EnsureDirective(); if (String.IsNullOrEmpty(this.serviceTypeName)) { return; } Assembly tempAssembly = null; if (!String.IsNullOrEmpty(this.sourceText)) { // generate a code snippet for any inline source CodeSnippetCompileUnit unit = new CodeSnippetCompileUnit(this.sourceText); unit.LinePragma = new CodeLinePragma(base.VirtualPath, this.lineNumber); // add known assembly references foreach (Assembly assembly in this.ReferencedAssemblies) { assemblyBuilder.AddAssemblyReference(assembly); if (!String.IsNullOrEmpty(assembly.Location) && !unit.ReferencedAssemblies.Contains(assembly.Location)) { unit.ReferencedAssemblies.Add(assembly.Location); } } // compile once so we can reflect and build proxy, etc. assemblyBuilder.AddCodeCompileUnit(this, unit); CompilerResults results = assemblyBuilder.CodeDomProvider.CompileAssemblyFromDom(new CompilerParameters(), unit); if (results.Errors.HasErrors) { CompilerError error = results.Errors[0]; throw new HttpParseException(error.ErrorText, null, error.FileName, "", error.Line); } tempAssembly = results.CompiledAssembly; } Type serviceType = this.GetTypeToCache(this.serviceTypeName, tempAssembly); this.GenerateServiceProxyCode(assemblyBuilder, serviceType); } catch (HttpParseException ex) { Console.Error.WriteLine(ex); throw; } catch (Exception ex) { Console.Error.WriteLine(ex); throw new HttpParseException("GenerateCode: " + ex.Message, ex, base.VirtualPath, this.sourceText, this.lineNumber); } }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { if (this._generatedCode == null) { this._generatedCode = GenerateCode(); } assemblyBuilder.AddAssemblyReference(typeof(SimpleWeb).Assembly); assemblyBuilder.AddAssemblyReference(typeof(SimpleTemplateBase).Assembly); assemblyBuilder.AddCodeCompileUnit(this, this._generatedCode); assemblyBuilder.GenerateTypeFactory(this._typeName); }
/// <summary> /// Generates source code for the virtual path of the build provider, and adds the source code to a specified assembly builder. /// </summary> /// <param name="assemblyBuilder">The assembly builder that references the source code generated by the build provider.</param> public override void GenerateCode(AssemblyBuilder assemblyBuilder) { try { assemblyBuilder.AddCodeCompileUnit(this, this.GetGeneratedCode()); assemblyBuilder.GenerateTypeFactory(string.Format(CultureInfo.InvariantCulture, "{0}.{1}", new object[] { this.host.DefaultNamespace, this.host.DefaultClassName })); } catch (Exception ex) { Log.Error("GenerateCode(): ", ex); } }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { BaseCodeDomTreeGenerator codeDomGen = CreateCodeDomTreeGenerator(this.Parser); codeDomGen.GeneratedTypeName = this.GeneratedTypeName; codeDomGen.GeneratedTypeNamespace = this.GeneratedTypeNamespace; codeDomGen.GeneratedTypeFullName = this.GeneratedTypeFullName; var compileUnit = new CodeCompileUnit(); codeDomGen.BuildCodeDomTree(compileUnit); assemblyBuilder.AddCodeCompileUnit(this, compileUnit); }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { // look at the assembly builder to see which language we should use in the App_Code directory EntityCodeGenerator generator = null; if (assemblyBuilder.CodeDomProvider.FileExtension.ToLowerInvariant() == "cs") { generator = new EntityCodeGenerator(LanguageOption.GenerateCSharpCode); } else { generator = new EntityCodeGenerator(LanguageOption.GenerateVBCode); } // generate the code for our CSDL file IList <EdmSchemaError> errors = null; using (XmlReader input = XmlReader.Create(VirtualPathProvider.OpenFile(base.VirtualPath))) { using (StringWriter output = new StringWriter(CultureInfo.InvariantCulture)) { // Read from input and generate into output, put errors in a class member var entityFrameworkVersion = GetEntityFrameworkVersion(BuildManager.TargetFramework.Version); errors = generator.GenerateCode(input, output, entityFrameworkVersion); if (errors.Count == 0) { output.Flush(); assemblyBuilder.AddCodeCompileUnit(this, new CodeSnippetCompileUnit(output.ToString())); } } } // if there are errors, package this data into XmlExceptions and throw this // if we are in VS, the ASP .NET stack will place this information in the error pane // if we are in the ASP .NET runtime, it will use this information to build the error page if (errors != null && errors.Count > 0) { XmlException inner = null; XmlException outer = null; foreach (EdmSchemaError error in errors) { outer = new XmlException(error.Message, inner, error.Line, error.Column); inner = outer; } throw outer; } BuildProviderUtils.AddArtifactReference(assemblyBuilder, this, base.VirtualPath); }
public override void GenerateCode(AssemblyBuilder myAb) { XmlDocument carXmlDoc = new XmlDocument(); using (Stream passedFile = OpenStream()) { carXmlDoc.Load(passedFile); } XmlNode mainNode = carXmlDoc.SelectSingleNode("/car"); string selectionMainNode = mainNode.Attributes["name"].Value; XmlNode colorNode = carXmlDoc.SelectSingleNode("/car/color"); string selectionColorNode = colorNode.InnerText; XmlNode doorNode = carXmlDoc.SelectSingleNode("/car/door"); string selectionDoorNode = doorNode.InnerText; XmlNode seatsNode = carXmlDoc.SelectSingleNode("/car/seats"); string selectionseatsNode = seatsNode.InnerText; CodeCompileUnit ccu = new CodeCompileUnit(); CodeNamespace cn = new CodeNamespace(); CodeMemberProperty cmp1 = new CodeMemberProperty(); CodeMemberProperty cmp2 = new CodeMemberProperty(); CodeMemberMethod cmm1 = new CodeMemberMethod(); cn.Imports.Add(new CodeNamespaceImport("System")); cmp1.Name = "Color"; cmp1.Type = new CodeTypeReference(typeof(string)); cmp1.Attributes = MemberAttributes.Public; cmp1.GetStatements.Add(new CodeSnippetExpression("return \"" + selectionColorNode + "\"")); cmp2.Name = "Doors"; cmp2.Type = new CodeTypeReference(typeof(int)); cmp2.Attributes = MemberAttributes.Public; cmp2.GetStatements.Add(new CodeSnippetExpression("return " + selectionDoorNode)); cmm1.Name = "Go"; cmm1.ReturnType = new CodeTypeReference(typeof(int)); cmm1.Attributes = MemberAttributes.Public; cmm1.Statements.Add(new CodeSnippetExpression("return " + selectionseatsNode)); CodeTypeDeclaration ctd = new CodeTypeDeclaration(selectionMainNode); ctd.Members.Add(cmp1); ctd.Members.Add(cmp2); ctd.Members.Add(cmm1); cn.Types.Add(ctd); ccu.Namespaces.Add(cn); myAb.AddCodeCompileUnit(this, ccu); }
/// <summary> /// 此方法已被重写以产生代码 /// </summary> /// <param name="assemblyBuilder">程序集构建器</param> public override void GenerateCode(AssemblyBuilder assemblyBuilder) { if (_type == null) { _type = CreateDocumentProviderType(); } var @namespace = new CodeNamespace("HTML"); @namespace.Types.Add(_type); var unit = new CodeCompileUnit(); unit.Namespaces.Add(@namespace); assemblyBuilder.AddCodeCompileUnit(this, unit); AddReferences(assemblyBuilder); }
private void GenerateCodeCore(AssemblyBuilder assemblyBuilder) { if (assemblyBuilder == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assemblyBuilder"); } CodeCompileUnit codeModel = this.parser.GetCodeModel(); if (codeModel != null) { assemblyBuilder.AddCodeCompileUnit(this, codeModel); if (this.parser.AssemblyDependencies != null) { foreach (Assembly assembly in this.parser.AssemblyDependencies) { assemblyBuilder.AddAssemblyReference(assembly); } } } }
void GenerateExpressionRootFactory(AssemblyBuilder assemblyBuilder, BuildProvider buildProvider, string activityNamespace, string activityName) { CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); // namespace <%= activityNamespace %> // { // public class <%= activityName %>_ExpressionRootFactory : System.ServiceModel.Activities.WorkflowService // { // public static System.Activities.XamlIntegration.ICompiledExpressionRoot CreateExpressionRoot(System.Activities.Activity activity) // { // return new <%= activityNamespace %>.<%= activityName %>(activity); // } // } // } CodeNamespace codeNamespace = new CodeNamespace(activityNamespace); CodeTypeDeclaration codeTypeDeclaration = new CodeTypeDeclaration(activityName + ExpressionRootFactorySuffix); codeTypeDeclaration.BaseTypes.Add(new CodeTypeReference(typeof(WorkflowService))); CodeMemberMethod codeMemberMethod = new CodeMemberMethod(); codeMemberMethod.Name = CreateExpressionRootMethodName; codeMemberMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static; codeMemberMethod.ReturnType = new CodeTypeReference(typeof(ICompiledExpressionRoot)); codeMemberMethod.Parameters.Add(new CodeParameterDeclarationExpression( new CodeTypeReference(typeof(Activity)), ActivityParameterName)); CodeTypeReference typeRef = new CodeTypeReference(activityNamespace + "." + activityName); CodeObjectCreateExpression expr = new CodeObjectCreateExpression(typeRef, new CodeArgumentReferenceExpression(ActivityParameterName)); codeMemberMethod.Statements.Add(new CodeMethodReturnStatement(expr)); codeTypeDeclaration.Members.Add(codeMemberMethod); codeNamespace.Types.Add(codeTypeDeclaration); codeCompileUnit.Namespaces.Add(codeNamespace); assemblyBuilder.AddCodeCompileUnit(buildProvider, codeCompileUnit); }
/// <summary> /// Generates source code for the virtual path of the build provider, and adds the source code to a specified assembly builder. /// </summary> /// <param name="assemblyBuilder">The assembly builder that references the source code generated by the build provider.</param> public override void GenerateCode(AssemblyBuilder assemblyBuilder) { if (assemblyBuilder == null) { throw new ArgumentNullException("assemblyBuilder"); } // get name and namespace from the filename string ns = string.Empty; string name = VirtualPathUtility.GetFileName(VirtualPath); int i = name.LastIndexOf('.'); if (i > 0) { name = name.Substring(0, i); // discard extension i = name.LastIndexOf('.'); // and split into namespace and class if (i > 0) { name = name.Substring(i + 1); ns = name.Substring(0, i); } } // load as XML XmlDocument doc = new XmlDocument(); using (Stream s = OpenStream(VirtualPath)) { doc.Load(s); } // compile the channel CodeCompileUnit ccu = new CodeCompileUnit(); RssCodeGenerator.GenerateCodeDomTree(doc.OuterXml, string.Empty, ns, name, ccu, true); assemblyBuilder.AddCodeCompileUnit(this, ccu); }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { // get name and namespace from the filename string fname = VirtualPathUtility.GetFileName(VirtualPath); fname = fname.Substring(0, fname.LastIndexOf('.')); // no extension int i = fname.LastIndexOf('.'); string name, ns; if (i < 0) { name = fname; ns = string.Empty; } else { name = fname.Substring(i + 1); ns = fname.Substring(0, i); } // load as XML XmlDocument doc = new XmlDocument(); using (Stream s = OpenStream(VirtualPath)) { doc.Load(s); } // create the channel GenericRssChannel channel = GenericRssChannel.LoadChannel(doc); // compile the channel CodeCompileUnit ccu = new CodeCompileUnit(); RssCodeGenerator.GenerateCodeDomTree(channel, ns, name, ccu); assemblyBuilder.AddCodeCompileUnit(this, ccu); }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { if (assemblyBuilder == null) { throw new ArgumentNullException("assemblyBuilder"); } // load as XML XmlDocument doc = new XmlDocument(); using (Stream s = OpenStream(VirtualPath)) { doc.Load(s); } // validate root rssdl node XmlNode root = doc.DocumentElement; if (root.Name != "rssdl") { throw new InvalidDataException(string.Format(CultureInfo.InvariantCulture, "Unexpected root node '{0}' -- expected root 'rssdl' node", root.Name)); } // iterate through rss nodes for (XmlNode n = root.FirstChild; n != null; n = n.NextSibling) { if (n.NodeType != XmlNodeType.Element) { continue; } if (n.Name != "rss") { throw new InvalidDataException( string.Format( CultureInfo.InvariantCulture, "Unexpected node '{0}' -- expected root 'rss' node", root.Name)); } string file = string.Empty; string url = string.Empty; string classNamePrefix = string.Empty; string namespaceName = string.Empty; foreach (XmlAttribute attr in n.Attributes) { switch (attr.Name) { case "name": classNamePrefix = attr.Value; break; case "url": url = attr.Value; break; case "file": file = VirtualPathUtility.Combine(VirtualPathUtility.GetDirectory(VirtualPath), attr.Value); break; case "namespace": namespaceName = attr.Value; break; default: throw new InvalidDataException( string.Format(CultureInfo.InvariantCulture, "Unexpected attribute '{0}'", attr.Name)); } } if (string.IsNullOrEmpty(classNamePrefix)) { throw new InvalidDataException("Missing 'name' attribute"); } if (string.IsNullOrEmpty(url) && string.IsNullOrEmpty(file)) { throw new InvalidDataException("Missing 'url' or 'file' attribute - one must be specified"); } if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(file)) { throw new InvalidDataException("Only one of 'file' and 'url' can be specified"); } // compile channel CodeCompileUnit ccu = new CodeCompileUnit(); if (!string.IsNullOrEmpty(url)) { // load RssDocument using (Stream feedStream = DownloadManager.GetFeed(url)) { using (XmlTextReader reader = new XmlTextReader(feedStream)) { string codeString = RssXmlHelper.ConvertToRssXml(reader); RssCodeGenerator.GenerateCodeDomTree(codeString, url, namespaceName, classNamePrefix, ccu, true); } } } else { using (XmlTextReader reader = new XmlTextReader(file)) { string codeString = RssXmlHelper.ConvertToRssXml(reader); RssCodeGenerator.GenerateCodeDomTree(codeString, url, namespaceName, classNamePrefix, ccu, true); } } assemblyBuilder.AddCodeCompileUnit(this, ccu); } }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { string contentType, fileExtension; string originalSource, prettyPrintResource, compactedResource; ResourceCodeProvider provider = assemblyBuilder.CodeDomProvider as ResourceCodeProvider; if (provider != null) { originalSource = provider.CompileResource( this, base.VirtualPath, out prettyPrintResource, out compactedResource); contentType = provider.ContentType; fileExtension = provider.FileExtension; } else { // read the resource contents using (TextReader reader = this.OpenReader()) { originalSource = compactedResource = prettyPrintResource = reader.ReadToEnd(); } contentType = "text/plain"; fileExtension = "txt"; } IResourceNameGenerator nameGenerator = assemblyBuilder.CodeDomProvider as IResourceNameGenerator; if (nameGenerator != null) { this.ResourceFullName = nameGenerator.GenerateResourceName(base.VirtualPath); } else { this.ResourceFullName = ResourceBuildProvider.GenerateTypeNameFromPath(base.VirtualPath); } byte[] gzippedBytes, deflatedBytes; ResourceBuildProvider.Compress(compactedResource, out gzippedBytes, out deflatedBytes); string hash = ResourceBuildProvider.ComputeHash(compactedResource); // generate a resource container CodeCompileUnit generatedUnit = new CodeCompileUnit(); #region namespace ResourceNamespace CodeNamespace ns = new CodeNamespace(this.ResourceNamespace); generatedUnit.Namespaces.Add(ns); #endregion namespace ResourceNamespace #region public sealed class ResourceTypeName CodeTypeDeclaration resourceType = new CodeTypeDeclaration(); resourceType.IsClass = true; resourceType.Name = this.ResourceTypeName; resourceType.Attributes = MemberAttributes.Public | MemberAttributes.Final; provider.SetBaseClass(resourceType); resourceType.BaseTypes.Add(typeof(IOptimizedResult)); ns.Types.Add(resourceType); #endregion public sealed class ResourceTypeName #region [BuildPath(virtualPath)] string virtualPath = base.VirtualPath; if (HttpRuntime.AppDomainAppVirtualPath.Length > 1) { virtualPath = virtualPath.Substring(HttpRuntime.AppDomainAppVirtualPath.Length); } virtualPath = "~" + virtualPath; CodeAttributeDeclaration attribute = new CodeAttributeDeclaration( new CodeTypeReference(typeof(BuildPathAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression(virtualPath))); resourceType.CustomAttributes.Add(attribute); #endregion [BuildPath(virtualPath)] #region private static readonly byte[] GzippedBytes CodeMemberField field = new CodeMemberField(); field.Name = "GzippedBytes"; field.Type = new CodeTypeReference(typeof(byte[])); field.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final; CodeArrayCreateExpression arrayInit = new CodeArrayCreateExpression(field.Type, gzippedBytes.Length); foreach (byte b in gzippedBytes) { arrayInit.Initializers.Add(new CodePrimitiveExpression(b)); } field.InitExpression = arrayInit; resourceType.Members.Add(field); #endregion private static static readonly byte[] GzippedBytes #region private static readonly byte[] DeflatedBytes; field = new CodeMemberField(); field.Name = "DeflatedBytes"; field.Type = new CodeTypeReference(typeof(byte[])); field.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final; arrayInit = new CodeArrayCreateExpression(field.Type, deflatedBytes.Length); foreach (byte b in deflatedBytes) { arrayInit.Initializers.Add(new CodePrimitiveExpression(b)); } field.InitExpression = arrayInit; resourceType.Members.Add(field); #endregion private static readonly byte[] DeflatedBytes; #region string IOptimizedResult.Source { get; } // add a readonly property with the original resource source CodeMemberProperty property = new CodeMemberProperty(); property.Name = "Source"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult)); property.HasGet = true; // get { return originalSource; } if (originalSource == null || originalSource.Length <= 0x5DC) { property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(originalSource))); } else { string escaped = ResourceBuildProvider.QuoteSnippetStringCStyle(originalSource); property.GetStatements.Add(new CodeMethodReturnStatement(new CodeSnippetExpression(escaped))); } resourceType.Members.Add(property); #endregion string IOptimizedResult.Source { get; } #region string IOptimizedResult.PrettyPrinted { get; } // add a readonly property with the resource data property = new CodeMemberProperty(); property.Name = "PrettyPrinted"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult)); property.HasGet = true; if (String.Equals(originalSource, prettyPrintResource)) { // get { return ((IOptimizedResult)this).Source; } CodeExpression thisRef = new CodeCastExpression(typeof(IOptimizedResult), new CodeThisReferenceExpression()); CodePropertyReferenceExpression sourceProperty = new CodePropertyReferenceExpression(thisRef, "Source"); property.GetStatements.Add(new CodeMethodReturnStatement(sourceProperty)); } else { // get { return prettyPrintResource; } if (prettyPrintResource == null || prettyPrintResource.Length <= 0x5DC) { property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(prettyPrintResource))); } else { string escaped = ResourceBuildProvider.QuoteSnippetStringCStyle(prettyPrintResource); property.GetStatements.Add(new CodeMethodReturnStatement(new CodeSnippetExpression(escaped))); } } resourceType.Members.Add(property); #endregion string IOptimizedResult.PrettyPrinted { get; } #region string IOptimizedResult.Compacted { get; } // add a readonly property with the compacted resource data property = new CodeMemberProperty(); property.Name = "Compacted"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult)); property.HasGet = true; // get { return compactedResource; } if (compactedResource == null || compactedResource.Length <= 0x5DC) { property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(compactedResource))); } else { string escaped = ResourceBuildProvider.QuoteSnippetStringCStyle(compactedResource); property.GetStatements.Add(new CodeMethodReturnStatement(new CodeSnippetExpression(escaped))); } resourceType.Members.Add(property); #endregion string IOptimizedResult.Compacted { get; } #region byte[] IOptimizedResult.Gzipped { get; } // add a readonly property with the gzipped resource data property = new CodeMemberProperty(); property.Name = "Gzipped"; property.Type = new CodeTypeReference(typeof(byte[])); property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult)); property.HasGet = true; // get { return GzippedBytes; } property.GetStatements.Add(new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(this.ResourceTypeName), "GzippedBytes"))); resourceType.Members.Add(property); #endregion byte[] IOptimizedResult.Gzipped { get; } #region byte[] IOptimizedResult.Deflated { get; } // add a readonly property with the deflated resource data property = new CodeMemberProperty(); property.Name = "Deflated"; property.Type = new CodeTypeReference(typeof(byte[])); property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult)); property.HasGet = true; // get { return DeflatedBytes; } property.GetStatements.Add(new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(this.ResourceTypeName), "DeflatedBytes"))); resourceType.Members.Add(property); #endregion byte[] IOptimizedResult.Deflated { get; } #region string IBuildResultMeta.ContentType { get; } // add a readonly property with the MIME type property = new CodeMemberProperty(); property.Name = "ContentType"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IBuildResult)); property.HasGet = true; // get { return contentType; } property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(contentType))); resourceType.Members.Add(property); #endregion string IBuildResultMeta.ContentType { get; } #region string IBuildResultMeta.FileExtension { get; } // add a readonly property with the MIME type property = new CodeMemberProperty(); property.Name = "FileExtension"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IBuildResult)); property.HasGet = true; // get { return fileExtension; } property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(fileExtension))); resourceType.Members.Add(property); #endregion string IBuildResultMeta.FileExtension { get; } #region string IBuildResultMeta.Hash { get; } // add a readonly property with the resource data property = new CodeMemberProperty(); property.Name = "Hash"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IBuildResult)); property.HasGet = true; // get { return hash); } property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(hash))); resourceType.Members.Add(property); #endregion string IBuildResultMeta.Hash { get; } if (this.VirtualPathDependencies.Count > 0) { resourceType.BaseTypes.Add(typeof(IDependentResult)); #region private static readonly string[] Dependencies field = new CodeMemberField(); field.Name = "Dependencies"; field.Type = new CodeTypeReference(typeof(string[])); field.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final; arrayInit = new CodeArrayCreateExpression(field.Type, this.VirtualPathDependencies.Count); foreach (string key in this.VirtualPathDependencies) { arrayInit.Initializers.Add(new CodePrimitiveExpression(key)); } field.InitExpression = arrayInit; resourceType.Members.Add(field); #endregion private static readonly string[] Dependencies #region IEnumerable<string> IDependentResult.VirtualPathDependencies { get; } // add a readonly property returning the static data property = new CodeMemberProperty(); property.Name = "VirtualPathDependencies"; property.Type = new CodeTypeReference(typeof(IEnumerable <string>)); property.PrivateImplementationType = new CodeTypeReference(typeof(IDependentResult)); property.HasGet = true; // get { return Dependencies; } property.GetStatements.Add(new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(resourceType.Name), "Dependencies"))); resourceType.Members.Add(property); #endregion IEnumerable<string> IDependentResult.VirtualPathDependencies { get; } } // allow the code provider to extend with additional properties provider.GenerateCodeExtensions(this, resourceType); // Generate _ASP FastObjectFactory assemblyBuilder.GenerateTypeFactory(this.ResourceFullName); assemblyBuilder.AddCodeCompileUnit(this, generatedUnit); }
/// <summary> /// Generates source code for the virtual path of the build provider, and adds the source code to a specified assembly builder. /// </summary> /// <param name="assemblyBuilder">The assembly builder that references the source code generated by the build provider.</param> public override void GenerateCode(AssemblyBuilder assemblyBuilder) { Utility.WriteTrace("Invoking BuildProvider"); DataService.LoadProviders(); ICodeLanguage language = new CSharpCodeLanguage(); DirectoryInfo di = new DirectoryInfo(HostingEnvironment.ApplicationPhysicalPath + "\\App_Code"); FileInfo[] fi = di.GetFiles("*.vb"); if (fi.Length > 0) { language = new VBCodeLanguage(); } StringBuilder code = new StringBuilder(language.DefaultUsingStatements); TurboCompiler tc = new TurboCompiler(); // loop over the providers, and generate code for each foreach (DataProvider provider in DataService.Providers) { Utility.WriteTrace(String.Format("Creating code for {0}", provider.Name)); string[] tableList = DataService.GetTableNames(provider.Name); string[] viewList = DataService.GetViewNames(provider.Name); foreach (string tbl in tableList) { TurboTemplate tt = CodeService.BuildClassTemplate(tbl, language, provider); tc.AddTemplate(tt); if (provider.GenerateODSControllers) { TurboTemplate tODS = CodeService.BuildODSTemplate(tbl, language, provider); tc.AddTemplate(tODS); } } foreach (string view in viewList) { TurboTemplate tt = CodeService.BuildViewTemplate(view, language, provider); tc.AddTemplate(tt); } tc.AddTemplate(CodeService.BuildSPTemplate(language, provider)); } if (DataService.Providers.Count > 0) { tc.AddTemplate(CodeService.BuildStructsTemplate(language, DataService.Provider)); } foreach (TurboTemplate tt in tc.Templates) { tt.AddUsingBlock = false; } tc.Run(); foreach (TurboTemplate tt in tc.Templates) { code.Append(tt.FinalCode); } assemblyBuilder.AddCodeCompileUnit(this, new CodeSnippetCompileUnit(code.ToString())); }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { // load as XML XmlDocument doc = new XmlDocument(); using (Stream s = OpenStream(VirtualPath)) { doc.Load(s); } // valide root rssdl node XmlNode root = doc.DocumentElement; if (root.Name != "rssdl") { throw new InvalidDataException( string.Format("Unexpected root node '{0}' -- expected root 'rssdl' node", root.Name)); } // iterate through rss nodes for (XmlNode n = root.FirstChild; n != null; n = n.NextSibling) { if (n.NodeType != XmlNodeType.Element) { continue; } if (n.Name != "rss") { throw new InvalidDataException( string.Format("Unexpected node '{0}' -- expected root 'rss' node", root.Name)); } string name = string.Empty; string file = string.Empty; string url = string.Empty; string ns = string.Empty; foreach (XmlAttribute attr in n.Attributes) { switch (attr.Name) { case "name": name = attr.Value; break; case "url": if (!string.IsNullOrEmpty(file)) { throw new InvalidDataException("Only one of 'file' and 'url' can be specified"); } url = attr.Value; break; case "file": if (!string.IsNullOrEmpty(url)) { throw new InvalidDataException("Only one of 'file' and 'url' can be specified"); } file = VirtualPathUtility.Combine(VirtualPathUtility.GetDirectory(VirtualPath), attr.Value); break; case "namespace": ns = attr.Value; break; default: throw new InvalidDataException( string.Format("Unexpected attribute '{0}'", attr.Name)); } } if (string.IsNullOrEmpty(name)) { throw new InvalidDataException("Missing 'name' attribute"); } if (string.IsNullOrEmpty(url) && string.IsNullOrEmpty(file)) { throw new InvalidDataException("Missing 'url' or 'file' attribute - one must be specified"); } // load channel GenericRssChannel channel = null; if (!string.IsNullOrEmpty(url)) { channel = GenericRssChannel.LoadChannel(url); } else { XmlDocument rssDoc = new XmlDocument(); using (Stream s = OpenStream(file)) { rssDoc.Load(s); } channel = GenericRssChannel.LoadChannel(rssDoc); } // compile channel CodeCompileUnit ccu = new CodeCompileUnit(); RssCodeGenerator.GenerateCodeDomTree(channel, ns, name, ccu); assemblyBuilder.AddCodeCompileUnit(this, ccu); } }
public void AddCodeCompileUnit(CodeCompileUnit compileUnit) { _assemblyBuilder.AddCodeCompileUnit(_buildProvider, compileUnit); }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { assemblyBuilder.AddCodeCompileUnit(this, GeneratedCode); }
private void GenerateServiceProxyCode(AssemblyBuilder assemblyBuilder, Type serviceType) { IResourceNameGenerator nameGenerator = assemblyBuilder.CodeDomProvider as IResourceNameGenerator; if (nameGenerator != null) { this.ResourceFullName = nameGenerator.GenerateResourceName(base.VirtualPath); } else { this.ResourceFullName = ResourceBuildProvider.GenerateTypeNameFromPath(base.VirtualPath); } // TODO: consolidate app relative path conversion // calculate the service end-point path string proxyPath = ResourceHandler.EnsureAppRelative(base.VirtualPath).TrimStart('~'); // build proxy from main service type JsonServiceDescription desc = new JsonServiceDescription(serviceType, proxyPath); JsonServiceProxyGenerator proxy = new JsonServiceProxyGenerator(desc); string proxyOutput = proxy.OutputProxy(false); proxyOutput = ScriptResourceCodeProvider.FirewallScript(proxyPath, proxyOutput, true); string debugProxyOutput = proxy.OutputProxy(true); debugProxyOutput = ScriptResourceCodeProvider.FirewallScript(proxyPath, debugProxyOutput, false); byte[] gzippedBytes, deflatedBytes; ResourceBuildProvider.Compress(proxyOutput, out gzippedBytes, out deflatedBytes); string hash = ResourceBuildProvider.ComputeHash(proxyOutput); // generate a service factory CodeCompileUnit generatedUnit = new CodeCompileUnit(); #region namespace ResourceNamespace CodeNamespace ns = new CodeNamespace(this.ResourceNamespace); generatedUnit.Namespaces.Add(ns); #endregion namespace ResourceNamespace #region public sealed class ResourceTypeName : JsonServiceInfo CodeTypeDeclaration resourceType = new CodeTypeDeclaration(); resourceType.IsClass = true; resourceType.Name = this.ResourceTypeName; resourceType.Attributes = MemberAttributes.Public | MemberAttributes.Final; resourceType.BaseTypes.Add(typeof(IJsonServiceInfo)); resourceType.BaseTypes.Add(typeof(IOptimizedResult)); ns.Types.Add(resourceType); #endregion public sealed class ResourceTypeName : CompiledBuildResult #region [BuildPath(virtualPath)] string virtualPath = base.VirtualPath; if (HttpRuntime.AppDomainAppVirtualPath.Length > 1) { virtualPath = virtualPath.Substring(HttpRuntime.AppDomainAppVirtualPath.Length); } virtualPath = "~" + virtualPath; CodeAttributeDeclaration attribute = new CodeAttributeDeclaration( new CodeTypeReference(typeof(BuildPathAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression(virtualPath))); resourceType.CustomAttributes.Add(attribute); #endregion [BuildPath(virtualPath)] #region private static readonly byte[] GzippedBytes CodeMemberField field = new CodeMemberField(); field.Name = "GzippedBytes"; field.Type = new CodeTypeReference(typeof(byte[])); field.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final; CodeArrayCreateExpression arrayInit = new CodeArrayCreateExpression(field.Type, gzippedBytes.Length); foreach (byte b in gzippedBytes) { arrayInit.Initializers.Add(new CodePrimitiveExpression(b)); } field.InitExpression = arrayInit; resourceType.Members.Add(field); #endregion private static static readonly byte[] GzippedBytes #region private static readonly byte[] DeflatedBytes field = new CodeMemberField(); field.Name = "DeflatedBytes"; field.Type = new CodeTypeReference(typeof(byte[])); field.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final; arrayInit = new CodeArrayCreateExpression(field.Type, deflatedBytes.Length); foreach (byte b in deflatedBytes) { arrayInit.Initializers.Add(new CodePrimitiveExpression(b)); } field.InitExpression = arrayInit; resourceType.Members.Add(field); #endregion private static readonly byte[] DeflatedBytes #region string IOptimizedResult.Source { get; } // add a readonly property with the original resource source CodeMemberProperty property = new CodeMemberProperty(); property.Name = "Source"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult)); property.HasGet = true; // get { return debugProxyOutput; } property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(debugProxyOutput))); resourceType.Members.Add(property); #endregion string IOptimizedResult.Source { get; } #region string IOptimizedResult.PrettyPrinted { get; } // add a readonly property with the debug proxy code string property = new CodeMemberProperty(); property.Name = "PrettyPrinted"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult)); property.HasGet = true; // get { return ((IOptimizedResult)this).Source; } CodeExpression thisRef = new CodeCastExpression(typeof(IOptimizedResult), new CodeThisReferenceExpression()); CodePropertyReferenceExpression sourceProperty = new CodePropertyReferenceExpression(thisRef, "Source"); property.GetStatements.Add(new CodeMethodReturnStatement(sourceProperty)); resourceType.Members.Add(property); #endregion string IOptimizedResult.PrettyPrinted { get; } #region string IOptimizedResult.Compacted { get; } // add a readonly property with the proxy code string property = new CodeMemberProperty(); property.Name = "Compacted"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult)); property.HasGet = true; // get { return proxyOutput; } property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(proxyOutput))); resourceType.Members.Add(property); #endregion string IOptimizedResult.Compacted { get; } #region byte[] IOptimizedResult.Gzipped { get; } // add a readonly property with the gzipped proxy code property = new CodeMemberProperty(); property.Name = "Gzipped"; property.Type = new CodeTypeReference(typeof(byte[])); property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult)); property.HasGet = true; // get { return GzippedBytes; } property.GetStatements.Add(new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(this.ResourceTypeName), "GzippedBytes"))); resourceType.Members.Add(property); #endregion byte[] IOptimizedResult.Gzipped { get; } #region byte[] IOptimizedResult.Deflated { get; } // add a readonly property with the deflated proxy code property = new CodeMemberProperty(); property.Name = "Deflated"; property.Type = new CodeTypeReference(typeof(byte[])); property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult)); property.HasGet = true; // get { return DeflatedBytes; } property.GetStatements.Add(new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(this.ResourceTypeName), "DeflatedBytes"))); resourceType.Members.Add(property); #endregion byte[] IOptimizedResult.Deflated { get; } #region string IBuildResultMeta.Hash { get; } // add a readonly property with the hash of the resource data property = new CodeMemberProperty(); property.Name = "Hash"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IBuildResult)); property.HasGet = true; // get { return hash; } property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(hash))); resourceType.Members.Add(property); #endregion string IBuildResultMeta.Hash { get; } #region string IBuildResultMeta.ContentType { get; } // add a readonly property with the MIME of the resource data property = new CodeMemberProperty(); property.Name = "ContentType"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IBuildResult)); property.HasGet = true; // get { return ScriptResourceCodeProvider.MimeType; } property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(ScriptResourceCodeProvider.MimeType))); resourceType.Members.Add(property); #endregion string IBuildResultMeta.ContentType { get; } #region string IBuildResultMeta.FileExtension { get; } // add a readonly property with the extension of the resource data property = new CodeMemberProperty(); property.Name = "FileExtension"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IBuildResult)); property.HasGet = true; // get { return ScriptResourceCodeProvider.FileExt; } property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(ScriptResourceCodeProvider.FileExt))); resourceType.Members.Add(property); #endregion string IBuildResultMeta.FileExtension { get; } #region public Type IJrpcServiceInfo.ServiceType { get; } // add a static field with the service type property = new CodeMemberProperty(); property.Name = "ServiceType"; property.Type = new CodeTypeReference(typeof(Type)); property.Attributes = MemberAttributes.Public; property.ImplementationTypes.Add(new CodeTypeReference(typeof(IJsonServiceInfo))); property.HasGet = true; // get { return typeof(serviceType); } property.GetStatements.Add(new CodeMethodReturnStatement(new CodeTypeOfExpression(serviceType.FullName))); resourceType.Members.Add(property); #endregion public Type IJrpcServiceInfo.ServiceType { get; } #region object IJrpcServiceInfo.CreateService(); CodeMemberMethod codeMethod = new CodeMemberMethod(); codeMethod.Name = "CreateService"; codeMethod.PrivateImplementationType = new CodeTypeReference(typeof(IJsonServiceInfo)); codeMethod.ReturnType = new CodeTypeReference(typeof(Object)); // return new serviceType(); codeMethod.Statements.Add(new CodeMethodReturnStatement(new CodeObjectCreateExpression(serviceType))); resourceType.Members.Add(codeMethod); #endregion object IJrpcServiceInfo.CreateService(); #region MethodInfo IJrpcServiceInfo.ResolveMethodName(string name); codeMethod = new CodeMemberMethod(); codeMethod.Name = "ResolveMethodName"; codeMethod.PrivateImplementationType = new CodeTypeReference(typeof(IJsonServiceInfo)); codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(String), "name")); codeMethod.ReturnType = new CodeTypeReference(typeof(MethodInfo)); CodeVariableReferenceExpression nameParam = new CodeVariableReferenceExpression("name"); // if (String.IsNullOrEmpty(name)) { return null; } CodeConditionStatement nullCheck = new CodeConditionStatement(); nullCheck.Condition = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(String)), "IsNullOrEmpty", nameParam); nullCheck.TrueStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null))); codeMethod.Statements.Add(nullCheck); Dictionary <string, MethodInfo> methodMap = JsonServiceBuildProvider.CreateMethodMap(serviceType); foreach (string name in methodMap.Keys) { CodeConditionStatement nameTest = new CodeConditionStatement(); // if (String.Equals(name, methodName)) { ... } nameTest.Condition = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(String)), "Equals", nameParam, new CodePrimitiveExpression(name)); // this.ServiceType CodePropertyReferenceExpression serviceTypeRef = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "ServiceType"); // method name CodePrimitiveExpression methodNameRef = new CodePrimitiveExpression(methodMap[name].Name); // this.ServiceType.GetMethod(methodNameRef) CodeMethodInvokeExpression methodInfoRef = new CodeMethodInvokeExpression(serviceTypeRef, "GetMethod", methodNameRef); // return MethodInfo; nameTest.TrueStatements.Add(new CodeMethodReturnStatement(methodInfoRef)); codeMethod.Statements.Add(nameTest); } codeMethod.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null))); resourceType.Members.Add(codeMethod); #endregion MethodInfo IJrpcServiceInfo.ResolveMethodName(string name); #region string[] IJrpcServiceInfo.GetMethodParams(string name); codeMethod = new CodeMemberMethod(); codeMethod.Name = "GetMethodParams"; codeMethod.PrivateImplementationType = new CodeTypeReference(typeof(IJsonServiceInfo)); codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(String), "name")); codeMethod.ReturnType = new CodeTypeReference(typeof(String[])); CodeVariableReferenceExpression nameParam2 = new CodeVariableReferenceExpression("name"); // if (String.IsNullOrEmpty(name)) { return new string[0]; } CodeConditionStatement nullCheck2 = new CodeConditionStatement(); nullCheck2.Condition = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(String)), "IsNullOrEmpty", nameParam); nullCheck2.TrueStatements.Add(new CodeMethodReturnStatement(new CodeArrayCreateExpression(typeof(String[]), 0))); codeMethod.Statements.Add(nullCheck2); foreach (MethodInfo method in methodMap.Values) { string[] paramMap = JsonServiceBuildProvider.CreateParamMap(method); if (paramMap.Length < 1) { continue; } CodeConditionStatement nameTest = new CodeConditionStatement(); // if (String.Equals(name, method.Name)) { ... } nameTest.Condition = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(String)), "Equals", nameParam2, new CodePrimitiveExpression(method.Name)); // = {...} CodePrimitiveExpression[] paramList = new CodePrimitiveExpression[paramMap.Length]; for (int i = 0; i < paramMap.Length; i++) { paramList[i] = new CodePrimitiveExpression(paramMap[i]); } // new string[] = {...} CodeArrayCreateExpression paramArray = new CodeArrayCreateExpression(typeof(String[]), paramList); // return string[]; nameTest.TrueStatements.Add(new CodeMethodReturnStatement(paramArray)); codeMethod.Statements.Add(nameTest); } codeMethod.Statements.Add(new CodeMethodReturnStatement(new CodeArrayCreateExpression(typeof(String[]), 0))); resourceType.Members.Add(codeMethod); #endregion string[] IJrpcServiceInfo.GetMethodParams(string name); if (this.VirtualPathDependencies.Count > 0) { resourceType.BaseTypes.Add(typeof(IDependentResult)); #region private static readonly string[] Dependencies field = new CodeMemberField(); field.Name = "Dependencies"; field.Type = new CodeTypeReference(typeof(string[])); field.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final; arrayInit = new CodeArrayCreateExpression(field.Type, this.VirtualPathDependencies.Count); foreach (string key in this.VirtualPathDependencies) { arrayInit.Initializers.Add(new CodePrimitiveExpression(key)); } field.InitExpression = arrayInit; resourceType.Members.Add(field); #endregion private static readonly string[] Dependencies #region IEnumerable<string> IDependentResult.VirtualPathDependencies { get; } // add a readonly property returning the static data property = new CodeMemberProperty(); property.Name = "VirtualPathDependencies"; property.Type = new CodeTypeReference(typeof(IEnumerable <string>)); property.PrivateImplementationType = new CodeTypeReference(typeof(IDependentResult)); property.HasGet = true; // get { return Dependencies; } property.GetStatements.Add(new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(resourceType.Name), "Dependencies"))); resourceType.Members.Add(property); #endregion IEnumerable<string> IDependentResult.VirtualPathDependencies { get; } } // Generate _ASP FastObjectFactory assemblyBuilder.GenerateTypeFactory(this.ResourceFullName); assemblyBuilder.AddCodeCompileUnit(this, generatedUnit); }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { assemblyBuilder.AddCodeCompileUnit(this, new CodeSnippetCompileUnit(GetGeneratedCode())); }
/* * Line 12: namespace Hao.Kung.Samples { * Line 13: using System; * Line 14: using System.Net; * Line 15: using System.Web.Services; * Line 16: using System.Collections; * Line 17: using System.Xml.Serialization; * Line 18: using System.Web.Services; * Line 19: * Line 20: * Line 21: [WebService(Name="http://tempuri.org/")] * Line 22: [WebServiceBinding(ConformsTo=System.Web.Services.WsiProfiles.BasicProfile1_1)] * Line 23: public partial class MSNSearch { * Line 24: * Line 25: public MSNSearch() { * Line 26: this.VirtualPath = "/atlas/BCL/msn.asbx"; * this.BridgeXml = <contents of MSN.asbx> * Line 27: } * Line 28: [System.Web.Script.Services.ScriptService()] * Line 29: [System.Web.Services.WebMethodAttribute()] * Line 30: [System.Xml.Serialization.XmlIncludeAttribute(typeof(MSN.SearchRequest))] * Line 31: public object Search(System.Collections.IDictionary args) { * Line 32: return this.Invoke(new System.Web.Services.BridgeRequest("Search", args)); * Line 33: } * Line 34: */ public override void GenerateCode(AssemblyBuilder assemBuilder) { CodeNamespace ns = new CodeNamespace(Service.Namespace); ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.Net")); ns.Imports.Add(new CodeNamespaceImport("System.Web.Services")); ns.Imports.Add(new CodeNamespaceImport("System.Collections")); ns.Imports.Add(new CodeNamespaceImport("System.Xml.Serialization")); ns.Imports.Add(new CodeNamespaceImport("Microsoft.Web.Preview.Services")); ns.Imports.Add(new CodeNamespaceImport("System.Web.Script.Services")); CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(ns); CodeTypeDeclaration classType = new CodeTypeDeclaration(Service.Classname); classType.BaseTypes.Add(typeof(BridgeHandler)); classType.IsPartial = true; ns.Types.Add(classType); classType.CustomAttributes.Add(new CodeAttributeDeclaration("ScriptService")); classType.CustomAttributes.Add(new CodeAttributeDeclaration("WebService", new CodeAttributeArgument("Name", new CodePrimitiveExpression("http://tempuri.org/")))); classType.CustomAttributes.Add(new CodeAttributeDeclaration("WebServiceBinding", new CodeAttributeArgument("ConformsTo", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(WsiProfiles)), "BasicProfile1_1")))); /** * public ClassName() { * VirtualPath = <the virtual path> * } */ CodeConstructor constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public; constructor.Statements.Add(new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "VirtualPath"), new CodePrimitiveExpression(VirtualPath))); constructor.Statements.Add(new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "BridgeXml"), new CodePrimitiveExpression(_bridgeXml))); classType.Members.Add(constructor); ServiceInfo serviceInfo = Service.ServiceInfo; foreach (BridgeMethodInfo methodInfo in serviceInfo.Methods.Values) { classType.Members.Add(GenerateWebMethodCode(methodInfo.Name, methodInfo.XmlIncludes, methodInfo.GetEnabled, methodInfo.ResponseFormat, false)); } // Skip the proxy method code generation for REST if (!string.Equals(serviceInfo.ServiceClass, "Microsoft.Web.Preview.Services.BridgeRestProxy")) { classType.Members.Add(GenerateProxyMethodCode()); } // BridgeMethod hook classType.Members.Add(GenerateWebMethodCode("__invokeBridge", null, false, ResponseFormat.Json, true)); assemBuilder.AddCodeCompileUnit(this, unit); if (!string.IsNullOrEmpty(Service.PartialClassFile)) { using (TextReader reader = OpenReader(Service.PartialClassFile)) { CodeSnippetCompileUnit snippet = new CodeSnippetCompileUnit(reader.ReadToEnd()); if (HttpContext.Current != null) { snippet.LinePragma = new CodeLinePragma(HttpContext.Current.Request.MapPath(Service.PartialClassFile), 1); } assemBuilder.AddCodeCompileUnit(this, snippet); } } }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { assemblyBuilder.AddCodeCompileUnit(this, this.GetGeneratedCode()); assemblyBuilder.GenerateTypeFactory(string.Format(CultureInfo.InvariantCulture, "{0}.{1}", this.host.DefaultNamespace, this.host.DefaultClassName)); }
/// <summary> /// Generates source code for the virtual path of the build provider, and adds the source code to a specified assembly builder. /// </summary> /// <param name="assemblyBuilder">The assembly builder that references the source code generated by the build provider.</param> public override void GenerateCode(AssemblyBuilder assemblyBuilder) { assemblyBuilder.AddCodeCompileUnit(this, PersistenceHelper.BuildCodeTree(this.VirtualPath, true)); }