Пример #1
0
        static EntryAssemblyInformation()
        {
            EntryAssembly = Assembly.GetEntryAssembly();

            foreach (object obj in EntryAssembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), true))
            {
                Title = (string)typeof(AssemblyTitleAttribute).GetProperty("Title").GetValue(obj, null);
            }

            foreach (object obj in EntryAssembly.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), true))
            {
                Description = ((AssemblyDescriptionAttribute)obj).Description;
            }

            foreach (object obj in EntryAssembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), true))
            {
                Company = ((AssemblyCompanyAttribute)obj).Company;
            }

            foreach (object obj in EntryAssembly.GetCustomAttributes(typeof(AssemblyProductAttribute), true))
            {
                Product = ((AssemblyProductAttribute)obj).Product;
            }

            foreach (object obj in EntryAssembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), true))
            {
                Copyright = ((AssemblyCopyrightAttribute)obj).Copyright;
            }

            Version = EntryAssembly.GetName().Version.ToString();

            StartupPath = System.Windows.Forms.Application.StartupPath;
        }
Пример #2
0
        private static void logStartupState(Configuration config)
        {
            // begin logging session with a form feed
            Log.Logger.Information("\r\n\f");
            Log.Logger.Information("Begin. {@DebugInfo}", new
            {
                AppName = EntryAssembly.GetName().Name,
                Version = BuildVersion.ToString(),
#if DEBUG
                Mode = "Debug",
#else
                Mode = "Release",
#endif

                LogLevel_Verbose_Enabled     = Log.Logger.IsVerboseEnabled(),
                LogLevel_Debug_Enabled       = Log.Logger.IsDebugEnabled(),
                LogLevel_Information_Enabled = Log.Logger.IsInformationEnabled(),
                LogLevel_Warning_Enabled     = Log.Logger.IsWarningEnabled(),
                LogLevel_Error_Enabled       = Log.Logger.IsErrorEnabled(),
                LogLevel_Fatal_Enabled       = Log.Logger.IsFatalEnabled(),

                config.LibationFiles,
                AudibleFileStorage.BooksDirectory,

                config.InProgress,

                AudibleFileStorage.DownloadsInProgressDirectory,
                DownloadsInProgressFiles = Directory.EnumerateFiles(AudibleFileStorage.DownloadsInProgressDirectory).Count(),

                AudibleFileStorage.DecryptInProgressDirectory,
                DecryptInProgressFiles = Directory.EnumerateFiles(AudibleFileStorage.DecryptInProgressDirectory).Count(),
            });
        }
Пример #3
0
        protected override string GetFileName()
        {
            var basepath     = Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%");
            var assemblyName = EntryAssembly.GetName().Name;
            var filepath     = Path.Combine(basepath, "settings", $"{assemblyName}.json");

            return(filepath);
        }
Пример #4
0
 private static T getAttribute <T> () where T : Attribute
 {
     object[] attributes = EntryAssembly.GetCustomAttributes(typeof(T), false);
     if (attributes.Length == 0)
     {
         return(null);
     }
     return(attributes[0] as T);
 }
        /// <summary>
        /// Initializes static members of the <see cref="EmbeddedResources"/> class.
        /// </summary>
        static EmbeddedResources()
        {
            EntryAssembly = typeof(EmbeddedResources).GetTypeInfo().Assembly;
            ResourceNames = new ReadOnlyCollection <string>(EntryAssembly.GetManifestResourceNames());
            var uri  = new UriBuilder(EntryAssembly.CodeBase);
            var path = Uri.UnescapeDataString(uri.Path);

            EntryAssemblyDirectory = Path.GetDirectoryName(path);
        }
Пример #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="App"/> class.
        /// </summary>
        /// <param name="owner">The owner program.</param>
        /// <param name="plugin">The plugin.</param>
        /// <param name="assemblyName">The assembly containg the plugin code and resources.</param>
        public App(Application owner, IPluginClient plugin, string assemblyName)
        {
            Owner        = owner;
            Plugin       = plugin;
            AssemblyName = assemblyName;

            // Ensure only one instance is running at a time.
            Logger.Write(Category.Debug, "Checking uniqueness");

            try
            {
                AppGuid = Plugin.Guid;
                if (AppGuid == Guid.Empty)
                {
                    // In case the guid is provided by the project settings and not source code.
                    Contract.RequireNotNull(Assembly.GetEntryAssembly(), out Assembly EntryAssembly);
                    Contract.RequireNotNull(EntryAssembly.GetCustomAttribute <GuidAttribute>(), out GuidAttribute AppGuidAttribute);
                    AppGuid = Guid.Parse(AppGuidAttribute.Value);
                }

                string AppUniqueId = AppGuid.ToString("B").ToUpperInvariant();

                // Try to create a global named event with a unique name. If we can create it we are first, otherwise there is another instance.
                // In that case, we just abort.
                bool createdNew;
                InstanceEvent = new EventWaitHandle(false, EventResetMode.ManualReset, AppUniqueId, out createdNew);
                if (!createdNew)
                {
                    Logger.Write(Category.Warning, "Another instance is already running");
                    InstanceEvent.Close();
                    InstanceEvent = null;
                    Owner.Shutdown();
                    return;
                }
            }
            catch (Exception e)
            {
                Logger.Write(Category.Error, $"(from App) {e.Message}");

                Owner.Shutdown();
                return;
            }

            // This code is here mostly to make sure that the Taskbar static class is initialized ASAP.
            // The taskbar rectangle is never empty. And if it is, we have no purpose.
            if (TaskbarLocation.ScreenBounds.IsEmpty)
            {
                Owner.Shutdown();
            }
            else
            {
                Owner.Startup += OnStartup;

                // Make sure we stop only on a call to Shutdown. This is for plugins that have a main window, we don't want to exit when it's closed.
                Owner.ShutdownMode = ShutdownMode.OnExplicitShutdown;
            }
        }
Пример #7
0
        private static void GetAllAssemblies()
        {
            void addAssemblies()
            {
                for (int i = 0; i < AssembliesCore._referencedAssemblies.Length; i++)
                {
                    AddAssembly(AssembliesCore._referencedAssemblies[i], false);
                }
            }

            AddAssembly(EntryAssembly, false);

            if (AssembliesCore._referencedAssemblies == null)
            {
                var cauldronHelper = EntryAssembly.GetType("CauldronInterceptionHelper")?.GetMethod("GetReferencedAssemblies", BindingFlags.Public | BindingFlags.Static);

                if (cauldronHelper != null)
                {
                    if (cauldronHelper.Invoke(null, null) is Assembly[] refAssemblies && refAssemblies.Length > 0)
                    {
                        AssembliesCore._referencedAssemblies = refAssemblies;
                        addAssemblies();
                        return;
                    }
                }

                var assemblies    = new List <Assembly>();
                var allAssemblies = AppDomain.CurrentDomain.GetAssemblies();

                for (int i = 0; i < allAssemblies.Length; i++)
                {
                    var assembly = allAssemblies[i];
                    if (AddAssembly(assembly, false) != null)
                    {
                        var referencedAssemblies = assembly.GetReferencedAssemblies();
                        for (int c = 0; c < referencedAssemblies.Length; c++)
                        {
                            LoadAssembly(referencedAssemblies[c]);
                        }
                    }
                }
                ;

                return;
            }

            addAssemblies();
        }
Пример #8
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            //Class1 test = new Class1();

            Assembly EntryAssembly;

            EntryAssembly = System.Reflection.Assembly.GetExecutingAssembly();
            foreach (AssemblyName Name in EntryAssembly.GetReferencedAssemblies())
            {
                Console.WriteLine("Name: {0}", Name.ToString());
            }


            Startup startup = new Startup();

            startup.Start();
        }
Пример #9
0
        public void InitializeServices(AutofacServiceProvider rootServices)
        {
            TenantServices ??= new AutofacServiceProvider(rootServices.LifetimeScope.BeginLifetimeScope(builder =>
            {
                var services = new ServiceCollection();

                // HACK: IWebHostEnvironment is registered in the root container but we need to register a temporary instance for the time of tenant services configuration
                // because discovery of default application parts relies on IWebHostEnvironment.ApplicationName
                // https://github.com/dotnet/aspnetcore/blob/v3.1.6/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreServiceCollectionExtensions.cs#L81
                var dummyWebHostEnvironmentService = ServiceDescriptor.Singleton <IWebHostEnvironment>(new DummyWebHostEnvironment {
                    ApplicationName = EntryAssembly?.GetName().Name
                });

                services.Add(dummyWebHostEnvironmentService);

                ConfigureServices(services);

                services.RemoveAll((service, _) => service == dummyWebHostEnvironmentService || ShouldResolveFromRoot(service));

                builder.Populate(services);
            }));
        }
Пример #10
0
        public Application(string[] args)
        {
            CommandLineArgs.AddRange(args);

            var cmdParser = new CommandLineParser();

            EntryAssembly = Assembly.GetEntryAssembly();
            if (EntryAssembly == null)
            {
                #pragma warning disable CA1303 // Do not pass literals as localized parameters
                throw new Exception("Can't get entry assembly!");
                #pragma warning restore CA1303 // Do not pass literals as localized parameters
            }
            var entryAssemblyName = EntryAssembly.GetName()?.Name;
            if (entryAssemblyName == null)
            {
                #pragma warning disable CA1303 // Do not pass literals as localized parameters
                throw new Exception("Can't get entry assembly name!");
                #pragma warning restore CA1303 // Do not pass literals as localized parameters
            }


            if (!IsInteractiveMode)
            {
                Options     = cmdParser.Parse <ApplicationOptions>(CommandLineArgs.ToArray());
                ServiceName = (((ApplicationOptions)Options).ServiceNamePrefix == ApplicationOptions.NOPREFIX ? "" : ((ApplicationOptions)Options).ServiceNamePrefix)
                              + entryAssemblyName;
            }
            else
            {
                if (Manager != null)
                {
                    Options = cmdParser.Parse(CommandLineArgs.ToArray(), Manager.OptionsClass);
                }
                ServiceName = entryAssemblyName;
            }

            Manager = new T();
        }
Пример #11
0
        /// <summary>
        /// 取得类型
        /// </summary>
        /// <returns>类型</returns>
        private Type GetType(string typeName)
        {
            Type type = Type.GetType(typeName);

            if (type == null)
            {
                type = DefaultAssembly.GetType(typeName);
            }
            if (type == null)
            {
                type = CallingAssembly.GetType(typeName);
            }
            if (type == null)
            {
                type = ExecutingAssembly.GetType(typeName);
            }
            if (type == null)
            {
                type = EntryAssembly.GetType(typeName);
            }
            return(type);
        }
Пример #12
0
        public void CanResolveAllSystemEntryPoints()
        {
            IEnumerable <Type> EntryPoints = EntryAssembly.GetTypes()
                                             .Where(_ => typeof(TBase).IsAssignableFrom(_) &&
                                                    !_.IsAbstract)
                                             .ToArray();

            RegisterEntryPoints(EntryPoints);
            RegisterDependencies();
            AddExtraRegistrations();

            using IServiceScope scope = CreateServiceScope();

            IServiceProvider serviceProvider = scope.ServiceProvider;

            foreach (Type entryPoint in EntryPoints)
            {
                serviceProvider
                .GetService(entryPoint)
                .Should()
                .NotBeNull(entryPoint.Name);
            }
        }
        internal bool CompileInternal(ProjectContext context, string config, string probingFolderPath)
        {
            // Check if ambient library
            if (AmbientLibraries.Contains(context.ProjectName()))
            {
                return(true);
            }

            bool compilationResult;

            // Check if already compiled
            if (_compiledLibraries.TryGetValue(context.ProjectName(), out compilationResult))
            {
                return(compilationResult);
            }

            // Get compilation options and source files
            var compilationOptions = context.ResolveCompilationOptions(config);
            var projectSourceFiles = CompilerUtility.GetCompilationSources(context, compilationOptions);

            // Check if precompiled
            if (!projectSourceFiles.Any())
            {
                return(_compiledLibraries[context.ProjectName()] = true);
            }

            // Set up Output Paths
            var outputPaths            = context.GetOutputPaths(config);
            var outputPath             = outputPaths.CompilationOutputPath;
            var intermediateOutputPath = outputPaths.IntermediateOutputDirectoryPath;

            Directory.CreateDirectory(outputPath);
            Directory.CreateDirectory(intermediateOutputPath);

            // Create the library exporter
            var exporter = context.CreateExporter(config);

            // Gather exports for the project
            var dependencies = exporter.GetDependencies().ToList();

            // Get compilation options
            var outputName = outputPaths.CompilationFiles.Assembly;

            // Set default platform if it isn't already set and we're on desktop
            if (compilationOptions.EmitEntryPoint == true && String.IsNullOrEmpty(compilationOptions.Platform) && context.TargetFramework.IsDesktop())
            {
                // See https://github.com/dotnet/cli/issues/2428 for more details.
                compilationOptions.Platform = RuntimeInformation.ProcessArchitecture == Architecture.X64 ?
                                              "x64" : "anycpu32bitpreferred";
            }

            var references  = new List <string>();
            var sourceFiles = new List <string>();
            var resources   = new List <string>();

            // Get the runtime directory
            var runtimeDirectory = Paths.GetParentFolderPath(EntryAssembly.Location);

            foreach (var dependency in dependencies)
            {
                sourceFiles.AddRange(dependency.SourceReferences.Select(s => s.GetTransformedFile(intermediateOutputPath)));

                foreach (var resourceFile in dependency.EmbeddedResources)
                {
                    var transformedResource = resourceFile.GetTransformedFile(intermediateOutputPath);
                    var resourceName        = ResourceManifestName.CreateManifestName(
                        Path.GetFileName(resourceFile.ResolvedPath), compilationOptions.OutputName);
                    resources.Add($"\"{transformedResource}\",{resourceName}");
                }

                var library = dependency.Library as ProjectDescription;
                var package = dependency.Library as PackageDescription;

                // Compile other referenced libraries
                if (library != null && !AmbientLibraries.Contains(library.Identity.Name) && dependency.CompilationAssemblies.Any())
                {
                    if (!_compiledLibraries.ContainsKey(library.Identity.Name))
                    {
                        var projectContext = GetProjectContextFromPath(library.Project.ProjectDirectory);

                        if (projectContext != null)
                        {
                            // Right now, if !success we try to use the last build
                            var success = Compile(projectContext, config, probingFolderPath);
                        }
                    }
                }

                // Check for an unresolved library
                if (library != null && !library.Resolved)
                {
                    var assetFileName = CompilerUtility.GetAssemblyFileName(library.Identity.Name);

                    // Search in the runtime directory
                    var assetResolvedPath = Path.Combine(runtimeDirectory, assetFileName);

                    if (!File.Exists(assetResolvedPath))
                    {
                        // Fallback to the project output path or probing folder
                        assetResolvedPath = ResolveAssetPath(outputPath, probingFolderPath, assetFileName);

                        if (String.IsNullOrEmpty(assetResolvedPath))
                        {
                            // Fallback to this (possible) precompiled module bin folder
                            var path = Path.Combine(Paths.GetParentFolderPath(library.Path), Constants.BinDirectoryName, assetFileName);
                            assetResolvedPath = File.Exists(path) ? path : null;
                        }
                    }

                    if (!String.IsNullOrEmpty(assetResolvedPath))
                    {
                        references.Add(assetResolvedPath);
                    }
                }
                // Check for an unresolved package
                else if (package != null && !package.Resolved)
                {
                    var    runtimeAssets   = new HashSet <string>(package.RuntimeAssemblies.Select(x => x.Path), StringComparer.OrdinalIgnoreCase);
                    string fallbackBinPath = null;

                    foreach (var asset in package.CompileTimeAssemblies)
                    {
                        var assetFileName  = Path.GetFileName(asset.Path);
                        var isRuntimeAsset = runtimeAssets.Contains(asset.Path);

                        // Search in the runtime directory
                        var relativeFolderPath = isRuntimeAsset ? String.Empty : CompilerUtility.RefsDirectoryName;
                        var assetResolvedPath  = Path.Combine(runtimeDirectory, relativeFolderPath, assetFileName);

                        if (!File.Exists(assetResolvedPath))
                        {
                            // Fallback to the project output path or probing folder
                            assetResolvedPath = ResolveAssetPath(outputPath, probingFolderPath, assetFileName, relativeFolderPath);
                        }

                        if (String.IsNullOrEmpty(assetResolvedPath))
                        {
                            if (fallbackBinPath == null)
                            {
                                fallbackBinPath = String.Empty;

                                // Fallback to a (possible) parent precompiled module bin folder
                                var parentBinPaths = CompilerUtility.GetOtherParentProjectsLocations(context, package)
                                                     .Select(x => Path.Combine(x, Constants.BinDirectoryName));

                                foreach (var binaryPath in parentBinPaths)
                                {
                                    var path = Path.Combine(binaryPath, relativeFolderPath, assetFileName);

                                    if (File.Exists(path))
                                    {
                                        assetResolvedPath = path;
                                        fallbackBinPath   = binaryPath;
                                        break;
                                    }
                                }
                            }
                            else if (!String.IsNullOrEmpty(fallbackBinPath))
                            {
                                var path = Path.Combine(fallbackBinPath, relativeFolderPath, assetFileName);
                                assetResolvedPath = File.Exists(path) ? path : null;
                            }
                        }

                        if (!String.IsNullOrEmpty(assetResolvedPath))
                        {
                            references.Add(assetResolvedPath);
                        }
                    }
                }
                // Check for a precompiled library
                else if (library != null && !dependency.CompilationAssemblies.Any())
                {
                    // Search in the project output path or probing folder
                    var assetFileName     = CompilerUtility.GetAssemblyFileName(library.Identity.Name);
                    var assetResolvedPath = ResolveAssetPath(outputPath, probingFolderPath, assetFileName);

                    if (String.IsNullOrEmpty(assetResolvedPath))
                    {
                        // Fallback to this precompiled project output path
                        var path = Path.Combine(CompilerUtility.GetAssemblyFolderPath(library.Project.ProjectDirectory,
                                                                                      config, context.TargetFramework.DotNetFrameworkName), assetFileName);
                        assetResolvedPath = File.Exists(path) ? path : null;
                    }

                    if (!String.IsNullOrEmpty(assetResolvedPath))
                    {
                        references.Add(assetResolvedPath);
                    }
                }
                // Check for a resolved but ambient library (compiled e.g by VS)
                else if (library != null && AmbientLibraries.Contains(library.Identity.Name))
                {
                    // Search in the regular project output path, fallback to the runtime directory
                    references.AddRange(dependency.CompilationAssemblies.Select(r => File.Exists(r.ResolvedPath)
                        ? r.ResolvedPath : Path.Combine(runtimeDirectory, r.FileName)));
                }
                else
                {
                    references.AddRange(dependency.CompilationAssemblies.Select(r => r.ResolvedPath));
                }
            }

            // Check again if already compiled, here through the dependency graph
            if (_compiledLibraries.TryGetValue(context.ProjectName(), out compilationResult))
            {
                return(compilationResult);
            }

            var sw = Stopwatch.StartNew();

            string            depsJsonFile      = null;
            DependencyContext dependencyContext = null;

            // Add dependency context as a resource
            if (compilationOptions.PreserveCompilationContext == true)
            {
                var allExports         = exporter.GetAllExports().ToList();
                var exportsLookup      = allExports.ToDictionary(e => e.Library.Identity.Name);
                var buildExclusionList = context.GetTypeBuildExclusionList(exportsLookup);
                var filteredExports    = allExports
                                         .Where(e => e.Library.Identity.Type.Equals(LibraryType.ReferenceAssembly) ||
                                                !buildExclusionList.Contains(e.Library.Identity.Name));

                dependencyContext = new DependencyContextBuilder().Build(compilationOptions,
                                                                         filteredExports,
                                                                         filteredExports,
                                                                         false, // For now, just assume non-portable mode in the legacy deps file (this is going away soon anyway)
                                                                         context.TargetFramework,
                                                                         context.RuntimeIdentifier ?? string.Empty);

                depsJsonFile = Path.Combine(intermediateOutputPath, compilationOptions.OutputName + "dotnet-compile.deps.json");
                resources.Add($"\"{depsJsonFile}\",{compilationOptions.OutputName}.deps.json");
            }

            // Add project source files
            sourceFiles.AddRange(projectSourceFiles);

            // Add non culture resources
            var resgenFiles = CompilerUtility.GetNonCultureResources(context.ProjectFile, intermediateOutputPath, compilationOptions);

            AddNonCultureResources(resources, resgenFiles);

            var translated = TranslateCommonOptions(compilationOptions, outputName);

            var allArgs = new List <string>(translated);

            allArgs.AddRange(GetDefaultOptions());

            // Add assembly info
            var assemblyInfo = Path.Combine(intermediateOutputPath, $"dotnet-compile.assemblyinfo.cs");

            allArgs.Add($"\"{assemblyInfo}\"");

            if (!String.IsNullOrEmpty(outputName))
            {
                allArgs.Add($"-out:\"{outputName}\"");
            }

            allArgs.AddRange(references.Select(r => $"-r:\"{r}\""));
            allArgs.AddRange(resources.Select(resource => $"-resource:{resource}"));
            allArgs.AddRange(sourceFiles.Select(s => $"\"{s}\""));

            // Gather all compile IO
            var inputs  = new List <string>();
            var outputs = new List <string>();

            inputs.Add(context.ProjectFile.ProjectFilePath);

            if (context.LockFile != null)
            {
                inputs.Add(context.LockFile.LockFilePath);
            }

            if (context.LockFile.ExportFile != null)
            {
                inputs.Add(context.LockFile.ExportFile.ExportFilePath);
            }

            inputs.AddRange(sourceFiles);
            inputs.AddRange(references);

            inputs.AddRange(resgenFiles.Select(x => x.InputFile));

            var cultureResgenFiles = CompilerUtility.GetCultureResources(context.ProjectFile, outputPath, compilationOptions);

            inputs.AddRange(cultureResgenFiles.SelectMany(x => x.InputFileToMetadata.Keys));

            outputs.AddRange(outputPaths.CompilationFiles.All());
            outputs.AddRange(resgenFiles.Where(x => x.OutputFile != null).Select(x => x.OutputFile));
            //outputs.AddRange(cultureResgenFiles.Where(x => x.OutputFile != null).Select(x => x.OutputFile));

            // Locate RSP file
            var rsp = Path.Combine(intermediateOutputPath, $"dotnet-compile-csc.rsp");

            // Check if there is no need to compile
            if (!CheckMissingIO(inputs, outputs) && !TimestampsChanged(inputs, outputs))
            {
                if (File.Exists(rsp))
                {
                    // Check if the compilation context has been changed
                    var prevInputs = new HashSet <string>(File.ReadAllLines(rsp));
                    var newInputs  = new HashSet <string>(allArgs);

                    if (!prevInputs.Except(newInputs).Any() && !newInputs.Except(prevInputs).Any())
                    {
                        PrintMessage($"{context.ProjectName()}: Previously compiled, skipping dynamic compilation.");
                        return(_compiledLibraries[context.ProjectName()] = true);
                    }
                }
                else
                {
                    // Write RSP file for the next time
                    File.WriteAllLines(rsp, allArgs);

                    PrintMessage($"{context.ProjectName()}:  Previously compiled, skipping dynamic compilation.");
                    return(_compiledLibraries[context.ProjectName()] = true);
                }
            }

            if (!CompilerUtility.GenerateNonCultureResources(context.ProjectFile, resgenFiles, Diagnostics))
            {
                return(_compiledLibraries[context.ProjectName()] = false);
            }

            PrintMessage(String.Format($"{context.ProjectName()}: Dynamic compiling for {context.TargetFramework.DotNetFrameworkName}"));

            // Write the dependencies file
            if (dependencyContext != null)
            {
                var writer = new DependencyContextWriter();
                using (var fileStream = File.Create(depsJsonFile))
                {
                    writer.Write(dependencyContext, fileStream);
                }
            }

            // Write assembly info and RSP files
            var assemblyInfoOptions = AssemblyInfoOptions.CreateForProject(context);

            File.WriteAllText(assemblyInfo, AssemblyInfoFileGenerator.GenerateCSharp(assemblyInfoOptions, sourceFiles));
            File.WriteAllLines(rsp, allArgs);

            // Locate runtime config files
            var runtimeConfigPath    = Path.Combine(runtimeDirectory, EntryAssembly.GetName().Name + FileNameSuffixes.RuntimeConfigJson);
            var cscRuntimeConfigPath = Path.Combine(runtimeDirectory, "csc" + FileNameSuffixes.RuntimeConfigJson);

            // Automatically create the csc runtime config file
            if (Files.IsNewer(runtimeConfigPath, cscRuntimeConfigPath))
            {
                lock (_syncLock)
                {
                    if (Files.IsNewer(runtimeConfigPath, cscRuntimeConfigPath))
                    {
                        File.Copy(runtimeConfigPath, cscRuntimeConfigPath, true);
                    }
                }
            }

            // Locate csc.dll and the csc.exe asset
            var cscDllPath = Path.Combine(runtimeDirectory, CompilerUtility.GetAssemblyFileName("csc"));

            // Search in the runtime directory
            var cscRelativePath = Path.Combine("runtimes", "any", "native", "csc.exe");
            var cscExePath      = Path.Combine(runtimeDirectory, cscRelativePath);

            // Fallback to the packages storage
            if (!File.Exists(cscExePath) && !String.IsNullOrEmpty(context.PackagesDirectory))
            {
                cscExePath = Path.Combine(context.PackagesDirectory, CscLibrary?.Name ?? String.Empty,
                                          CscLibrary?.Version ?? String.Empty, cscRelativePath);
            }

            // Automatically create csc.dll
            if (Files.IsNewer(cscExePath, cscDllPath))
            {
                lock (_syncLock)
                {
                    if (Files.IsNewer(cscExePath, cscDllPath))
                    {
                        File.Copy(cscExePath, cscDllPath, true);
                    }
                }
            }

            // Locate the csc dependencies file
            var cscDepsPath = Path.Combine(runtimeDirectory, "csc.deps.json");

            // Automatically create csc.deps.json
            if (NativePDBWriter != null && Files.IsNewer(cscDllPath, cscDepsPath))
            {
                lock (_syncLock)
                {
                    if (Files.IsNewer(cscDllPath, cscDepsPath))
                    {
                        // Only reference windows native pdb writers
                        var runtimeLibraries = new List <RuntimeLibrary>();
                        runtimeLibraries.Add(NativePDBWriter);

                        DependencyContext cscDependencyContext = new DependencyContext(
                            DependencyContext.Default.Target, CompilationOptions.Default,
                            new List <CompilationLibrary>(), runtimeLibraries,
                            new List <RuntimeFallbacks>());

                        // Write the csc.deps.json file
                        if (cscDependencyContext != null)
                        {
                            var writer = new DependencyContextWriter();
                            using (var fileStream = File.Create(cscDepsPath))
                            {
                                writer.Write(cscDependencyContext, fileStream);
                            }
                        }

                        // Windows native pdb writers are outputed on dotnet publish.
                        // But not on dotnet build during development, we do it here.

                        // Check if there is a packages storage
                        if (!String.IsNullOrEmpty(context.PackagesDirectory))
                        {
                            var assetPaths = NativePDBWriter.NativeLibraryGroups.SelectMany(l => l.AssetPaths);

                            foreach (var assetPath in assetPaths)
                            {
                                // Resolve the pdb writer from the packages storage
                                var pdbResolvedPath = Path.Combine(context.PackagesDirectory,
                                                                   NativePDBWriter.Name, NativePDBWriter.Version, assetPath);

                                var pdbOutputPath = Path.Combine(runtimeDirectory, assetPath);

                                // Store the pdb writer in the runtime directory
                                if (Files.IsNewer(pdbResolvedPath, pdbOutputPath))
                                {
                                    Directory.CreateDirectory(Paths.GetParentFolderPath(pdbOutputPath));
                                    File.Copy(pdbResolvedPath, pdbOutputPath, true);
                                }
                            }
                        }
                    }
                }
            }

            // Execute CSC!
            var result = Command.Create("csc.dll", new string[] { $"-noconfig", "@" + $"{rsp}" })
                         .WorkingDirectory(runtimeDirectory)
                         .OnErrorLine(line => Diagnostics.Add(line))
                         .OnOutputLine(line => Diagnostics.Add(line))
                         .Execute();

            compilationResult = result.ExitCode == 0;

            if (compilationResult)
            {
                compilationResult &= CompilerUtility.GenerateCultureResourceAssemblies(context.ProjectFile, cultureResgenFiles, references, Diagnostics);
            }

            PrintMessage(String.Empty);

            if (compilationResult && Diagnostics.Count == 0)
            {
                PrintMessage($"{context.ProjectName()}: Dynamic compilation succeeded.");
                PrintMessage($"0 Warning(s)");
                PrintMessage($"0 Error(s)");
            }
            else if (compilationResult && Diagnostics.Count > 0)
            {
                PrintMessage($"{context.ProjectName()}: Dynamic compilation succeeded but has warnings.");
                PrintMessage($"0 Error(s)");
            }
            else
            {
                PrintMessage($"{context.ProjectName()}: Dynamic compilation failed.");
            }

            foreach (var diagnostic in Diagnostics)
            {
                PrintMessage(diagnostic);
            }

            PrintMessage($"Time elapsed {sw.Elapsed}");
            PrintMessage(String.Empty);

            return(_compiledLibraries[context.ProjectName()] = compilationResult);
        }
Пример #14
0
        private XDocument Serialize()
        {
            XDocument xDoc = new XDocument();

            //apender
            var param = new XElement("param");

            param.SetAttributeValue("name", "ConversionPattern");
            param.SetAttributeValue("value", LogPattern);

            var layout = new XElement("layout", param);

            layout.SetAttributeValue("type", typeof(PatternLayout));

            var file = new XElement("file");

            file.SetAttributeValue("value", LogFilePath);

            var append = new XElement("appendToFile");

            append.SetAttributeValue("value", AppendToFile);

            var rollingstyle = new XElement("rollingStyle");

            rollingstyle.SetAttributeValue("value",
                                           Enum.GetName(typeof(RollingFileAppender.RollingMode)
                                                        , RollingFileAppender.RollingMode.Size));

            var maxFiles = new XElement("maxSizeRollBackups");

            maxFiles.SetAttributeValue("value", MaxLogFiles);

            var maxFileSize = new XElement("maximumFileSize");

            maxFileSize.SetAttributeValue("value", "{0}MB".FormatWith(MaxLogSizeInMB));

            var staticLogFile = new XElement("StaticLogFileName");

            staticLogFile.SetAttributeValue("value", true);

            var appender = new XElement("appender"
                                        , file
                                        , append
                                        , rollingstyle
                                        , maxFiles
                                        , maxFileSize
                                        , staticLogFile
                                        , layout);

            appender.SetAttributeValue("name", EntryAssembly.GetName().Name);
            appender.SetAttributeValue("type", typeof(RollingFileAppender));

            //Root
            var level = new XElement("level");

            level.SetAttributeValue("value", Level.Name);
            var appRef = new XElement("appender-ref");

            appRef.SetAttributeValue("ref", EntryAssembly.GetName().Name);

            var root = new XElement("root", level, appRef);

            //Config
            var section = new XElement("section");

            section.SetAttributeValue("name", "log4net");
            section.SetAttributeValue("type", "{0}, {1}".FormatWith(typeof(Log4NetConfigurationSectionHandler), "log4net"));

            var configSection = new XElement("configSections", section);

            var configuration = new XElement("configuration",
                                             configSection,
                                             new XElement("log4net",
                                                          appender, root));

            return(XDocument.Parse(configuration.ToString()));
        }
Пример #15
0
 public ViewLocator(Application application)
     : this(EntryAssembly != null && !EntryAssembly.IsInDesignMode() ? new[] { EntryAssembly } : new Assembly[0])
 {
 }
Пример #16
0
        // will be called when all assemblies are loaded (can be async for downloading)
        // which means we need to report errors to the plugin, since it won't get it from calling managed code
        internal bool CreateApplication()
        {
            SetCurrentApplication(null);

            if (EntryAssembly == null)
            {
                EmitError(2103, "Could not find the entry point assembly");
                return(false);
            }

            Type entry_type = EntryAssembly.GetType(EntryPointType);

            if (entry_type == null)
            {
                EmitError(2103, String.Format("Could not find the startup type {0} on the {1}",
                                              EntryPointType, EntryPointAssembly));
                return(false);
            }

            if (!entry_type.IsSubclassOf(typeof(Application)) && entry_type != typeof(Application))
            {
#if SANITY
                Type t       = entry_type;
                int  spacing = 0;
                Console.WriteLine("Application type: {0}", typeof(Application).AssemblyQualifiedName);
                while (t != null)
                {
                    if (spacing > 0)
                    {
                        for (int i = 0; i < spacing; i++)
                        {
                            Console.Write(" ");
                        }
                        Console.Write("+ ");
                    }
                    Console.WriteLine("{0} from {1}", t.AssemblyQualifiedName, t.Assembly.Location);
                    spacing += 2;
                    t        = t.BaseType;
                }
#endif

                EmitError(2103, "Startup type does not derive from System.Windows.Application");
                return(false);
            }

            foreach (Assembly a in Assemblies)
            {
                Application.LoadXmlnsDefinitionMappings(a);
            }

            Application instance = null;

            try {
                instance = (Application)Activator.CreateInstance(entry_type);
                // set HasElevatedPermissions based on IsRunningOutOfBrowser and ElevatedPermissions.Required
                if (IsElevatedPermissionsRequired)
                {
                    instance.HasElevatedPermissions = instance.IsRunningOutOfBrowser;
                }
            } catch {
                EmitError(2103, String.Format("Error while creating the instance of type {0}", entry_type));
                return(false);
            }

            if (instance.IsRunningOutOfBrowser)
            {
                IntPtr         window_handle = instance.MainWindow.native;
                WindowSettings ws            = OutOfBrowserSettings.WindowSettings;
                if (ws != null)
                {
                    Window w = instance.MainWindow;
                    w.Width  = ws.Width;
                    w.Height = ws.Height;

                    switch (ws.WindowStartupLocation)
                    {
                    case WindowStartupLocation.Manual:
                        w.Left = ws.Left;
                        w.Top  = ws.Top;
                        break;

                    case WindowStartupLocation.CenterScreen:
                        IntPtr windowing_system = NativeMethods.runtime_get_windowing_system();
                        IntPtr moon_window      = NativeMethods.window_get_moon_window(window_handle);
                        w.Left = ((NativeMethods.moon_windowing_system_get_screen_width(windowing_system, moon_window) - w.Width) / 2);
                        w.Top  = ((NativeMethods.moon_windowing_system_get_screen_height(windowing_system, moon_window) - w.Height) / 2);
                        break;

                    default:
                        // let the OS decide where to show the window
                        break;
                    }

                    Uri    source = UriHelper.FromNativeUri(NativeMethods.surface_get_source_location(Surface.Native));
                    string host   = source.Host;
                    if (String.IsNullOrEmpty(source.Host))
                    {
                        host = "localhost";
                    }
                    NativeMethods.window_set_title(window_handle, ws.Title + " - " + host);
                    NativeMethods.window_set_style(window_handle, ws.WindowStyle);
                }
                else
                {
                    NativeMethods.window_set_title(window_handle, OutOfBrowserSettings.ShortName);
                }
            }

            StartupEventArgs args = new StartupEventArgs();
            instance.OnStartup(args);

            return(true);
        }