Пример #1
0
        public async Task <ActionResult <Word> > PostWord(Word item)
        {
            // clean the item, we don't support related words in this way
            item.RelatedFrom = null;
            item.RelatedTo   = null;

            var wordText = item.Value;

            item.NumberOfLetters = ScraperUtils.CountNumberOfLetters(wordText);
            item.NumberOfWords   = ScraperUtils.CountNumberOfWords(wordText);
            item.Category        = null;
            item.CreatedDate     = (item.CreatedDate == null ? DateTime.Now : item.CreatedDate);

            // use the following statement so that User won't be inserted
            item.User = new User()
            {
                UserId = 1
            };
            db.Entry(item.User).State = EntityState.Unchanged;

            db.Words.Add(item);
            await db.SaveChangesAsync();

            return(CreatedAtAction(nameof(GetWord), new { id = item.WordId }, item));
        }
Пример #2
0
        public static void AddToDatabase(WordHintDbContext db, string source, User user, string wordText, IEnumerable <string> relatedValues, TextWriter writer = null, bool doStoreState = true)
        {
            // Note that  tracking should be disabled to speed things up
            // note that this doesn't load the virtual properties, but loads the object ids after a save
            // db.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

            // ensure uppercase
            wordText = wordText.ToUpper();

            var word = new Word
            {
                Language        = "no",
                Value           = wordText,
                NumberOfLetters = ScraperUtils.CountNumberOfLetters(wordText),
                NumberOfWords   = ScraperUtils.CountNumberOfWords(wordText),
                User            = user,
                CreatedDate     = DateTime.Now,
                Source          = source
            };

            // ensure related are all uppercase and distinct
            var relatedValuesUpperCase = relatedValues.Select(x => x.ToUpper()).Distinct();

            // get all related words (hints) as Word objects
            var relatedWords = relatedValuesUpperCase.Select(hintText => new Word
            {
                Language        = "no",
                Value           = hintText,
                NumberOfLetters = ScraperUtils.CountNumberOfLetters(hintText),
                NumberOfWords   = ScraperUtils.CountNumberOfWords(hintText),
                User            = user,
                CreatedDate     = DateTime.Now,
                Source          = source
            });

            AddToDatabase(db, source, word, relatedWords, writer, doStoreState);
        }
Пример #3
0
        public static int SimplifyRequiredNamespacesForNames(string repoRoot, string apiCsv, string input, string output)
        {
            RepoInfo repoInfo = new RepoInfo(repoRoot);
            Dictionary <string, string> headerToNamespace = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            foreach (var part in repoInfo.GetPartitionInfos())
            {
                foreach (var header in part.GetTraverseHeaders(true, "x64"))
                {
                    string fileName = Path.GetFileName(header);
                    headerToNamespace[fileName] = part.Namespace;
                }
            }

            CsvConfiguration config = new CsvConfiguration(CultureInfo.InvariantCulture);

            config.Delimiter       = ",";
            config.HasHeaderRecord = true;

            Dictionary <string, string> nameToNamespace = new Dictionary <string, string>();

            using (var reader = new StreamReader(apiCsv))
                using (var csvReader = new CsvReader(reader, config))
                {
                    var anonymousTypeDefinition = new
                    {
                        Name     = string.Empty,
                        Title    = string.Empty,
                        Header   = string.Empty,
                        TechRoot = string.Empty
                    };

                    foreach (var record in csvReader.GetRecords(anonymousTypeDefinition))
                    {
                        if (!string.IsNullOrEmpty(record.Header) && !string.IsNullOrEmpty(record.Title))
                        {
                            if (headerToNamespace.TryGetValue(record.Header, out var namespaceName))
                            {
                                nameToNamespace[record.Title] = namespaceName;
                            }
                        }
                    }
                }

            // Load up all the names along with their final value. This
            // will get rid of duplicates and take the final one
            Dictionary <string, string> namesAndValues = new Dictionary <string, string>();

            foreach (var line in File.ReadAllLines(input))
            {
                string[] parts = line.Split('=');
                if (parts.Length == 2)
                {
                    string name = parts[0];
                    string ns   = parts[1];
                    namesAndValues[name] = ns;
                }
            }

            string emitterGeneratedDir      = Path.Combine(repoRoot, $@"generation\emitter\generated\x64");
            var    scrapedNamesToNamespaces = ScraperUtils.GetNameToNamespaceMap(emitterGeneratedDir);

            using (StreamWriter writer = new StreamWriter(output))
            {
                writer.WriteLine("--requiredNamespaceForName");
                foreach (var line in File.ReadAllLines(input))
                {
                    string[] parts = line.Split('=');
                    if (parts.Length == 2)
                    {
                        string name = parts[0];
                        string ns   = parts[1];

                        // Skip if we never scanned it
                        if (!scrapedNamesToNamespaces.ContainsKey(name))
                        {
                            continue;
                        }

                        // If this isn't the one that has the final value, skip it
                        if (namesAndValues[name] != ns)
                        {
                            continue;
                        }

                        // Skip if this line is redundant, because the name is in the correct namespace
                        // based on the header
                        if (nameToNamespace.TryGetValue(name, out var headerNamespace))
                        {
                            if (ns == headerNamespace)
                            {
                                continue;
                            }

                            Console.WriteLine($"Keeping override: {line} (header goes into {headerNamespace})");
                        }

                        writer.WriteLine(line);
                    }
                }
            }

            return(0);
        }
Пример #4
0
        public async Task <IActionResult> PutWord(long id, Word item)
        {
            if (id != item.WordId)
            {
                return(BadRequest());
            }

            var alreadyExist = db.Words
                               .AsNoTracking()
                               .FirstOrDefault(a => a.Value == item.Value);

            if (alreadyExist != null)
            {
                // already have this entry, cannot create an duplicate

                // find all the relations to this word.
                var wordRelations = await db.WordRelations
                                    .AsNoTracking()
                                    .Where(e => id == e.WordFromId || id == e.WordToId)
                                    .ToListAsync();

                if (wordRelations.Any())
                {
                    var allRelatedWordsIds = wordRelations
                                             .SelectMany(w => new[] { w.WordFromId, w.WordToId })
                                             .Distinct()
                                             .Where(w => w != id && w != alreadyExist.WordId)
                                             .OrderBy(w => w)
                                             .ToList()
                    ;

                    // create new relations to the original word
                    var allWordRelationsFrom = allRelatedWordsIds.Select(wordFromId =>
                                                                         new WordRelation {
                        WordFromId = wordFromId, WordToId = alreadyExist.WordId
                    }
                                                                         );

                    // add relation from each hint to word as well
                    var allWordRelationsTo = allRelatedWordsIds.Select(wordToId =>
                                                                       new WordRelation {
                        WordFromId = alreadyExist.WordId, WordToId = wordToId
                    }
                                                                       );

                    // all relations
                    var allWordRelations = allWordRelationsFrom.Concat(allWordRelationsTo).Distinct();

                    // which relations need to be added?
                    var newWordRelations = allWordRelations.Where(x => !db.WordRelations.Any(z => z.WordFromId == x.WordFromId && z.WordToId == x.WordToId)).ToList();

                    if (newWordRelations.Count > 0)
                    {
                        db.WordRelations.AddRange(newWordRelations);
                    }

                    // then delete the original relations
                    db.WordRelations.RemoveRange(wordRelations);
                }

                // then delete the actual word
                db.Words.Remove(item);
                await db.SaveChangesAsync();

                return(Ok(alreadyExist));
            }
            else
            {
                // make sure the counts are recalculated
                var wordText = item.Value;
                item.NumberOfLetters = ScraperUtils.CountNumberOfLetters(wordText);
                item.NumberOfWords   = ScraperUtils.CountNumberOfWords(wordText);

                db.Entry(item).State = EntityState.Modified;
                await db.SaveChangesAsync();

                return(Ok(item));
            }
        }