// Constructor public Arguments(string[] Args){ //Parameters=new StringDictionary(); Parameters=new HybridDictionary(); Regex Spliter=new Regex(@"^-{1,2}|^/|=|:", RegexOptions.IgnoreCase|RegexOptions.Compiled); Regex Remover= new Regex(@"^['""]?(.*?)['""]?$", RegexOptions.IgnoreCase|RegexOptions.Compiled); string Parameter=null; string[] Parts; // Valid parameters forms: // {-,/,--}param{ ,=,:}((",')value(",')) // Examples: -param1 value1 --param2 /param3:"Test-:-work" /param4=happy -param5 '--=nice=--' foreach(string Txt in Args){ // Look for new parameters (-,/ or --) and a possible enclosed value (=,:) Parts=Spliter.Split(Txt,3); switch(Parts.Length){ // Found a value (for the last parameter found (space separator)) case 1: if(Parameter!=null){ if(!Parameters.Contains(Parameter)){ Parts[0]=Remover.Replace(Parts[0],"$1"); Parameters.Add(Parameter,Parts[0]); } Parameter=null; } // else Error: no parameter waiting for a value (skipped) break; // Found just a parameter case 2: // The last parameter is still waiting. With no value, set it to true. if(Parameter!=null){ if(!Parameters.Contains(Parameter)) Parameters.Add(Parameter,"true"); } Parameter=Parts[1]; break; // Parameter with enclosed value case 3: // The last parameter is still waiting. With no value, set it to true. if(Parameter!=null){ if(!Parameters.Contains(Parameter)) Parameters.Add(Parameter,"true"); } Parameter=Parts[1]; // Remove possible enclosing characters (",') if(!Parameters.Contains(Parameter)){ Parts[2]=Remover.Replace(Parts[2],"$1"); Parameters.Add(Parameter,Parts[2]); } Parameter=null; break; } } // In case a parameter is still waiting if(Parameter!=null){ if(!Parameters.Contains(Parameter)) Parameters.Add(Parameter,"true"); } }
static void Main(string[] args) { HybridDictionary hb = new HybridDictionary(); hb.Add("M", "Male"); hb.Add("S", "Scot"); hb.Add("F", "Female"); Console.WriteLine("M:{0}", hb["S"]); Console.ReadKey(); }
private void AnalyzeEnum( Type enumType ) { _enumName = enumType.Name; R.FieldInfo[] fieldInfos = enumType.GetFields( BindingFlags.Static | BindingFlags.Public ); _namedValues = new HybridDictionary( fieldInfos.Length, false ); _valuedNames = new HybridDictionary( fieldInfos.Length, false ); foreach( R.FieldInfo fi in fieldInfos ) { if( ( fi.Attributes & EnumField ) == EnumField ) { string name = fi.Name; object value = fi.GetValue( null ); Attribute[] attrs = Attribute.GetCustomAttributes( fi, typeof( XmlEnumAttribute ) ); if( attrs.Length > 0 ) { XmlEnumAttribute attr = (XmlEnumAttribute)attrs[0]; name = attr.Name; } _namedValues.Add( name, value ); if( !_valuedNames.Contains( value )) _valuedNames.Add( value, name ); } } }
public void PutClient(string auth, s2hClient Client) { lock (m_Clients) { m_Clients.Add(auth, Client); } }
public void NotEmpty () { HybridDictionary hd = new HybridDictionary (true); hd.Add ("CCC", "ccc"); AssertEquals ("Count", 1, hd.Count); Assert ("null", !hd.Contains (null)); }
public ConsumerConnectionPointCollection(ICollection connectionPoints) { if (connectionPoints == null) { throw new ArgumentNullException("connectionPoints"); } _ids = new HybridDictionary(connectionPoints.Count, true /* caseInsensitive */); foreach (object obj in connectionPoints) { if (obj == null) { throw new ArgumentException(SR.GetString(SR.Collection_CantAddNull), "connectionPoints"); } ConsumerConnectionPoint point = obj as ConsumerConnectionPoint; if (point == null) { throw new ArgumentException(SR.GetString(SR.Collection_InvalidType, "ConsumerConnectionPoint"), "connectionPoints"); } string id = point.ID; if (!_ids.Contains(id)) { InnerList.Add(point); _ids.Add(id, point); } else { throw new ArgumentException(SR.GetString(SR.WebPart_Collection_DuplicateID, "ConsumerConnectionPoint", id), "connectionPoints"); } } }
public override object Resolve(IKernel kernel) { string key = null; var argument = arguments[0]; if (arguments.Length == 2) { key = (string)argument; argument = arguments[1]; } else if (argument is string) { return kernel.Resolve((string)argument, ComponentType); } if (argument is Uri) { argument = WcfEndpoint.At((Uri)argument); } var args = new HybridDictionary(); args.Add(Guid.NewGuid().ToString(), argument); if (key == null) { return kernel.Resolve(ComponentType, args); } return kernel.Resolve(key, ComponentType, args); }
/// <summary> /// Initializes a new instance of the <see cref="BadgeComponent"/> class. /// </summary> /// <param name="userId">The user identifier.</param> /// <param name="data">The data.</param> internal BadgeComponent(uint userId, UserData data) { BadgeList = new HybridDictionary(); foreach (var current in data.Badges.Where(current => !BadgeList.Contains(current.Code))) BadgeList.Add(current.Code, current); _userId = userId; }
public WebPartDescriptionCollection(ICollection webPartDescriptions) { if (webPartDescriptions == null) { throw new ArgumentNullException("webPartDescriptions"); } _ids = new HybridDictionary(webPartDescriptions.Count, true /* caseInsensitive */); foreach (object obj in webPartDescriptions) { if (obj == null) { throw new ArgumentException(SR.GetString(SR.Collection_CantAddNull), "webPartDescriptions"); } WebPartDescription description = obj as WebPartDescription; if (description == null) { throw new ArgumentException(SR.GetString(SR.Collection_InvalidType, "WebPartDescription"), "webPartDescriptions"); } string id = description.ID; if (!_ids.Contains(id)) { InnerList.Add(description); _ids.Add(id, description); } else { throw new ArgumentException(SR.GetString(SR.WebPart_Collection_DuplicateID, "WebPartDescription", id), "webPartDescriptions"); } } }
public BasicPropertiesWrapper(IBasicProperties basicProperties) { ContentType = basicProperties.ContentType; ContentEncoding = basicProperties.ContentEncoding; DeliveryMode = basicProperties.DeliveryMode; Priority = basicProperties.Priority; CorrelationId = basicProperties.CorrelationId; ReplyTo = basicProperties.ReplyTo; Expiration = basicProperties.Expiration; MessageId = basicProperties.MessageId; Timestamp = basicProperties.Timestamp.UnixTime; Type = basicProperties.Type; UserId = basicProperties.UserId; AppId = basicProperties.AppId; ClusterId = basicProperties.ClusterId; if (basicProperties.IsHeadersPresent()) { Headers = new HybridDictionary(); foreach (DictionaryEntry header in basicProperties.Headers) { Headers.Add(header.Key, header.Value); } } }
public UI(UIComponentGroup headGroup) { m_menuDictionary = new HybridDictionary(4, true); m_menuStack = new UIMenuStack(); UIMenu menu = new UIMenu(headGroup); m_menuDictionary.Add(1, menu); }
/// <summary> /// Initializes a new instance of the <see cref="UserBadgeManager" /> class. /// </summary> /// <param name="userId">The user identifier.</param> /// <param name="data">The data.</param> internal UserBadgeManager(uint userId, UserData data) { BadgeList = new HybridDictionary(); foreach (Badge current in data.Badges.Where(current => !BadgeList.Contains(current.Code))) BadgeList.Add(current.Code, current); _userId = userId; }
protected virtual object MappingInternal(IStatementSetting statement, IDictionary dictionary, Type instanceType, object instance) { var parameters = new HybridDictionary { { typeof(IObjectMapper), dictionary } }; if(instance != null) { parameters.Add(typeof(ObjectMapperExtender), instance); } var resultType = statement.ResultTypeName; return this.GetOrCreateObject(resultType, instanceType, parameters, x => ObjectMapper.RefectionMapping(x, dictionary)); }
// populate a dictionary from the given list private static HybridDictionary DictionaryFromList(Type[] types) { HybridDictionary dictionary = new HybridDictionary(types.Length); for (int i=0; i<types.Length; ++i) { dictionary.Add(types[i], null); } return dictionary; }
private IEnumerable<Mailbox> RemoveMailbox(IEnumerable<Mailbox> source, string email) { email = email.With(_ => _.Trim()); var addresses = new HybridDictionary(); if (!string.IsNullOrEmpty(email)) foreach (Mailbox mailbox in MailboxList.Parse(email)) if (!string.IsNullOrEmpty(mailbox.Address)) addresses.Add(mailbox.Address.ToLower(), mailbox); foreach (Mailbox item in source) if (addresses.Count == 0 || !addresses.Contains(item.Address.ToLower())) yield return item; }
public void HybridDictionaryTest() { string methodName = "HybridDictionaryTest"; string filePath = className + "." + methodName + ".xml"; HybridDictionary hybridDictionary = new HybridDictionary(); hybridDictionary.Add(1, "Aaron"); hybridDictionary.Add(2, "Monica"); hybridDictionary.Add(3, "Michelle"); hybridDictionary.Add(4, "Michael"); hybridDictionary.Add(5, "Nathan"); FileStream fs = new FileStream(filePath, FileMode.Create); DictionarySerializer ds = new DictionarySerializer(hybridDictionary); XmlSerializer s = new XmlSerializer(typeof (DictionarySerializer)); s.Serialize(fs, ds); fs.Close(); FileStream fsopen = new FileStream(filePath, FileMode.Open); ds = (DictionarySerializer) s.Deserialize(fsopen); Console.WriteLine("Deserialized " + ds.dictionary.Count + " items"); }
public void All () { HybridDictionary dict = new HybridDictionary (true); dict.Add ("CCC", "ccc"); dict.Add ("BBB", "bbb"); dict.Add ("fff", "fff"); dict ["EEE"] = "eee"; dict ["ddd"] = "ddd"; Assert.AreEqual (5, dict.Count, "#1"); Assert.AreEqual ("eee", dict["eee"], "#2"); dict.Add ("CCC2", "ccc"); dict.Add ("BBB2", "bbb"); dict.Add ("fff2", "fff"); dict ["EEE2"] = "eee"; dict ["ddd2"] = "ddd"; dict ["xxx"] = "xxx"; dict ["yyy"] = "yyy"; Assert.AreEqual (12, dict.Count, "#3"); Assert.AreEqual ("eee", dict["eee"], "#4"); dict.Remove ("eee"); Assert.AreEqual (11, dict.Count, "Removed/Count"); Assert.IsFalse (dict.Contains ("eee"), "Removed/Contains(xxx)"); DictionaryEntry[] entries = new DictionaryEntry [11]; dict.CopyTo (entries, 0); Assert.IsTrue (dict.Contains ("xxx"), "Contains(xxx)"); dict.Clear (); Assert.AreEqual (0, dict.Count, "Cleared/Count"); Assert.IsFalse (dict.Contains ("xxx"), "Cleared/Contains(xxx)"); }
public ChannelDemultiplexer(IChannel[] channels, int[] ids, IChannel input, bool autoStart, bool waitOnStop) : base(true,autoStart,waitOnStop) { this.input = input; int count = channels.Length; if(count != ids.Length) throw new ArgumentException("Channel and ID count mismatch.","ids"); dictionary = new HybridDictionary(count,true); for(int i=0;i<count;i++) dictionary.Add(ids[i],channels[i]); }
/// <summary> /// Obtain the property name corresponding to a given column name. /// </summary> /// <param name="name">The name of the column</param> /// <returns>The corresponding FieldMap</returns> public FieldMap FindColumn( string name ) { Check.VerifyNotNull( name, Error.NullParameter, "name" ); if( columns == null ) { columns = new HybridDictionary( fields.Count, true ); foreach( FieldMap fm in fields ) { columns.Add( fm.ColumnName, fm ); } } return columns[ name ] as FieldMap; }
/// <summary> /// Obtain the column name corresponding to a given property name. /// </summary> /// <param name="name">The name of the property</param> /// <returns>The corresponding FieldMap</returns> public FieldMap FindProperty( string name ) { Check.VerifyNotNull( name, Error.NullParameter, "name" ); if( properties == null ) { properties = new HybridDictionary( fields.Count, true ); foreach( FieldMap fm in fields ) { properties.Add( fm.MemberName, fm ); } } return properties[ name ] as FieldMap; }
public s2h.s2h_errors CreateConnection(string host, int port, out s2hConnection conn) { SocksOverHttp.s2h.s2h_errors iRes; Socket socket = null; conn = new s2hConnection(); iRes = conn.Connect(host, port, out socket); if (iRes != s2h.s2h_errors.s2h_ok) { try { conn.Close(); } catch (Exception) {} conn = null; } lock (m_Connections) { m_Connections.Add(conn.handle, conn); } return(iRes); }
private static string GetFontTable(Font font) { var fontTable = new StringBuilder(); // Append table control string fontTable.Append(@"{\fonttbl{\f0"); fontTable.Append(@"\"); var rtfFontFamily = new HybridDictionary(); rtfFontFamily.Add(FontFamily.GenericMonospace.Name, RtfFontFamilyDef.Modern); rtfFontFamily.Add(FontFamily.GenericSansSerif, RtfFontFamilyDef.Swiss); rtfFontFamily.Add(FontFamily.GenericSerif, RtfFontFamilyDef.Roman); rtfFontFamily.Add("UNKNOWN", RtfFontFamilyDef.Unknown); // If the font's family corresponds to an RTF family, append the // RTF family name, else, append the RTF for unknown font family. fontTable.Append(rtfFontFamily.Contains(font.FontFamily.Name) ? rtfFontFamily[font.FontFamily.Name] : rtfFontFamily["UNKNOWN"]); // \fcharset specifies the character set of a font in the font table. // 0 is for ANSI. fontTable.Append(@"\fcharset0 "); // Append the name of the font fontTable.Append(font.Name); // Close control string fontTable.Append(@";}}"); return fontTable.ToString(); }
private bool ClearInternal(bool clearing) { lock (this) { HybridDictionary dictionary2 = this._poolCollection; if (0 < dictionary2.Count) { HybridDictionary dictionary = new HybridDictionary(dictionary2.Count, false); foreach (DictionaryEntry entry in dictionary2) { if (entry.Value != null) { System.Data.ProviderBase.DbConnectionPool pool = (System.Data.ProviderBase.DbConnectionPool) entry.Value; if (clearing || (!pool.ErrorOccurred && (pool.Count == 0))) { System.Data.ProviderBase.DbConnectionFactory connectionFactory = pool.ConnectionFactory; connectionFactory.PerformanceCounters.NumberOfActiveConnectionPools.Decrement(); connectionFactory.QueuePoolForRelease(pool, clearing); } else { dictionary.Add(entry.Key, entry.Value); } } } this._poolCollection = dictionary; this._poolCount = dictionary.Count; } if (!clearing && (this._poolCount == 0)) { if (1 == this._state) { this._state = 2; Bid.Trace("<prov.DbConnectionPoolGroup.ClearInternal|RES|INFO|CPOOL> %d#, Idle\n", this.ObjectID); } else if (2 == this._state) { this._state = 4; Bid.Trace("<prov.DbConnectionPoolGroup.ReadyToRemove|RES|INFO|CPOOL> %d#, Disabled\n", this.ObjectID); } } return (4 == this._state); } }
public virtual void TestSizeOne() { ICacheController cc = GetController(); IDictionary props = new HybridDictionary(); props.Add("CacheSize", "1"); cc.Configure(props); string testKey = "testKey"; string testVal = "testVal"; cc[testKey] = testVal; Assert.AreEqual(testVal, cc[testKey] ); string testKey2 = "testKey2"; string testVal2 = "testVal2"; cc[testKey2] = testVal2; Assert.AreEqual(testVal2, cc[testKey2]); Assert.IsNull(cc[testKey]); }
/// <summary> /// Initializes a new instance of the <see cref="Languages" /> class. /// </summary> /// <param name="language">The language.</param> internal Languages(string language) { Texts = new HybridDictionary(); using (var queryReactor = Azure.GetDatabaseManager().GetQueryReactor()) { queryReactor.SetQuery($"SELECT * FROM server_langs WHERE lang = '{language}' ORDER BY id DESC"); var table = queryReactor.GetTable(); if (table == null) return; foreach (DataRow dataRow in table.Rows) { var name = dataRow["name"].ToString(); var text = dataRow["text"].ToString(); Texts.Add(name, text); } } }
/// <summary> /// Initializes a new instance of the <see cref="ServerLanguageSettings" /> class. /// </summary> /// <param name="language">The language.</param> internal ServerLanguageSettings(string language) { Texts = new HybridDictionary(); using (IQueryAdapter queryReactor = Yupi.GetDatabaseManager().GetQueryReactor()) { queryReactor.SetQuery($"SELECT * FROM server_langs WHERE lang = '{language}' ORDER BY id DESC"); DataTable table = queryReactor.GetTable(); if (table == null) return; foreach (DataRow dataRow in table.Rows) { string name = dataRow["name"].ToString(); string text = dataRow["text"].ToString(); Texts.Add(name, text); } } }
public void TestReturnInstanceOfCachedOject() { ICacheController cacheController = new LruCacheController(); IDictionary props = new HybridDictionary(); props.Add("CacheSize", "1"); cacheController.Configure(props); FlushInterval interval = new FlushInterval(); interval.Hours = 1; interval.Initialize(); CacheModel cacheModel = new CacheModel(); cacheModel.FlushInterval = interval; cacheModel.CacheController = cacheController; cacheModel.IsReadOnly = true; cacheModel.IsSerializable = false; Order order = new Order(); order.CardNumber = "CardNumber"; order.Date = DateTime.Now; order.LineItemsCollection = new LineItemCollection(); LineItem item = new LineItem(); item.Code = "Code1"; order.LineItemsCollection.Add(item); item = new LineItem(); item.Code = "Code2"; order.LineItemsCollection.Add(item); CacheKey key = new CacheKey(); key.Update(order); int firstId = HashCodeProvider.GetIdentityHashCode(order); cacheModel[ key ] = order; Order order2 = cacheModel[ key ] as Order; int secondId = HashCodeProvider.GetIdentityHashCode(order2); Assert.AreEqual(firstId, secondId, "hasCode different"); }
private void Initialize(WebPartVerbCollection existingVerbs, ICollection verbs) { int count = ((existingVerbs != null) ? existingVerbs.Count : 0) + ((verbs != null) ? verbs.Count : 0); _ids = new HybridDictionary(count, /* caseInsensitive */ true); if (existingVerbs != null) { foreach (WebPartVerb existingVerb in existingVerbs) { // Don't need to check arg, since we know it is valid since it came // from a CatalogPartCollection. if (_ids.Contains(existingVerb.ID)) { throw new ArgumentException(SR.GetString(SR.WebPart_Collection_DuplicateID, "WebPartVerb", existingVerb.ID), "existingVerbs"); } _ids.Add(existingVerb.ID, existingVerb); InnerList.Add(existingVerb); } } if (verbs != null) { foreach (object obj in verbs) { if (obj == null) { throw new ArgumentException(SR.GetString(SR.Collection_CantAddNull), "verbs"); } WebPartVerb webPartVerb = obj as WebPartVerb; if (webPartVerb == null) { throw new ArgumentException(SR.GetString(SR.Collection_InvalidType, "WebPartVerb"), "verbs"); } if (_ids.Contains(webPartVerb.ID)) { throw new ArgumentException(SR.GetString(SR.WebPart_Collection_DuplicateID, "WebPartVerb", webPartVerb.ID), "verbs"); } _ids.Add(webPartVerb.ID, webPartVerb); InnerList.Add(webPartVerb); } } }
public void All () { HybridDictionary dict = new HybridDictionary (true); dict.Add ("CCC", "ccc"); dict.Add ("BBB", "bbb"); dict.Add ("fff", "fff"); dict ["EEE"] = "eee"; dict ["ddd"] = "ddd"; Assertion.AssertEquals ("#1", 5, dict.Count); Assertion.AssertEquals ("#2", "eee", dict ["eee"]); dict.Add ("CCC2", "ccc"); dict.Add ("BBB2", "bbb"); dict.Add ("fff2", "fff"); dict ["EEE2"] = "eee"; dict ["ddd2"] = "ddd"; dict ["xxx"] = "xxx"; dict ["yyy"] = "yyy"; Assertion.AssertEquals ("#3", 12, dict.Count); Assertion.AssertEquals ("#4", "eee", dict ["eee"]); }
public void Test01() { HybridDictionary hd; int cnt; const int BIG_LENGTH = 100; // simple string values string[] valuesShort = { "", " ", "$%^#", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keysShort = { Int32.MaxValue.ToString(), " ", System.DateTime.Today.ToString(), "", "$%^#" }; string[] valuesLong = new string[BIG_LENGTH]; string[] keysLong = new string[BIG_LENGTH]; for (int i = 0; i < BIG_LENGTH; i++) { valuesLong[i] = "Item" + i; keysLong[i] = "keY" + i; } // [] HybridDictionary.IsSynchronized should return false //----------------------------------------------------------------- hd = new HybridDictionary(); // [] on empty dictionary // if (hd.IsSynchronized) { Assert.False(true, string.Format("Error, returned true for empty dictionary")); } // [] on short filled dictionary // hd.Clear(); cnt = valuesShort.Length; for (int i = 0; i < cnt; i++) { hd.Add(keysShort[i], valuesShort[i]); } if (hd.Count != cnt) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, cnt)); } if (hd.IsSynchronized) { Assert.False(true, string.Format("Error, returned true for short filled dictionary")); } // [] on long filled dictionary // hd.Clear(); cnt = valuesLong.Length; for (int i = 0; i < cnt; i++) { hd.Add(keysLong[i], valuesLong[i]); } if (hd.Count != cnt) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, cnt)); } if (hd.IsSynchronized) { Assert.False(true, string.Format("Error, returned true for long filled dictionary")); } }
public void Test01() { const int BIG_LENGTH = 100; HybridDictionary hd; // simple string values string[] valuesShort = { "", " ", "$%^#", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keysShort = { Int32.MaxValue.ToString(), " ", System.DateTime.Today.ToString(), "", "$%^#" }; string[] valuesLong = new string[BIG_LENGTH]; string[] keysLong = new string[BIG_LENGTH]; Array arr; ICollection vs; // Values collection int ind; for (int i = 0; i < BIG_LENGTH; i++) { valuesLong[i] = "Item" + i; keysLong[i] = "keY" + i; } // [] HybridDictionary is constructed as expected //----------------------------------------------------------------- hd = new HybridDictionary(); // [] for empty dictionary // if (hd.Count > 0) hd.Clear(); if (hd.Values.Count != 0) { Assert.False(true, string.Format("Error, returned Values.Count = {0}", hd.Values.Count)); } // [] for short filled dictionary // int len = valuesShort.Length; hd.Clear(); for (int i = 0; i < len; i++) { hd.Add(keysShort[i], valuesShort[i]); } if (hd.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len)); } vs = hd.Values; if (vs.Count != len) { Assert.False(true, string.Format("Error, returned Values.Count = {0}", vs.Count)); } arr = Array.CreateInstance(typeof(Object), len); vs.CopyTo(arr, 0); for (int i = 0; i < len; i++) { ind = Array.IndexOf(arr, valuesShort[i]); if (ind < 0) { Assert.False(true, string.Format("Error, Values doesn't contain \"{1}\" value. Search result: {2}", i, valuesShort[i], ind)); } } // [] for long filled dictionary // len = valuesLong.Length; hd.Clear(); for (int i = 0; i < len; i++) { hd.Add(keysLong[i], valuesLong[i]); } if (hd.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len)); } vs = hd.Values; if (vs.Count != len) { Assert.False(true, string.Format("Error, returned Values.Count = {0}", vs.Count)); } arr = Array.CreateInstance(typeof(Object), len); vs.CopyTo(arr, 0); for (int i = 0; i < len; i++) { ind = Array.IndexOf(arr, valuesLong[i]); if (ind < 0) { Assert.False(true, string.Format("Error, Values doesn't contain \"{1}\" value. Search result: {2}", i, valuesLong[i], ind)); } } // // [] get Values on dictionary with different_in_casing_only keys - list // hd.Clear(); string intlStr = "intlStr"; hd.Add("keykey", intlStr); // 1st key hd.Add("keyKey", intlStr); // 2nd key if (hd.Count != 2) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, 2)); } // get Values // vs = hd.Values; if (vs.Count != hd.Count) { Assert.False(true, string.Format("Error, returned Values.Count = {0}", vs.Count)); } arr = Array.CreateInstance(typeof(Object), 2); vs.CopyTo(arr, 0); ind = Array.IndexOf(arr, intlStr); if (ind < 0) { Assert.False(true, string.Format("Error, Values doesn't contain {0} value", intlStr)); } // // [] get Values on dictionary with different_in_casing_only keys - hashtable // hd.Clear(); hd.Add("keykey", intlStr); // 1st key for (int i = 0; i < BIG_LENGTH; i++) { hd.Add(keysLong[i], valuesLong[i]); } hd.Add("keyKey", intlStr); // 2nd key if (hd.Count != BIG_LENGTH + 2) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, BIG_LENGTH + 2)); } // get Values // vs = hd.Values; if (vs.Count != hd.Count) { Assert.False(true, string.Format("Error, returned Values.Count = {0}", vs.Count)); } arr = Array.CreateInstance(typeof(Object), BIG_LENGTH + 2); vs.CopyTo(arr, 0); for (int i = 0; i < BIG_LENGTH; i++) { if (Array.IndexOf(arr, valuesLong[i]) < 0) { Assert.False(true, string.Format("Error, Values doesn't contain {0} value", valuesLong[i], i)); } } ind = Array.IndexOf(arr, intlStr); if (ind < 0) { Assert.False(true, string.Format("Error, Values doesn't contain {0} value", intlStr)); } // // [] Change long dictionary and check Values // hd.Clear(); len = valuesLong.Length; for (int i = 0; i < len; i++) { hd.Add(keysLong[i], valuesLong[i]); } if (hd.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len)); } vs = hd.Values; if (vs.Count != len) { Assert.False(true, string.Format("Error, returned Values.Count = {0}", vs.Count)); } hd.Remove(keysLong[0]); if (hd.Count != len - 1) { Assert.False(true, string.Format("Error, didn't remove element")); } if (vs.Count != len - 1) { Assert.False(true, string.Format("Error, Values were not updated after removal")); } arr = Array.CreateInstance(typeof(Object), hd.Count); vs.CopyTo(arr, 0); ind = Array.IndexOf(arr, valuesLong[0]); if (ind >= 0) { Assert.False(true, string.Format("Error, Values still contains removed value " + ind)); } hd.Add(keysLong[0], "new item"); if (hd.Count != len) { Assert.False(true, string.Format("Error, didn't add element")); } if (vs.Count != len) { Assert.False(true, string.Format("Error, Values were not updated after addition")); } arr = Array.CreateInstance(typeof(Object), hd.Count); vs.CopyTo(arr, 0); ind = Array.IndexOf(arr, "new item"); if (ind < 0) { Assert.False(true, string.Format("Error, Values doesn't contain added value ")); } // // [] Change short dictionary and check Values // hd.Clear(); len = valuesShort.Length; for (int i = 0; i < len; i++) { hd.Add(keysShort[i], valuesShort[i]); } if (hd.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len)); } vs = hd.Values; if (vs.Count != len) { Assert.False(true, string.Format("Error, returned Values.Count = {0}", vs.Count)); } hd.Remove(keysShort[0]); if (hd.Count != len - 1) { Assert.False(true, string.Format("Error, didn't remove element")); } if (vs.Count != len - 1) { Assert.False(true, string.Format("Error, Values were not updated after removal")); } arr = Array.CreateInstance(typeof(Object), hd.Count); vs.CopyTo(arr, 0); ind = Array.IndexOf(arr, valuesShort[0]); if (ind >= 0) { Assert.False(true, string.Format("Error, Values still contains removed value " + ind)); } hd.Add(keysShort[0], "new item"); if (hd.Count != len) { Assert.False(true, string.Format("Error, didn't add element")); } if (vs.Count != len) { Assert.False(true, string.Format("Error, Values were not updated after addition")); } arr = Array.CreateInstance(typeof(Object), hd.Count); vs.CopyTo(arr, 0); ind = Array.IndexOf(arr, "new item"); if (ind < 0) { Assert.False(true, string.Format("Error, Values doesn't contain added value ")); } }
/// <summary> /// Gets the bar width distribution and calculates narrow bar width over the specified /// range of the histogramResult. A histogramResult could have multiple ranges, separated /// by quiet zones. /// </summary> /// <param name="hist">histogramResult data</param> /// <param name="iStart">start coordinate to be considered</param> /// <param name="iEnd">end coordinate + 1</param> private static void GetBarWidthDistribution(ref histogramResult hist, int iStart, int iEnd) { HybridDictionary hdLightBars = new HybridDictionary(); HybridDictionary hdDarkBars = new HybridDictionary(); bool bDarkBar = (hist.histogram[iStart] <= hist.threshold); int iBarStart = 0; for (int i = iStart + 1; i < iEnd; i++) { bool bDark = (hist.histogram[i] <= hist.threshold); if (bDark != bDarkBar) { int iBarWidth = i - iBarStart; if (bDarkBar) { if (!hdDarkBars.Contains(iBarWidth)) hdDarkBars.Add(iBarWidth, 1); else hdDarkBars[iBarWidth] = (int)hdDarkBars[iBarWidth] + 1; } else { if (!hdLightBars.Contains(iBarWidth)) hdLightBars.Add(iBarWidth, 1); else hdLightBars[iBarWidth] = (int)hdLightBars[iBarWidth] + 1; } bDarkBar = bDark; iBarStart = i; } } // Now get the most common bar widths CalcNarrowBarWidth(hdLightBars, out hist.lightnarrowbarwidth, out hist.lightwiderbarwidth); CalcNarrowBarWidth(hdDarkBars, out hist.darknarrowbarwidth, out hist.darkwiderbarwidth); }
public string setInLineStyles(string htmlContent) { htmlContent = this.removeStylesForFirstDiv(htmlContent); int startIndex = 0; int indexClass = htmlContent.IndexOf("class", startIndex); HybridDictionary hdStyles = new System.Collections.Specialized.HybridDictionary(); // The token class was found: while (indexClass >= 0) { int nextChar = indexClass + 5; string className = string.Empty; // It is a class attribute applied to a html tag: if (nextChar < htmlContent.Length && htmlContent[nextChar] == '=') { // Get the class name: for (int i = nextChar + 1; htmlContent[i] != ' ' && htmlContent[i] != '>'; i++) { className += htmlContent[i]; } } if (!string.IsNullOrEmpty(className) && !hdStyles.Contains(className)) { string classDef = this.getClassDefinition(htmlContent, className); if (!string.IsNullOrEmpty(classDef) && !hdStyles.Contains(className)) { hdStyles.Add(className, classDef); } } startIndex = indexClass + 5; indexClass = htmlContent.IndexOf("class", startIndex); } string htmlContentChanged = string.Empty; // We finished to collect all the class elements and its definitions: if (hdStyles.Count > 0) { StringBuilder sbClasses = new StringBuilder(htmlContent); // We are ready to replace class entries to inline styles: IDictionaryEnumerator e = hdStyles.GetEnumerator(); while (e.MoveNext()) { string classToReplace = "class=" + e.Key.ToString(); string inlineStyle = "style=\"" + e.Value.ToString() + "\""; // First option: sbClasses.Replace(classToReplace, inlineStyle); // Second option: classToReplace = "class=\"" + e.Key.ToString() + "\""; sbClasses.Replace(classToReplace, inlineStyle); } htmlContentChanged = sbClasses.ToString(); } else { htmlContentChanged = htmlContent; } return(htmlContentChanged); }
public void Populate() { #region Types of Keywords FieldPublicDynamic = new { PropPublic1 = "A", PropPublic2 = 1, PropPublic3 = "B", PropPublic4 = "B", PropPublic5 = "B", PropPublic6 = "B", PropPublic7 = "B", PropPublic8 = "B", PropPublic9 = "B", PropPublic10 = "B", PropPublic11 = "B", PropPublic12 = new { PropSubPublic1 = 0, PropSubPublic2 = 1, PropSubPublic3 = 2 } }; FieldPublicObject = new StringBuilder("Object - StringBuilder"); FieldPublicInt32 = int.MaxValue; FieldPublicInt64 = long.MaxValue; FieldPublicULong = ulong.MaxValue; FieldPublicUInt = uint.MaxValue; FieldPublicDecimal = 100000.999999m; FieldPublicDouble = 100000.999999d; FieldPublicChar = 'A'; FieldPublicByte = byte.MaxValue; FieldPublicBoolean = true; FieldPublicSByte = sbyte.MaxValue; FieldPublicShort = short.MaxValue; FieldPublicUShort = ushort.MaxValue; FieldPublicFloat = 100000.675555f; FieldPublicInt32Nullable = int.MaxValue; FieldPublicInt64Nullable = 2; FieldPublicULongNullable = ulong.MaxValue; FieldPublicUIntNullable = uint.MaxValue; FieldPublicDecimalNullable = 100000.999999m; FieldPublicDoubleNullable = 100000.999999d; FieldPublicCharNullable = 'A'; FieldPublicByteNullable = byte.MaxValue; FieldPublicBooleanNullable = true; FieldPublicSByteNullable = sbyte.MaxValue; FieldPublicShortNullable = short.MaxValue; FieldPublicUShortNullable = ushort.MaxValue; FieldPublicFloatNullable = 100000.675555f; #endregion #region System FieldPublicDateTime = new DateTime(2000, 1, 1, 1, 1, 1); FieldPublicTimeSpan = new TimeSpan(1, 10, 40); FieldPublicEnumDateTimeKind = DateTimeKind.Local; // Instantiate date and time using Persian calendar with years, // months, days, hours, minutes, seconds, and milliseconds FieldPublicDateTimeOffset = new DateTimeOffset(1387, 2, 12, 8, 6, 32, 545, new System.Globalization.PersianCalendar(), new TimeSpan(1, 0, 0)); FieldPublicIntPtr = new IntPtr(100); FieldPublicTimeZone = TimeZone.CurrentTimeZone; FieldPublicTimeZoneInfo = TimeZoneInfo.Utc; FieldPublicTuple = Tuple.Create <string, int, decimal>("T-string\"", 1, 1.1m); FieldPublicType = typeof(object); FieldPublicUIntPtr = new UIntPtr(100); FieldPublicUri = new Uri("http://www.site.com"); FieldPublicVersion = new Version(1, 0, 100, 1); FieldPublicGuid = new Guid("d5010f5b-0cd1-44ca-aacb-5678b9947e6c"); FieldPublicSingle = Single.MaxValue; FieldPublicException = new Exception("Test error", new Exception("inner exception")); FieldPublicEnumNonGeneric = EnumTest.ValueA; FieldPublicAction = () => true.Equals(true); FieldPublicAction2 = (a, b) => true.Equals(true); FieldPublicFunc = () => true; FieldPublicFunc2 = (a, b) => true; #endregion #region Arrays and Collections FieldPublicArrayUni = new string[2]; FieldPublicArrayUni[0] = "[0]"; FieldPublicArrayUni[1] = "[1]"; FieldPublicArrayTwo = new string[2, 2]; FieldPublicArrayTwo[0, 0] = "[0, 0]"; FieldPublicArrayTwo[0, 1] = "[0, 1]"; FieldPublicArrayTwo[1, 0] = "[1, 0]"; FieldPublicArrayTwo[1, 1] = "[1, 1]"; FieldPublicArrayThree = new string[1, 1, 2]; FieldPublicArrayThree[0, 0, 0] = "[0, 0, 0]"; FieldPublicArrayThree[0, 0, 1] = "[0, 0, 1]"; FieldPublicJaggedArrayTwo = new string[2][]; FieldPublicJaggedArrayTwo[0] = new string[5] { "a", "b", "c", "d", "e" }; FieldPublicJaggedArrayTwo[1] = new string[4] { "a1", "b1", "c1", "d1" }; FieldPublicJaggedArrayThree = new string[1][][]; FieldPublicJaggedArrayThree[0] = new string[1][]; FieldPublicJaggedArrayThree[0][0] = new string[2]; FieldPublicJaggedArrayThree[0][0][0] = "[0][0][0]"; FieldPublicJaggedArrayThree[0][0][1] = "[0][0][1]"; FieldPublicMixedArrayAndJagged = new int[3][, ] { new int[, ] { { 1, 3 }, { 5, 7 } }, new int[, ] { { 0, 2 }, { 4, 6 }, { 8, 10 } }, new int[, ] { { 11, 22 }, { 99, 88 }, { 0, 9 } } }; FieldPublicDictionary = new System.Collections.Generic.Dictionary <string, string>(); FieldPublicDictionary.Add("Key1", "Value1"); FieldPublicDictionary.Add("Key2", "Value2"); FieldPublicDictionary.Add("Key3", "Value3"); FieldPublicDictionary.Add("Key4", "Value4"); FieldPublicList = new System.Collections.Generic.List <int>(); FieldPublicList.Add(0); FieldPublicList.Add(1); FieldPublicList.Add(2); FieldPublicQueue = new System.Collections.Generic.Queue <int>(); FieldPublicQueue.Enqueue(10); FieldPublicQueue.Enqueue(11); FieldPublicQueue.Enqueue(12); FieldPublicHashSet = new System.Collections.Generic.HashSet <string>(); FieldPublicHashSet.Add("HashSet1"); FieldPublicHashSet.Add("HashSet2"); FieldPublicSortedSet = new System.Collections.Generic.SortedSet <string>(); FieldPublicSortedSet.Add("SortedSet1"); FieldPublicSortedSet.Add("SortedSet2"); FieldPublicSortedSet.Add("SortedSet3"); FieldPublicStack = new System.Collections.Generic.Stack <string>(); FieldPublicStack.Push("Stack1"); FieldPublicStack.Push("Stack2"); FieldPublicStack.Push("Stack3"); FieldPublicLinkedList = new System.Collections.Generic.LinkedList <string>(); FieldPublicLinkedList.AddFirst("LinkedList1"); FieldPublicLinkedList.AddLast("LinkedList2"); FieldPublicLinkedList.AddAfter(FieldPublicLinkedList.Find("LinkedList1"), "LinkedList1.1"); FieldPublicObservableCollection = new System.Collections.ObjectModel.ObservableCollection <string>(); FieldPublicObservableCollection.Add("ObservableCollection1"); FieldPublicObservableCollection.Add("ObservableCollection2"); FieldPublicKeyedCollection = new MyDataKeyedCollection(); FieldPublicKeyedCollection.Add(new MyData() { Data = "data1", Id = 0 }); FieldPublicKeyedCollection.Add(new MyData() { Data = "data2", Id = 1 }); var list = new List <string>(); list.Add("list1"); list.Add("list2"); list.Add("list3"); FieldPublicReadOnlyCollection = new ReadOnlyCollection <string>(list); FieldPublicReadOnlyDictionary = new ReadOnlyDictionary <string, string>(FieldPublicDictionary); FieldPublicReadOnlyObservableCollection = new ReadOnlyObservableCollection <string>(FieldPublicObservableCollection); FieldPublicCollection = new Collection <string>(); FieldPublicCollection.Add("collection1"); FieldPublicCollection.Add("collection2"); FieldPublicCollection.Add("collection3"); FieldPublicArrayListNonGeneric = new System.Collections.ArrayList(); FieldPublicArrayListNonGeneric.Add(1); FieldPublicArrayListNonGeneric.Add("a"); FieldPublicArrayListNonGeneric.Add(10.0m); FieldPublicArrayListNonGeneric.Add(new DateTime(2000, 01, 01)); FieldPublicBitArray = new System.Collections.BitArray(3); FieldPublicBitArray[2] = true; FieldPublicSortedList = new System.Collections.SortedList(); FieldPublicSortedList.Add("key1", 1); FieldPublicSortedList.Add("key2", 2); FieldPublicSortedList.Add("key3", 3); FieldPublicSortedList.Add("key4", 4); FieldPublicHashtableNonGeneric = new System.Collections.Hashtable(); FieldPublicHashtableNonGeneric.Add("key1", 1); FieldPublicHashtableNonGeneric.Add("key2", 2); FieldPublicHashtableNonGeneric.Add("key3", 3); FieldPublicHashtableNonGeneric.Add("key4", 4); FieldPublicQueueNonGeneric = new System.Collections.Queue(); FieldPublicQueueNonGeneric.Enqueue("QueueNonGeneric1"); FieldPublicQueueNonGeneric.Enqueue("QueueNonGeneric2"); FieldPublicQueueNonGeneric.Enqueue("QueueNonGeneric3"); FieldPublicStackNonGeneric = new System.Collections.Stack(); FieldPublicStackNonGeneric.Push("StackNonGeneric1"); FieldPublicStackNonGeneric.Push("StackNonGeneric2"); FieldPublicIEnumerable = FieldPublicSortedList; FieldPublicBlockingCollection = new System.Collections.Concurrent.BlockingCollection <string>(); FieldPublicBlockingCollection.Add("BlockingCollection1"); FieldPublicBlockingCollection.Add("BlockingCollection2"); FieldPublicConcurrentBag = new System.Collections.Concurrent.ConcurrentBag <string>(); FieldPublicConcurrentBag.Add("ConcurrentBag1"); FieldPublicConcurrentBag.Add("ConcurrentBag2"); FieldPublicConcurrentBag.Add("ConcurrentBag3"); FieldPublicConcurrentDictionary = new System.Collections.Concurrent.ConcurrentDictionary <string, int>(); FieldPublicConcurrentDictionary.GetOrAdd("ConcurrentDictionary1", 0); FieldPublicConcurrentDictionary.GetOrAdd("ConcurrentDictionary2", 0); FieldPublicConcurrentQueue = new System.Collections.Concurrent.ConcurrentQueue <string>(); FieldPublicConcurrentQueue.Enqueue("ConcurrentQueue1"); FieldPublicConcurrentQueue.Enqueue("ConcurrentQueue2"); FieldPublicConcurrentStack = new System.Collections.Concurrent.ConcurrentStack <string>(); FieldPublicConcurrentStack.Push("ConcurrentStack1"); FieldPublicConcurrentStack.Push("ConcurrentStack2"); // FieldPublicOrderablePartitioner = new OrderablePartitioner(); // FieldPublicPartitioner; // FieldPublicPartitionerNonGeneric; FieldPublicHybridDictionary = new System.Collections.Specialized.HybridDictionary(); FieldPublicHybridDictionary.Add("HybridDictionaryKey1", "HybridDictionary1"); FieldPublicHybridDictionary.Add("HybridDictionaryKey2", "HybridDictionary2"); FieldPublicListDictionary = new System.Collections.Specialized.ListDictionary(); FieldPublicListDictionary.Add("ListDictionaryKey1", "ListDictionary1"); FieldPublicListDictionary.Add("ListDictionaryKey2", "ListDictionary2"); FieldPublicNameValueCollection = new System.Collections.Specialized.NameValueCollection(); FieldPublicNameValueCollection.Add("Key1", "Value1"); FieldPublicNameValueCollection.Add("Key2", "Value2"); FieldPublicOrderedDictionary = new System.Collections.Specialized.OrderedDictionary(); FieldPublicOrderedDictionary.Add(1, "OrderedDictionary1"); FieldPublicOrderedDictionary.Add(2, "OrderedDictionary1"); FieldPublicOrderedDictionary.Add("OrderedDictionaryKey2", "OrderedDictionary2"); FieldPublicStringCollection = new System.Collections.Specialized.StringCollection(); FieldPublicStringCollection.Add("StringCollection1"); FieldPublicStringCollection.Add("StringCollection2"); #endregion #region Several PropXmlDocument = new XmlDocument(); PropXmlDocument.LoadXml("<xml>something</xml>"); var tr = new StringReader("<Root>Content</Root>"); PropXDocument = XDocument.Load(tr); PropStream = GenerateStreamFromString("Stream"); PropBigInteger = new System.Numerics.BigInteger(100); PropStringBuilder = new StringBuilder("StringBuilder"); FieldPublicIQueryable = new List <string>() { "IQueryable" }.AsQueryable(); #endregion #region Custom FieldPublicMyCollectionPublicGetEnumerator = new MyCollectionPublicGetEnumerator("a b c", new char[] { ' ' }); FieldPublicMyCollectionInheritsPublicGetEnumerator = new MyCollectionInheritsPublicGetEnumerator("a b c", new char[] { ' ' }); FieldPublicMyCollectionExplicitGetEnumerator = new MyCollectionExplicitGetEnumerator("a b c", new char[] { ' ' }); FieldPublicMyCollectionInheritsExplicitGetEnumerator = new MyCollectionInheritsExplicitGetEnumerator("a b c", new char[] { ' ' }); FieldPublicMyCollectionInheritsTooIEnumerable = new MyCollectionInheritsTooIEnumerable("a b c", new char[] { ' ' }); FieldPublicEnumSpecific = EnumTest.ValueB; MyDelegate = MethodDelegate; EmptyClass = new EmptyClass(); StructGeneric = new ThreeTuple <int>(0, 1, 2); StructGenericNullable = new ThreeTuple <int>(0, 1, 2); FieldPublicNullable = new Nullable <ThreeTuple <int> >(StructGeneric); #endregion }