Beispiel #1
0
 public CompilerResults Compile()
 {
     Dictionary<string, string> dictionary = new Dictionary<string, string>();
     dictionary.Add("CompilerVersion", "v4.0");
     CodeDomProvider codeDomProvider;
     switch (this.codeLang)
     {
         case CodeLang.CSharp:
             codeDomProvider = new CSharpCodeProvider(dictionary);
             break;
         case CodeLang.VisualBasic:
             codeDomProvider = new VBCodeProvider(dictionary);
             break;
         default:
             throw new NotSupportedException(string.Format("Not supported code language - {0}", this.codeLang));
     }
     foreach (string reference in this.references)
         this.parameters.ReferencedAssemblies.Add(reference);
     if (this.codeLang == CodeLang.VisualBasic)
     {
         foreach (object obj in new List<string>()
         {  
             "FreeQuant.FIX", 
             "FreeQuant.Instruments", 
             "FreeQuant.Series", 
             "FreeQuant.Charting" 
         })
             this.parameters.ReferencedAssemblies.Add(Path.Combine(Framework.Installation.BinDir.FullName, string.Format("{0}.dll", obj)));
     }
     return codeDomProvider.CompileAssemblyFromFile(this.parameters, this.filenames.ToArray());
 }
Beispiel #2
0
        public static void Load(PluginInterface.logprintf_t logprint, string indent)
        {
            LogPrint = logprint;
            Indent = indent;
            if (!Directory.Exists(WorkingDir))
                Directory.CreateDirectory(WorkingDir);

            ConvertIncludes();

            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory = false;
            parameters.ReferencedAssemblies.AddRange(Assembly.GetExecutingAssembly().GetReferencedAssemblies().Select(entry => entry.Name).ToArray());
            parameters.WarningLevel = 4;

            string[] csfiles = Directory.GetFiles(WorkingDir, "*.cs");
            LogPrint(Indent + "Loading " + csfiles.Length + " CSharp files...");
            foreach (string file in csfiles)
            {
                PrepCompilerParameters(file, parameters);
                //if (csfiles.Length > 0)
                //{
                CSharpCodeProvider csprovider = new CSharpCodeProvider();
                //CompilerResults results = csprovider.CompileAssemblyFromFile(parameters, csfiles);
                CompilerResults results = csprovider.CompileAssemblyFromFile(parameters, file);
                Parse(results);
                //}
                //parameters.ReferencedAssemblies.Add(file); //Hozzáadja az aktuális fájlt a következőhöz, hogy... - Csak a legutolsó kapná meg az összeset
            }
            LogPrint(Indent + "Loaded " + csfiles.Length + " CSharp files.");

            string[] vbfiles = Directory.GetFiles(WorkingDir, "*.vb");
            LogPrint(Indent + "Loading " + vbfiles.Length + " VisualBasic files...");
            //if (vbfiles.Length > 0)
            foreach (string file in vbfiles)
            {
                PrepCompilerParameters(file, parameters);
                VBCodeProvider vbprovider = new VBCodeProvider();
                CompilerResults results = vbprovider.CompileAssemblyFromFile(parameters, vbfiles);
                Parse(results);
            }
            LogPrint(Indent + "Loaded " + vbfiles.Length + " VisualBasic files.");
        }
Beispiel #3
0
		public static bool CompileVBScripts( bool debug, bool cache, out Assembly assembly )
		{
			Console.Write( "Scripts: Compiling VB.NET scripts..." );
			string[] files = GetScripts( "*.vb" );

			if( files.Length == 0 )
			{
				Console.WriteLine( "no files found." );
				assembly = null;
				return true;
			}

			if( File.Exists( "Scripts/Output/Scripts.VB.dll" ) )
			{
				if( cache && File.Exists( "Scripts/Output/Scripts.VB.hash" ) )
				{
					byte[] hashCode = GetHashCode( "Scripts/Output/Scripts.VB.dll", files, debug );

					try
					{
						using( FileStream fs = new FileStream( "Scripts/Output/Scripts.VB.hash", FileMode.Open, FileAccess.Read, FileShare.Read ) )
						{
							using( BinaryReader bin = new BinaryReader( fs ) )
							{
								byte[] bytes = bin.ReadBytes( hashCode.Length );

								if( bytes.Length == hashCode.Length )
								{
									bool valid = true;

									for( int i = 0; i < bytes.Length; ++i )
									{
										if( bytes[i] != hashCode[i] )
										{
											valid = false;
											break;
										}
									}

									if( valid )
									{
										assembly = Assembly.LoadFrom( "Scripts/Output/Scripts.VB.dll" );

										if( !m_AdditionalReferences.Contains( assembly.Location ) )
										{
											m_AdditionalReferences.Add( assembly.Location );
										}

										Console.WriteLine( "done (cached)" );

										return true;
									}
								}
							}
						}
					}
					catch
					{
					}
				}
			}

			DeleteFiles( "Scripts.VB*.dll" );
#if Framework_3_5
			using ( VBCodeProvider provider = new VBCodeProvider( new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } } ) )
#else
			using ( VBCodeProvider provider = new VBCodeProvider() )
#endif
			{
				string path = GetUnusedPath( "Scripts.VB" );

				CompilerParameters parms = new CompilerParameters( GetReferenceAssemblies(), path, debug );

				string defines = GetDefines();

				if( defines != null )
					parms.CompilerOptions = String.Format( "/D:{0}", defines );

				if( Core.HaltOnWarning )
					parms.WarningLevel = 4;

				CompilerResults results = provider.CompileAssemblyFromFile( parms, files );
				m_AdditionalReferences.Add( path );

				Display( results );

				if( results.Errors.Count > 0 )
				{
					assembly = null;
					return false;
				}

				if( cache && Path.GetFileName( path ) == "Scripts.VB.dll" )
				{
					try
					{
						byte[] hashCode = GetHashCode( path, files, debug );

						using( FileStream fs = new FileStream( "Scripts/Output/Scripts.VB.hash", FileMode.Create, FileAccess.Write, FileShare.None ) )
						{
							using( BinaryWriter bin = new BinaryWriter( fs ) )
							{
								bin.Write( hashCode, 0, hashCode.Length );
							}
						}
					}
					catch
					{
					}
				}

				assembly = results.CompiledAssembly;
				return true;
			}
		}
Beispiel #4
0
        public static Assembly CompileVB(string path, string dllName, string[] reflections)
        {
            if (!path.EndsWith(@"\") && !path.EndsWith(@"/")) path += "/";

            ArrayList files = ParseDirectory(new DirectoryInfo(path), "*.vb", true);

            if (files.Count == 0)
            {
                return null;
            }

            if (File.Exists(dllName))
            {
                File.Delete(dllName);
            }

            try
            {
                CodeDomProvider compiler = new VBCodeProvider();

                CompilerParameters param = new CompilerParameters(reflections, dllName, true);

                param.GenerateExecutable = false;
                param.GenerateInMemory = false;
                param.WarningLevel = 2;
                param.CompilerOptions = @"/lib:.";

                string[] filePaths = new string[files.Count];

                for (int i = 0; i < files.Count; i++)
                {
                    filePaths[i] = ((FileInfo)files[i]).FullName;
                }

                CompilerResults rlt = compiler.CompileAssemblyFromFile(param, filePaths);

                GC.Collect();

                if (rlt == null)
                {
                    return null;
                }

                if (rlt.Errors.HasErrors)
                {
                    foreach (CompilerError err in rlt.Errors)
                    {
                        if (err.IsWarning)
                        {
                            continue;
                        }

                        StringBuilder sb = new StringBuilder();

                        sb.Append("    ");
                        sb.Append(err.FileName);
                        sb.Append(" 行:");
                        sb.Append(err.Line);
                        sb.Append(" 列:");
                        sb.Append(err.Column);

                        if (log.IsErrorEnabled)
                        {
                            log.Error("Compilation failed, because:");
                            log.Error(err.ErrorText);
                            log.Error(sb.ToString());
                        }
                    }
                    return null;
                }

                return rlt.CompiledAssembly;
            }
            catch (Exception ex)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("Compilation", ex);
                }

                return null;
            }
        }
Beispiel #5
0
        /// <summary>
        /// Loads a C#/VB Script.
        /// </summary>
        /// <param name="includes">A array of string of referenced assembly file names.</param>
        /// <param name="ct">The CodeType of the script.</param>
        /// <exception cref="ModuleLoadException">When the module fails to load this is thrown.</exception>
        public void LoadScript(string[] includes, CodeType ct)
        {
            CodeDomProvider languageProvider = null;
            switch ( ct ) {
                case CodeType.CSharp:
                    languageProvider = new CSharpCodeProvider();
                    break;
                case CodeType.VisualBasic:
                    languageProvider = new VBCodeProvider();
                    break;
            }

            if ( languageProvider == null )
                throw new ModuleLoadException( "Compiler class for CodeType: " + ( (int)ct ).ToString() + " not found." );

            for ( int i = 0; i < filenames.Length; i++ ) {
                if ( !System.IO.File.Exists( filenames[i] ) && Configuration.ModuleConfig.ModulePath != null )
                    filenames[i] =
                        System.IO.Path.GetFullPath( System.IO.Path.Combine( Configuration.ModuleConfig.ModulePath, filenames[i] ) );
            }

            CompilerParameters cp = new CompilerParameters();
            cp.GenerateInMemory = true;
            cp.GenerateExecutable = false;
            cp.ReferencedAssemblies.AddRange( includes );
            cp.OutputAssembly = assemblyName;
            cp.IncludeDebugInformation = false;

            CompilerResults cr = languageProvider.CompileAssemblyFromFile(
                cp, filenames );

            if ( cr.Errors.Count > 0 ) {
                string[] errors = new string[cr.Errors.Count];
                for ( int i = 0; i < cr.Errors.Count; i++ )
                    errors[i] = cr.Errors[i].ToString();
                throw new ModuleLoadException( "Failed to compile", errors );
            }

            Type moduleType = null;
            assembly = cr.CompiledAssembly;

            try {
                moduleType = assembly.GetType( classname, true, false );
            }
            catch ( Exception ) {
                throw new ModuleLoadException( "Type not found: " + classname );
            }

            bool createAnInstance = true;
            bool useParamList = true;

            ConstructorInfo classConstructor =
                moduleType.GetConstructor(
                BindingFlags.Public | BindingFlags.Instance,
                null,
                new Type[] { typeof( ModuleProxy ), typeof( int ) }, //Constructor arglist.
                null );

            if ( classConstructor == null ) {

                useParamList = false;

                classConstructor = moduleType.GetConstructor(
                    BindingFlags.Public | BindingFlags.Instance,
                    null, new Type[0], null );

                if ( classConstructor == null )
                    createAnInstance = false;
            }

            if ( createAnInstance && useParamList )
                instanceOfModule = classConstructor.Invoke( new object[] { this, (object)moduleId } );
            else if ( createAnInstance )
                instanceOfModule = classConstructor.Invoke( null );
            else
                instanceOfModule = null;

            useParamList = false; //Shortchange our system. See above.

            IModuleCreator imc = instanceOfModule as IModuleCreator;
            if ( imc != null ) {
                imc.Initialize( this, moduleId );
                imc.Initialize();
            }
        }
Beispiel #6
0
        public static CompilerResults CompileFromVBSourceStream(Stream sourceStream, CompilerParameters cParams)
        {
            String tmpFile = Path.GetTempFileName();
            using (FileStream output = new FileStream(tmpFile, FileMode.Create))
            {
                byte[] buffer = new byte[sourceStream.Length];
                sourceStream.Seek(0, SeekOrigin.Begin);
                sourceStream.Read(buffer, 0, buffer.Length);
                output.Write(buffer, 0, buffer.Length);
            }

            using (CodeDomProvider provider = new VBCodeProvider())
            {
                CompilerResults res = provider.CompileAssemblyFromFile(cParams, tmpFile);

                File.Delete(tmpFile);

                return res;
            }
        }
Beispiel #7
0
        public static CompilerResults CompileFromVBSourceFile(String sourceFile, CompilerParameters cParams)
        {
            using (CodeDomProvider provider = new VBCodeProvider())
            {
                CompilerResults res = provider.CompileAssemblyFromFile(cParams, sourceFile);

                return res;
            }
        }
        /// <summary>
        /// Compiles all the vb scripts.
        /// </summary>
        private void CompileVBScripts()
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            dictionary.Add("CompilerVersion", Settings.Framework);
            CompilerParameters compilerParameters = new CompilerParameters
            {
                GenerateInMemory = true
            };

            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            for (int i = 0; i < assemblies.Length; i++)
            {
                Assembly assembly = assemblies[i];
                compilerParameters.ReferencedAssemblies.Add(assembly.Location);
            }
            foreach (string refs in System.IO.Directory.GetFiles(Settings.ScriptLocation + "\\references"))
                compilerParameters.ReferencedAssemblies.Add(refs);
            foreach (Type type in Settings.types.Values)
                compilerParameters.ReferencedAssemblies.Add(Assembly.GetAssembly(type).Location);
            VBCodeProvider vbCodeProvider = new VBCodeProvider();
            CompilerResults compilerResults = vbCodeProvider.CompileAssemblyFromFile(compilerParameters, Settings.ScriptLocation + currentcompilefile + ".vb");
            if (compilerResults.Errors.Count != 0)
            {
                foreach (CompilerError err in compilerResults.Errors)
                    Console.WriteLine(err.ToString());
            }
            else
            {
                foreach (Type type in compilerResults.CompiledAssembly.GetTypes())
                {
                    if (type.Namespace == "scriptnamespace" && type.IsClass && type.Name == "scriptclass")
                    {
                        foreach (MethodInfo method in type.GetMethods())
                        {
                            if (method.IsStatic)
                            {
                                if (method.Name.StartsWith("script_"))
                                    scriptCollection.AddOrUpdate(uint.Parse(method.Name.Split('_')[1]), method);
                            }
                        }
                    }
                }
            }
        }
        public static bool CompileVBScripts( bool debug, bool cache, out Assembly assembly )
        {
            Console.Write( "Scripts: Compilando Scripts VB.NET... " );
            string[] files = GetScripts( "*.vb" );

            if( files.Length == 0 )
            {
                Console.WriteLine( "Nenhum arquivo encontrado." );
                assembly = null;
                return true;
            }

            if( File.Exists( "Scripts/Output/Scripts.VB.dll" ) )
            {
                if( cache && File.Exists( "Scripts/Output/Scripts.VB.hash" ) )
                {
                    byte[] hashCode = GetHashCode( "Scripts/Output/Scripts.VB.dll", files, debug );

                    try
                    {
                        using( FileStream fs = new FileStream( "Scripts/Output/Scripts.VB.hash", FileMode.Open, FileAccess.Read, FileShare.Read ) )
                        {
                            using( BinaryReader bin = new BinaryReader( fs ) )
                            {
                                byte[] bytes = bin.ReadBytes( hashCode.Length );

                                if( bytes.Length == hashCode.Length )
                                {
                                    bool valid = true;

                                    for( int i = 0; i < bytes.Length; ++i )
                                    {
                                        if( bytes[i] != hashCode[i] )
                                        {
                                            valid = false;
                                            break;
                                        }
                                    }

                                    if( valid )
                                    {
                                        assembly = Assembly.LoadFrom( "Scripts/Output/Scripts.VB.dll" );

                                        if( !m_AdditionalReferences.Contains( assembly.Location ) )
                                        {
                                            m_AdditionalReferences.Add( assembly.Location );
                                        }

                                        Console.WriteLine( "Pronto (encontrado em cache)" );

                                        return true;
                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                    }
                }
            }

            DeleteFiles( "Scripts.VB*.dll" );

            using ( VBCodeProvider provider = new VBCodeProvider() )
            {
                string path = GetUnusedPath( "Scripts.VB" );

                CompilerParameters parms = new CompilerParameters( GetReferenceAssemblies(), path, debug );

                string options = GetCompilerOptions( debug );

                if( options != null )
                    parms.CompilerOptions = options;

                if( Core.HaltOnWarning )
                    parms.WarningLevel = 4;

                CompilerResults results = provider.CompileAssemblyFromFile( parms, files );
                m_AdditionalReferences.Add( path );

                Display( results );

                if( results.Errors.Count > 0 )
                {
                    assembly = null;
                    return false;
                }

                if( cache && Path.GetFileName( path ) == "Scripts.VB.dll" )
                {
                    try
                    {
                        byte[] hashCode = GetHashCode( path, files, debug );

                        using( FileStream fs = new FileStream( "Scripts/Output/Scripts.VB.hash", FileMode.Create, FileAccess.Write, FileShare.None ) )
                        {
                            using( BinaryWriter bin = new BinaryWriter( fs ) )
                            {
                                bin.Write( hashCode, 0, hashCode.Length );
                            }
                        }
                    }
                    catch
                    {
                    }
                }

                assembly = results.CompiledAssembly;
                return true;
            }
        }
        /// <summary>
        /// 编译VB的源码
        /// </summary>
        private static bool CompileVBScripts( bool bDebug, bool bCache, string strAssemblyDirectory, string strScriptDirectory, ref ScriptAssemblyInfo scriptAssemblyInfo )
        {
            LOGs.WriteLine( LogMessageType.MSG_INFO, LanguageString.SingletonInstance.ScriptCompilerString010 );

            string[] strFiles = GetScripts( strScriptDirectory, "*.vb" );

            string strFilePath = strAssemblyDirectory + "/Scripts.VB.dll";

            if ( strFiles.Length <= 0 )
            {
                if ( bCache && File.Exists( strFilePath ) )
                {
                    Assembly assembly = Assembly.LoadFile( Path.GetFullPath( strFilePath ) );

                    scriptAssemblyInfo.AddScriptAssembly( assembly );
                    scriptAssemblyInfo.AddHashCode( assembly, new byte[0] );
                    scriptAssemblyInfo.AddScriptFiles( assembly, strFiles );

                    if ( s_AdditionalReferences.Contains( assembly.Location ) == false )
                    {
                        s_AdditionalReferences.Add( assembly.Location );
                        s_AdditionalReferenceArray = s_AdditionalReferences.ToArray();
                    }

                    LOGs.WriteLine( LogMessageType.MSG_INFO, LanguageString.SingletonInstance.ScriptCompilerString011 );
                    return true;
                }
                else
                {
                    LOGs.WriteLine( LogMessageType.MSG_WARNING, LanguageString.SingletonInstance.ScriptCompilerString012 );
                    return true;
                }
            }

            string strHashFilePath = strAssemblyDirectory + "/Scripts.CS.hash";

            if ( File.Exists( strFilePath ) )
            {
                if ( bCache && File.Exists( strHashFilePath ) )
                {
                    byte[] byteHashCode = GetHashCode( strFilePath, strFiles, bDebug );

                    using ( FileStream fileStream = new FileStream( strHashFilePath, FileMode.Open, FileAccess.Read, FileShare.Read ) )
                    {
                        using ( BinaryReader binaryReader = new BinaryReader( fileStream ) )
                        {
                            byte[] bytes = binaryReader.ReadBytes( byteHashCode.Length );

                            if ( bytes.Length == byteHashCode.Length )
                            {
                                bool bValid = true;

                                for ( int iIndex = 0; iIndex < bytes.Length; ++iIndex )
                                {
                                    if ( bytes[iIndex] != byteHashCode[iIndex] )
                                    {
                                        bValid = false;
                                        break;
                                    }
                                }

                                if ( bValid )
                                {
                                    Assembly assembly = Assembly.LoadFile( Path.GetFullPath( strFilePath ) );

                                    scriptAssemblyInfo.AddScriptAssembly( assembly );
                                    scriptAssemblyInfo.AddHashCode( assembly, byteHashCode );
                                    scriptAssemblyInfo.AddScriptFiles( assembly, strFiles );

                                    if ( s_AdditionalReferences.Contains( assembly.Location ) == false )
                                    {
                                        s_AdditionalReferences.Add( assembly.Location );
                                        s_AdditionalReferenceArray = s_AdditionalReferences.ToArray();
                                    }

                                    LOGs.WriteLine( LogMessageType.MSG_INFO, LanguageString.SingletonInstance.ScriptCompilerString013 );

                                    return true;
                                }
                            }
                        }
                    }
                }
            }

            DeleteFiles( strAssemblyDirectory, "Scripts.VB*.dll" );

            using ( VBCodeProvider provider = new VBCodeProvider( new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } } ) )
            {
                string strUnusedPath = GetUnusedPath( strAssemblyDirectory, "Scripts.VB" );

                CompilerParameters compilerParameters = new CompilerParameters( GetReferenceAssemblies( strScriptDirectory ), strUnusedPath, bDebug );

                string strDefines = GetDefines();

                if ( strDefines != string.Empty )
                    compilerParameters.CompilerOptions = strDefines;

                if ( OneServer.HaltOnWarning == true )
                    compilerParameters.WarningLevel = 4;

                CompilerResults compilerResults = provider.CompileAssemblyFromFile( compilerParameters, strFiles );

                Display( strScriptDirectory, compilerResults );

                if ( compilerResults.Errors.Count > 0 )
                    return false;

                // 开始HashCode
                byte[] byteHashCode = GetHashCode( strUnusedPath, strFiles, bDebug );

                using ( FileStream fileStream = new FileStream( strHashFilePath, FileMode.Create, FileAccess.Write, FileShare.None ) )
                {
                    using ( BinaryWriter binaryWriter = new BinaryWriter( fileStream ) )
                        binaryWriter.Write( byteHashCode, 0, byteHashCode.Length );
                }

                Assembly assembly = Assembly.LoadFile( Path.GetFullPath( strUnusedPath ) );

                scriptAssemblyInfo.AddScriptAssembly( assembly );
                scriptAssemblyInfo.AddHashCode( assembly, byteHashCode );
                scriptAssemblyInfo.AddScriptFiles( assembly, strFiles );

                if ( s_AdditionalReferences.Contains( assembly.Location ) == false )
                {
                    s_AdditionalReferences.Add( assembly.Location );
                    s_AdditionalReferenceArray = s_AdditionalReferences.ToArray();
                }

                return true;
            }
        }