public static HashSet<String> GetReplaysInFolder(String folderPath, ReplayType type, bool recursive = true)
        {
            HashSet<String> replaysInFolder;

            if (type == ReplayType.Warcraft3)
            {
                //make a set of replays in the folder, and replays that exist
                replaysInFolder = new HashSet<String>(Directory.GetFiles(folderPath, "*.w3g"));

                if (recursive)
                {
                    Queue<String> directories = new Queue<String>(Directory.GetDirectories(folderPath));
                    while (directories.Count > 0)
                    {
                        String dir = directories.Dequeue();
                        replaysInFolder = new HashSet<String>(replaysInFolder.Concat(Directory.GetFiles(dir, "*.w3g")));
                        directories = new Queue<String>(directories.Concat(Directory.GetDirectories(dir)));
                    }

                    HashSet<String> existingReplays = DatabaseHandler.GetWarcraft3ReplayPaths();
                    replaysInFolder.ExceptWith(existingReplays);
                }
            }

            //add new replay types here, otherwise an exception is thrown
            else
            {
                throw new ArgumentException();
            }

            return replaysInFolder;
        }
Example #2
0
        /// <summary>
        ///  Uses a djikstra-like algorithm to flood the graph from the start
        ///  node until the target node is found.
        ///  All visited nodes have their distance from the start node updated.
        /// </summary>
        /// <param name="start">The starting node.</param>
        /// <param name="target">The target node.</param>
        /// <param name="front">The last newly found nodes.</param>
        /// <param name="visited">The already visited nodes.</param>
        /// <param name="distFromStart">The traversed distance from the
        /// starting node in edges.</param>
        /// <returns>The distance from the start node to the target node.</returns>
        /// <remarks> - Currently the target node is never found if contained
        /// in front or visited.
        ///  - If front = { start }, then distFromStart should be 0.</remarks>
        public int dijkstraStep(GraphNode start, GraphNode target,
            HashSet<GraphNode> front, HashSet<GraphNode> visited, int distFromStart)
        {
            HashSet<GraphNode> newFront = new HashSet<GraphNode>();
            HashSet<GraphNode> newVisited = new HashSet<GraphNode>(visited);
            newVisited.Concat(front);

            foreach (GraphNode node in front)
            {
                newVisited.Add(node);
                foreach (GraphNode adjacentNode in node.Adjacent)
                {
                    if (adjacentNode == target) return distFromStart + 1;

                    // Could be combined in newVisited...
                    if (visited.Contains(adjacentNode)) continue;
                    if (front.Contains(adjacentNode)) continue;

                    newFront.Add(adjacentNode);
                }
            }
            // This wouldn't need recursion, but it's more convenient this way.
            if (newFront.Count > 0)
                return dijkstraStep(start, target, newFront, newVisited, distFromStart + 1);
            throw new GraphNotConnectedException();
        }
Example #3
0
        private static void ExcludeFiles(ICollection<IPackageFile> packageFiles)
        {
            // Always exclude the nuspec file
            // Review: This exclusion should be done by the package builder because it knows which file would collide with the auto-generated
            // manifest file.
            var excludes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            var wildCards = excludes.Concat(new[] {@"**\*" + Constants.ManifestExtension, @"**\*" + Constants.PackageExtension});

            PathResolver.FilterPackageFiles(packageFiles, ResolvePath, wildCards);
        }
Example #4
0
        /// <summary>
        /// Combines and orders two parties by highest speed first.
        /// </summary>
        /// <param name="p1">Party 1</param>
        /// <param name="p2">Party 2</param>
        /// <returns>A HashSet of combined IEngageables from both parties sorted by descending speed.</returns>
        private static HashSet<IEngageable> arrangeAttackOrder(HashSet<IEngageable> p1, HashSet<IEngageable> p2)
        {
            HashSet<IEngageable> bothParties = new HashSet<IEngageable>();

            IEnumerable<IEngageable> concat = p1.Concat(p2).OrderByDescending(member => member.getSpeed());

            foreach (IEngageable member in concat)
            {
                bothParties.Add(member);
            }

            return bothParties;
        }
Example #5
0
 public Connection(IMessageBus messageBus,
                   IJsonSerializer jsonSerializer,
                   string baseSignal,
                   string connectionId,
                   IEnumerable<string> signals,
                   IEnumerable<string> groups,
                   ITraceManager traceManager)
 {
     _messageBus = messageBus;
     _serializer = jsonSerializer;
     _baseSignal = baseSignal;
     _connectionId = connectionId;
     _signals = new HashSet<string>(signals);
     _groups = new HashSet<string>(groups);
     _trace = traceManager;
     _signalsAndGroups = _signals.Concat(_groups);
 }
Example #6
0
/*
        public static IAssemblySymbol[] GetReferencedAssemblies(IAssemblySymbol assembly)
        {
            var result = assembly.GetType().GetMethod("GetLinkedReferencedAssemblies", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(assembly, new object[0]);
            if (result == null)
                return new IAssemblySymbol[0];
            return result.ToArray();
        }
*/

        public static IAssemblySymbol[] Sort(Tuple<IAssemblySymbol, IAssemblySymbol[]>[] assemblies)
        {
            var currentList = assemblies.ToList();

            var prepend = new HashSet<Tuple<IAssemblySymbol, IAssemblySymbol[]>>();
            do 
            {
                prepend.Clear();
                var indices = currentList.Select((x, i) => new { Item = x, Index = i }).ToDictionary(x => x.Item.Item1, x => x.Index);
                for (var i = 0; i < currentList.Count; i++)
                {
                    var item = currentList[i];
                    foreach (var referencedAssembly in item.Item2)
                    {
                        int assemblyIndex;
                        if (indices.TryGetValue(referencedAssembly, out assemblyIndex))
                        {
                            if (assemblyIndex > i)
                            {
                                var referencedAssemblyItem = currentList[assemblyIndex];
                                prepend.Add(referencedAssemblyItem);
                            }
                        }                        
                    }
                }
                if (prepend.Any())
                {
                    var newItems = prepend.Concat(currentList.Where(x => !prepend.Contains(x))).ToArray();
                    currentList.Clear();
                    currentList.AddRange(newItems);
                }
            }
            while (prepend.Any());

            return currentList.Select(x => x.Item1).ToArray();
        }
        void solutionWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (isCanceling || _stopReporting)
            {
                return;
            }

            progressBar.Value = e.ProgressPercentage;
            lblProgressText.Content = e.ProgressPercentage.ToString() + "/" + maxSteps;
            bestSoFar = (HashSet<ushort>)(e.UserState);
            lblBestResult.Content = string.Format(L10n.Plural("Best result so far: {0} additional point spent", "Best result so far: {0} additional points spent", (uint)bestSoFar.Count), bestSoFar.Count);
            tree.HighlightedNodes = new HashSet<ushort>(bestSoFar.Concat(tree.SkilledNodes));
            tree.DrawNodeBaseSurroundHighlight();
        }
        public static HashSet<string> getDep(HashSet<string> dllSet, string fileName)
        {
            /*
             * Add Part where 
             * !File.exists(fileName) download();
             */
            XmlTextReader reader = new XmlTextReader(fileName);
            HashSet<string> set_for_this_Dep = new HashSet<string>();

            while (reader.Read())
            {
                if (reader.NodeType == System.Xml.XmlNodeType.Element &&
                    reader.Name == "Reference")
                {
                    reader.Read();
                    string dllPath = reader.Value.Trim();

                    if (!dllSet.Contains(dllPath))
                    {
                        dllSet.Add(dllPath);
                        string depPath = dllPath.Substring(0, dllPath.Length-4) + ".dep";

                        set_for_this_Dep.Add(depPath);
                        //dllSet.UnionWith(getDep(dllSet, depPath));
                    }
                }
            }

            foreach (string dll in set_for_this_Dep)
            {
                dllSet.Concat(getDep(new HashSet<string>(), dll));
            }

            return dllSet;
        }
Example #9
0
		/// <summary>
		/// Gets all titles that are suitable for player.
		/// </summary>
		/// <param name="player">The player for title checks.</param>
		/// <returns>All title suitable for given player or an empty list if none.</returns>
		public static ICollection GetPlayerTitles(GamePlayer player)
		{
			var titles = new HashSet<IPlayerTitle>();
			
			titles.Add(ClearTitle);
			
			return titles.Concat(m_titles.Where(t => t.IsSuitable(player))).ToArray();
		}
Example #10
0
		public IndexDefinition CreateIndexDefinition()
		{
			var fromClauses = new HashSet<string>();
			var realMappings = new HashSet<string>();

			if (!string.IsNullOrEmpty(ForEntityName))
			{
				fromClauses.Add("from doc in docs." + ForEntityName);
			}
			else
			{
				fromClauses.Add("from doc in docs");
			}

			foreach (var map in Items)
			{
				var currentDoc = "doc";
				var currentExpression = new StringBuilder();

				int currentIndex = 0;
				while (currentIndex < map.From.Length)
				{
					char currentChar = map.From[currentIndex++];
					switch (currentChar)
					{
						case ',':

							// doc.NewDoc.Items
							String newDocumentSource = string.Format("{0}.{1}", currentDoc, currentExpression);

							// docNewDocItemsItem
							String newDoc = string.Format("{0}Item", newDocumentSource.Replace(".", ""));

							// from docNewDocItemsItem in doc.NewDoc.Items
							String docInclude = string.Format("from {0} in ((IEnumerable<dynamic>){1}).DefaultIfEmpty()", newDoc, newDocumentSource);
							fromClauses.Add(docInclude);

							// Start building the property again
							currentExpression.Clear();

							// And from this new doc
							currentDoc = newDoc;

							break;
						default:
							currentExpression.Append(currentChar);
							break;
					}
				}

				if (currentExpression.Length > 0 && currentExpression[0] != '[')
				{
					currentExpression.Insert(0, '.');
				}
				// We get rid of any _Range(s) etc
				var indexedMember = currentExpression.ToString().Replace("_Range", "");
				if (indexedMember.Length == 0)
				{
					realMappings.Add(string.Format("{0} = {1}",
						map.To.Replace("_Range", ""),
						currentDoc
						));
				}
				else
				{
					realMappings.Add(string.Format("{0} = {1}{2}",
						map.To.Replace("_Range", ""),
						currentDoc,
						indexedMember
						));
				}
			}

			var index = new IndexDefinition
			{
				Map = string.Format("{0}\r\nselect new {{ {1} }}",
									string.Join("\r\n", fromClauses.ToArray()),
									string.Join(", ",
												realMappings.Concat(new[] { AggregationMapPart() }).Where(x => x != null))),
				Reduce = DynamicAggregation ? null : AggregationReducePart(),
				TransformResults = DynamicAggregation ? AggregationReducePart() : null,
			};

			if (DynamicAggregation)
			{
				foreach (var item in GroupByItems)
				{
					index.Stores[ToFieldName(item.To)] = FieldStorage.Yes;
				}
			}

			foreach (var descriptor in SortDescriptors)
			{
				index.SortOptions[ToFieldName(descriptor.Field)] = descriptor.FieldType;
			}

			foreach (var field in HighlightedFields.EmptyIfNull())
			{
				index.Stores[field] = FieldStorage.Yes;
				index.Indexes[field] = FieldIndexing.Analyzed;
			}
			return index;
		}
 public void ExecuteTheseHandlersFirst(params Type[] handlerTypes) {
     AssertInit();
     var firstOrderedHandlers = new HashSet<Type>();
     foreach (var handler in handlerTypes) {
         var firstOrderedHandler = orderedMessageHandlerList.FirstOrDefault(x => handler.IsAssignableFrom(x));
         if (firstOrderedHandler != null && !firstOrderedHandlers.Contains(firstOrderedHandler)) {
             firstOrderedHandlers.Add(firstOrderedHandler);
         }
     }
     var allOtherHandlers = orderedMessageHandlerList.Except(firstOrderedHandlers).ToList();
     orderedMessageHandlerList = firstOrderedHandlers.Concat(allOtherHandlers).ToList();
 }
Example #12
0
        /// <summary>
        ///  Converts an MST spanning a set of GraphNodes back into its equivalent
        ///  as a HashSet of SkillNode IDs.
        /// </summary>
        /// <param name="mst">The spanned MinimalSpanningTree.</param>
        /// <param name="visualize">A debug parameter that highlights all used
        /// GraphNodes' SkillNode equivalents in the tree.</param>
        /// <returns>A HashSet containing the node IDs of all SkillNodes spanned
        /// by the MST.</returns>
        HashSet<ushort> SpannedMstToSkillnodes(MinimalSpanningTree mst, bool visualize)
        {
            if (!mst.IsSpanned)
                throw new Exception("The passed MST is not spanned!");

            HashSet<ushort> newSkilledNodes = new HashSet<ushort>();
            foreach (GraphEdge edge in mst.SpanningEdges)
            {
                ushort target = edge.outside.Id;

                HashSet<ushort> start;
                if (edge.inside is Supernode)
                    start = tree.SkilledNodes;
                else
                    start = new HashSet<ushort>() { edge.inside.Id };

                var path = tree.GetShortestPathTo(target, start);

                newSkilledNodes = new HashSet<ushort>(newSkilledNodes.Concat(path));
            }

            if (visualize)
            {
                tree._nodeHighlighter.UnhighlightAllNodes(NodeHighlighter.HighlightState.FromAttrib);
                foreach (GraphNode steinerNode in mst.mstNodes)
                    tree._nodeHighlighter.HighlightNode(SkillTree.Skillnodes[steinerNode.Id], NodeHighlighter.HighlightState.FromAttrib);
            }

            //tree.DrawHighlights(tree._nodeHighlighter);
            return newSkilledNodes;
        }
Example #13
0
        private HashSet<FragmentQuery> GetUsedViewsAndRemoveTrueSurrogate(ref Tile<FragmentQuery> rewriting)
        {
            var usedViews = new HashSet<FragmentQuery>(rewriting.GetNamedQueries());
            if (!usedViews.Contains(_trueViewSurrogate.Query))
            {
                return usedViews; // no surrogate
            }
            // remove the surrogate
            usedViews.Remove(_trueViewSurrogate.Query);

            // first, try to union usedViews to see whether we can get True
            Tile<FragmentQuery> unionTile = null;
            var usedFollowedByUnusedViews = usedViews.Concat(_fragmentQueries);
            foreach (var view in usedFollowedByUnusedViews)
            {
                unionTile = (unionTile == null) ? CreateTile(view) : _qp.Union(unionTile, CreateTile(view));
                usedViews.Add(view);
                if (IsTrue(unionTile.Query))
                {
                    // we found a true rewriting
                    rewriting = rewriting.Replace(_trueViewSurrogate, unionTile);
                    return usedViews;
                }
            }
            // now we either found the rewriting or we can just take all views because we are in relaxed mode for update views
            Debug.Fail("Shouldn't happen");
            return usedViews;
        }
        void solutionWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (isCanceling)
            {
                btnPopupPauseResume.IsEnabled = true;
                isCanceling = false;
                return;
            }

            lblProgressText.Content = L10n.Message("Finished!");
            btnPopupCancelClose.Content = L10n.Message("Close");
            btnPopupPauseResume.IsEnabled = false;
            bestSoFar = (HashSet<ushort>)e.Result;
            isPaused = true;

            // Draw the final solution in case not all ProgressChangeds get executed.
            progressBar.Value = maxSteps;
            lblBestResult.Content = string.Format(L10n.Plural("Best result so far: {0} additional point spent", "Best result so far: {0} additional points spent", (uint)bestSoFar.Count), bestSoFar.Count);
            tree.HighlightedNodes = new HashSet<ushort>(bestSoFar.Concat(tree.SkilledNodes));
            tree.DrawNodeBaseSurroundHighlight();
        }
Example #15
0
        static void Main(string[] args)
        {
            ConfigurationItemFactory.Default.Targets.RegisterDefinition("ServiceManager", typeof(ServiceManagerTarget));

            string subdir = null, runDebugMethodOnExtension = null;
            var baseDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Extensions");
            Environment.CurrentDirectory = ConfigurationManager.AppSettings["DataDirectory"] ?? AppDomain.CurrentDomain.BaseDirectory;
            var extensionIDs = new HashSet<string>();
            Process process = null;
            Guid guid = Guid.Empty;
            Logger logger = null;

            var options = new OptionSet
            {
                { "guid=", "Specifies a GUID that the extension can use to identify itself to the parent process", v =>
                    {
                        Guid id;
                        if(!Guid.TryParse(v, out id))
                            throw new OptionException("The specified id was not a valid GUID", "guid");
                        guid = id;
                    }
                },
                { "basedir=", "Specifies the base plugins directory (can be relative or absolute)", v => baseDir = Path.IsPathRooted(v) ? v : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, v) },
                { "subdir=", "Specifies the extension subdirectory name", v => subdir = v },
                { "debug=", "Specifies an extension ID to run the debug method on", v => runDebugMethodOnExtension = v },
                { "pid=", "Parent process ID - if specified, this process will close when the parent process closes", v =>
                    {
                        int pid;
                        if(!int.TryParse(v, out pid))
                            throw new OptionException("The parent process ID must be a 32 bit integer", "pid");
                        try
                        {
                            process = Process.GetProcessById(pid);
                        }
                        catch(Exception ex)
                        {
                            throw new OptionException(ex.Message, "pid");
                        }
                        if(process == null)
                            throw new OptionException("There is no process with ID [" + pid + "]", "pid");
                    }
                },
                { "<>", v => extensionIDs.Add(v) }
            };

            CancellationTokenSource src = new CancellationTokenSource();
            try
            {
                options.Parse(args);
                if(subdir == null)
                {
                    Console.Write("Enter plugin directory name (not the full path): ");
                    subdir = Console.ReadLine();
                    if(string.IsNullOrWhiteSpace(subdir))
                    {
                        Console.WriteLine("No plugin directory specified.");
                        Exit(null, src, ExtensionRunnerExitCode.InvalidArguments);
                    }
                }

                GlobalDiagnosticsContext.Set("ExeBaseDir", new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName);
                GlobalDiagnosticsContext.Set("SubDirName", subdir);
                GlobalDiagnosticsContext.Set("ParentProcess", process == null ? "" : process.Id.ToString());
                logger = LogManager.GetCurrentClassLogger();
                logger.Info(new [] {
                    "ExtensionRunner Started:",
                    "	=> Command Line: " + Environment.CommandLine,
                    "	=> Subdirectory: " + subdir,
                    "	=> Base Directory: " + baseDir,
                    "	=> Specified Extensions: " + extensionIDs.Concat(", "),
                    "	=> GUID: " + guid,
                    "	=> Parent Process ID: " + (process == null ? "(none)" : process.Id.ToString())
                }.Concat(Environment.NewLine));

                AppDomain.CurrentDomain.UnhandledException += (s,e) => logger.FatalException("UNTRAPPED SERVICE EXCEPTION", (Exception)e.ExceptionObject);
                TaskScheduler.UnobservedTaskException += (s,e) => logger.FatalException("UNTRAPPED TASK EXCEPTION:", e.Exception);

                if(process != null)
                {
                    Task.Factory.StartNew(() =>
                    {
                        while(!src.IsCancellationRequested)
                        {
                            process.Refresh();
                            if(process.HasExited)
                            {
                                logger.Warn("Detected parent process shutdown.");
                                Exit(logger, src, ExtensionRunnerExitCode.ParentExited);
                                return;
                            }
                            Thread.Sleep(250);
                        }
                    });
                }

                // Read list of available extensions
                Dictionary<string, ExtensionInfo> extInfos;
                using(var loader = new SafeExtensionLoader(baseDir, subdir, process == null ? "" : process.Id.ToString(), src))
                    extInfos = loader.AvailableExtensions.ToDictionary(x => x.ExtensionID, x => x.Clone());

                if(extensionIDs.Count == 0)
                    extensionIDs = new HashSet<string>(extInfos.Select(x => x.Key)); // use all available extensions
                else
                    extensionIDs = new HashSet<string>(extensionIDs.Where(x => extInfos.ContainsKey(x))); // eliminate invalid any extension IDs
                logger.Info("Active extensions: " + (extensionIDs.Any() ? extensionIDs.Concat(", ") : "(none)"));
                logger.Info("Inactive extensions: " + (!extensionIDs.Any() ? extInfos.Where(x => !extensionIDs.Contains(x.Key)).Concat(", ") : "(none)"));

                var extLoaders = new List<SafeExtensionLoader>();
                var extTasks = new List<Task>();
                try
                {
                    foreach(var id in extensionIDs)
                    {
                        logger.Debug("Starting appdomain for extension: {0}", id);
                        var loader = new SafeExtensionLoader(baseDir, subdir, process == null ? "" : process.Id.ToString(), src);
                        var extID = id;
                        extTasks.Add(Task.Factory.StartNew(() => loader.RunExtension(guid, runDebugMethodOnExtension == extID, extID)));
                    }
                    Task.WaitAll(extTasks.ToArray(), src.Token);
                }
                finally
                {
                    foreach(var extLoader in extLoaders)
                        extLoader.Dispose();
                }
                //using(var loader = new SafeExtensionLoader(baseDir, subdir, process == null ? "" : process.Id.ToString(), src))
                //{
                //    var runExtsTask = Task.Factory.StartNew(() =>
                //    {
                //        // Verify that all extensions are available and if so, run them
                //        var sb = new StringBuilder();
                //        sb.AppendLine("[list of all plugins]");
                //        foreach(var extInfo in loader.AllExtensions)
                //            sb.AppendLine("\t" + extInfo.ExtensionID + ": " + extInfo.Name + " [" + (extensionIDs.Count == 0 || extensionIDs.Contains(extInfo.ExtensionID) ? "ACTIVE" : "INACTIVE") + "]");
                //        logger.Info(sb.ToString());
                //        loader.RunExtensions(guid, runDebugMethodOnExtension, extensionIDs.ToArray());
                //    }, src.Token);

                //    loader.RunMainAppThread();
                //    Task.WaitAll(new[] { runExtsTask }, src.Token);
                //}
            }
            catch(OptionException ex)
            {
                if(logger != null)
                    logger.Error("Invalid command options: " + ex.Message, options.WriteOptionDescriptions());
                Exit(logger, src, ExtensionRunnerExitCode.Exception);
            }
            catch(Exception ex)
            {
                if(logger != null)
                    logger.FatalException("An exception was thrown", ex);
                Exit(logger, src, ExtensionRunnerExitCode.Exception);
            }
            finally
            {
                Exit(logger, src, ExtensionRunnerExitCode.Success);
            }
        }
Example #16
0
        private void ProcessPublicBags(Random rand, Tuple<Player, int>[] dat)
        {
            var lootCount = PublicBag.BaseLootCount + PublicBag.PersonMultiplier*dat.Length;
            if (lootCount < PublicBag.MinLootCount) lootCount = PublicBag.MinLootCount;
            if (lootCount > PublicBag.MaxLootCount) lootCount = PublicBag.MaxLootCount;

            var loots = new HashSet<Item>();
            var pots = new List<Item>();
            for (var i = 0;
                i < lootCount ||
                (loots.Count < PublicBag.MinLootCount &&
                 pots.Count < PublicBag.MinLootCount);
                i++)
            {
                var loot = PublicBag.GetRandomLoot(rand);
                if (loot != null)
                {
                    if (loot.Potion)
                        pots.Add(loot);
                    else
                        loots.Add(loot);
                }
            }
            ShowBags(rand, loots.Concat(pots), null);
        }
        protected override void ProcessAssembly(AssemblyDefinition assemblyDef)
        {
            if (_frameworkProfile == null) {
                _frameworkProfile = assemblyDef.GuessAssemblyProfile();
            }
            if (_frameworkProfile != null) {
                foreach (var moduleDef in assemblyDef.Modules) {
                    var resolver = moduleDef.AssemblyResolver as DefaultAssemblyResolver;
                    if (resolver != null) {
                        resolver.AddSearchDirectory(_frameworkProfile.ReferencesDirectory);
                    }
                }
            }

            _usedTypeReferences = new HashSet<TypeReference>(CecilEqualityComparer.Default);
            base.ProcessAssembly(assemblyDef);
            var unprocessedTypes = new Queue<TypeReference>(_usedTypeReferences);
            _usedTypeReferences = null;

            var processedTypes = new HashSet<TypeDefinition>(CecilEqualityComparer.Default);
            var unresolvedTypes = new HashSet<TypeReference>(CecilEqualityComparer.Default);

            while (unprocessedTypes.Any()) {
                var typeRef = unprocessedTypes.Dequeue();

                if (typeRef == null) {
                    continue;
                }

                if (typeRef.IsGenericParameter) {
                    continue;
                }

                var typeSpec = typeRef as TypeSpecification;
                if (typeSpec != null) {
                    var elementType = typeSpec.ElementType;
                    Debug.Assert(elementType != null);
                    unprocessedTypes.Enqueue(elementType);

                    var genericInstanceTypeRef = typeRef as GenericInstanceType;
                    if (genericInstanceTypeRef != null) {
                        foreach (var genericArgument in genericInstanceTypeRef.GenericArguments) {
                            unprocessedTypes.Enqueue(genericArgument);
                        }
                    }

                    var requiredModifierTypeRef = typeRef as RequiredModifierType;
                    if (requiredModifierTypeRef != null) {
                        unprocessedTypes.Enqueue(requiredModifierTypeRef.ModifierType);
                    }

                    var optionalModifierTypeRef = typeRef as OptionalModifierType;
                    if (optionalModifierTypeRef != null) {
                        unprocessedTypes.Enqueue(optionalModifierTypeRef.ModifierType);
                    }

                    var functionPointerTypeRef = typeRef as FunctionPointerType;
                    if (functionPointerTypeRef != null) {
                        unprocessedTypes.Enqueue(functionPointerTypeRef.ReturnType);
                        foreach (var parameter in functionPointerTypeRef.Parameters) {
                            unprocessedTypes.Equals(parameter.ParameterType);
                            foreach (var customAttr in parameter.CustomAttributes) {
                                unprocessedTypes.Enqueue(customAttr.AttributeType);
                            }
                        }
                        foreach (var customAttr in functionPointerTypeRef.MethodReturnType.CustomAttributes) {
                            unprocessedTypes.Enqueue(customAttr.AttributeType);
                        }
                    }
                    continue;
                }

                var typeDef = typeRef as TypeDefinition;
                if (typeDef == null) {
                    typeDef = typeRef.TryResolve();
                    if (typeDef != null) {
                        unprocessedTypes.Enqueue(typeDef);
                    } else {
                        unresolvedTypes.Add(typeRef);
                        Debug.WriteLine(string.Format("Cannot resolve type {0}", typeRef.FullName));
                    }
                    continue;
                }

                processedTypes.Add(typeDef);
            }
            _resolvedTypes = processedTypes;
            _unresolvedTypes = unresolvedTypes;

            _allTypes = new HashSet<TypeReference>(_unresolvedTypes.Concat(_resolvedTypes), CecilEqualityComparer.Default);
        }