static int[,] DFS(int[,] board, Possible[,] root)
        {
            int row, col;
            CellIndexWithFewestFlags(root, out row, out col);
            foreach (var number in GetFlags(root[row, col]).ToList())
            {
                var tempBoard = new int[9, 9];
                var tempRoot = new Possible[9, 9];
                Array.Copy(board, tempBoard, 9 * 9);
                Array.Copy(root, tempRoot, 9 * 9);

                root[row, col] &= ~number;
                tempBoard[row, col] = CellValue(number);

                FillOut(tempBoard, tempRoot);

                var correct = false;
                if (HasError(tempRoot, out correct)) continue;
                if (correct) return tempBoard;

                var solution = DFS(tempBoard, tempRoot);
                if (solution != null) return solution;
            }
            return null; // None of the guesses were correct.
        }
 public static Possible[,] InizialzeRoot()
 {
     var root = new Possible[9, 9];
     for (int row = 0; row < 9; row++)
     {
         for (int col = 0; col < 9; col++)
         {
             root[row, col] = All;
         }
     }
     return root;
 }
Пример #3
0
        public async Task TestMissingTypeNameInJson()
        {
            // we will specify a field name that does not exist in TestCacheFactoryConfiguration
            string jsonString = GetJsonStringFromDictionary(
                new Dictionary <string, object>()
            {
                { "StringWithNoDefaultValue", "Value_of_StringWithNoDefaultValue" },
            }, NameOfAssemblyContainingTypeSystemObject, null);

            // this Json string will produce a failure and there will be no results to validate. We will set the result validation to null here
            resultValidationLambda = null;

            // call InitializeCache, there should be no exception
            Possible <ICache, Failure> cache = await InitializeCacheAsync(jsonString);

            // make sure that we do not get a cache
            Assert.False(cache.Succeeded);

            // validate the returned error message
            Assert.Contains("Cache factory Type name is required, but it was not specified", cache.Failure.Describe());
        }
        public async Task MaterializeOverExistentFile()
        {
            const string TargetContent = "This should be the final content";

            string targetPath = GetFullPath("NiftyBits");

            WriteFile("NiftyBits", "Please replace this");

            ContentHash availableHash = await AddContent(TargetContent);

            await LoadContentAndExpectAvailable(ContentCache, availableHash);

            Possible <Unit> maybeMaterialized = await ContentCache.TryMaterializeAsync(
                FileRealizationMode.Copy,
                AbsolutePath.Create(Context.PathTable, targetPath).Expand(Context.PathTable),
                availableHash);

            XAssert.IsTrue(maybeMaterialized.Succeeded);

            XAssert.AreEqual(TargetContent, File.ReadAllText(targetPath));
        }
Пример #5
0
        public async Task TestInvalidJsonField()
        {
            // we will specify a field name that does not exist in TestCacheFactoryConfiguration
            string jsonString = GetJsonStringFromDictionary(new Dictionary <string, object>()
            {
                { "InvalidFieldName", "Value_of_StringWithDefaultValue" },
                { "StringWithNoDefaultValue", "Value_of_StringWithNoDefaultValue" },
            });

            // this Json string will produce a failure and there will be no results to validate. We will set the result validation to null here
            resultValidationLambda = null;

            // call InitializeCache, there should be no exception
            Possible <ICache, Failure> cache = await InitializeCacheAsync(jsonString);

            // make sure that we do not get a cache
            Assert.False(cache.Succeeded);

            // validate the returned error message
            XAssert.AreEqual("BuildXL.Cache.Tests.TestCacheFactory does not support setting 'InvalidFieldName' in Json configuration data", cache.Failure.Describe());
        }
Пример #6
0
        private async Task <Possible <NinjaGraphWithModuleDefinition> > TryComputeBuildGraphAsync()
        {
            Possible <NinjaGraphResult> maybeGraph = await ComputeBuildGraphAsync();

            var result         = maybeGraph.Result;
            var specFileConfig = SpecFile.ChangeExtension(m_context.PathTable, PathAtom.Create(m_context.StringTable, ".ninja.dsc"));   // It needs to be a .dsc for the parsing to work

            var moduleDescriptor = ModuleDescriptor.CreateWithUniqueId(m_resolverSettings.ModuleName, this);
            var moduleDefinition = ModuleDefinition.CreateModuleDefinitionWithImplicitReferences(
                moduleDescriptor,
                ProjectRoot,
                m_resolverSettings.File,
                new List <AbsolutePath>()
            {
                specFileConfig
            },
                allowedModuleDependencies: null, // no module policies
                cyclicalFriendModules: null);    // no whitelist of cycles

            return(new NinjaGraphWithModuleDefinition(result.Graph, moduleDefinition));
        }
Пример #7
0
        /// <summary>
        /// Combined load+open. This assumes that the named content is probably available (e.g. named in a cache entry)
        /// and so soft misses are promoted to failures.
        /// </summary>
        protected virtual async Task <Possible <StreamWithLength> > TryLoadContentAndOpenStreamAsync(ContentHash contentHash)
        {
            if (!EngineEnvironmentSettings.SkipExtraneousPins)
            {
                Possible <ContentAvailabilityBatchResult> maybeAvailable =
                    await ArtifactContentCache.TryLoadAvailableContentAsync(new[] { contentHash }, Context.CancellationToken);

                if (!maybeAvailable.Succeeded)
                {
                    return(maybeAvailable.Failure);
                }

                bool contentIsAvailable = maybeAvailable.Result.AllContentAvailable;
                if (!contentIsAvailable)
                {
                    return(new Failure <string>("Required content is not available in the cache"));
                }
            }

            return(await ArtifactContentCache.TryOpenContentStreamAsync(contentHash));
        }
        /// <inheritdoc />
        public async Task <Possible <Unit, Failure> > TryMaterializeAsync(
            FileRealizationMode fileRealizationModes,
            ExpandedAbsolutePath path,
            ContentHash contentHash,
            CancellationToken cancellationToken)
        {
            // TODO: The cache should be able to do this itself, preferably sharing the same code.
            //       When placing content, we may be replacing output that has been hardlinked elsewhere.
            //       Deleting links requires some care and magic, e.g. if a process has the file mapped.
            //       Correspondingly, IArtifactContentCache prescribes that materialization always produces a 'new' file.

            Possible <Unit, Failure> placeResult = await PerformArtifactCacheOperationAsync(
                () => Helpers.RetryOnFailureAsync(
                    async lastAttempt =>
            {
                return(await TryMaterializeCoreAsync(fileRealizationModes, path, contentHash, cancellationToken));
            }),
                nameof(TryMaterializeAsync));

            return(placeResult);
        }
Пример #9
0
        /// <summary>
        /// Tries to delete file or directory if exists.
        /// </summary>
        /// <param name="fileOrDirectoryPath">Path to file or directory to be deleted, if exists.</param>
        /// <param name="tempDirectoryCleaner">Temporary directory cleaner.</param>
        public static Possible <Unit, Failure> TryDeletePathIfExists(string fileOrDirectoryPath, ITempDirectoryCleaner tempDirectoryCleaner = null)
        {
            if (FileExistsNoFollow(fileOrDirectoryPath))
            {
                Possible <Unit, RecoverableExceptionFailure> possibleDeletion = TryDeleteFile(
                    fileOrDirectoryPath,
                    waitUntilDeletionFinished: true,
                    tempDirectoryCleaner: tempDirectoryCleaner);

                if (!possibleDeletion.Succeeded)
                {
                    return(possibleDeletion.WithGenericFailure());
                }
            }
            else if (DirectoryExistsNoFollow(fileOrDirectoryPath))
            {
                DeleteDirectoryContents(fileOrDirectoryPath, deleteRootDirectory: true, tempDirectoryCleaner: tempDirectoryCleaner);
            }

            return(Unit.Void);
        }
Пример #10
0
        public async Task TestInvalidAssemblyNameInJson()
        {
            // we will specify a field name that does not exist in TestCacheFactoryConfiguration
            string jsonString = GetJsonStringFromDictionary(
                new Dictionary <string, object>()
            {
                { "StringWithNoDefaultValue", "Value_of_StringWithNoDefaultValue" },
            }, "InvalidAssemblyName");

            // this Json string will produce a failure and there will be no results to validate. We will set the result validation to null here
            resultValidationLambda = null;

            // call InitializeCache, there should be no exception
            Possible <ICache, Failure> cache = await InitializeCacheAsync(jsonString);

            // make sure that we do not get a cache
            Assert.False(cache.Succeeded);

            // validate the returned error message
            Assert.StartsWith("InvalidAssemblyName:BuildXL.Cache.Tests.TestCacheFactory cannot be loaded or it is not a valid ICacheFactory type", cache.Failure.Describe());
        }
Пример #11
0
        /// <summary>
        /// Combined operation of opening and tracking a directory (or its absence), enumerating it, and then tracking changes to that enumeration result (its membership).
        /// The membership of the directory will be invalidated if a name is added or removed directly inside the directory (i.e., when <c>FindFirstFile</c>
        /// and <c>FindNextFile</c> would see a different set of names).
        /// </summary>
        public Possible <FileChangeTrackingSet.EnumerationResult> TryEnumerateDirectoryAndTrackMembership(
            string path,
            Action <string, FileAttributes> handleEntry,
            Func <string, FileAttributes, bool> shouldIncludeEntry,
            bool supersedeWithStrongIdentity)
        {
            Contract.Requires(!string.IsNullOrWhiteSpace(path));
            Contract.Requires(handleEntry != null);

            if (IsDisabledOrNullTrackingSet)
            {
                var possibleFingerprintResult = DirectoryMembershipTrackingFingerprinter.ComputeFingerprint(path, handleEntry, shouldIncludeEntry);
                if (!possibleFingerprintResult.Succeeded)
                {
                    return(possibleFingerprintResult.Failure);
                }

                return(new FileChangeTrackingSet.EnumerationResult(
                           possibleFingerprintResult.Result.Fingerprint,
                           possibleFingerprintResult.Result.PathExistence,
                           new Failure <string>("Tracking set is disabled")));
            }

            // Note that we still attempt to enumerate-and-track even if this tracker is already disabled (but was created with a tracking set). We need the result if possible
            // (and if additional tracking succeeds while disabled, there's no harm).
            Possible <FileChangeTrackingSet.EnumerationResult> possibleEnumerationResult = m_changeTrackingSet.TryEnumerateDirectoryAndTrackMembership(
                path,
                handleEntry,
                shouldIncludeEntry,
                fingerprintFilter: null,
                supersedeWithStrongIdentity: supersedeWithStrongIdentity);

            if (!possibleEnumerationResult.Succeeded)
            {
                DisableTracking(path, possibleEnumerationResult.Failure);
                return(possibleEnumerationResult.Failure);
            }

            return(possibleEnumerationResult);
        }
Пример #12
0
        /// <summary>
        /// This elimination works out if there is an intersection between mutually exclusive sets
        /// that contains any values that are in the intersection and not in the outersection of one set.
        /// If this is so, (and both sets must contain that value) then the values can be eliminated from
        /// the other set also. Only need - in addition to above, used when intersecting points > 1.
        /// </summary>
        static public int CreateCompleteIntersectActions(Keys <TKey> group1, Keys <TKey> group2, IPuzzleEngine <TKey> engine)
        {
            int         added            = 0;
            Keys <TKey> keysIntersection = new Keys <TKey>(group1);

            keysIntersection.IntersectWith(group2);
            if (keysIntersection.Count > 1)
            {
                Keys <TKey> keysOuter1 = new Keys <TKey>(group1);
                keysOuter1.ExceptWith(keysIntersection);
                Keys <TKey> keysOuter2 = new Keys <TKey>(group2);
                keysOuter2.ExceptWith(keysIntersection);

                IPossible valuesIntersect = engine.Puzzle.Space.AllValuesAt(keysIntersection);
                IPossible valuesOuter1    = engine.Puzzle.Space.AllValuesAt(keysOuter1);
                IPossible valuesOuter2    = engine.Puzzle.Space.AllValuesAt(keysOuter2);


                Possible filter2 = new Possible(valuesIntersect);
                filter2.FilterOut(valuesOuter1);
                if (filter2.Count > 0)
                {
                    engine.Add(new JobFilter <TKey>("Intersection", keysOuter2, filter2));
                    added++;
                }
                // find each value that is present in the intersection (and not in outer1)
                // and eliminate it from the set2

                // find each value that is present in the intersection (and not in outer)
                // and eliminate it from the set1
                Possible filter1 = new Possible(valuesIntersect);
                filter1.FilterOut(valuesOuter2);
                if (filter1.Count > 0)
                {
                    engine.Add(new JobFilter <TKey>("Intersection", keysOuter1, filter1));
                    added++;
                }
            }
            return(added);
        }
Пример #13
0
        /// <summary>
        /// Gets an instance of <see cref="ICacheConfigData"/> from cache configuration.
        /// </summary>
        internal static Possible <ICacheConfigData> TryGetCacheConfigData(
            PathTable pathTable,
            string cacheDirectory,
            ICacheConfiguration config)
        {
            Contract.Requires(pathTable != null);
            Contract.Requires(pathTable.IsValid);
            Contract.Requires(config != null);
            Contract.Requires(config.CacheLogFilePath.IsValid);
            Contract.Requires(config.CacheConfigFile.IsValid);
            Contract.Requires(!string.IsNullOrWhiteSpace(cacheDirectory));

            Possible <string> maybeConfigData = TryReadCacheConfigFile(config.CacheConfigFile.ToString(pathTable));

            if (!maybeConfigData.Succeeded)
            {
                return(maybeConfigData.Failure);
            }

            // Update the cache config to dynamically set the cache path if it is configured to use the per-invocation path.
            // TODO: Ideally this would be exposed as config constructor parameters to BuildXL to not require manipulating the json config.
            //       But for now we just modify the config text before passing it along to the cache.
            string cacheConfigContent = maybeConfigData.Result;

            cacheConfigContent = cacheConfigContent.Replace("[DominoSelectedLogPath]", config.CacheLogFilePath.ToString(pathTable).Replace(@"\", @"\\"));  // Escape path separation chars to json format
            cacheConfigContent = cacheConfigContent.Replace("[BuildXLSelectedLogPath]", config.CacheLogFilePath.ToString(pathTable).Replace(@"\", @"\\")); // Escape path separation chars to json format
            cacheConfigContent = cacheConfigContent.Replace("[DominoSelectedRootPath]", cacheDirectory.Replace(@"\", @"\\"));
            cacheConfigContent = cacheConfigContent.Replace("[BuildXLSelectedRootPath]", cacheDirectory.Replace(@"\", @"\\"));
            cacheConfigContent = cacheConfigContent.Replace("[UseDedupStore]", config.UseDedupStore.ToString());

            ICacheConfigData cacheConfigData;
            Exception        exception;

            if (!CacheFactory.TryCreateCacheConfigData(cacheConfigContent, out cacheConfigData, out exception))
            {
                return(new Failure <string>(I($"Unable to create cache config data: {exception.Message}")));
            }

            return(new Possible <ICacheConfigData>(cacheConfigData));
        }
        public async Task MaterializeOverExistentFile()
        {
            const string TargetContent = "This should be the final content";

            string targetPath = GetFullPath("NiftyBits");

            WriteFile("NiftyBits", "Please replace this");

            ContentHash availableHash = await AddContent(TargetContent);

            await LoadContentAndExpectAvailable(ContentCache, availableHash);

            Possible <Unit> maybeMaterialized = await ContentCache.TryMaterializeAsync(
                FileRealizationMode.Copy,
                AbsolutePath.Create(Context.PathTable, targetPath).Expand(Context.PathTable),
                availableHash,
                Context.CancellationToken);

            XAssert.IsTrue(maybeMaterialized.Succeeded);

            XAssert.AreEqual(TargetContent, File.ReadAllText(targetPath));

            if (!OperatingSystemHelper.IsUnixOS)
            {
                // Test materialization failure due to open file handle
                // Disabled on Mac because on unix file systems opening a file doesn't prevent it from being deleted by a different process
                using (var fs = new FileStream(targetPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                    maybeMaterialized = await ContentCache.TryMaterializeAsync(
                        FileRealizationMode.Copy,
                        AbsolutePath.Create(Context.PathTable, targetPath).Expand(Context.PathTable),
                        availableHash,
                        Context.CancellationToken);

                    XAssert.IsFalse(maybeMaterialized.Succeeded, "Expected materialization failure due to open file handle, but it succeed");

                    XAssert.IsTrue(maybeMaterialized.Failure is FailToDeleteForMaterializationFailure);
                }
            }
        }
        /// <inheritdoc />
        public async Task <Possible <ContentHash, Failure> > TryStoreAsync(
            FileRealizationMode fileRealizationModes,
            ExpandedAbsolutePath path)
        {
            string expandedPath = GetExpandedPathForCache(path);

            Possible <ICacheSession, Failure> maybeOpen   = m_cache.Get(nameof(TryStoreAsync));
            Possible <CasHash, Failure>       maybeStored = await PerformArtifactCacheOperationAsync(
                () => maybeOpen.ThenAsync(
                    async cache =>
            {
                var result = await Helpers.RetryOnFailureAsync(
                    async lastAttempt =>
                {
                    return(await cache.AddToCasAsync(expandedPath, GetFileStateForRealizationMode(fileRealizationModes)));
                });
                return(result);
            }),
                nameof(TryStoreAsync));

            return(maybeStored.Then <ContentHash>(c => c.ToContentHash()));
        }
Пример #16
0
        private static async Task <Possible <PublishedEntryRef, Failure> > AdaptPublishedEntry(Task <Possible <StrongFingerprint, Failure> > cacheCoreEntryPromise, PublishedEntryRefLocality locality)
        {
            Possible <StrongFingerprint, Failure> maybeFingerprint = await cacheCoreEntryPromise;

            if (maybeFingerprint.Succeeded)
            {
                StrongFingerprint fingerprint = maybeFingerprint.Result;

                if (fingerprint is StrongFingerprintSentinel)
                {
                    return(PublishedEntryRef.Ignore);
                }

                return(new PublishedEntryRef(
                           pathSetHash: ContentHashingUtilities.CreateFrom(fingerprint.CasElement.ToArray()),
                           strongFingerprint: new StrongContentFingerprint(FingerprintUtilities.CreateFrom(fingerprint.HashElement.ToArray())),
                           oringinatingCache: fingerprint.CacheId,
                           locality: locality));
            }

            return(maybeFingerprint.Failure);
        }
        private static async Task <Possible <Stream, Failure> > TryGetStreamFromContentHash(
            IArtifactContentCache contentCache,
            ContentHash contentHash,
            BoxRef <long> contentSize = null)
        {
            if (!EngineEnvironmentSettings.SkipExtraneousPins)
            {
                Possible <ContentAvailabilityBatchResult, Failure> maybeAvailable =
                    await contentCache.TryLoadAvailableContentAsync(new[] { contentHash });

                if (!maybeAvailable.Succeeded)
                {
                    return(maybeAvailable.Failure);
                }

                bool contentIsAvailable = maybeAvailable.Result.AllContentAvailable;
                if (!contentIsAvailable)
                {
                    return(default(Stream));
                }
            }

            var maybeStream = await contentCache.TryOpenContentStreamAsync(contentHash);

            if (!maybeStream.Succeeded)
            {
                return(maybeStream.Failure);
            }

            Stream stream = maybeStream.Result;

            if (contentSize != null)
            {
                contentSize.Value = stream.Length;
            }

            return(stream);
        }
Пример #18
0
        public async Task ListMultipleEntriesForSamePathSet()
        {
            ContentHash pathSetHash = await AddContent("This is a list of paths");

            WeakContentFingerprint   weak    = CreateWeakFingerprint("Fingerprint text here");
            StrongContentFingerprint strongA = CreateStrongFingerprint("Strong fingerprint text here");
            StrongContentFingerprint strongB = CreateStrongFingerprint("Slightly different fingerprint text here");

            CacheEntry entryA = await CreateCacheEntryAndStoreContent("Metadata A", "A", "B");

            CacheEntry entryB = await CreateCacheEntryAndStoreContent("Metadata B", "A-prime", "B-prime");

            await PublishExpectingNoConflict(weak, pathSetHash, strongA, entryA);
            await PublishExpectingNoConflict(weak, pathSetHash, strongB, entryB);

            List <PublishedEntryRef> refs = new List <PublishedEntryRef>();

            foreach (Task <Possible <PublishedEntryRef, Failure> > maybeEntryTask in FingerprintStore.ListPublishedEntriesByWeakFingerprint(weak))
            {
                Possible <PublishedEntryRef> maybeEntry = await maybeEntryTask;
                XAssert.IsTrue(maybeEntry.Succeeded);
                refs.Add(maybeEntry.Result);
            }

            if (refs[0].StrongFingerprint == strongA)
            {
                XAssert.AreEqual(strongB, refs[1].StrongFingerprint);
                XAssert.AreEqual(pathSetHash, refs[1].PathSetHash);
            }
            else
            {
                XAssert.AreEqual(strongB, refs[0].StrongFingerprint);
                XAssert.AreEqual(pathSetHash, refs[0].PathSetHash);

                XAssert.AreEqual(strongA, refs[1].StrongFingerprint);
                XAssert.AreEqual(pathSetHash, refs[1].PathSetHash);
            }
        }
Пример #19
0
        /// <nodoc />
        public async Task <Possible <IPlugin> > GetOrCreateAsync(PluginCreationArgument startPluginArguments)
        {
            var creationResult = await m_plugins.GetOrAdd(startPluginArguments.PluginPath, path => CreatePluginAsync(startPluginArguments));

            if (!creationResult.Succeeded)
            {
                m_plugins.TryRemove(startPluginArguments.PluginPath, out _);
                return(creationResult);
            }

            var plugin = creationResult.Result;
            Possible <List <PluginMessageType> > messageType = await GetSupportedMessageTypeAsync(plugin);

            if (messageType.Succeeded)
            {
                // Register the plugin in handlers only when response of supportedMessageType is received
                foreach (var pluginMessageType in messageType.Result)
                {
                    IPlugin alreadyRegisteredPlugin = null;
                    if (!m_pluginHandlers.TryGet(pluginMessageType, out alreadyRegisteredPlugin))
                    {
                        m_pluginHandlers.TryAdd(pluginMessageType, plugin);
                    }
                    else
                    {
                        Tracing.Logger.Log.PluginManagerErrorMessage(m_loggingContext, $"Two plugins({plugin.FilePath} and {alreadyRegisteredPlugin.FilePath}) can hanlde {pluginMessageType} that we don't suuport this scenario");
                    }
                }
                Tracing.Logger.Log.PluginManagerLogMessage(m_loggingContext, $"Supported Messagey Type for {plugin.Name} is {string.Join(",", messageType.Result)}");
                plugin.SupportedMessageType = messageType.Result;
            }
            else
            {
                Tracing.Logger.Log.PluginManagerLogMessage(m_loggingContext, $"Can't get supported message tyep for {plugin.Name}");
            }

            return(creationResult);
        }
Пример #20
0
        public async Task FailedPublishReturnsConflictingEntry()
        {
            ContentHash pathSetHash = await AddContent("This is a list of paths");

            WeakContentFingerprint   weak   = CreateWeakFingerprint("Fingerprint text here");
            StrongContentFingerprint strong = CreateStrongFingerprint("Strong fingerprint text here");

            CacheEntry originalEntry = await CreateCacheEntryAndStoreContent("Metadata", "A", "B");

            Possible <CacheEntryPublishResult> maybePublished = await FingerprintStore.TryPublishCacheEntryAsync(
                weak,
                pathSetHash,
                strong,
                originalEntry);

            XAssert.IsTrue(maybePublished.Succeeded);

            CacheEntryPublishResult publishResult = maybePublished.Result;

            XAssert.AreEqual(CacheEntryPublishStatus.Published, publishResult.Status);

            CacheEntry successorEntry = await CreateCacheEntryAndStoreContent("Metadata", "Different A", "Different B");

            Possible <CacheEntryPublishResult> maybePublishedAgain = await FingerprintStore.TryPublishCacheEntryAsync(
                weak,
                pathSetHash,
                strong,
                successorEntry);

            // The conflict info is in the result (not a failure).
            XAssert.IsTrue(maybePublishedAgain.Succeeded);
            CacheEntryPublishResult publishAgainResult = maybePublishedAgain.Result;

            XAssert.AreEqual(CacheEntryPublishStatus.RejectedDueToConflictingEntry, publishAgainResult.Status);

            // Original entry should be returned.
            AssertCacheEntriesEquivalent(publishAgainResult.ConflictingEntry, originalEntry);
        }
Пример #21
0
        public async Task <IActionResult> LiveData(string xAco, string yAco, string zAco, string xGeo, string yGeo, int testNumber)
        {
            var result = new MobileData()
            {
                xAco = xAco, yAco = yAco, zAco = zAco, xGeo = xGeo, yGeo = yGeo, TestNumber = testNumber
            };

            await _context.AddAsync(result);

            await _context.SaveChangesAsync();

            if (double.Parse(zAco) > 20)
            {
                var suspended = new Possible()
                {
                    Id = result.Id, xAco = xAco, yAco = yAco, zAco = zAco, xGeo = xGeo, yGeo = yGeo, TestNumber = testNumber, Type = DefType.Hole
                };

                await _context.AddAsync(suspended);

                await _context.SaveChangesAsync();
            }
            else if (double.Parse(zAco) < 2)
            {
                var posible = new Possible()
                {
                    Id = result.Id, xAco = xAco, yAco = yAco, zAco = zAco, xGeo = xGeo, yGeo = yGeo, TestNumber = testNumber, Type = DefType.Bump
                };

                await _context.AddAsync(posible);

                await _context.SaveChangesAsync();
            }



            return(Ok(new { xAco, yAco, zAco }));
        }
Пример #22
0
 protected override void ExecuteTask()
 {
     if ((this.ConditionsTrue))
     {
         this.Then.Execute();
     }
     else
     {
         bool Executed = false;
         foreach (TaskContainer Possible in this.ElseIf)
         {
             if (Possible.IfDefined)
             {
                 Possible.Execute();
                 Executed = true;
             }
         }
         if (!Executed & this.Else != null)
         {
             this.Else.Execute();
         }
     }
 }
Пример #23
0
        public void GetReparsePointTarget()
        {
            string symlinkPath = GetFullPath("symlink");
            // the length of the target path must be at least 128 chars, so we could properly test the parsing
            // of the struct returned from DeviceIoControl.
            string symlinkTarget = PathGeneratorUtilities.GetAbsolutePath("Z", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), $"{Guid.NewGuid().ToString()}.txt");

            XAssert.IsTrue(symlinkTarget.Length >= 128);

            XAssert.IsTrue(FileUtilities.TryCreateSymbolicLink(symlinkPath, symlinkTarget, isTargetFile: true));

            Possible <ReparsePointType> reparsePointType = FileUtilities.TryGetReparsePointType(symlinkPath);

            XAssert.IsTrue(reparsePointType.Succeeded);
            XAssert.IsTrue(reparsePointType.Result == ReparsePointType.SymLink);

            using (var symlinkHandle = OpenHandleForReparsePoint(symlinkPath))
            {
                var possibleSymlinkTargetToCheck = FileUtilities.TryGetReparsePointTarget(symlinkHandle, symlinkPath);
                XAssert.IsTrue(possibleSymlinkTargetToCheck.Succeeded, I($"Failed to get the reparse point target for '{symlinkPath}'"));
                XAssert.AreEqual(symlinkTarget, possibleSymlinkTargetToCheck.Result);
            }
        }
Пример #24
0
        /// <summary>
        /// Return result for the activity
        /// </summary>
        /// <param name="result">The return result</param>
        /// <returns>
        /// Returns the same value as given
        /// </returns>
        /// <notes>
        /// Returns the same value as given such that code can be
        /// written that looks like:
        /// <code>return activity.Returns(result);</code>
        /// If we had a formal way to do tail-calls in C# we would
        /// have done that.  This is as close as it gets.
        /// </notes>
        public Possible <CasEntries, Failure> Returns(Possible <CasEntries, Failure> result)
        {
            if (result.Succeeded)
            {
                if (TraceReturnValuesEnabled())
                {
                    Write(
                        ReturnOptions,
                        new
                    {
                        CasEntries = result.Result.ToETWFormat(),
                    });
                }

                Stop();
            }
            else
            {
                StopFailure(result.Failure);
            }

            return(result);
        }
Пример #25
0
        /// <summary>
        /// Return result for the activity
        /// </summary>
        /// <param name="result">The return result</param>
        /// <returns>
        /// Returns the same value as given
        /// </returns>
        /// <notes>
        /// Returns the same value as given such that code can be
        /// written that looks like:
        /// <code>return activity.Returns(result);</code>
        /// If we had a formal way to do tail-calls in C# we would
        /// have done that.  This is as close as it gets.
        /// </notes>
        public Possible <ValidateContentStatus, Failure> Returns(Possible <ValidateContentStatus, Failure> result)
        {
            if (result.Succeeded)
            {
                if (TraceReturnValuesEnabled())
                {
                    Write(
                        ReturnOptions,
                        new
                    {
                        Status = result.Result,
                    });
                }

                Stop();
            }
            else
            {
                StopFailure(result.Failure);
            }

            return(result);
        }
Пример #26
0
        /// <summary>
        /// Return result for the activity
        /// </summary>
        /// <param name="result">The return result</param>
        /// <returns>
        /// Returns the same value as given
        /// </returns>
        /// <notes>
        /// Returns the same value as given such that code can be
        /// written that looks like:
        /// <code>return activity.Returns(result);</code>
        /// If we had a formal way to do tail-calls in C# we would
        /// have done that.  This is as close as it gets.
        /// </notes>
        public Possible <CacheSessionStatistics[], Failure> Returns(Possible <CacheSessionStatistics[], Failure> result)
        {
            if (result.Succeeded)
            {
                if (TraceReturnValuesEnabled())
                {
                    Write(
                        ReturnOptions,
                        new
                    {
                        SessionStatistics = result.Result,
                    });
                }

                Stop();
            }
            else
            {
                StopFailure(result.Failure);
            }

            return(result);
        }
Пример #27
0
        /// <summary>
        /// Return result for the activity
        /// </summary>
        /// <param name="result">The return result</param>
        /// <returns>
        /// Returns the same value as given
        /// </returns>
        /// <notes>
        /// Returns the same value as given such that code can be
        /// written that looks like:
        /// <code>return activity.Returns(result);</code>
        /// If we had a formal way to do tail-calls in C# we would
        /// have done that.  This is as close as it gets.
        /// </notes>
        public Possible <string, Failure> Returns(Possible <string, Failure> result)
        {
            if (result.Succeeded)
            {
                if (TraceReturnValuesEnabled())
                {
                    Write(
                        ReturnOptions,
                        new
                    {
                        CacheId = result.Result,
                    });
                }

                Stop();
            }
            else
            {
                StopFailure(result.Failure);
            }

            return(result);
        }
Пример #28
0
        public async Task TestJsonStringWithMissingRequiredParameter()
        {
            // we will not specify StringWithNoDefaultValue - a required parameter that does not have a default value in TestCacheFactory
            string jsonString = GetJsonStringFromDictionary(new Dictionary <string, object>()
            {
                { "StringWithDefaultValue", "Value_of_StringWithDefaultValue" },
                { "IntValue", 123 },
                { "BoolValue", false },
                { "FloatValue", 245.45 }
            });

            // this Json string will produce a failure and there will be no results to validate. We will set the result validation to null here
            resultValidationLambda = null;

            // call InitializeCache, there should be no exception
            Possible <ICache, Failure> cache = await InitializeCacheAsync(jsonString);

            // make sure that we do not get a cache
            XAssert.IsFalse(cache.Succeeded);

            // validate the returned error message
            XAssert.AreEqual("BuildXL.Cache.Tests.TestCacheFactory requires a value for 'StringWithNoDefaultValue' in Json configuration data", cache.Failure.Describe());
        }
Пример #29
0
        private Possible <DeserializedJavaScriptProject> CreateJavaScriptProject(string name, IReadOnlyCollection <string> dependencies, RelativePath projectFolder)
        {
            var maybeCustomScripts = new Possible <IReadOnlyDictionary <string, string> >((IReadOnlyDictionary <string, string>)null);

            // If there is a callback defined, give it a chance to retrieve custom scripts
            if (m_resolverSettings.CustomScripts != null)
            {
                maybeCustomScripts = ResolveCustomScripts(name, projectFolder);
                if (!maybeCustomScripts.Succeeded)
                {
                    return(maybeCustomScripts.Failure);
                }
            }

            // The callback does not want to customize the scripts for this particular project or there is no callback.
            // Let's try to find a package.json under the project folder
            if (maybeCustomScripts.Result == null)
            {
                var packageJsonPath = m_resolverSettings.Root.Combine(m_context.PathTable, projectFolder).Combine(m_context.PathTable, "package.json");
                maybeCustomScripts = GetScriptsFromPackageJson(packageJsonPath, m_resolverSettings.Location(m_context.PathTable));

                if (!maybeCustomScripts.Succeeded)
                {
                    return(maybeCustomScripts.Failure);
                }
            }

            return(new DeserializedJavaScriptProject(
                       name: name,
                       projectFolder: m_resolverSettings.Root.Combine(m_context.PathTable, projectFolder),
                       dependencies: dependencies,
                       availableScriptCommands: maybeCustomScripts.Result,
                       tempFolder: m_resolverSettings.Root,
                       outputDirectories: CollectionUtilities.EmptyArray <PathWithTargets>(),
                       sourceFiles: CollectionUtilities.EmptyArray <PathWithTargets>()
                       ));
        }
Пример #30
0
        private async Task <Possible <ProjectGraphResult> > TryComputeBuildGraphIfNeededAsync()
        {
            if (m_projectGraph == null)
            {
                // Get the locations where the MsBuild assemblies should be searched
                if (!TryRetrieveMsBuildSearchLocations(out IEnumerable <AbsolutePath> msBuildSearchLocations))
                {
                    // Errors should have been logged
                    return(new MsBuildGraphConstructionFailure(m_resolverSettings, m_context.PathTable));
                }

                if (!TryRetrieveParsingEntryPoint(out IEnumerable <AbsolutePath> parsingEntryPoints))
                {
                    // Errors should have been logged
                    return(new MsBuildGraphConstructionFailure(m_resolverSettings, m_context.PathTable));
                }

                // If we should run the dotnet core version of MSBuild, let's retrieve the locations where dotnet.exe
                // should be found
                IEnumerable <AbsolutePath> dotNetSearchLocations = null;
                if (m_resolverSettings.ShouldRunDotNetCoreMSBuild())
                {
                    if (!TryRetrieveDotNetSearchLocations(out dotNetSearchLocations))
                    {
                        // Errors should have been logged
                        return(new MsBuildGraphConstructionFailure(m_resolverSettings, m_context.PathTable));
                    }
                }

                BuildParameters.IBuildParameters buildParameters = RetrieveBuildParameters();

                m_projectGraph = await TryComputeBuildGraphAsync(msBuildSearchLocations, dotNetSearchLocations, parsingEntryPoints, buildParameters);
            }

            return(m_projectGraph.Value);
        }
Пример #31
0
        private async Task <Possible <ProjectGraphResult> > TryComputeBuildGraphIfNeededAsync()
        {
            if (m_projectGraph == null)
            {
                // Get the locations where the MsBuild assemblies should be searched
                if (!TryRetrieveMsBuildSearchLocations(out IEnumerable <AbsolutePath> searchLocations))
                {
                    // Errors should have been logged
                    return(new MsBuildGraphConstructionFailure(m_resolverSettings, Context.PathTable));
                }

                if (!TryRetrieveParsingEntryPoint(out IEnumerable <AbsolutePath> parsingEntryPoints))
                {
                    // Errors should have been logged
                    return(new MsBuildGraphConstructionFailure(m_resolverSettings, Context.PathTable));
                }

                BuildParameters.IBuildParameters buildParameters = RetrieveBuildParameters();

                m_projectGraph = await TryComputeBuildGraphAsync(searchLocations, parsingEntryPoints, buildParameters);
            }

            return(m_projectGraph.Value);
        }
        /// <summary>
        /// Bond-serializes a given <typeparamref name="T"/> and stores the result to the content cache.
        /// The returned content hash can be used to later deserialize the structure with <see cref="TryLoadAndDeserializeContent{T}"/>.
        /// </summary>
        public static async Task <Possible <ContentHash> > TrySerializeAndStoreContent <T>(
            this IArtifactContentCache contentCache,
            T valueToSerialize,
            BoxRef <long> contentSize = null)
        {
            return(await BondExtensions.TrySerializeAndStoreContent(
                       valueToSerialize,
                       async (valueHash, valueBuffer) =>
            {
                using (var entryStream = new MemoryStream(
                           valueBuffer.Array,
                           valueBuffer.Offset,
                           valueBuffer.Count,
                           writable: false))
                {
                    Possible <Unit, Failure> maybeStored = await contentCache.TryStoreAsync(
                        entryStream,
                        contentHash: valueHash);

                    return maybeStored.WithGenericFailure();
                }
            },
                       contentSize));
        }
        public static void CellIndexWithFewestFlags(Possible[,] root, out int row, out int col)
        {
            row = -1;
            col = -1;
            var lowestNumber = int.MaxValue;
            for (int iRow = 0; iRow < 9; iRow++)
            {
                for (int iCol = 0; iCol < 9; iCol++)
                {
                    var cell = root[iRow, iCol];
                    if (!OnlyOnePosiblity(cell))
                    {
                        var numberOfPosibiltiesInCell = GetFlags(cell).Count();

                        if (lowestNumber > numberOfPosibiltiesInCell)
                        {
                            row = iRow;
                            col = iCol;
                            lowestNumber = numberOfPosibiltiesInCell;
                        }
                    }
                }
            }
        }
 public static bool IsCorrect(Possible[,] posArray)
 {
     var isCorrect = false;
     return !HasError(posArray, out isCorrect) && isCorrect;
 }
Пример #35
0
 public SampleMeasure()
 {
   Size = 3;
   actual = Possible.C;
 }
 private static int CellValue(Possible pos) => Array.IndexOf(posabilities, pos) + 1;
 public static IEnumerable<Possible> GetFlags(Possible input)
 {
     if (input.HasFlag(One)) yield return One;
     if (input.HasFlag(Two)) yield return Two;
     if (input.HasFlag(Three)) yield return Three;
     if (input.HasFlag(Four)) yield return Four;
     if (input.HasFlag(Five)) yield return Five;
     if (input.HasFlag(Six)) yield return Six;
     if (input.HasFlag(Seven)) yield return Seven;
     if (input.HasFlag(Eight)) yield return Eight;
     if (input.HasFlag(Nine)) yield return Nine;
 }
 public static bool OnlyOnePosiblity(Possible possible) => (possible & (possible - 1)) == 0;
 private static bool OnlyInBox(Possible[,] root, int row, int col, Possible number)
 {
     var boxRow = (row / 3) * 3;
     var boxCol = (col / 3) * 3;
     for (int iCol = boxCol; iCol < boxCol + 3; iCol++)
     {
         for (int iRow = boxRow; iRow < boxRow + 3; iRow++)
         {
             if (iCol == col && iRow == row) continue;
             if (root[iRow, iCol].HasFlag(number)) return false;
         }
     }
     return true;
 }
        public static Possible CheckCellWithPos(Possible[,] root, int row, int col)
        {
            var possible = root[row, col];
            if (OnlyOnePosiblity(possible)) return possible;
            foreach (var number in GetFlags(possible).ToList())
            {
                var onlyInRow = true;
                var onlyInCol = true;
                for (int i = 0; i < 9; i++)
                {
                    if (i != col && root[row, i].HasFlag(number))
                    {
                        onlyInRow = false;
                    }
                    if (i != row && root[i, col].HasFlag(number))
                    {
                        onlyInCol = false;
                    }
                    if (!onlyInCol && !onlyInRow) break;
                }
                if (onlyInCol || onlyInRow)
                {
                    return number;
                }

                if (OnlyInBox(root, row, col, number))
                {
                    return number;
                }
            }
            return possible;
        }
 private static bool FillOut(int[,] board, Possible[,] posArray, bool useSimpleMethod)
 {
     var anyChangeAtAll = false;
     var changed = false;
     do
     {
         changed = false;
         for (int row = 0; row < 9; row++)
         {
             for (int col = 0; col < 9; col++)
             {
                 Possible possible;
                 if (useSimpleMethod)
                 {
                     possible = posArray[row, col] = CheckCell(board, row, col);
                 }
                 else
                 {
                     possible = CheckCellWithPos(posArray, row, col);
                 }
                 if (possible == 0) return false;
                 if (board[row, col] == 0 && OnlyOnePosiblity(possible))
                 {
                     board[row, col] = CellValue(possible);
                     changed = true;
                     anyChangeAtAll = true;
                 }
             }
         }
     } while (changed);
     return anyChangeAtAll;
 }
 public static void FillOut(int[,] board, Possible[,] root)
 {
     do
     {
         FillOut(board, root, true);
     }
     while (FillOut(board, root, false));
 }
 public static bool HasError(Possible[,] arr, out bool IsCorrect)
 {
     IsCorrect = true;
     for (int row = 0; row < 9; row++)
     {
         for (int col = 0; col < 9; col++)
         {
             if (arr[row, col] == 0) return true;
             if (!OnlyOnePosiblity(arr[row, col]))
                 IsCorrect = false;
         }
     }
     return false;
 }