Example #1
0
        private void CompileClick(CompileTarget target)
        {
            if (openDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            string folder = "";

            if (target == CompileTarget.File)
            {
                if (folderDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
            }

            folder = folderDialog.SelectedPath;

            var database       = cbbDatabaseList.SelectedItem as DatabaseInfo;
            var templates      = openDialog.FileNames.ToList();
            var selectedTables = lbTables.SelectedItems.OfType <TableInfo>().ToList();

            if (database == null || templates.Count == 0 || selectedTables.Count == 0)
            {
                return;
            }

            Compile?.Invoke(database, selectedTables, templates, target, folder);
        }
Example #2
0
        public DeployFileCollection GetDeployFiles(ConfigurationSelector configuration)
        {
            DeployFileCollection deployFiles = new DeployFileCollection();

            CProjectConfiguration conf   = (CProjectConfiguration)GetConfiguration(configuration);
            CompileTarget         target = conf.CompileTarget;

            // Headers and resources
            foreach (ProjectFile f in Files)
            {
                if (f.BuildAction == BuildAction.Content)
                {
                    string targetDirectory =
                        (IsHeaderFile(f.Name) ? TargetDirectory.Include : TargetDirectory.ProgramFiles);

                    deployFiles.Add(new DeployFile(this, f.FilePath, f.ProjectVirtualPath, targetDirectory));
                }
            }

            // Output
            string output = GetOutputFileName(configuration);

            if (!string.IsNullOrEmpty(output))
            {
                string targetDirectory = string.Empty;

                switch (target)
                {
                case CompileTarget.Bin:
                    targetDirectory = TargetDirectory.ProgramFiles;
                    break;

                case CompileTarget.SharedLibrary:
                    targetDirectory = TargetDirectory.ProgramFiles;
                    break;

                case CompileTarget.StaticLibrary:
                    targetDirectory = TargetDirectory.ProgramFiles;
                    break;
                }

                deployFiles.Add(new DeployFile(this, output, Path.GetFileName(output), targetDirectory));
            }

            // PkgPackage
            if (target != CompileTarget.Bin)
            {
                string pkgfile = WriteDeployablePgkPackage(this, conf);
                deployFiles.Add(new DeployFile(this, Path.Combine(BaseDirectory, pkgfile), pkgfile, LinuxTargetDirectory.PkgConfig));
            }

            return(deployFiles);
        }
Example #3
0
        public void ReadDefaultCompileTarget(MSBuildProject project)
        {
            string outputType = project.EvaluatedProperties.GetValue("OutputType");

            if (!string.IsNullOrEmpty(outputType))
            {
                if (!Enum.TryParse(outputType, out defaultCompileTarget))
                {
                    defaultCompileTarget = CompileTarget.Library;
                }
            }
        }
        static string TargetToString(CompileTarget target)
        {
            switch (target)
            {
            case CompileTarget.WinExe:
                return("winexe");

            case CompileTarget.Library:
                return("library");
            }
            return("exe");
        }
Example #5
0
        public void Store(ItemConfigurationCollection <ItemConfiguration> configs)
        {
            int           codePage;
            CompileTarget compileTarget = (CompileTarget)compileTargetCombo.Active;
            LangVersion   langVersion   = (LangVersion)langVerCombo.Active;


            if (codepageEntry.Entry.Text.Length > 0)
            {
                // Get the codepage. If the user specified an encoding name, find it.
                int trialCodePage = -1;
                foreach (TextEncoding e in TextEncoding.SupportedEncodings)
                {
                    if (e.Id == codepageEntry.Entry.Text)
                    {
                        trialCodePage = e.CodePage;
                        break;
                    }
                }

                if (trialCodePage != -1)
                {
                    codePage = trialCodePage;
                }
                else
                {
                    if (!int.TryParse(codepageEntry.Entry.Text, out trialCodePage))
                    {
                        return;
                    }
                    codePage = trialCodePage;
                }
            }
            else
            {
                codePage = 0;
            }

            project.CompileTarget = compileTarget;

            CSharpProjectParameters projectParameters = (CSharpProjectParameters)project.LanguageParameters;

            projectParameters.CodePage = codePage;

            if (iconEntry.Sensitive)
            {
                projectParameters.Win32Icon = iconEntry.Path;
            }

            if (mainClassEntry.Sensitive)
            {
                projectParameters.MainClass = mainClassEntry.Entry.Text;
            }

            foreach (DotNetProjectConfiguration configuration in configs)
            {
                CSharpCompilerParameters compilerParameters = (CSharpCompilerParameters)configuration.CompilationParameters;
                compilerParameters.UnsafeCode  = allowUnsafeCodeCheckButton.Active;
                compilerParameters.LangVersion = langVersion;
            }
        }
        public static BuildResult Compile(ProjectItemCollection projectItems, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, IProgressMonitor monitor)
        {
            CSharpCompilerParameters compilerParameters = (CSharpCompilerParameters)configuration.CompilationParameters ?? new CSharpCompilerParameters();
            CSharpProjectParameters  projectParameters  = (CSharpProjectParameters)configuration.ProjectParameters ?? new CSharpProjectParameters();

            string outputName       = configuration.CompiledOutputName;
            string responseFileName = Path.GetTempFileName();

            TargetRuntime runtime = MonoDevelop.Core.Runtime.SystemAssemblyService.DefaultRuntime;
            DotNetProject project = configuration.ParentItem as DotNetProject;

            if (project != null)
            {
                runtime = project.TargetRuntime;
            }

            StringBuilder sb       = new StringBuilder();
            List <string> gacRoots = new List <string> ();

            sb.AppendFormat("\"/out:{0}\"", outputName);
            sb.AppendLine();

            HashSet <string> alreadyAddedReference = new HashSet <string> ();

            foreach (ProjectReference lib in projectItems.GetAll <ProjectReference> ())
            {
                if (lib.ReferenceType == ReferenceType.Project && !(lib.OwnerProject.ParentSolution.FindProjectByName(lib.Reference) is DotNetProject))
                {
                    continue;
                }
                foreach (string fileName in lib.GetReferencedFileNames(configSelector))
                {
                    switch (lib.ReferenceType)
                    {
                    case ReferenceType.Gac:
                        SystemPackage pkg = lib.Package;
                        if (pkg == null)
                        {
                            string msg = string.Format(GettextCatalog.GetString("{0} could not be found or is invalid."), lib.Reference);
                            monitor.ReportWarning(msg);
                            continue;
                        }

                        if (alreadyAddedReference.Add(fileName))
                        {
                            AppendQuoted(sb, "/r:", fileName);
                        }

                        if (pkg.GacRoot != null && !gacRoots.Contains(pkg.GacRoot))
                        {
                            gacRoots.Add(pkg.GacRoot);
                        }
                        if (!string.IsNullOrEmpty(pkg.Requires))
                        {
                            foreach (string requiredPackage in pkg.Requires.Split(' '))
                            {
                                SystemPackage rpkg = runtime.AssemblyContext.GetPackage(requiredPackage);
                                if (rpkg == null)
                                {
                                    continue;
                                }
                                foreach (SystemAssembly assembly in rpkg.Assemblies)
                                {
                                    if (alreadyAddedReference.Add(assembly.Location))
                                    {
                                        AppendQuoted(sb, "/r:", assembly.Location);
                                    }
                                }
                            }
                        }
                        break;

                    default:
                        if (alreadyAddedReference.Add(fileName))
                        {
                            AppendQuoted(sb, "/r:", fileName);
                        }
                        break;
                    }
                }
            }

            sb.AppendLine("/nologo");
            sb.Append("/warn:"); sb.Append(compilerParameters.WarningLevel.ToString());
            sb.AppendLine();

            if (configuration.SignAssembly)
            {
                if (File.Exists(configuration.AssemblyKeyFile))
                {
                    AppendQuoted(sb, "/keyfile:", configuration.AssemblyKeyFile);
                }
            }

            if (configuration.DebugMode)
            {
                sb.AppendLine("/debug:+");
                sb.AppendLine("/debug:full");
            }

            switch (compilerParameters.LangVersion)
            {
            case LangVersion.Default:
                break;

            case LangVersion.ISO_1:
                sb.AppendLine("/langversion:ISO-1");
                break;

            case LangVersion.ISO_2:
                sb.AppendLine("/langversion:ISO-2");
                break;

            default:
                string message = "Invalid LangVersion enum value '" + compilerParameters.LangVersion.ToString() + "'";
                monitor.ReportError(message, null);
                LoggingService.LogError(message);
                return(null);
            }

            // mcs default is + but others might not be
            if (compilerParameters.Optimize)
            {
                sb.AppendLine("/optimize+");
            }
            else
            {
                sb.AppendLine("/optimize-");
            }

            bool hasWin32Res = !string.IsNullOrEmpty(projectParameters.Win32Resource) && File.Exists(projectParameters.Win32Resource);

            if (hasWin32Res)
            {
                AppendQuoted(sb, "/win32res:", projectParameters.Win32Resource);
            }

            if (!string.IsNullOrEmpty(projectParameters.Win32Icon) && File.Exists(projectParameters.Win32Icon))
            {
                if (hasWin32Res)
                {
                    monitor.ReportWarning("Both Win32 icon and Win32 resource cannot be specified. Ignoring the icon.");
                }
                else
                {
                    AppendQuoted(sb, "/win32icon:", projectParameters.Win32Icon);
                }
            }

            if (projectParameters.CodePage != 0)
            {
                sb.AppendLine("/codepage:" + projectParameters.CodePage);
            }
            else if (runtime is MonoTargetRuntime)
            {
                sb.AppendLine("/codepage:utf8");
            }

            if (compilerParameters.UnsafeCode)
            {
                sb.AppendLine("-unsafe");
            }
            if (compilerParameters.NoStdLib)
            {
                sb.AppendLine("-nostdlib");
            }

            if (!string.IsNullOrEmpty(compilerParameters.PlatformTarget) && compilerParameters.PlatformTarget.ToLower() != "anycpu")
            {
                //HACK: to ignore the platform flag for Mono <= 2.4, because gmcs didn't support it
                if (runtime.RuntimeId == "Mono" && runtime.AssemblyContext.GetAssemblyLocation("Mono.Debugger.Soft", null) == null)
                {
                    LoggingService.LogWarning("Mono runtime '" + runtime.DisplayName +
                                              "' appears to be too old to support the 'platform' C# compiler flag.");
                }
                else
                {
                    sb.AppendLine("/platform:" + compilerParameters.PlatformTarget);
                }
            }

            if (compilerParameters.TreatWarningsAsErrors)
            {
                sb.AppendLine("-warnaserror");
                if (!string.IsNullOrEmpty(compilerParameters.WarningsNotAsErrors))
                {
                    sb.AppendLine("-warnaserror-:" + compilerParameters.WarningsNotAsErrors);
                }
            }

            if (compilerParameters.DefineSymbols.Length > 0)
            {
                string define_str = string.Join(";", compilerParameters.DefineSymbols.Split(new char [] { ',', ' ', ';' }, StringSplitOptions.RemoveEmptyEntries));
                if (define_str.Length > 0)
                {
                    AppendQuoted(sb, "/define:", define_str);
                    sb.AppendLine();
                }
            }

            CompileTarget ctarget = configuration.CompileTarget;

            if (!string.IsNullOrEmpty(projectParameters.MainClass))
            {
                sb.AppendLine("/main:" + projectParameters.MainClass);
                // mcs does not allow providing a Main class when compiling a dll
                // As a workaround, we compile as WinExe (although the output will still
                // have a .dll extension).
                if (ctarget == CompileTarget.Library)
                {
                    ctarget = CompileTarget.WinExe;
                }
            }

            switch (ctarget)
            {
            case CompileTarget.Exe:
                sb.AppendLine("/t:exe");
                break;

            case CompileTarget.WinExe:
                sb.AppendLine("/t:winexe");
                break;

            case CompileTarget.Library:
                sb.AppendLine("/t:library");
                break;
            }

            foreach (ProjectFile finfo in projectItems.GetAll <ProjectFile> ())
            {
                if (finfo.Subtype == Subtype.Directory)
                {
                    continue;
                }

                switch (finfo.BuildAction)
                {
                case "Compile":
                    AppendQuoted(sb, "", finfo.Name);
                    break;

                case "EmbeddedResource":
                    string fname = finfo.Name;
                    if (string.Compare(Path.GetExtension(fname), ".resx", true) == 0)
                    {
                        fname = Path.ChangeExtension(fname, ".resources");
                    }
                    sb.Append('"'); sb.Append("/res:");
                    sb.Append(fname); sb.Append(','); sb.Append(finfo.ResourceId);
                    sb.Append('"'); sb.AppendLine();
                    break;

                default:
                    continue;
                }
            }
            if (compilerParameters.GenerateXmlDocumentation)
            {
                AppendQuoted(sb, "/doc:", Path.ChangeExtension(outputName, ".xml"));
            }

            if (!string.IsNullOrEmpty(compilerParameters.AdditionalArguments))
            {
                sb.AppendLine(compilerParameters.AdditionalArguments);
            }

            if (!string.IsNullOrEmpty(compilerParameters.NoWarnings))
            {
                AppendQuoted(sb, "/nowarn:", compilerParameters.NoWarnings);
            }

            if (runtime.RuntimeId == "MS.NET")
            {
                sb.AppendLine("/fullpaths");
                sb.AppendLine("/utf8output");
            }

            string output = "";
            string error  = "";

            File.WriteAllText(responseFileName, sb.ToString());

            string compilerName;

            try {
                compilerName = GetCompilerName(runtime, configuration.TargetFramework);
            } catch (Exception e) {
                string message = "Could not obtain a C# compiler";
                monitor.ReportError(message, e);
                return(null);
            }

            monitor.Log.WriteLine(compilerName + " /noconfig " + sb.ToString().Replace('\n', ' '));

            string workingDir = ".";

            if (configuration.ParentItem != null)
            {
                workingDir = configuration.ParentItem.BaseDirectory;
                if (workingDir == null)
                {
                    // Dummy projects created for single files have no filename
                    // and so no BaseDirectory.
                    // This is a workaround for a bug in
                    // ProcessStartInfo.WorkingDirectory - not able to handle null
                    workingDir = ".";
                }
            }

            LoggingService.LogInfo(compilerName + " " + sb.ToString());

            ExecutionEnvironment envVars = runtime.GetToolsExecutionEnvironment(project.TargetFramework);
            string cargs = "/noconfig @\"" + responseFileName + "\"";

            int exitCode = DoCompilation(compilerName, cargs, workingDir, envVars, gacRoots, ref output, ref error);

            BuildResult result = ParseOutput(output, error);

            if (result.CompilerOutput.Trim().Length != 0)
            {
                monitor.Log.WriteLine(result.CompilerOutput);
            }

            //if compiler crashes, output entire error string
            if (result.ErrorCount == 0 && exitCode != 0)
            {
                try {
                    monitor.Log.Write(File.ReadAllText(error));
                } catch (IOException) {
                }
                result.AddError("The compiler appears to have crashed. Check the build output pad for details.");
                LoggingService.LogError("C# compiler crashed. Response file '{0}', stdout file '{1}', stderr file '{2}'",
                                        responseFileName, output, error);
            }
            else
            {
                FileService.DeleteFile(responseFileName);
                FileService.DeleteFile(output);
                FileService.DeleteFile(error);
            }
            return(result);
        }
		protected override void OnReadProjectHeader (ProgressMonitor monitor, MSBuildProject msproject)
		{
			base.OnReadProjectHeader (monitor, msproject);

			compileTarget = msproject.EvaluatedProperties.GetValue<CompileTarget> ("OutputType");
			defaultNamespace = msproject.EvaluatedProperties.GetValue ("RootNamespace", string.Empty);
			usePartialTypes = msproject.EvaluatedProperties.GetValue ("UsePartialTypes", true);

			string frameworkIdentifier = msproject.EvaluatedProperties.GetValue ("TargetFrameworkIdentifier");
			string frameworkVersion = msproject.EvaluatedProperties.GetValue ("TargetFrameworkVersion");
			string frameworkProfile = msproject.EvaluatedProperties.GetValue ("TargetFrameworkProfile");

			//determine the default target framework from the project type's default
			//overridden by the components in the project
			var def = GetDefaultTargetFrameworkForFormat (ToolsVersion);
			var targetFx = new TargetFrameworkMoniker (
				string.IsNullOrEmpty (frameworkIdentifier)? def.Identifier : frameworkIdentifier,
				string.IsNullOrEmpty (frameworkVersion)? def.Version : frameworkVersion,
				string.IsNullOrEmpty (frameworkProfile)? def.Profile : frameworkProfile);


			string fx = ExtendedProperties ["InternalTargetFrameworkVersion"] as string;
			if (!string.IsNullOrEmpty (fx)) {
				targetFx = TargetFrameworkMoniker.Parse (fx);
				ExtendedProperties.Remove ("InternalTargetFrameworkVersion");
			}

			TargetFramework = Runtime.SystemAssemblyService.GetTargetFramework (targetFx);
		}
Example #8
0
        public static BuildResult Compile(ProjectItemCollection projectItems, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, ProgressMonitor monitor)
        {
            var compilerParameters = (CSharpCompilerParameters)configuration.CompilationParameters ?? new CSharpCompilerParameters();
            var projectParameters  = (CSharpProject)configuration.ParentItem;

            FilePath outputName       = configuration.CompiledOutputName;
            string   responseFileName = Path.GetTempFileName();

            //make sure that the output file is writable
            if (File.Exists(outputName))
            {
                bool isWriteable = false;
                int  count       = 0;
                do
                {
                    try {
                        outputName.MakeWritable();
                        using (var stream = File.OpenWrite(outputName)) {
                            isWriteable = true;
                        }
                    } catch (Exception) {
                        Thread.Sleep(20);
                    }
                } while (count++ < 5 && !isWriteable);
                if (!isWriteable)
                {
                    MessageService.ShowError(string.Format(GettextCatalog.GetString("Can't lock file: {0}."), outputName));
                    return(null);
                }
            }

            //get the runtime
            TargetRuntime runtime = MonoDevelop.Core.Runtime.SystemAssemblyService.DefaultRuntime;
            DotNetProject project = configuration.ParentItem as DotNetProject;

            if (project != null)
            {
                runtime = project.TargetRuntime;
            }

            //get the compiler name
            string compilerName;

            try {
                compilerName = GetCompilerName(runtime, configuration.TargetFramework);
            } catch (Exception e) {
                string message = "Could not obtain a C# compiler";
                monitor.ReportError(message, e);
                return(null);
            }

            var sb = new StringBuilder();

            HashSet <string> alreadyAddedReference = new HashSet <string> ();

            var monoRuntime = runtime as MonoTargetRuntime;

            if (!compilerParameters.NoStdLib && (monoRuntime == null || monoRuntime.HasMultitargetingMcs))
            {
                string corlib = project.AssemblyContext.GetAssemblyFullName("mscorlib", project.TargetFramework);
                if (corlib != null)
                {
                    corlib = project.AssemblyContext.GetAssemblyLocation(corlib, project.TargetFramework);
                }
                if (corlib == null)
                {
                    var br = new BuildResult();
                    br.AddError(string.Format("Could not find mscorlib for framework {0}", project.TargetFramework.Id));
                    return(br);
                }
                AppendQuoted(sb, "/r:", corlib);
                sb.AppendLine("-nostdlib");
            }

            List <string> gacRoots = new List <string> ();

            sb.AppendFormat("\"/out:{0}\"", outputName);
            sb.AppendLine();

            foreach (ProjectReference lib in projectItems.GetAll <ProjectReference> ())
            {
                if (lib.ReferenceType == ReferenceType.Project)
                {
                    var ownerProject = lib.OwnerProject;
                    if (ownerProject != null)
                    {
                        var parentSolution = ownerProject.ParentSolution;
                        if (parentSolution != null && !(lib.ResolveProject(parentSolution) is DotNetProject))
                        {
                            continue;
                        }
                    }
                }
                string refPrefix = string.IsNullOrEmpty(lib.Aliases) ? "" : lib.Aliases + "=";
                foreach (string fileName in lib.GetReferencedFileNames(configSelector))
                {
                    switch (lib.ReferenceType)
                    {
                    case ReferenceType.Package:
                        SystemPackage pkg = lib.Package;
                        if (pkg == null)
                        {
                            string msg = string.Format(GettextCatalog.GetString("{0} could not be found or is invalid."), lib.Reference);
                            monitor.ReportWarning(msg);
                            continue;
                        }

                        if (alreadyAddedReference.Add(fileName))
                        {
                            AppendQuoted(sb, "/r:", refPrefix + fileName);
                        }

                        if (pkg.GacRoot != null && !gacRoots.Contains(pkg.GacRoot))
                        {
                            gacRoots.Add(pkg.GacRoot);
                        }
                        if (!string.IsNullOrEmpty(pkg.Requires))
                        {
                            foreach (string requiredPackage in pkg.Requires.Split(' '))
                            {
                                SystemPackage rpkg = runtime.AssemblyContext.GetPackage(requiredPackage);
                                if (rpkg == null)
                                {
                                    continue;
                                }
                                foreach (SystemAssembly assembly in rpkg.Assemblies)
                                {
                                    if (alreadyAddedReference.Add(assembly.Location))
                                    {
                                        AppendQuoted(sb, "/r:", assembly.Location);
                                    }
                                }
                            }
                        }
                        break;

                    default:
                        if (alreadyAddedReference.Add(fileName))
                        {
                            AppendQuoted(sb, "/r:", refPrefix + fileName);
                        }
                        break;
                    }
                }
            }

            if (alreadyAddedReference.Any(reference => SystemAssemblyService.ContainsReferenceToSystemRuntime(reference)))
            {
                LoggingService.LogInfo("Found PCLv2 assembly.");
                var facades = runtime.FindFacadeAssembliesForPCL(project.TargetFramework);
                foreach (var facade in facades)
                {
                    AppendQuoted(sb, "/r:", facade);
                }
            }

            string sysCore = project.AssemblyContext.GetAssemblyFullName("System.Core", project.TargetFramework);

            if (sysCore != null && !alreadyAddedReference.Contains(sysCore))
            {
                var asm = project.AssemblyContext.GetAssemblyFromFullName(sysCore, null, project.TargetFramework);
                if (asm != null)
                {
                    AppendQuoted(sb, "/r:", asm.Location);
                }
            }

            sb.AppendLine("/nologo");
            sb.Append("/warn:"); sb.Append(compilerParameters.WarningLevel.ToString());
            sb.AppendLine();

            if (configuration.SignAssembly)
            {
                if (File.Exists(configuration.AssemblyKeyFile))
                {
                    AppendQuoted(sb, "/keyfile:", configuration.AssemblyKeyFile);
                }
                if (configuration.DelaySign)
                {
                    sb.AppendLine("/delaySign");
                }
            }

            var debugType = configuration.DebugType;

            if (string.IsNullOrEmpty(debugType))
            {
                debugType = configuration.DebugSymbols ? "full" : "none";
            }
            else if (string.Equals(debugType, "pdbonly", StringComparison.OrdinalIgnoreCase))
            {
                //old Mono compilers don't support pdbonly
                if (monoRuntime != null && !monoRuntime.HasMultitargetingMcs)
                {
                    debugType = "full";
                }
            }
            if (!string.Equals(debugType, "none", StringComparison.OrdinalIgnoreCase))
            {
                sb.AppendLine("/debug:" + debugType);
            }

            if (compilerParameters.LangVersion != LangVersion.Default)
            {
                var langVersionString = CSharpCompilerParameters.TryLangVersionToString(compilerParameters.LangVersion);
                if (langVersionString == null)
                {
                    string message = "Invalid LangVersion enum value '" + compilerParameters.LangVersion.ToString() + "'";
                    monitor.ReportError(message, null);
                    LoggingService.LogError(message);
                    return(null);
                }
                sb.AppendLine("/langversion:" + langVersionString);
            }

            // mcs default is + but others might not be
            if (compilerParameters.Optimize)
            {
                sb.AppendLine("/optimize+");
            }
            else
            {
                sb.AppendLine("/optimize-");
            }

            bool hasWin32Res = !string.IsNullOrEmpty(projectParameters.Win32Resource) && File.Exists(projectParameters.Win32Resource);

            if (hasWin32Res)
            {
                AppendQuoted(sb, "/win32res:", projectParameters.Win32Resource);
            }

            if (!string.IsNullOrEmpty(projectParameters.Win32Icon) && File.Exists(projectParameters.Win32Icon))
            {
                if (hasWin32Res)
                {
                    monitor.ReportWarning("Both Win32 icon and Win32 resource cannot be specified. Ignoring the icon.");
                }
                else
                {
                    AppendQuoted(sb, "/win32icon:", projectParameters.Win32Icon);
                }
            }

            if (projectParameters.CodePage != 0)
            {
                sb.AppendLine("/codepage:" + projectParameters.CodePage);
            }
            else if (runtime is MonoTargetRuntime)
            {
                sb.AppendLine("/codepage:utf8");
            }

            if (compilerParameters.UnsafeCode)
            {
                sb.AppendLine("-unsafe");
            }
            if (compilerParameters.NoStdLib)
            {
                sb.AppendLine("-nostdlib");
            }

            if (!string.IsNullOrEmpty(compilerParameters.PlatformTarget) && compilerParameters.PlatformTarget.ToLower() != "anycpu")
            {
                //HACK: to ignore the platform flag for Mono <= 2.4, because gmcs didn't support it
                if (runtime.RuntimeId == "Mono" && runtime.AssemblyContext.GetAssemblyLocation("Mono.Debugger.Soft", null) == null)
                {
                    LoggingService.LogWarning("Mono runtime '" + runtime.DisplayName +
                                              "' appears to be too old to support the 'platform' C# compiler flag.");
                }
                else
                {
                    sb.AppendLine("/platform:" + compilerParameters.PlatformTarget);
                }
            }

            if (compilerParameters.TreatWarningsAsErrors)
            {
                sb.AppendLine("-warnaserror");
                if (!string.IsNullOrEmpty(compilerParameters.WarningsNotAsErrors))
                {
                    sb.AppendLine("-warnaserror-:" + compilerParameters.WarningsNotAsErrors);
                }
            }

            foreach (var define in configuration.GetDefineSymbols())
            {
                AppendQuoted(sb, "/define:", define);
                sb.AppendLine();
            }

            CompileTarget ctarget = configuration.CompileTarget;

            if (!string.IsNullOrEmpty(projectParameters.MainClass))
            {
                sb.AppendLine("/main:" + projectParameters.MainClass);
                // mcs does not allow providing a Main class when compiling a dll
                // As a workaround, we compile as WinExe (although the output will still
                // have a .dll extension).
                if (ctarget == CompileTarget.Library)
                {
                    ctarget = CompileTarget.WinExe;
                }
            }

            switch (ctarget)
            {
            case CompileTarget.Exe:
                sb.AppendLine("/t:exe");
                break;

            case CompileTarget.WinExe:
                sb.AppendLine("/t:winexe");
                break;

            case CompileTarget.Library:
                sb.AppendLine("/t:library");
                break;
            }

            foreach (ProjectFile finfo in projectItems.GetAll <ProjectFile> ())
            {
                if (finfo.Subtype == Subtype.Directory)
                {
                    continue;
                }

                switch (finfo.BuildAction)
                {
                case "Compile":
                    AppendQuoted(sb, "", finfo.Name);
                    break;

                case "EmbeddedResource":
                    string fname = finfo.Name;
                    if (string.Compare(Path.GetExtension(fname), ".resx", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        fname = Path.ChangeExtension(fname, ".resources");
                    }
                    sb.Append('"'); sb.Append("/res:");
                    sb.Append(fname); sb.Append(','); sb.Append(finfo.ResourceId);
                    sb.Append('"'); sb.AppendLine();
                    break;

                default:
                    continue;
                }
            }
            if (!compilerParameters.DocumentationFile.IsNullOrEmpty)
            {
                AppendQuoted(sb, "/doc:", compilerParameters.DocumentationFile);
            }

            if (!string.IsNullOrEmpty(compilerParameters.NoWarnings))
            {
                AppendQuoted(sb, "/nowarn:", compilerParameters.NoWarnings);
            }

            if (runtime.RuntimeId == "MS.NET")
            {
                sb.AppendLine("/fullpaths");
                sb.AppendLine("/utf8output");
            }

            string output = "";
            string error  = "";

            File.WriteAllText(responseFileName, sb.ToString());

            monitor.Log.WriteLine(compilerName + " /noconfig " + sb.ToString().Replace('\n', ' '));

            // Dummy projects created for single files have no filename
            // and so no BaseDirectory.
            string workingDir = null;

            if (configuration.ParentItem != null)
            {
                workingDir = configuration.ParentItem.BaseDirectory;
            }

            LoggingService.LogInfo(compilerName + " " + sb);

            ExecutionEnvironment envVars = runtime.GetToolsExecutionEnvironment(project.TargetFramework);
            string cargs = "/noconfig @\"" + responseFileName + "\"";

            int exitCode = DoCompilation(monitor, compilerName, cargs, workingDir, envVars, gacRoots, ref output, ref error);

            BuildResult result = ParseOutput(workingDir, output, error);

            if (result.CompilerOutput.Trim().Length != 0)
            {
                monitor.Log.WriteLine(result.CompilerOutput);
            }

            //if compiler crashes, output entire error string
            if (result.ErrorCount == 0 && exitCode != 0)
            {
                try {
                    monitor.Log.Write(File.ReadAllText(error));
                } catch (IOException) {
                }
                result.AddError("The compiler appears to have crashed. Check the build output pad for details.");
                LoggingService.LogError("C# compiler crashed. Response file '{0}', stdout file '{1}', stderr file '{2}'",
                                        responseFileName, output, error);
            }
            else
            {
                FileService.DeleteFile(responseFileName);
                FileService.DeleteFile(output);
                FileService.DeleteFile(error);
            }
            return(result);
        }
		static string TargetToString (CompileTarget target)
		{
			switch (target) {
				case CompileTarget.WinExe:
					return "winexe";
				case CompileTarget.Library:
					return "library";
			}
			return "exe";
		}
Example #10
0
        private async void FrmDatabase_Compile(DatabaseInfo database, List <Schemas.TableInfo> selectedTables, List <string> selectedTemplates, CompileTarget target, string outputFolder)
        {
            try
            {
                frmOutput.Clear();
                frmOutput.DockState = WeifenLuo.WinFormsUI.Docking.DockState.DockBottom;

                Stopwatch sw = new Stopwatch();
                sw.Start();
                frmOutput.WriteLine("-----已启动生成-----");
                frmOutput.WriteLine("正在读取数据库结构...");
                var tableSchema = await database.ReLoadDatabaseSchema();

                frmOutput.WriteLine("正在准备数据...");
                var _selectTableNames = selectedTables.Select(t => t.ToString()).ToList();
                var tables            = tableSchema.Where(t => _selectTableNames.Contains(t.ToString())).ToList();
                frmOutput.WriteLine("正在加载模板...");

                var templates = new List <TemplateInfo>();
                foreach (string tmpFile in selectedTemplates)
                {
                    templates.Add(TemplateInfo.Get(tmpFile));
                }

                frmOutput.WriteLine("正在生成...");

                var singleTemplates = templates.Where(t => t.Config.isSingle);
                var entityTemplates = templates.Where(t => !t.Config.isSingle);

                if (singleTemplates.Any())
                {
                    var model = new DatabaseModel
                    {
                        DatabaseName = database.DatabaseName,
                        Tables       = tables
                    };
                    foreach (var template in singleTemplates)
                    {
                        model.TemplateFile = template.Name;
                        string fileName = "";
                        string content  = Razor.Parse(template.Content, model);
                        if (target == CompileTarget.File)
                        {
                            fileName = Path.Combine(outputFolder, template.Config.folder);
                            fileName = Path.Combine(fileName, string.Format(template.Config.fileName, model.DatabaseName));// string.Format("{0}{1}", Path.GetFileNameWithoutExtension(template.Name), template.Config.fileName));
                            FileStream fs    = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Write);
                            byte[]     bytes = System.Text.Encoding.UTF8.GetBytes(content);
                            fs.Write(bytes, 0, bytes.Length);
                            fs.Close();
                        }
                        else
                        {
                            fileName = string.Format("{0}{1}", Path.GetFileNameWithoutExtension(template.Name), template.Config.fileName);
                            CodeForm frmCode = new CodeForm(content);
                            frmCode.Text = fileName;
                            frmCode.Show(dockPanel);
                        }
                        frmOutput.WriteLine(string.Format(">{0}", fileName));
                    }
                }

                for (int i = 0; i < tables.Count; i++)
                {
                    var table = tables[i];
                    var model = new TableModel
                    {
                        DatabaseName = database.DatabaseName,
                        Table        = table
                    };
                    frmOutput.WriteLine(string.Format("{0}>{1}", i + 1, table.TableName));
                    foreach (var template in templates.Where(t => !t.Config.isSingle))
                    {
                        model.TemplateFile = template.Name;
                        string fileName = "";
                        string content  = Razor.Parse(template.Content, model);
                        if (target == CompileTarget.File)
                        {
                            fileName = Path.Combine(outputFolder, template.Config.folder);
                            if (!Directory.Exists(fileName))
                            {
                                Directory.CreateDirectory(fileName);
                            }
                            fileName = Path.Combine(fileName, string.Format(template.Config.fileName, table.TableName));// string.Format("{0}{1}", table.TableName, template.Config.fileName));
                            FileStream fs    = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Write);
                            byte[]     bytes = System.Text.Encoding.UTF8.GetBytes(content);
                            fs.Write(bytes, 0, bytes.Length);
                            fs.Close();
                        }
                        else
                        {
                            fileName = string.Format(template.Config.fileName, table.TableName);// string.Format("{0}{1}", table.TableName, template.Config.fileName);
                            CodeForm frmCode = new CodeForm(content);
                            frmCode.Text = fileName;
                            frmCode.Show(dockPanel);
                        }
                        frmOutput.WriteLine(string.Format(">{0}", fileName));
                    }
                }

                sw.Stop();
                frmOutput.WriteLine(string.Format("=====生成完成  总用时:{0} 毫秒=====", sw.ElapsedMilliseconds));
                frmOutput.DockState = WeifenLuo.WinFormsUI.Docking.DockState.DockBottomAutoHide;
            }
            catch (Exception ex)
            {
                frmOutput.WriteLine("生成错误:" + ex.Message);
            }
        }
        public override void CopyFrom(IConfiguration configuration)
        {
            base.CopyFrom (configuration);
            DotNetProjectConfiguration conf = (DotNetProjectConfiguration) configuration;

            assembly = conf.assembly;
            netRuntime = conf.netRuntime;
            compiletarget = conf.compiletarget;
            sourcePath = conf.sourcePath;
            compilationParameters = conf.compilationParameters != null ? (ICloneable)conf.compilationParameters.Clone () : null;
        }