/// <summary> /// 判断账号密码是否存在正确 /// </summary> /// <param name="acc"></param> /// <param name="pwd"></param> /// <returns></returns> public bool Match(string acc, string pwd) { //if (!accModelDict.ContainsKey(acc)) // return false; //return accModelDict[acc].Password == pwd; //如果内存里面有 直接判断 if (accModelDict.ContainsKey(acc)) { return(accModelDict[acc].Password == pwd); } AccountModel model = new AccountModel(); //如果没有 那就真的没有 if (!model.Exists(acc)) { return(false); } //如果数据库里面存在 model.GetModel(acc); //添加到内存里 accModelDict.TryAdd(model.Account, model); //再进行判断 return(model.Password == pwd); }
public IDictionary <long, IList <WorkSchedule> > GetAll(short pastMonths, short newMonths) { SynchronizedDictionary <long, IList <WorkSchedule> > result = new SynchronizedDictionary <long, IList <WorkSchedule> >(); List <Task> tasks = new List <Task>(); DateTime firstDay = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date; DateTime lastDay = firstDay.AddMonths(1).AddMilliseconds(-1); foreach (ProjectInfoS item in ProjectInfoS.FetchList(Database.Default, p => p.OriginateTime <= lastDay && (p.ClosedDate == null || p.ClosedDate >= firstDay))) { //项目经理 long projectManager = item.ProjectManager; if (!result.ContainsKey(projectManager)) { result.Add(projectManager, null); tasks.Add(Task.Run(async() => { result[projectManager] = await ClusterClient.Default.GetGrain <IWorkScheduleGrain>(projectManager).FetchWorkSchedules(pastMonths, newMonths); })); } //开发经理 long developManager = item.DevelopManager; if (!result.ContainsKey(developManager)) { result.Add(developManager, null); tasks.Add(Task.Run(async() => { result[developManager] = await ClusterClient.Default.GetGrain <IWorkScheduleGrain>(developManager).FetchWorkSchedules(pastMonths, newMonths); })); } } Task.WaitAll(tasks.ToArray()); return(result); }
public void DictionaryCopyConstructorProperlyCopiesEntriesAndSetsGottenTracking() { var other = new Dictionary <string, string>(); other.Add("key1", "otherValue1"); other.Add("key2", "otherValue2"); // trackAccessed = false, trackGotten = true var sd = new SynchronizedDictionary <string, string>(other, false, true); Assert.IsTrue(sd.ContainsKey("key1")); Assert.IsTrue(sd.ContainsKey("key2")); Assert.AreEqual(sd["key1"], "otherValue1"); Assert.AreEqual(sd["key2"], "otherValue2"); // Accessed Tracking is disabled Assert.IsFalse(sd.TrackAccessed); Assert.IsNull(sd.Accessed); // Accessed Tracking is enabled Assert.IsTrue(sd.TrackGotten); Assert.IsNotNull(sd.Gotten); Assert.AreEqual(sd.Gotten.Count, 2); }
/// <summary> /// Has this particular URL been cached? /// </summary> /// <param name="URL">The URL.</param> /// <returns>Returns true if the URL has been cached.</returns> public virtual bool HasCached(string URL, string POST = null, int maxRedirects = 10) { if (!Redirects || !Responses) { return(false); } int redirects = 0; RESTART: if (redirects > maxRedirects) { return(false); } if (Redirects && Redirects.ContainsKey(GetInternalUrlPostStorageName(URL, POST))) { URL = Redirects[GetInternalUrlPostStorageName(URL, POST)]; redirects++; goto RESTART; } if (Responses && Responses.ContainsKey(GetInternalUrlPostStorageName(URL, POST))) { return(true); } return(false); }
/// <summary> /// 匹配账号密码是否存在且正确 /// </summary> /// <param name="account"></param> /// <param name="password"></param> /// <returns></returns> public bool Match(string account, string password) { if (!accountModels.ContainsKey(account)) { return(false); } return(accountModels[account].Password == password); }
/// <summary> /// 设置扩展属性 /// 若指定属性不存在,则添加该属性,若指定属性已存在,则修改该属性 /// </summary> /// <param name="name"></param> /// <param name="value"></param> public virtual void SetValue(string name, object value) { if (extendProperties.ContainsKey(name)) { extendProperties[name] = value; } else { extendProperties.Add(name, value); } }
public static DBSchema GetSchemaCached(this IDAC dac) { using (_schemaCache.EnterWriteScope()) { var connectionString = dac.ConnectionString; if (!_schemaCache.ContainsKey(connectionString)) { _schemaCache[connectionString] = dac.GetSchema(); } return(_schemaCache[connectionString]); } }
private static String FromCache(int contactID, Size photoSize) { if (_photoCache.ContainsKey(contactID)) { if (_photoCache[contactID].ContainsKey(photoSize)) { return(_photoCache[contactID][photoSize]); } } return(String.Empty); }
/// <summary> /// Подписаться на получение реалтайм данных для инструмента. /// </summary> /// <param name="security">Инструмент.</param> protected virtual void SubscribeSecurity(Security security) { if (_allSecurity == null && !_securityMap.ContainsKey(security)) { return; } Connector.RegisterSecurity(security); foreach (var tuple in GetDataTypes(security)) { var msgType = tuple.MessageType; if (msgType == typeof(QuoteChangeMessage)) { Connector.RegisterMarketDepth(security); } //else if (msgType == typeof(Level1ChangeMessage)) // Connector.RegisterSecurity(security); else if (msgType == typeof(ExecutionMessage)) { switch ((ExecutionTypes)tuple.Arg) { case ExecutionTypes.Tick: Connector.RegisterTrades(security); break; case ExecutionTypes.Order: case ExecutionTypes.Trade: break; case ExecutionTypes.OrderLog: Connector.RegisterOrderLog(security); break; default: throw new ArgumentOutOfRangeException(); } } else if (msgType.IsCandleMessage()) { var map = _securityMap.TryGetValue(security); if (map == null) { continue; } _adapter.SendInMessage(new MarketDataMessage { IsSubscribe = true, SecurityId = security.ToSecurityId(), DataType = msgType.ToCandleMarketDataType(), Arg = tuple.Arg, To = DateTimeOffset.MaxValue, TransactionId = Connector.TransactionIdGenerator.GetNextId() }); } } }
public void RemoveAuction(Auction auction) { if (auction == null || !auctions.ContainsKey(auction.AuctionId)) { return; } auctions.Remove(auction.ItemLowId); items.Remove(auction.ItemLowId); AuctionMgr instance = Singleton <AuctionMgr> .Instance; ItemRecord record = null; if (instance.AuctionItems.ContainsKey(auction.ItemLowId)) { record = instance.AuctionItems[auction.ItemLowId]; instance.AuctionItems.Remove(auction.ItemLowId); } ServerApp <RealmServer> .IOQueue.AddMessage(() => { if (record != null) { record.IsAuctioned = false; record.Save(); } auction.Delete(); }); }
/// <summary> /// Parses the XML of the configuration section. /// </summary> /// <param name="parent">The configuration settings in a corresponding parent configuration section.</param> /// <param name="configContext">An HttpConfigurationContext when Create is called from the ASP.NET configuration system. Otherwise, this parameter is reserved and is a null reference.</param> /// <param name="section">The XmlNode that contains the configuration information from the configuration file. Provides direct access to the XML contents of the configuration section.</param> /// <returns>A configuration object.</returns> public object Create(object parent, object configContext, System.Xml.XmlNode section) { if (section == null) { throw new ConfigurationErrorsException("The sourceForge/objectFactory section has not been defined."); } objectDefinitions = new SynchronizedDictionary<string, ObjectDefinition>(); if (section.HasChildNodes) { // Register each object's configuration, without the constructor or property information foreach (XmlElement element in section.SelectNodes("object")) { // In the event of a reference property or constructor argument already being processed, don't process the definition again if (objectDefinitions.ContainsKey(element.GetAttribute("id")) == false) { ObjectDefinition objectDefinition = GetObjectDefinition(section as XmlElement, element, element.GetAttribute("id")); objectDefinitions.Add(objectDefinition.Id, objectDefinition); } } } return this; }
private IDictionary <Jid, UserRosterItemDic> LoadRosterItems() { var items = new SynchronizedDictionary <Jid, UserRosterItemDic>(); ExecuteList(new SqlQuery("jabber_roster").Select("jid", "item_jid", "name", "subscription", "ask", "groups")) .ForEach(r => { var item = new UserRosterItem(new Jid((string)r[1])) { Name = r[2] as string, Subscribtion = (SubscriptionType)Convert.ToInt32(r[3]), Ask = (AskType)Convert.ToInt32(r[4]), }; if (r[5] != null) { item.Groups.AddRange(((string)r[5]).Split(new[] { GroupSeparator }, StringSplitOptions.RemoveEmptyEntries)); } var jid = new Jid((string)r[0]); if (!items.ContainsKey(jid)) { items[jid] = new UserRosterItemDic(); } items[jid][item.Jid] = item; }); return(items); }
public void RemoveAuction(Auction auction) { if (auction == null) { return; } if (!auctions.ContainsKey(auction.AuctionId)) { return; } auctions.Remove(auction.ItemLowId); items.Remove(auction.ItemLowId); AuctionMgr mgr = AuctionMgr.Instance; ItemRecord record = null; if (mgr.AuctionItems.ContainsKey(auction.ItemLowId)) { record = mgr.AuctionItems[auction.ItemLowId]; mgr.AuctionItems.Remove(auction.ItemLowId); } //remove from database RealmServer.IOQueue.AddMessage(() => { if (record != null) { record.IsAuctioned = false; record.Save(); } auction.Delete(); }); }
/// <summary> /// Получить или установить обработчик по типу сообщения. /// </summary> /// <param name="type">Тип сообщения.</param> /// <returns>Обработчик.</returns> public IMessageProcessor this[MessageTypes type] { get { var index = (int)type; return(index >= 0 && index < _allProcessors.Length ? _allProcessors[index] : DefaultProcessor); } set { lock (_innerDict.SyncRoot) { if (_innerDict.ContainsKey(type)) { if (_innerDict[type] == value) { return; } Remove(type); } Add(type, value); } } }
public void TestAddRemoveByKey() { SynchronizedDictionary <int, string> test = new SynchronizedDictionary <int, string>(new IgnoreLocking()); for (int i = 0; i < 10; i++) { test.Add(i, i.ToString()); } for (int i = 0; i < 10; i++) { Assert.IsTrue(test.ContainsKey(i)); } string cmp; for (int i = 0; i < 10; i++) { Assert.IsTrue(test.TryGetValue(i, out cmp) && cmp == i.ToString()); } for (int i = 0; i < 10; i++) { Assert.IsTrue(test.Remove(i)); } }
public void Offline(MobaClient client) { if (!clientAccDict.ContainsKey(client)) { return; } string acc = clientAccDict[client]; if (accClientDict.ContainsKey(acc)) { accClientDict.Remove(acc); } if (clientAccDict.ContainsKey(client)) { clientAccDict.Remove(client); } }
/// <summary> /// 下线 /// </summary> /// <param name="client"></param> /// <param name="playerId"></param> public void Offline(MobaClient client) { if (!clientIdDict.ContainsKey(client)) { return; } int id = clientIdDict[client]; if (clientIdDict.ContainsKey(client)) { clientIdDict.Remove(client); } if (idClientDict.ContainsKey(id)) { idClientDict.Remove(id); } }
public void DictionaryCopyConstructorProperlyCopiesEntriesWithTrackingExplicitlyDisabled() { var other = new Dictionary <string, string>(); other.Add("key1", "otherValue1"); other.Add("key2", "otherValue2"); var sd = new SynchronizedDictionary <string, string>(other, false); Assert.IsTrue(sd.ContainsKey("key1")); Assert.IsTrue(sd.ContainsKey("key2")); Assert.AreEqual(sd["key1"], "otherValue1"); Assert.AreEqual(sd["key2"], "otherValue2"); Assert.IsFalse(sd.TrackAccessed); Assert.IsNull(sd.Accessed); Assert.IsFalse(sd.TrackGotten); Assert.IsNull(sd.Gotten); }
public void AddingKeysDoesNotAffectTrackingStatusOrCollectionsWhenInitiallyDisabled() { var sd = new SynchronizedDictionary <string, string>(); sd.Add("key1", "value1"); sd.Add("key2", "value2"); // First ensure that items are available Assert.IsTrue(sd.ContainsKey("key1")); Assert.IsTrue(sd.ContainsKey("key2")); // Now ensure that tracking is disabled by default Assert.IsFalse(sd.TrackAccessed); Assert.IsFalse(sd.TrackGotten); // Now ensure that tracking collections are null Assert.IsNull(sd.Accessed); Assert.IsNull(sd.Gotten); }
public void TestComparer() { SynchronizedDictionary <string, string> test = new SynchronizedDictionary <string, string>(StringComparer.OrdinalIgnoreCase); test["a"] = "b"; Assert.IsTrue(test.ContainsKey("A")); test = new SynchronizedDictionary <string, string>(StringComparer.OrdinalIgnoreCase, new IgnoreLocking()); test["a"] = "b"; Assert.IsTrue(test.ContainsKey("A")); }
/// <summary> /// 判断是否存在角色 /// </summary> /// <param name="accountId"></param> /// <returns></returns> public bool Has(int accountId) { if (accPlayerDict.ContainsKey(accountId)) { return(true); } PlayerModel model = new PlayerModel(); //如果没有那就真的没有 if (!model.ExistsByAccId(accountId)) { return(false); } //如果数据库里面存在 model.GetModelByAccId(accountId); //添加到内存里 accPlayerDict.TryAdd(accountId, model.Id); idModelDict.TryAdd(model.Id, model); //再进行判断 return(true); }
public void AccessedTrackingBeginsWhenItIsEnabled() { var sd = new SynchronizedDictionary <string, string>(); sd.Add("key1", "value1"); sd.Add("key2", "value2"); // Turn on access tracking sd.TrackAccessed = true; Assert.IsTrue(sd.TrackAccessed); Assert.IsNotNull(sd.Accessed); sd.ContainsKey("key1"); Assert.AreEqual(sd.Accessed.Count, 1); sd.ContainsKey("key2"); Assert.AreEqual(sd.Accessed.Count, 2); // A second 'access' does not affect count sd.ContainsKey("key1"); Assert.AreEqual(sd.Accessed.Count, 2); }
public void PublishDataForKey(string key, object data) { if (_handlers.ContainsKey(key)) { IList <DataHandler> handlers = null; using (_handlers.GetWriteLock()) { handlers = new List <DataHandler>(_handlers[key]); //Copy _handlers[key].Clear(); } //Call ThreadPool.QueueUserWorkItem(x => { foreach (var handler in handlers) { handler.OnDataAvailible(data); } handlers.Clear(); }); } }
public void CopyConstructorProperlyCopiesInstanceIncludingTracking() { var other = new SynchronizedDictionary <string, string>(true, true); other.Add("key1", "otherValue1"); other.Add("key2", "otherValue2"); other.ContainsKey("key1"); // Accessed var otherValue1 = other["key1"]; // Gotten other.ContainsKey("key2"); // Accessed var otherValue2 = other["key2"]; // Gotten var sd = new SynchronizedDictionary <string, string>(other); Assert.IsTrue(sd.TrackAccessed); Assert.IsTrue(sd.TrackGotten); // As of now we have not accessed or gotten anything from our new clone Assert.AreEqual(sd.Accessed.Count, 2); // retains Accessed count from original Assert.AreEqual(sd.Gotten.Count, 2); // retains Gotten count from original }
/// <summary> /// 匹配账号密码是否存在正确 /// </summary> /// <returns></returns> public bool Match(string acc, string pwd) { //如果内存有就直接判断 if (accModelDict.ContainsKey(acc)) { return(accModelDict[acc].Password == pwd); } AccountModel model = new AccountModel(); if (!model.Exists(acc)) { return(false); } //如果数据库存在 model.GetModel(acc); //添加到内存 accModelDict.TryAdd(model.Account, model); return(model.Password == pwd); }
/// <summary> /// Подписаться на получение реалтайм данных для инструмента. /// </summary> /// <param name="security">Инструмент.</param> protected virtual void SubscribeSecurity(Security security) { if (_allSecurity == null && !_securityMap.ContainsKey(security)) { return; } Connector.RegisterSecurity(security); if (CheckSecurity <QuoteChangeMessage>(security)) { Connector.RegisterMarketDepth(security); } if (CheckSecurity <Trade>(security)) { Connector.RegisterTrades(security); } if (CheckSecurity <OrderLogItem>(security)) { Connector.RegisterOrderLog(security); } //if (CheckSecurity<Level1ChangeMessage>(security)) // Connector.RegisterSecurity(security); if (SupportedCandleSeries.Any()) { var map = _securityMap.TryGetValue(security); if (map == null) { return; } foreach (var series in map.CandleSeries) { _adapter.SendInMessage(new MarketDataMessage { IsSubscribe = true, SecurityId = security.ToSecurityId(), DataType = series.CandleType.ToCandleMessageType().ToCandleMarketDataType(), Arg = series.Arg, To = DateTimeOffset.MaxValue, TransactionId = Connector.TransactionIdGenerator.GetNextId() }); } } }
private void SecurityPicker_OnSecuritySelected(Security security) { Level1.IsEnabled = Reports.IsEnabled = NewOrder.IsEnabled = Depth.IsEnabled = HistoryCandles.IsEnabled = RealTimeCandles.IsEnabled = security != null; if (security == null) { return; } Level1.IsChecked = Trader.RegisteredSecurities.Contains(SelectedSecurity); Reports.IsChecked = _reportSecurities.Contains(SelectedSecurity); RealTimeCandles.IsChecked = _сandles.Keys.Any(s => s.Security == SelectedSecurity); Depth.IsChecked = _quotesWindows.ContainsKey(SelectedSecurity); }
/// <summary> /// Подписаться на получение реалтайм данных для инструмента. /// </summary> /// <param name="security">Инструмент.</param> protected virtual void SubscribeSecurity(Security security) { if (_allSecurity == null && !_securityMap.ContainsKey(security)) { return; } Connector.Connector.RegisterSecurity(security); if (CheckSecurity <MarketDepth>(security)) { Connector.Connector.RegisterMarketDepth(security); } if (CheckSecurity <Trade>(security)) { Connector.Connector.RegisterTrades(security); } if (CheckSecurity <OrderLogItem>(security)) { Connector.Connector.RegisterOrderLog(security); } if (CheckSecurity <Level1ChangeMessage>(security)) { Connector.Connector.RegisterSecurity(security); } if (_isExternalCandleSource) { var map = _securityMap.TryGetValue(security); if (map == null) { return; } var source = (IExternalCandleSource)Connector.Connector; foreach (var series in map.CandleSeries) { source.SubscribeCandles(new CandleSeries(series.CandleType, security, series.Arg), DateTimeOffset.MinValue, DateTimeOffset.MaxValue); } } }
private void SecurityPicker_OnSecuritySelected(Security security) { Histogram.IsEnabled = Options.IsEnabled = Level1.IsEnabled = Reports.IsEnabled = NewOrder.IsEnabled = Depth.IsEnabled = HistoryCandles.IsEnabled = RealTimeCandles.IsEnabled = security != null; if (security == null) { return; } Options.IsEnabled = security.Type == SecurityTypes.Future || security.Type == SecurityTypes.Option; Level1.IsChecked = Trader.RegisteredSecurities.Contains(SelectedSecurity); Reports.IsChecked = _reportSecurities.ContainsKey(SelectedSecurity); Options.IsChecked = _optionSecurities.ContainsKey(SelectedSecurity); RealTimeCandles.IsChecked = _realTimeCandles.Keys.Any(s => s.Security == SelectedSecurity); Depth.IsChecked = _quotesWindows.ContainsKey(SelectedSecurity); }
public void TestLock() { LockCounterFactory <SimpleReadWriteLocking> factory = new LockCounterFactory <SimpleReadWriteLocking>(); ILockStrategy lck = factory.Create(); SynchronizedDictionary <int, string> test = new SynchronizedDictionary <int, string>(lck); Assert.IsTrue(ReferenceEquals(lck, test.Lock)); test.Add(42, "42"); Assert.AreEqual(1, factory.TotalWriterCount); Assert.AreEqual(0, factory.TotalReaderCount); test[42] = "51"; Assert.AreEqual(2, factory.TotalWriterCount); test.Add(1, "52"); Assert.AreEqual(3, factory.TotalWriterCount); test.Remove(-1); Assert.AreEqual(4, factory.TotalWriterCount); test.Remove(1); Assert.AreEqual(5, factory.TotalWriterCount); Assert.AreEqual("51", test[42]); Assert.AreEqual(1, factory.TotalReaderCount); foreach (KeyValuePair <int, string> i in test) { GC.KeepAlive(i); } Assert.AreEqual(2, factory.TotalReaderCount); Assert.AreEqual(false, test.ContainsKey(-1)); Assert.AreEqual(3, factory.TotalReaderCount); Assert.AreEqual(1, test.Count); Assert.AreEqual(4, factory.TotalReaderCount); string cmp; Assert.IsTrue(test.TryGetValue(42, out cmp) && cmp == "51"); Assert.AreEqual(5, factory.TotalReaderCount); }
private void ProcessSubscribeAction(MarketDataMessage message) { if (message == null) { throw new ArgumentNullException("message"); } var key = Tuple.Create(message.SecurityId, message.DataType); if (_subscriptionQueue.ContainsKey(key)) { return; } var enumerator = GetConnectedAdapters().ToArray().Cast <IMessageAdapter>().GetEnumerator(); _subscriptionQueue.Add(key, new RefPair <IEnumerator <IMessageAdapter>, bool>(enumerator, false)); ProcessSubscriptionAction(enumerator, message); }
public void SynchronizedDictionaryUnitTest() { SynchronizedDictionary<int, string> dictionary = new SynchronizedDictionary<int, string>(); dictionary.Add(1, "one"); dictionary.Add(2, "two"); Assert.IsTrue(dictionary.Count == 2); foreach (KeyValuePair<int, string> keyValuePair in dictionary) { Assert.IsTrue(dictionary.ContainsKey(keyValuePair.Key)); Assert.IsTrue(dictionary.ContainsValue(keyValuePair.Value)); } dictionary.Remove(1); Assert.IsTrue(dictionary.Count == 1); dictionary.Clear(); Assert.IsTrue(dictionary.Count == 0); }
private IDictionary<Jid, UserRosterItemDic> LoadRosterItems() { var items = new SynchronizedDictionary<Jid, UserRosterItemDic>(); ExecuteList(new SqlQuery("jabber_roster").Select("jid", "item_jid", "name", "subscription", "ask", "groups")) .ForEach(r => { var item = new UserRosterItem(new Jid((string)r[1])) { Name = r[2] as string, Subscribtion = (SubscriptionType)Convert.ToInt32(r[3]), Ask = (AskType)Convert.ToInt32(r[4]), }; if (r[5] != null) item.Groups.AddRange(((string)r[5]).Split(new[] { GroupSeparator }, StringSplitOptions.RemoveEmptyEntries)); var jid = new Jid((string)r[0]); if (!items.ContainsKey(jid)) items[jid] = new UserRosterItemDic(); items[jid][item.Jid] = item; }); return items; }