コード例 #1
0
ファイル: DownloadFile.cs プロジェクト: zzekikaya/AspNetCore
        public static async Task DownloadAsync(
            string uri,
            string destinationPath,
            HttpClient httpClient,
            CancellationToken cancellationToken,
            TaskLoggingHelper log,
            int timeoutSeconds)
        {
            // Timeout if the response has not begun within 1 minute
            httpClient.Timeout = TimeSpan.FromMinutes(1);

            var destinationExists = File.Exists(destinationPath);
            var reachedCopy       = false;

            try
            {
                using (var response = await httpClient.GetAsync(uri, cancellationToken))
                {
                    response.EnsureSuccessStatusCode();
                    cancellationToken.ThrowIfCancellationRequested();

                    using (var responseStreamTask = response.Content.ReadAsStreamAsync())
                    {
                        var finished = await Task.WhenAny(
                            responseStreamTask,
                            Task.Delay(TimeSpan.FromSeconds(timeoutSeconds)));

                        if (!ReferenceEquals(responseStreamTask, finished))
                        {
                            throw new TimeoutException($"Download failed to complete in {timeoutSeconds} seconds.");
                        }

                        using (var responseStream = await responseStreamTask)
                        {
                            if (destinationExists)
                            {
                                // Check hashes before using the downloaded information.
                                var downloadHash = GetHash(responseStream);
                                responseStream.Position = 0L;

                                byte[] destinationHash;
                                using (var destinationStream = File.OpenRead(destinationPath))
                                {
                                    destinationHash = GetHash(destinationStream);
                                }

                                var sameHashes = downloadHash.Length == destinationHash.Length;
                                for (var i = 0; sameHashes && i < downloadHash.Length; i++)
                                {
                                    sameHashes = downloadHash[i] == destinationHash[i];
                                }

                                if (sameHashes)
                                {
                                    log.LogMessage($"Not overwriting existing and matching file '{destinationPath}'.");
                                    return;
                                }
                            }
                            else
                            {
                                // May need to create directory to hold the file.
                                var destinationDirectory = Path.GetDirectoryName(destinationPath);
                                if (!string.IsNullOrEmpty(destinationDirectory))
                                {
                                    Directory.CreateDirectory(destinationDirectory);
                                }
                            }

                            // Create or overwrite the destination file.
                            reachedCopy = true;
                            using (var outStream = File.Create(destinationPath))
                            {
                                await responseStream.CopyToAsync(outStream);

                                await outStream.FlushAsync();
                            }
                        }
                    }
                }
            }
            catch (HttpRequestException ex) when(destinationExists)
            {
                if (ex.InnerException is SocketException socketException)
                {
                    log.LogWarning($"Unable to download {uri}, socket error code '{socketException.SocketErrorCode}'.");
                }
                else
                {
                    log.LogWarning($"Unable to download {uri}: {ex.Message}");
                }
            }
            catch (Exception ex)
            {
                log.LogError($"Downloading '{uri}' failed.");
                log.LogErrorFromException(ex, showStackTrace: true);
                if (reachedCopy)
                {
                    File.Delete(destinationPath);
                }
            }
        }
コード例 #2
0
        public IReadOnlyList <SolutionInfo> Create(IEnumerable <ITaskItem> solutionItems, IDictionary <string, string> properties, string defaultConfig, CancellationToken ct)
        {
            var timer = Stopwatch.StartNew();

            var solutions = new ConcurrentBag <SolutionInfo>();

            Parallel.ForEach(solutionItems, solution =>
            {
                if (ct.IsCancellationRequested)
                {
                    return;
                }

                var solutionFile  = solution.ItemSpec.Replace('\\', '/');
                var solutionProps = new Dictionary <string, string>(properties, StringComparer.OrdinalIgnoreCase);
                foreach (var prop in MSBuildListSplitter.GetNamedProperties(solution.GetMetadata("AdditionalProperties")))
                {
                    solutionProps[prop.Key] = prop.Value;
                }

                if (!solutionProps.TryGetValue("Configuration", out var configName))
                {
                    solutionProps["Configuration"] = configName = defaultConfig;
                }

                var key = $"SlnInfo:{solutionFile}:{configName}";
                var obj = _buildEngine.GetRegisteredTaskObject(key, RegisteredTaskObjectLifetime.Build);

                if (obj is SolutionInfo cachedSlnInfo)
                {
                    solutions.Add(cachedSlnInfo);
                    return;
                }

                _logger.LogMessage($"Analyzing {solutionFile} ({configName})");
                var projects     = new ConcurrentBag <ProjectInfo>();
                var projectFiles = GetProjectsForSolutionConfig(solutionFile, configName);
                using (var projCollection = new ProjectCollection(solutionProps)
                {
                    IsBuildEnabled = false
                })
                {
                    Parallel.ForEach(projectFiles, projectFile =>
                    {
                        if (ct.IsCancellationRequested)
                        {
                            return;
                        }

                        try
                        {
                            projects.Add(new ProjectInfoFactory(_logger).Create(projectFile, projCollection));
                        }
                        catch (Exception ex)
                        {
                            _logger.LogErrorFromException(ex);
                        }
                    });
                }

                bool.TryParse(solution.GetMetadata("Build"), out var shouldBuild);
                bool.TryParse(solution.GetMetadata("IsPatching"), out var isPatching);

                var solutionInfo = new SolutionInfo(
                    solutionFile,
                    configName,
                    projects.ToArray(),
                    shouldBuild,
                    isPatching);

                _buildEngine.RegisterTaskObject(key, solutionInfo, RegisteredTaskObjectLifetime.Build, allowEarlyCollection: true);

                solutions.Add(solutionInfo);
            });

            timer.Stop();
            _logger.LogMessage(MessageImportance.High, $"Finished design-time build in {timer.ElapsedMilliseconds}ms");
            return(solutions.ToArray());
        }
コード例 #3
0
        public IList <string> Merge(List <TypeDefinition> subclasses, string applicationClass, bool embed, string bundledWearApplicationName, IEnumerable <string> mergedManifestDocuments)
        {
            string applicationName = ApplicationName;

            var manifest = doc.Root;

            if (manifest == null || manifest.Name != "manifest")
            {
                throw new Exception("Root element must be 'manifest'");
            }

            var manifest_package = (string)manifest.Attribute("package");

            if (!string.IsNullOrWhiteSpace(manifest_package))
            {
                PackageName = manifest_package;
            }

            manifest.SetAttributeValue(XNamespace.Xmlns + "android", "http://schemas.android.com/apk/res/android");
            if (manifest.Attribute(androidNs + "versionCode") == null)
            {
                manifest.SetAttributeValue(androidNs + "versionCode", "1");
            }
            if (manifest.Attribute(androidNs + "versionName") == null)
            {
                manifest.SetAttributeValue(androidNs + "versionName", "1.0");
            }

            app = CreateApplicationElement(manifest, applicationClass, subclasses);

            if (app.Attribute(androidNs + "label") == null && applicationName != null)
            {
                app.SetAttributeValue(androidNs + "label", applicationName);
            }

            var existingTypes = new HashSet <string> (
                app.Descendants().Select(a => (string)a.Attribute(attName)).Where(v => v != null));

            if (!string.IsNullOrEmpty(bundledWearApplicationName))
            {
                if (!app.Elements("meta-data").Any(e => e.Attributes(androidNs + "name").Any(a => a.Value == bundledWearApplicationName)))
                {
                    app.Add(new XElement("meta-data", new XAttribute(androidNs + "name", "com.google.android.wearable.beta.app"), new XAttribute(androidNs + "resource", "@xml/wearable_app_desc")));
                }
            }

            // If no <uses-sdk> is specified, add it with both minSdkVersion and
            // targetSdkVersion set to TargetFrameworkVersion
            if (!manifest.Elements("uses-sdk").Any())
            {
                manifest.AddFirst(
                    new XElement("uses-sdk",
                                 new XAttribute(androidNs + "minSdkVersion", SdkVersionName),
                                 new XAttribute(androidNs + "targetSdkVersion", SdkVersionName)));
            }

            // If no minSdkVersion is specified, set it to TargetFrameworkVersion
            var uses = manifest.Element("uses-sdk");

            if (uses.Attribute(androidNs + "minSdkVersion") == null)
            {
                int minSdkVersion;
                if (!int.TryParse(SdkVersionName, out minSdkVersion))
                {
                    minSdkVersion = XABuildConfig.NDKMinimumApiAvailable;
                }
                minSdkVersion = Math.Min(minSdkVersion, XABuildConfig.NDKMinimumApiAvailable);
                uses.SetAttributeValue(androidNs + "minSdkVersion", minSdkVersion.ToString());
            }

            string targetSdkVersion;
            var    tsv = uses.Attribute(androidNs + "targetSdkVersion");

            if (tsv != null)
            {
                targetSdkVersion = tsv.Value;
            }
            else
            {
                targetSdkVersion = SdkVersionName;
                uses.AddBeforeSelf(new XComment("suppress UsesMinSdkAttributes"));
            }

            int?tryTargetSdkVersion = MonoAndroidHelper.SupportedVersions.GetApiLevelFromId(targetSdkVersion);

            if (!tryTargetSdkVersion.HasValue)
            {
                throw new InvalidOperationException(string.Format("The targetSdkVersion ({0}) is not a valid API level", targetSdkVersion));
            }
            int targetSdkVersionValue = tryTargetSdkVersion.Value;

            foreach (var t in subclasses)
            {
                if (t.IsAbstract)
                {
                    continue;
                }

                if (PackageName == null)
                {
                    PackageName = t.Namespace;
                }

                var name       = JavaNativeTypeManager.ToJniName(t).Replace('/', '.');
                var compatName = JavaNativeTypeManager.ToCompatJniName(t).Replace('/', '.');
                if (((string)app.Attribute(attName)) == compatName)
                {
                    app.SetAttributeValue(attName, name);
                }

                Func <TypeDefinition, string, int, XElement> generator = GetGenerator(t);
                if (generator == null)
                {
                    continue;
                }

                try {
                    // activity not present: create a launcher for it IFF it has attribute
                    if (!existingTypes.Contains(name) && !existingTypes.Contains(compatName))
                    {
                        XElement fromCode = generator(t, name, targetSdkVersionValue);
                        if (fromCode == null)
                        {
                            continue;
                        }

                        IEnumerable <MethodDefinition> constructors = t.Methods.Where(m => m.IsConstructor).Cast <MethodDefinition> ();
                        if (!constructors.Any(c => !c.HasParameters && c.IsPublic))
                        {
                            string        message        = $"The type '{t.FullName}' must provide a public default constructor";
                            SequencePoint sourceLocation = FindSource(constructors);

                            if (sourceLocation != null && sourceLocation.Document?.Url != null)
                            {
                                log.LogError(
                                    subcategory:      String.Empty,
                                    errorCode:        "XA4213",
                                    helpKeyword:      String.Empty,
                                    file:             sourceLocation.Document.Url,
                                    lineNumber:       sourceLocation.StartLine,
                                    columnNumber:     sourceLocation.StartColumn,
                                    endLineNumber:    sourceLocation.EndLine,
                                    endColumnNumber:  sourceLocation.EndColumn,
                                    message:          message);
                            }
                            else
                            {
                                log.LogCodedError("XA4213", message);
                            }
                            continue;
                        }
                        app.Add(fromCode);
                    }
                    foreach (var d in app.Descendants().Where(a => ((string)a.Attribute(attName)) == compatName))
                    {
                        d.SetAttributeValue(attName, name);
                    }
                } catch (InvalidActivityNameException ex) {
                    log.LogErrorFromException(ex);
                }
            }

            var icon = app.Attribute(androidNs + "icon");

            if (icon == null)
            {
                var activity = app.Element("activity");
                if (activity != null)
                {
                    var activityIcon = activity.Attribute(androidNs + "icon");
                    if (activityIcon != null)
                    {
                        app.Add(new XAttribute(androidNs + "icon", activityIcon.Value));
                    }
                }
            }

            PackageName = AndroidAppManifest.CanonicalizePackageName(PackageName);

            if (!PackageName.Contains('.'))
            {
                throw new InvalidOperationException("/manifest/@package attribute MUST contain a period ('.').");
            }

            manifest.SetAttributeValue("package", PackageName);

            if (MultiDex)
            {
                app.Add(CreateMonoRuntimeProvider("mono.android.MultiDexLoader", null, initOrder: --AppInitOrder));
            }

            var providerNames = AddMonoRuntimeProviders(app);

            if (Debug && !embed && InstantRunEnabled)
            {
                if (int.TryParse(SdkVersion, out int apiLevel) && apiLevel >= 19)
                {
                    app.Add(CreateMonoRuntimeProvider("mono.android.ResourcePatcher", null, initOrder: --AppInitOrder));
                }
            }
            if (Debug)
            {
                app.Add(new XComment("suppress ExportedReceiver"));
                app.Add(new XElement("receiver",
                                     new XAttribute(androidNs + "name", "mono.android.Seppuku"),
                                     new XElement("intent-filter",
                                                  new XElement("action",
                                                               new XAttribute(androidNs + "name", "mono.android.intent.action.SEPPUKU")),
                                                  new XElement("category",
                                                               new XAttribute(androidNs + "name", "mono.android.intent.category.SEPPUKU." + PackageName)))));
                if (app.Attribute(androidNs + "debuggable") == null)
                {
                    app.Add(new XAttribute(androidNs + "debuggable", "true"));
                }
            }
            if (Debug || NeedsInternet)
            {
                AddInternetPermissionForDebugger();
            }

            if (!embed)
            {
                AddFastDeployPermissions();
            }

            // If the manifest has android:installLocation, but we are targeting
            // API 7 or lower, remove it for the user and show a warning
            if (manifest.Attribute(androidNs + "installLocation") != null)
            {
                if (targetSdkVersionValue < 8)
                {
                    manifest.Attribute(androidNs + "installLocation").Remove();
                    Console.Error.WriteLine("monodroid: warning 1 : installLocation cannot be specified for Android versions less than 2.2.  Attribute installLocation ignored.");
                }
            }

            AddInstrumentations(manifest, subclasses, targetSdkVersionValue);
            AddPermissions(app);
            AddPermissionGroups(app);
            AddPermissionTrees(app);
            AddUsesPermissions(app);
            AddUsesFeatures(app);
            AddSupportsGLTextures(app);

            ReorderActivityAliases(app);
            ReorderElements(app);

            if (mergedManifestDocuments != null)
            {
                foreach (var mergedManifest in mergedManifestDocuments)
                {
                    try {
                        MergeLibraryManifest(mergedManifest);
                    } catch (Exception ex) {
                        log.LogCodedWarning("XA4302", "Unhandled exception merging `AndroidManifest.xml`: {0}", ex);
                    }
                }
            }

            return(providerNames);

            SequencePoint FindSource(IEnumerable <MethodDefinition> methods)
            {
                if (methods == null)
                {
                    return(null);
                }

                SequencePoint ret = null;

                foreach (MethodDefinition method in methods.Where(m => m != null && m.HasBody && m.DebugInformation != null))
                {
                    foreach (Instruction ins in method.Body.Instructions)
                    {
                        SequencePoint seq = method.DebugInformation.GetSequencePoint(ins);
                        if (seq == null)
                        {
                            continue;
                        }

                        if (ret == null || seq.StartLine < ret.StartLine)
                        {
                            ret = seq;
                        }
                        break;
                    }
                }

                return(ret);
            }
        }
コード例 #4
0
ファイル: ResolveEnvironment.cs プロジェクト: PeezoSlug/PTVS
        public bool Execute()
        {
            string id = InterpreterId;

            ProjectCollection collection = null;
            Project           project    = null;

#if !BUILDTASKS_CORE
            var exports = GetExportProvider();
            if (exports == null)
            {
                _log.LogError("Unable to obtain interpreter service.");
                return(false);
            }
#endif

            try
            {
                try
                {
                    project = ProjectCollection.GlobalProjectCollection.GetLoadedProjects(_projectPath).Single();
                }
                catch (InvalidOperationException)
                {
                    // Could not get exactly one project matching the path.
                }

                if (project == null)
                {
                    collection = new ProjectCollection();
                    project    = collection.LoadProject(_projectPath);
                }

                if (id == null)
                {
                    id = project.GetPropertyValue("InterpreterId");
                    if (String.IsNullOrWhiteSpace(id))
                    {
#if !BUILDTASKS_CORE
                        var options = exports.GetExportedValueOrDefault <IInterpreterOptionsService>();
                        if (options != null)
                        {
                            id = options.DefaultInterpreterId;
                        }
#endif
                    }
                }

                var projectHome = PathUtils.GetAbsoluteDirectoryPath(
                    project.DirectoryPath,
                    project.GetPropertyValue("ProjectHome")
                    );

                var searchPath = project.GetPropertyValue("SearchPath");
                if (!string.IsNullOrEmpty(searchPath))
                {
                    SearchPaths = searchPath.Split(';')
                                  .Select(p => PathUtils.GetAbsoluteFilePath(projectHome, p))
                                  .ToArray();
                }
                else
                {
                    SearchPaths = new string[0];
                }

#if BUILDTASKS_CORE
                ProjectItem item = null;
                InterpreterConfiguration config = null;

                if (string.IsNullOrEmpty(id))
                {
                    id = project.GetItems(MSBuildConstants.InterpreterReferenceItem).Select(pi => pi.GetMetadataValue(MSBuildConstants.IdKey)).LastOrDefault(i => !string.IsNullOrEmpty(i));
                }
                if (string.IsNullOrEmpty(id))
                {
                    item = project.GetItems(MSBuildConstants.InterpreterItem).FirstOrDefault();
                    if (item == null)
                    {
                        var found = PythonRegistrySearch.PerformDefaultSearch().OrderByDescending(i => i.Configuration.Version).ToArray();
                        config = (
                            found.Where(i => CPythonInterpreterFactoryConstants.TryParseInterpreterId(i.Configuration.Id, out var co, out _) &&
                                        PythonRegistrySearch.PythonCoreCompany.Equals(co, StringComparison.OrdinalIgnoreCase)).FirstOrDefault()
                            ?? found.FirstOrDefault()
                            )?.Configuration;
                    }
                }
                else
                {
                    // Special case MSBuild environments
                    var m = Regex.Match(id, @"MSBuild\|(?<id>.+?)\|(?<moniker>.+)$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
                    if (m.Success && m.Groups["id"].Success)
                    {
                        var subId = m.Groups["id"].Value;
                        item = project.GetItems(MSBuildConstants.InterpreterItem)
                               .FirstOrDefault(pi => subId.Equals(pi.GetMetadataValue(MSBuildConstants.IdKey), StringComparison.OrdinalIgnoreCase));
                    }
                    if (item == null)
                    {
                        config = PythonRegistrySearch.PerformDefaultSearch()
                                 .FirstOrDefault(pi => id.Equals(pi.Configuration.Id, StringComparison.OrdinalIgnoreCase))?.Configuration;
                    }
                }
                if (item != null)
                {
                    PrefixPath = PathUtils.GetAbsoluteDirectoryPath(projectHome, item.EvaluatedInclude);
                    if (PathUtils.IsSubpathOf(projectHome, PrefixPath))
                    {
                        ProjectRelativePrefixPath = PathUtils.GetRelativeDirectoryPath(projectHome, PrefixPath);
                    }
                    else
                    {
                        ProjectRelativePrefixPath = string.Empty;
                    }
                    InterpreterPath         = PathUtils.GetAbsoluteFilePath(PrefixPath, item.GetMetadataValue(MSBuildConstants.InterpreterPathKey));
                    WindowsInterpreterPath  = PathUtils.GetAbsoluteFilePath(PrefixPath, item.GetMetadataValue(MSBuildConstants.WindowsPathKey));
                    Architecture            = InterpreterArchitecture.TryParse(item.GetMetadataValue(MSBuildConstants.ArchitectureKey)).ToString("X");
                    PathEnvironmentVariable = item.GetMetadataValue(MSBuildConstants.PathEnvVarKey).IfNullOrEmpty("PYTHONPATH");
                    Description             = item.GetMetadataValue(MSBuildConstants.DescriptionKey).IfNullOrEmpty(PathUtils.CreateFriendlyDirectoryPath(projectHome, PrefixPath));
                    Version ver;
                    if (Version.TryParse(item.GetMetadataValue(MSBuildConstants.VersionKey) ?? "", out ver))
                    {
                        MajorVersion = ver.Major.ToString();
                        MinorVersion = ver.Minor.ToString();
                    }
                    else
                    {
                        MajorVersion = MinorVersion = "0";
                    }
                    return(true);
                }
                else if (config != null)
                {
                    UpdateResultFromConfiguration(config, projectHome);
                    return(true);
                }
#else
                // MsBuildProjectContextProvider isn't available in-proc, instead we rely upon the
                // already loaded VsProjectContextProvider which is loaded in proc and already
                // aware of the projects loaded in Solution Explorer.
                var projectContext = exports.GetExportedValueOrDefault <MsBuildProjectContextProvider>();
                if (projectContext != null)
                {
                    projectContext.AddContext(project);
                }
                try
                {
                    var config = exports.GetExportedValue <IInterpreterRegistryService>().FindConfiguration(id);

                    if (config != null)
                    {
                        UpdateResultFromConfiguration(config, projectHome);
                        return(true);
                    }
                }
                finally
                {
                    if (projectContext != null)
                    {
                        projectContext.RemoveContext(project);
                    }
                }
#endif

                if (!string.IsNullOrEmpty(id))
                {
                    _log.LogError(
                        "The environment '{0}' is not available. Check your project configuration and try again.",
                        id
                        );
                    return(false);
                }
            }
            catch (Exception ex)
            {
                _log.LogErrorFromException(ex);
            }
            finally
            {
                if (collection != null)
                {
                    collection.UnloadAllProjects();
                    collection.Dispose();
                }
            }

            _log.LogError("Unable to resolve environment");
            return(false);
        }
コード例 #5
0
        protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands)
        {
            if (ProvideCommandLineArgs)
            {
                CommandLineArgs = GetArguments(commandLineCommands, responseFileCommands)
                                  .Select(arg => new TaskItem(arg)).ToArray();
            }

            if (SkipCompilerExecution)
            {
                return(0);
            }

            try
            {
                string workingDir = CurrentDirectoryToUse();
                string?tempDir    = BuildServerConnection.GetTempPath(workingDir);

                if (!UseSharedCompilation ||
                    HasToolBeenOverridden ||
                    !BuildServerConnection.IsCompilerServerSupported)
                {
                    return(base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands));
                }

                using var logger = new CompilerServerLogger();
                using (_sharedCompileCts = new CancellationTokenSource())
                {
                    logger.Log($"CommandLine = '{commandLineCommands}'");
                    logger.Log($"BuildResponseFile = '{responseFileCommands}'");

                    var clientDir = Path.GetDirectoryName(PathToManagedTool);
                    if (clientDir is null || tempDir is null)
                    {
                        return(base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands));
                    }

                    // Note: we can't change the "tool path" printed to the console when we run
                    // the Csc/Vbc task since MSBuild logs it for us before we get here. Instead,
                    // we'll just print our own message that contains the real client location
                    Log.LogMessage(ErrorString.UsingSharedCompilation, clientDir);

                    var buildPaths = new BuildPathsAlt(
                        clientDir: clientDir,
                        workingDir: workingDir,
                        // MSBuild doesn't need the .NET SDK directory
                        sdkDir: null,
                        tempDir: tempDir);

                    // Note: using ToolArguments here (the property) since
                    // commandLineCommands (the parameter) may have been mucked with
                    // (to support using the dotnet cli)
                    var responseTask = BuildServerConnection.RunServerCompilationAsync(
                        Language,
                        RoslynString.IsNullOrEmpty(SharedCompilationId) ? null : SharedCompilationId,
                        GetArguments(ToolArguments, responseFileCommands).ToList(),
                        buildPaths,
                        keepAlive: null,
                        libEnvVariable: LibDirectoryToUse(),
                        logger: logger,
                        cancellationToken: _sharedCompileCts.Token);

                    responseTask.Wait(_sharedCompileCts.Token);

                    var response = responseTask.Result;
                    if (response != null)
                    {
                        ExitCode = HandleResponse(response, pathToTool, responseFileCommands, commandLineCommands, logger);
                    }
                    else
                    {
                        logger.LogError($"Server compilation failed, falling back to {pathToTool}");
                        Log.LogMessage(ErrorString.SharedCompilationFallback, pathToTool);

                        ExitCode = base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                ExitCode = 0;
            }
            catch (Exception e)
            {
                var util = new TaskLoggingHelper(this);
                util.LogErrorWithCodeFromResources("Compiler_UnexpectedException");
                util.LogErrorFromException(e, showStackTrace: true, showDetail: true, file: null);
                ExitCode = -1;
            }

            return(ExitCode);
        }
コード例 #6
0
ファイル: Configuration.cs プロジェクト: steveharter/arcade
        /// <summary>
        /// Build up the <see cref="ZipData"/> instance for a given zip container. This will also report any consistency
        /// errors found when examining the zip archive.
        /// </summary>
        private bool TryBuildZipData(FileSignInfo zipFileSignInfo, out ZipData zipData)
        {
            Debug.Assert(zipFileSignInfo.IsZipContainer());

            try
            {
                using (var archive = new ZipArchive(File.OpenRead(zipFileSignInfo.FullPath), ZipArchiveMode.Read))
                {
                    var nestedParts = new List <ZipPart>();

                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        string relativePath = entry.FullName;

                        // `entry` might be just a pointer to a folder. We skip those.
                        if (relativePath.EndsWith("/") && entry.Name == "")
                        {
                            continue;
                        }

                        ImmutableArray <byte> contentHash;
                        using (var stream = entry.Open())
                        {
                            contentHash = ContentUtil.GetContentHash(stream);
                        }

                        var fileUniqueKey = new SignedFileContentKey(contentHash, relativePath);

                        if (!_whichPackagesTheFileIsIn.TryGetValue(fileUniqueKey, out var packages))
                        {
                            packages = new HashSet <string>();
                        }

                        packages.Add(zipFileSignInfo.FileName);
                        _whichPackagesTheFileIsIn[fileUniqueKey] = packages;

                        // if we already encountered file that hash the same content we can reuse its signed version when repackaging the container.
                        var fileName = Path.GetFileName(relativePath);
                        if (!_filesByContentKey.TryGetValue(new SignedFileContentKey(contentHash, fileName), out var fileSignInfo))
                        {
                            string extractPathRoot = _useHashInExtractionPath ? ContentUtil.HashToString(contentHash) : _filesByContentKey.Count().ToString();
                            string tempPath        = Path.Combine(_pathToContainerUnpackingDirectory, extractPathRoot, relativePath);
                            _log.LogMessage($"Extracting file '{fileName}' from '{zipFileSignInfo.FullPath}' to '{tempPath}'.");

                            Directory.CreateDirectory(Path.GetDirectoryName(tempPath));

                            using (var stream = entry.Open())
                                using (var tempFileStream = File.OpenWrite(tempPath))
                                {
                                    stream.CopyTo(tempFileStream);
                                }

                            fileSignInfo = TrackFile(tempPath, contentHash, isNested: true);
                        }

                        if (fileSignInfo.SignInfo.ShouldSign)
                        {
                            nestedParts.Add(new ZipPart(relativePath, fileSignInfo));
                        }
                    }

                    zipData = new ZipData(zipFileSignInfo, nestedParts.ToImmutableArray());

                    return(true);
                }
            }
            catch (Exception e)
            {
                _log.LogErrorFromException(e);
                zipData = null;
                return(false);
            }
        }
コード例 #7
0
 public void LogErrorFromException(Exception exception)
 {
     _log.LogErrorFromException(exception, true, true, null);
 }
コード例 #8
0
        public IList <string> Merge(List <TypeDefinition> subclasses, List <string> selectedWhitelistAssemblies, string applicationClass, bool embed, string bundledWearApplicationName, IEnumerable <string> mergedManifestDocuments)
        {
            string applicationName = ApplicationName;

            var manifest = doc.Root;

            if (manifest == null || manifest.Name != "manifest")
            {
                throw new Exception("Root element must be 'manifest'");
            }

            var manifest_package = (string)manifest.Attribute("package");

            if (!string.IsNullOrWhiteSpace(manifest_package))
            {
                PackageName = manifest_package;
            }

            manifest.SetAttributeValue(XNamespace.Xmlns + "android", "http://schemas.android.com/apk/res/android");
            if (manifest.Attribute(androidNs + "versionCode") == null)
            {
                manifest.SetAttributeValue(androidNs + "versionCode", "1");
            }
            if (manifest.Attribute(androidNs + "versionName") == null)
            {
                manifest.SetAttributeValue(androidNs + "versionName", "1.0");
            }

            app = CreateApplicationElement(manifest, applicationClass, subclasses, selectedWhitelistAssemblies);

            if (app.Attribute(androidNs + "label") == null && applicationName != null)
            {
                app.SetAttributeValue(androidNs + "label", applicationName);
            }

            var existingTypes = new HashSet <string> (
                app.Descendants().Select(a => (string)a.Attribute(attName)).Where(v => v != null));

            if (!string.IsNullOrEmpty(bundledWearApplicationName))
            {
                if (!app.Elements("meta-data").Any(e => e.Attributes(androidNs + "name").Any(a => a.Value == bundledWearApplicationName)))
                {
                    app.Add(new XElement("meta-data", new XAttribute(androidNs + "name", "com.google.android.wearable.beta.app"), new XAttribute(androidNs + "resource", "@xml/wearable_app_desc")));
                }
            }

            // If no <uses-sdk> is specified, add it with both minSdkVersion and
            // targetSdkVersion set to TargetFrameworkVersion
            if (!manifest.Elements("uses-sdk").Any())
            {
                manifest.AddFirst(
                    new XElement("uses-sdk",
                                 new XAttribute(androidNs + "minSdkVersion", SdkVersionName),
                                 new XAttribute(androidNs + "targetSdkVersion", SdkVersionName)));
            }

            // If no minSdkVersion is specified, set it to TargetFrameworkVersion
            var uses = manifest.Element("uses-sdk");

            if (uses.Attribute(androidNs + "minSdkVersion") == null)
            {
                int minSdkVersion;
                if (!int.TryParse(SdkVersionName, out minSdkVersion))
                {
                    minSdkVersion = 11;
                }
                minSdkVersion = Math.Min(minSdkVersion, 11);
                uses.SetAttributeValue(androidNs + "minSdkVersion", minSdkVersion.ToString());
            }

            string targetSdkVersion;
            var    tsv = uses.Attribute(androidNs + "targetSdkVersion");

            if (tsv != null)
            {
                targetSdkVersion = tsv.Value;
            }
            else
            {
                targetSdkVersion = SdkVersionName;
                uses.AddBeforeSelf(new XComment("suppress UsesMinSdkAttributes"));
            }

            int targetSdkVersionValue;

            if (!int.TryParse(MonoAndroidHelper.GetPlatformApiLevel(targetSdkVersion), out targetSdkVersionValue))
            {
                throw new InvalidOperationException(string.Format("The targetSdkVersion ({0}) is not a valid API level", targetSdkVersion));
            }

            foreach (var t in subclasses)
            {
                if (t.IsAbstract)
                {
                    continue;
                }

                if (PackageName == null)
                {
                    PackageName = t.Namespace;
                }

                var name       = JniType.ToJniName(t).Replace('/', '.');
                var compatName = JniType.ToCompatJniName(t).Replace('/', '.');
                if (((string)app.Attribute(attName)) == compatName)
                {
                    app.SetAttributeValue(attName, name);
                }

                Func <TypeDefinition, string, int, XElement> generator = GetGenerator(t);
                if (generator == null)
                {
                    continue;
                }

                try {
                    // activity not present: create a launcher for it IFF it has attribute
                    if (!existingTypes.Contains(name) && !existingTypes.Contains(compatName))
                    {
                        XElement fromCode = generator(t, name, targetSdkVersionValue);
                        if (fromCode == null)
                        {
                            continue;
                        }

                        if (!t.Methods.Where(m => m.IsConstructor).Cast <MethodDefinition> ().Any(c => !c.HasParameters && c.IsPublic))
                        {
                            throw new InvalidOperationException(string.Format("The type '{0}' needs to have a public default constructor.",
                                                                              t.FullName));
                        }
                        app.Add(fromCode);
                    }
                    foreach (var d in app.Descendants().Where(a => ((string)a.Attribute(attName)) == compatName))
                    {
                        d.SetAttributeValue(attName, name);
                    }
                } catch (InvalidActivityNameException ex) {
                    log.LogErrorFromException(ex);
                }
            }

            var icon = app.Attribute(androidNs + "icon");

            if (icon == null)
            {
                var activity = app.Element("activity");
                if (activity != null)
                {
                    var activityIcon = activity.Attribute(androidNs + "icon");
                    if (activityIcon != null)
                    {
                        app.Add(new XAttribute(androidNs + "icon", activityIcon.Value));
                    }
                }
            }

            PackageName = AndroidAppManifest.CanonicalizePackageName(PackageName);

            if (!PackageName.Contains('.'))
            {
                throw new InvalidOperationException("/manifest/@package attribute MUST contain a period ('.').");
            }

            manifest.SetAttributeValue("package", PackageName);

            var providerNames = AddMonoRuntimeProviders(app);

            if (Debug)
            {
                app.Add(new XComment("suppress ExportedReceiver"));
                app.Add(new XElement("receiver",
                                     new XAttribute(androidNs + "name", "mono.android.Seppuku"),
                                     new XElement("intent-filter",
                                                  new XElement("action",
                                                               new XAttribute(androidNs + "name", "mono.android.intent.action.SEPPUKU")),
                                                  new XElement("category",
                                                               new XAttribute(androidNs + "name", "mono.android.intent.category.SEPPUKU." + PackageName)))));
                if (app.Attribute(androidNs + "debuggable") == null)
                {
                    app.Add(new XAttribute(androidNs + "debuggable", "true"));
                }
            }
            if (Debug || NeedsInternet)
            {
                AddInternetPermissionForDebugger();
            }

            if (!embed)
            {
                AddFastDeployPermissions();
            }

            AddAddOns(app, SdkDir, SdkVersionName, Addons);

            // If the manifest has android:installLocation, but we are targeting
            // API 7 or lower, remove it for the user and show a warning
            if (manifest.Attribute(androidNs + "installLocation") != null)
            {
                if (targetSdkVersionValue < 8)
                {
                    manifest.Attribute(androidNs + "installLocation").Remove();
                    Console.Error.WriteLine("monodroid: warning 1 : installLocation cannot be specified for Android versions less than 2.2.  Attribute installLocation ignored.");
                }
            }

            AddInstrumentations(manifest, subclasses, targetSdkVersionValue);
            AddPermissions(app, selectedWhitelistAssemblies);
            AddPermissionGroups(app, selectedWhitelistAssemblies);
            AddPermissionTrees(app, selectedWhitelistAssemblies);
            AddUsesPermissions(app, selectedWhitelistAssemblies);
            AddUsesFeatures(app, selectedWhitelistAssemblies);
            AddSupportsGLTextures(app, selectedWhitelistAssemblies);

            ReorderActivityAliases(app);
            ReorderElements(app);

            if (mergedManifestDocuments != null)
            {
                foreach (var mergedManifest in mergedManifestDocuments)
                {
                    try {
                        MergeLibraryManifest(mergedManifest);
                    } catch (Exception ex) {
                        log.LogWarningFromException(ex);
                    }
                }
            }

            return(providerNames);
        }
コード例 #9
0
 void IXmlTransformationLogger.LogErrorFromException(Exception ex)
 {
     loggingHelper.LogErrorFromException(ex, stackTrace, stackTrace, null);
 }
コード例 #10
0
 /// <inheritdoc/>
 public override void LogErrorFromException(Exception exception)
 => Logger.LogErrorFromException(exception);
コード例 #11
0
 public void LogErrorFromException(Exception exception)
 {
     _log.LogErrorFromException(exception);
 }
コード例 #12
0
 public void Debug(object message, Exception exception)
 {
     _msbuildLogger.LogErrorFromException(exception, true);
 }
コード例 #13
0
ファイル: Configuration.cs プロジェクト: safern/arcade
        /// <summary>
        /// Build up the <see cref="ZipData"/> instance for a given zip container. This will also report any consistency
        /// errors found when examining the zip archive.
        /// </summary>
        private bool TryBuildZipData(FileSignInfo zipFileSignInfo, out ZipData zipData)
        {
            Debug.Assert(zipFileSignInfo.IsZipContainer());

            try
            {
                using (var archive = new ZipArchive(File.OpenRead(zipFileSignInfo.FullPath), ZipArchiveMode.Read))
                {
                    var nestedParts = new List <ZipPart>();

                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        string relativePath = entry.FullName;
                        string extension    = Path.GetExtension(relativePath);

                        if (!_fileExtensionSignInfo.TryGetValue(extension, out var extensionSignInfo) || !extensionSignInfo.ShouldSign)
                        {
                            continue;
                        }

                        ImmutableArray <byte> contentHash;
                        using (var stream = entry.Open())
                        {
                            contentHash = ContentUtil.GetContentHash(stream);
                        }

                        // if we already encountered file that hash the same content we can reuse its signed version when repackaging the container.
                        string fileName = Path.GetFileName(relativePath);
                        if (!_filesByContentKey.TryGetValue(new SignedFileContentKey(contentHash, fileName), out var fileSignInfo))
                        {
                            string tempDir  = Path.Combine(_pathToContainerUnpackingDirectory, ContentUtil.HashToString(contentHash));
                            string tempPath = Path.Combine(tempDir, Path.GetFileName(relativePath));
                            Directory.CreateDirectory(tempDir);

                            using (var stream = entry.Open())
                                using (var tempFileStream = File.OpenWrite(tempPath))
                                {
                                    stream.CopyTo(tempFileStream);
                                }

                            fileSignInfo = TrackFile(tempPath, contentHash, isNested: true);
                        }

                        if (fileSignInfo.SignInfo.ShouldSign)
                        {
                            nestedParts.Add(new ZipPart(relativePath, fileSignInfo));
                        }
                    }

                    zipData = new ZipData(zipFileSignInfo, nestedParts.ToImmutableArray());

                    return(true);
                }
            }
            catch (Exception e)
            {
                _log.LogErrorFromException(e);
                zipData = null;
                return(false);
            }
        }
コード例 #14
0
 public void LogErrorFromException(Exception e)
 {
     log.LogErrorFromException(e);
 }
コード例 #15
0
        /// <summary>
        /// Build up the <see cref="ZipData"/> instance for a given zip container. This will also report any consistency
        /// errors found when examining the zip archive.
        /// </summary>
        private bool TryBuildZipData(FileSignInfo zipFileSignInfo, out ZipData zipData, string alternativeArchivePath = null)
        {
            string archivePath = zipFileSignInfo.FullPath;

            if (alternativeArchivePath != null)
            {
                archivePath = alternativeArchivePath;
                Debug.Assert(Path.GetExtension(archivePath) == ".zip");
            }
            else
            {
                Debug.Assert(zipFileSignInfo.IsZipContainer());
            }

            try
            {
                using (var archive = new ZipArchive(File.OpenRead(archivePath), ZipArchiveMode.Read))
                {
                    var nestedParts = new Dictionary <string, ZipPart>();


                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        string relativePath = entry.FullName;

                        // `entry` might be just a pointer to a folder. We skip those.
                        if (relativePath.EndsWith("/") && entry.Name == "")
                        {
                            continue;
                        }

                        using (var entryStream = entry.Open())
                            using (MemoryStream entryMemoryStream = new MemoryStream((int)entry.Length))
                            {
                                entryStream.CopyTo(entryMemoryStream);
                                entryMemoryStream.Position = 0;
                                ImmutableArray <byte> contentHash = ContentUtil.GetContentHash(entryMemoryStream);

                                var fileUniqueKey = new SignedFileContentKey(contentHash, Path.GetFileName(relativePath));

                                if (!_whichPackagesTheFileIsIn.TryGetValue(fileUniqueKey, out var packages))
                                {
                                    packages = new HashSet <string>();
                                }

                                packages.Add(Path.GetFileName(archivePath));

                                _whichPackagesTheFileIsIn[fileUniqueKey] = packages;

                                // if we already encountered file that has the same content we can reuse its signed version when repackaging the container.
                                var fileName = Path.GetFileName(relativePath);
                                if (!_filesByContentKey.TryGetValue(fileUniqueKey, out var fileSignInfo))
                                {
                                    string extractPathRoot = _useHashInExtractionPath ? fileUniqueKey.StringHash : _filesByContentKey.Count().ToString();
                                    string tempPath        = Path.Combine(_pathToContainerUnpackingDirectory, extractPathRoot, relativePath);
                                    _log.LogMessage($"Extracting file '{fileName}' from '{archivePath}' to '{tempPath}'.");

                                    Directory.CreateDirectory(Path.GetDirectoryName(tempPath));

                                    entryMemoryStream.Position = 0;
                                    using (var tempFileStream = File.OpenWrite(tempPath))
                                    {
                                        entryMemoryStream.CopyTo(tempFileStream);
                                    }

                                    _hashToCollisionIdMap.TryGetValue(fileUniqueKey, out string collisionPriorityId);
                                    PathWithHash nestedFile = new PathWithHash(tempPath, contentHash);
                                    fileSignInfo = TrackFile(nestedFile, zipFileSignInfo.File, collisionPriorityId);
                                }

                                if (fileSignInfo.ShouldTrack)
                                {
                                    nestedParts.Add(relativePath, new ZipPart(relativePath, fileSignInfo));
                                }
                            }
                    }

                    zipData = new ZipData(zipFileSignInfo, nestedParts.ToImmutableDictionary());

                    return(true);
                }
            }
            catch (Exception e)
            {
                _log.LogErrorFromException(e);
                zipData = null;
                return(false);
            }
        }
コード例 #16
0
 public void LogErrorFromException(Exception exception, bool showStackTrace)
 {
     _logger.LogErrorFromException(exception, showStackTrace);
 }
コード例 #17
0
        public bool Execute()
        {
            string id = InterpreterId;

            ProjectCollection collection = null;
            Project           project    = null;

            var exports = FromInProc() ?? FromOutOfProc();

            if (exports == null)
            {
                _log.LogError("Unable to obtain interpreter service.");
                return(false);
            }

            try {
                try {
                    project = ProjectCollection.GlobalProjectCollection.GetLoadedProjects(_projectPath).Single();
                } catch (InvalidOperationException) {
                    // Could not get exactly one project matching the path.
                }

                if (project == null)
                {
                    collection = new ProjectCollection();
                    project    = collection.LoadProject(_projectPath);
                }

                if (id == null)
                {
                    id = project.GetPropertyValue("InterpreterId");
                    if (String.IsNullOrWhiteSpace(id))
                    {
                        var options = exports.GetExportedValueOrDefault <IInterpreterOptionsService>();
                        if (options != null)
                        {
                            id = options.DefaultInterpreterId;
                        }
                    }
                }

                var projectHome = PathUtils.GetAbsoluteDirectoryPath(
                    project.DirectoryPath,
                    project.GetPropertyValue("ProjectHome")
                    );

                var searchPath = project.GetPropertyValue("SearchPath");
                if (!string.IsNullOrEmpty(searchPath))
                {
                    SearchPaths = searchPath.Split(';')
                                  .Select(p => PathUtils.GetAbsoluteFilePath(projectHome, p))
                                  .ToArray();
                }
                else
                {
                    SearchPaths = new string[0];
                }

                // MsBuildProjectContextProvider isn't available in-proc, instead we rely upon the
                // already loaded VsProjectContextProvider which is loaded in proc and already
                // aware of the projects loaded in Solution Explorer.
                var projectContext = exports.GetExportedValueOrDefault <MsBuildProjectContextProvider>();
                if (projectContext != null)
                {
                    projectContext.AddContext(project);
                }
                try {
                    var factory = exports.GetExportedValue <IInterpreterRegistryService>().FindInterpreter(id);

                    if (factory == null)
                    {
                        _log.LogError(
                            "The environment '{0}' is not available. Check your project configuration and try again.",
                            factory.Configuration.Description
                            );
                        return(false);
                    }
                    else
                    {
                        PrefixPath = PathUtils.EnsureEndSeparator(factory.Configuration.PrefixPath);
                        if (PathUtils.IsSubpathOf(projectHome, PrefixPath))
                        {
                            ProjectRelativePrefixPath = PathUtils.GetRelativeDirectoryPath(projectHome, PrefixPath);
                        }
                        else
                        {
                            ProjectRelativePrefixPath = string.Empty;
                        }
                        InterpreterPath         = factory.Configuration.InterpreterPath;
                        WindowsInterpreterPath  = factory.Configuration.WindowsInterpreterPath;
                        Architecture            = factory.Configuration.Architecture.ToString();
                        PathEnvironmentVariable = factory.Configuration.PathEnvironmentVariable;
                        Description             = factory.Configuration.Description;
                        MajorVersion            = factory.Configuration.Version.Major.ToString();
                        MinorVersion            = factory.Configuration.Version.Minor.ToString();

                        return(true);
                    }
                } finally {
                    if (projectContext != null)
                    {
                        projectContext.RemoveContext(project);
                    }
                }
            } catch (Exception ex) {
                _log.LogErrorFromException(ex);
            } finally {
                if (collection != null)
                {
                    collection.UnloadAllProjects();
                    collection.Dispose();
                }
            }

            _log.LogError("Unable to resolve environment");
            return(false);
        }
コード例 #18
0
ファイル: ManagedCompiler.cs プロジェクト: sinclair83/roslyn
        protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands)
        {
            if (ProvideCommandLineArgs)
            {
                CommandLineArgs = GetArguments(commandLineCommands, responseFileCommands)
                                  .Select(arg => new TaskItem(arg)).ToArray();
            }

            if (SkipCompilerExecution)
            {
                return(0);
            }

            try
            {
                using var logger = new CompilerServerLogger($"MSBuild {Process.GetCurrentProcess().Id}");
                string workingDir = CurrentDirectoryToUse();
                string?tempDir    = BuildServerConnection.GetTempPath(workingDir);
                var    requestId  = Guid.NewGuid();

                if (!UseSharedCompilation ||
                    HasToolBeenOverridden ||
                    !BuildServerConnection.IsCompilerServerSupported)
                {
                    LogCompilationMessage(logger, requestId, CompilationKind.Tool, $"using command line tool by design '{pathToTool}'");
                    return(base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands));
                }

                _sharedCompileCts = new CancellationTokenSource();
                logger.Log($"CommandLine = '{commandLineCommands}'");
                logger.Log($"BuildResponseFile = '{responseFileCommands}'");

                var clientDir = Path.GetDirectoryName(PathToManagedTool);
                if (clientDir is null || tempDir is null)
                {
                    LogCompilationMessage(logger, requestId, CompilationKind.Tool, $"using command line tool because we could not find client directory '{PathToManagedTool}'");
                    return(base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands));
                }

                var buildPaths = new BuildPathsAlt(
                    clientDir: clientDir,
                    workingDir: workingDir,
                    // MSBuild doesn't need the .NET SDK directory
                    sdkDir: null,
                    tempDir: tempDir);

                // Note: using ToolArguments here (the property) since
                // commandLineCommands (the parameter) may have been mucked with
                // (to support using the dotnet cli)
                var responseTask = BuildServerConnection.RunServerCompilationAsync(
                    requestId,
                    Language,
                    RoslynString.IsNullOrEmpty(SharedCompilationId) ? null : SharedCompilationId,
                    GetArguments(ToolArguments, responseFileCommands).ToList(),
                    buildPaths,
                    keepAlive: null,
                    libEnvVariable: LibDirectoryToUse(),
                    logger: logger,
                    cancellationToken: _sharedCompileCts.Token);

                responseTask.Wait(_sharedCompileCts.Token);

                ExitCode = HandleResponse(requestId, responseTask.Result, pathToTool, responseFileCommands, commandLineCommands, logger);
            }
            catch (OperationCanceledException)
            {
                ExitCode = 0;
            }
            catch (Exception e)
            {
                var util = new TaskLoggingHelper(this);
                util.LogErrorWithCodeFromResources("Compiler_UnexpectedException");
                util.LogErrorFromException(e, showStackTrace: true, showDetail: true, file: null);
                ExitCode = -1;
            }
            finally
            {
                _sharedCompileCts?.Dispose();
                _sharedCompileCts = null;
            }

            return(ExitCode);
        }
コード例 #19
0
        /// <inheritdoc cref="ILogEventSink.Emit"/>
        public void Emit(LogEvent logEvent)
        {
            object?GetScalarValueOrNull(string key)
            {
                if (!logEvent.Properties.TryGetValue(key, out var value))
                {
                    return(null);
                }
                return(value is ScalarValue scalarValue ? scalarValue.Value : null);
            }

            string?GetStringOrNull(string key) =>
            GetScalarValueOrNull(key)?.ToString();

            int GetIntOrZero(string key)
            {
                var scalarValue = GetScalarValueOrNull(key);

                if (scalarValue == null)
                {
                    return(0);
                }
                if (scalarValue is int intValue)
                {
                    return(intValue);
                }
                if (int.TryParse(scalarValue.ToString(), out intValue))
                {
                    return(intValue);
                }
                return(0);
            }

            string?subcategory     = GetStringOrNull(Subcategory);
            string?code            = GetStringOrNull(MessageCode);
            string?helpKeyword     = GetStringOrNull(HelpKeyword);
            string?file            = GetStringOrNull(File);
            int    lineNumber      = GetIntOrZero(LineNumber);
            int    columnNumber    = GetIntOrZero(ColumnNumber);
            int    lineEndNumber   = GetIntOrZero(EndLineNumber);
            int    columnEndNumber = GetIntOrZero(EndColumnNumber);
            string message         = logEvent.RenderMessage(_formatProvider);

            switch (logEvent.Level)
            {
            case LogEventLevel.Verbose:
                _loggingHelper.LogMessage(subcategory, code, helpKeyword, file, lineNumber, columnNumber,
                                          lineEndNumber, columnEndNumber, MessageImportance.Low, message);
                break;

            case LogEventLevel.Debug:
                _loggingHelper.LogMessage(subcategory, code, helpKeyword, file, lineNumber, columnNumber,
                                          lineEndNumber, columnEndNumber, MessageImportance.Normal, message);
                break;

            case LogEventLevel.Information:
                _loggingHelper.LogMessage(subcategory, code, helpKeyword, file, lineNumber, columnNumber,
                                          lineEndNumber, columnEndNumber, MessageImportance.High, message);
                break;

            case LogEventLevel.Warning:
                _loggingHelper.LogWarning(subcategory, code, helpKeyword, file, lineNumber, columnNumber,
                                          lineEndNumber, columnEndNumber, message);
                if (logEvent.Exception != null)
                {
                    _loggingHelper.LogWarningFromException(logEvent.Exception);
                }
                break;

            case LogEventLevel.Fatal:
            case LogEventLevel.Error:
                if (logEvent.Level == LogEventLevel.Fatal)
                {
                    subcategory = subcategory ?? "Fatal error";
                }
                _loggingHelper.LogError(subcategory, code, helpKeyword, file, lineNumber, columnNumber,
                                        lineEndNumber, columnEndNumber, message);
                if (logEvent.Exception != null)
                {
                    _loggingHelper.LogErrorFromException(logEvent.Exception, false, false, file);
                }
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
コード例 #20
0
 public void Error(string message, Exception exception)
 {
     Log.LogErrorFromException(exception, true);
 }