/// <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));
            }
        }
Esempio n. 2
0
            public bool CheckSecret(IActivityMonitor m, bool throwOnMissing)
            {
                if (_checkedSecret.HasValue)
                {
                    return(_checkedSecret.Value);
                }
                // If we are bound to a repository that has a secret, its configuration, if available, is the one to use!
                INuGetRepository repo = _baseFeed as INuGetRepository;
                bool             isBoundToProtectedRepository = repo != null && !String.IsNullOrEmpty(repo.SecretKeyName);

                if (isBoundToProtectedRepository)
                {
                    var fromRepo = !String.IsNullOrEmpty(repo.ResolveSecret(m, false));
                    if (fromRepo)
                    {
                        m.Trace($"Feed '{Name}' uses secret from repository '{repo.Name}'.");
                        _checkedSecret = true;
                        return(true);
                    }
                }
                if (Credentials != null)
                {
                    string secret;
                    if (Credentials.IsSecretKeyName == true)
                    {
                        secret         = _baseFeed.Client.SecretKeyStore.GetSecretKey(m, Credentials.PasswordOrSecretKeyName, throwOnMissing);
                        _checkedSecret = secret != null;
                        if (_checkedSecret == true)
                        {
                            m.Trace($"Feed '{Name}' uses its configured credential '{Credentials.PasswordOrSecretKeyName}'.");
                        }
                    }
                    else
                    {
                        secret         = Credentials.PasswordOrSecretKeyName;
                        _checkedSecret = true;
                        m.Trace($"Feed '{Name}' uses its configured password.");
                    }
                    if (_checkedSecret == true)
                    {
                        NuGetClient.EnsureVSSFeedEndPointCredentials(m, Url, secret);
                    }
                    else
                    {
                        m.Error($"Feed '{Name}': unable to resolve the credentials.");
                    }
                }
                else
                {
                    // There is no credential: let it be and hope it works.
                    m.Trace($"Feed '{Name}' has no available secret. It must be a public feed.");
                }
                return(_checkedSecret ?? false);
            }
Esempio n. 3
0
 public static void Trace(this IYodiiEngineStaticOnlyResult @this, IActivityMonitor m)
 {
     if (@this.Success)
     {
         m.Trace().Send("Success!");
     }
     else
     {
         m.Trace().Send("Failed!");
         @this.StaticFailureResult.Trace(m);
     }
 }
Esempio n. 4
0
        public override bool Accept(IActivityMonitor m, ModifiedDiff modifiedDiff)
        {
            var matchingPath = DiffRoot.Paths.FirstOrDefault(path => modifiedDiff.OldPath.StartsWith(path) || modifiedDiff.NewPath.StartsWith(path));

            if (matchingPath != null)
            {
                m.Trace($"Modified file ('{modifiedDiff.OldPath}'=>'{modifiedDiff.NewPath}') matched with one of the DiffRoot '{DiffRoot.Name}' path: {matchingPath}");
                ModifiedDiffs.Add(modifiedDiff);
                return(true);
            }
            m.Trace($"Modified file ('{modifiedDiff.OldPath}'=>'{modifiedDiff.NewPath}') did not match with any of the DiffRoot '{DiffRoot.Name}' paths.");
            return(false);
        }
Esempio n. 5
0
        public override bool Accept(IActivityMonitor m, DeletedDiff deletedDiff)
        {
            var matchingPath = DiffRoot.Paths.FirstOrDefault(path => deletedDiff.Path.StartsWith(path));

            if (matchingPath != null)
            {
                m.Trace($"Deleted file ({deletedDiff.Path}) matched with one of the DiffRoot '{DiffRoot.Name}' path: {matchingPath}");
                DeletedDiffs.Add(deletedDiff);
                return(true);
            }
            m.Trace($"Deleted file ({deletedDiff.Path}) did not match with any of the DiffRoot '{DiffRoot.Name}' paths.");
            return(false);
        }
Esempio n. 6
0
        public bool SetWorldMapping(IActivityMonitor m, string worldFullName, NormalizedPath mappedPath)
        {
            var worlds = ReadWorlds(m);

            if (worlds == null)
            {
                return(false);
            }
            var w = worlds.FirstOrDefault(x => x.FullName.Equals(worldFullName, StringComparison.OrdinalIgnoreCase));

            if (w == null)
            {
                m.Error($"World '{worldFullName}' not found.");
                return(false);
            }
            if (w.Root == mappedPath)
            {
                m.Trace($"World '{w.FullName}' is already mapped to '{w.Root}'.");
                return(true);
            }
            if (!mappedPath.IsRooted)
            {
                m.Error($"Invalid '{mappedPath}'. It must be rooted.");
                return(false);
            }
            if (!WorldLocalMapping.SetMap(m, w.FullName, mappedPath))
            {
                return(true);
            }
            m.Info($"World '{w.FullName}' is now mapped to '{mappedPath}'.");
            ReadWorlds(m, false);
            return(true);
        }
Esempio n. 7
0
            public void Add(string name, List <XNode> e, bool replace, bool @override)
            {
                Monitor.Trace($"Registering {name} reusable for {Element.ToStringPath()}.");
                if (_map == null)
                {
                    _map = new Dictionary <string, List <XNode> >();
                }
                bool existsAbove = Parent?.Find(name, clone: false) != null;
                bool existsHere  = _map.ContainsKey(name);

                if (replace && !existsHere)
                {
                    Monitor.Warn($"{Element.ToStringPath()}: Reusable '{name}' does not replace any previously registered item. Replace=\"True\" attribute should be removed.");
                }
                if (!replace && existsHere)
                {
                    Monitor.Error($"{Element.ToStringPath()}: Reusable '{name}' is already registered at this level. Use Replace=\"True\" attribute if replacement is intentional.");
                }
                if (@override && !existsAbove)
                {
                    Monitor.Warn($"{Element.ToStringPath()}: Reusable '{name}' does not override any registered item above. Override=\"True\" attribute should be removed.");
                }
                if (!@override && existsAbove)
                {
                    Monitor.Error($"{Element.ToStringPath()}: Reusable '{name}' is already registered above. Use Override=\"True\" attribute if redefinition is intentional.");
                }
                _map[name] = e;
            }
 static void EvalKnownPaths(IActivityMonitor monitor, string binPathName, string aspectName, XElement element, NormalizedPath basePath, NormalizedPath outputPath, NormalizedPath projectPath)
 {
     foreach (var e in element.Elements())
     {
         if (!e.HasElements)
         {
             Debug.Assert(Math.Min(Math.Min("{BasePath}".Length, "{OutputPath}".Length), "{ProjectPath}".Length) == 10);
             string?v = e.Value;
             if (v != null && v.Length >= 10)
             {
                 var vS = ReplacePattern(basePath, "{BasePath}", v);
                 vS = ReplacePattern(outputPath, "{OutputPath}", vS);
                 vS = ReplacePattern(projectPath, "{ProjectPath}", vS);
                 if (v != vS)
                 {
                     monitor.Trace($"BinPathConfiguration '{binPathName}', aspect '{aspectName}': Configuration value '{v}' has been evaluated to '{vS}'.");
                     e.Value = vS;
                 }
             }
         }
         else
         {
             EvalKnownPaths(monitor, binPathName, aspectName, e, basePath, outputPath, projectPath);
         }
     }
Esempio n. 9
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);
     }
 }
Esempio n. 10
0
        IFileInfo GetWritableDestination(IActivityMonitor m, ref NormalizedPath destination)
        {
            destination = destination.ResolveDots();
            if (destination.IsEmptyPath)
            {
                throw new ArgumentNullException(nameof(destination));
            }
            var fDest = GetFileInfo(destination);

            if (fDest.Exists && fDest.IsDirectory)
            {
                m.Error($"Cannot replace a folder '{destination}' by a file content.");
                fDest = null;
            }
            if (fDest.PhysicalPath == null)
            {
                m.Error($"Destination file '{destination}' is not writable.");
                fDest = null;
            }
            if (fDest != null)
            {
                string dir = Path.GetDirectoryName(fDest.PhysicalPath);
                if (!Directory.Exists(dir))
                {
                    m.Trace($"Creating directory '{dir}'.");
                    Directory.CreateDirectory(dir);
                }
            }
            return(fDest);
        }
Esempio n. 11
0
        /// <summary>
        /// Sets the TargetFramework(s) element in the project file.
        /// The dependencies are analysed and new <see cref="Dependencies.UselessDependencies"/> may appear.
        /// </summary>
        /// <param name="m">The activity monitor to use.</param>
        /// <param name="frameworks">The framework(s) to set.</param>
        /// <returns>True if the change has been made. False if the frameworks are the same as the current one.</returns>
        public bool SetTargetFrameworks(IActivityMonitor m, CKTrait frameworks)
        {
            if (frameworks?.IsEmpty ?? true)
            {
                throw new ArgumentException("Must not be null or empty.", nameof(frameworks));
            }
            if (frameworks.Context != Savors)
            {
                throw new ArgumentException("Must be from MSProject.Traits context.", nameof(frameworks));
            }
            if (_file == null)
            {
                throw new InvalidOperationException("Invalid project file.");
            }
            if (TargetFrameworks == frameworks)
            {
                return(false);
            }
            XElement f = _file.Document.Root
                         .Elements("PropertyGroup")
                         .Elements()
                         .Where(x => x.Name.LocalName == "TargetFramework" || x.Name.LocalName == "TargetFrameworks")
                         .SingleOrDefault();

            f.ReplaceWith(new XElement(frameworks.IsAtomic ? "TargetFramework" : "TargetFrameworks", frameworks.ToString()));
            m.Trace($"Replacing TargetFrameworks='{TargetFrameworks}' with '{frameworks}' in {ToString()}.");
            TargetFrameworks = frameworks;
            OnChange(m);
            return(true);
        }
Esempio n. 12
0
        /// <summary>
        /// Removes a set of dependencies.
        /// </summary>
        /// <param name="toRemove">Set of dependenies to remove.</param>
        /// <returns>The number of changes.</returns>
        public int RemoveDependencies(IActivityMonitor m, IReadOnlyList <DeclaredPackageDependency> toRemove)
        {
            if (!_dependencies.IsInitialized)
            {
                throw new InvalidOperationException("Invalid Project.");
            }
            if (toRemove == null)
            {
                throw new ArgumentException("Empty dependency to remove.", nameof(toRemove));
            }
            if (toRemove.Count == 0)
            {
                return(0);
            }
            var extra = toRemove.FirstOrDefault(r => !_dependencies.Packages.Contains(r));

            if (extra != null)
            {
                throw new ArgumentException($"Dependency not contained: {extra}.", nameof(toRemove));
            }
            int changeCount = toRemove.Count;
            var parents     = toRemove.Select(p => p.OriginElement.Parent).Distinct().ToList();

            changeCount += parents.Count;
            toRemove.Select(r =>
            {
                m.Trace($"Remove in {ToString()}: {r.PackageId}.");
                return(r.OriginElement);
            }).Remove();
            // Removes empty <ItemGroup />.
            parents.Where(p => !p.HasElements).Remove();
            OnChange(m);
            return(changeCount);
        }
Esempio n. 13
0
        /// <summary>
        /// Ensures that a path is a directory, creating it as necessary (if
        /// the path is writable).
        /// </summary>
        /// <param name="m">The monitor to use.</param>
        /// <param name="dir">The target path in this file system.</param>
        /// <returns>True on success, false on error.</returns>
        public bool EnsureDirectory(IActivityMonitor m, NormalizedPath dir)
        {
            dir = dir.ResolveDots();
            if (dir.IsEmptyPath)
            {
                throw new ArgumentNullException(nameof(dir));
            }
            var p = GetFileInfo(dir);

            if (!p.Exists)
            {
                if (p.PhysicalPath == null)
                {
                    m.Error($"Directory path '{dir}' is not writable.");
                    return(false);
                }
                if (!Directory.Exists(p.PhysicalPath))
                {
                    m.Trace($"Creating directory '{p.PhysicalPath}'.");
                    Directory.CreateDirectory(p.PhysicalPath);
                }
            }
            else if (!p.IsDirectory)
            {
                m.Error($"Path '{dir}' is a file. Cannot transform it into a directory.");
                return(false);
            }
            return(true);
        }
Esempio n. 14
0
 void DemoLogs(IActivityMonitor m, FileInfo f, Exception ex)
 {
     m.Trace().Send("Data from '{0}' processed.", f.Name);
     m.Info().Send(ex, "An error occurred while processing '{0}'. Process will be retried later.", f.Name);
     m.Warn().Send("File '{0}' is too big ({1} Kb). It must be less than 50Kb.", f.Name, f.Length / 1024);
     m.Error().Send(ex, "File '{0}' can not be processed.", f.Name);
     m.Fatal().Send(ex, "This will cancel the whole operation.");
 }
 void DemoLogs( IActivityMonitor m, FileInfo f, Exception ex )
 {
     m.Trace().Send( "Data from '{0}' processed.", f.Name );
     m.Info().Send( ex, "An error occurred while processing '{0}'. Process will be retried later.", f.Name );
     m.Warn().Send( "File '{0}' is too big ({1} Kb). It must be less than 50Kb.", f.Name, f.Length / 1024 );
     m.Error().Send( ex, "File '{0}' can not be processed.", f.Name );
     m.Fatal().Send( ex, "This will cancel the whole operation." );
 }
Esempio n. 16
0
        static void CleanupTimedFolders(IActivityMonitor m, IBasicTestHelper basic, string basePath, int maxCurrentLogFolderCount, int maxArchivedLogFolderCount)
        {
            Debug.Assert(basePath.EndsWith(FileUtil.DirectorySeparatorString));
            // Note: The comparer is a reverse comparer. The most RECENT timed folder is the FIRST.
            GetTimedFolders(basePath, out SortedDictionary <DateTime, string> timedFolders, out string archivePath, false);
            if (timedFolders.Count > maxCurrentLogFolderCount)
            {
                int retryCount = 5;
retry:
                try
                {
                    if (archivePath == null)
                    {
                        m.Trace("Creating Archive folder.");
                        Directory.CreateDirectory(archivePath = basePath + "Archive");
                    }
                    foreach (var old in timedFolders.Values.Skip(maxCurrentLogFolderCount))
                    {
                        var fName = Path.GetFileName(old);
                        m.Trace($"Moving '{fName}' folder into Archive folder.");
                        var target = Path.Combine(archivePath, fName);
                        if (Directory.Exists(target))
                        {
                            target += '-' + Guid.NewGuid().ToString();
                        }
                        Directory.Move(old, target);
                    }
                    GetTimedFolders(archivePath, out timedFolders, out _, true);
                    foreach (var tooOld in timedFolders.Values.Skip(maxArchivedLogFolderCount))
                    {
                        basic.CleanupFolder(tooOld, false);
                    }
                }
                catch (Exception ex)
                {
                    if (--retryCount < 0)
                    {
                        m.Error($"Aborting Log's cleanup of timed folders in '{basePath}' after 5 retries.", ex);
                        return;
                    }
                    m.Warn($"Log's cleanup of timed folders in '{basePath}' failed. Retrying.", ex);
                    Thread.Sleep(retryCount * 100);
                    goto retry;
                }
            }
        }
Esempio n. 17
0
            /// <summary>
            /// Ensures that the the Git Repository is opened and updates the <see cref="Worlds"/>.
            /// Returns true on success, false on error.
            /// </summary>
            /// <param name="m">The monitor to use.</param>
            /// <param name="force">True to refresh the <see cref="Worlds"/> even if <see cref="IsOpen"/> is already true.</param>
            /// <returns>Whether this repository has been successfully opened.</returns>
            internal bool Refresh(IActivityMonitor m, bool force = true)
            {
                bool isOpened = false;

                if (!IsOpen)
                {
                    _git = GitRepository.Create(m, this, Root, Root.LastPart, false, BranchName, checkOutBranchName: true);
                    if (_git == null)
                    {
                        return(false);
                    }
                    isOpened = true;
                }
                if (force || isOpened)
                {
                    if (_git.Pull(m, MergeFileFavor.Theirs).ReloadNeeded || isOpened)
                    {
                        var worldNames = Directory.GetFiles(Root, "*.World.xml")
                                         .Select(p => LocalWorldName.TryParse(p, _store.WorldLocalMapping))
                                         .Where(w => w != null)
                                         .ToDictionary(w => w.FullName);

                        var invalidParallels = worldNames.Values.Where(p => p.ParallelName != null && !worldNames.ContainsKey(p.Name)).ToList();
                        foreach (var orphan in invalidParallels)
                        {
                            m.Warn($"Invalid Parallel World '{orphan.FullName}': unable to find the default stack definition '{orphan.Name}' in the repository. It is ignored.");
                            worldNames.Remove(orphan.FullName);
                        }
                        foreach (var exists in _worlds)
                        {
                            if (!worldNames.Remove(exists.WorldName.FullName))
                            {
                                if (exists.WorldName.HasDefinitionFile)
                                {
                                    m.Warn($"Unable to find World definition file for '{exists.WorldName}'. File '{exists.WorldName.XmlDescriptionFilePath}' not found.");
                                    exists.WorldName.HasDefinitionFile = false;
                                }
                            }
                            else
                            {
                                if (!exists.WorldName.HasDefinitionFile)
                                {
                                    m.Trace($"Found World definition file for '{exists.WorldName}'.");
                                    exists.WorldName.HasDefinitionFile = true;
                                }
                            }
                        }
                        foreach (var newWorld in worldNames.Values)
                        {
                            m.Info($"Found a new World definition: creating '{newWorld.FullName}' entry.");
                            newWorld.HasDefinitionFile = true;
                            _worlds.Add(new WorldInfo(this, newWorld));
                        }
                    }
                }
                return(IsOpen);
            }
        /// <summary>
        /// Low level helper that initializes a new <see cref="StObjEngineConfiguration"/> and computes the force setup flag
        /// that can be used by other helpers that need to run a setup.
        /// </summary>
        /// <param name="helper">The <see cref="IStObjSetupTestHelper"/> helper.</param>
        /// <returns>The configuration and the flag.</returns>
        static public (StObjEngineConfiguration Configuration, ForceSetupLevel ForceSetup) CreateDefaultConfiguration(IActivityMonitor monitor,
                                                                                                                      IStObjSetupTestHelper helper)
        {
            var stObjConf = new StObjEngineConfiguration
            {
                RevertOrderingNames         = helper.StObjRevertOrderingNames,
                TraceDependencySorterInput  = helper.StObjTraceGraphOrdering,
                TraceDependencySorterOutput = helper.StObjTraceGraphOrdering,
            };
            // BinPath by default is: the first "CKSetup/DefaultBinPaths" if it has been configured
            // otherwise it is the {ClosestSUTProjectFolder}/{PathToBin} (if no ClosestSUTProjectFolder
            // has been found, {ClosestSUTProjectFolder} is the {TestProjectFolder} so {ClosestSUTProjectFolder}/{PathToBin}
            // is... this {BinFolder})
            NormalizedPath binPath;

            if (helper.CKSetup.DefaultBinPaths.Count > 0)
            {
                binPath = helper.CKSetup.DefaultBinPaths[0];
                monitor.Info($"Using first configured 'CKSetup/DefaultBinPaths' = {binPath}");
            }
            else
            {
                binPath = helper.ClosestSUTProjectFolder.Combine(helper.PathToBin);
                monitor.Info($"No 'CKSetup/DefaultBinPaths' configuration. Using ClosestSUTProjectFolder/PathToBin: {binPath}.");
            }

            var b = new BinPathConfiguration
            {
                // The name of the BinPath to use is the current IStObjMapTestHelper.BinPathName.
                Name = helper.BinPathName,
                Path = binPath,
                // Then the OutputPath will copy the generated assembly to this bin folder.
                OutputPath    = helper.BinFolder,
                CompileOption = CompileOption.Compile,
                // ...and the G0.cs to the TestProjectFolder.
                GenerateSourceFiles = helper.StObjGenerateSourceFiles,
                ProjectPath         = helper.TestProjectFolder
            };

            stObjConf.BinPaths.Add(b);

            // Consider by default the CKSetup configuration that be not None,
            // but if it is None, set it to Engine: the engine must run even if
            // all the binaries are unchanged to check the G0.cs and assembly.

            var f = helper.CKSetup.ForceSetup;

            if (f == ForceSetupLevel.None)
            {
                monitor.Trace($"Setting CKSetup ForceSetupLevel to Engine so it can check the required artifacts.");
                f = ForceSetupLevel.Engine;
            }
            return(stObjConf, f);
        }
Esempio n. 19
0
 void AddCurrentShaToCache(IActivityMonitor m, ZeroBuildProjectInfo p)
 {
     if (!_sha1Cache.TryGetValue(p.Project.FullFolderPath, out var shaList))
     {
         _sha1Cache.Add(p.Project.FullFolderPath, shaList = new HashSet <string>());
     }
     if (shaList.Add(_currentShas[p.Index]) && shaList.Count > 1)
     {
         m.Trace($"Added new Shalias for {p.Project.FullFolderPath}.");
     }
 }
Esempio n. 20
0
        /// <summary>
        /// Helper that deletes a local directory with retries.
        /// Throws the exception after 4 unsuccessful retries.
        /// From https://github.com/libgit2/libgit2sharp/blob/f8e2d42ed9051fa5a5348c1a13d006f0cc069bc7/LibGit2Sharp.Tests/TestHelpers/DirectoryHelper.cs#L40
        /// </summary>
        /// <param name="m">The monitor to use.</param>
        /// <param name="directoryPath">The directory path on the local file system to delete.</param>
        /// <returns>True if the Directory was deleted or did not exist, false if it didn't deleted the directory.</returns>
        public static bool RawDeleteLocalDirectory(IActivityMonitor m, string directoryPath)
        {
            // From http://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true/329502#329502

            if (!Directory.Exists(directoryPath))
            {
                m.Trace($"Directory '{directoryPath}' does not exist.");
                return(true);
            }
            NormalizeAttributes(directoryPath);
            return(DeleteDirectory(m, directoryPath, maxAttempts: 5, initialTimeout: 16, timeoutFactor: 2));
        }
Esempio n. 21
0
 void RegisterRegularType(Type t)
 {
     if (!_regularTypeCollector.ContainsKey(t))
     {
         var c = TypeAttributesCache.CreateOnRegularType(_monitor, _serviceProvider, t);
         _regularTypeCollector.Add(t, c);
         if (c != null)
         {
             _monitor.Trace($"At least one bound attribute on '{t}' has been registered.");
             RegisterAssembly(t);
         }
     }
 }
Esempio n. 22
0
 /// <summary>
 /// Logs potential errors. Returns true if no error occured, false on error.
 /// </summary>
 /// <param name="m"></param>
 /// <param name="res"></param>
 /// <returns>True on success, false on error.</returns>
 async Task <bool> LogErrors(IActivityMonitor m, HttpResponseMessage res)
 {
     if (res.StatusCode == HttpStatusCode.Unauthorized)
     {
         using (m.OpenError("Unauthorized Status Code"))
         {
             if (res.Headers.Contains("www-authenticate"))
             {
                 List <string> auth = res.Headers.GetValues("www-authenticate").ToList();
                 if (auth.Contains("ipaddress"))
                 {
                     m.Error("Login is not allowed from your IP address");
                 }
                 else if (auth.Contains("otp"))
                 {
                     m.Error("OTP required for authentication");
                 }
                 else
                 {
                     m.Error("Unable to authenticate, need: " + string.Join(", ", auth));
                 }
             }
             else
             {
                 if ((await res.Content.ReadAsStringAsync()).Contains("one-time pass"))
                 {
                     m.Error("OTP required for authentication.");
                 }
                 else
                 {
                     m.Error("Unknown error.");
                 }
             }
         }
         return(false);
     }
     if (!res.IsSuccessStatusCode)
     {
         using (m.OpenError($"Response status code is not a success code: '{res.ReasonPhrase}'."))
         {
             m.Trace(await res.Content.ReadAsStringAsync());
         }
         return(false);
     }
     else
     {
         m.Debug("Response status code is a success status code.");
     }
     return(true);
 }
Esempio n. 23
0
        /// <summary>
        /// Saves this file into one or more actual paths on the file system.
        /// </summary>
        /// <param name="monitor">The monitor to use.</param>
        /// <param name="outputPaths">Any number of target directories.</param>
        /// <returns>True on success, false is an error occurred (the error has been logged).</returns>
        public void Save(IActivityMonitor monitor, IReadOnlyCollection <NormalizedPath> outputPaths)
        {
            monitor.Trace($"Saving '{Name}'.");
            var imports = Imports.ToString();

            if (imports.Length > 0)
            {
                imports += Environment.NewLine;
            }
            var all = imports + Body.ToString();

            foreach (var p in outputPaths)
            {
                File.WriteAllText(p.AppendPart(Name), all);
            }
        }
        /// <summary>
        /// Tries to set the <see cref="CKTypeKind.IsPocoClass"/> flag for a type (that must be a class).
        /// This fails if the type is already registered as another kind of type.
        /// </summary>
        /// <param name="m">The monitor to use.</param>
        /// <param name="t">The type to configure.</param>
        /// <returns>True on success, false on error.</returns>
        internal bool SetPocoClass(IActivityMonitor m, Type t)
        {
            Debug.Assert(t.IsClass);
            var exist = RawGet(m, t);

            if (exist == CKTypeKind.None)
            {
                m.Trace($"Type '{t}' is now defined as a PocoClass.");
                _cache[t] = CKTypeKind.IsPocoClass;
            }
            else if (exist != CKTypeKind.IsPocoClass)
            {
                m.Error($"Type '{t}' is already registered as a '{ToStringFull( exist )}'. It can not be defined as a PocoClass.");
                return(false);
            }
            return(true);
        }
Esempio n. 25
0
        public void DependentToken_API_use()
        {
            var monitor = new ActivityMonitor();

            monitor.Output.CreateBridgeTo(TestHelper.ConsoleMonitor.Output.BridgeTarget);

            using (monitor.OpenTrace().Send("Create token and dependent monitor."))
            {
                // Creates the token.
                var token = monitor.DependentActivity().CreateToken();
                // Creates a dependent monitor.
                using (var monitorDep = token.CreateDependentMonitor(m => m.Output.CreateBridgeTo(TestHelper.ConsoleMonitor.Output.BridgeTarget)))
                {
                    monitor.Trace().Send("Doing something...");
                    // ...
                }
            }
            using (monitor.OpenTrace().Send("Create token with delayed launch of the dependent activity."))
            {
                // Creates the token.
                var token = monitor.DependentActivity().CreateToken(delayedLaunch: true);
                // Signals the launch of the dependent activity.
                monitor.DependentActivity().Launch(token);
                // Creates a dependent monitor.
                using (var monitorDep = token.CreateDependentMonitor(m => m.Output.CreateBridgeTo(TestHelper.ConsoleMonitor.Output.BridgeTarget)))
                {
                    monitor.Trace().Send("Doing something...");
                    // ...
                }
            }
            using (monitor.OpenTrace().Send("Starting a dependent activity on an existing monitor."))
            {
                // Creates the token.
                var token = monitor.DependentActivity().CreateToken();

                IActivityMonitor wMonitor = monitor;
                using (wMonitor.StartDependentActivity(token))
                {
                    wMonitor.Trace().Send("Doing something...");
                    // ...
                }
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Gets or creates the <see cref="ITypeScope"/> builder from an interface, the direct base type or from
        /// an already stub type that is named with <see cref="GetAutoImplementedTypeName(IDynamicAssembly, Type)"/> (its
        /// name ends with "_CK").
        /// <para>
        /// Public constructors of the <see cref="Type.BaseType"/> if it exists are automatically replicated: protected
        /// constructors are to be called by generated code if needed.
        /// </para>
        /// </summary>
        /// <param name="this">This Dynamic assembly.</param>
        /// <param name="monitor">The monitor to use.</param>
        /// <param name="type">The base or stub type. Can be an interface.</param>
        /// <param name="created">True if the type scope has been created. False if it was already defined.</param>
        /// <returns>Th generated class builder.</returns>
        public static ITypeScope FindOrCreateAutoImplementedClass(this IDynamicAssembly @this, IActivityMonitor monitor, Type type, out bool created)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            Type?  baseType;
            string name = type.Name;

            if (name.EndsWith("_CK", StringComparison.Ordinal))
            {
                baseType = type.BaseType;
            }
            else
            {
                baseType = type;
                name    += "_CK";
            }
            var ns = @this.Code.Global.FindOrCreateNamespace(type.Namespace ?? String.Empty);

            ITypeScope?tB = ns.FindType(name);

            if (created = (tB == null))
            {
                monitor.Trace($"Creating ITypeScope builder for class: '{ns.FullName}.{name}'.");
                tB = ns.CreateType("internal class " + name);
                if (baseType != null)
                {
                    if (baseType != typeof(object))
                    {
                        tB.Definition.BaseTypes.Add(new ExtendedTypeName(baseType.ToCSharpName()));
                        // Only public constructors are replicated: protected constructors are to be called
                        // by generated code.
                        tB.CreatePassThroughConstructors(baseType, ctor => ctor.IsPublic ? "public " : null);
                    }
                }
                else if (type.IsInterface)
                {
                    tB.Definition.BaseTypes.Add(new ExtendedTypeName(type.ToCSharpName()));
                }
            }
            return(tB !);
        }
Esempio n. 27
0
 protected override BuildState Build(IActivityMonitor m, DependentSolution s, ISolutionDriver driver, IReadOnlyList <UpdatePackageInfo> upgrades, SVersion sVersion, IReadOnlyCollection <UpdatePackageInfo> buildProjectsUpgrade)
 {
     if (_commits[s.Index] != driver.GitRepository.Head.CommitSha)
     {
         m.Error($"Commit changed between PrepareBuild call and this Build. Build canceled.");
         return(BuildState.Failed);
     }
     if (!driver.UpdatePackageDependencies(m, buildProjectsUpgrade))
     {
         return(BuildState.Failed);
     }
     if (driver.GitRepository.CanAmendCommit)
     {
         if (!driver.GitRepository.AmendCommit(m))
         {
             return(BuildState.Failed);
         }
     }
     else
     {
         if (!driver.GitRepository.Commit(m, "Required Build commit (for CI): build dependencies changed."))
         {
             return(BuildState.Failed);
         }
         var currentSha = driver.GitRepository.Head.CommitSha;
         if (_commits[s.Index] != currentSha)
         {
             m.Warn("A required commit has been created because build dependencies changed whereas normal ones didn't and commit cannot be amended. Build will be be retried.");
             _commits[s.Index] = currentSha;
             return(BuildState.MustRetry);
         }
     }
     if (sVersion == null)
     {
         m.Trace("Retry mode: skipping actual build.");
         return(BuildState.MustRetry);
     }
     return(driver.Build(m, _withUnitTest, withZeroBuilder: true, withPushToRemote: false)
             ? BuildState.Succeed
             : BuildState.Failed);
 }
Esempio n. 28
0
        public static void ReplayLogs(DirectoryInfo directory, bool recurse, Func <MultiLogReader.Monitor, ActivityMonitor> monitorProvider, IActivityMonitor m = null)
        {
            var reader = new MultiLogReader();

            using (m != null ? m.OpenTrace().Send("Reading files from '{0}' {1}.", directory.FullName, recurse ? "(recursive)" : null) : null)
            {
                var files = reader.Add(directory.EnumerateFiles("*.ckmon", recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).Select(f => f.FullName));
                if (files.Count == 0)
                {
                    if (m != null)
                    {
                        m.Warn().Send("No *.ckmon files found!");
                    }
                }
                else
                {
                    var monitors = reader.GetActivityMap().Monitors;
                    if (m != null)
                    {
                        m.Trace().Send(String.Join(Environment.NewLine, files));
                        m.CloseGroup(String.Format("Found {0} file(s) containing {1} monitor(s).", files.Count, monitors.Count));
                        m.OpenTrace().Send("Extracting entries.");
                    }
                    foreach (var mon in monitors)
                    {
                        var replay = monitorProvider(mon);
                        if (replay == null)
                        {
                            if (m != null)
                            {
                                m.Info().Send("Skipping activity from '{0}'.", mon.MonitorId);
                            }
                        }
                        else
                        {
                            mon.Replay(replay, m);
                        }
                    }
                }
            }
        }
Esempio n. 29
0
 /// <summary>
 /// Checks out a branch: calls <see cref="FetchAll"/> and pulls remote 'origin' branch changes.
 /// There must not be any uncommitted changes on the current head.
 /// The branch must exist locally or on the 'origin' remote.
 /// If the branch exists only in the "origin" remote, a local branch is automatically
 /// created that tracks the remote one.
 /// </summary>
 /// <param name="m">The monitor.</param>
 /// <param name="branchName">The local name of the branch.</param>
 /// <returns>
 /// Success is true on success, false on error (such as merge conflicts) and in case of success,
 /// the result states whether a reload should be required or if nothing changed.
 /// </returns>
 public (bool Success, bool ReloadNeeded) Checkout(IActivityMonitor m, string branchName)
 {
     using (m.OpenInfo($"Checking out branch '{branchName}' in '{SubPath}'."))
     {
         if (!FetchBranches(m))
         {
             return(false, false);
         }
         try
         {
             bool   reloadNeeded = false;
             Branch b            = GetBranch(m, branchName, logErrorMissingLocalAndRemote: true);
             if (b == null)
             {
                 return(false, false);
             }
             if (b.IsCurrentRepositoryHead)
             {
                 m.Trace($"Already on {branchName}.");
             }
             else
             {
                 if (!CheckCleanCommit(m))
                 {
                     return(false, false);
                 }
                 m.Info($"Checking out {branchName} (leaving {CurrentBranchName}).");
                 Commands.Checkout(Git, b);
                 OnNewCurrentBranch(m);
                 reloadNeeded = true;
             }
             (bool Success, bool ReloadNeeded) = DoPull(m, MergeFileFavor.Theirs);
             return(Success, reloadNeeded || ReloadNeeded);
         }
         catch (Exception ex)
         {
             m.Error(ex);
             return(false, true);
         }
     }
 }
Esempio n. 30
0
        protected override async ValueTask <IOutgoingPacket> DoStorePacket(IActivityMonitor?m, IOutgoingPacket packet)
        {
            int packetSize = packet.GetSize(_protocolConfig.ProtocolLevel);

            m?.Trace($"Renting {packetSize} bytes to persist {packet}.");
            IMemoryOwner <byte> memOwner = MemoryPool <byte> .Shared.Rent(packetSize);

            PipeWriter pipe = PipeWriter.Create(memOwner.Memory.AsStream());   // And write their content to this memory.

            using (m?.OpenTrace($"Serializing {packet} into memory..."))
            {
                if (await packet.WriteAsync(_protocolConfig.ProtocolLevel, pipe, default) != WriteResult.Written)
                {
                    throw new InvalidOperationException("Didn't wrote packet correctly.");
                }
            }
            Memory <byte> slicedMem = memOwner.Memory.Slice(0, packetSize);

            base[packet.PacketId].Content.Storage = new StoredPacket(slicedMem, memOwner);
            return(new FromMemoryOutgoingPacket(slicedMem, packet.Qos, packet.PacketId));
        }
Esempio n. 31
0
        static void DumpMonitorOutput(IActivityMonitor monitor)
        {
            Exception exception1;
            Exception exception2;

            try
            {
                throw new InvalidOperationException("Exception!");
            }
            catch (Exception e)
            {
                exception1 = e;
            }

            try
            {
                throw new InvalidOperationException("Inception!", exception1);
            }
            catch (Exception e)
            {
                exception2 = e;
            }

            for (int i = 0; i < 5; i++)
            {
                using (monitor.OpenTrace().Send("Dump output loop {0}", i))
                {
                    for (int j = 0; j < 1000; j++)
                    {
                        monitor.Trace().Send("Trace log! {0}", j);
                        monitor.Info().Send("Info log! {0}", j);
                        monitor.Warn().Send("Warn log! {0}", j);
                        monitor.Error().Send("Error log! {0}", j);
                        monitor.Error().Send("Fatal log! {0}", j);

                        monitor.Error().Send(exception2, "Exception log! {0}", j);
                    }
                }
            }
        }
Esempio n. 32
0
 public static void Trace( this IYodiiEngineResult @this, IActivityMonitor m )
 {
     if( @this.Success )
     {
         m.Trace().Send( "Success!" );
     }
     else
     {
         m.Trace().Send( "Failed!" );
         if( @this.StaticFailureResult != null ) @this.StaticFailureResult.Trace( m );
     }
 }
Esempio n. 33
0
        static void DumpMonitorOutput( IActivityMonitor monitor )
        {
            Exception exception1;
            Exception exception2;

            try
            {
                throw new InvalidOperationException( "Exception!" );
            }
            catch( Exception e )
            {
                exception1 = e;
            }

            try
            {
                throw new InvalidOperationException( "Inception!", exception1 );
            }
            catch( Exception e )
            {
                exception2 = e;
            }

            for( int i = 0; i < 5; i++ )
            {
                using( monitor.OpenTrace().Send( "Dump output loop {0}", i ) )
                {
                    for( int j = 0; j < 1000; j++ )
                    {
                        monitor.Trace().Send( "Trace log! {0}", j );
                        monitor.Info().Send( "Info log! {0}", j );
                        monitor.Warn().Send( "Warn log! {0}", j );
                        monitor.Error().Send( "Error log! {0}", j );
                        monitor.Error().Send( "Fatal log! {0}", j );

                        monitor.Error().Send( exception2, "Exception log! {0}", j );

                    }
                }
            }
        }
Esempio n. 34
0
 public static void Trace( this IStaticFailureResult @this, IActivityMonitor m )
 {
     m.Trace().Send( "Blocking Plugins: {0}", String.Join( ", ", @this.BlockingPlugins.Select( p => p.PluginInfo.PluginFullName + " (" + p.WantedConfigSolvedStatus + "/" + p.DisabledReason + ")" ) ) );
     m.Trace().Send( "Blocking Services: {0}", String.Join( ", ", @this.BlockingServices.Select( s => s.ServiceInfo.ServiceFullName + " (" + s.WantedConfigSolvedStatus + "/" + s.DisabledReason + ")" ) ) );
 }
 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;
     }
 }
Esempio n. 36
0
 public static void ReplayLogs( DirectoryInfo directory, bool recurse, Func<MultiLogReader.Monitor, ActivityMonitor> monitorProvider, IActivityMonitor m = null )
 {
     var reader = new MultiLogReader();
     using( m != null ? m.OpenTrace().Send( "Reading files from '{0}' {1}.", directory.FullName, recurse ? "(recursive)" : null ) : null )
     {
         var files = reader.Add( directory.EnumerateFiles( "*.ckmon", recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly ).Select( f => f.FullName ) );
         if( files.Count == 0 )
         {
             if( m != null ) m.Warn().Send( "No *.ckmon files found!" );
         }
         else
         {
             var monitors = reader.GetActivityMap().Monitors;
             if( m != null )
             {
                 m.Trace().Send( String.Join( Environment.NewLine, files ) );
                 m.CloseGroup( String.Format( "Found {0} file(s) containing {1} monitor(s).", files.Count, monitors.Count ) );
                 m.OpenTrace().Send( "Extracting entries." );
             }
             foreach( var mon in monitors )
             {
                 var replay = monitorProvider( mon );
                 if( replay == null )
                 {
                     if( m != null ) m.Info().Send( "Skipping activity from '{0}'.", mon.MonitorId );
                 }
                 else
                 {
                     mon.Replay( replay, m );
                 }
             }
         }
     }
 }