public void Make(string resourceFile)
		{
			string starterTemplate = GetStarterTemplate();
			if(genData.MtaAttribute)
			{
				starterTemplate = starterTemplate.Replace("[STAThread]", "[MTAThread]");
			}
			starterTemplate = starterTemplate.Replace("// This is a template. Do not remove //# strings", string.Empty);
			starterTemplate = SetStarterVersion(starterTemplate);
			starterTemplate = SetNETVersion(starterTemplate);
			starterTemplate = AppendPrivatePath(starterTemplate);
			starterTemplate = RemoveZipCode(starterTemplate);
			starterTemplate = SetZipTemplate(starterTemplate, genData);
			starterTemplate = OptimizeSelf(starterTemplate);
			starterTemplate = SetEntryPoint(starterTemplate);
			if(genData.Console)
			{
				starterTemplate = starterTemplate.Replace(
					"using System.Windows.Forms;", string.Empty);
				starterTemplate = starterTemplate.Replace(
					"MessageBox.Show(null, s, \"Error\")", "Console.WriteLine(s)");
			}
			if(genData.BatchMode)
			{
				BatchMode(genData.Console, starterTemplate);
			}
			else
			{
				CodeCompileUnit cu = new CodeSnippetCompileUnit(MixTemplate(starterTemplate, genData.AssemblyInfo));
				CompileCU(genData.Console, resourceFile, cu);
			}
		}
Example #2
0
        public static CompilerResults Build(string source)
        {
            CompilerResults cr;
            if (_Cache.TryGetValue(source, out cr)) return cr;

            var csource =
                @"using System;" +
                @"using System.Collections.Generic;" +
                @"using System.Linq;" +
                @"using System.Text;" +
                @"public class Program " +
                @"{" +
                @"	public static void Main(string[] args) {}" +
                @"	public static string Get(string[] args)" +
                @"	{" +
                source +
                @"	}" +
                @"}";

            var csu = new CodeSnippetCompileUnit(csource);
            var provider = new CSharpCodeProvider();
            var options = new CompilerParameters();
            options.GenerateInMemory = true;
            options.IncludeDebugInformation = true;
            options.ReferencedAssemblies.Add("System.dll");
            options.ReferencedAssemblies.Add("System.Core.dll");
            options.MainClass = "Program";
            cr = provider.CompileAssemblyFromSource(options, new string[] { csource });
            _Cache[source] = cr;
            return cr;
        }
		public void Constructor0_Deny_Unrestricted ()
		{
			CodeSnippetCompileUnit cscu = new CodeSnippetCompileUnit ();
			Assert.IsNull (cscu.LinePragma, "LinePragma");
			cscu.LinePragma = new CodeLinePragma ();
			Assert.AreEqual (String.Empty, cscu.Value, "Value");
			cscu.Value = "mono";
		}
		public void Constructor1_Deny_Unrestricted ()
		{
			CodeSnippetCompileUnit cscu = new CodeSnippetCompileUnit ("mono");
			Assert.IsNull (cscu.LinePragma, "LinePragma");
			cscu.LinePragma = new CodeLinePragma (String.Empty, Int32.MaxValue);
			Assert.AreEqual ("mono", cscu.Value, "Value");
			cscu.Value = String.Empty;
		}
 private void EnsureCodeCompileUnit() {
     if (_snippetCompileUnit == null) {
         // Read the contents of the file
         string sourceString = Util.StringFromVirtualPath(VirtualPathObject);
         _snippetCompileUnit = new CodeSnippetCompileUnit(sourceString);
         _snippetCompileUnit.LinePragma = BaseCodeDomTreeGenerator.CreateCodeLinePragmaHelper(
             VirtualPath, 1);
     }
 }
 private void EnsureCodeCompileUnit()
 {
     if (this._snippetCompileUnit == null)
     {
         string str = Util.StringFromVirtualPath(base.VirtualPathObject);
         this._snippetCompileUnit = new CodeSnippetCompileUnit(str);
         this._snippetCompileUnit.LinePragma = BaseCodeDomTreeGenerator.CreateCodeLinePragmaHelper(base.VirtualPath, 1);
     }
 }
Example #7
0
        public string Compute(string expression)
        {
            var source = "class Evaluator { public static string Evaluate() { return ("+expression+").ToString(); } }";

            var compileUnit = new CodeSnippetCompileUnit(source);
            var provider = new CSharpCodeProvider();

            var parameters = new CompilerParameters();
            var results = provider.CompileAssemblyFromDom(parameters, compileUnit);

            var type = results.CompiledAssembly.GetType("Evaluator");
            var method = type.GetMethod("Evaluate");
            return (string) method.Invoke(null, null);
        }
        public System.CodeDom.CodeObject CreateCodeObject()
        {
            var llex = PathHelper.GetExecutingPath("llex.exe");
            var tmpFile = Path.GetTempFileName();

            AppDomain.CurrentDomain.ExecuteAssembly(
                llex,
                new[]
                {
                    "Aphid.alx",
                    tmpFile
                });

            var snippet = new CodeSnippetCompileUnit(File.ReadAllText(tmpFile));
            File.Delete(tmpFile);
            return snippet;
        }
		public void Constructor1 ()
		{
			string value = "mono";

			CodeSnippetCompileUnit cscu = new CodeSnippetCompileUnit (value);
			Assert.IsNull (cscu.LinePragma, "#1");

			Assert.IsNotNull (cscu.Value, "#2");
			Assert.AreEqual (value, cscu.Value, "#3");
			Assert.AreSame (value, cscu.Value, "#4"); 

			Assert.IsNotNull (cscu.AssemblyCustomAttributes, "#5");
			Assert.AreEqual (0, cscu.AssemblyCustomAttributes.Count, "#6");

			Assert.IsNotNull (cscu.Namespaces, "#7");
			Assert.AreEqual (0, cscu.Namespaces.Count, "#8");

			Assert.IsNotNull (cscu.ReferencedAssemblies, "#9");
			Assert.AreEqual (0, cscu.ReferencedAssemblies.Count, "#10");

#if NET_2_0
			Assert.IsNotNull (cscu.StartDirectives, "#11");
			Assert.AreEqual (0, cscu.StartDirectives.Count, "#12");

			Assert.IsNotNull (cscu.EndDirectives, "#13");
			Assert.AreEqual (0, cscu.EndDirectives.Count, "#14");
#endif

			Assert.IsNotNull (cscu.UserData, "#15");
			Assert.AreEqual (typeof(ListDictionary), cscu.UserData.GetType (), "#16");
			Assert.AreEqual (0, cscu.UserData.Count, "#17");
			
			cscu.Value = null;
			Assert.IsNotNull (cscu.Value, "#18");
			Assert.AreEqual (string.Empty, cscu.Value, "#19");

			CodeLinePragma clp = new CodeLinePragma ("mono", 10);
			cscu.LinePragma = clp;
			Assert.IsNotNull (cscu.LinePragma, "#20");
			Assert.AreSame (clp, cscu.LinePragma, "#21");

			cscu = new CodeSnippetCompileUnit ((string) null);

			Assert.IsNotNull (cscu.Value, "#22");
			Assert.AreEqual (string.Empty, cscu.Value, "#23");
		}
        /*
         *  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);
                }
            }
        }
Example #11
0
 private void ValidateSnippetCompileUnit(CodeSnippetCompileUnit e) {
     if (e.LinePragma != null) ValidateLinePragmaStart(e.LinePragma);
 }
    // This is used in the CBM scenario only
    /// <devdoc>
    /// Returns the CodeCompileUnit and sets the associated dictionary containing the line pragmas.
    /// </devdoc>
    protected internal virtual CodeCompileUnit GetCodeCompileUnit(out IDictionary linePragmasTable) {

        // Default implementation with code at line 1

        string sourceString = Util.StringFromVirtualPath(VirtualPathObject);
        CodeSnippetCompileUnit snippetCompileUnit = new CodeSnippetCompileUnit(sourceString);

        LinePragmaCodeInfo codeInfo = new LinePragmaCodeInfo(1 /* startLine */, 1 /* startColumn */, 1 /* startGeneratedColumn */, -1 /* codeLength */, false /* isCodeNuggest */);
        linePragmasTable = new Hashtable();
        linePragmasTable[1] = codeInfo;

        return snippetCompileUnit;
    }
 protected internal virtual CodeCompileUnit GetCodeCompileUnit(out IDictionary linePragmasTable)
 {
     CodeSnippetCompileUnit unit = new CodeSnippetCompileUnit(Util.StringFromVirtualPath(this.VirtualPathObject));
     LinePragmaCodeInfo info = new LinePragmaCodeInfo(1, 1, 1, -1, false);
     linePragmasTable = new Hashtable();
     linePragmasTable[1] = info;
     return unit;
 }
Example #14
0
 protected virtual CodeCompileUnit CreateCompilationUnit() {
   var unit = new CodeSnippetCompileUnit(code);
   return unit;
 }
Example #15
0
		protected virtual void GenerateSnippetCompileUnit (CodeSnippetCompileUnit e)
		{
			if (e.LinePragma != null)
				GenerateLinePragmaStart (e.LinePragma);

			output.WriteLine (e.Value);

			if (e.LinePragma != null)
				GenerateLinePragmaEnd (e.LinePragma);

		}
Example #16
0
        /// <summary>
        /// ������ȡCDSSSystemData GlobalData�����ݵĶ�̬code,����������
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private static CodeSnippetCompileUnit ConstructAndCompileCode(string value)
        {
            CodeNamespace CurrentNameSpace
                = InitializeNameSpace(CONST_GENERATECODE_NAMESPACE);
            CodeTypeDeclaration ctd = CreateClass(CONST_GENERATECODE_CLASSNAME);
            CurrentNameSpace.Types.Add(ctd);
            CodeMemberMethod mtd = CreateMethod(
                CONST_GENERATECODE_METHODNAME_OBTAIN_SYSTEM_DATA);
            ctd.Members.Add(mtd);

            mtd.Statements.Add(new CodeSnippetExpression("return" + "\n" + value));

            CSharpCodeProvider provider = new CSharpCodeProvider();
            ICodeGenerator codeGen = provider.CreateGenerator();
            string codeSnippet = GenerateCode(codeGen, CurrentNameSpace);

            CodeSnippetCompileUnit unit = new CodeSnippetCompileUnit(codeSnippet);
            return unit;
        }
Example #17
0
		bool Initialize (string taskName, IDictionary<string, string> factoryIdentityParameters, IDictionary<string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost)
		{
			task_name = taskName;
			if (parameterGroup != null)
				parameter_group = new Dictionary<string, TaskPropertyInfo> (parameterGroup);
			
			List<string> references = new List<string> ();
			List<string> namespace_uses = new List<string> ();
			namespace_uses.Add ("Microsoft.Build.Framework");
			string type = null, language = null, code = null;

			var xml = XmlReader.Create (new StringReader (taskBody), new XmlReaderSettings () { ConformanceLevel = ConformanceLevel.Fragment });
			for (xml.MoveToContent (); !xml.EOF; xml.MoveToContent ()) {
				switch (xml.NodeType) {
				case XmlNodeType.Element:
					switch (xml.LocalName) {
					case "Reference":
						references.Add (xml.GetAttribute ("Include"));
						xml.Skip ();
						break;
					case "Using":
						namespace_uses.Add (xml.GetAttribute ("Namespace"));
						xml.Skip ();
						break;
					case "Code":
						// MSB3757: Multiple Code elements have been found, this is not allowed.
						if (code != null)
							throw new InvalidProjectFileException (null, "Multiple Code elements are not allowed", "MSB", "3757", null);
						type = xml.GetAttribute ("Type");
						language = xml.GetAttribute ("Language");
						code = xml.ReadElementContentAsString ();
						break;
					}
					break;
				default:
					xml.Skip ();
					break;
				}
			}

			if (language != "cs" && language != "vb")
				throw new InvalidProjectFileException (null, string.Format ("{0} is not supported language for inline task", language), "MSB", "4175", null);

			CodeCompileUnit ccu;

			if (type == "Class") {  // 'code' contains the whole class that implements the task
				ccu = new CodeSnippetCompileUnit (code);
			}
			else {  // 'code' contains parts of the class that implements the task
				ccu = new CodeCompileUnit ();
				var nsp = new CodeNamespace ();
				nsp.Imports.AddRange (namespace_uses.Select (x => new CodeNamespaceImport (x)).ToArray ());
				ccu.Namespaces.Add (nsp);

				var taskClass = new CodeTypeDeclaration {
					IsClass = true,
					Name = taskName,
					TypeAttributes = TypeAttributes.Public
				};

				var parameters = new List<CodeMemberProperty> ();
				var parametersBackingFields = new List<CodeMemberField> ();

				// add a public property + backing field for each parameter
				foreach (var param in parameter_group) {
					var prop = new CodeMemberProperty {
						Attributes = MemberAttributes.Public | MemberAttributes.Final,
						Name = param.Value.Name,
						Type = new CodeTypeReference (param.Value.PropertyType)
					};

					var propBf = new CodeMemberField {
						Attributes = MemberAttributes.Private,
						Name = "_" + prop.Name,
						Type = prop.Type
					};

					// add getter and setter to the property
					prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), propBf.Name)));
					prop.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), propBf.Name), new CodePropertySetValueReferenceExpression ()));

					parameters.Add (prop);
					parametersBackingFields.Add (propBf);
				}

				taskClass.Members.AddRange (parameters.ToArray ());
				taskClass.Members.AddRange (parametersBackingFields.ToArray ());
				taskClass.BaseTypes.Add ("Microsoft.Build.Utilities.Task");  // The documentation says "ITask", but the very first example shows "Log" which is not in ITask! It is likely that the generated code uses Task or TaskExtension.

				if (type == "Method") {  // 'code' contains the 'Execute' method directly
					taskClass.Members.Add (new CodeSnippetTypeMember (code));
				}
				else if (type == "Fragment") {  // 'code' contains the body of the 'Execute' method
					var method = new CodeMemberMethod {
						Attributes = MemberAttributes.Public | MemberAttributes.Override,
						Name = "Execute",
						ReturnType = new CodeTypeReference (typeof (bool))
					};

					// add the code and a 'return true' at the end of the method
					method.Statements.Add (new CodeSnippetStatement (code));
					method.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (true)));

					taskClass.Members.Add (method);
				}
				else {
					throw new ArgumentException ("Invalid type: " + type);
				}

				nsp.Types.Add (taskClass);
			}

			var cscParams = new CompilerParameters ();
			cscParams.ReferencedAssemblies.Add ("Microsoft.Build.Framework.dll");
			cscParams.ReferencedAssemblies.Add ("Microsoft.Build.Utilities.v4.0.dll"); // since we use Task, it depends on this dll.
			cscParams.ReferencedAssemblies.AddRange (GetReferences (references, taskFactoryLoggingHost));
			cscParams.GenerateInMemory = true;
			var results = CodeDomProvider.CreateProvider (language).CompileAssemblyFromDom (cscParams, ccu);
			var errors = new CompilerError [results.Errors.Count];
			results.Errors.CopyTo (errors, 0);
			if (errors.Any (e => !e.IsWarning)) {
				string msg = string.Format ("Invalid '{0}' source code of '{1}' type: {2}", language, type, string.Join (" ", errors.Where (e => !e.IsWarning).Select (e => e.ToString ())));
				throw new InvalidProjectFileException (null, msg, "MSB", "3758", null);
			}
			assembly = results.CompiledAssembly;
			return true;
		}
        /// <summary>
        /// This method returns a code compile unit that will be added
        /// to the other depdnecies in order to compile
        /// </summary>
        internal CodeCompileUnit GetCodeModel()
        {
            // Do we have something to compile?
            //
            if (sourceString == null || sourceString.Length == 0)
                return null;

            CodeSnippetCompileUnit snippetCompileUnit = new CodeSnippetCompileUnit(sourceString);

            // Put in some context so that the file can be debugged.
            //
            string pragmaFile = HostingEnvironmentWrapper.MapPath(virtualPath);
            snippetCompileUnit.LinePragma = new CodeLinePragma(pragmaFile, lineNumber);

            return snippetCompileUnit;
        }
        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 virtual CompilerResults CompileModuleFromSourceBatch(CompilerParameters options, string[] sources, ErrorNodeList errorNodes){
   if (options == null || sources == null){Debug.Assert(false); return null;}
   int n = sources.Length;
   System.CodeDom.CodeSnippetCompileUnit[] cuSnippets = new System.CodeDom.CodeSnippetCompileUnit[n];
   for (int i = 0; i < n; i++)
     cuSnippets[i] = new CodeSnippetCompileUnit(sources[i]); 
   return this.CompileModuleFromDomBatch(options, cuSnippets, errorNodes);
 }
 public virtual CompilerResults CompileModuleFromSource(CompilerParameters options, string source, ErrorNodeList errorNodes){
   if (options == null || source == null){Debug.Assert(false); return null;}
   CodeSnippetCompileUnit cuSnippet = new CodeSnippetCompileUnit(source);
   return this.CompileModuleFromDom(options, cuSnippet, errorNodes);
 }
        /**
         * Standard procedure to compile resources:
         * 1. Get an AppDomain correspondint to the Classloader.
         * 2. Create an assembly in the given appdomain
         * 3. Create a type for each resource, given the className (resourceName), contents
              (pReader.getBytes(resourceName)), and the AppDomain.
         * 4.  Write the compiled types to the store.
         */
        public override CompilationResult compile(
            string[] pResourceNames,
            ResourceReader pReader,
            ResourceStore pStore,
            ClassLoader pClassLoader
            )
        {
            int OFFSETCONSTANT = 8;
            Type[] types = new Type[pResourceNames.Length];
            string[] contents = new string[pResourceNames.Length];
            CodeSnippetCompileUnit[] units = new CodeSnippetCompileUnit[pResourceNames.Length];
            for (int i = 0; i < types.Length; i++)
            {
                string resourceName = pResourceNames[i].Replace('.','/')+".java";
                byte[] byteArray = pReader.getBytes(resourceName);
                string fileContents = this.StringFromBytes(byteArray);
                units[i] = new CodeSnippetCompileUnit(fileContents.Replace("cli.", ""));
                if (fileContents.Contains("public static void consequence"))
                {
                    object[] info = this.GetLinePragmaInfo(fileContents,OFFSETCONSTANT);
                    if(info != null)
                        units[i].LinePragma = new CodeLinePragma(info[0] as string, (int)info[1]);
                }
            }

            CodeDomProvider provider = GetProvider();
            CompilerParameters compilerParameters = new CompilerParameters();
            compilerParameters.GenerateInMemory = true;
            compilerParameters.IncludeDebugInformation = true;

            //            compilerParameters.OutputAssembly = pResourceNames[i].Substring(pResourceNames[i].LastIndexOf('.') + 1);

            int count = 0;
            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {

               if (assembly.FullName.StartsWith("CompiledRules"))
                {
                    try
                    {
                        File.Delete(assembly.Location);
                    }
                    catch (System.Exception e)
                    {
                        count++;
                    }
                }
                else
                {
                    compilerParameters.ReferencedAssemblies.Add(assembly.Location);
                }

            }

            compilerParameters.OutputAssembly = "CompiledRules" + count + ".dll";

            CompilerResults results = provider.CompileAssemblyFromDom
                //(compilerParameters, contents);
                (compilerParameters, units);

            Collection problems = new ArrayList();

            DotnetPackageCompilationData pcData = (DotnetPackageCompilationData)
                ((PackageStore)pStore).getPackageCompilationData();

            MemoryStream stream = new MemoryStream(1024);
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, results.CompiledAssembly);

            for (int i = 0; i < types.Length; i++)
            {
                string resourceName = pResourceNames[i];
                pcData.write(resourceName, new object[]{results.CompiledAssembly, stream.GetBuffer()});

            }
            CompilationProblem[] result = new CompilationProblem[problems.size()];
            return new CompilationResult(result);
        }
        /// <devdoc>
        ///    <para> Generates code for the specified snippet code block
        ///       </para>
        /// </devdoc>
        private void GenerateSnippetCompileUnit(CodeSnippetCompileUnit e) {
            
            GenerateDirectives(e.StartDirectives);

            if (e.LinePragma != null) GenerateLinePragmaStart(e.LinePragma);
            Output.WriteLine(e.Value);
            if (e.LinePragma != null) GenerateLinePragmaEnd(e.LinePragma);

            if (e.EndDirectives.Count > 0) {
                GenerateDirectives(e.EndDirectives);
            }            
        }
Example #24
0
        /// <summary>
        /// 编译代码文件
        /// </summary>
        /// <param name="sourceCode">待编译代码</param>
        /// <param name="filePath">生成文件路径</param>
        /// <param name="referenceString">引用字符串</param>
        /// <returns>编译结果</returns>
        public static string CompileCode(string sourceCode, string filePath, string[] referenceString)
        {
            var p = new CSharpCodeProvider();
#pragma warning disable 618
            var cc = p.CreateCompiler();
#pragma warning restore 618
            var options = new CompilerParameters(referenceString) { GenerateExecutable = true, OutputAssembly = filePath };
            var cu = new CodeSnippetCompileUnit(sourceCode);
            var cr = cc.CompileAssemblyFromDom(options, cu);
            return cr.Errors.Count == 0 ? "" : cr.Errors.Cast<CompilerError>().Aggregate("", (current, error) => current + (error + "\n"));
        }
 private CodeCompileUnit CreateCompileUnit(string virtualPath) {
     var contents = GetContents(virtualPath);
     var unit = new CodeSnippetCompileUnit(contents);
     var physicalPath = _virtualPathProvider.MapPath(virtualPath);
     if (!string.IsNullOrEmpty(physicalPath)) {
         unit.LinePragma = new CodeLinePragma(physicalPath, 1);
     }
     return unit;
 }
 internal CodeCompileUnit GetCodeModel()
 {
     if ((this.sourceString == null) || (this.sourceString.Length == 0))
     {
         return null;
     }
     CodeSnippetCompileUnit unit = new CodeSnippetCompileUnit(this.sourceString);
     string fileName = HostingEnvironmentWrapper.MapPath(this.virtualPath);
     unit.LinePragma = new CodeLinePragma(fileName, this.lineNumber);
     return unit;
 }
Example #27
0
		void CopyFileWithChecksum (Stream input, string to, string from, ICodePragmaGenerator pragmaGenerator)
		{
			if (pragmaGenerator == null) {
				// This is BAD, BAD, BAD! CodeDOM API is really no good in this
				// instance.
				string filedata;
				using (StreamReader sr = new StreamReader (input, WebEncoding.FileEncoding)) {
					filedata = sr.ReadToEnd ();
				}

				var snippet = new CodeSnippetCompileUnit (filedata);
				snippet.LinePragma = new CodeLinePragma (from, 1);
				filedata = null;
				AddCodeCompileUnit (snippet);
				snippet = null;
				
				return;
			}
			
			MD5 checksum = MD5.Create ();
			using (FileStream fs = new FileStream (to, FileMode.Create, FileAccess.Write)) {
				using (StreamWriter sw = new StreamWriter (fs, Encoding.UTF8)) {
					using (StreamReader sr = new StreamReader (input, WebEncoding.FileEncoding)) {
						int count = pragmaGenerator.ReserveSpace (from);
						char[] src;
						
						if (count > COPY_BUFFER_SIZE)
							src = new char [count];
						else
							src = new char [COPY_BUFFER_SIZE];

						sw.Write (src, 0, count);
						do {
							count = sr.Read (src, 0, COPY_BUFFER_SIZE);
							if (count == 0) {
								UpdateChecksum (src, 0, checksum, true);
								break;
							}
						
							sw.Write (src, 0, count);
							UpdateChecksum (src, count, checksum, false);
						} while (true);
						src = null;
					}
				}
			}
			pragmaGenerator.DecorateFile (to, from, checksum, Encoding.UTF8);
		}
Example #28
0
        /// <summary>
        /// CreateSourceFiles - Parse Wsdl Schema and generate DataContract, DataContractSerializer types,
        /// HostedServices and Client Proxies.
        /// </summary>
        /// <remarks>Currently only generates C# source files.</remarks>
        /// <param name="contractFilename">The name of a contract source code (.cs) file.</param>
        /// <param name="hostedServiceFilename">The name of a hosted service source code (.cs) file.</param>
        /// <param name="clientProxyFilename">The name of a client proxy source code (.cs) file.</param>
        /// <param name="targetPlatform">Specifies the target runtime platform.</param>
        public void CreateSourceFiles(string contractFilename, string hostedServiceFilename, string clientProxyFilename, TargetPlatform targetPlatform)
        {
            m_platform = targetPlatform;

            Logger.WriteLine("", LogLevel.Normal);
            Logger.WriteLine("Generating contract source: " + contractFilename + "...", LogLevel.Normal);

            if (contractFilename == null)
                throw new ArgumentNullException("codeFilename", "You must pass a valid code filename.");

            if (m_svcDesc.Types == null)
            {
                throw new Exception("No wsdl types found.");
            }

            string path = Path.GetDirectoryName(contractFilename).Trim();

            if(!string.IsNullOrEmpty(path) && !Directory.Exists(path)) 
            {
                Directory.CreateDirectory(path);
            }

            // Create code file stream
            FileStream dcStream = new FileStream(contractFilename, FileMode.Create, FileAccess.Write, FileShare.None);
            StreamWriter dcStreamWriter = new StreamWriter(dcStream);

            // Write the auto generated header
            dcStreamWriter.Write(AutoGenTextHeader.Message);

            try
            {

                // Set up data contract code generator
                CSharpCodeProvider cSharpCP = new CSharpCodeProvider();
                ICodeGenerator codeGen = cSharpCP.CreateGenerator(dcStreamWriter);
                CodeGeneratorOptions codeGenOptions = new CodeGeneratorOptions();
                codeGenOptions.BracingStyle = "C";

                // Cobble up a valid .net namespace. Turn any progression that's not a-z or A-Z to a single '.'
                string targetNamespaceName = CodeGenUtils.GenerateDotNetNamespace(m_svcDesc.TargetNamespace);

                // For some reason we have to force schemas to compile. Though it was suppose to automatically. Huh!
                foreach (XmlSchema schema in m_svcDesc.Types.Schemas)
                {
                    XmlSchemaSet schemaSet = new XmlSchemaSet();
                    schemaSet.Add(schema);
                    schemaSet.Compile();
                }
                

                // Create new code namespace
                CodeNamespace targetNamespace = new CodeNamespace(targetNamespaceName);

                // Add data contract using directives
                CodeSnippetCompileUnit compileUnit = new CodeSnippetCompileUnit("using System;");
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using System.Xml;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                if (m_platform == TargetPlatform.MicroFramework)
                {
                    compileUnit.Value = "using System.Ext;";
                    codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                    compileUnit.Value = "using System.Ext.Xml;";
                    codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                }
                compileUnit.Value = "using Ws.ServiceModel;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using Ws.Services.Mtom;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using Ws.Services.Serialization;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlElement = Ws.Services.Xml.WsXmlNode;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlAttribute = Ws.Services.Xml.WsXmlAttribute;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlConvert = Ws.Services.Serialization.WsXmlConvert;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Namespaces.Add(targetNamespace);
                m_dcCodeGen.CodeNamespaces = compileUnit.Namespaces;

                Logger.WriteLine("", LogLevel.Normal);

                // Create HostedServices and ClientProxies collections
                HostedServices hostedServices = new HostedServices(targetNamespaceName);
                ClientProxies clientProxies = new ClientProxies(targetNamespaceName);

                // For each PortType process
                foreach (PortType portType in m_svcDesc.PortTypes)
                {
                    // For each operation in the port type:
                    // Get input and output message parts.
                    // If the message part is a simple type:
                    //   Build HostedService operation.
                    // Else if the message part is an element:
                    //   Find elements in Schema
                    //   If element type is native xml type:
                    //     Build HostedService operation.
                    //   Else if element references a simple or complex type:
                    //     If simpleType is base xml type with restrictions:
                    //       Build HostedService operation.
                    //     Else
                    //       Build DataContract and DataContractSerializer.
                    //       Build HostedService Operation.
                    //     

                    if (!CodeGenUtils.IsSoapBinding(portType, m_svcDesc))
                    {
                        continue;
                    }

                    // Create instance of a HostedService to hold the port type details
                    HostedService hostedService = new HostedService(portType.Name, m_svcDesc.TargetNamespace, m_platform);

                    // Create instance of ClientProxyGenerator
                    ClientProxy clientProxy = new ClientProxy(portType.Name, m_platform);

                    // Create service contract interface
                    CodeTypeDeclaration serviceCodeType = new CodeTypeDeclaration("I" + portType.Name);
                    CodeAttributeArgument codeAttr = new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(m_svcDesc.TargetNamespace));
                    CodeAttributeDeclaration codeAttrDecl = new CodeAttributeDeclaration("ServiceContract", codeAttr);
                    serviceCodeType.CustomAttributes.Add(codeAttrDecl);

                    // Check for Policy assertions. If found add policy assertion attributes. Policy assertion attributes
                    // are required to regenerate policy assertions when converting a service to Wsdl.
                    List<PolicyAssertion> policyAssertions = GetPolicyAssertions();
                    bool OptimizedMimeEncoded = false;
                    foreach (PolicyAssertion assert in policyAssertions)
                    {
                        serviceCodeType.CustomAttributes.Add(CreatePolicyAssertions(assert.Name, assert.Namespace.ToString(), assert.PolicyID));
                    
                        // if Optimized Mime assertion id found set a processing flag
                        if (assert.Name == "OptimizedMimeSerialization")
                        {
                            OptimizedMimeEncoded = true;
                        }
                    }

                    // Add type declaration
                    serviceCodeType.TypeAttributes = TypeAttributes.Public;
                    serviceCodeType.IsInterface = true;

                    // Create service contract callback client interface
                    CodeTypeDeclaration serviceCallbackCodeType = new CodeTypeDeclaration("I" + portType.Name + "Callback");

                    // Add type declaration
                    serviceCallbackCodeType.TypeAttributes = TypeAttributes.Public;
                    serviceCallbackCodeType.IsInterface = true;

                    // If the binding contains a ref to Mtom encoding type set the Mtom flag
                    if (OptimizedMimeEncoded)
                    {
                        m_dcCodeGen.EncodingType = MessageEncodingType.Mtom;
                        hostedService.EncodingType = MessageEncodingType.Mtom;
                        clientProxy.EncodingType = MessageEncodingType.Mtom;
                    }

                    // Step through port operations, get method names and parse elements.
                    for (int pt_index = 0; pt_index < portType.Operations.Count; ++pt_index)
                    {
                        Operation operation = portType.Operations[pt_index];
                        string operationName = operation.Name;

                        string inputMessageName = null;
                        string outputMessageName = null;
                        MessagePartCollection inputMessageParts = null;
                        MessagePartCollection outputMessageParts = null;
                        string inAction = null;
                        string outAction = null;
                        GetAction(portType, operation, m_svcDesc.TargetNamespace, ref inAction, ref outAction);

                        // Oneway request port type
                        if (operation.Messages.Flow == OperationFlow.OneWay)
                        {
                            OperationInput input = operation.Messages.Input;
                            inputMessageName = input.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }
                        // Twoway request/response pattern
                        else if (operation.Messages.Flow == OperationFlow.RequestResponse)
                        {
                            OperationInput input = operation.Messages.Input;
                            inputMessageName = input.Message.Name;
                            OperationOutput output = operation.Messages.Output;
                            outputMessageName = output.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }
                        // Event pattern
                        else if (operation.Messages.Flow == OperationFlow.Notification)
                        {
                            OperationOutput output = operation.Messages.Output;
                            outputMessageName = output.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }

                        // Find input and output message parts collection in messages collection
                        // and store for later.
                        foreach (Message message in m_svcDesc.Messages)
                        {
                            if (inputMessageName != null)
                                if (message.Name == inputMessageName)
                                {
                                    inputMessageParts = message.Parts;

                                    // Add operation for HostedService code generation
                                    hostedService.Messages.Add(message);

                                    // Add Message to ClientProxy generator for later
                                    clientProxy.Messages.Add(message);
                                }

                            if (outputMessageName != null)
                                if (message.Name == outputMessageName)
                                {
                                    outputMessageParts = message.Parts;

                                    // Add operation for HostedService code generation
                                    hostedService.Messages.Add(message);

                                    // Add Message to ClientProxy generator for later
                                    clientProxy.Messages.Add(message);
                                }
                        }

                        try
                        {
                            // Try to generate Data Contracts and DataContractSerializers
                            GenerateTypeContracts(operation, inputMessageParts, outputMessageParts);

                            // If operation flow is notification (event) add OperationContract to ServiceContractCallback
                            // else add OperationContract to ServiceContract
                            if (operation.Messages.Flow == OperationFlow.Notification)
                            {
                                AddServiceOperationToInterface(operation, outAction, serviceCallbackCodeType);
                            }
                            else
                                AddServiceOperationToInterface(operation, inAction, serviceCodeType);
                        }
                        catch (Exception e)
                        {
                            dcStreamWriter.Close();
                            File.Delete(contractFilename);
                            Logger.WriteLine("Failed to generate service code. " + e.Message, LogLevel.Normal);
                            return;
                        }
                    }

                    // Add serviceCodeType Service Contract interface to namespace
                    // A serviceCodeType is added even if the wsdl only contains notifications. In that case
                    // the contract will be empty but the ServiceContract attribute and CallbackContract argument
                    // will be used to point to the notification or callback contract interace
                    targetNamespace.Types.Add(serviceCodeType);

                    // If service contract callback type contains members add callback contract to namespace
                    // and add CallbackContract reference attribute to serviceCodeType contract.
                    if (serviceCallbackCodeType.Members.Count > 0)
                    {
                        // Add the callback argument to the service description attribute
                        CodeAttributeArgument callbackArg = new CodeAttributeArgument("CallbackContract",
                            new CodeTypeOfExpression(serviceCallbackCodeType.Name)
                        );
                        serviceCodeType.CustomAttributes[0].Arguments.Add(callbackArg);

                        // Add the callback interface to namespace
                        targetNamespace.Types.Add(serviceCallbackCodeType);
                    }

                    // If the hosted service has opeations add to Hosted Services collection for Code Gen
                    if (hostedService.ServiceOperations.Count > 0)
                        hostedServices.Add(hostedService);

                    // If the client Proxy service has opeations add to client proxy collection for Code Gen
                    if (clientProxy.ServiceOperations.Count > 0)
                        clientProxies.Add(clientProxy);
                }

                // MOD: 12-02-08 Added code to handle multiple type namespaces
                // Generate contract source file
                foreach (CodeNamespace codeNamespace in compileUnit.Namespaces)
                {
                    codeGen.GenerateCodeFromNamespace(codeNamespace, dcStreamWriter, codeGenOptions);
                }
                dcStreamWriter.Flush();
                dcStreamWriter.Close();

                // Generate Hosted Service code
                Logger.WriteLine("Generating Hosted Service source: " + hostedServiceFilename + "...", LogLevel.Normal);
                HostedServiceGenerator hsGen = new HostedServiceGenerator();
                hsGen.GenerateCode(hostedServiceFilename, hostedServices);

                // Generate Client proxy code
                Logger.WriteLine("Generating Client Proxy source: " + clientProxyFilename + "...", LogLevel.Normal);
                ClientProxyGenerator cpGen = new ClientProxyGenerator();
                cpGen.GenerateCode(clientProxyFilename, clientProxies);
            }
            catch (Exception e)
            {
                dcStreamWriter.Close();
                File.Delete(contractFilename);
                Logger.WriteLine("Failed to generate service code. " + e.Message, LogLevel.Normal);
                throw new Exception("Failed to generate service code. ", e);
            }
        }
    internal CodeCompileUnit GetCodeModel() {

        // Do we have something to compile?
        if (_sourceString == null)
            return null;

        CodeSnippetCompileUnit snippetCompileUnit = new CodeSnippetCompileUnit(_sourceString);

        // Put in some context so that the file can be debugged.
        snippetCompileUnit.LinePragma = BaseCodeDomTreeGenerator.CreateCodeLinePragmaHelper(
            _virtualPath.VirtualPathString, _lineNumber);

        return snippetCompileUnit;
    }
        protected virtual CodeSnippetCompileUnit Rewrite(CodeSnippetCompileUnit source, ref bool didRewrite)
        {
            if (source == null)
            {
                return source;
            }

            bool didChildRewrite = false;
            CodeSnippetCompileUnit result = new CodeSnippetCompileUnit();
            result.Value = source.Value;
            result.LinePragma = this.Rewrite(source.LinePragma, ref didChildRewrite);
            this.Rewrite(result.Namespaces, source.Namespaces, ref didChildRewrite);
            this.Rewrite(result.ReferencedAssemblies, source.ReferencedAssemblies, ref didChildRewrite);
            this.Rewrite(result.AssemblyCustomAttributes, source.AssemblyCustomAttributes, ref didChildRewrite);
            this.Rewrite(result.StartDirectives, source.StartDirectives, ref didChildRewrite);
            this.Rewrite(result.EndDirectives, source.EndDirectives, ref didChildRewrite);
            this.Rewrite(result.UserData, source.UserData, ref didChildRewrite);
            if (didChildRewrite)
            {
                didRewrite = true;
                return result;
            }
            else
            {
                return source;
            }
        }