Пример #1
0
 /// <summary>
 /// Reads the Stacks.xml file and instanciates the <see cref="StackRepo"/> objects and
 /// their <see cref="WorldInfo"/>: creating the StackRepo registers the required secrets
 /// in the key store.
 /// </summary>
 /// <param name="m">The monitor to use.</param>
 internal void ReadStacksFromLocalStacksFilePath(IActivityMonitor m)
 {
     if (!File.Exists(StacksFilePath))
     {
         m.Warn($"File '{StacksFilePath}' not found.");
     }
     else
     {
         using (m.OpenInfo($"Reading '{StacksFilePath}'."))
         {
             try
             {
                 _stackRepos.Clear();
                 _stackRepos.AddRange(XDocument.Load(StacksFilePath).Root.Elements().Select(e => StackRepo.Parse(this, e)));
             }
             catch (Exception ex)
             {
                 m.Error($"Unable to read '{StacksFilePath}' file.", ex);
             }
         }
     }
     if (_stackRepos.Count == 0)
     {
         using (m.OpenInfo("Since there is no Stack defined, we initialize CK and CK-Build mapped to '/Dev/CK' by default."))
         {
             m.Info($"Use 'run World/{nameof( SetWorldMapping )}' command to update the mapping.");
             _stackRepos.Add(new StackRepo(this, new Uri("https://github.com/signature-opensource/CK-Stack.git"), true));
             _stackRepos.Add(new StackRepo(this, new Uri("https://github.com/CK-Build/CK-Build-Stack.git"), true));
             WorldLocalMapping.SetMap(m, "CK-Build", "/Dev/CK");
             WorldLocalMapping.SetMap(m, "CK", "/Dev/CK");
             WriteStacksToLocalStacksFilePath(m);
         }
     }
 }
Пример #2
0
 internal void TerminateAspects(Func <bool> onError)
 {
     using (_monitor.OpenInfo("Terminating Aspects."))
     {
         for (int i = _runContext.Aspects.Count - 1; i >= 0; --i)
         {
             IStObjEngineAspect a = _runContext.Aspects[i];
             using (_monitor.OpenInfo($"Aspect: {a.GetType().FullName}."))
             {
                 try
                 {
                     if (!a.Terminate(_monitor, this))
                     {
                         onError();
                     }
                 }
                 catch (Exception ex)
                 {
                     _monitor.Error(ex);
                     onError();
                 }
             }
         }
         _trampoline.Execute(_monitor, onError);
     }
 }
Пример #3
0
        BuildResult CreateResultByPreparingBuilds(IActivityMonitor m, bool forceRebuild)
        {
            BuildResult result = null;

            using (m.OpenInfo("Preparing builds."))
            {
                if (!RunPrepareBuild(m))
                {
                    m.CloseGroup("Failed.");
                    return(null);
                }
                result = CreateBuildResult(m);
                if (result == null)
                {
                    return(null);
                }
                if (forceRebuild)
                {
                    using (m.OpenInfo("Forcing rebuild: Removing already existing artifacts that will be produced from caches."))
                    {
                        _localFeedProvider.RemoveFromAllCaches(m, result.GeneratedArtifacts.Select(g => g.Artifact));
                        _localFeedProvider.GetFeed(_type).Remove(m, result.GeneratedArtifacts.Select(g => g.Artifact));
                    }
                }
                m.CloseGroup("Success.");
            }
            return(result);
        }
 internal void RunAspects(Func <bool> onError, bool postCode)
 {
     using (_monitor.OpenInfo($"Running Aspects ({(postCode ? "Post" : "Pre" )} Code Generation)."))
     {
         foreach (var a in _startContext.Aspects)
         {
             using (_monitor.OpenInfo($"Aspect: {a.GetType()}."))
             {
                 try
                 {
                     bool success = postCode ? a.RunPostCode(_monitor, this) : a.RunPreCode(_monitor, this);
                     if (!success)
                     {
                         onError();
                     }
                 }
                 catch (Exception ex)
                 {
                     _monitor.Error(ex);
                     onError();
                 }
             }
         }
         if (postCode)
         {
             _trampolinePostCode.Execute(_monitor, onError);
         }
         else
         {
             _trampoline.Execute(_monitor, onError);
         }
     }
 }
Пример #5
0
        /// <summary>
        /// Runs the build. Orchestrates calls to <see cref="PrepareBuild"/> and <see cref="Build"/>.
        /// </summary>
        /// <param name="m">The monitor to use.</param>
        /// <returns>The BuildResult on success, null on error.</returns>
        public BuildResult Run(IActivityMonitor m, bool forceRebuild)
        {
            if (_packagesVersion.Count > 0)
            {
                throw new InvalidOperationException();
            }

            BuildResult result = CreateResultByPreparingBuilds(m, forceRebuild);

            if (result == null)
            {
                return(null);
            }
            using (m.OpenInfo("Running builds."))
            {
                BuildState state = RunBuild(m);
                if (state == BuildState.Failed)
                {
                    m.CloseGroup("Failed.");
                    return(null);
                }
                if (state == BuildState.Succeed)
                {
                    m.CloseGroup("Success.");
                }
                else
                {
                    // This is not really optimal but it is required only for DevelopBuilder
                    // (where version numbers are not fully known upfront AND commit may not be
                    // amendable (when on a fresh checkout).
                    // We may have resolved and applied the buildUpgrades in a tight dedicated loop
                    // but we would need to do exactly the same code than the DevelopBuilder.RunBuild does:
                    // applying build upgrades, checks the commit, then calls ReadCommitVersionInfo on actual
                    // (non amended commits), applies this new version to any previous solution and start again...
                    // This is exactly what this whole code does thanks to the BuildState.MustRetry.
                    using (m.OpenInfo("Retrying running builds."))
                    {
                        do
                        {
                            result = CreateResultByPreparingBuilds(m, forceRebuild);
                            state  = RunBuild(m);
                        }while(state == BuildState.MustRetry);
                        if (state == BuildState.Failed)
                        {
                            m.CloseGroup("Retry failed.");
                            m.CloseGroup("Failed (with retries).");
                            return(null);
                        }
                        if (state == BuildState.Succeed)
                        {
                            m.CloseGroup("Retry succeed.");
                            m.CloseGroup("Success (with retries).");
                        }
                    }
                }
            }
            return(result);
        }
Пример #6
0
 bool DoSomething(IActivityMonitor m, FileInfo file)
 {
     using (m.OpenInfo().Send("Do something important on file '{0}'.", file.Name))
     {
         if (!file.Exists)
         {
             m.Warn().Send("File does not exist.");
         }
         else
         {
             m.Trace().Send("File last modified at {1:T}. {0} Kb to process.", file.Length, file.LastWriteTimeUtc);
             try
             {
                 // ... Process file ...
             }
             catch (Exception ex)
             {
                 m.Error().Send(ex, "While processing.");
                 return(false);
             }
         }
         m.SetTopic("Changing my mind. Keeping it as-is.");
         return(true);
     }
 }
Пример #7
0
        public bool Execute(IActivityMonitor m, Func <bool> onError)
        {
            bool trampolineSuccess = true;
            int  i = 0;

            using (m.OpenInfo($"Executing initial {_postActions.Count} deferred actions.")
                   .ConcludeWith(() => $"Executed {i} actions."))
            {
                while (i < _postActions.Count)
                {
                    var a = _postActions[i];
                    Debug.Assert(a != null);
                    _postActions[i++] = null;
                    try
                    {
                        if (!a(m, _holder))
                        {
                            m.Error("A deferred action failed.");
                            trampolineSuccess = onError();
                        }
                    }
                    catch (Exception ex)
                    {
                        m.Error(ex);
                        trampolineSuccess = onError();
                    }
                }
                _postActions.Clear();
            }
            return(trampolineSuccess);
        }
Пример #8
0
 /// <summary>
 /// Reads or creates a new <see cref="SolutionFile"/>.
 /// </summary>
 /// <param name="m">The monitor to use.</param>
 /// <param name="ctx">The project file context.</param>
 /// <param name="solutionPath">The path to the .sln file relative to the <see cref="MSProjContext.FileSystem"/>.</param>
 /// <param name="mustExist">False to allow the file to not exist.</param>
 /// <returns>
 /// The solution file or null on error (for example when not found and <paramref name="mustExist"/> is true).
 /// </returns>
 public static SolutionFile Read(FileSystem fs, IActivityMonitor m, NormalizedPath solutionPath, bool mustExist = true)
 {
     using (m.OpenInfo($"Reading '{solutionPath}'."))
     {
         var file = fs.GetFileInfo(solutionPath);
         if (!file.Exists && mustExist)
         {
             m.Error($"File '{solutionPath}' not found. Unable to read the solution.");
             return(null);
         }
         var s = new SolutionFile(fs, solutionPath);
         if (file.Exists)
         {
             using (var r = new Reader(m, file.CreateReadStream()))
             {
                 if (!s.Read(r))
                 {
                     m.Error("Unable to read the Solution.");
                     return(null);
                 }
             }
         }
         else
         {
             m.Warn($"File '{solutionPath}' not found. Creating an empty solution.");
         }
         return(s);
     }
 }
        public void Run()
        {
            _monitor.Info().Send("ThreadContext{0}Begin", NumMonitor);
            foreach (var bc in _monitor.Output.Clients.OfType <BuggyClient>())
            {
                bc.RunThreadId = Thread.CurrentThread.ManagedThreadId;
            }
            for (int i = 0; i < OperationCount; ++i)
            {
                double op = Rand.NextDouble();
                if (op < 1.0 / 60)
                {
                    _monitor.MinimalFilter = _monitor.MinimalFilter == LogFilter.Debug ? LogFilter.Verbose : LogFilter.Debug;
                }

                if (op < 1.0 / 3)
                {
                    _monitor.Info().Send("OP-{0}-{1}", NumMonitor, i);
                }
                else if (op < 2.0 / 3)
                {
                    _monitor.OpenInfo().Send("G-OP-{0}-{1}", NumMonitor, i);
                }
                else
                {
                    _monitor.CloseGroup();
                }
            }
            _monitor.Info().Send("ThreadContext{0}End", NumMonitor);
        }
        /// <summary>
        /// Allows a direct login if and only if:
        ///     * Scheme is "Guest"
        ///     * The payload is valid
        ///     * The payload's token is neither null or whitespaces
        /// </summary>
        /// <param name="ctx">The current context.</param>
        /// <param name="monitor">The monitor to use.</param>
        /// <param name="scheme">The authentication scheme.</param>
        /// <param name="payload">The login payload.</param>
        /// <returns></returns>
        public Task <bool> AllowAsync(HttpContext ctx, IActivityMonitor monitor, string scheme, object payload)
        {
            using (monitor.OpenInfo($"{GetType()}.AllowAsync challenge"))
            {
                if (scheme != "Guest")
                {
                    monitor.Trace("Invalid scheme");
                    return(Task.FromResult(false));
                }
                monitor.Trace("Valid scheme");

                IGuestActorInfo info;
                try
                {
                    info = _infoFactory.ExtractPayload(payload);
                }
                catch (Exception exception)
                {
                    monitor.Error("Error while extracting payload.", exception);
                    return(Task.FromResult(false));
                }

                Debug.Assert(info != null);

                if (string.IsNullOrWhiteSpace(info.Token))
                {
                    monitor.Trace("Invalid payload");
                    return(Task.FromResult(false));
                }
                monitor.Trace("Valid payload");

                monitor.Info("DirectLogin allowed.");
                return(Task.FromResult(true));
            }
        }
Пример #11
0
 public void Initialize(IActivityMonitor m)
 {
     using (m.OpenInfo().Send("{0} opens file {1}.", _name, _fileName))
     {
         _file = File.OpenOrCreate(_fileName);
     }
 }
Пример #12
0
 void DemoOpenGroupBetter(IActivityMonitor m)
 {
     using (m.OpenInfo().Send("Doing things..."))
     {
         // ...
     }
 }
Пример #13
0
        /// <summary>
        /// Dumps the <see cref="Solutions"/> order by their index along with optional details.
        /// </summary>
        /// <param name="m">The monitor to use.</param>
        /// <param name="current">The current solution (a star will precede its name).</param>
        /// <param name="solutionLineDetail">Optional details to be appended on the information, header, line.</param>
        /// <param name="solutionDetail">
        /// Optional detailed log generator.
        /// When not null, a group is opened by solution and this is called.
        /// </param>
        public void LogSolutions(
            IActivityMonitor m,
            DependentSolution current = null,
            Func <DependentSolution, string> solutionLineDetail         = null,
            Action <IActivityMonitor, DependentSolution> solutionDetail = null)
        {
            int rank = -1;

            foreach (var s in Solutions)
            {
                if (rank != s.Rank)
                {
                    rank = s.Rank;
                    m.Info($" -- Rank {rank}");
                }
                if (solutionDetail != null)
                {
                    using (m.OpenInfo($"{(s == current ? '*' : ' ')}   {s.Index} - {s} {solutionLineDetail?.Invoke( s )}"))
                    {
                        solutionDetail(m, s);
                    }
                }
                else
                {
                    m.Info($"{(s == current ? '*' : ' ')}   {s.Index} - {s} {solutionLineDetail?.Invoke( s )}");
                }
            }
        }
        static StObjMapInfo?LockedGetMapInfo(Assembly a, [AllowNull] ref IActivityMonitor monitor)
        {
            if (_alreadyHandled.TryGetValue(a, out var info))
            {
                return(info);
            }
            LockedEnsureMonitor(ref monitor);
            var attr = a.GetCustomAttributesData().FirstOrDefault(m => m.AttributeType.Name == "SignatureAttribute" && m.AttributeType.Namespace == "CK.StObj");

            if (attr != null)
            {
                using (monitor.OpenInfo($"Analyzing '{a.FullName}' assembly."))
                {
                    info = StObjMapInfo.Create(monitor, a, attr);
                    if (info != null)
                    {
                        var sha1S = info.GeneratedSignature.ToString();
                        if (_alreadyHandled.TryGetValue(sha1S, out var exists))
                        {
                            Debug.Assert(exists != null);
                            monitor.Info($"StObjMap found with the same signature as an already existing one. Keeping the previous one.");
                            info = exists;
                        }
                        else
                        {
                            _alreadyHandled.Add(sha1S, info);
                            _availableMaps.Add(info);
                        }
                    }
                }
                _alreadyHandled.Add(a, info);
            }
            return(info);
        }
Пример #15
0
        /// <summary>
        /// Pushes a version lightweight tag to the 'origin' remote.
        /// </summary>
        /// <param name="m">The monitor to use.</param>
        /// <param name="v">The version to push.</param>
        /// <returns>True on success, false on error.</returns>
        public bool PushVersionTag(IActivityMonitor m, SVersion v)
        {
            var sv = 'v' + v.ToString();

            using (m.OpenInfo($"Pushing tag {sv} to remote for {SubPath}."))
            {
                try
                {
                    Remote remote  = Git.Network.Remotes["origin"];
                    var    options = new PushOptions()
                    {
                        CredentialsProvider = (url, user, cred) => ProtoGitFolder.PATCredentialsHandler(m)
                    };

                    var exists = Git.Tags[sv];
                    if (exists == null)
                    {
                        m.Error($"Version Tag {sv} does not exist in {SubPath}.");
                        return(false);
                    }
                    Git.Network.Push(remote, exists.CanonicalName, options);
                    return(true);
                }
                catch (Exception ex)
                {
                    m.Error($"PushVersionTags failed ({sv} on {SubPath}).", ex);
                    return(false);
                }
            }
        }
        CSCodeGenerationResult GeneratePocoSupport(IActivityMonitor monitor, ICSCodeGenerationContext c, IPocoSupportResult pocoSupport, JsonSerializationCodeGen jsonCodeGen)
        {
            using var g = monitor.OpenInfo($"Generating C# Json serialization code.");

            bool success = true;

            // Generates the factory and the Poco class code.
            foreach (var root in pocoSupport.Roots)
            {
                var factory = c.Assembly.FindOrCreateAutoImplementedClass(monitor, root.PocoFactoryClass);
                foreach (var i in root.Interfaces)
                {
                    var interfaceName = i.PocoInterface.ToCSharpName();
                    var readerName    = "PocoJsonSerializer.IFactoryReader<" + interfaceName + ">";

                    factory.Definition.BaseTypes.Add(new ExtendedTypeName(readerName));
                    factory.Append(interfaceName).Append(' ').Append(readerName).Append(".Read( ref System.Text.Json.Utf8JsonReader r, PocoJsonSerializerOptions options )").NewLine()
                    .Append(" => r.TokenType == System.Text.Json.JsonTokenType.Null ? null : new ")
                    .Append(root.PocoClass.Name).Append("( ref r, options );").NewLine();
                }
                factory.Append("public IPoco ReadTyped( ref System.Text.Json.Utf8JsonReader r, PocoJsonSerializerOptions options ) => new ").Append(root.PocoClass.Name).Append("( ref r, options );").NewLine();

                var pocoClass = c.Assembly.FindOrCreateAutoImplementedClass(monitor, root.PocoClass);

                // Generates the Poco class Read and Write methods.
                // UnionTypes on properties are registered.
                success &= ExtendPocoClass(monitor, root, jsonCodeGen, pocoClass);
            }
            return(success
                    ? new CSCodeGenerationResult(nameof(FinalizeJsonSupport))
                    : CSCodeGenerationResult.Failed);
        }
Пример #17
0
        /// <summary>
        /// Initializes the Git folders: this instanciates the <see cref="GitFolder"/> from the
        /// <see cref="XGitFolder.ProtoGitFolder"/>.
        /// </summary>
        /// <param name="monitor">The monitor to use.</param>
        /// <returns>The world  on success, null on error.</returns>
        World IXTypedObjectProvider <World> .GetObject(IActivityMonitor m)
        {
            var proto = Parent.Descendants <XGitFolder>().Select(g => g.ProtoGitFolder).ToList();
            List <GitFolder> gitFolders = new List <GitFolder>();

            using (m.OpenInfo($"Initializing {proto.Count} Git folders."))
            {
                try
                {
                    foreach (var p in proto)
                    {
                        var g = _fileSystem.EnsureGitFolder(m, p);
                        if (g != null)
                        {
                            gitFolders.Add(g);
                        }
                        else
                        {
                            m.Error($"GitFolder creation failed for {p.FolderPath}.");
                            return(null);
                        }
                    }
                    DumpGitFolders(m, gitFolders);
                    return(_world);
                }
                catch (Exception ex)
                {
                    m.Error(ex);
                    return(null);
                }
            }
        }
 void DemoOpenGroupBetter( IActivityMonitor m )
 {
     using( m.OpenInfo().Send( "Doing things..." ) )
     {
         // ...
     }
 }
Пример #19
0
        /// <summary>
        /// Copy a text content to a <paramref name="destination"/> path in this
        /// file system.
        /// The destination must not be an existing folder and must be physically accessible
        /// (<see cref="IFileInfo.PhysicalPath"/> must not be null): if inside a <see cref="GitFolder"/>, it must
        /// be a in the current head (ie. corresponds to a file in the current working directory).
        /// </summary>
        /// <param name="m">The activity monitor.</param>
        /// <param name="content">The content text.</param>
        /// <param name="destination">The target path in this file system.</param>
        /// <returns>True on success, false on error.</returns>
        public bool CopyTo(IActivityMonitor m, string content, NormalizedPath destination, Encoding encoding = null)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }
            var fDest = GetWritableDestination(m, ref destination);

            if (fDest == null)
            {
                return(false);
            }
            using (m.OpenInfo($"{(fDest.Exists ? "Replacing" : "Creating")} {destination}."))
            {
                try
                {
                    if (encoding == null)
                    {
                        File.WriteAllText(fDest.PhysicalPath, content);
                    }
                    else
                    {
                        File.WriteAllText(fDest.PhysicalPath, content, encoding);
                    }
                    return(true);
                }
                catch (Exception ex)
                {
                    m.Error(ex);
                    return(false);
                }
            }
        }
Пример #20
0
        /// <summary>
        /// Copy a content to a <paramref name="destination"/> path in this
        /// file system.
        /// The destination must not be an existing folder and must be physically accessible
        /// (<see cref="IFileInfo.PhysicalPath"/> must not be null): if inside a <see cref="GitFolder"/>, it must
        /// be a in the current head (ie. corresponds to a file in the current working directory).
        /// </summary>
        /// <param name="m">The activity monitor.</param>
        /// <param name="content">The content source.</param>
        /// <param name="destination">The target path in this file system.</param>
        /// <returns>True on success, false on error.</returns>
        public bool CopyTo(IActivityMonitor m, Stream content, NormalizedPath destination)
        {
            IFileInfo fDest = GetWritableDestination(m, ref destination);

            if (fDest == null)
            {
                return(false);
            }
            using (m.OpenInfo($"{(fDest.Exists ? "Replacing" : "Creating")} {destination}."))
            {
                try
                {
                    using (var d = new FileStream(fDest.PhysicalPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                    {
                        content.CopyTo(d);
                    }
                    return(true);
                }
                catch (Exception ex)
                {
                    m.Fatal(ex);
                    return(false);
                }
            }
        }
Пример #21
0
 public bool FetchBranches(IActivityMonitor m, bool originOnly = true)
 {
     using (m.OpenInfo($"Fetching {(originOnly ? "origin" : "all remotes")} in repository '{SubPath}'."))
     {
         try
         {
             foreach (Remote remote in Git.Network.Remotes.Where(r => !originOnly || r.Name == "origin"))
             {
                 m.Info($"Fetching remote '{remote.Name}'.");
                 IEnumerable <string> refSpecs = remote.FetchRefSpecs.Select(x => x.Specification).ToArray();
                 Commands.Fetch(Git, remote.Name, refSpecs, new FetchOptions()
                 {
                     CredentialsProvider = (url, user, cred) => PATCredentialsHandler(m),
                     TagFetchMode        = TagFetchMode.All
                 }, $"Fetching remote '{remote.Name}'.");
             }
             return(true);
         }
         catch (Exception ex)
         {
             using (m.OpenFatal("This error need manual fix : "))
             {
                 m.Fatal(ex);
             }
             return(false);
         }
     }
 }
Пример #22
0
        BuildState RunBuild(IActivityMonitor m)
        {
            BuildState finalState = BuildState.Succeed;

            foreach (var(s, d) in DependentSolutionContext.Solutions)
            {
                DependentSolutionContext.DependencyContext.LogSolutions(m, s);
                IReadOnlyCollection <UpdatePackageInfo> buildProjectsUpgrade = GetBuildProjectUpgrades(s);
                using (m.OpenInfo($"Running {s} build."))
                {
                    // _targetVersions[i] is null if build must not be done (this is for ReleaseBuilder only).
                    // We use the null version also for DevelopBuilder:
                    var sVersion = finalState == BuildState.MustRetry ? null : _targetVersions[s.Index];
                    finalState = Build(m, s, d, _upgrades[s.Index], sVersion, buildProjectsUpgrade);
                    ZeroBuilder.RegisterSHAlias(m);
                    // For DevelopBuilder that returned Retry, we continue to apply the
                    // current change on subsequent solutions to minimize the number of actual builds.
                    if (finalState == BuildState.Failed)
                    {
                        break;
                    }
                }
            }
            return(finalState);
        }
Пример #23
0
        bool RunPrepareBuild(IActivityMonitor m)
        {
            // Required for DevelopBuilder retry.
            _packagesVersion.Clear();
            var solutionAndDrivers = DependentSolutionContext.Solutions;

            for (int i = 0; i < solutionAndDrivers.Count; ++i)
            {
                var s        = solutionAndDrivers[i];
                var upgrades = s.Solution.ImportedLocalPackages
                               .Select(p => new UpdatePackageInfo(
                                           p.Project,
                                           p.Package.Artifact.Type,
                                           p.Package.Artifact.Name,
                                           _packagesVersion[p.Package.Artifact]))
                               .ToList();
                _upgrades[i] = upgrades;
                using (m.OpenInfo($"Preparing {s} build."))
                {
                    var pr = PrepareBuild(m, s.Solution, s.Driver, upgrades);
                    ZeroBuilder.RegisterSHAlias(m);
                    if (pr.Version == null)
                    {
                        return(false);
                    }
                    m.CloseGroup($"Target version: {pr.Version}{(pr.MustBuild ? "" :" (no build required)")}");
                    _targetVersions[i] = pr.MustBuild ? pr.Version : null;
                    _packagesVersion.AddRange(s.Solution.Solution.GeneratedArtifacts.Select(p => new KeyValuePair <Artifact, SVersion>(p.Artifact, pr.Version)));
                }
            }
            return(true);
        }
Пример #24
0
 /// <summary>
 /// Opens the key vault.
 /// </summary>
 /// <param name="m">The monitor to use.</param>
 /// <param name="passPhrase">The key vault pass phrase.</param>
 /// <returns>True on success.</returns>
 public bool OpenKeyVault(IActivityMonitor m, string passPhrase)
 {
     if (!CheckPassPhraseConstraints(m, passPhrase))
     {
         return(false);
     }
     if (_passPhrase != null)
     {
         m.Info($"Key Vault is already opened.");
         return(true);
     }
     if (KeyVaultFileExists)
     {
         try
         {
             var keys = KeyVault.DecryptValues(File.ReadAllText(KeyVaultPath), passPhrase);
             m.OpenInfo($"Opening existing Key Vault with keys: {keys.Keys.Concatenate()}.");
             _store.ImportSecretKeys(m, keys);
             _passPhrase = passPhrase;
             _vaultContent.Clear();
             _vaultContent.AddRange(keys);
         }
         catch (Exception ex)
         {
             m.Error("Unable to open the key vault.", ex);
             return(false);
         }
     }
     else
     {
         _passPhrase = passPhrase;
         m.OpenInfo($"New Key Vault opened.");
     }
     if (_store.Infos.Any(s => !s.IsSecretAvailable))
     {
         using (m.OpenWarn($"Missing secrets:"))
         {
             foreach (var s in _store.Infos.Where(s => !s.IsSecretAvailable))
             {
                 m.Warn(s.ToString());
             }
         }
     }
     m.CloseGroup();
     return(true);
 }
 void DemoOpenGroupThisWorksFine( IActivityMonitor m )
 {
     using( m.OpenInfo().Send( "Doing things..." ) )
     {
         // ...
         m.CloseGroup( "Success." );
     }
 }
Пример #26
0
 protected void OpenPumps(IActivityMonitor?m, T newState)
 {
     using (m?.OpenInfo("Opening pumps."))
     {
         Open();
         _state = newState;
     }
 }
Пример #27
0
 void DemoOpenGroupThisWorksFine(IActivityMonitor m)
 {
     using (m.OpenInfo().Send("Doing things..."))
     {
         // ...
         m.CloseGroup("Success.");
     }
 }
 void FinalizeJsonSupport(IActivityMonitor monitor, JsonSerializationCodeGen jsonCodeGen)
 {
     using var g = monitor.OpenInfo($"Finalizing Json serialization C# code.");
     if (jsonCodeGen.FinalizeCodeGeneration(monitor))
     {
         foreach (var a in _finalReadWrite)
         {
             a();
         }
     }
 }
Пример #29
0
 /// <summary>
 /// Reads the current Sha and updates the cache with them.
 /// This must be called only when file changes are, by design, not changing anything to
 /// the build projects' executable.
 /// </summary>
 /// <param name="m">The monitor to use.</param>
 public void RegisterSHAlias(IActivityMonitor m)
 {
     using (m.OpenInfo("Registering Sha signatures aliases."))
     {
         foreach (var p in ZeroBuildProjects)
         {
             _currentShas[p.Index] = _context.FindDriver(p.Project).GitRepository.Head.GetSha(p.Project.SolutionRelativeFolderPath);
             AddCurrentShaToCache(m, p);
         }
         SaveShaCache(m);
     }
 }
 void DemoOpenGroupWithDynamicConclusion( IActivityMonitor m )
 {
     int nbProcessed = 0;
     using( m.OpenInfo().Send( "Doing things..." )
                         .ConcludeWith( () => String.Format( "{0} files.", nbProcessed ) ) )
     {
         // ...
         nbProcessed += 21;
         m.CloseGroup( "Success." );
         // The user Group conclusion is: "Success. - 21 files." (the two conclusions are concatenated).
     }
 }
        public async Task RevokeAllKeys(IActivityMonitor monitor)
        {
            var store = LocalParty?.KeyStore;

            if (store != null)
            {
                using (monitor.OpenInfo($"Revoking all keys of {ToString()}."))
                {
                    await store.DropAllKeyAsync(monitor, PartyName);
                }
            }
        }
Пример #32
0
        void DemoOpenGroupWithDynamicConclusion(IActivityMonitor m)
        {
            int nbProcessed = 0;

            using (m.OpenInfo().Send("Doing things...")
                   .ConcludeWith(() => String.Format("{0} files.", nbProcessed)))
            {
                // ...
                nbProcessed += 21;
                m.CloseGroup("Success.");
                // The user Group conclusion is: "Success. - 21 files." (the two conclusions are concatenated).
            }
        }
Пример #33
0
 void StObjInitialize(IActivityMonitor m, IContextualStObjMap map)
 {
     using (m.OpenInfo($"Initializing CK.DB.Auth.Package : IAuthenticationDatabaseService"))
     {
         _allProviders = map.Implementations.OfType <IGenericAuthenticationProvider>().ToDictionary(p => p.ProviderName, StringComparer.OrdinalIgnoreCase);
         if (BasicProvider != null)
         {
             _allProviders.Add(BasicToGenericProviderAdapter.Name, new BasicToGenericProviderAdapter(BasicProvider));
         }
         _allProvidersValues = new CKReadOnlyCollectionOnICollection <IGenericAuthenticationProvider>(_allProviders.Values);
         m.CloseGroup($"{_allProviders.Count} providers: " + _allProviders.Keys.Concatenate());
     }
 }
 bool DoSomething( IActivityMonitor m, FileInfo file )
 {
     using( m.OpenInfo().Send( "Do something important on file '{0}'.", file.Name ) )
     {
         if( !file.Exists )
         {
             m.Warn().Send( "File does not exist." );
         }
         else
         {
             m.Trace().Send( "File last modified at {1:T}. {0} Kb to process.", file.Length, file.LastWriteTimeUtc );
             try
             {
                 // ... Process file ...
             }
             catch( Exception ex )
             {
                 m.Error().Send( ex, "While processing." );
                 return false;
             }
         }
         m.SetTopic( "Changing my mind. Keeping it as-is." );
         return true;
     }
 }
 void DemoOpenGroupFarFromPerfect( IActivityMonitor m )
 {
     m.OpenInfo().Send( "Doing things..." );
     // ...
     m.CloseGroup( "Success." );
 }