Esempio n. 1
0
        internal static SubscriptionDescriptor[] GetEventSinks(Type type)
        {
            if (m_subscriptionDescriptorCache.ContainsKey(type))
            {
                return(m_subscriptionDescriptorCache[type]);
            }

            var methods =
                from n in type.GetMethods(BindingFlags.Public | BindingFlags.Instance)
                where
                !n.IsVirtual &&
                n.GetCustomAttributes(typeof(EventSubscription), true).Length > 0
                select n;

            List <SubscriptionDescriptor> descriptors = new List <SubscriptionDescriptor>();

            foreach (MethodInfo mi in methods)
            {
                descriptors.Add(new SubscriptionDescriptor
                {
                    MethodInfo   = mi,
                    Subscription = mi.GetCustomAttributes(typeof(EventSubscription), true).FirstOrDefault() as EventSubscription
                });
            }

            SubscriptionDescriptor[] result = descriptors.ToArray();
            m_subscriptionDescriptorCache.Add(type, result);
            return(result);
        }
Esempio n. 2
0
 public object this[string fieldName]
 {
     get
     {
         lock (m_fields)
         {
             if (!m_fields.ContainsKey(fieldName))
             {
                 return(null);
             }
             return(m_fields[fieldName].Value);
         }
     }
     set
     {
         lock (m_fields)
         {
             if (!m_fields.ContainsKey(fieldName))
             {
                 m_fields.Add(fieldName, new FieldValue(fieldName, value));
             }
             else
             {
                 m_fields[fieldName] = new FieldValue(fieldName, value);
             }
         }
     }
 }
Esempio n. 3
0
        internal static PublicationDescriptor[] GetEventSources(Type type)
        {
            if (m_publicationDescriptorCache.ContainsKey(type))
            {
                return(m_publicationDescriptorCache[type]);
            }

            // there has to be a less convoluted LINQ query to pull this off, I just can't work it out yet

            var events =
                from n in type.GetEvents(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                where n.GetCustomAttributes(typeof(EventPublication), true).Length > 0
                select n;

            List <PublicationDescriptor> descriptors = new List <PublicationDescriptor>();

            foreach (EventInfo ei in events)
            {
                descriptors.Add(new PublicationDescriptor
                {
                    EventInfo   = ei,
                    Publication = ei.GetCustomAttributes(typeof(EventPublication), true).FirstOrDefault() as EventPublication
                });
            }
            PublicationDescriptor[] result = descriptors.ToArray();
            m_publicationDescriptorCache.Add(type, result);
            return(result);
        }
Esempio n. 4
0
 public void RemoveFile(string path)
 {
     if (filesMod.ContainsKey(path))
     {
         filesMod.Remove(path);
     }
 }
Esempio n. 5
0
        private PropertyInfo Getproperty(Type type, string propertyname)
        {
            if (propertyname == "$type")
            {
                return(null);
            }
            StringBuilder sb = new StringBuilder();

            sb.Append(type.Name);
            sb.Append("|");
            sb.Append(propertyname);
            string n = sb.ToString();

            if (_propertycache.ContainsKey(n))
            {
                return(_propertycache[n]);
            }
            var pr = type.GetProperties();

            foreach (PropertyInfo p in pr)
            {
                StringBuilder sbb = new StringBuilder();
                sbb.Append(type.Name);
                sbb.Append("|");
                sbb.Append(p.Name);
                string nn = sbb.ToString();
                if (_propertycache.ContainsKey(nn) == false)
                {
                    _propertycache.Add(nn, p);
                }
            }
            return(_propertycache[n]);
        }
Esempio n. 6
0
 public bool BuilderExists(int x, int y, int z)
 {
     if (Chunks.ContainsKey(new Vector3Int(x, y, z)))
     {
         return(Chunks[new Vector3Int(x, y, z)] != null);
     }
     return(false);
 }
Esempio n. 7
0
 public void RegisterType(Type concreteType, Type registerAs)
 {
     if (m_typeRegistrations.ContainsKey(registerAs))
     {
         // replace the registration
         m_typeRegistrations[registerAs] = concreteType;
     }
     else
     {
         m_typeRegistrations.Add(registerAs, concreteType);
     }
 }
Esempio n. 8
0
 public bool BuilderExists(int x, int y, int z)
 {
     try {
         if (Chunks.ContainsKey(new Vector3Int(x, y, z)))
         {
             return(Chunks[new Vector3Int(x, y, z)] != null);
         }
     }
     catch (KeyNotFoundException e) {
         return(false);
     }
     return(false);
 }
Esempio n. 9
0
        protected string GetInnerText(SafeDictionary <string> attributes, UltraLinkField linkField)
        {
            if (attributes.ContainsKey("text"))
            {
                return(attributes["text"]);
            }

            if (attributes.ContainsKey("description"))
            {
                return(attributes["description"]);
            }

            if (linkField.IsInternal)
            {
                if (linkField.UseItemDisplayName && linkField.TargetItem != null)
                {
                    return(string.IsNullOrEmpty(linkField.TargetItem.DisplayName) ? linkField.TargetItem.Name : linkField.TargetItem.DisplayName);
                }
                return(linkField.LinkDisplayText);
            }

            if (!string.IsNullOrEmpty(linkField.LinkDisplayText))
            {
                return(linkField.LinkDisplayText);
            }

            if (linkField.LinkType == "phone")
            {
                if (linkField.PhoneMask != null && !string.IsNullOrEmpty(linkField.CustomLink))
                {
                    var maskValue = linkField.PhoneMask["Mask"];

                    if (string.IsNullOrEmpty(maskValue))
                    {
                        return(linkField.CustomLink);
                    }

                    var mask = maskValue?.Replace(".", "\\.").Replace("_", "-");

                    return(FormatPhoneNumber(linkField.CustomLink, mask));
                }
            }

            if (string.IsNullOrEmpty(linkField.LinkDisplayText))
            {
                return(linkField.CustomLink);
            }

            return(string.Empty);
        }
Esempio n. 10
0
 public static void Register <TView, TViewModel>()
     where TView : Page
     where TViewModel : class, IViewModel, new()
 {
     lock (m_index)
     {
         var viewType      = typeof(TView);
         var viewModelType = typeof(TViewModel);
         if (!m_index.ContainsKey(viewType))
         {
             m_index.Add(viewType, viewModelType);
         }
     }
 }
Esempio n. 11
0
        private SafeTopicHandle getKafkaTopicHandle(string topic)
        {
            // TODO: We should consider getting rid of these and add proper support in librdkafka itself
            //       (producev() with RD_KAFKA_V_TOPIC() is one step closer)
            if (topicHandles.ContainsKey(topic))
            {
                return(topicHandles[topic]);
            }

            var topicConfigHandle = SafeTopicConfigHandle.Create();

            if (topicConfig != null)
            {
                topicConfig
                .ToList()
                .ForEach((kvp) => { topicConfigHandle.Set(kvp.Key, kvp.Value.ToString()); });
            }
            topicConfigHandle.Set("produce.offset.report", "true");
            IntPtr configPtr = topicConfigHandle.DangerousGetHandle();

            // note: there is a possible (benign) race condition here - topicHandle could have already
            // been created for the topic (and possibly added to topicHandles). If the topicHandle has
            // already been created, rdkafka will return it and not create another. the call to rdkafka
            // is threadsafe.
            var topicHandle = kafkaHandle.Topic(topic, configPtr);

            topicHandles.Add(topic, topicHandle);

            return(topicHandle);
        }
Esempio n. 12
0
        public bool Complete(T req, bool isError)
        {
            if (loadingGroupRes.ContainsKey(req))
            {
                loadingGroupRes.Remove(req);
                RemoveProgress(req);
                loadedCount++;
                if (m_OnComplete != null)
                {
                    m_OnComplete(req, isError);
                }
                else
                {
                    OnComplete(req, isError);
                }
                DispatchOnProgress();
            }
            // Debug.LogFormat("i={0},totalCount={1},loadedCount={2},IsDown={3},req={4},isErr={5}",i,totalCount,loadedCount,IsDown,req,isError);
            if (IsDown)
            {
                DispatchOnComplete();
            }

            return(true);
            // return i >= 0;
        }
Esempio n. 13
0
        /// <summary>
        /// Reflect the Class Name in the Source
        /// </summary>
        /// <param name="templateSource">
        /// The template source.
        /// </param>
        /// <returns>
        /// </returns>
        private static Item[] RunEnumeration(string templateSource, Item sourceItem)
        {
            templateSource = templateSource.Replace("lucene:", string.Empty);
            var commands = templateSource.Split(';');
            var refinements = new SafeDictionary<string>();

            foreach (var command in commands)
            {
                if (!command.IsNullOrEmpty())
                {
                    var commandSplit = command.Split(':');
                    if (commandSplit.Length == 2)
                    {
                        refinements.Add(commandSplit[0], commandSplit[1]);
                    }
                }
            }

            if (refinements.ContainsKey("location"))
            {
                int hitsCount;
                var items = Context.ContentDatabase.GetItem(refinements["location"]).Search(refinements, out hitsCount);
                return items.ToList().Select(x => x.GetItem()).ToArray();
            }
            else
            {
                int hitsCount;
                var items = sourceItem.Search(refinements, out hitsCount);
                return items.ToList().Select(x => x.GetItem()).ToArray();
            }
        }
        /// <summary>
        /// The get field crawler values.
        /// </summary>
        /// <param name="field">
        /// The field.
        /// </param>
        /// <param name="fieldCrawlers">
        /// The field crawlers.
        /// </param>
        /// <returns>
        /// The IEnumerable of field crawler values.
        /// </returns>
        public static IEnumerable<string> GetFieldCrawlerValues(Field field, SafeDictionary<string, string> fieldCrawlers)
        {
            Assert.IsNotNull(field, "Field was not supplied");
            Assert.IsNotNull(fieldCrawlers, "Field Crawler collection is not specified");

            if (fieldCrawlers.ContainsKey(field.TypeKey))
            {
                var fieldCrawlerType = fieldCrawlers[field.TypeKey];

                if (!string.IsNullOrEmpty(fieldCrawlerType))
                {
                    var fieldCrawler = ReflectionUtil.CreateObject(fieldCrawlerType, new object[] { field });

                    if (fieldCrawler is IMultivaluedFieldCrawler)
                    {
                        return (fieldCrawler as IMultivaluedFieldCrawler).GetValues();
                    }

                    if (fieldCrawler is FieldCrawlerBase)
                    {
                        return new[] { (fieldCrawler as FieldCrawlerBase).GetValue() };
                    }
                }
            }

            return new[] { new DefaultFieldCrawler(field).GetValue() };
        }
Esempio n. 15
0
        /// <summary>
        /// The get field crawler values.
        /// </summary>
        /// <param name="field">
        /// The field.
        /// </param>
        /// <param name="fieldCrawlers">
        /// The field crawlers.
        /// </param>
        /// <returns>
        /// The IEnumerable of field crawler values.
        /// </returns>
        public static IEnumerable <string> GetFieldCrawlerValues(Field field, SafeDictionary <string, string> fieldCrawlers)
        {
            Assert.IsNotNull(field, "Field was not supplied");
            Assert.IsNotNull(fieldCrawlers, "Field Crawler collection is not specified");

            if (fieldCrawlers.ContainsKey(field.TypeKey))
            {
                var fieldCrawlerType = fieldCrawlers[field.TypeKey];

                if (!string.IsNullOrEmpty(fieldCrawlerType))
                {
                    var fieldCrawler = ReflectionUtil.CreateObject(fieldCrawlerType, new object[] { field });

                    if (fieldCrawler is IMultivaluedFieldCrawler)
                    {
                        return((fieldCrawler as IMultivaluedFieldCrawler).GetValues());
                    }

                    if (fieldCrawler is FieldCrawlerBase)
                    {
                        return(new[] { (fieldCrawler as FieldCrawlerBase).GetValue() });
                    }
                }
            }

            return(new[] { new DefaultFieldCrawler(field).GetValue() });
        }
        /// <summary>
        /// Reflect the Class Name in the Source
        /// </summary>
        /// <param name="templateSource">
        /// The template source.
        /// </param>
        /// <returns>
        /// </returns>
        private static Item[] RunEnumeration(string templateSource, Item sourceItem)
        {
            templateSource = templateSource.Replace("lucene:", string.Empty);
            var commands    = templateSource.Split(';');
            var refinements = new SafeDictionary <string>();

            foreach (var command in commands)
            {
                if (!command.IsNullOrEmpty())
                {
                    var commandSplit = command.Split(':');
                    if (commandSplit.Length == 2)
                    {
                        refinements.Add(commandSplit[0], commandSplit[1]);
                    }
                }
            }

            if (refinements.ContainsKey("location"))
            {
                int hitsCount;
                var items = Context.ContentDatabase.GetItem(refinements["location"]).Search(refinements, out hitsCount);
                return(items.ToList().Select(x => x.GetItem()).ToArray());
            }
            else
            {
                int hitsCount;
                var items = sourceItem.Search(refinements, out hitsCount);
                return(items.ToList().Select(x => x.GetItem()).ToArray());
            }
        }
Esempio n. 17
0
 internal List <Getters> GetGetters(Type type)
 {
     if (_getterscache.ContainsKey(type))
     {
         return(_getterscache[type]);
     }
     else
     {
         PropertyInfo[] props   = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
         List <Getters> getters = new List <Getters>();
         foreach (PropertyInfo p in props)
         {
             GenericGetter g = CreateGetMethod(p);
             if (g != null)
             {
                 Getters gg = new Getters();
                 gg.Name   = p.Name;
                 gg.Getter = g;
                 getters.Add(gg);
             }
         }
         _getterscache.Add(type, getters);
         return(getters);
     }
 }
Esempio n. 18
0
        /// <summary>
        /// Original Implementation of AddStandardValues
        /// </summary>
        /// <param name="template"></param>
        /// <param name="database"></param>
        /// <param name="language"></param>
        /// <param name="result"></param>
        private void AddStandardValues(Template template, Database database, Language language, SafeDictionary <ID, string> result)
        {
            ID standardValueHolderId = template.StandardValueHolderId;

            if (ID.IsNullOrEmpty(standardValueHolderId))
            {
                return;
            }
            bool?currentValue = Switcher <bool?, LanguageFallbackItemSwitcher> .CurrentValue;
            Item item;

            if (currentValue == false)
            {
                try
                {
                    Switcher <bool?, LanguageFallbackItemSwitcher> .Exit();

                    item = ItemManager.GetItem(standardValueHolderId, language, Version.Latest, database, SecurityCheck.Disable);
                    goto IL_5A;
                }
                finally
                {
                    Switcher <bool?, LanguageFallbackItemSwitcher> .Enter(currentValue);
                }
            }
            item = ItemManager.GetItem(standardValueHolderId, language, Version.Latest, database, SecurityCheck.Disable);
IL_5A:
            if (item == null)
            {
                return;
            }
            foreach (Field field in item.Fields)
            {
                if (!result.ContainsKey(field.ID))
                {
                    string value = field.GetValue(false, true);
                    if (value != null)
                    {
                        result[field.ID] = value;
                    }
                }
            }
            if (!result.ContainsKey(FieldIDs.StandardValueHolderId))
            {
                result[FieldIDs.StandardValueHolderId] = standardValueHolderId.ToString();
            }
        }
Esempio n. 19
0
 private void PerformBroadcasting(UdpPacket packet, byte[] packageData)
 {
     if (clientCache.ContainsKey(packet.UserId))
     {
         var receivers = clientCache[packet.PId];
         if (receivers.Count > 0)
         {
             Parallel.ForEach(receivers, receiver =>
             {
                 if (receiver.Key != packet.UserId)
                 {
                     AsyncBeginSend(new UdpPacketBuffer(packageData, receiver.Value));
                 }
             });
         }
     }
 }
Esempio n. 20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="url"></param>
        /// <param name="path"></param>
        public void Load(string url, string path)
        {
            string key = CUtils.GetUDKey(url);

            if (downloadings.ContainsKey(key))
            {
                return;
            }

            var req = new ReqInfo();

            req.url      = url;
            req.saveName = path;//CUtils.GetFileName (url);
            req.index    = 0;

            Load(req);
        }
Esempio n. 21
0
        public T Get <T>(string key, T @default = default(T))
        {
            lock (this) {
                if (PropertyData.ContainsKey(key))
                {
                    return((T)PropertyData[key].GetValue(this, null));
                }

                var ret = Data[key];
                if (ret == null || ret.Equals(default(T)))
                {
                    return(@default);
                }

                return((T)ret);
            }
        }
Esempio n. 22
0
        /// <summary>
        /// 增加一个成员字段
        /// </summary>
        /// <param name="fieldMap">成员字段的映射信息</param>
        /// <returns></returns>
        protected FieldMap AddField(FieldMap fieldMap)
        {
            Check.IsNull(fieldMap, "fieldMap");
            Check.Valid(_Fields.ContainsKey(fieldMap.Field), "字段成员名称重复。");

            ValidateReadonly();
            _Fields.Add(fieldMap.Field, fieldMap);
            return(fieldMap);
        }
Esempio n. 23
0
 /// <summary>
 /// Adds a field entity
 /// </summary>
 /// <param name="fd"></param>
 public void AddFieldEntity(TypeDefinition td, FieldDefinition fd)
 {
     if (!fieldEntities.ContainsKey(fd.FullName))
     {
         var             field = fd.Instantiate(MethodOrFieldAnalyzer.GetGenericTypeParameters(this.host, td));
         DeclFieldEntity dfe   = new DeclFieldEntity(field);
         fieldEntities[field.FullName] = dfe;
     }
 }
        /// <summary>
        /// Tries to load the referenced assemblies.
        /// </summary>
        /// <param name="inputAssemblies">Assemblies</param>
        private void TryLoadReferencedAssemblies(Assembly[] inputAssemblies)
        {
            var ws = new SafeDictionary <string, Assembly>();

            foreach (Assembly a in inputAssemblies)
            {
                if (a == null)
                {
                    continue;
                }

                // recursively load all the assemblies reachables from the root!
                if (!Assemblies.ContainsKey(
                        a.GetName().FullName) && !ws.ContainsKey(a.GetName().FullName))
                {
                    ws.Add(a.GetName().FullName, a);
                }

                while (ws.Count > 0)
                {
                    var en = ws.Keys.GetEnumerator();
                    en.MoveNext();
                    var a_name     = en.Current;
                    var a_assembly = ws[a_name];
                    Assemblies.Add(a_name, a_assembly);
                    ws.Remove(a_name);

                    foreach (AssemblyName name in a_assembly.GetReferencedAssemblies())
                    {
                        Assembly b;
                        ExtendedReflection.Utilities.ReflectionHelper.TryLoadAssembly(name.FullName, out b);

                        if (b != null)
                        {
                            if (!Assemblies.ContainsKey(b.GetName().FullName) &&
                                !ws.ContainsKey(b.GetName().FullName))
                            {
                                ws.Add(b.GetName().FullName, b);
                            }
                        }
                    }
                }
            }
        }
Esempio n. 25
0
        /// <summary>
        ///ContainsKey 的测试
        ///</summary>
        public void ContainsKeyTestHelper <KeyT, ValueT>()
        {
            SafeDictionary <KeyT, ValueT> target = new SafeDictionary <KeyT, ValueT>(); // TODO: 初始化为适当的值
            KeyT key      = default(KeyT);                                              // TODO: 初始化为适当的值
            bool expected = false;                                                      // TODO: 初始化为适当的值
            bool actual;

            actual = target.ContainsKey(key);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("验证此测试方法的正确性。");
        }
Esempio n. 26
0
 static bool IsMusicAvailabe(int roomId, int userId)
 {
     if (musicCache.ContainsKey(roomId))
     {
         if (musicCache[roomId].PlayerId != userId)
         {
             return(false);
         }
     }
     return(true);
 }
        bool ICollection <KeyValuePair <TKey, TValue> > .Contains(KeyValuePair <TKey, TValue> item)
        {
            // No risk of dead needles here
            Predicate <WeakNeedle <TKey> > check = input =>
            {
                TKey foundKey;
                if (PrivateTryGetValue(input, out foundKey))
                {
                    return(_keyComparer.Equals(foundKey, item.Key));
                }
                return(false);
            };

            return(_wrapped.ContainsKey
                   (
                       _keyComparer.GetHashCode(item.Key),
                       check,
                       input => EqualityComparer <TValue> .Default.Equals(input, item.Value)
                   ));
        }
    public void GenerateChunks(int threads)
    {
        Stopwatch watch = new Stopwatch();

        watch.Start();
        List <Vector2Int>[] colCoords = new List <Vector2Int> [threads];

        for (int t = 0; t < threads; t++)
        {
            colCoords[t] = new List <Vector2Int>();
        }

        int i = 0;

        for (int x = 0; x < width; x++)
        {
            for (int z = 0; z < depth; z++)
            {
                Vector2Int col_pos = new Vector2Int(x, z);
                if (!Columns.ContainsKey(col_pos))
                {
                    GameObject obj = Instantiate(ColumnObj, VoxelConversions.ChunkCoordToWorld(new Vector3Int(x, 0, z)), Quaternion.identity, transform);
                    obj.name         = "Column " + col_pos.ToString();
                    Columns[col_pos] = obj.GetComponent <ChunkColumn>();
                    Columns[col_pos].Init(col_pos, this, CreateTerrainSampler());
                }

                colCoords[i % colCoords.Length].Add(col_pos);
                i++;

                /*for (int y = 0; y < height; y++)
                 * {
                 *  Vector3Int pos = new Vector3Int(x, y, z);
                 *  chunkCoords.Add(pos);
                 *
                 *  Vector2Int col_pos = new Vector2Int(pos.x, pos.z);
                 *  if (!Columns.ContainsKey(col_pos))
                 *  {
                 *      GameObject obj = new GameObject("Column " + col_pos.ToString(), typeof(ChunkColumn));
                 *      Columns[col_pos] = obj.GetComponent<ChunkColumn>();
                 *      Columns[col_pos].Init(20, col_pos, CreateTerrainSampler());
                 *  }
                 * }*/
            }
        }
        watch.Stop();
        Debug.Log("Finished spawning columns: " + watch.Elapsed);
        for (int t = 0; t < colCoords.Length; t++)
        {
            //Debug.Log(colCoords[t].Count);
            GenerateChunks("Gen_" + t, colCoords[t].ToArray());
        }
    }
Esempio n. 29
0
        public void CloseRemove(string name)
        {
            if (_asyncTasks.ContainsKey(name))
            {
                _asyncTasks.Remove(name);
            }

            if (_asyncTasks.Count == 0)
            {
                _closeWait.Set();
            }
        }
Esempio n. 30
0
 private GenericSetter GetSetter(PropertyInfo prop)
 {
     if (_settercache.ContainsKey(prop))
     {
         return(_settercache[prop]);
     }
     else
     {
         GenericSetter s = CreateSetMethod(prop);
         _settercache.Add(prop, s);
         return(s);
     }
 }
Esempio n. 31
0
 private Type GetTypeFromCache(string typename)
 {
     if (_typecache.ContainsKey(typename))
     {
         return(_typecache[typename]);
     }
     else
     {
         Type t = Type.GetType(typename);
         _typecache.Add(typename, t);
         return(t);
     }
 }
        public void 取得SafeDictionary是否含有指定鍵值_SafeDictionary內包含該鍵值_應回傳True()
        {
            var safeDictionary = new SafeDictionary <int, int>
            {
                { 1, 3 },
                { 2, 8 }
            };
            const int  key            = 2;
            var        result         = safeDictionary.ContainsKey(key);
            const bool expectedResult = true;

            result.Should().Be(expectedResult);
        }
        public static string GetFieldCrawlerValue(Field field, SafeDictionary<string, string> fieldCrawlers)
        {
            Assert.IsNotNull(field, "Field was not supplied");
            Assert.IsNotNull(fieldCrawlers, "Field Crawler collection is not specified");

            if (fieldCrawlers.ContainsKey(field.TypeKey))
            {
                var fieldCrawlerType = fieldCrawlers[field.TypeKey];

                if (!fieldCrawlerType.IsNullOrEmpty())
                {
                    var fieldCrawler = ReflectionUtil.CreateObject(fieldCrawlerType, new object[] { field });

                    if (fieldCrawler.IsNotNull() && fieldCrawler is FieldCrawlerBase)
                    {
                        return (fieldCrawler as FieldCrawlerBase).GetValue();
                    }
                }
            }

            return new DefaultFieldCrawler(field).GetValue();
        }
        /// <summary>
        /// Compares current uncovered locations with the previous uncovered locations
        /// </summary>
        internal void AnalyzePreviousAndCurrentUncoveredLoc(string currPUTSignature,
            out HashSet<string> allGivenUpLocations, out HashSet<string> allCoveredLocations,
            out HashSet<string> newUncoveredLocations, out bool hasSomeCoveredLocation,
            out bool bAllAreNewLocations, out bool bNoneAreNewLocations)
        {
            hasSomeCoveredLocation = false;
            bAllAreNewLocations = true;
            bNoneAreNewLocations = true;

            var resolvedPrevLocations = new SafeSet<string>();
            var bestFitnessValues = new SafeDictionary<string, int>();

            //This dictionary is constructed since the FactorySuggestionStore is based
            //on declarting type not on the explorable type, which can be different
            allGivenUpLocations = new HashSet<string>();
            allCoveredLocations = new HashSet<string>();
            tempAllLocationStore = new SafeDictionary<string, PersistentUncoveredLocationStore>();

            //All final suggested sequences of the current PUT
            var putspecificsequences = new List<MethodSignatureSequence>();

            foreach (var fss in this.FactorySuggestionsDictionary.Values)
            {
                foreach (var codelockey in fss.locationStoreSpecificSequences.Keys)
                {
                    var pucls = fss.locationStoreSpecificSequences[codelockey];
                    if (!pucls.IsDormat())  //Donot touch dormant persistent stores
                        tempAllLocationStore[codelockey] = pucls;
                }

                foreach (var givenUpLocation in fss.PermanentFailedUncoveredLocations)
                    allGivenUpLocations.Add(givenUpLocation);

                foreach (var coveredLocation in fss.SuccessfulCoveredLocations)
                    allCoveredLocations.Add(coveredLocation);

                //MethodSignatureSequenceList mssl;
                //if (fss.FinalPUTSequences.TryGetValue(currPUTSignature, out mssl))
                //{
                //    foreach (var seq in mssl.SequenceList)
                //    {
                //        if (!putspecificsequences.Contains(seq))
                //            putspecificsequences.Add(seq);
                //    }
                //}
            }

            var failedLocations = new SafeSet<PersistentUncoveredLocationStore>();
            //Traverse all uncovered locations
            foreach (var ucovLocList in this.UncoveredLocationDictionary.Values)
            {
                var locationStr = ucovLocList.Location.ToString();
                var key = UncoveredCodeLocationStore.GetKey(ucovLocList.Location.ToString(),
                    ucovLocList.ExplorableType.ToString(), ucovLocList.TermIndex);

                //Check whether there are any defect detecting sequences. If yes promote them
                //in the associated factory store
                foreach (var ucls in ucovLocList.StoreList)
                {
                    if (ucls.IsADefectDetectingSequence)
                    {
                        var fss = this.FactorySuggestionsDictionary[ucls.ExplorableType.ToString()];
                        SafeDebug.AssumeNotNull(fss, "fss cannot be null");
                        fss.AddToDefectDetectingSequences(ucls.MethodCallSequence);
                    }
                }

                if (allGivenUpLocations.Contains(key))
                {
                    //This location has been earlier given up. No need to deal with this
                    resolvedPrevLocations.Add(key);
                    this.Log.LogMessage(WikiTopics.MissingWikiTopic, "Location " + locationStr + " is ignored since it was already given up earlier!!!");
                    continue;
                }

                if (allCoveredLocations.Contains(key))
                {
                    //This location has been covered earlier. Ideally this case should not happen
                    //resolvedPrevLocations.Add(key);
                    this.Log.LogMessage(WikiTopics.MissingWikiTopic,
                        "Location " + locationStr + " is previously covered, but can be reported since the caller could be different.");
                    bAllAreNewLocations = false;
                    //continue;
                }

                //Get the associated factory suggestion store
                if (tempAllLocationStore.ContainsKey(key))
                {
                    bAllAreNewLocations = false;
                    var pucls = tempAllLocationStore[key];
                    resolvedPrevLocations.Add(key);

                    //For some formats such as TRUE_SET, we do not need the fitness measure
                    //If they are not covered in one attempt, they won't be covered any time
                    if (ucovLocList.StoreList.Count > 0)
                    {
                        var fmt = ucovLocList.StoreList[0].DesiredFieldModificationType;
                        if (!this.IsFitnessRequired(fmt))
                        {
                            pucls.NumberOfUnsuccessfulAttempts = PexMeConstants.MAX_UNSUCCESSFUL_ATTEMPTS + 1;
                        }
                    }

                    //Reached the threshold of number of attempts. So deleting this uncovered location forever
                    if (pucls.NumberOfUnsuccessfulAttempts + 1 <= PexMeConstants.MAX_UNSUCCESSFUL_ATTEMPTS)
                    {
                        //Handle according to fitness value and drop the other methods that
                        //acutally did not help increase the fitness value
                        this.RemoveSuggestionsWithLowFitness(ucovLocList, tempAllLocationStore[key], putspecificsequences);
                        this.Log.LogMessage(WikiTopics.MissingWikiTopic,
                        "Location " + locationStr + " is resolved and is still uncovered in the new run " +
                        "(fitness: " + pucls.Fitnessvalue + "), (Attempt: " + pucls.NumberOfUnsuccessfulAttempts + ")");
                    }
                    else
                    {
                        this.Log.LogMessage(WikiTopics.MissingWikiTopic,
                        "Location " + locationStr + " is resolved and but not making any process!!! Will be deleted forever");
                        //This pucls data will be deleted forever since it reached its max attempts without any progress
                        failedLocations.Add(pucls);
                    }
                }
            }

            //New locations that added to the factory suggestion store
            newUncoveredLocations = new HashSet<string>();
            foreach (var ucovLocList in this.UncoveredLocationDictionary.Values)
            {
                var key = UncoveredCodeLocationStore.GetKey(ucovLocList.Location.ToString(),
                        ucovLocList.ExplorableType.ToString(), ucovLocList.TermIndex);
                if (!resolvedPrevLocations.Contains(key))
                {
                    newUncoveredLocations.Add(key);
                    this.Log.LogMessage(WikiTopics.MissingWikiTopic,
                        "Location " + ucovLocList.Location.ToString() + " is newly added in the new run");
                    bNoneAreNewLocations = false;
                }
            }

            //Unresolved locations from the previous run. This means that these sequences
            //are either already covered or not covered due to some new exception...
            var unresolvedPrevLocations = new SafeSet<PersistentUncoveredLocationStore>();
            var alreadyCoveredLocations = new SafeSet<PersistentUncoveredLocationStore>();
            foreach (var fss in this.FactorySuggestionsDictionary.Values)
            {
                var allRemovedPUCLS = new List<PersistentUncoveredLocationStore>();

                //Delete all failed locations if the suggested methods for this
                //failed location are all actually already explored. If not, place
                //them in pending status. Usually this case happens, if covering
                //the same location within the method is required by another location
                foreach (var pucls in failedLocations)
                {
                    var key = UncoveredCodeLocationStore.GetKey(pucls.CodeLocation.ToString(),
                        pucls.ExplorableType.ToString(), pucls.TermIndex);

                    fss.RemoveUncoveredLocationStore(pucls, false, this);
                    allRemovedPUCLS.Add(pucls);
                }

                foreach (var codelockey in fss.locationStoreSpecificSequences.Keys)
                {
                    var tpucls = fss.locationStoreSpecificSequences[codelockey];
                    if (tpucls.IsDormat())
                        continue;

                    if (allGivenUpLocations.Contains(codelockey))
                    {
                        bAllAreNewLocations = false;
                        unresolvedPrevLocations.Add(tpucls);
                        this.Log.LogWarning(WikiTopics.MissingWikiTopic, "UncoveredLocation",
                            "Location " + codelockey + " was already given up. Should not be reported again!!! Anyways, Deleting this location forever");
                        continue;
                    }

                    if (!resolvedPrevLocations.Contains(codelockey))
                    {
                        //Check whether this location is covered based on the coverage
                        if (tpucls.AlreadyCovered || this.IsPrevUncoveredLocationCovered(tpucls))
                        {
                            alreadyCoveredLocations.Add(tpucls);
                            this.Log.LogMessage(WikiTopics.MissingWikiTopic,
                                "Location " + codelockey + " is successfully covered in the new run");
                            hasSomeCoveredLocation = true;
                        }
                        else
                        {
                            bAllAreNewLocations = false;
                            unresolvedPrevLocations.Add(tpucls);
                            this.Log.LogWarning(WikiTopics.MissingWikiTopic, "UncoveredLocation",
                                "Location " + codelockey + " from the previous run is not found in the new run!!! Deleting this location forever");
                        }
                    }
                }

                //Delete all unresolved locations as they won't be required anymore!!!
                foreach (var pucls in unresolvedPrevLocations)
                {
                    fss.RemoveUncoveredLocationStore(pucls, false, this);
                    allRemovedPUCLS.Add(pucls);
                }

                //Handle all removed PUCLS
                foreach (var pucls in allRemovedPUCLS)
                {
                    var key = UncoveredCodeLocationStore.GetKey(pucls.CodeLocation, pucls.ExplorableType, pucls.TermIndex);
                    fss.PermanentFailedUncoveredLocations.Add(key);
                    if (!fss.TemporaryFailedUncoveredLocations.ContainsKey(key))
                    {
                        //Are there any active uncovered locations
                        if (this.AnyActiveUncoveredLocations())
                            fss.TemporaryFailedUncoveredLocations[key] = 1;
                        else
                            fss.TemporaryFailedUncoveredLocations[key] = PexMeConstants.MAX_UNCOVEREDLOC_ATTEMPTS;
                    }
                }

                //Delete all the information regarding covered locations and upgrade their specific factory methods
                foreach (var pucls in alreadyCoveredLocations)
                {
                    fss.RemoveUncoveredLocationStore(pucls, true, this);
                }

                alreadyCoveredLocations.Clear();
            }
        }
Esempio n. 35
0
        /// <summary>
        /// 取所有语言
        /// </summary>
        /// <returns></returns>
        private ISafeDictionary<string, string> GetLang() {
            if (lang.IsNullEmpty()) Msg.WriteEnd("语言未设置!");
            string path = "".GetMapPath() + "\\lang\\{0}.lang".FormatWith(lang);
            if (!FileDirectory.FileExists(path)) Msg.WriteEnd("语言文件{0}.lang不存在!".FormatWith(lang));

            string lineText = string.Empty; ISafeDictionary<string, string> list = new SafeDictionary<string, string>();
            using (StreamReader reader = new StreamReader(path, System.Text.Encoding.UTF8)) {
                while ((lineText = reader.ReadLine()).IsNotNull()) {
                    int len = lineText.IndexOf('=');
                    if (lineText.IsNullEmpty() || len == -1) continue;
                    string key = lineText.Substring(0, len).Trim();
                    string value = lineText.Substring(len + 1).Trim();
                    if (!list.ContainsKey(key)) list.Add(key, value); else list[key] = value;
                }
            }
            return list;
        }
        /// <summary>
        /// Tries to load the referenced assemblies.
        /// </summary>
        /// <param name="inputAssemblies">Assemblies</param>
        private void TryLoadReferencedAssemblies(Assembly[] inputAssemblies)
        {
            var ws = new SafeDictionary<string, Assembly>();

            foreach (Assembly a in inputAssemblies)
            {
                if (a == null)
                {
                    continue;
                }

                // recursively load all the assemblies reachables from the root!
                if (!Assemblies.ContainsKey(
                    a.GetName().FullName) && !ws.ContainsKey(a.GetName().FullName))
                {
                    ws.Add(a.GetName().FullName, a);
                }

                while (ws.Count > 0)
                {
                    var en = ws.Keys.GetEnumerator();
                    en.MoveNext();
                    var a_name = en.Current;
                    var a_assembly = ws[a_name];
                    Assemblies.Add(a_name, a_assembly);
                    ws.Remove(a_name);

                    foreach (AssemblyName name in a_assembly.GetReferencedAssemblies())
                    {
                        Assembly b;
                        ExtendedReflection.Utilities.ReflectionHelper.TryLoadAssembly(name.FullName, out b);

                        if (b != null)
                        {
                            if (!Assemblies.ContainsKey(b.GetName().FullName) &&
                                !ws.ContainsKey(b.GetName().FullName))
                            {
                                ws.Add(b.GetName().FullName, b);
                            }
                        }
                    }
                }
            }
        }
        public static void Load()
        {
            BaseInformations = new SafeDictionary<uint, ConquerItemBaseInformation>(10000);
            PlusInformations = new SafeDictionary<uint, SafeDictionary<byte, ConquerItemPlusInformation>>(10000);
            GradeInformations = new SafeDictionary<string, SafeDictionary<int, ConquerItemBaseInformation>>(10000);
            GradeInformations2 = new SafeDictionary<string, SafeDictionary<uint, int>>(10000);
            string[] baseText = File.ReadAllLines(ServerBase.Constants.ItemBaseInfosPath);
            string text = "►◄►◄►◄►◄►◄►◄►◄►◄►◄►◄►◄►◄►◄►◄►◄►◄►◄►◄►◄►◄";
            int for1prg = baseText.Length / (System.Console.WindowWidth - text.Length);
            int count = 0;
            System.Console.Write(text);
            var old1 = System.Console.BackgroundColor;
            var old2 = System.Console.ForegroundColor;
            System.Console.BackgroundColor = ConsoleColor.Gray;
            System.Console.ForegroundColor = ConsoleColor.Gray;
            int gkey = 0;
            int lastlevel = 0;
            string lastgr = "";
            foreach (string line in baseText)
            {
                count++;
                if (count == for1prg)
                {
                    count = 0;
                    System.Console.Write("▼◘");
                }
                string _item_ = line.Trim();
                if (_item_.Length > 11)
                {
                    if (_item_.IndexOf("//", 0, 2) != 0)
                    {
                        ConquerItemBaseInformation CIBI = new ConquerItemBaseInformation();
                        CIBI.Parse(_item_);

                        var Grades = GradeInformations[CIBI.Description];
                        BaseInformations.Add(CIBI.ID, CIBI);
                        if (GradeInformations.ContainsKey(CIBI.Description) == false)
                        {
                            GradeInformations2.Add(CIBI.Description, new SafeDictionary<uint, int>(1000));
                            GradeInformations2[CIBI.Description].Add((uint)(CIBI.ID / 10), 0);
                            lastlevel = CIBI.Level;
                            GradeInformations.Add(CIBI.Description, new SafeDictionary<int, ConquerItemBaseInformation>(1000));
                            gkey = 0;
                        }
                        else
                        {
                            if (lastgr != CIBI.Description)
                                gkey = GradeInformations2[CIBI.Description].Count - 1;

                            if (GradeInformations2[CIBI.Description].ContainsKey(CIBI.ID / 10) && CIBI.Level == lastlevel)
                            {
                                CIBI.GradeKey = gkey;
                                continue;
                            }
                            else
                            {
                                GradeInformations2[CIBI.Description].Add((uint)(CIBI.ID / 10), 0);
                                lastlevel = CIBI.Level;
                                gkey = gkey + 1;
                            }
                        }
                        lastgr = CIBI.Description;
                        CIBI.GradeKey = gkey;
                        GradeInformations[CIBI.Description].Add(gkey, CIBI);
                    }
                }
            }
            GradeInformations2.Base.Clear();
            System.Console.BackgroundColor = old1;
            System.Console.ForegroundColor = old2;
            baseText = File.ReadAllLines(ServerBase.Constants.ItemPlusInfosPath);

            foreach (string line in baseText)
            {
                try
                {
                    string _item_ = line.Trim();
                    ConquerItemPlusInformation CIPI = new ConquerItemPlusInformation();
                    CIPI.Parse(_item_);
                    SafeDictionary<byte, ConquerItemPlusInformation> info = null;
                    if (PlusInformations.TryGetValue(CIPI.ID, out info))
                    {
                        info.Add(CIPI.Plus, CIPI);
                    }
                    else
                    {
                        PlusInformations.Add(CIPI.ID, new SafeDictionary<byte, ConquerItemPlusInformation>(1000));
                        if (PlusInformations.TryGetValue(CIPI.ID, out info))
                        {
                            info.Add(CIPI.Plus, CIPI);
                        }
                    }
                }
                catch
                {
                    Console.WriteLine(line);
                    Console.ReadLine();
                }
            }
            Console.WriteLine("Item Base and Plus information loaded.");
        }