Пример #1
0
        /// <summary>
        /// Gets the application assemblies.
        /// </summary>
        /// <param name="assemblyFilter">(Optional) A filter for the assemblies.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// A promise of an enumeration of application assemblies.
        /// </returns>
        public virtual async Task<IEnumerable<Assembly>> GetAppAssembliesAsync(Func<AssemblyName, bool> assemblyFilter = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // TODO The assemblies from the current domain do not consider the not loaded
            // but required referenced assemblies. Therefore load all the references recursively.
            // This could be optimized somehow.
            var assemblies = this.GetLoadedAssemblies();

            assemblyFilter = assemblyFilter ?? this.AssemblyFilter;
            var loadedAssemblyRefs = new HashSet<string>(assemblies.Select(a => a.GetName().FullName));
            var assembliesToCheck = assemblies.Where(a => assemblyFilter(a.GetName())).ToList();

            while (assembliesToCheck.Count > 0)
            {
                var assemblyRefsToLoad = new HashSet<AssemblyName>();
                foreach (var assembly in assembliesToCheck)
                {
                    var referencesToLoad = this.GetReferencedAssemblies(assembly).Where(a => !loadedAssemblyRefs.Contains(a.FullName) && assemblyFilter(a));
                    assemblyRefsToLoad.AddRange(referencesToLoad);
                }

                loadedAssemblyRefs.AddRange(assemblyRefsToLoad.Select(an => an.FullName));
                assembliesToCheck = assemblyRefsToLoad.Select(this.AssemblyLoader.LoadAssembly).ToList();
                assemblies.AddRange(assembliesToCheck);
            }

            await this.AddAdditionalAssembliesAsync(assemblies, assemblyFilter, cancellationToken).PreserveThreadContext();
            return assemblies;
        }
Пример #2
0
        public static ClaimsIdentity CreateUserIdentity(string emailAddress, string id, string[] organizationIds, string[] roles, string defaultProjectId = null) {
            var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name, emailAddress),
                    new Claim(ClaimTypes.NameIdentifier, id),
                    new Claim(OrganizationIdsClaim, String.Join(",", organizationIds))
                };

            if (!String.IsNullOrEmpty(defaultProjectId))
                claims.Add(new Claim(DefaultProjectIdClaim, defaultProjectId));

            var userRoles = new HashSet<string>(roles);
            if (userRoles.Any()) {
                // add implied scopes
                if (userRoles.Contains(AuthorizationRoles.GlobalAdmin))
                    userRoles.Add(AuthorizationRoles.User);

                if (userRoles.Contains(AuthorizationRoles.User))
                    userRoles.Add(AuthorizationRoles.Client);

                claims.AddRange(userRoles.Select(scope => new Claim(ClaimTypes.Role, scope)));
            } else {
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.Client));
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.User));
            }

            return new ClaimsIdentity(claims, UserAuthenticationType);
        }
        ///<summary>Gets all files that indirectly depend on the specified file.</summary>
        public async Task<IEnumerable<string>> GetRecursiveDependentsAsync(string fileName)
        {
            HashSet<GraphNode> visited;
            fileName = Path.GetFullPath(fileName);
            using (await rwLock.ReadLockAsync())
            {
                GraphNode rootNode;
                if (!nodes.TryGetValue(fileName, out rootNode))
                    return Enumerable.Empty<string>();

                var stack = new Stack<GraphNode>();
                stack.Push(rootNode);
                visited = new HashSet<GraphNode> { rootNode };
                while (stack.Count > 0)
                {
                    foreach (var child in stack.Pop().Dependents)
                    {
                        if (!visited.Add(child)) continue;
                        stack.Push(child);
                    }
                }
                // Don't return the original file.
                visited.Remove(rootNode);
            }
            return visited.Select(n => n.FileName);
        }
        public void Install(RunningDeployment deployment)
        {
            var transformDefinitions = GetTransformDefinitions(deployment.Variables.Get(SpecialVariables.Package.AdditionalXmlConfigurationTransforms));

            var sourceExtensions = new HashSet<string>(
                  transformDefinitions
                    .Where(transform => transform.Advanced)
                    .Select(transform => "*" + Path.GetExtension(transform.SourcePattern))
                    .Distinct()
                );

            if (deployment.Variables.GetFlag(SpecialVariables.Package.AutomaticallyRunConfigurationTransformationFiles))
            {
                sourceExtensions.Add("*.config");
                transformDefinitions.Add(new XmlConfigTransformDefinition("Release"));

                var environment = deployment.Variables.Get(SpecialVariables.Environment.Name);
                if (!string.IsNullOrWhiteSpace(environment))
                {
                    transformDefinitions.Add(new XmlConfigTransformDefinition(environment));
                }
            }

            var transformsRun = new HashSet<Tuple<string, string>>();
            foreach (var configFile in fileSystem.EnumerateFilesRecursively(deployment.CurrentDirectory, sourceExtensions.ToArray()))
            {
                ApplyTransformations(configFile, transformDefinitions, transformsRun);
            }

            deployment.Variables.SetStrings(SpecialVariables.AppliedXmlConfigTransforms, transformsRun.Select(t => t.Item1), "|");
        }
Пример #5
0
        public static ClaimsIdentity ToIdentity(this User user, string defaultProjectId = null) {
            if (user == null)
                return WindowsIdentity.GetAnonymous();
            
            var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name, user.EmailAddress),
                    new Claim(ClaimTypes.NameIdentifier, user.Id),
                    new Claim(OrganizationIdsClaim, String.Join(",", user.OrganizationIds.ToArray()))
                };

            if (!String.IsNullOrEmpty(defaultProjectId))
                claims.Add(new Claim(DefaultProjectIdClaim, defaultProjectId));

            var userRoles = new HashSet<string>(user.Roles.ToArray());
            if (userRoles.Any()) {
                // add implied scopes
                if (userRoles.Contains(AuthorizationRoles.GlobalAdmin))
                    userRoles.Add(AuthorizationRoles.User);

                if (userRoles.Contains(AuthorizationRoles.User))
                    userRoles.Add(AuthorizationRoles.Client);

                claims.AddRange(userRoles.Select(scope => new Claim(ClaimTypes.Role, scope)));
            } else {
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.Client));
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.User));
            }

            return new ClaimsIdentity(claims, UserAuthenticationType);
        }
Пример #6
0
        /// <summary> Converts a console file args into actual files. </summary>
        /// <remarks> Sequences like "test.vsdx *.vsdx .\test.vsdx" will be correctly recognized,
        /// no file duplicates will be created. </remarks>
        /// <param name="passedFileArgs">File arguments in the console input.</param>
        /// <returns>Sequence of files recognized in the console input.</returns>
        public static IEnumerable<FileInfo> GatherFiles(IList<string> passedFileArgs)
        {
            // Expand passed console input with possible wildcards and duplications into real unique file names:
            var expandedPaths = new HashSet<string>();
            foreach (var inputItem in passedFileArgs) {
                if (string.IsNullOrWhiteSpace(inputItem)) { continue; }

                string[] files;
                if (Directory.Exists(inputItem)) {
                    files = GetFiles(inputItem);
                } else {
                    string path = Path.GetDirectoryName(inputItem);
                    string filename = Path.GetFileName(inputItem);
                    if (filename == "*") {
                        filename = "*.*";
                    }

                    files = GetFiles(path, filename);
                }

                foreach (var file in files) {
                    expandedPaths.Add(file);
                }
            }
            // Expanded file names can be safely turned into FileInfos, since GetFiles()
            // only return real files which can be accessed.
            return expandedPaths.Select(expandedPath => new FileInfo(expandedPath));
        }
Пример #7
0
        public void MatchIndex()
        {
            string tournamentName = "ChallongeNet" + Utilities.RandomName();
            Debug.WriteLine(string.Format("Initializing with name {0}", tournamentName));

            var tournamentUnderTest = this.target.TournamentCreate(tournamentName, TournamentType.SingleElimination, tournamentName);

            var participantNames = new HashSet<string>();
            const int NumberOfParticipants = 8;
            while (participantNames.Count < NumberOfParticipants)
            {
                string name = "ChallongeNet" + Utilities.RandomName();
                participantNames.Add(name);
            }

            var participants = participantNames.Select(name => this.target.ParticipantCreate(tournamentUnderTest, new ParticipantCreateParameters { Name = name })).ToList();

            tournamentUnderTest = this.target.TournamentStart(tournamentUnderTest);

            var participant = participants.First();
            var parameters = new MatchIndexParameters { ParticipantId = participant.Id };
            var matches = this.target.MatchIndex(tournamentUnderTest, parameters);
            var m = matches.Where(match => match.Player1Id == participant.Id || match.Player2Id == participant.Id);
            Assert.AreEqual(1, m.Count());

            parameters = new MatchIndexParameters { State = MatchIndexParameters.MatchIndexState.complete };
            matches = this.target.MatchIndex(tournamentUnderTest, parameters);
            Assert.AreEqual(0, matches.Count);

            this.target.TournamentDestroy(tournamentUnderTest);
        }
Пример #8
0
 public ReplayViewModel Get([FromUri]string[] ids)
 {
     var heads = new[]
     {
         new Directed {X = 1, Y = 13, Direction = Direction.East},
         new Directed {X = 25, Y = 13, Direction = Direction.West},
         new Directed {X = 13, Y = 1, Direction = Direction.North},
         new Directed {X = 13, Y = 25, Direction = Direction.South}
     };
     var n = 0;
     var unique = new HashSet<string>(ids);
     var fighters = unique
         .Select(id => snakeStore.GetById(id))
         .Where(s => s != null)
         .Take(4)
         .Select(snake => new Fighter(snake.Id, snake.Chips, heads[n++]))
         .ToList();
     var tickCount = Environment.TickCount;
     var replay = new Replay(tickCount) { BattleField = new BattleField() };
     if (fighters.Count > 0)
     {
         var battleField = new BattleField();
         var battleManager = new BattleManager(fighters, replay, new FieldComparer(battleField), battleField, tickCount);
         battleManager.Fight(550); //original 550    
     }
     var model = Mapper.Map<Replay, ReplayViewModel>(replay);
     return model;
 }
Пример #9
0
        public bool MapCanBeSolved()
        {
            var cluesFound = new HashSet<Clue>();
            var doorManager = model.DoorAndClueManager;
            //Door & Clue manager works on the reduced map, so we use this here
            //Potentially could be problematic if something is wrong with map reduction
            var totalVerticesReducedMap = model.GraphNoCycles.mapNoCycles.VertexCount;

            int lastTimeAccessibleVertices = 0;
            int noAccessibleVertices = 0;
            do
            {
                lastTimeAccessibleVertices = noAccessibleVertices;

                var accessibleVertices = doorManager.GetAccessibleVerticesWithClues(cluesFound.Select(c => c.OpenLockIndex));

                //Add any clues in these vertices to the clues we have (hashset ensures we don't add twice)
                var cluesAtVertices = accessibleVertices.SelectMany(v => doorManager.ClueMap.ContainsKey(v) ? doorManager.ClueMap[v] : new List<Clue> ());
                foreach (var clue in cluesAtVertices) { cluesFound.Add(clue); }

                noAccessibleVertices = accessibleVertices.Count();
            } while (noAccessibleVertices != lastTimeAccessibleVertices);

            //Couldn't touch all vertices - map is not solvable
            if (noAccessibleVertices < totalVerticesReducedMap)
                return false;

            return true;
        }
Пример #10
0
        private static void Main(string[] args)
        {
            int t = int.Parse(Console.ReadLine());
            string[] k = new string[t];
            for (int i = 0; i < k.Length; i++)
            {
                k[i] = Console.ReadLine();
            }

            string temp = @"<[ ]{0,}[a-z]{1,}[\d]{0,}";
            var regex = new Regex(temp);
            HashSet<string> rez = new HashSet<string>();
            for (int i = 0; i < k.Length; i++)
            {
                var matchs = regex.Matches(k[i]);
                foreach (var r in matchs)
                {
                    var match = (Match)r;

                        rez.Add(match.Value);

                }
            }
            var s = rez
                .Select(f=>f.Substring(1))
                .ToArray();
            Array.Sort(s);
            string mimimi = string.Join(";", s);

            Console.Write(mimimi);
        }
Пример #11
0
 protected ApprovalProcess(Guid promotionId, HashSet<Editor> editors)
 {
     Id = Guid.NewGuid();
     PromotionId = promotionId;
     Status = ApprovalStatus.Pending;
     ApprovalRequests = editors.Select(e => new ApprovalRequest(e)).ToList();
 }
Пример #12
0
        public static UnifiedBubbleGroup CreateUnified(List<BubbleGroup> groups, BubbleGroup primaryGroup)
        {
            lock (BubbleGroupDatabase.OperationLock)
            {
                var unifiedGroupsToKill = new HashSet<UnifiedBubbleGroup>();
                foreach (var group in groups)
                {
                    if (group.IsUnified)
                    {
                        unifiedGroupsToKill.Add(group.Unified);
                        @group.DeregisterUnified();
                    }
                }
                foreach (var unifiedGroup in unifiedGroupsToKill)
                {
                    BubbleGroupManager.BubbleGroupsRemove(unifiedGroup);
                }
                BubbleGroupIndex.RemoveUnified(unifiedGroupsToKill.Select(x => x.ID).ToArray());

                var unified = CreateUnifiedInternal(groups, primaryGroup);
                BubbleGroupIndex.AddUnified(unified);
                BubbleGroupManager.BubbleGroupsAdd(unified);
                return unified;
            }
        }
Пример #13
0
        public void onProductListReceived (string productListString) {
            if (productListString.Length == 0) {
                biller.logError (UnibillError.STOREKIT_RETURNED_NO_PRODUCTS);
                biller.onSetupComplete (false);
                return;
            }

            Dictionary<string, object> response = (Dictionary<string, object>)Unibill.Impl.MiniJSON.jsonDecode(productListString);
            HashSet<PurchasableItem> productsReceived = new HashSet<PurchasableItem>();
            foreach (var identifier in response.Keys) {
                var item = remapper.getPurchasableItemFromPlatformSpecificId(identifier.ToString());
                Dictionary<string, object> details = (Dictionary<string, object>)response[identifier];

                PurchasableItem.Writer.setLocalizedPrice(item, details["price"].ToString());
                PurchasableItem.Writer.setLocalizedTitle(item, details["localizedTitle"].ToString());
                PurchasableItem.Writer.setLocalizedDescription(item, details["localizedDescription"].ToString());
                productsReceived.Add(item);
            }

            HashSet<PurchasableItem> productsNotReceived = new HashSet<PurchasableItem> (products);
            productsNotReceived.ExceptWith (productsReceived);
            if (productsNotReceived.Count > 0) {
                foreach (PurchasableItem product in productsNotReceived) {
                    biller.logError(UnibillError.STOREKIT_REQUESTPRODUCTS_MISSING_PRODUCT, product.Id, remapper.mapItemIdToPlatformSpecificId(product));
                }
            }

            this.productsNotReturnedByStorekit = new HashSet<string>(productsNotReceived.Select(x => remapper.mapItemIdToPlatformSpecificId(x)));

            // We should complete so long as we have at least one purchasable product.
            biller.onSetupComplete(true);
        }
Пример #14
0
        private SyntaxNode AddNamespaceImports(
            Document document,
            SemanticModel model,
            OptionSet options,
            IEnumerable<INamespaceSymbol> namespaces)
        {
            var existingNamespaces = new HashSet<INamespaceSymbol>();
            this.GetExistingImportedNamespaces(document, model, existingNamespaces);

            var namespacesToAdd = new HashSet<INamespaceSymbol>(namespaces);
            namespacesToAdd.RemoveAll(existingNamespaces);

            var root = model.SyntaxTree.GetRoot();
            if (namespacesToAdd.Count == 0)
            {
                return root;
            }

            var gen = SyntaxGenerator.GetGenerator(document);

            var newRoot = root;
            foreach (var import in namespacesToAdd.Select(ns => gen.NamespaceImportDeclaration(ns.ToDisplayString()).WithAdditionalAnnotations(Simplifier.Annotation)))
            {
                newRoot = this.InsertNamespaceImport(newRoot, gen, import, options);
            }

            return newRoot;
        }
Пример #15
0
        public static int Circulars(int range)
        {
            int count = 0;
            HashSet<int> primes = new HashSet<int>();
            primes.UnionWith(Primes.primeRange(range));
            HashSet<string> stringprimes = new HashSet<string>();
            stringprimes.UnionWith(primes.Select<int, string>(x => x.ToString()));

            stringprimes.RemoveWhere(x => x.Contains('2') || x.Contains('4') || x.Contains('6') || x.Contains('8') || x.Contains('0'));

            foreach (string number in stringprimes) {
                string varnumber = number.Substring(0);
                bool allPrime = true;
                for (int i = 0; i < number.Length; i++) {
                    char c = varnumber.First<char>();
                    varnumber += c;
                    varnumber = varnumber.Remove(0, 1);
                    if (!primes.Contains(int.Parse(varnumber))) {
                        //Console.WriteLine(number);
                        allPrime = false;
                        break;
                    }
                }
                if (allPrime == true) {
                    count++;
                }
                allPrime = true;
            }
            return count + 1;
        }
Пример #16
0
        /// <summary>
        /// Retrieves all events across all aggregates that are related to the specified aggregate ids, in the order in which they were recorded.
        /// </summary>
        /// <param name="events">The events.</param>
        /// <param name="relatedToAggregateIds">The aggregate ids to which the events relate.</param>
        public static async Task<IEnumerable<StorableEvent>> RelatedEvents(
            this IQueryable<StorableEvent> events,
            params Guid[] relatedToAggregateIds)
        {
            var ids = new HashSet<Guid>(relatedToAggregateIds);

            var relatedEvents = new HashSet<StorableEvent>();

            int currentCount;

            do
            {
                currentCount = relatedEvents.Count;

                var unqueriedIds = ids.Where(id => ! relatedEvents.Select(e => e.AggregateId).Contains(id));

                var newEvents = await events.Where(e => unqueriedIds.Any(id => id == e.AggregateId)).ToArrayAsync();

                relatedEvents.UnionWith(newEvents);

                var moreIds = newEvents
                    .SelectMany(e => e.Body.ExtractGuids())
                    .Distinct()
                    .ToArray();

                if (!moreIds.Any())
                {
                    break;
                }

                ids.UnionWith(moreIds);
            } while (currentCount != relatedEvents.Count);

            return relatedEvents.OrderBy(e => e.Id);
        }
        private async Task<SyntaxNode> AddNamespaceImportsAsync(
            Document document,
            SemanticModel model,
            OptionSet options,
            IEnumerable<INamespaceSymbol> namespaces,
            CancellationToken cancellationToken)
        {
            var existingNamespaces = new HashSet<INamespaceSymbol>();
            await this.GetExistingImportedNamespacesAsync(document, model, existingNamespaces, cancellationToken).ConfigureAwait(false);

            var namespacesToAdd = new HashSet<INamespaceSymbol>(namespaces);
            namespacesToAdd.RemoveAll(existingNamespaces);

            var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
            if (namespacesToAdd.Count == 0)
            {
                return root;
            }

            var gen = SyntaxGenerator.GetGenerator(document);

            var newRoot = root;
            foreach (var import in namespacesToAdd.Select(ns => gen.NamespaceImportDeclaration(ns.ToDisplayString()).WithAdditionalAnnotations(Simplifier.Annotation)))
            {
                newRoot = this.InsertNamespaceImport(newRoot, gen, import, options);
            }

            return newRoot;
        }
 public static void SomeFunction()
 {
     Dictionary<int, int> dict = new Dictionary<int, int>();
     dict.Add(4, 3);
     Console.WriteLine(dict[4]);
     Console.WriteLine(dict.ContainsKey(8));
     dict.Remove(4);
     foreach(int key in dict.Keys)
         Console.WriteLine(key);
     foreach(int val in dict.Values)
         Console.WriteLine(val);
     foreach(var kv in dict)
         Console.WriteLine(kv.Key + " " + kv.Value);
     var dict2 = dict.ToDictionary(o => o.Key, o => o.Value);
     var vals = dict.Values;
     
     HashSet<int> hash = new HashSet<int>();
     hash.Add(999);
     Console.WriteLine(hash.Contains(999));
     hash.Remove(999);
     Console.WriteLine(hash.Contains(999));
     foreach(int hashItem in hash)
         Console.WriteLine(hashItem);
     var z = hash.Select(o => 3).ToArray();
     var g = hash.GroupBy(o => o).Select(o => o.Count()).Min();
 }
		internal Assembly CompileAndLoadClassDefinition(string code, string className, HashSet<string> assemblies)
		{
			using (var ms = new MemoryStream())
			{
				string assemblyFileName = className + Guid.NewGuid().ToString().Replace("-", "") + ".dll";

				assemblies.Add(typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).Assembly.Location);
				var references = assemblies.Select(a => MetadataReference.CreateFromFile(a));
				var compilation = CSharpCompilation.Create(assemblyFileName,
					new[] { CSharpSyntaxTree.ParseText(code) }, references,
					new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary
//#if !DEBUG
//, optimizationLevel: OptimizationLevel.Release
//#endif
));

				var result = compilation.Emit(ms);
				if (!result.Success)
				{
					var errors = string.Join(Environment.NewLine, result.Diagnostics);
					throw new Exception("Unable to compile. Errors:" + Environment.NewLine + errors);
				}

				var assembly = Assembly.Load(ms.GetBuffer());
				return assembly;
			}
		}
        /// <summary>
        /// Returns a list of assemblies that need binding redirects.
        /// </summary>
        /// <param name="assemblies">List assemblies to analyze for binding redirects</param>
        public static IEnumerable<AssemblyBinding> GetBindingRedirects(IEnumerable<IAssembly> assemblies)
        {
            if (assemblies == null) {
                throw new ArgumentNullException("assemblies");
            }

            // Evaluate the list eagerly
            var assemblyList = assemblies.ToList();

            var assemblyNameLookup = assemblyList.ToDictionary(GetUniqueKey);

            // Output set of assemblies we need redirects for
            var redirectAssemblies = new HashSet<IAssembly>();

            // For each available assembly
            foreach (IAssembly assembly in assemblyList) {
                foreach (IAssembly referenceAssembly in assembly.ReferencedAssemblies) {
                    Tuple<string, string> key = GetUniqueKey(referenceAssembly);
                    IAssembly targetAssembly;
                    // If we have an assembly with the same unique key in our list of a different version then we want to use that version
                    // then we want to add a redirect for that assembly
                    if (assemblyNameLookup.TryGetValue(key, out targetAssembly) && targetAssembly.Version != referenceAssembly.Version) {
                        redirectAssemblies.Add(targetAssembly);
                    }
                }
            }

            return redirectAssemblies.Select(a => new AssemblyBinding(a));
        }
        public IList<HtmlCompletion> GetEntries(HtmlCompletionContext context)
        {
            var list = new HashSet<string>();

            context.Document.HtmlEditorTree.RootNode.Accept(this, list);

            return new List<HtmlCompletion>(list.Select(s => new SimpleHtmlCompletion(s, context.Session)));
        }
        public IList<HtmlCompletion> GetEntries(HtmlCompletionContext context)
        {
            var list = new HashSet<string>();
            var glyph = GlyphService.GetGlyph(StandardGlyphGroup.GlyphGroupVariable, StandardGlyphItem.GlyphItemPublic);

            context.Document.HtmlEditorTree.RootNode.Accept(this, list);

            return list.Select(s => new HtmlCompletion(s, s, s, glyph, HtmlIconAutomationText.AttributeIconText)).ToList();
        }
        public string[] GetAllProjectReferences(string projectName)
        {
            var project = Solution.Projects.First(x => x.Name == projectName);
            var allReferences = new HashSet<MetadataReference>();

            PopulateWithReferences(allReferences, project);

            return allReferences.Select(x => x.Display).ToArray();
        }
Пример #24
0
        /// <summary>
        /// Calculate a path from the start location to the destination location
        /// </summary>
        /// <remarks>
        /// Based on the A* pathfinding algorithm described on Wikipedia
        /// </remarks>
        /// <see href="https://en.wikipedia.org/wiki/A*_search_algorithm#Pseudocode"/>
        /// <param name="start">Start location</param>
        /// <param name="goal">Destination location</param>
        /// <param name="allowUnsafe">Allow possible but unsafe locations</param>
        /// <returns>A list of locations, or null if calculation failed</returns>
        public static Queue<Location> CalculatePath(World world, Location start, Location goal, bool allowUnsafe = false)
        {
            Queue<Location> result = null;

            AutoTimeout.Perform(() =>
            {
                HashSet<Location> ClosedSet = new HashSet<Location>(); // The set of locations already evaluated.
                HashSet<Location> OpenSet = new HashSet<Location>(new[] { start });  // The set of tentative nodes to be evaluated, initially containing the start node
                Dictionary<Location, Location> Came_From = new Dictionary<Location, Location>(); // The map of navigated nodes.

                Dictionary<Location, int> g_score = new Dictionary<Location, int>(); //:= map with default value of Infinity
                g_score[start] = 0; // Cost from start along best known path.
                // Estimated total cost from start to goal through y.
                Dictionary<Location, int> f_score = new Dictionary<Location, int>(); //:= map with default value of Infinity
                f_score[start] = (int)start.DistanceSquared(goal); //heuristic_cost_estimate(start, goal)

                while (OpenSet.Count > 0)
                {
                    Location current = //the node in OpenSet having the lowest f_score[] value
                        OpenSet.Select(location => f_score.ContainsKey(location)
                        ? new KeyValuePair<Location, int>(location, f_score[location])
                        : new KeyValuePair<Location, int>(location, int.MaxValue))
                        .OrderBy(pair => pair.Value).First().Key;
                    if (current == goal)
                    { //reconstruct_path(Came_From, goal)
                        List<Location> total_path = new List<Location>(new[] { current });
                        while (Came_From.ContainsKey(current))
                        {
                            current = Came_From[current];
                            total_path.Add(current);
                        }
                        total_path.Reverse();
                        result = new Queue<Location>(total_path);
                    }
                    OpenSet.Remove(current);
                    ClosedSet.Add(current);
                    foreach (Location neighbor in GetAvailableMoves(world, current, allowUnsafe))
                    {
                        if (ClosedSet.Contains(neighbor))
                            continue;		// Ignore the neighbor which is already evaluated.
                        int tentative_g_score = g_score[current] + (int)current.DistanceSquared(neighbor); //dist_between(current,neighbor) // length of this path.
                        if (!OpenSet.Contains(neighbor))	// Discover a new node
                            OpenSet.Add(neighbor);
                        else if (tentative_g_score >= g_score[neighbor])
                            continue;		// This is not a better path.

                        // This path is the best until now. Record it!
                        Came_From[neighbor] = current;
                        g_score[neighbor] = tentative_g_score;
                        f_score[neighbor] = g_score[neighbor] + (int)neighbor.DistanceSquared(goal); //heuristic_cost_estimate(neighbor, goal)
                    }
                }
            }, TimeSpan.FromSeconds(5));

            return result;
        }
Пример #25
0
 private Entry PickOtherMethod(HashSet<Entry> except)
 {
     var except2 = new HashSet<string>(except.Select(e => e.OptUnitID));
     var randomUnit = Units[RandomGenerator.Random.Next(Units.Count)];
     while (except2.Contains(randomUnit.ID))
     {
         randomUnit = Units[RandomGenerator.Random.Next(Units.Count)];
     }
     return new Entry(randomUnit.ID, randomUnit.CreateContext());
 }
 public IMapa Przetwarzaj(HashSet<VoronoiEdge> krawedzieWoronoja)
 {
     _komorkiZVectorami = new Dictionary<Vector, IKomorka>();
      _rogiZVectorami = new Dictionary<Vector, IRog>();
      Mapa.Dwukrawedzie = krawedzieWoronoja.Select(woro => UtworzDwukrawedz(woro)).ToList();
      UstawKomorkomPrzylegle();
      UstawRogomBliskich();
      Mapa.ZakonczonoTworzenie = true;
      return Mapa;
 }
Пример #27
0
        protected override bool TickCore(RealmTime time)
        {
            var entities = GetNearestEntities(28, 0x0d5e)
                .Concat(GetNearestEntities(28, 0x0d60))
                .ToArray();
            if (entities.Length != 5)
                return true;

            var packets = new List<Packet>();
            var owner = Host.Self.Owner;
            if (entities.All(_ => _.ObjectType != 0x0d5e))
            {
                var players = new HashSet<Entity>();
                foreach (var i in entities.SelectMany(_ => (_ as Enemy).DamageCounter.GetPlayerData()).Where(i => i.Item1.Quest == Host))
                    players.Add(i.Item1);
                packets.AddRange(players.Select(i => new NotificationPacket
                {
                    ObjectId = i.Id, Color = new ARGB(0xFF00FF00), Text = "Quest Complete!"
                }));

                if (Host.Self.Owner is GameWorld)
                    (Host.Self.Owner as GameWorld).EnemyKilled(Host as Enemy,
                        (entities.Last() as Enemy).DamageCounter.Parent.LastHitter);
                Despawn.Instance.Tick(Host, time);
                foreach (var i in entities)
                    Die.Instance.Tick(i, time);
            }
            else
            {
                var hasCorpse = entities.Any(_ => _.ObjectType == 0x0d60);
                for (var i = 0; i < entities.Length; i++)
                    for (var j = i + 1; j < entities.Length; j++)
                    {
                        packets.Add(new ShowEffectPacket
                        {
                            TargetId = entities[i].Id,
                            EffectType = EffectType.Stream,
                            Color = new ARGB(hasCorpse ? 0xffffff00 : 0xffff0000),
                            PosA = new Position
                            {
                                X = entities[j].X,
                                Y = entities[j].Y
                            },
                            PosB = new Position
                            {
                                X = entities[i].X,
                                Y = entities[i].Y
                            }
                        });
                    }
            }
            owner.BroadcastPackets(packets, null);

            return true;
        }
        public static IEnumerable<VocabularyItem> GenerateVocabulary(InputSettings settings)
        {
            var words = new HashSet<string>();
            while (words.Count < settings.VocabularySize)
                words.Add(GenerateOneWord(settings.WordMaxLength));

            Func<int> genOccurrence = () => _st_random.Next(settings.WordMaxOccurrences + 1);
            return words
                   .Select(word => new VocabularyItem(word, genOccurrence()))
                   .ToArray();
        }
        public IList<HtmlCompletion> GetEntries(HtmlCompletionContext context)
        {
            var list = new HashSet<string>();

            if (context.Element != null && _inputTypes.Contains(context.Element.Name))
            {
                context.Document.HtmlEditorTree.RootNode.Accept(this, list);
            }

            return new List<HtmlCompletion>(list.Select(s => new SimpleHtmlCompletion(s, context.Session)));
        }
Пример #30
0
        private static void Print(NodeExt[] workers, int sec, HashSet <NodeExt> done)
        {
            const int width = -5;

            Console.Write($"{sec,width}");
            for (int i = 1; i <= workers.Length; i++)
            {
                Console.Write($"{workers[i - 1]?.Label ?? '.',width}");
            }
            Console.WriteLine(string.Join(", ", done?.Select(l => l.Label)));
        }
Пример #31
0
        public static string GetUsersString(HashSet<Guid> users)
        {
            var usersString = users.Select(GetUser)
                                   .Aggregate(string.Empty, (current, user) => current + (user.DisplayName + ", "));
            if (!string.IsNullOrEmpty(usersString))
            {
                usersString = usersString.Remove(usersString.Length - 2);
            }

            return usersString;
        }
Пример #32
0
        public void Setup(IActivityMonitor monitor)
        {
            using (monitor.OpenInfo($"Executing {_scripts.Count} script(s) on this Workstation."))
                using (var tempPS1 = new TemporaryFile("ps1"))
                {
                    bool             hasError         = false;
                    HashSet <EnvVar> currentVariables = null;
                    foreach (var o in _scripts)
                    {
                        if (hasError)
                        {
                            break;
                        }
                        switch (o)
                        {
                        case HashSet <EnvVar> v: currentVariables = v; break;

                        case ScriptLine script:
                        {
                            using (monitor.OpenTrace($"Executing script Type='{script.Type}', WorkingDir='{script.WorkingDir}', Arguments='{script.Arguments}', ContinueOnNonZeroExitCode='{script.ContinueOnNonZeroExitCode}'."))
                            {
                                monitor.Debug($"With EnvironmentVariables: {currentVariables?.Select( v => v.ToString() ).Concatenate()}.");
                                monitor.Debug(script.Script);
                                var variables = currentVariables?.Select(v => (v.Name, Environment.ExpandEnvironmentVariables(v.Value))).ToList()
                                                ?? new List <(string Name, string)>();
                                variables.Add(("CKLI_WORLD_MAPPING", _fileSystem.Root));

                                System.IO.File.WriteAllText(tempPS1.Path, script.Script);
                                if (!ProcessRunner.RunPowerShell(
                                        monitor,
                                        script.WorkingDir,
                                        tempPS1.Path,
                                        new[] { script.Arguments },
                                        stdErrorLevel: LogLevel.Warn,
                                        variables))
                                {
                                    hasError |= !script.ContinueOnNonZeroExitCode;
                                    if (!hasError)
                                    {
                                        monitor.Warn("ContinueOnNonZeroExitCode is true: error is ignored.");
                                    }
                                }
                            }
                            break;
                        }
                        }
                    }
                }
        }
Пример #33
0
        public IEnumerable <ResourceRecord> FindResponse(Question question)
        {
            HashSet <SerializableResourceRecord> cachedResourceRecords = null;

            var questionName = $"{question.Name} {question.Type}";

            if (cachedRecords.ContainsKey(questionName))
            {
                cachedResourceRecords = cachedRecords[questionName];
            }

            return(cachedResourceRecords?.Select(cachedRecordValue => new ResourceRecord(
                                                     cachedRecordValue.Name, cachedRecordValue.Data,
                                                     cachedRecordValue.Type, cachedRecordValue.Class,
                                                     cachedRecordValue.TimeToLive)));
        }
Пример #34
0
        private async Task FillDescriptionUsedEntities(StringBuilder strFile, HashSet <Guid> workflowsWithEntities, Dictionary <EntityReference, HashSet <Guid> > dictUsedEntities)
        {
            string message = string.Empty;

            if (dictUsedEntities.Count == 0)
            {
                strFile
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine(this._iWriteToOutput.WriteToOutput(_service.ConnectionData, "No used entities in workflows."))
                ;

                return;
            }

            strFile
            .AppendLine()
            .AppendLine()
            .AppendFormat(this._iWriteToOutput.WriteToOutput(_service.ConnectionData, "Used Entities {0}", dictUsedEntities.Count)).AppendLine()
            ;

            var orderedList = dictUsedEntities.Keys.OrderBy(i => i.LogicalName).ThenBy(i => i.Name).ThenBy(i => i.Id);

            {
                var table = new FormatTextTableHandler(
                    nameof(EntityReference.LogicalName)
                    , nameof(EntityReference.Name)
                    , nameof(EntityReference.Id)
                    , "Url"
                    );

                foreach (var item in orderedList)
                {
                    var values = new List <string>()
                    {
                        item.LogicalName, item.Name, item.Id.ToString()
                    };

                    var url = _service.ConnectionData.GetEntityInstanceUrl(item.LogicalName, item.Id);

                    if (!string.IsNullOrEmpty(url))
                    {
                        values.Add(url);
                    }

                    table.AddLine(values);
                }

                table.GetFormatedLines(false).ForEach(s => strFile.AppendLine(tabspacer + s));
            }

            strFile
            .AppendLine()
            .AppendLine()
            .AppendLine()
            .AppendLine(new string('-', 150))
            .AppendLine()
            .AppendLine()
            .AppendLine()
            ;

            strFile.AppendFormat("Used Entities Full Information {0}", dictUsedEntities.Count).AppendLine();

            foreach (var item in orderedList)
            {
                strFile
                .AppendLine()
                .AppendLine()
                .AppendLine()
                ;

                var table = new FormatTextTableHandler();
                table.SetHeader(nameof(EntityReference.LogicalName), nameof(EntityReference.Name), nameof(EntityReference.Id));

                table.AddLine(item.LogicalName, item.Name, item.Id.ToString());
                table.GetFormatedLines(false).ForEach(s => strFile.AppendLine(s));

                var url = _service.ConnectionData.GetEntityInstanceUrl(item.LogicalName, item.Id);

                if (!string.IsNullOrEmpty(url))
                {
                    strFile.AppendLine("Url:");
                    strFile.AppendLine(url);
                }

                strFile.AppendLine();

                try
                {
                    var entityMetadata = _descriptor.MetadataSource.GetEntityMetadata(item.LogicalName);

                    if (entityMetadata != null)
                    {
                        var repositoryGeneric = new GenericRepository(_service, entityMetadata);

                        var entity = await repositoryGeneric.GetEntityByIdAsync(item.Id, ColumnSetInstances.AllColumns);

                        if (entity != null)
                        {
                            var desc = await EntityDescriptionHandler.GetEntityDescriptionAsync(entity, _service.ConnectionData);

                            strFile
                            .AppendLine(desc)
                            .AppendLine()
                            .AppendLine()
                            ;
                        }
                        else
                        {
                            strFile
                            .AppendFormat("{0} With Id = {1} Does Not Exists", item.LogicalName, item.Id).AppendLine()
                            .AppendLine()
                            .AppendLine()
                            ;
                        }
                    }
                    else
                    {
                        strFile
                        .AppendFormat("Entity with name '{0}' Does Not Exists", item.LogicalName).AppendLine()
                        .AppendFormat("{0} With Id = {1} Does Not Exists", item.LogicalName, item.Id).AppendLine()
                        .AppendLine()
                        .AppendLine()
                        ;
                    }
                }
                catch (Exception ex)
                {
                    var description = DTEHelper.GetExceptionDescription(ex);

                    strFile
                    .AppendLine(description)
                    .AppendLine()
                    .AppendLine()
                    ;
                }

                message = await _descriptor.GetSolutionComponentsDescriptionAsync(dictUsedEntities[item].Select(id => new SolutionComponent()
                {
                    ObjectId      = id,
                    ComponentType = new OptionSetValue((int)ComponentType.Workflow),
                }));

                strFile
                .AppendLine("This entity Used By Workflows:")
                .AppendLine(message)
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine(new string('-', 150))
                ;
            }

            if (workflowsWithEntities.Any())
            {
                strFile
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine("These entities Used By Workflows:")
                ;

                message = await _descriptor.GetSolutionComponentsDescriptionAsync(workflowsWithEntities.Select(id => new SolutionComponent()
                {
                    ObjectId      = id,
                    ComponentType = new OptionSetValue((int)ComponentType.Workflow),
                }));

                strFile.AppendLine(message);
            }
        }
Пример #35
0
        internal static UdonBehaviour[] ConvertToUdonBehavioursInternal(UdonSharpBehaviour[] components, bool shouldUndo, bool showPrompts)
        {
            components = components.Distinct().ToArray();

            bool convertChildren = true;

            if (showPrompts)
            {
                HashSet <UdonSharpBehaviour> allReferencedBehaviours = new HashSet <UdonSharpBehaviour>();

                // Check if any of these need child component conversion
                foreach (UdonSharpBehaviour targetObject in components)
                {
                    HashSet <UdonSharpBehaviour> referencedBehaviours = new HashSet <UdonSharpBehaviour>();

                    CollectUdonSharpBehaviourReferencesInternal(targetObject, referencedBehaviours);

                    if (referencedBehaviours.Count > 1)
                    {
                        foreach (UdonSharpBehaviour referencedBehaviour in referencedBehaviours)
                        {
                            if (referencedBehaviour != targetObject)
                            {
                                allReferencedBehaviours.Add(referencedBehaviour);
                            }
                        }
                    }
                }

                if (allReferencedBehaviours.Count > 0)
                {
                    // This is an absolute mess, it should probably just be simplified to counting the number of affected behaviours
                    string referencedBehaviourStr;
                    if (allReferencedBehaviours.Count <= 2)
                    {
                        referencedBehaviourStr = string.Join(", ", allReferencedBehaviours.Select(e => $"'{e.ToString()}'"));
                    }
                    else
                    {
                        referencedBehaviourStr = $"{allReferencedBehaviours.Count} behaviours";
                    }

                    string rootBehaviourStr;

                    if (components.Length <= 2)
                    {
                        rootBehaviourStr = $"{string.Join(", ", components.Select(e => $"'{e.ToString()}'"))} reference{(components.Length == 1 ? "s" : "")} ";
                    }
                    else
                    {
                        rootBehaviourStr = $"{components.Length} behaviours to convert reference ";
                    }

                    string messageStr = $"{rootBehaviourStr}{referencedBehaviourStr}. Do you want to convert all referenced behaviours as well? If no, references to these behaviours will be set to null.";

                    int result = EditorUtility.DisplayDialogComplex("Dependent behaviours found", messageStr, "Yes", "Cancel", "No");

                    if (result == 2) // No
                    {
                        convertChildren = false;
                    }
                    else if (result == 1) // Cancel
                    {
                        return(null);
                    }
                }
            }

            if (shouldUndo)
            {
                Undo.RegisterCompleteObjectUndo(components, "Convert to UdonBehaviour");
            }

            List <UdonBehaviour> createdComponents = new List <UdonBehaviour>();

            foreach (UdonSharpBehaviour targetObject in components)
            {
                MonoScript            behaviourScript = MonoScript.FromMonoBehaviour(targetObject);
                UdonSharpProgramAsset programAsset    = GetUdonSharpProgramAsset(behaviourScript);

                if (programAsset == null)
                {
                    if (showPrompts)
                    {
                        string scriptPath      = AssetDatabase.GetAssetPath(behaviourScript);
                        string scriptDirectory = Path.GetDirectoryName(scriptPath);
                        string scriptFileName  = Path.GetFileNameWithoutExtension(scriptPath);

                        string assetPath = Path.Combine(scriptDirectory, $"{scriptFileName}.asset").Replace('\\', '/');

                        if (EditorUtility.DisplayDialog("No linked program asset", $"There was no UdonSharpProgramAsset found for '{behaviourScript.GetClass()}', do you want to create one?", "Ok", "Cancel"))
                        {
                            if (AssetDatabase.LoadAssetAtPath <UdonSharpProgramAsset>(assetPath) != null)
                            {
                                if (!EditorUtility.DisplayDialog("Existing file found", $"Asset file {assetPath} already exists, do you want to overwrite it?", "Ok", "Cancel"))
                                {
                                    continue;
                                }
                            }
                        }
                        else
                        {
                            continue;
                        }

                        programAsset = ScriptableObject.CreateInstance <UdonSharpProgramAsset>();
                        programAsset.sourceCsScript = behaviourScript;
                        AssetDatabase.CreateAsset(programAsset, assetPath);
                        AssetDatabase.SaveAssets();

                        UdonSharpProgramAsset.ClearProgramAssetCache();

                        programAsset.CompileCsProgram();

                        AssetDatabase.SaveAssets();

                        AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
                    }
                    else
                    {
                        Debug.LogWarning($"Could not convert U# behaviour '{behaviourScript.GetClass()}' on '{targetObject.gameObject}' because it does not have a corresponding UdonSharpProgramAsset");
                        continue;
                    }
                }

                GameObject targetGameObject = targetObject.gameObject;

                UdonBehaviour udonBehaviour = null;

                if (shouldUndo)
                {
                    udonBehaviour = Undo.AddComponent <UdonBehaviour>(targetGameObject);
                }
                else
                {
                    udonBehaviour = targetGameObject.AddComponent <UdonBehaviour>();
                }

                udonBehaviour.programSource = programAsset;

                //if (shouldUndo)
                //    Undo.RegisterCompleteObjectUndo(targetObject, "Convert C# to U# behaviour");

                UdonSharpEditorUtility.SetBackingUdonBehaviour(targetObject, udonBehaviour);

                try
                {
                    if (convertChildren)
                    {
                        UdonSharpEditorUtility.CopyProxyToUdon(targetObject, shouldUndo ? ProxySerializationPolicy.AllWithCreateUndo : ProxySerializationPolicy.All);
                    }
                    else
                    {
                        UdonSharpEditorUtility.CopyProxyToUdon(targetObject, ProxySerializationPolicy.RootOnly);
                    }
                }
                catch (System.Exception e)
                {
                    Debug.LogError(e);
                }

                UdonSharpEditorUtility.SetBackingUdonBehaviour(targetObject, null);

                System.Type behaviourType = targetObject.GetType();

                UdonSharpBehaviour newProxy;

                SetIgnoreEvents(true);

                try
                {
                    if (shouldUndo)
                    {
                        newProxy = (UdonSharpBehaviour)Undo.AddComponent(targetObject.gameObject, behaviourType);
                    }
                    else
                    {
                        newProxy = (UdonSharpBehaviour)targetObject.gameObject.AddComponent(behaviourType);
                    }

                    UdonSharpEditorUtility.SetBackingUdonBehaviour(newProxy, udonBehaviour);
                    try
                    {
                        UdonSharpEditorUtility.CopyUdonToProxy(newProxy);
                    }
                    catch (System.Exception e)
                    {
                        Debug.LogError(e);
                    }

                    if (shouldUndo)
                    {
                        Undo.DestroyObjectImmediate(targetObject);
                    }
                    else
                    {
                        Object.DestroyImmediate(targetObject);
                    }

                    newProxy.hideFlags = HideFlags.DontSaveInBuild |
#if !UDONSHARP_DEBUG
                                         HideFlags.HideInInspector |
#endif
                                         HideFlags.DontSaveInEditor;

                    newProxy.enabled = false;
                }
                finally
                {
                    SetIgnoreEvents(false);
                }

                createdComponents.Add(udonBehaviour);
            }

            return(createdComponents.ToArray());
        }
Пример #36
0
        /// <summary>
        /// Updates the selection due to a change to <see cref="SelectedIndex"/> or
        /// <see cref="SelectedItem"/>.
        /// </summary>
        /// <param name="index">The new selected index.</param>
        /// <param name="clear">Whether to clear existing selection.</param>
        private void UpdateSelectedItem(int index, bool clear = true)
        {
            var oldIndex = _selectedIndex;
            var oldItem  = _selectedItem;

            if (index == -1 && AlwaysSelected)
            {
                index = Math.Min(SelectedIndex, ItemCount - 1);
            }

            var           item        = ElementAt(Items, index);
            var           itemChanged = !Equals(item, oldItem);
            var           added       = -1;
            HashSet <int> removed     = null;

            _selectedIndex = index;
            _selectedItem  = item;

            if (oldIndex != index || itemChanged || _selection.HasMultiple)
            {
                if (clear)
                {
                    removed = _selection.Clear();
                }

                if (index != -1)
                {
                    if (_selection.Add(index))
                    {
                        added = index;
                    }

                    if (removed?.Contains(index) == true)
                    {
                        removed.Remove(index);
                        added = -1;
                    }
                }

                if (removed != null)
                {
                    foreach (var i in removed)
                    {
                        MarkItemSelected(i, false);
                    }
                }

                MarkItemSelected(index, true);

                RaisePropertyChanged(
                    SelectedIndexProperty,
                    oldIndex,
                    index);
            }

            if (itemChanged)
            {
                RaisePropertyChanged(
                    SelectedItemProperty,
                    oldItem,
                    item);
            }

            if (removed != null && index != -1)
            {
                removed.Remove(index);
            }

            if (added != -1 || removed?.Count > 0)
            {
                ResetSelectedItems();

                var e = new SelectionChangedEventArgs(
                    SelectionChangedEvent,
                    added != -1 ? new[] { ElementAt(Items, added) } : Array.Empty <object>(),
                    removed?.Select(x => ElementAt(Items, x)).ToArray() ?? Array.Empty <object>());
                RaiseEvent(e);
            }

            if (AutoScrollToSelectedItem && _selectedIndex != -1)
            {
                ScrollIntoView(_selectedItem);
            }
        }
Пример #37
0
        public static void AnalyzeResourcesAction()
        {
            var target = The.UI.GetActiveTarget();

            requestedPaths = new List <PathRequestRecord>();
            var crossRefReport           = new List <Tuple <string, List <string> > >();
            var missingResourcesReport   = new List <string>();
            var suspiciousTexturesReport = new List <string>();
            var bundles         = new HashSet <string>();
            var cookingRulesMap = CookingRulesBuilder.Build(The.Workspace.AssetFiles, target);

            AssetBundle.Current = new PackedAssetBundle(The.Workspace.GetBundlePath(target.Platform, CookingRulesBuilder.MainBundleName));
            foreach (var i in cookingRulesMap)
            {
                if (i.Key.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
                {
                    if (i.Value.TextureAtlas == null && i.Value.PVRFormat != PVRFormat.PVRTC4 && i.Value.PVRFormat != PVRFormat.PVRTC4_Forced)
                    {
                        suspiciousTexturesReport.Add(string.Format("{0}: {1}, atlas: none",
                                                                   i.Key, i.Value.PVRFormat));
                    }
                    if (i.Value.PVRFormat != PVRFormat.PVRTC4 && i.Value.PVRFormat != PVRFormat.PVRTC4_Forced && i.Value.PVRFormat != PVRFormat.PVRTC2)
                    {
                        int  w;
                        int  h;
                        bool hasAlpha;
                        TextureConverterUtils.GetPngFileInfo(
                            Path.Combine(The.Workspace.AssetsDirectory, i.Key), out w, out h,
                            out hasAlpha, false);
                        if (w >= 1024 || h >= 1024)
                        {
                            suspiciousTexturesReport.Add(string.Format("{3}: {0}, {1}, {2}, {4}, atlas: {5}",
                                                                       w, h, hasAlpha, i.Key, i.Value.PVRFormat, i.Value.TextureAtlas));
                        }
                    }
                }
                foreach (var bundle in i.Value.Bundles)
                {
                    if (bundle != CookingRulesBuilder.MainBundleName)
                    {
                        bundles.Add(bundle);
                    }
                }
            }
            AssetBundle.Current = new AggregateAssetBundle(bundles.Select(i => new PackedAssetBundle(The.Workspace.GetBundlePath(target.Platform, i))).ToArray());
            The.Workspace.AssetFiles.EnumerationFilter = (info) => {
                CookingRules rules;
                if (cookingRulesMap.TryGetValue(info.Path, out rules))
                {
                    if (rules.Ignore)
                    {
                        return(false);
                    }
                }
                return(true);
            };
            var usedImages = new HashSet <string>();
            var usedSounds = new HashSet <string>();

            foreach (var srcFileInfo in The.Workspace.AssetFiles.Enumerate(".tan"))
            {
                var srcPath = srcFileInfo.Path;
                using (var scene = (Frame)Node.CreateFromAssetBundle(srcPath)) {
                    foreach (var j in scene.Descendants)
                    {
                        var checkTexture = new Action <SerializableTexture>((Lime.SerializableTexture t) => {
                            if (t == null)
                            {
                                return;
                            }
                            string texPath;
                            try {
                                texPath = t.SerializationPath;
                            } catch {
                                return;
                            }
                            if (string.IsNullOrEmpty(texPath))
                            {
                                return;
                            }
                            if (texPath.Length == 2 && texPath[0] == '#')
                            {
                                switch (texPath[1])
                                {
                                case 'a':
                                case 'b':
                                case 'c':
                                case 'd':
                                case 'e':
                                case 'f':
                                case 'g':
                                    return;

                                default:
                                    suspiciousTexturesReport.Add(string.Format("wrong render target: {0}, {1}", texPath, j.ToString()));
                                    return;
                                }
                            }
                            string[] possiblePaths = new string[]
                            {
                                texPath + ".atlasPart",
                                texPath + ".pvr",
                                texPath + ".jpg",
                                texPath + ".png",
                                texPath + ".dds",
                                texPath + ".jpg",
                                texPath + ".png",
                            };
                            foreach (var tpp in possiblePaths)
                            {
                                if (Lime.AssetBundle.Current.FileExists(tpp))
                                {
                                    Lime.AssetBundle.Current.OpenFile(tpp);
                                    usedImages.Add(texPath.Replace('\\', '/'));
                                    return;
                                }
                            }
                            missingResourcesReport.Add(string.Format("texture missing:\n\ttexture path: {0}\n\tscene path: {1}\n",
                                                                     t.SerializationPath, j.ToString()));
                        });
                        var checkAnimators = new Action <Node>((Node n) => {
                            Lime.Animator <Lime.SerializableTexture> ta;
                            if (n.Animators.TryFind <SerializableTexture>("Texture", out ta))
                            {
                                foreach (var key in ta.ReadonlyKeys)
                                {
                                    checkTexture(key.Value);
                                }
                            }
                        });
                        if (j is Widget)
                        {
                            var w = j as Lime.Widget;
                            var serializableTexture = w.Texture as SerializableTexture;
                            if (serializableTexture != null)
                            {
                                checkTexture(serializableTexture);
                            }
                            checkAnimators(w);
                        }
                        else if (j is ParticleModifier)
                        {
                            var pm = j as Lime.ParticleModifier;
                            var serializableTexture = pm.Texture as SerializableTexture;
                            if (serializableTexture != null)
                            {
                                checkTexture(serializableTexture);
                            }
                            checkAnimators(pm);
                        }
                        else if (j is Lime.Audio)
                        {
                            var au   = j as Lime.Audio;
                            var path = au.Sample.SerializationPath + ".sound";
                            usedSounds.Add(au.Sample.SerializationPath.Replace('\\', '/'));
                            if (!Lime.AssetBundle.Current.FileExists(path))
                            {
                                missingResourcesReport.Add(string.Format("audio missing:\n\taudio path: {0}\n\tscene path: {1}\n",
                                                                         path, j.ToString()));
                            }
                            else
                            {
                                using (var tempStream = Lime.AssetBundle.Current.OpenFile(path)) {
                                }
                            }
                            // FIXME: should we check for audio:Sample animators too?
                        }
                    }
                }
                var reportList = new List <string>();
                foreach (var rpr in requestedPaths)
                {
                    string pattern = String.Format(@".*[/\\](.*)\.{0}", target.Platform.ToString());
                    string bundle  = "";
                    foreach (Match m in Regex.Matches(rpr.bundle, pattern, RegexOptions.IgnoreCase))
                    {
                        bundle = m.Groups[1].Value;
                    }
                    int index = Array.IndexOf(cookingRulesMap[srcPath].Bundles, bundle);
                    if (index == -1)
                    {
                        reportList.Add(string.Format("\t[{0}]=>[{2}]: {1}",
                                                     string.Join(", ", cookingRulesMap[srcPath].Bundles), rpr.path, bundle));
                    }
                }
                requestedPaths.Clear();
                if (reportList.Count > 0)
                {
                    crossRefReport.Add(new Tuple <string, List <string> >(srcPath, reportList));
                }
                Lime.Application.FreeScheduledActions();
            }

            var allImages = new Dictionary <string, bool>();

            foreach (var img in The.Workspace.AssetFiles.Enumerate(".png"))
            {
                var key = Path.Combine(Path.GetDirectoryName(img.Path), Path.GetFileNameWithoutExtension(img.Path)).Replace('\\', '/');
                if (!key.StartsWith("Fonts"))
                {
                    allImages[key] = false;
                }
            }
            foreach (var img in usedImages)
            {
                allImages[img] = true;
            }
            var unusedImages = allImages.Where(kv => !kv.Value).Select(kv => kv.Key).ToList();

            var allSounds = new Dictionary <string, bool>();

            foreach (var sound in The.Workspace.AssetFiles.Enumerate(".ogg"))
            {
                var key = Path.Combine(Path.GetDirectoryName(sound.Path), Path.GetFileNameWithoutExtension(sound.Path))
                          .Replace('\\', '/');
                allSounds[key] = false;
            }
            foreach (var sound in usedSounds)
            {
                allSounds[sound] = true;
            }
            var unusedSounds = allSounds.Where(kv => !kv.Value).Select(kv => kv.Key).ToList();

            Action <string> writeHeader = (s) => {
                int n0 = (80 - s.Length) / 2;
                int n1 = (80 - s.Length) % 2 == 0 ? n0 : n0 - 1;
                Console.WriteLine("\n" + new String('=', n0) + " " + s + " " + new String('=', n1));
            };

            writeHeader("Cross Bundle Dependencies");
            foreach (var scenePath in crossRefReport)
            {
                Console.WriteLine("\n" + scenePath.Item1);
                foreach (var refStr in scenePath.Item2)
                {
                    Console.WriteLine(refStr);
                }
            }
            writeHeader("Missing Resources");
            foreach (var s in missingResourcesReport)
            {
                Console.WriteLine(s);
            }
            writeHeader("Unused Images");
            foreach (var s in unusedImages)
            {
                Console.WriteLine(s);
            }
            writeHeader("Unused Sounds");
            foreach (var s in unusedSounds)
            {
                Console.WriteLine(s);
            }
            writeHeader("Suspicious Textures");
            foreach (var s in suspiciousTexturesReport)
            {
                Console.WriteLine(s);
            }
            The.Workspace.AssetFiles.EnumerationFilter = null;
        }
Пример #38
0
        public void All_symbols_in_card_texts_are_considered_in_code()
        {
            var alphabet = new HashSet <char>();

            var languages = new HashSet <string>(CardLocalization.GetAllLanguages(), Str.Comparer);

            languages.Remove("cn");
            languages.Remove("tw");
            languages.Remove("jp");
            languages.Remove("kr");

            foreach (var set in Repo.SetsByCode.Values)
            {
                alphabet.UnionWith(set.Name);
                alphabet.UnionWith(set.Code);
            }

            foreach (var card in Repo.Cards)
            {
                alphabet.UnionWithNullable(card.NameEn);
                alphabet.UnionWithNullable(card.TypeEn);
                alphabet.UnionWithNullable(card.FlavorEn);
                alphabet.UnionWithNullable(card.TextEn);
                alphabet.UnionWithNullable(card.Artist);

                foreach (string lang in languages)
                {
                    alphabet.UnionWithNullable(card.GetName(lang));
                    alphabet.UnionWithNullable(card.GetType(lang));
                    alphabet.UnionWithNullable(card.GetFlavor(lang));
                    alphabet.UnionWithNullable(card.GetText(lang));
                }
            }

            var chars = alphabet.Select(c => char.ToLower(c, Str.Culture)).Distinct().OrderBy(c => c).ToArray();

            Log.Debug(() => new string(chars));

            var specialChars = new List <char>();

            // ReSharper disable StringLiteralTypo
            var latin             = new HashSet <char>("abcdefghijklmnopqrstuvwxyz");
            var cyrillic          = new HashSet <char>("абвгдежзийклмнопрстуфхцчшщьыъэюя");
            var numbers           = new HashSet <char>("01234567890");
            var knownSpecialChars = new HashSet <char>("ºß林泰玄");

            // ReSharper restore StringLiteralTypo

            foreach (char c in chars)
            {
                if (latin.Contains(c))
                {
                    continue;
                }

                if (cyrillic.Contains(c))
                {
                    continue;
                }

                if (numbers.Contains(c))
                {
                    continue;
                }

                if (c == '\n')
                {
                    continue;
                }

                if (c == '\r')
                {
                    continue;
                }

                if (MtgAlphabet.Replacements.ContainsKey(c))
                {
                    continue;
                }

                if (MtgAlphabet.WordCharsSet.Contains(c))
                {
                    continue;
                }

                if (MtgAlphabet.LeftDelimitersSet.Contains(c))
                {
                    continue;
                }

                if (MtgAlphabet.RightDelimitersSet.Contains(c))
                {
                    continue;
                }

                if (MtgAlphabet.SingletoneWordChars.Contains(c))
                {
                    continue;
                }

                if (knownSpecialChars.Contains(c))
                {
                    continue;
                }

                specialChars.Add(c);
            }

            var specialCharsStr = new string(specialChars.ToArray());

            Log.Debug(specialCharsStr);

            var notConsideredChars = new string(specialCharsStr.Where(char.IsLetterOrDigit).ToArray());

            Assert.That(notConsideredChars, Is.Empty);
        }
Пример #39
0
        internal async Task OnPersonaState(string nickname = null, string avatarHash = null)
        {
            if ((DateTime.UtcNow < LastAnnouncementCheck.AddHours(MinAnnouncementCheckTTL)) && (ShouldSendHeartBeats || (LastHeartBeat == DateTime.MinValue)))
            {
                return;
            }

            await RequestsSemaphore.WaitAsync().ConfigureAwait(false);

            try {
                if ((DateTime.UtcNow < LastAnnouncementCheck.AddHours(MinAnnouncementCheckTTL)) && (ShouldSendHeartBeats || (LastHeartBeat == DateTime.MinValue)))
                {
                    return;
                }

                // Don't announce if we don't meet conditions
                bool?eligible = await IsEligibleForMatching().ConfigureAwait(false);

                if (!eligible.HasValue)
                {
                    // This is actually network failure, so we'll stop sending heartbeats but not record it as valid check
                    ShouldSendHeartBeats = false;

                    return;
                }

                if (!eligible.Value)
                {
                    LastAnnouncementCheck = DateTime.UtcNow;
                    ShouldSendHeartBeats  = false;

                    return;
                }

                string tradeToken = await Bot.ArchiHandler.GetTradeToken().ConfigureAwait(false);

                if (string.IsNullOrEmpty(tradeToken))
                {
                    // This is actually network failure, so we'll stop sending heartbeats but not record it as valid check
                    ShouldSendHeartBeats = false;

                    return;
                }

                HashSet <Steam.Asset.EType> acceptedMatchableTypes = Bot.BotConfig.MatchableTypes.Where(type => AcceptedMatchableTypes.Contains(type)).ToHashSet();

                if (acceptedMatchableTypes.Count == 0)
                {
                    Bot.ArchiLogger.LogNullError(nameof(acceptedMatchableTypes));
                    LastAnnouncementCheck = DateTime.UtcNow;
                    ShouldSendHeartBeats  = false;

                    return;
                }

                HashSet <Steam.Asset> inventory = await Bot.ArchiWebHandler.GetInventory(tradable : true, wantedTypes : acceptedMatchableTypes).ConfigureAwait(false);

                if (inventory == null)
                {
                    // This is actually inventory failure, so we'll stop sending heartbeats but not record it as valid check
                    ShouldSendHeartBeats = false;

                    return;
                }

                LastAnnouncementCheck = DateTime.UtcNow;

                // This is actual inventory
                if (inventory.Count < MinItemsCount)
                {
                    ShouldSendHeartBeats = false;

                    return;
                }

                const string request = URL + "/Api/Announce";

                Dictionary <string, string> data = new Dictionary <string, string>(9, StringComparer.Ordinal)
                {
                    { "AvatarHash", avatarHash ?? "" },
                    { "GamesCount", inventory.Select(item => item.RealAppID).Distinct().Count().ToString() },
                    { "Guid", ASF.GlobalDatabase.Guid.ToString("N") },
                    { "ItemsCount", inventory.Count.ToString() },
                    { "MatchableTypes", JsonConvert.SerializeObject(acceptedMatchableTypes) },
                    { "MatchEverything", Bot.BotConfig.TradingPreferences.HasFlag(BotConfig.ETradingPreferences.MatchEverything) ? "1" : "0" },
                    { "Nickname", nickname ?? "" },
                    { "SteamID", Bot.SteamID.ToString() },
                    { "TradeToken", tradeToken }
                };

                WebBrowser.BasicResponse response = await Bot.ArchiWebHandler.WebBrowser.UrlPost(request, data, requestOptions : WebBrowser.ERequestOptions.ReturnClientErrors).ConfigureAwait(false);

                if (response == null)
                {
                    return;
                }

                if (response.StatusCode.IsClientErrorCode())
                {
                    LastHeartBeat        = DateTime.MinValue;
                    ShouldSendHeartBeats = false;

                    return;
                }

                LastHeartBeat        = DateTime.UtcNow;
                ShouldSendHeartBeats = true;
            } finally {
                RequestsSemaphore.Release();
            }
        }
Пример #40
0
        /// <inheritdoc />
        public string DescribeExtent()
        {
            Contract.Assume(m_descriptors != null, "Init must have been called");

            return(string.Join(", ", m_descriptors.Select(descriptor => descriptor.Name)));
        }
        public IDirectoryContents GetDirectoryContents(string subpath)
        {
            if (subpath == null)
            {
                return(NotFoundDirectoryContents.Singleton);
            }

            var folder = NormalizePath(subpath);

            var entries = new List <IFileInfo>();

            if (folder == "")
            {
                entries.Add(new EmbeddedDirectoryInfo(Application.ModulesPath));
            }
            else if (folder == Application.ModulesPath)
            {
                entries.AddRange(Application.ModuleNames
                                 .Select(n => new EmbeddedDirectoryInfo(n)));
            }
            else if (folder == Application.ModulePath)
            {
                return(new PhysicalDirectoryContents(Application.Path));
            }
            else if (folder.StartsWith(Application.ModuleRoot, StringComparison.Ordinal))
            {
                var tokenizer = new StringTokenizer(folder, new char[] { '/' });
                if (tokenizer.Any(s => s == "Pages" || s == "Views"))
                {
                    var folderSubPath = folder.Substring(Application.ModuleRoot.Length);
                    return(new PhysicalDirectoryContents(Application.Root + folderSubPath));
                }
            }
            else if (folder.StartsWith(Application.ModulesRoot, StringComparison.Ordinal))
            {
                var path        = folder.Substring(Application.ModulesRoot.Length);
                var index       = path.IndexOf('/');
                var name        = index == -1 ? path : path.Substring(0, index);
                var assetPaths  = _environment.GetModule(name).AssetPaths;
                var folders     = new HashSet <string>(StringComparer.Ordinal);
                var folderSlash = folder + '/';

                foreach (var assetPath in assetPaths.Where(a => a.StartsWith(folderSlash, StringComparison.Ordinal)))
                {
                    var folderPath = assetPath.Substring(folderSlash.Length);
                    var pathIndex  = folderPath.IndexOf('/');
                    var isFilePath = pathIndex == -1;

                    if (isFilePath)
                    {
                        entries.Add(GetFileInfo(assetPath));
                    }
                    else
                    {
                        folders.Add(folderPath.Substring(0, pathIndex));
                    }
                }

                entries.AddRange(folders.Select(f => new EmbeddedDirectoryInfo(f)));
            }

            return(new EmbeddedDirectoryContents(entries));
        }
Пример #42
0
        Configuration.PackageReference[] GetWorkflowPackageDependencies(string[] fileNames)
        {
            var assemblies = new HashSet <Assembly>();

            foreach (var path in fileNames)
            {
                var metadata = WorkflowBuilder.ReadMetadata(path);
                using (var markupReader = new StringReader(metadata.WorkflowMarkup))
                    using (var reader = XmlReader.Create(markupReader))
                    {
                        reader.ReadToFollowing(WorkflowElementName);
                        using (var workflowReader = reader.ReadSubtree())
                        {
                            while (workflowReader.ReadToFollowing(ExpressionElementName))
                            {
                                if (!workflowReader.HasAttributes)
                                {
                                    continue;
                                }
                                if (workflowReader.GetAttribute(TypeAttributeName, XsiAttributeValue) == IncludeWorkflowTypeName)
                                {
                                    var includePath    = workflowReader.GetAttribute(PathAttributeName);
                                    var separatorIndex = includePath != null?includePath.IndexOf(AssemblySeparator) : -1;

                                    if (separatorIndex >= 0 && !Path.IsPathRooted(includePath))
                                    {
                                        var assemblyName = includePath.Split(new[] { AssemblySeparator }, 2)[0];
                                        if (!string.IsNullOrEmpty(assemblyName))
                                        {
                                            var assembly = Assembly.Load(assemblyName);
                                            assemblies.Add(assembly);
                                        }
                                    }
                                }
                            }
                        }
                    }

                assemblies.Add(typeof(WorkflowBuilder).Assembly);
                assemblies.AddRange(metadata.GetExtensionTypes().Select(type => type.Assembly));

                var layoutPath = Path.ChangeExtension(path, BonsaiExtension + LayoutExtension);
                if (File.Exists(layoutPath))
                {
                    var visualizerMap = new Lazy <IDictionary <string, Type> >(() =>
                                                                               TypeVisualizerLoader.GetTypeVisualizerDictionary(packageConfiguration)
                                                                               .Select(descriptor => descriptor.VisualizerTypeName).Distinct()
                                                                               .Select(typeName => Type.GetType(typeName, false))
                                                                               .Where(type => type != null)
                                                                               .ToDictionary(type => type.FullName)
                                                                               .Wait());

                    using (var reader = XmlReader.Create(layoutPath))
                    {
                        var layout = (VisualizerLayout)VisualizerLayout.Serializer.Deserialize(reader);
                        foreach (var settings in GetVisualizerSettings(layout))
                        {
                            Type type;
                            var  typeName = settings.VisualizerTypeName;
                            if (typeName == null)
                            {
                                continue;
                            }
                            if (visualizerMap.Value.TryGetValue(typeName, out type))
                            {
                                assemblies.Add(type.Assembly);
                            }
                        }
                    }
                }
            }

            var packageMap   = GetPackageReferenceMap(packageConfiguration);
            var dependencies = GetAssemblyPackageReferences(
                packageConfiguration,
                assemblies.Select(assembly => assembly.GetName().Name),
                packageMap);

            if (File.Exists(scriptEnvironment.ProjectFileName))
            {
                dependencies = dependencies.Concat(
                    from id in scriptEnvironment.GetPackageReferences()
                    where packageConfiguration.Packages.Contains(id)
                    select packageConfiguration.Packages[id]);
            }

            return(dependencies.ToArray());
        }
Пример #43
0
        static Weights()
        {
            try
            {
                _drawingTargets = new List <Targets.Item>();
                Items           = new HashSet <Item>
                {
                    new Item(
                        "killable", "AA Killable", 20, false,
                        t => t.Health < ObjectManager.Player.GetAutoAttackDamage(t, true) ? 10 : 0),
                    new Item(
                        "attack-damage", "Attack Damage", 15, false, delegate(Obj_AI_Hero t)
                    {
                        var ad           = t.FlatPhysicalDamageMod;
                        ad              += ad / 100 * (t.Crit * 100) * (t.HasItem(ItemData.Infinity_Edge.Id) ? 2.5f : 2f);
                        var averageArmor = GameObjects.AllyHeroes.Select(a => a.Armor).DefaultIfEmpty(0).Average() *
                                           t.PercentArmorPenetrationMod - t.FlatArmorPenetrationMod;
                        return((ad * (100 / (100 + (averageArmor > 0 ? averageArmor : 0)))) * t.AttackSpeedMod);
                    }),
                    new Item(
                        "ability-power", "Ability Power", 15, false, delegate(Obj_AI_Hero t)
                    {
                        var averageMr =
                            GameObjects.AllyHeroes.Select(a => a.SpellBlock).DefaultIfEmpty(0).Average() *
                            t.PercentMagicPenetrationMod - t.FlatMagicPenetrationMod;
                        return(t.FlatMagicDamageMod * (100 / (100 + (averageMr > 0 ? averageMr : 0))));
                    }),
                    new Item(
                        "low-resists", "Resists", 0, true,
                        t =>
                        ObjectManager.Player.FlatPhysicalDamageMod >= ObjectManager.Player.FlatMagicDamageMod
                                ? t.Armor
                                : t.SpellBlock),
                    new Item("low-health", "Health", 20, true, t => t.Health),
                    new Item(
                        "short-distance-player", "Distance to Player", 5, true, t => t.Distance(ObjectManager.Player)),
                    new Item("short-distance-cursor", "Distance to Cursor", 0, true, t => t.Distance(Game.CursorPos)),
                    new Item(
                        "crowd-control", "Crowd Control", 0, false, delegate(Obj_AI_Hero t)
                    {
                        var buffs =
                            t.Buffs.Where(
                                x =>
                                x.Type == BuffType.Charm || x.Type == BuffType.Knockback ||
                                x.Type == BuffType.Suppression || x.Type == BuffType.Fear ||
                                x.Type == BuffType.Taunt || x.Type == BuffType.Stun || x.Type == BuffType.Slow ||
                                x.Type == BuffType.Silence || x.Type == BuffType.Snare ||
                                x.Type == BuffType.Polymorph).ToList();
                        return(buffs.Any() ? buffs.Max(x => x.EndTime) + 1f : 0f);
                    }),
                    new Item(
                        "gold", "Acquired Gold", 0, false,
                        t =>
                        (t.MinionsKilled + t.NeutralMinionsKilled) * 22.35f + t.ChampionsKilled * 300f +
                        t.Assists * 95f),
                    new Item(
                        "team-focus", "Team Focus", 0, false,
                        t =>
                        Aggro.Items.Where(a => a.Value.Target.Hero.NetworkId == t.NetworkId)
                        .Select(a => a.Value.Value)
                        .DefaultIfEmpty(0)
                        .Sum()),
                    new Item(
                        "focus-me", "Focus Me", 0, false, delegate(Obj_AI_Hero t)
                    {
                        var entry = Aggro.GetSenderTargetEntry(t, ObjectManager.Player);
                        return(entry != null ? entry.Value + 1f : 0);
                    })
                };

                Average  = (float)Items.Select(w => w.Weight).DefaultIfEmpty(0).Average();
                MaxRange = 2000f;
            }
            catch (Exception ex)
            {
                Global.Logger.AddItem(new LogItem(ex));
            }
        }
Пример #44
0
        /// <inheritdoc/>
        protected override void ReParseImpl()
        {
            Stopwatch stopwatch = Stopwatch.StartNew();

            ITextSnapshot snapshot = TextBuffer.CurrentSnapshot;

            try
            {
                ITextDocument       textDocument  = TextDocument;
                string              fileName      = textDocument != null ? textDocument.FilePath : null;
                Document            document      = snapshot.GetOpenDocumentInCurrentContextWithChanges();
                SourceTextContainer textContainer = document != null?document.GetTextAsync().Result.Container : null;

                Project  project  = document != null ? document.Project : null;
                Solution solution = project.Solution;

                List <ITagSpan <IInheritanceTag> > tags = new List <ITagSpan <IInheritanceTag> >();

                if (document != null && !string.IsNullOrEmpty(fileName))
                {
                    SyntaxTree    syntaxTree    = document.GetSyntaxTreeAsync().Result;
                    SyntaxNode    syntaxRoot    = syntaxTree.GetRoot();
                    SemanticModel semanticModel = document.GetSemanticModelAsync().Result;
                    Compilation   compilation   = semanticModel.Compilation;

                    IDictionary <ISymbol, ISet <ISymbol> > interfaceImplementations = new Dictionary <ISymbol, ISet <ISymbol> >();

                    List <CSharpSyntaxNode> allMembers = new List <CSharpSyntaxNode>();
                    IEnumerable <BaseTypeDeclarationSyntax> typeNodes = syntaxRoot.DescendantNodes().OfType <BaseTypeDeclarationSyntax>();
                    foreach (var typeNode in typeNodes)
                    {
                        ISymbol symbol = semanticModel.GetDeclaredSymbol(typeNode);
                        if (symbol == null)
                        {
                            MarkDirty(true);
                            return;
                        }

                        INamedTypeSymbol typeSymbol = symbol as INamedTypeSymbol;
                        if (typeSymbol == null)
                        {
                            continue;
                        }

                        // get implemented interface symbols
                        foreach (INamedTypeSymbol namedTypeSymbol in typeSymbol.AllInterfaces)
                        {
                            foreach (ISymbol member in namedTypeSymbol.GetMembers())
                            {
                                ISymbol implementation = typeSymbol.FindImplementationForInterfaceMember(member);
                                if (implementation == null || !implementation.ContainingSymbol.Equals(typeSymbol))
                                {
                                    continue;
                                }

                                ISet <ISymbol> symbols;
                                if (!interfaceImplementations.TryGetValue(implementation, out symbols))
                                {
                                    symbols = new HashSet <ISymbol>();
                                    interfaceImplementations[implementation] = symbols;
                                }

                                symbols.Add(member);
                            }
                        }

                        TypeDeclarationSyntax typeDeclarationSyntax = typeNode as TypeDeclarationSyntax;
                        if (typeDeclarationSyntax != null)
                        {
                            allMembers.AddRange(typeDeclarationSyntax.Members);
                        }

                        if (typeSymbol.IsSealed)
                        {
                            continue;
                        }

                        // types which implement or derive from this type
                        ISet <ITypeSymbol> derivedTypes = new HashSet <ITypeSymbol>();
                        derivedTypes.UnionWith(FindDerivedClassesAsync.Value(typeSymbol, solution, null, CancellationToken.None).Result);
                        derivedTypes.UnionWith(FindDerivedInterfacesAsync.Value(typeSymbol, solution, null, CancellationToken.None).Result);
                        derivedTypes.UnionWith(FindImplementingTypesAsync.Value(typeSymbol, solution, null, CancellationToken.None).Result);

                        if (derivedTypes.Count == 0)
                        {
                            continue;
                        }

                        StringBuilder builder = new StringBuilder();
                        string        elementKindDisplayName =
                            "types";

                        builder.AppendLine("Derived " + elementKindDisplayName + ":");
                        foreach (var derived in derivedTypes)
                        {
                            builder.AppendLine("    " + derived.ToString());
                        }

                        SyntaxToken  identifier = typeNode.Accept(IdentifierSyntaxVisitor.Instance);
                        SnapshotSpan span       = new SnapshotSpan(snapshot, new Span(identifier.SpanStart, identifier.Span.Length));

                        InheritanceGlyph tag = typeSymbol.TypeKind == TypeKind.Interface ? InheritanceGlyph.HasImplementations : InheritanceGlyph.Overridden;

                        var targets = derivedTypes.Select(i => new TypeTarget(textContainer, i, solution));
                        tags.Add(new TagSpan <IInheritanceTag>(span, _tagFactory.CreateTag(tag, builder.ToString().TrimEnd(), targets)));
                    }

                    foreach (var eventFieldDeclarationSyntax in allMembers.OfType <EventFieldDeclarationSyntax>().ToArray())
                    {
                        allMembers.AddRange(eventFieldDeclarationSyntax.Declaration.Variables);
                    }

                    foreach (CSharpSyntaxNode memberNode in allMembers)
                    {
                        if (!(memberNode is MethodDeclarationSyntax) &&
                            !(memberNode is PropertyDeclarationSyntax) &&
                            !(memberNode is EventDeclarationSyntax) &&
                            !(memberNode is VariableDeclaratorSyntax))
                        {
                            continue;
                        }

                        ISymbol symbol = semanticModel.GetDeclaredSymbol(memberNode);
                        if (symbol == null)
                        {
                            MarkDirty(true);
                            return;
                        }

                        // members which this member implements
                        ISet <ISymbol> implementedMethods = new HashSet <ISymbol>();
                        if (!interfaceImplementations.TryGetValue(symbol, out implementedMethods))
                        {
                            implementedMethods = new HashSet <ISymbol>();
                        }

                        ISet <ISymbol> overriddenMethods = new HashSet <ISymbol>();

                        IMethodSymbol methodSymbol = symbol as IMethodSymbol;
                        if (methodSymbol != null)
                        {
                            // methods which this method overrides
                            for (IMethodSymbol current = methodSymbol.OverriddenMethod;
                                 current != null;
                                 current = current.OverriddenMethod)
                            {
                                overriddenMethods.Add(current);
                            }
                        }
                        else
                        {
                            IPropertySymbol propertySymbol = symbol as IPropertySymbol;
                            if (propertySymbol != null)
                            {
                                // properties which this property overrides
                                for (IPropertySymbol current = propertySymbol.OverriddenProperty;
                                     current != null;
                                     current = current.OverriddenProperty)
                                {
                                    overriddenMethods.Add(current);
                                }
                            }
                            else
                            {
                                IEventSymbol eventSymbol = symbol as IEventSymbol;
                                if (eventSymbol != null)
                                {
                                    // events which this event overrides
                                    for (IEventSymbol current = eventSymbol.OverriddenEvent;
                                         current != null;
                                         current = current.OverriddenEvent)
                                    {
                                        overriddenMethods.Add(current);
                                    }
                                }
                            }
                        }

                        ISet <ISymbol> implementingMethods = new HashSet <ISymbol>(SymbolFinder.FindImplementationsAsync(symbol, solution).Result);

                        ISet <ISymbol> overridingMethods = new HashSet <ISymbol>(SymbolFinder.FindOverridesAsync(symbol, solution).Result);

                        if (implementingMethods.Count == 0 && implementedMethods.Count == 0 && overriddenMethods.Count == 0 && overridingMethods.Count == 0)
                        {
                            continue;
                        }

                        StringBuilder builder = new StringBuilder();
                        string        elementKindDisplayName =
                            symbol is IPropertySymbol ? "properties" :
                            symbol is IEventSymbol ? "events" :
                            "methods";

                        if (implementedMethods.Count > 0)
                        {
                            builder.AppendLine("Implemented " + elementKindDisplayName + ":");
                            foreach (var methodId in implementedMethods)
                            {
                                builder.AppendLine("    " + methodId.ToString());
                            }
                        }

                        if (overriddenMethods.Count > 0)
                        {
                            builder.AppendLine("Overridden " + elementKindDisplayName + ":");
                            foreach (var methodId in overriddenMethods)
                            {
                                builder.AppendLine("    " + methodId.ToString());
                            }
                        }

                        if (implementingMethods.Count > 0)
                        {
                            builder.AppendLine("Implementing " + elementKindDisplayName + " in derived types:");
                            foreach (var methodId in implementingMethods)
                            {
                                builder.AppendLine("    " + methodId.ToString());
                            }
                        }

                        if (overridingMethods.Count > 0)
                        {
                            builder.AppendLine("Overriding " + elementKindDisplayName + " in derived types:");
                            foreach (var methodId in overridingMethods)
                            {
                                builder.AppendLine("    " + methodId.ToString());
                            }
                        }

                        SyntaxToken  identifier = memberNode.Accept(IdentifierSyntaxVisitor.Instance);
                        SnapshotSpan span       = new SnapshotSpan(snapshot, new Span(identifier.SpanStart, identifier.Span.Length));

                        InheritanceGlyph tag;
                        if (implementedMethods.Count > 0)
                        {
                            if (overridingMethods.Count > 0)
                            {
                                tag = InheritanceGlyph.ImplementsAndOverridden;
                            }
                            else if (implementingMethods.Count > 0)
                            {
                                tag = InheritanceGlyph.ImplementsAndHasImplementations;
                            }
                            else
                            {
                                tag = InheritanceGlyph.Implements;
                            }
                        }
                        else if (implementingMethods.Count > 0)
                        {
                            tag = InheritanceGlyph.HasImplementations;
                        }
                        else if (overriddenMethods.Count > 0)
                        {
                            if (overridingMethods.Count > 0)
                            {
                                tag = InheritanceGlyph.OverridesAndOverridden;
                            }
                            else
                            {
                                tag = InheritanceGlyph.Overrides;
                            }
                        }
                        else
                        {
                            tag = InheritanceGlyph.Overridden;
                        }

                        List <ISymbol> members = new List <ISymbol>();
                        members.AddRange(implementedMethods);
                        members.AddRange(overriddenMethods);
                        members.AddRange(implementingMethods);
                        members.AddRange(overridingMethods);

                        var targets = members.Select(i => new MemberTarget(textContainer, i, solution));
                        tags.Add(new TagSpan <IInheritanceTag>(span, _tagFactory.CreateTag(tag, builder.ToString().TrimEnd(), targets)));
                    }
                }

                InheritanceParseResultEventArgs result = new InheritanceParseResultEventArgs(snapshot, stopwatch.Elapsed, tags);
                OnParseComplete(result);
            }
            catch (InvalidOperationException)
            {
                MarkDirty(true);
                throw;
            }
        }
Пример #45
0
        private bool DPLLAlgo(CNF f, List <int> unchLit, Dictionary <int, int> totalModel)
        {
            //Console.WriteLine(f);
            CNF newf = f;

            do
            {
                if (newf.IsEmpty())
                {
                    model = new Dictionary <int, int>(totalModel);
                    return(true);
                }

                if (newf.HasEmptyConj())
                {
                    return(false);
                }


                var unionLit             = newf.GetUnionDisj();
                HashSet <Literal> newLit = new HashSet <Literal>();
                foreach (var u in unionLit)
                {
                    UnitPropagation(u, totalModel, newLit);
                }
                unchLit.RemoveAll(x => newLit.Select(y => y.Name).Contains(x));

                newf = EliminatePureLiterals(newf, newLit);
            } while (newf.GetUnionDisj().Count > 0);

            if (newf.IsEmpty())
            {
                model = new Dictionary <int, int>(totalModel);
                return(true);
            }

            if (newf.HasEmptyConj())
            {
                return(false);
            }

            var l = ChooseLiteral(unchLit);

            if (l.Name == 0) // нет невыьранных литералов
            {
                Console.WriteLine("no Lit: " + newf.Count);
                return(DPLLAlgo(newf, unchLit, totalModel));
            }
            else
            {
                newf.Add(l);
                if (DPLLAlgo(newf, new List <int>(unchLit), new Dictionary <int, int>(totalModel)))
                {
                    return(true);
                }
                else
                {
                    //Console.WriteLine("Back Track: " + l + " " + newf.Count + " UncLit:" + unchLit.Count);

                    newf.AddInversed(l);
                    return(DPLLAlgo(newf, unchLit, totalModel));
                }
            }
        }
Пример #46
0
        private List <ResolvedItem> ResolveItem(IdentifiableObject item,
                                                ComponentTemplate template, HashSet <IdentifiableObject> resolved, int recurseLevel)
        {
            List <ResolvedItem> toResolve = new List <ResolvedItem>();

            if (!ContinueRecursion(recurseLevel))
            {
                _log.Debug($"Reached max recusion level when trying to resolve item {item.Id}, skipping.");
                return(toResolve);
            }
            List <Component> components = new List <Component>();

            if (item is Page)
            {
                var page = (Page)item;
                if (resolved.Contains(page))
                {
                    return(toResolve);
                }
                components.AddRange(page.ComponentPresentations.Select(cp => cp.Component));
            }
            if (item is Component)
            {
                components.Add(item as Component);
            }
            if (components.Count <= 0)
            {
                return(toResolve);
            }
            var toProcess = new HashSet <Component>();
            var depths    = new Dictionary <Component, int>();

            for (int i = 0; i < components.Count; i++)
            { // note: avoiding recursive approach here so we can truely do infinite depth without stack overflows
                var c     = components[i];
                int depth = recurseLevel;
                if (depths.ContainsKey(c))
                {
                    depth = depths[c];
                }
                if (!ContinueRecursion(depth))
                {
                    continue;
                }
                if (toProcess.Contains(c))
                {
                    continue;
                }
                toProcess.Add(c);
                List <Component> linked = GatherLinkedComponents(c);
                foreach (var linkedComponent in linked)
                {
                    if (!ContinueRecursion(depth + 1))
                    {
                        break;
                    }
                    if (toProcess.Contains(linkedComponent))
                    {
                        continue;
                    }
                    components.Add(linkedComponent);
                    depths.Add(linkedComponent, depth + 1);
                }
            }
            toResolve.AddRange(toProcess.Select(
                                   component => ResolveComponent(component, template, resolved, recurseLevel)).Where(r => r != null));
            return(toResolve);
        }
Пример #47
0
        // Internal for testing
        // metadataPropertyKeys.Key = property name, metadataPropertyKeys.Value = property type
        internal static string Parse(string code, IEnumerable <KeyValuePair <string, string> > metadataPropertyKeys, IExecutionState executionState)
        {
            // Generate a syntax tree from the code
            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code, new CSharpParseOptions(kind: SourceCodeKind.Script), cancellationToken: executionState.CancellationToken);

            // "Lift" class and method declarations
            LiftingWalker liftingWalker = new LiftingWalker();

            liftingWalker.Visit(syntaxTree.GetRoot(executionState.CancellationToken));

            // Get the using statements
            HashSet <string> namespaces = new HashSet <string>(executionState.Namespaces);

            namespaces.Add("System");
            namespaces.Add("System.Collections");
            namespaces.Add("System.Collections.Generic");
            namespaces.Add("System.Linq");
            namespaces.Add("System.Text");
            namespaces.Add("Statiq.Core");
            string usingStatements = string.Join(Environment.NewLine, namespaces.Select(x => "using " + x + ";"));

            // Get the document metadata properties and add to the script host object,
            // but only if they don't conflict with properties from ScriptBase
            string metadataProperties =
                metadataPropertyKeys == null
                    ? string.Empty
                    : string.Join(
                    Environment.NewLine,
                    metadataPropertyKeys
                    .Where(x => !string.IsNullOrWhiteSpace(x.Key) && !ReservedPropertyNames.Contains(x.Key))
                    .Select(x => $"public {x.Value ?? "object"} {GetValidIdentifier(x.Key)} => Metadata.Get<{x.Value ?? "object"}>(\"{x.Key}\");"));

            // Determine if we need a return statement
            string preScript  = null;
            string postScript = null;

            if (!code.Contains(';'))
            {
                // This is an expression, so add the return before and semicolon after
                preScript  = "return";
                postScript = ";";
            }
            else if (!liftingWalker.HasReturnStatement)
            {
                // Includes multiple statements but no return so add one
                postScript = "return null;";
            }

            // Get call signatures for IExecutionState and IMetadata
            string executionStateCalls = string.Join(
                Environment.NewLine,
                ReflectionHelper.GetCallSignatures(typeof(IExecutionState), nameof(ScriptBase.ExecutionState)));
            string metadataCalls = string.Join(
                Environment.NewLine,
                ReflectionHelper.GetCallSignatures(typeof(IMetadata), nameof(ScriptBase.Metadata)));

            // Return the fully parsed script
            return
                ($@"{usingStatements}
{liftingWalker.UsingDirectives}
public class {ScriptClassName} : ScriptBase, IExecutionState, IMetadata
{{
public {ScriptClassName}(IMetadata metadata, IExecutionState executionState, IExecutionContext executionContext)
    : base(metadata, executionState, executionContext) {{ }}
public override async Task<object> EvaluateAsync()
{{
await Task.CompletedTask;
{preScript}
{liftingWalker.ScriptCode}
{postScript}
}}
{liftingWalker.MethodDeclarations}
{metadataProperties}
{executionStateCalls}
{metadataCalls}
}}
{liftingWalker.TypeDeclarations}
public static class ScriptExtensionMethods
{{
{liftingWalker.ExtensionMethodDeclarations}
}}");
        }
Пример #48
0
        private static ReferenceInfo?BuildReference(
            ProjectAssetsFile projectAssets,
            string referenceName,
            bool treatAsUsed)
        {
            var dependencyNames       = new HashSet <string>();
            var compilationAssemblies = ImmutableArray.CreateBuilder <string>();
            var referenceType         = ReferenceType.Unknown;
            var itemSpecification     = referenceName;

            var packagesPath = projectAssets.Project?.Restore?.PackagesPath ?? string.Empty;

            RoslynDebug.AssertNotNull(projectAssets.Targets);
            RoslynDebug.AssertNotNull(projectAssets.Libraries);

            foreach (var target in projectAssets.Targets.Values)
            {
                var key = target.Keys.FirstOrDefault(library => library.Split('/')[0] == referenceName);
                if (key is null ||
                    !projectAssets.Libraries.TryGetValue(key, out var library))
                {
                    continue;
                }

                var targetLibrary = target[key];

                referenceType = targetLibrary.Type switch
                {
                    "package" => ReferenceType.Package,
                    "project" => ReferenceType.Project,
                    _ => ReferenceType.Assembly
                };

                if (referenceType == ReferenceType.Project &&
                    library.Path is not null)
                {
                    // Project references are keyed by their filename but the
                    // item specification should be the path to the project file
                    // with Windows-style directory separators.
                    itemSpecification = library.Path.Replace('/', '\\');
                }

                if (targetLibrary.Dependencies != null)
                {
                    dependencyNames.AddRange(targetLibrary.Dependencies.Keys);
                }

                if (targetLibrary.Compile != null)
                {
                    compilationAssemblies.AddRange(targetLibrary.Compile.Keys
                                                   .Where(assemblyPath => !assemblyPath.EndsWith(NuGetEmptyFileName))
                                                   .Select(assemblyPath => Path.GetFullPath(Path.Combine(packagesPath, library.Path, assemblyPath))));
                }
            }

            if (referenceType == ReferenceType.Unknown)
            {
                return(null);
            }

            var dependencies = dependencyNames
                               .Select(dependency => BuildReference(projectAssets, dependency, treatAsUsed: false))
                               .WhereNotNull()
                               .ToImmutableArray();

            return(new ReferenceInfo(referenceType, itemSpecification, treatAsUsed, compilationAssemblies.ToImmutable(), dependencies));
        }
    }
Пример #49
0
        public Tuple <HashSet <int>, HashSet <int> > LargestCliqueHeuristic(bool modeVerticesOnly)
        {
            var path          = @"C:\Users\User\Documents\log.txt";
            var vertexDegrees = VertexDegrees();
            var list          = new LinkedList <CliqueNode>();
            var queue         = new FastPriorityQueue <CliqueNode>(Size);

            for (var i = 0; i < vertexDegrees.Length; i++)
            {
                var cliqueNode = new CliqueNode(i, vertexDegrees[i]);
                list.AddLast(cliqueNode);
                queue.Enqueue(cliqueNode, cliqueNode.VertexSmallestDegree);
            }
            var unmergable = new bool[Size, Size];
            var flag       = true;

            while (true)
            {
                CliqueNode node1 = queue.Dequeue(), node2 = null;
                var        unmergableWithNode1 = new LinkedList <CliqueNode>();
                do
                {
                    if (node2 != null)
                    {
                        unmergableWithNode1.AddLast(node2);
                    }
                    if (queue.Count <= 0)
                    {
                        // node1 is no more mergable with any of the elements in the queue
                        foreach (var node in unmergableWithNode1)
                        {
                            queue.Enqueue(node, node.VertexSmallestDegree);
                        }
                        unmergableWithNode1.Clear();
                        if (queue.Count <= 1)
                        {
                            flag = false;
                            break;
                        }
                        node1 = queue.Dequeue();
                    }
                    node2 = queue.Dequeue();
                } while (unmergable[node1.CliqueNumber, node2.CliqueNumber]);
                if (!flag)
                {
                    break;
                }
                foreach (var node in unmergableWithNode1)
                {
                    queue.Enqueue(node, node.VertexSmallestDegree);
                }
                var mergable = true;
                foreach (var node1Vertex in node1.Vertices)
                {
                    foreach (var node2Vertex in node2.Vertices)
                    {
                        if (!this.IsEdge(node1Vertex, node2Vertex))
                        {
                            queue.Enqueue(node1, node1.VertexSmallestDegree);
                            queue.Enqueue(node2, node2.VertexSmallestDegree);
                            unmergable[node1.CliqueNumber, node2.CliqueNumber]     =
                                unmergable[node2.CliqueNumber, node1.CliqueNumber] = true;
                            mergable = false;
                            break;
                        }
                    }
                    if (!mergable)
                    {
                        break;
                    }
                }
                if (mergable)
                {
                    using (var sw = File.AppendText(path))
                    {
                        sw.WriteLine($"{node1.CliqueNumber}-{node2.CliqueNumber}");
                    }

                    node1.Vertices.UnionWith(node2.Vertices);
                    node1.VertexSmallestDegree = Math.Min(node1.VertexSmallestDegree, node2.VertexSmallestDegree);
                    for (var i = 0; i < Size; i++)
                    {
                        unmergable[node1.CliqueNumber, i] |= unmergable[node2.CliqueNumber, i];
                    }
                    queue.Enqueue(node1, node1.VertexSmallestDegree);
                }
            }
            HashSet <int> clique = null;

            if (modeVerticesOnly)
            {
                foreach (var cliqueNode in list)
                {
                    if (clique == null || cliqueNode.Vertices.Count > clique.Count)
                    {
                        clique = cliqueNode.Vertices;
                    }
                }
            }
            else
            {
                var gEdgeCount = 0;
                foreach (var cliqueNode in list)
                {
                    if (clique == null)
                    {
                        clique = cliqueNode.Vertices;
                    }
                    else
                    {
                        var newGVertices  = new HashSet <int>(cliqueNode.Vertices.Select(FirstGraphVertex));
                        var newGEdgeCount = _g.Subgraph(newGVertices).EdgeCount;
                        if (newGVertices.Count + newGEdgeCount > clique.Count + gEdgeCount)
                        {
                            clique     = cliqueNode.Vertices;
                            gEdgeCount = newGEdgeCount;
                        }
                    }
                }
            }

            var gVertices = new HashSet <int>(clique?.Select(FirstGraphVertex));
            var hVertices = new HashSet <int>(clique?.Select(SecondGraphVertex));

            return(new Tuple <HashSet <int>, HashSet <int> >(gVertices, hVertices));
        }
Пример #50
0
        /// <summary>
        /// Fills in the set Jira sprint issues according to the defined rules.
        /// </summary>
        public async Task PrioritizeBacklogAsync()
        {
            // Retrieves the issues in the sprint asynchroniously.
            Task <JiraSeachResults> getBacklogIssues = GetUnclosedSprintIssuesAsync();

            // Awaits for retrieving the sprint issues.
            JiraSeachResults backlogIssues = await getBacklogIssues;

            if (backlogIssues == null)
            {
                Writer.WriteLine($"There are no issues in sprint {SprintId}.");
                MailSender.SendMail(EmailFrom, EmailTo, EmailFromPassword, "CTC prioritization feels kinda weird", $"The tool hasn't found any issue in the given sprint (ID: {SprintId}). Is this really the sprint you want to prioritize?");
                return;
            }
            Writer.WriteLine($"There are {backlogIssues.Count} issues to prioritize in sprint {SprintId}.");
            Writer.WriteLine();

            // Gets a non-duplicated list of epics
            HashSet <string> epicKeys = new HashSet <string>();

            foreach (JiraIssue issue in backlogIssues.Results)
            {
                if (issue.Fields.Epic != null && issue.Fields.Epic.StartsWith("CTC-"))
                {
                    epicKeys.Add(issue.Fields.Epic);
                }
            }

            // Retrieves the issues' epics asynchronously.
            var epicIssues = epicKeys.Select(epic => GetEpic(epic)).ToList();

            // Waits for the tasks creating pages and count their successfulness.
            JiraIssue[] epics = await Task.WhenAll(epicIssues);


            // Prioritizes the issues asynchronously.
            var prioritizedIssues = backlogIssues.Results.Select(issue => ProcessIssueAsync(issue, issue.Fields.Epic != null && issue.Fields.Epic.StartsWith("CTC-") ? epics.Where(epic => epic.Key == issue.Fields.Epic).FirstOrDefault() : null)).ToList();

            // Waits for the tasks creating pages and count their successfulness.
            Tuple <int, string>[] prioritizedResults = await Task.WhenAll(prioritizedIssues);

            /*
             * // For debugging async-await
             * List<String> prioritizedIssues = new List<string>();
             * foreach (JiraIssue issue in backlogIssues.Results)
             * {
             *  prioritizedIssues.Add(await ProcessIssueAsync(issue));
             * }
             * string[] prioritizedResults = prioritizedIssues.ToArray();
             */

            // Write out the final results.
            int failedIssueNumber = prioritizedResults.Where(x => x.Item1 == 0).Count();

            Writer.WriteLine();
            Writer.WriteLine("------------------------");
            Writer.WriteLine("FINAL RESULTS");
            Writer.WriteLine($"Number of all issues: {backlogIssues.Count}");
            Writer.WriteLine();
            Writer.WriteLine($"Number of updated issues: {prioritizedResults.Where(x => x.Item1 == 1).Count()}");
            Writer.WriteLine($"Number of issues that didn't need to be updated: {prioritizedResults.Where(x => x.Item1 == 2).Count()}");
            Writer.WriteLine($"Number of issues whose update failed: {failedIssueNumber}");

            // If there were any failures, they are listed and a notification email is sent.
            if (failedIssueNumber > 0)
            {
                StringBuilder failedIssues = new StringBuilder();
                foreach (Tuple <int, string> t in prioritizedResults)
                {
                    if (t.Item1 == 0)
                    {
                        failedIssues.AppendLine(t.Item2);
                        failedIssues.AppendLine();
                    }
                }

                Writer.WriteLine("");
                Writer.WriteLine("Issues whose update failed:");
                Writer.WriteLine(failedIssues.ToString());

                MailSender.SendMail(EmailFrom, EmailTo, EmailFromPassword, "CTC prioritization ended with errors", $"Prioritization ended with the following errors in updates: {failedIssues.ToString()}");
            }
        }
Пример #51
0
        public void Synchronize()
        {
            Task.Run(async() =>
            {
                try
                {
                    if (Interlocked.Read(ref _runner) >= 2)
                    {
                        return;
                    }

                    Interlocked.Increment(ref _runner);
                    while (Interlocked.Read(ref _runner) != 1)
                    {
                        await Task.Delay(100);
                    }

                    if (Interlocked.Read(ref _running) >= 2)
                    {
                        return;
                    }

                    try
                    {
                        Interlocked.Exchange(ref _running, 1);

                        var isImmature    = false;                      // The last 100 blocks are reorgable. (Assume it is mature at first.)
                        SyncInfo syncInfo = null;
                        while (IsRunning)
                        {
                            try
                            {
                                // If we didn't yet initialized syncInfo, do so.
                                if (syncInfo is null)
                                {
                                    syncInfo = await GetSyncInfoAsync();
                                }

                                Height heightToRequest = StartingHeight;
                                uint256 currentHash    = null;
                                using (await IndexLock.LockAsync())
                                {
                                    if (Index.Count != 0)
                                    {
                                        var lastIndex   = Index.Last();
                                        heightToRequest = lastIndex.BlockHeight + 1;
                                        currentHash     = lastIndex.BlockHash;
                                    }
                                }

                                // If not synchronized or already 5 min passed since last update, get the latest blockchain info.
                                if (!syncInfo.IsCoreSynchornized || (syncInfo.BlockchainInfoUpdated - DateTimeOffset.UtcNow) > TimeSpan.FromMinutes(5))
                                {
                                    syncInfo = await GetSyncInfoAsync();
                                }

                                if (syncInfo.BlockCount - heightToRequest <= 100)
                                {
                                    // Both Wasabi and our Core node is in sync. Start doing stuff through P2P from now on.
                                    if (syncInfo.IsCoreSynchornized && syncInfo.BlockCount == heightToRequest - 1)
                                    {
                                        syncInfo = await GetSyncInfoAsync();
                                        // Double it to make sure not to accidentally miss any notification.
                                        if (syncInfo.IsCoreSynchornized && syncInfo.BlockCount == heightToRequest - 1)
                                        {
                                            // Mark the process notstarted, so it can be started again and finally block can mark it is stopped.
                                            Interlocked.Exchange(ref _running, 0);
                                            return;
                                        }
                                    }

                                    // Mark the synchronizing process is working with immature blocks from now on.
                                    isImmature = true;
                                }

                                Block block = await RpcClient.GetBlockAsync(heightToRequest);

                                // Reorg check, except if we're requesting the starting height, because then the "currentHash" wouldn't exist.

                                if (heightToRequest != StartingHeight && currentHash != block.Header.HashPrevBlock)
                                {
                                    // Reorg can happen only when immature. (If it'd not be immature, that'd be a huge issue.)
                                    if (isImmature)
                                    {
                                        await ReorgOneAsync();
                                    }
                                    else
                                    {
                                        Logger.LogCritical <IndexBuilderService>("This is something serious! Over 100 block reorg is noticed! We cannot handle that!");
                                    }

                                    // Skip the current block.
                                    continue;
                                }

                                if (isImmature)
                                {
                                    PrepareBech32UtxoSetHistory();
                                }

                                var scripts = new HashSet <Script>();

                                foreach (var tx in block.Transactions)
                                {
                                    // If stop was requested return.
                                    // Because this tx iteration can take even minutes
                                    // It doesn't need to be accessed with a thread safe fasion with Interlocked through IsRunning, this may have some performance benefit
                                    if (_running != 1)
                                    {
                                        return;
                                    }

                                    for (int i = 0; i < tx.Outputs.Count; i++)
                                    {
                                        var output = tx.Outputs[i];
                                        if (!output.ScriptPubKey.IsPayToScriptHash && output.ScriptPubKey.IsWitness)
                                        {
                                            var outpoint = new OutPoint(tx.GetHash(), i);
                                            Bech32UtxoSet.Add(outpoint, output.ScriptPubKey);
                                            if (isImmature)
                                            {
                                                Bech32UtxoSetHistory.Last().StoreAction(ActionHistoryHelper.Operation.Add, outpoint, output.ScriptPubKey);
                                            }
                                            scripts.Add(output.ScriptPubKey);
                                        }
                                    }

                                    foreach (var input in tx.Inputs)
                                    {
                                        OutPoint prevOut = input.PrevOut;
                                        if (Bech32UtxoSet.TryGetValue(prevOut, out Script foundScript))
                                        {
                                            Bech32UtxoSet.Remove(prevOut);
                                            if (isImmature)
                                            {
                                                Bech32UtxoSetHistory.Last().StoreAction(ActionHistoryHelper.Operation.Remove, prevOut, foundScript);
                                            }
                                            scripts.Add(foundScript);
                                        }
                                    }
                                }

                                GolombRiceFilter filter = null;
                                if (scripts.Count != 0)
                                {
                                    filter = new GolombRiceFilterBuilder()
                                             .SetKey(block.GetHash())
                                             .SetP(20)
                                             .SetM(1 << 20)
                                             .AddEntries(scripts.Select(x => x.ToCompressedBytes()))
                                             .Build();
                                }

                                var filterModel = new FilterModel
                                {
                                    BlockHash   = block.GetHash(),
                                    BlockHeight = heightToRequest,
                                    Filter      = filter
                                };

                                await File.AppendAllLinesAsync(IndexFilePath, new[] { filterModel.ToHeightlessLine() });
                                using (await IndexLock.LockAsync())
                                {
                                    Index.Add(filterModel);
                                }
                                if (File.Exists(Bech32UtxoSetFilePath))
                                {
                                    File.Delete(Bech32UtxoSetFilePath);
                                }
                                await File.WriteAllLinesAsync(Bech32UtxoSetFilePath, Bech32UtxoSet
                                                              .Select(entry => entry.Key.Hash + ":" + entry.Key.N + ":" + ByteHelpers.ToHex(entry.Value.ToCompressedBytes())));

                                // If not close to the tip, just log debug.
                                // Use height.Value instead of simply height, because it cannot be negative height.
                                if (syncInfo.BlockCount - heightToRequest.Value <= 3 || heightToRequest % 100 == 0)
                                {
                                    Logger.LogInfo <IndexBuilderService>($"Created filter for block: {heightToRequest}.");
                                }
                                else
                                {
                                    Logger.LogDebug <IndexBuilderService>($"Created filter for block: {heightToRequest}.");
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.LogDebug <IndexBuilderService>(ex);
                            }
                        }
                    }
                    finally
                    {
                        Interlocked.CompareExchange(ref _running, 3, 2);                         // If IsStopping, make it stopped.
                        Interlocked.Decrement(ref _runner);
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogError <IndexBuilderService>($"Synchronization attempt failed to start: {ex}");
                }
            });
        }
Пример #52
0
        /// <summary>
        /// This function returns a changeset based on the selections of the user.
        /// Currently returns null if a conflict is detected.
        /// </summary>
        /// <param name="registry"></param>
        /// <param name="changeSet"></param>
        /// <param name="installer">A module installer for the current KSP install</param>
        /// <param name="version">The version of the current KSP install</param>
        public IEnumerable <ModChange> ComputeChangeSetFromModList(
            IRegistryQuerier registry, HashSet <ModChange> changeSet, ModuleInstaller installer,
            KspVersionCriteria version)
        {
            var modules_to_install = new HashSet <CkanModule>();
            var modules_to_remove  = new HashSet <CkanModule>();

            foreach (var change in changeSet)
            {
                switch (change.ChangeType)
                {
                case GUIModChangeType.None:
                    break;

                case GUIModChangeType.Update:
                case GUIModChangeType.Install:
                    modules_to_install.Add(change.Mod);
                    break;

                case GUIModChangeType.Remove:
                    modules_to_remove.Add(change.Mod);
                    break;

                case GUIModChangeType.Replace:
                    ModuleReplacement repl = registry.GetReplacement(change.Mod, version);
                    if (repl != null)
                    {
                        modules_to_remove.Add(repl.ToReplace);
                        modules_to_install.Add(repl.ReplaceWith);
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            var installed_modules =
                registry.InstalledModules.Select(imod => imod.Module).ToDictionary(mod => mod.identifier, mod => mod);

            foreach (var dependency in registry.FindReverseDependencies(
                         modules_to_remove
                         .Select(mod => mod.identifier)
                         .Except(modules_to_install.Select(m => m.identifier))
                         ))
            {
                //TODO This would be a good place to have an event that alters the row's graphics to show it will be removed
                CkanModule depMod;
                if (installed_modules.TryGetValue(dependency, out depMod))
                {
                    CkanModule module_by_version = registry.GetModuleByVersion(depMod.identifier,
                                                                               depMod.version)
                                                   ?? registry.InstalledModule(dependency).Module;
                    changeSet.Add(new ModChange(module_by_version, GUIModChangeType.Remove, null));
                    modules_to_remove.Add(module_by_version);
                }
            }
            foreach (var im in registry.FindRemovableAutoInstalled(
                         registry.InstalledModules.Where(im => !modules_to_remove.Any(m => m.identifier == im.identifier) || modules_to_install.Any(m => m.identifier == im.identifier))
                         ))
            {
                changeSet.Add(new ModChange(im.Module, GUIModChangeType.Remove, new SelectionReason.NoLongerUsed()));
                modules_to_remove.Add(im.Module);
            }

            // Get as many dependencies as we can, but leave decisions and prompts for installation time
            RelationshipResolverOptions opts = RelationshipResolver.DependsOnlyOpts();

            opts.without_toomanyprovides_kraken = true;
            opts.without_enforce_consistency    = true;

            var resolver = new RelationshipResolver(
                modules_to_install,
                modules_to_remove,
                opts, registry, version);

            changeSet.UnionWith(
                resolver.ModList()
                .Select(m => new ModChange(m, GUIModChangeType.Install, resolver.ReasonFor(m))));

            return(changeSet);
        }
Пример #53
0
        public void OnProductListFetched(AssetStorePurchases purchases, bool fetchDetailsCalled)
        {
            var isSet = purchases.queryArgs?.isFilterSet == true;

            if (isSet && !filters.Equals(purchases.queryArgs))
            {
                return;
            }

            if (purchases.startIndex > 0 && numTotalItems != purchases.total)
            {
                // if a new page has arrived but the total has changed or the searchText has changed, do a re-fetch
                var queryArgs = BuildQueryFromFilter((int)numCurrentItems, purchases.startIndex + purchases.list.Count);
                m_AssetStoreClient.ListPurchases(queryArgs);
                return;
            }

            var oldPackageIds = new HashSet <string>(m_VisualStateList.Select(v => v.packageUniqueId));
            var newPackageIds = purchases.productIds.Select(id => id.ToString()).ToList();

            if (purchases.startIndex == 0)
            {
                // override the result if the new list starts from index 0 (meaning it's a refresh)
                m_VisualStateList.Rebuild(newPackageIds);
                m_VisualStateList.ClearExtraItems();
                m_VisualStateList.SetTotal(purchases.total);
            }
            else if (purchases.startIndex == numCurrentItems)
            {
                // append the result if it is the next page
                m_VisualStateList.AddRange(newPackageIds);
                m_VisualStateList.ClearExtraItems();
            }
            else
            {
                // if the content is neither starting from zero or next page, we simply discard it
                return;
            }

            if (!fetchDetailsCalled && purchases.list.Any())
            {
                m_AssetStoreClient.FetchDetails(purchases.productIds);
            }

            // only try to rebuild the list immediately if we are already on the `AssetStore` tab.
            // if not we'll just wait for tab switch which will trigger the rebuild as well
            if (m_PackageFiltering.currentFilterTab == PackageFilterTab.AssetStore)
            {
                HashSet <string> removed = null;
                List <string>    added   = null;
                if (purchases.startIndex == 0)
                {
                    removed = oldPackageIds;
                    added   = new List <string>();
                    foreach (var id in newPackageIds)
                    {
                        if (removed.Contains(id))
                        {
                            removed.Remove(id);
                        }
                        else
                        {
                            added.Add(id);
                        }
                    }
                }
                else if (purchases.startIndex == oldPackageIds.Count)
                {
                    added = newPackageIds;
                }

                var addedPackages   = added?.Select(id => m_PackageDatabase.GetPackage(id));
                var removedPackages = removed?.Select(id => m_PackageDatabase.GetPackage(id));
                TriggerOnListUpdate(addedPackages, removedPackages, false);
            }

            RefreshVisualStates();
        }
Пример #54
0
        public async Task PopulateAsync(
            Type readModelType,
            CancellationToken cancellationToken)
        {
            var stopwatch         = Stopwatch.StartNew();
            var readStoreManagers = ResolveReadStoreManagers(readModelType);

            var readModelTypes = new[]
            {
                typeof(IAmReadModelFor <, ,>),
                typeof(IAmAsyncReadModelFor <, ,>)
            };

            var aggregateEventTypes = new HashSet <Type>(readModelType
                                                         .GetTypeInfo()
                                                         .GetInterfaces()
                                                         .Where(i => i.GetTypeInfo().IsGenericType &&
                                                                readModelTypes.Contains(i.GetGenericTypeDefinition()))
                                                         .Select(i => i.GetTypeInfo().GetGenericArguments()[2]));

            _log.Verbose(() => string.Format(
                             "Read model '{0}' is interested in these aggregate events: {1}",
                             readModelType.PrettyPrint(),
                             string.Join(", ", aggregateEventTypes.Select(e => e.PrettyPrint()).OrderBy(s => s))));

            long totalEvents     = 0;
            long relevantEvents  = 0;
            var  currentPosition = GlobalPosition.Start;

            while (true)
            {
                _log.Verbose(() => string.Format(
                                 "Loading events starting from {0} and the next {1} for populating '{2}'",
                                 currentPosition,
                                 _configuration.PopulateReadModelEventPageSize,
                                 readModelType.PrettyPrint()));
                var allEventsPage = await _eventStore.LoadAllEventsAsync(
                    currentPosition,
                    _configuration.PopulateReadModelEventPageSize,
                    cancellationToken)
                                    .ConfigureAwait(false);

                totalEvents    += allEventsPage.DomainEvents.Count;
                currentPosition = allEventsPage.NextGlobalPosition;

                if (!allEventsPage.DomainEvents.Any())
                {
                    _log.Verbose(() => $"No more events in event store, stopping population of read model '{readModelType.PrettyPrint()}'");
                    break;
                }

                var domainEvents = allEventsPage.DomainEvents
                                   .Where(e => aggregateEventTypes.Contains(e.EventType))
                                   .ToList();
                relevantEvents += domainEvents.Count;

                if (!domainEvents.Any())
                {
                    continue;
                }

                var applyTasks = readStoreManagers
                                 .Select(m => m.UpdateReadStoresAsync(domainEvents, cancellationToken));
                await Task.WhenAll(applyTasks).ConfigureAwait(false);
            }

            stopwatch.Stop();
            _log.Information(
                "Population of read model '{0}' took {1:0.###} seconds, in which {2} events was loaded and {3} was relevant",
                readModelType.PrettyPrint(),
                stopwatch.Elapsed.TotalSeconds,
                totalEvents,
                relevantEvents);
        }
 public IEnumerable <IFile> GetFiles()
 {
     return(_files.Select(x => new InlinePackageFile(_package, x)));
 }
Пример #56
0
        public void ValidateAAPLOptionChainSecurityIdentifiers()
        {
            var chainProvider  = new BacktestingOptionChainProvider();
            var aapl           = Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
            var chains         = new HashSet <Symbol>();
            var expectedChains = File.ReadAllLines("TestData/aapl_chain.csv")
                                 .Where(x => !string.IsNullOrWhiteSpace(x))
                                 .ToDictionary(x => x, _ => false);

            Assert.AreNotEqual(0, expectedChains.Count);

            var start = new DateTime(2020, 1, 1);
            var end   = new DateTime(2020, 7, 1);

            foreach (var date in Time.EachDay(start, end))
            {
                if (USHoliday.Dates.Contains(date) || date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
                {
                    continue;
                }

                foreach (var symbol in chainProvider.GetOptionContractList(aapl, date))
                {
                    chains.Add(symbol);
                }
            }

            var fails = new HashSet <Symbol>();

            foreach (var chain in chains)
            {
                if (expectedChains.ContainsKey(chain.ID.ToString()))
                {
                    expectedChains[chain.ID.ToString()] = true;
                    continue;
                }

                fails.Add(chain);
            }

            Assert.AreEqual(0, fails.Count, $"The following option Symbols were not found in the expected chain:    \n{string.Join("\n", fails.Select(x => x.ID.ToString()))}");
            Assert.IsTrue(expectedChains.All(kvp => kvp.Value), $"The following option Symbols were not loaded:    \n{string.Join("\n", expectedChains.Where(kvp => !kvp.Value).Select(x => x.Key))}");
        }
        /// <summary>
        /// This enables scanning for and loading of plug-ins
        /// </summary>
        /// <param name="hostBuilder">IHostBuilder</param>
        private static void ConfigurePluginScanAndLoad(IHostBuilder hostBuilder)
        {
            // Configure the actual scanning & loading
            hostBuilder.ConfigureServices((hostBuilderContext, serviceCollection) =>
            {
                hostBuilder.Properties.TryRetrievePluginBuilder(out var pluginBuilder);

                if (pluginBuilder.UseContentRoot)
                {
                    var contentRootPath = hostBuilderContext.HostingEnvironment.ContentRootPath;
                    pluginBuilder.AddScanDirectories(contentRootPath);
                }

                var scannedAssemblies = new HashSet <Assembly>();

                if (pluginBuilder.FrameworkDirectories.Count > 0)
                {
                    foreach (var frameworkScanRoot in pluginBuilder.FrameworkDirectories)
                    {
                        // Do the globbing and try to load the framework files into the default AssemblyLoadContext
                        foreach (var frameworkAssemblyPath in pluginBuilder.FrameworkMatcher.GetResultsInFullPath(frameworkScanRoot))
                        {
                            var frameworkAssemblyName = new AssemblyName(Path.GetFileNameWithoutExtension(frameworkAssemblyPath));
                            if (AssemblyLoadContext.Default.TryGetAssembly(frameworkAssemblyName, out var alreadyLoadedAssembly))
                            {
                                scannedAssemblies.Add(alreadyLoadedAssembly);
                                continue;
                            }

                            // TODO: Log the loading?
                            var loadedAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(frameworkAssemblyPath);
                            if (loadedAssembly != null)
                            {
                                scannedAssemblies.Add(loadedAssembly);
                            }
                        }
                    }
                }

                if (pluginBuilder.PluginDirectories.Count > 0)
                {
                    foreach (var pluginScanRootPath in pluginBuilder.PluginDirectories)
                    {
                        // Do the globbing and try to load the plug-ins
                        var pluginPaths = pluginBuilder.PluginMatcher.GetResultsInFullPath(pluginScanRootPath);
                        // Use the globbed files, and load the assemblies
                        var pluginAssemblies = pluginPaths
                                               .Select(LoadPlugin)
                                               .Where(plugin => plugin != null);
                        foreach (var pluginAssembly in pluginAssemblies)
                        {
                            scannedAssemblies.Add(pluginAssembly);
                        }
                    }
                }
                var plugins = scannedAssemblies.Select(CreatePluginInstance).Where(plugin => plugin != null).OrderBy(plugin => plugin.GetOrder());

                foreach (var plugin in plugins)
                {
                    plugin.ConfigureHost(hostBuilderContext, serviceCollection);
                }
            });
        }
Пример #58
0
        private async Task FillDescriptionNotExistsEntities(StringBuilder strFile, HashSet <Guid> workflowsWithEntities, Dictionary <EntityReference, HashSet <Guid> > list)
        {
            {
                var listToDelete = new List <EntityReference>();

                foreach (var itemRef in list.Keys)
                {
                    try
                    {
                        var entityMetadata = _descriptor.MetadataSource.GetEntityMetadata(itemRef.LogicalName);

                        if (entityMetadata != null)
                        {
                            var repositoryGeneric = new GenericRepository(_service, entityMetadata);

                            var entity = await repositoryGeneric.GetEntityByIdAsync(itemRef.Id, ColumnSetInstances.AllColumns);

                            if (entity != null)
                            {
                                listToDelete.Add(itemRef);
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }
                }

                foreach (var item in listToDelete)
                {
                    list.Remove(item);
                }

                workflowsWithEntities.Clear();

                foreach (var set in list.Values)
                {
                    foreach (var item in set)
                    {
                        workflowsWithEntities.Add(item);
                    }
                }
            }

            if (list.Count == 0)
            {
                strFile
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine(this._iWriteToOutput.WriteToOutput(_service.ConnectionData, "No used not exists entities in workflows."))
                ;
                return;
            }

            strFile
            .AppendLine()
            .AppendLine()
            .AppendFormat(this._iWriteToOutput.WriteToOutput(_service.ConnectionData, "Used Not Exists Entities {0}", list.Count)).AppendLine()
            ;

            var orderedList = list.Keys.OrderBy(i => i.LogicalName).ThenBy(i => i.Name).ThenBy(i => i.Id);

            {
                FormatTextTableHandler table = new FormatTextTableHandler();
                table.SetHeader(nameof(EntityReference.LogicalName), nameof(EntityReference.Name), nameof(EntityReference.Id), "Url");

                foreach (var item in orderedList)
                {
                    var values = new List <string>()
                    {
                        item.LogicalName, item.Name, item.Id.ToString()
                    };

                    var url = _service.ConnectionData.GetEntityInstanceUrl(item.LogicalName, item.Id);

                    if (!string.IsNullOrEmpty(url))
                    {
                        values.Add(url);
                    }

                    table.AddLine(values);
                }

                table.GetFormatedLines(false).ForEach(s => strFile.AppendLine(tabspacer + s));
            }

            strFile
            .AppendLine()
            .AppendLine()
            .AppendLine()
            .AppendLine(new string('-', 150))
            .AppendLine()
            .AppendLine()
            .AppendLine()
            ;

            strFile.AppendFormat("Used Not Exists Entities Full Information {0}", list.Count).AppendLine();

            foreach (var item in orderedList)
            {
                strFile
                .AppendLine()
                .AppendLine()
                .AppendLine();

                FormatTextTableHandler table = new FormatTextTableHandler();
                table.SetHeader(nameof(EntityReference.LogicalName), nameof(EntityReference.Name), nameof(EntityReference.Id));
                table.AddLine(item.LogicalName, item.Name, item.Id.ToString());
                table.GetFormatedLines(false).ForEach(s => strFile.AppendLine(s));

                var url = _service.ConnectionData.GetEntityInstanceUrl(item.LogicalName, item.Id);

                if (!string.IsNullOrEmpty(url))
                {
                    strFile.AppendLine("Url:");
                    strFile.AppendLine(url);
                }

                strFile.AppendLine();

                var message = await _descriptor.GetSolutionComponentsDescriptionAsync(list[item].Select(id => new SolutionComponent()
                {
                    ObjectId      = id,
                    ComponentType = new OptionSetValue((int)ComponentType.Workflow),
                }));

                strFile
                .AppendLine("This entity Used By Workflows:")
                .AppendLine(message)
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine(new string('-', 150))
                ;
            }

            if (workflowsWithEntities.Any())
            {
                strFile
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine("These entities Used By Workflows:")
                ;

                var desc = await _descriptor.GetSolutionComponentsDescriptionAsync(workflowsWithEntities.Select(id => new SolutionComponent()
                {
                    ObjectId      = id,
                    ComponentType = new OptionSetValue((int)ComponentType.Workflow),
                }));

                strFile.AppendLine(desc);
            }
        }
Пример #59
0
 public IEnumerable <String> GetSecurityDBNames(String ServerName = null)
 {
     return((String.IsNullOrWhiteSpace(ServerName)) ? _ICP4SecurityServers?.Select(x => x.SecurityDB.Name)
                                                        : _ICP4SecurityServers?.Where(x => x.Name == ServerName)
            ?.Select(x => x.SecurityDB.Name));
 }
Пример #60
0
 public IEnumerable <IFile> GetChildren()
 {
     return(_folders.Select(x => new InlinePackageFile(_package, x)));
 }