Exemplo n.º 1
0
        public CrawlerContext()
        {
            CommandQueue = new SynchronizedCollection<Command>();

            CrawledCreators = new SynchronizedSet<string>(new HashedSet<string>());
            CrawledIdentifiers = new SynchronizedSet<string>(new HashedSet<string>());
        }
Exemplo n.º 2
0
        private void imgAddTargets_Click(object sender, EventArgs e)
        {
            SynchronizedCollection<IPAddress> ipsFiltered = new SynchronizedCollection<IPAddress>();
            foreach (IPAddress ip in listBoxTargets.Items)
            {
                ipsFiltered.Add(ip);
            }

            SynchronizedCollection<IPAddress> ipsPrevFiltered = new SynchronizedCollection<IPAddress>();
            foreach (IPAddress ip in listBoxTargets.Items)
            {
                ipsPrevFiltered.Add(ip);
            }

            FormSelectIPs fSel = new FormSelectIPs(typeList, Data.Data.neighbors, true, null, ipsPrevFiltered);
            fSel.ShowDialog();

            SynchronizedCollection<IPAddress> lstIps = fSel.GetSelectedIPs();

            if (lstIps.Count > 0)
                listBoxTargets.Items.Clear();

            foreach (IPAddress ip in lstIps)
            {
                listBoxTargets.Items.Add(ip);
            }
        }
Exemplo n.º 3
0
 public Neighbor()
 {
     ports = new SynchronizedCollection<Port>();
     canRoutePackets = RouteStatus.Unknow;
     osPlatform = Platform.Unknow;
     ips = new SynchronizedCollection<IPAddress>();
 }
Exemplo n.º 4
0
 /// <summary>
 /// New status for Event type
 /// </summary>
 /// <param name="tevent">Event type</param>
 /// <param name="tstatus">Execution status</param>
 public void add(SolutionEventType tevent, StatusType tstatus)
 {
     if(!states.ContainsKey(tevent)) {
         states[tevent] = new SynchronizedCollection<StatusType>();
     }
     states[tevent].Add(tstatus);
 }
Exemplo n.º 5
0
 private void AddNHibernateContextInitializers(SynchronizedCollection<EndpointDispatcher> endpoints)
 {
     foreach (var endpoint in endpoints)
     {
         endpoint.DispatchRuntime.MessageInspectors.Add(new NHibernateContextInitializer(TransactionHandlingMode));
     }
 }
Exemplo n.º 6
0
 public Router(WinPcapDevice dev, SynchronizedCollection<Data.Attack> attacks, SynchronizedCollection<string> slaacReqs)
 {
     this.device = dev;
     this.localPhysicalAddress = device.MacAddress;
     this.attacks = attacks;
     //this.slaacReqs = slaacReqs;
     this.dnsHijacking = new DNSHijacking(dev, attacks);
 }
        public Unsubscriber(SynchronizedCollection<INotificationObserver<string>> observers, INotificationObserver<string> observer)
        {
            Guard.NotNull(observers, nameof(observers));
            Guard.NotNull(observer, nameof(observer));

            this.observers = observers;
            this.observer = observer;
        }
 private void Initialize(SynchronizedCollection<XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo> xmlSerializerFaultContractInfos)
 {
     if (xmlSerializerFaultContractInfos == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("xmlSerializerFaultContractInfos");
     }
     _xmlSerializerFaultContractInfos = xmlSerializerFaultContractInfos;
 }
Exemplo n.º 9
0
 public void finishSocketGroundWork()
 {
     this.localPCName = System.Environment.MachineName;
     IPHostEntry selfInfo = Dns.GetHostEntry(this.localPCName);
     this.selfIPaddress = selfInfo.AddressList[0];
     this.selfEndPoint = new IPEndPoint(this.selfIPaddress, this.selfPortNumber);
     this.connectedClientList = new SynchronizedCollection<FlaggedSocket>();
     this.listenerSocket.Bind(this.selfEndPoint);
 }
Exemplo n.º 10
0
 public FormSelectIPs(PanelTargets.TypeList type, IList<Neighbor> lstNeighbors, bool multiSelect, SynchronizedCollection<IPAddress> lstIpsFiltered, SynchronizedCollection<IPAddress> lstPrevIpsFiltered)
 {
     this.lstPrevIpsFiltered = lstPrevIpsFiltered;
     this.lstIpsFiltered = lstIpsFiltered;
     this.multiSelect = multiSelect;
     this.lstNeighbors = lstNeighbors;
     lstSelectedIps = new SynchronizedCollection<IPAddress>();
     this.type = type;
     InitializeComponent();
 }
Exemplo n.º 11
0
        /// <summary>
        ///   Creates a new instance of the ProxyServer class.
        /// </summary>
        public ProxyServer()
        {
            _logger = LogManager.GetLogger("Proxy Server");

            _logger.Info("Starting MineProxy.Net " + Assembly.GetExecutingAssembly ().GetName ().Version);

            ReadConfig ();
            _pluginManager = new PluginManager(this);
            _openConnection = new SynchronizedCollection<ProxyConnection> ();
            _connectedUsers = new SynchronizedCollection<ProxyConnection> ();
        }
        /// <summary>
        /// コンストラクター
        /// </summary>
        public BaseTextFactoryBcp(string entName, string dataBaseName, string tableName)
            : base(entName)
        {
            //DB名取得
            this.dataBaseName = dataBaseName;

            //テーブル名取得
            this.tableName = tableName;

            //リスト作成
            this.bcpList = new SynchronizedCollection<string>();
        }
        public void WhenUnsubscribe_ShouldBeDisposed()
        {
            var mock1 = new Mock<INotificationObserver<string>>();
            var mock2 = new Mock<INotificationObserver<string>>();
            var mock3 = new Mock<INotificationObserver<string>>();

            var obs = new SynchronizedCollection<INotificationObserver<string>> {mock1.Object, mock2.Object, mock3.Object };
            var unsub = new Unsubscriber(obs, mock2.Object);
            unsub.Dispose();

            Assert.Equal(2, obs.Count);
            Assert.False(obs.Contains(mock2.Object));
        }
Exemplo n.º 14
0
        public void Error_reports_should_be_raised_only_for_the_call_which_triggered_them()
        {
            var consumer = new GenericConsumer<SendMessage>();
            Bus.AddInstanceSubscription(consumer);

            var errors = new SynchronizedCollection<BasicReturn>();

            Bus.Send(new RogerEndpoint("inexistent1"), new SendMessage(), errors.Add);
            Bus.Send(new RogerEndpoint("inexistent2"), new SendMessage(), errors.Add);

            Assert.IsFalse(consumer.WaitForDelivery());
            Assert.AreEqual(2, errors.Count);
        }
 public void WhenCtorBadArgs_ShouldThrowExceptions()
 {
     Assert.Throws<ArgumentNullException>(() =>
     {
         var mock = new Mock<INotificationObserver<string>>();
         var s = new Unsubscriber(null, mock.Object);
     });
     Assert.Throws<ArgumentNullException>(() =>
     {
         var obs = new SynchronizedCollection<INotificationObserver<string>> { };
         var s = new Unsubscriber(obs, null);
     });
 }
Exemplo n.º 16
0
        public Dispatcher(IAmACommandProcessor commandProcessor, IAmAMessageMapperRegistry messageMapperRegistry, IEnumerable<Connection> connections, ILog logger)
        {
            this.commandProcessor = commandProcessor;
            this.messageMapperRegistry = messageMapperRegistry;
            this.logger = logger;
            State = DispatcherState.DS_NOTREADY;

            Consumers = new SynchronizedCollection<Consumer>();
            CreateConsumers(connections).Each(consumer => Consumers.Add(consumer));
            
            State = DispatcherState.DS_AWAITING;
            logger.Debug(m => m("Dispatcher is ready to recieve"));
        }
Exemplo n.º 17
0
        public PasiveScan(WinPcapDevice device, SynchronizedCollection<Data.Attack> attacks, IList<Data.Neighbor> neighbors, SynchronizedCollection<string> slaacReqs)
        {
            this.device = device;
            this.localPhysicalAddress = device.MacAddress;
            this.attacks = attacks;
            this.neighbors = neighbors;

            this.route = new Router(device, attacks, slaacReqs);
            this.pasivePortScan = new PasivePortScanner(neighbors);
            /* Ataques pasivos */
            this.DHCPACKInjection = new DHCPACKInjection(device, attacks);
            this.DHCPIpv6 = new DHCPIpv6(device, attacks);
        }
Exemplo n.º 18
0
 public IGSMFullStatus()
     : base(IGSMStatusType.IGSMSTATUS_FULLANSWER)
 {
     m_bIsUpdating = false;
     m_timer = new System.Timers.Timer();
     m_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
     m_timer.Interval = IGSMSTATUS_REFRESHTIME;
     m_lUsers = new SynchronizedCollection<IGSMStatusUser>();
     if (m_xmlNodeAnswer.FirstChild != null)
         m_xmlNodeUsers = m_xmlNodeAnswer.FirstChild.AppendChild(m_xmlDoc.CreateNode(XmlNodeType.Element, IGSMSTATUS_USERS, null));
     SetParameter(IGSMSTATUS_COMPUTERNAME, Environment.MachineName);
     SetParameter(IGSMSTATUS_COMPUTERIP, IGServerManagerLocal.LocalInstance.ServerIP.ToString());
     SetParameter(IGSMSTATUS_COMPUTERPORT, IGServerManagerLocal.LocalInstance.ServerPort.ToString());
     Update();
 }
		internal DispatchRuntime (EndpointDispatcher dispatcher)
		{
			EndpointDispatcher = dispatcher;
			UnhandledDispatchOperation = new DispatchOperation (
				this, "*", "*", "*");

			AutomaticInputSessionShutdown = true;
			PrincipalPermissionMode = PrincipalPermissionMode.UseWindowsGroups; // silly default value for us.
			SuppressAuditFailure = true;
			ValidateMustUnderstand = true;

			InputSessionShutdownHandlers = new SynchronizedCollection<IInputSessionShutdown> ();
			InstanceContextInitializers = new SynchronizedCollection<IInstanceContextInitializer> ();
			MessageInspectors = new SynchronizedCollection<IDispatchMessageInspector> ();
		}
Exemplo n.º 20
0
        /// <summary>
        /// Initializes a new instance of Listener.
        /// </summary>
        public Listener(EncryptionMode Mode)
        {
            m_ListenerSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            m_LoginClients = new SynchronizedCollection<NetworkClient>();

            m_EMode = Mode;
            /*switch (Mode)
            {
                case EncryptionMode.AESCrypto:
                    m_AesCryptoService = new AesCryptoServiceProvider();
                    m_AesCryptoService.GenerateIV();
                    m_AesCryptoService.GenerateKey();
                    break;
            }*/
        }
Exemplo n.º 21
0
        public DispatchOperation(DispatchRuntime parent, string name, string action)
        {
            if (parent == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent");
            if (name == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name");

            _parent = parent;
            _name = name;
            _action = action;

            _faultContractInfos = parent.NewBehaviorCollection<FaultContractInfo>();
            _parameterInspectors = parent.NewBehaviorCollection<IParameterInspector>();
            _isOneWay = true;
        }
Exemplo n.º 22
0
        /// <summary>
        ///     Enqueues the specified item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns>A <see cref="Guid" /> used to dequeue items.</returns>
        public static Guid Enqueue(Item item)
        {
            var caller = Assembly.GetCallingAssembly().FullName;
            var guid = Guid.NewGuid();

            item.Id = guid;

            if (!Queues.ContainsKey(caller))
            {
                Queues[caller] = new SynchronizedCollection<Item>();
            }

            Queues[caller].Add(item);

            return guid;
        }
Exemplo n.º 23
0
        public ClientOperation(ClientRuntime parent, string name, string action, string replyAction)
        {
            if (parent == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent");

            if (name == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name");

            _parent = parent;
            _name = name;
            _action = action;
            _replyAction = replyAction;

            _faultContractInfos = parent.NewBehaviorCollection<FaultContractInfo>();
            this.parameterInspectors = parent.NewBehaviorCollection<IParameterInspector>();
        }
Exemplo n.º 24
0
        public CartService(Logging.ILogger logger
			, Repositories.ICartRepository cartRepository
            , Services.ICatalogService catalogService
			, Services.IAccountService accountService
			, Services.IEventPublisher eventPublisherService
			, Repositories.ICommentRepository commentRepository
			)
        {
            m_LastCartItems = new System.Collections.Generic.SynchronizedCollection<CartItem>();

            this.Logger = logger;
            this.CartRepository = cartRepository;
            this.CatalogService = catalogService;
            this.AccountService = accountService;
            this.EventPublisherService = eventPublisherService;
            this.CommentRepository = commentRepository;
        }
        public DispatchOperation(DispatchRuntime parent, string name, string action)
        {
            if (parent == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent");
            if (name == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name");

            this.parent = parent;
            this.name = name;
            this.action = action;
            this.impersonation = OperationBehaviorAttribute.DefaultImpersonationOption;

            this.callContextInitializers = parent.NewBehaviorCollection<ICallContextInitializer>();
            this.faultContractInfos = parent.NewBehaviorCollection<FaultContractInfo>();
            this.parameterInspectors = parent.NewBehaviorCollection<IParameterInspector>();
            this.isOneWay = true;
        }
 protected override FaultException CreateFaultException(MessageFault messageFault, string action)
 {
     IList<XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo> xmlSerializerFaultContractInfos;
     if (action != null)
     {
         xmlSerializerFaultContractInfos = new List<XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo>();
         for (int j = 0; j < this.xmlSerializerFaultContractInfos.Count; j++)
         {
             if ((this.xmlSerializerFaultContractInfos[j].FaultContractInfo.Action == action) || (this.xmlSerializerFaultContractInfos[j].FaultContractInfo.Action == "*"))
             {
                 xmlSerializerFaultContractInfos.Add(this.xmlSerializerFaultContractInfos[j]);
             }
         }
     }
     else
     {
         xmlSerializerFaultContractInfos = this.xmlSerializerFaultContractInfos;
     }
     System.Type detailType = null;
     object detailObj = null;
     for (int i = 0; i < xmlSerializerFaultContractInfos.Count; i++)
     {
         XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo info = xmlSerializerFaultContractInfos[i];
         XmlDictionaryReader readerAtDetailContents = messageFault.GetReaderAtDetailContents();
         XmlObjectSerializer serializer = info.Serializer;
         if (serializer.IsStartObject(readerAtDetailContents))
         {
             detailType = info.FaultContractInfo.Detail;
             try
             {
                 detailObj = serializer.ReadObject(readerAtDetailContents);
                 FaultException exception = base.CreateFaultException(messageFault, action, detailObj, detailType, readerAtDetailContents);
                 if (exception != null)
                 {
                     return exception;
                 }
             }
             catch (SerializationException)
             {
             }
         }
     }
     return new FaultException(messageFault, action);
 }
Exemplo n.º 27
0
        public TPMonitorController(ACTTabpageControl actTab)
        {
            this.actPlugin = ActGlobals.oFormActMain.PluginGetSelfData(actTab);
            this.actTab = actTab;
            this.actTab.ChangeLocation += new ACTTabpageControl.ChangeLocationEventHandler(this.ChangeLocation);
            this.actTab.ChangeScale += new ACTTabpageControl.ChangeScaleEventHandler(this.ChangeScale);

            HideJob = new SynchronizedCollection<JOB>();

            ActGlobals.oFormActMain.OnLogLineRead += act_OnLogLineRead;

            isExited = false;

            PartyMemberInfo = new SynchronizedCollection<Combatant>();
            for (int i = 0; i < 8; i++)
            {
                PartyMemberInfo.Add(new Combatant());
            }

            normalStyle = new TPViewer(this);
            normalStyle.Show();
            normalStyle.Hide();

            allianceStyle = new AllianceStyleViewer(this);
            allianceStyle.Show();
            allianceStyle.Hide();

            if (this.IsAllianceStyle)
                viewer = allianceStyle;
            else
                viewer = normalStyle;
            
            checkStatus = new Thread(new ThreadStart(CheckProcess));
            checkStatus.Name = "Check Status Thread";
            checkStatus.Start();

            getTP = new Thread(new ThreadStart(GetMemberTP));
            getTP.Name = "Get TP Thread";
            getTP.Start();
        }
Exemplo n.º 28
0
        /// <summary>
        /// Download all the latest RSS feed
        /// </summary>
        /// <param name="subscription"></param>
        /// <returns></returns>
        public List<FeedAndSource> DownloadAll(RssSubscription subscription)
        {
            var feeds = new SynchronizedCollection<FeedAndSource>();

            var tasks = new List<Task>();

            foreach (var sub in subscription.Items)
            {
                var r = Task.Factory.StartNew(() =>
                    {
                        var res = Fetch(sub.XmlUri);
                        if (res.IsFound)
                            feeds.Add(new FeedAndSource(sub, res.Item));
                    });

                tasks.Add(r);
            }

            Task.WaitAll(tasks.ToArray());

            return feeds.ToList();
        }
 public DispatchOperation(DispatchRuntime parent, string name, string action)
 {
     this.deserializeRequest = true;
     this.serializeReply = true;
     this.autoDisposeParameters = true;
     if (parent == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent");
     }
     if (name == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name");
     }
     this.parent = parent;
     this.name = name;
     this.action = action;
     this.impersonation = ImpersonationOption.NotAllowed;
     this.callContextInitializers = parent.NewBehaviorCollection<ICallContextInitializer>();
     this.faultContractInfos = parent.NewBehaviorCollection<FaultContractInfo>();
     this.parameterInspectors = parent.NewBehaviorCollection<IParameterInspector>();
     this.isOneWay = true;
 }
 /// <summary>
 ///   Clears log entries from memory. (Entries written to log file will remain)
 /// </summary>
 public static void Clear()
 {
     _mEntries = new SynchronizedCollection <LogEntry>();
 }
Exemplo n.º 31
0
            public override void Run()
            {
                try
                {
                    IDictionary <string, int?> values = new Dictionary <string, int?>();
                    IList <string>             allIDs = new SynchronizedCollection <string>();

                    StartingGun.Wait();
                    for (int iter = 0; iter < Iters; iter++)
                    {
                        // Add/update a document
                        Document doc = new Document();
                        // Threads must not update the same id at the
                        // same time:
                        if (ThreadRandom.NextDouble() <= AddChance)
                        {
                            string id    = string.Format(CultureInfo.InvariantCulture, "{0}_{1:X4}", ThreadID, ThreadRandom.Next(IdCount));
                            int    field = ThreadRandom.Next(int.MaxValue);
                            doc.Add(new StringField("id", id, Field.Store.YES));
                            doc.Add(new IntField("field", (int)field, Field.Store.YES));
                            w.UpdateDocument(new Term("id", id), doc);
                            Rt.Add(id, field);
                            if (!values.ContainsKey(id))//Key didn't exist before
                            {
                                allIDs.Add(id);
                            }
                            values[id] = field;
                        }

                        if (allIDs.Count > 0 && ThreadRandom.NextDouble() <= DeleteChance)
                        {
                            string randomID = allIDs[ThreadRandom.Next(allIDs.Count)];
                            w.DeleteDocuments(new Term("id", randomID));
                            Rt.Delete(randomID);
                            values[randomID] = Missing;
                        }

                        if (ThreadRandom.NextDouble() <= ReopenChance || Rt.Size() > 10000)
                        {
                            //System.out.println("refresh @ " + rt.Size());
                            Mgr.MaybeRefresh();
                            if (VERBOSE)
                            {
                                IndexSearcher s = Mgr.Acquire();
                                try
                                {
                                    Console.WriteLine("TEST: reopen " + s);
                                }
                                finally
                                {
                                    Mgr.Release(s);
                                }
                                Console.WriteLine("TEST: " + values.Count + " values");
                            }
                        }

                        if (ThreadRandom.Next(10) == 7)
                        {
                            Assert.AreEqual(null, Rt.Get("foo"));
                        }

                        if (allIDs.Count > 0)
                        {
                            string randomID = allIDs[ThreadRandom.Next(allIDs.Count)];
                            int?   expected = values[randomID];
                            if (expected == Missing)
                            {
                                expected = null;
                            }
                            Assert.AreEqual(expected, Rt.Get(randomID), "id=" + randomID);
                        }
                    }
                }
                catch (Exception t)
                {
                    throw new Exception(t.Message, t);
                }
            }
Exemplo n.º 32
0
        internal Event(
            Engine engine,
            UInt64 idRundownEvent,
            UInt64 idEventBinding,
            VideoLayer videoLayer,
            TEventType eventType,
            TStartType startType,
            TPlayState playState,
            DateTime scheduledTime,
            TimeSpan duration,
            TimeSpan scheduledDelay,
            TimeSpan scheduledTC,
            Guid mediaGuid,
            string eventName,
            DateTime startTime,
            TimeSpan startTC,
            TimeSpan?requestedStartTime,
            TimeSpan transitionTime,
            TimeSpan transitionPauseTime,
            TTransitionType transitionType,
            TEasing transitionEasing,
            decimal?audioVolume,
            UInt64 idProgramme,
            string idAux,
            bool isEnabled,
            bool isHold,
            bool isLoop,
            AutoStartFlags autoStartFlags,
            bool isCGEnabled,
            byte crawl,
            byte logo,
            byte parental)
        {
            _engine              = engine;
            _id                  = idRundownEvent;
            _idEventBinding      = idEventBinding;
            _layer               = videoLayer;
            _eventType           = eventType;
            _startType           = startType;
            _playState           = playState == TPlayState.Paused ? TPlayState.Scheduled: playState == TPlayState.Fading ? TPlayState.Played : playState;
            _scheduledTime       = scheduledTime;
            _duration            = duration;
            _scheduledDelay      = scheduledDelay;
            _scheduledTc         = scheduledTC;
            _eventName           = eventName;
            _startTime           = startTime;
            _startTc             = startTC;
            _requestedStartTime  = requestedStartTime;
            _transitionTime      = transitionTime;
            _transitionPauseTime = transitionPauseTime;
            _transitionType      = transitionType;
            _transitionEasing    = transitionEasing;
            _audioVolume         = audioVolume;
            _idProgramme         = idProgramme;
            _idAux               = idAux;
            _isEnabled           = isEnabled;
            _isHold              = isHold;
            _isLoop              = isLoop;
            _isCGEnabled         = isCGEnabled;
            _crawl               = crawl;
            _logo                = logo;
            _parental            = parental;
            _autoStartFlags      = autoStartFlags;
            _setMedia(null, mediaGuid);
            _subEvents = new Lazy <SynchronizedCollection <Event> >(() =>
            {
                var result = new SynchronizedCollection <Event>();
                if (_id != 0)
                {
                    var seList = Engine.DbReadSubEvents(this);
                    foreach (Event e in seList)
                    {
                        e.Parent = this;
                        result.Add(e);
                    }
                }
                return(result);
            });

            _next = new Lazy <Event>(() =>
            {
                var next = (Event)Engine.DbReadNext(this);
                if (next != null)
                {
                    next.Prior = this;
                }
                return(next);
            });
            _prior = new Lazy <Event>(() =>
            {
                Event prior = null;
                if (startType == TStartType.After && _idEventBinding > 0)
                {
                    prior = (Event)Engine.DbReadEvent(_idEventBinding);
                }
                return(prior);
            });

            _parent = new Lazy <Event>(() =>
            {
                if ((startType == TStartType.WithParent || startType == TStartType.WithParentFromEnd) && _idEventBinding > 0)
                {
                    return((Event)Engine.DbReadEvent(_idEventBinding));
                }
                return(null);
            });
        }
Exemplo n.º 33
0
        /// <summary>
        /// 各個体の評価 修正PFで評価
        /// </summary>
        private void CalcFitness(Tree individual, string buySQL)
        {
            var fitness    = new Fitness();
            var sqlConn    = @"Data Source=.\SQLEXPRESS;Initial Catalog=FXData;Integrated Security=True;Connection Timeout=30;";
            var db         = new DataBase(sqlConn);
            var condition  = " NextPrice * 3 >= TenMaxDD AND NextPrice * 2 > TenAfterPrice AND TenAfterPrice > NextPrice / 2";
            var afterPrice = "TenAfterPrice";
            var maxDD      = "TenMaxDD";

            if (buySQL == "")
            {
                var gprSql     = $"SELECT TOP {MaxRecord + 1} AsOfDate, NextPrice, {afterPrice}, {maxDD} FROM IndexData WHERE {individual.BuySQLString} AND {condition}";
                var table      = db.ExecuteReader(gprSql);
                var tradeCount = table == null || table.Rows == null ? 0 : table.Rows.Count;
                //極端に少ないものは除外
                //極端に多いものは除外
                if (tradeCount < MinRecord || tradeCount > MaxRecord)
                {
                    individual.FitnessInfo = null;
                    return;
                }

                var win = table.AsEnumerable().Where(row => double.Parse(row["NextPrice"].ToString()) < double.Parse(row[afterPrice].ToString())).Count();
                fitness.TradeCount = tradeCount;
                fitness.WinCount   = win;

                var startDate = new DateTime(2002, 1, 1);
                var endDate   = new DateTime(2016, 12, 31);

                //BRACテスト
                while (startDate < endDate)
                {
                    var filterData = table.AsEnumerable().Where(row => DateTime.Parse(row["AsOfDate"].ToString()) < startDate || startDate.AddYears(1) < DateTime.Parse(row["AsOfDate"].ToString()));
                    try
                    {
                        var gain     = filterData.Select(row => double.Parse(row[afterPrice].ToString()) / double.Parse(row["NextPrice"].ToString()) - 1.0).Average();
                        var pain     = filterData.Select(row => 1.0 - double.Parse(row[maxDD].ToString()) / double.Parse(row["NextPrice"].ToString())).Average();
                        var tradeNum = filterData.Count();

                        fitness.TradeCountList.Add(tradeCount - tradeNum);
                        fitness.PFList.Add(gain / pain);
                        fitness.GainList.Add(gain);
                        fitness.PainList.Add(pain);
                        startDate = startDate.AddYears(1);
                    }
                    catch (Exception e)
                    {
                        individual.FitnessInfo = null;
                        return;
                    }
                }
            }
            else
            {
                if (buyTable == null)
                {
                    var gprSql = $"SELECT TOP {MaxRecord + 1} CodeNum, AsOfDate, NextPrice, {afterPrice}, {maxDD}  FROM StockData WHERE {buySign} AND {condition}";
                    buyTable = db.ExecuteReader(gprSql);
                }

                fitness.TradeCount = buyTable.Rows.Count;
                var win = 0;

                var startDate = new DateTime(2007, 1, 1);
                var endDate   = new DateTime(2016, 12, 31);

                //AsOfDate,NextPrice,SellPrice,TenMaxDD
                //始値で買い,売りサインの次の日の始値で売る
                var list = new SynchronizedCollection <object[]>();
                //foreach(DataRow row in table.Rows)
                Parallel.ForEach(buyTable.AsEnumerable(), row =>
                {
                    var sql   = $"SELECT TOP 1 AsOfDate, NextPrice FROM StockData WHERE CodeNum = '{row["CodeNum"].ToString()}' AND AsOfDate > '{DateTime.Parse(row["AsOfDate"].ToString())}' AND AsOfDate < '{DateTime.Parse(row["AsOfDate"].ToString()).AddDays(afterPrice == "TenAfterPrice" ? 20 : 10)}' AND {individual.SellSQLString} AND {condition} AND NowPrice > {row["NextPrice"].ToString()}";
                    var temp  = db.ExecuteReader(sql);
                    sql       = $"SELECT TOP 1 AsOfDate, NextPrice FROM StockData WHERE CodeNum = '{row["CodeNum"].ToString()}' AND AsOfDate > '{DateTime.Parse(row["AsOfDate"].ToString())}' AND AsOfDate < '{DateTime.Parse(row["AsOfDate"].ToString()).AddDays(afterPrice == "TenAfterPrice" ? 20 : 10)}' AND {individual.SellLCSQLString} AND {condition} AND NowPrice < {row["NextPrice"].ToString()}";
                    var temp2 = db.ExecuteReader(sql);

                    if ((temp == null || temp.Rows == null || temp.Rows.Count == 0) & (temp2 == null || temp2.Rows == null || temp2.Rows.Count == 0))
                    {
                        //データなし
                        list.Add(new object[] { DateTime.Parse(row["AsOfDate"].ToString()), double.Parse(row["NextPrice"].ToString()), double.Parse(row[afterPrice].ToString()), double.Parse(row[maxDD].ToString()) });
                    }
                    else
                    {
                        DataTable result = null;
                        if (temp == null || temp.Rows == null || temp.Rows.Count == 0)
                        {
                            result = temp2;
                        }
                        else if (temp2 == null || temp2.Rows == null || temp2.Rows.Count == 0)
                        {
                            result = temp;
                        }
                        else
                        {
                            result = DateTime.Parse(temp.Rows[0]["AsOfDate"].ToString()) < DateTime.Parse(temp2.Rows[0]["AsOfDate"].ToString()) ? temp : temp2;
                        }
                        //データあり
                        var sql2 = $"SELECT MIN(LowValue) FROM Code{row["CodeNum"].ToString()} WHERE Date > '{DateTime.Parse(row["AsOfDate"].ToString())}' AND Date <= '{DateTime.Parse(result.Rows[0]["AsOfDate"].ToString())}'";
                        var dd   = db.ExecuteScalar(sql2, -1.0);
                        var sql3 = $"SELECT ShareUnitNum FROM ShareUnitTable WHERE CodeNum = '{row["CodeNum"].ToString()}'";
                        var unit = db.ExecuteScalar(sql3, -1);
                        if (dd == -1 || unit == -1)
                        {
                            list.Add(new object[] { DateTime.Parse(row["AsOfDate"].ToString()), double.Parse(row["NextPrice"].ToString()), double.Parse(row[afterPrice].ToString()), double.Parse(row[maxDD].ToString()) });
                            return;
                        }
                        list.Add(new object[] { DateTime.Parse(row["AsOfDate"].ToString()), double.Parse(row["NextPrice"].ToString()), double.Parse(result.Rows[0]["NextPrice"].ToString()), dd * unit });
                    }
                });

                //BRACテスト
                while (startDate < endDate)
                {
                    var filterData = list.Where(row => (DateTime)row[0] < startDate || startDate.AddYears(1) < (DateTime)row[0]);
                    try
                    {
                        var gain     = filterData.Select(row => (double)row[2] / (double)row[1] - 1.0).Average();
                        var pain     = filterData.Select(row => 1.0 - (double)row[3] / (double)row[1]).Average();
                        var tradeNum = filterData.Count();

                        fitness.TradeCountList.Add(fitness.TradeCount - tradeNum);
                        fitness.PFList.Add(gain / pain);
                        fitness.GainList.Add(gain);
                        fitness.PainList.Add(pain);
                        startDate = startDate.AddYears(1);
                    }
                    catch (Exception e)
                    {
                        individual.FitnessInfo = null;
                        return;
                    }
                }

                fitness.WinCount = list.Where(row => (double)row[1] < (double)row[2]).Count();
            }

            individual.FitnessInfo = fitness;
        }
Exemplo n.º 34
0
 private XmlSerializerFaultFormatter CreateFaultFormatter(SynchronizedCollection <FaultContractInfo> faultContractInfos)
 {
     return(new XmlSerializerFaultFormatter(faultContractInfos, _reflector.XmlSerializerFaultContractInfos));
 }
        public virtual void TestAccquireReleaseRace()
        {
            DocumentsWriterStallControl ctrl = new DocumentsWriterStallControl();

            ctrl.UpdateStalled(false);
            AtomicBoolean stop       = new AtomicBoolean(false);
            AtomicBoolean checkPoint = new AtomicBoolean(true);

            int numStallers              = AtLeast(1);
            int numReleasers             = AtLeast(1);
            int numWaiters               = AtLeast(1);
            var sync                     = new Synchronizer(numStallers + numReleasers, numStallers + numReleasers + numWaiters);
            var threads                  = new ThreadClass[numReleasers + numStallers + numWaiters];
            IList <Exception> exceptions = new SynchronizedCollection <Exception>();

            for (int i = 0; i < numReleasers; i++)
            {
                threads[i] = new Updater(stop, checkPoint, ctrl, sync, true, exceptions);
            }
            for (int i = numReleasers; i < numReleasers + numStallers; i++)
            {
                threads[i] = new Updater(stop, checkPoint, ctrl, sync, false, exceptions);
            }
            for (int i = numReleasers + numStallers; i < numReleasers + numStallers + numWaiters; i++)
            {
                threads[i] = new Waiter(stop, checkPoint, ctrl, sync, exceptions);
            }

            Start(threads);
            int   iters = AtLeast(10000);
            float checkPointProbability = TEST_NIGHTLY ? 0.5f : 0.1f;

            for (int i = 0; i < iters; i++)
            {
                if (checkPoint.Get())
                {
                    Assert.IsTrue(sync.UpdateJoin.@await(new TimeSpan(0, 0, 0, 10)), "timed out waiting for update threads - deadlock?");
                    if (exceptions.Count > 0)
                    {
                        foreach (Exception throwable in exceptions)
                        {
                            Console.WriteLine(throwable.ToString());
                            Console.Write(throwable.StackTrace);
                        }
                        Assert.Fail("got exceptions in threads");
                    }

                    if (ctrl.HasBlocked() && ctrl.Healthy)
                    {
                        AssertState(numReleasers, numStallers, numWaiters, threads, ctrl);
                    }

                    checkPoint.Set(false);
                    sync.Waiter.countDown();
                    sync.LeftCheckpoint.@await();
                }
                Assert.IsFalse(checkPoint.Get());
                Assert.AreEqual(0, sync.Waiter.Remaining);
                if (checkPointProbability >= (float)Random().NextDouble())
                {
                    sync.Reset(numStallers + numReleasers, numStallers + numReleasers + numWaiters);
                    checkPoint.Set(true);
                }
            }
            if (!checkPoint.Get())
            {
                sync.Reset(numStallers + numReleasers, numStallers + numReleasers + numWaiters);
                checkPoint.Set(true);
            }

            Assert.IsTrue(sync.UpdateJoin.@await(new TimeSpan(0, 0, 0, 10)));
            AssertState(numReleasers, numStallers, numWaiters, threads, ctrl);
            checkPoint.Set(false);
            stop.Set(true);
            sync.Waiter.countDown();
            sync.LeftCheckpoint.@await();

            for (int i = 0; i < threads.Length; i++)
            {
                ctrl.UpdateStalled(false);
                threads[i].Join(2000);
                if (threads[i].IsAlive && threads[i] is Waiter)
                {
                    if (threads[i].State == ThreadState.WaitSleepJoin)
                    {
                        Assert.Fail("waiter is not released - anyThreadsStalled: " + ctrl.AnyStalledThreads());
                    }
                }
            }
        }
Exemplo n.º 36
0
 public Data()
 {
     SlaacReqList         = new SynchronizedCollection <string>();
     WpadReqList          = new SynchronizedCollection <string>();
     ReconstructedPackets = new SynchronizedCollection <TcpReconstructorPacket>();
 }
Exemplo n.º 37
0
 internal DataContractSerializerFaultFormatter(SynchronizedCollection <FaultContractInfo> faultContractInfoCollection) : base(faultContractInfoCollection)
 {
 }
 internal XmlSerializerFaultFormatter(Type[] detailTypes,
                                      SynchronizedCollection <XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo> xmlSerializerFaultContractInfos)
     : base(detailTypes)
 {
     Initialize(xmlSerializerFaultContractInfos);
 }
Exemplo n.º 39
0
 static JumonyViewEngine()
 {
     ViewProviders = new SynchronizedCollection <IViewProvider>(_providersSync);
 }
 /// <summary>
 /// Initialize for error handler manager
 /// </summary>
 static ErrorHandlerManager()
 {
     _listErrorRecords = new SynchronizedCollection<ErrorRecord>();
 }
        public async Task <List <T> > ToListAsync()
        {
            //去除分页,获取前Take+Skip数量
            int?take = _source.GetTakeCount();
            int?skip = _source.GetSkipCount();

            skip = skip == null ? 0 : skip;
            var(sortColumn, sortType) = _source.GetOrderBy();
            var noPaginSource = _source.RemoveTake().RemoveSkip();

            if (!take.IsNullOrEmpty())
            {
                noPaginSource = noPaginSource.Take(take.Value + skip.Value);
            }

            //从各个分表获取数据
            var tables = _shardingConfig.GetReadTables(_source);
            SynchronizedCollection <IDbAccessor> dbs   = new SynchronizedCollection <IDbAccessor>();
            List <Task <List <T> > >             tasks = tables.Select(aTable =>
            {
                IDbAccessor db;
                if (_shardingDb.OpenedTransaction)
                {
                    db = _shardingDb.GetMapDbAccessor(aTable.conString, aTable.dbType, aTable.suffix);
                }
                else
                {
                    db = _dbFactory.GetDbAccessor(aTable.conString, aTable.dbType, null, aTable.suffix);
                }
                dbs.Add(db);

                var targetIQ = db.GetIQueryable <T>();
                var newQ     = noPaginSource.ReplaceQueryable(targetIQ);
                return(newQ
                       .Cast <object>()
                       .Select(x => x.ChangeType <T>())
                       .ToListAsync());
            }).ToList();
            List <T> all = new List <T>();

            (await Task.WhenAll(tasks.ToArray())).ToList().ForEach(x => all.AddRange(x));

            if (!_shardingDb.OpenedTransaction)
            {
                dbs.ForEach(x => x.Dispose());
            }
            //合并数据
            var resList = all;

            if (!sortColumn.IsNullOrEmpty() && !sortType.IsNullOrEmpty())
            {
                resList = resList.AsQueryable().OrderBy($"{sortColumn} {sortType}").ToList();
            }
            if (!skip.IsNullOrEmpty())
            {
                resList = resList.Skip(skip.Value).ToList();
            }
            if (!take.IsNullOrEmpty())
            {
                resList = resList.Take(take.Value).ToList();
            }

            return(resList);
        }
Exemplo n.º 42
0
 internal FaultFormatter(SynchronizedCollection <FaultContractInfo> faultContractInfoCollection)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 43
0
 /// <summary>
 /// Constructor, optional log name, default value is "Application"
 /// </summary>
 /// <param name="logName"></param>
 private EventLogMonitor(string logName = "Application")
 {
     EventLog        = new EventLog(logName);
     EventLogEntries = new SynchronizedCollection <LoggedEvent>();
 }
Exemplo n.º 44
0
		public BuildResult GenBuilds(string prefix = "") {
			if (Type == BuildType.Lock) {
				Best = new Monster(Mon, true);
				return BuildResult.Success;
			}
			else if (Type == BuildType.Link) {
				if (LinkBuild == null) {
					for (int i = 0; i < 6; i++)
						runes[i] = new Rune[0];
					return BuildResult.Failure;
				}
				else {
					CopyFrom(LinkBuild);
				}
			}

			if (runes.Any(r => r == null)) {
				BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "Null rune"));
				return BuildResult.BadRune;
			}
			if (!BuildSaveStats)
				BuildGoodRunes = false;

			if (!BuildGoodRunes) {
				RuneUsage = new RuneUsage();
				BuildUsage = new BuildUsage();
			}
			try {
				// if to get awakened
				if (DownloadAwake && !Mon.downloaded) {
					BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "Downloading Awake def"));
					var mref = MonsterStat.FindMon(Mon);
					if (mref != null) {
						// download the current (unawakened monster)
						var mstat = mref.Download();
						BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "Reading stats"));
						// if the retrieved mon is unawakened, get the awakened
						if (!mstat.Awakened && mstat.AwakenTo != null) {
							BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "Awakening"));
							Mon = mstat.AwakenTo.Download().GetMon(Mon);
						}
					}
					BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "Downloaded"));
				}
				// getting awakened also gets level 40, so...
				// only get lvl 40 stats if the monster isn't 40, wants to download AND isn't already downloaded (first and last are about the same)
				else if (Mon.level < 40 && DownloadStats && !Mon.downloaded) {
					BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "Downloading 40 def"));
					var mref = MonsterStat.FindMon(Mon);
					if (mref != null)
						Mon = mref.Download().GetMon(Mon);
				}
			}
			catch (Exception e) {
				BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "Failed downloading def: " + e.Message + Environment.NewLine + e.StackTrace));
			}

			if (!getRunningHandle())
				throw new InvalidOperationException("The build is locked with another action.");
			
			Loads.Clear();

			if (!Sort[Attr.Speed].EqualTo(0) && Sort[Attr.Speed] <= 1 // 1 SPD is too good to pass
				|| Mon.Current.Runes.Any(r => r == null)
				|| !Mon.Current.Runes.All(r => runes[r.Slot - 1].Contains(r)) // only IgnoreLess5 if I have my own runes
				|| Sort.NonZeroStats.HasCount(1)) // if there is only 1 sorting, must be too important to drop???
				IgnoreLess5 = false;

			Thread timeThread = null;

			if (!string.IsNullOrWhiteSpace(BuildStrategy)) {

				var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(asm => asm.GetTypes().Where(t => typeof(IBuildStrategyDefinition).IsAssignableFrom(t)));

				var type = types.FirstOrDefault(t => t.AssemblyQualifiedName.Contains(BuildStrategy));
				if (type != null) {
					var def = (IBuildStrategyDefinition)Activator.CreateInstance(type);
					runner = null;
					try {
						runner = def.GetRunner();
						// TODO: fixme
						var settings = new BuildSettings() {
							AllowBroken = AllowBroken,
							BuildDumpBads = BuildDumpBads,
							BuildGenerate = BuildGenerate,
							BuildGoodRunes = BuildGoodRunes,
							BuildSaveStats = BuildSaveStats,
							BuildTake = BuildTake,
							BuildTimeout = BuildTimeout,
							IgnoreLess5 = IgnoreLess5,
							RunesDropHalfSetStat = RunesDropHalfSetStat,
							RunesOnlyFillEmpty = RunesOnlyFillEmpty,
							RunesUseEquipped = RunesUseEquipped,
							RunesUseLocked = RunesUseLocked,
							Shrines = Shrines
						};

						if (runner != null) {
							runner.Setup(this, settings);
							tcs.TrySetResult(runner);
							this.Best = runner.Run(runes.SelectMany(r => r)).Result;

							return BuildResult.Success;
						}
					}
					catch (Exception ex) {
						tcs.TrySetException(ex);
						IsRunning = false;
						return BuildResult.Failure;
					}
					finally {
						tcs = new TaskCompletionSource<IBuildRunner>();
						IsRunning = false;
						runner?.TearDown();
						runner = null;
					}
				}
			}

			tcs.TrySetResult(null);

			try {
				Best = null;
				Stats bstats = null;
				count = 0;
				actual = 0;
				total = runes[0].Length;
				total *= runes[1].Length;
				total *= runes[2].Length;
				total *= runes[3].Length;
				total *= runes[4].Length;
				total *= runes[5].Length;
				complete = total;

				Mon.ExtraCritRate = extraCritRate;
				Mon.GetStats();
				Mon.DamageFormula?.Invoke(Mon);

				int?[] slotFakesTemp = new int?[6];
				bool[] slotPred = new bool[6];
				getPrediction(slotFakesTemp, slotPred);

				int[] slotFakes = slotFakesTemp.Select(i => i ?? 0).ToArray();

				var currentLoad = new Monster(Mon, true);
				currentLoad.Current.TempLoad = true;
				currentLoad.Current.Buffs = Buffs;
				currentLoad.Current.Shrines = Shrines;
				currentLoad.Current.Leader = Leader;

				currentLoad.Current.FakeLevel = slotFakes;
				currentLoad.Current.PredictSubs = slotPred;

				double currentScore = CalcScore(currentLoad.GetStats(true));

				BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "cooking"));

				if (total == 0) {
					BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "0 perms"));
					RuneLog.Info("Zero permuations");
					return BuildResult.NoPermutations;
				}

				bool hasSort = Sort.IsNonZero;
				if (BuildTake == 0 && !hasSort) {
					BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "No sort"));
					RuneLog.Info("No method of determining best");
					return BuildResult.NoSorting;
				}

				DateTime begin = DateTime.Now;

				RuneLog.Debug(count + "/" + total + "  " + string.Format("{0:P2}", (count + complete - total) / (double)complete));


				// set to running
				IsRunning = true;

#if BUILD_PRECHECK_BUILDS_DEBUG
				SynchronizedCollection<string> outstrs = new SynchronizedCollection<string>();
#endif
				BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "..."));

				List<Monster> tests = new List<Monster>();

				timeThread = new Thread(() => {
					while (IsRunning) {
						if (RunesOnlyFillEmpty)
							Thread.Sleep(30 / ((Mon?.Current?.RuneCount ?? 1) + 1));
						else
							Thread.Sleep(400);
						// every second, give a bit of feedback to those watching
						RuneLog.Debug(count + "/" + total + "  " + string.Format("{0:P2}", (count + complete - total) / (double)complete));
						if (tests != null)
							BuildProgTo?.Invoke(this, ProgToEventArgs.GetEvent(this, (count + complete - total) / (double)complete, tests.Count));

						if (BuildTimeout > 0 && DateTime.Now > begin.AddSeconds(BuildTimeout)) {
							RuneLog.Info("Timeout");
							BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, prefix + "Timeout"));
							BuildProgTo?.Invoke(this, ProgToEventArgs.GetEvent(this, 1, tests.Count));

							IsRunning = false;
						}
					}
				});
				timeThread.Start();

				double bestScore = double.MinValue;

				var opts = new ParallelOptions() {
					MaxDegreeOfParallelism = Environment.ProcessorCount - 1
				};

				var mmm = Maximum.NonZeroCached;

				// Parallel the outer loop
				// TODO: setup the begin/finish Actions with syncList.
				void body (Rune r0, ParallelLoopState loopState) {
					var tempReq = RequiredSets.ToList();
					var tempMax = Maximum == null || !Maximum.IsNonZero ? null : new Stats(Maximum, true);
					int tempCheck = 0;

					Monster myBest = null;
					List<Monster> syncList = new List<Monster>();

					void syncMyList() {
						lock (bestLock) {
#if DEBUG_SYNC_BUILDS
							foreach (var s in syncList) {
								if (s.Current.Runes.All(r => r.Assigned == mon)) {
									Console.WriteLine("!");
								}
							}
#endif
							tests.AddRange(syncList);

						}
						//syncList.ForEach(_ => tests.Add(_));
						syncList.Clear();
						if (tests.Count > Math.Max(BuildGenerate, 250000)) {
#if DEBUG_SYNC_BUILDS
								var rems = tests.OrderByDescending(b => b.score).Skip(75000).ToList();
								foreach (var bbb in rems) {
									if (bbb.Current.Runes.All(r => r.Assigned == mon)) {
										Console.WriteLine("!");
									}
								}
#endif
							lock (bestLock) {
								tests = tests.OrderByDescending(b => b.score).Take(75000).ToList();
							}
						}

						if (tests.Count > MaxBuilds32)
							IsRunning = false;
					}

					if (!IsRunning_Unsafe) {
						syncMyList();
						loopState.Break();
					}

					// number of builds ruled out since last sync
					int kill = 0;
					// number of builds added since last sync
					int plus = 0;
					// number of builds skipped
					int skip = 0;


					bool isBad;
					double myBestScore = double.MinValue, curScore, lastBest = double.MinValue;
					Stats cstats, myStats;


					Monster test = new Monster(Mon);
					test.Current.TempLoad = true;
					test.Current.Buffs = Buffs;
					test.Current.Shrines = Shrines;
					test.Current.Leader = Leader;

					test.Current.FakeLevel = slotFakes;
					test.Current.PredictSubs = slotPred;
					test.ApplyRune(r0, 7);

					RuneSet set4 = r0.SetIs4 ? r0.Set : RuneSet.Null;
					RuneSet set2 = r0.SetIs4 ? RuneSet.Null : r0.Set;
					int pop4 = 0;
					int pop2 = 0;

					foreach (Rune r1 in runes[1]) {
						// TODO: refactor to local method
						if (!IsRunning_Unsafe) // Can't break to a label, don't want to goto
							break;
						// TODO: break into multiple implementations that have less branching
#if BUILD_PRECHECK_BUILDS
						if (!AllowBroken && !RunesOnlyFillEmpty) {
							if (r1.SetIs4) {
								if (pop2 == 2)
									pop2 = 7;
								if (set4 == RuneSet.Null || pop4 >= 2) {
									set4 = r1.Set;
									pop4 = 2;
								}
								else if (set4 != r1.Set) {
#if BUILD_PRECHECK_BUILDS_DEBUG
									outstrs.Add($"bad4@2 {set4} {set2} | {r0.Set} {r1.Set}");
#endif
									skip += runes[2].Length * runes[3].Length * runes[4].Length * runes[5].Length;
									continue;
								}
							}
							else {
								if (pop4 == 2)
									pop4 = 7;
								if (set2 == RuneSet.Null || pop2 >= 2) {
									set2 = r1.Set;
									pop2 = 2;
								}
							}
						}
#endif
						test.ApplyRune(r1, 7);

						foreach (Rune r2 in runes[2]) {
							if (!IsRunning_Unsafe)
								break;
#if BUILD_PRECHECK_BUILDS
							if (!AllowBroken && !RunesOnlyFillEmpty) {
								if (r2.SetIs4) {
									if (pop2 == 3)
										pop2 = 7;
									if (set4 == RuneSet.Null || pop4 >= 3) {
										set4 = r2.Set;
										pop4 = 3;
									}
									else if (set4 != r2.Set) {
#if BUILD_PRECHECK_BUILDS_DEBUG
										outstrs.Add($"bad4@3 {set4} {set2} | {r0.Set} {r1.Set} {r2.Set}");
#endif
										skip += runes[3].Length * runes[4].Length * runes[5].Length;
										continue;
									}
								}
								else {
									if (pop4 == 3)
										pop4 = 7;
									if (set2 == RuneSet.Null || pop2 >= 3) {
										set2 = r2.Set;
										pop2 = 3;
									}
									else if (set4 != RuneSet.Null && set2 != r2.Set) {
#if BUILD_PRECHECK_BUILDS_DEBUG
										outstrs.Add($"bad2@3 {set4} {set2} | {r0.Set} {r1.Set} {r2.Set}");
#endif
										skip += runes[3].Length * runes[4].Length * runes[5].Length;
										continue;
									}
								}
							}
#endif
							test.ApplyRune(r2, 7);

							foreach (Rune r3 in runes[3]) {
								if (!IsRunning_Unsafe)
									break;
#if BUILD_PRECHECK_BUILDS
								if (!AllowBroken && !RunesOnlyFillEmpty) {
									if (r3.SetIs4) {
										if (pop2 == 4)
											pop2 = 7;
										if (set4 == RuneSet.Null || pop4 >= 4) {
											set4 = r3.Set;
											pop4 = 4;
										}
										else if (set4 != r3.Set) {
#if BUILD_PRECHECK_BUILDS_DEBUG
											outstrs.Add($"bad4@4 {set4} {set2} | {r0.Set} {r1.Set} {r2.Set} {r3.Set}");
#endif
											skip += runes[4].Length * runes[5].Length;
											continue;
										}
									}
									else {
										if (pop4 == 4)
											pop4 = 7;
										if (set2 == RuneSet.Null || pop2 >= 4) {
											set2 = r3.Set;
											pop2 = 4;
										}
										else if (set4 != RuneSet.Null && set2 != r3.Set) {
#if BUILD_PRECHECK_BUILDS_DEBUG
											outstrs.Add($"bad2@4 {set4} {set2} | {r0.Set} {r1.Set} {r2.Set} {r3.Set}");
#endif
											skip += runes[4].Length * runes[5].Length;
											continue;
										}
									}
								}
#endif
								test.ApplyRune(r3, 7);

								foreach (Rune r4 in runes[4]) {
									if (!IsRunning_Unsafe) {
										break;
									}
#if BUILD_PRECHECK_BUILDS
									if (!AllowBroken && !RunesOnlyFillEmpty) {
										if (r4.SetIs4) {
											if (pop2 == 5)
												pop2 = 7;
											if (set4 == RuneSet.Null || pop4 >= 5) {
												set4 = r4.Set;
												pop4 = 5;
											}
											else if (set4 != r4.Set) {
#if BUILD_PRECHECK_BUILDS_DEBUG
												outstrs.Add($"bad4@5 {set4} {set2} | {r0.Set} {r1.Set} {r2.Set} {r3.Set} {r4.Set}");
#endif
												skip += runes[5].Length;
												continue;
											}
										}
										else {
											if (pop4 == 5)
												pop4 = 7;
											if (set2 == RuneSet.Null || pop2 >= 5) {
												set2 = r4.Set;
												pop2 = 5;

											}
											else if (set4 != RuneSet.Null && set2 != r4.Set) {
#if BUILD_PRECHECK_BUILDS_DEBUG
												outstrs.Add($"bad2@5 {set4} {set2} | {r0.Set} {r1.Set} {r2.Set} {r3.Set} {r4.Set}");
#endif
												skip += runes[5].Length;
												continue;
											}
										}
									}
#endif
									test.ApplyRune(r4, 7);

									foreach (Rune r5 in runes[5]) {
										if (!IsRunning_Unsafe)
											break;

										test.ApplyRune(r5, 7);
										test.Current.CheckSets();
#if BUILD_PRECHECK_BUILDS_DEBUG
										outstrs.Add($"fine {set4} {set2} | {r0.Set} {r1.Set} {r2.Set} {r3.Set} {r4.Set} {r5.Set}");
#endif
										isBad = false;

										cstats = test.GetStats();

										// check if build meets minimum
										isBad |= !RunesOnlyFillEmpty && !AllowBroken && !test.Current.SetsFull;

										isBad |= tempMax != null && cstats.AnyExceedCached(tempMax);

										if (!isBad && GrindLoads) {
											var mahGrinds = grinds.ToList();
											for (int rg = 0; rg < 6; rg++) {
												var lgrinds = test.Runes[rg].FilterGrinds(mahGrinds);
												foreach (var g in lgrinds) {
													var tr = test.Runes[rg].Grind(g);
												}
												// TODO: 
											}
										}

										isBad |= !RunesOnlyFillEmpty && Minimum != null && !cstats.GreaterEqual(Minimum, true);
										// if no broken sets, check for broken sets
										// if there are required sets, ensure we have them
										/*isBad |= (tempReq != null && tempReq.Count > 0
											// this Linq adds no overhead compared to GetStats() and ApplyRune()
											//&& !tempReq.All(s => test.Current.Sets.Count(q => q == s) >= tempReq.Count(q => q == s))
											//&& !tempReq.GroupBy(s => s).All(s => test.Current.Sets.Count(q => q == s.Key) >= s.Count())
											);*/
										// TODO: recheck this code is correct
										if (tempReq != null && tempReq.Count > 0) {
											tempCheck = 0;
											foreach (var r in tempReq) {
												int i;
												for (i = 0; i < 3; i++) {
													if (test.Current.Sets[i] == r && (tempCheck & 1 << i) != 1 << i) {
														tempCheck |= 1 << i;
														break;
													}
												}
												if (i >= 3) {
													isBad |= true;
													break;
												}
											}
										}

										if (isBad) {
											kill++;
											curScore = 0;
										}
										else {
											// try to reduce CalcScore hits
											curScore = CalcScore(cstats);
											isBad |= IgnoreLess5 && curScore < currentScore * 1.05;
											if (isBad)
												kill++;
										}

										if (!isBad) {
											// we found an okay build!
											plus++;
											test.score = curScore;

											if (BuildSaveStats) {
												foreach (Rune r in test.Current.Runes) {
													if (!BuildGoodRunes) {
														r.manageStats.AddOrUpdate("LoadFilt", 1, (s, d) => { return d + 1; });
														RuneUsage.runesGood.AddOrUpdate(r, (byte)r.Slot, (key, ov) => (byte)r.Slot);
														r.manageStats.AddOrUpdate("currentBuildPoints", curScore, (k, v) => Math.Max(v, curScore));
														r.manageStats.AddOrUpdate("cbp" + ID, curScore, (k, v) => Math.Max(v, curScore));
													}
													else {
														r.manageStats.AddOrUpdate("LoadFilt", 0.001, (s, d) => { return d + 0.001; });
														RuneUsage.runesOkay.AddOrUpdate(r, (byte)r.Slot, (key, ov) => (byte)r.Slot);
														r.manageStats.AddOrUpdate("cbp" + ID, curScore, (k, v) => Math.Max(v, curScore * 0.9));
													}
												}
											}

											if (syncList.Count >= 500) {
												syncMyList();
											}

											// if we are to track all good builds, keep it
											if (!BuildDumpBads) {

												syncList.Add(new Monster(test, true));

												// locally track my best
												if (myBest == null || curScore > myBestScore) {
													myBest = new Monster(test, true);
													myStats = myBest.GetStats();
													myBestScore = CalcScore(myStats);
													myBest.score = myBestScore;
												}

												// if mine is better than what I last saw
												if (myBestScore > lastBest) {
													lock (bestLock) {
														if (Best == null) {
															Best = new Monster(myBest, true);
															bstats = Best.GetStats();
															bestScore = CalcScore(bstats);
															Best.score = bestScore;
														}
														else {
															// sync best score
															lastBest = bestScore;
															// double check
															if (myBestScore > lastBest) {
																Best = new Monster(myBest, true);
																bestScore = CalcScore(bstats);
																Best.score = bestScore;
																bstats = Best.GetStats();
															}
														}
													}
												}

											}
											// if we only want to track really good builds
											else {
												// if there are currently no good builds, keep it
												// or if this build is better than the best, keep it

												// locally track my best
												if (myBest == null || curScore > myBestScore) {
													myBest = new Monster(test, true);
													myStats = myBest.GetStats();
													myBestScore = CalcScore(myStats);
													myBest.score = myBestScore;
													syncList.Add(myBest);
												}
												else if (BuildSaveStats) {
													// keep it for spreadsheeting
													syncList.Add(new Monster(test, true) {
														score = curScore
													});
												}
											}
										}
									}
									// sum up what work we've done
									Interlocked.Add(ref count, kill);
									Interlocked.Add(ref count, skip);
									Interlocked.Add(ref skipped, skip);
									Interlocked.Add(ref actual, kill);
									Interlocked.Add(ref BuildUsage.failed, kill);
									kill = 0;
									skip = 0;
									Interlocked.Add(ref count, plus);
									Interlocked.Add(ref actual, plus);
									Interlocked.Add(ref BuildUsage.passed, plus);
									plus = 0;

									// if we've got enough, stop
									if (BuildGenerate > 0 && BuildUsage.passed >= BuildGenerate) {
										IsRunning = false;
										break;
									}
								}
							}
						}
					}
					// just before dying
					syncMyList();
				}
				Parallel.ForEach(runes[0], opts, body);


				BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, prefix + "finalizing..."));
				BuildProgTo?.Invoke(this, ProgToEventArgs.GetEvent(this, 0.99, -1));

#if BUILD_PRECHECK_BUILDS_DEBUG
				System.IO.File.WriteAllLines("_into_the_bridge.txt", outstrs.ToArray());
#endif
				if (BuildSaveStats) {
					foreach (var ra in runes) {
						foreach (var r in ra) {
							if (!BuildGoodRunes) {
								r.manageStats.AddOrUpdate("buildScoreTotal", CalcScore(Best), (k, v) => v + CalcScore(Best));
								RuneUsage.runesUsed.AddOrUpdate(r, (byte)r.Slot, (key, ov) => (byte)r.Slot);
								r.manageStats.AddOrUpdate("LoadGen", total, (s, d) => { return d + total; });

							}
							else {
								RuneUsage.runesBetter.AddOrUpdate(r, (byte)r.Slot, (key, ov) => (byte)r.Slot);
								r.manageStats.AddOrUpdate("LoadGen", total * 0.001, (s, d) => { return d + total * 0.001; });
							}
						}
					}
				}

				// write out completion
				RuneLog.Debug(IsRunning + " " + count + "/" + total + "  " + string.Format("{0:P2}", (count + complete - total) / (double)complete));
				BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, prefix + " completed"));
				BuildProgTo?.Invoke(this, ProgToEventArgs.GetEvent(this, 1, tests.Count));

				// sort *all* the builds
				int takeAmount = 1;
				if (BuildSaveStats)
					takeAmount = 10;
				if (BuildTake > 0)
					takeAmount = BuildTake;

				if (IgnoreLess5)
					tests.Add(new Monster(Mon, true));

				foreach (var ll in tests.Where(t => t != null).OrderByDescending(r => CalcScore(r.GetStats())).Take(takeAmount))
					Loads.Add(ll);

				BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "Found a load " + Loads.Count()));

				if (!BuildGoodRunes)
					BuildUsage.loads = tests.ToList();

				// dump everything to console, if nothing to print to
				if (BuildPrintTo == null)
					foreach (var l in Loads) {
						RuneLog.Debug(l.GetStats().Health + "  " + l.GetStats().Attack + "  " + l.GetStats().Defense + "  " + l.GetStats().Speed
							+ "  " + l.GetStats().CritRate + "%" + "  " + l.GetStats().CritDamage + "%" + "  " + l.GetStats().Resistance + "%" + "  " + l.GetStats().Accuracy + "%");
					}

				// sadface if no builds
				if (!Loads.Any()) {
					RuneLog.Info("No builds :(");
					BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, prefix + "Zero :("));
				}
				else {
					// remember the good one
					Best = Loads.First();
					Best.Current.TempLoad = false;
					Best.score = CalcScore(Best.GetStats());
					BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, prefix + "best " + (Best?.score ?? -1)));
					Best.Current.ActualTests = actual;
					foreach (var bb in Loads) {
						foreach (Rune r in bb.Current.Runes) {
							double val = Best.score;
							if (BuildGoodRunes) {
								val *= 0.25;
								if (bb == Best)
									RuneUsage.runesSecond.AddOrUpdate(r, (byte)r.Slot, (key, ov) => (byte)r.Slot);
							}

							if (bb != Best)
								val *= 0.1;
							else
								r.manageStats.AddOrUpdate("In", BuildGoodRunes ? 2 : 1, (s, e) => BuildGoodRunes ? 2 : 1);

							r.manageStats.AddOrUpdate("buildScoreIn", val, (k, v) => v + val);
						}
					}
					for (int i = 0; i < 6; i++) {
						if (!BuildGoodRunes && Mon.Current.Runes[i] != null && Mon.Current.Runes[i].Id != Best.Current.Runes[i].Id)
							Mon.Current.Runes[i].Swapped = true;
					}
					foreach (var ra in runes) {
						foreach (var r in ra) {
							var cbp = r.manageStats.GetOrAdd("currentBuildPoints", 0);
							if (cbp / Best.score < 1)
								r.manageStats.AddOrUpdate("bestBuildPercent", cbp / Best.score, (k, v) => Math.Max(v, cbp / Best.score));
						}
					}
				}

				tests.Clear();
				tests = null;
				BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, prefix + "Test cleared"));
				return BuildResult.Success;
			}
			catch (Exception e) {
				RuneLog.Error("Error " + e);
				BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, prefix + e.ToString()));
				return BuildResult.Failure;
			}
			finally {
				tcs = new TaskCompletionSource<IBuildRunner>();
				IsRunning = false;
				if (timeThread != null)
					timeThread.Join();
			}
		}
Exemplo n.º 45
0
        public DocumentNode AddDocumentNode(int docID, bool needVisible, string nodeTitle, bool links)
        {
            if (documentNodes == null)
            {
                documentNodes = new SynchronizedCollection <KeyValuePair <int, DocumentNode> >();
            }
            int indexOf = -1;

            for (int i = 0; i < documentNodes.Count && indexOf == -1; i++)
            {
                if (documentNodes[i].Key == docID)
                {
                    indexOf = i;
                }
            }

            if (indexOf == -1)
            {
                try
                {
                    var newNode = new DocumentNode(docID, docID.ToString(), nodeTitle, links);
                    documentNodes.Add(new KeyValuePair <int, DocumentNode>(docID, newNode));
                    if (!Environment.UserSettings.LinkDocIDs.Contains(docID))
                    {
                        Environment.UserSettings.LinkDocIDs.Add(docID);
                    }

                    if (workFolderNodes.Count > 0)
                    {
                        int placeid = WorkFolderNode.Index;
                        Nodes.Insert(placeid + 1, newNode);
                        lastOverNode = null;
                    }
                    else
                    {
                        Nodes.Insert(1, newNode);
                    }
                    // убираем болд
                    newNode.RemoveBoldRecursive();

                    return(newNode);
                }
                catch
                {
                    if (Environment.UserSettings.LinkDocIDs.Contains(docID))
                    {
                        Environment.UserSettings.LinkDocIDs.Remove(docID);
                    }
                    return(null);
                }
            }

            DocumentNode docNode = documentNodes[indexOf].Value;

            docNode.LoadSubNodes();
            if (!Nodes.Contains(docNode))
            {
                if (workFolderNodes.Count > 0)
                {
                    int placeid = WorkFolderNode.Index;
                    Nodes.Insert(placeid + 1, docNode);
                    lastOverNode = null;
                }
                else
                {
                    Nodes.Insert(1, docNode);
                }
            }
            if (needVisible)
            {
                docNode.EnsureVisible();
            }
            return(docNode);
        }
Exemplo n.º 46
0
        internal Event(
            Engine engine,
            UInt64 idRundownEvent,
            UInt64 idEventBinding,
            VideoLayer videoLayer,
            TEventType eventType,
            TStartType startType,
            TPlayState playState,
            DateTime scheduledTime,
            TimeSpan duration,
            TimeSpan scheduledDelay,
            TimeSpan scheduledTC,
            Guid mediaGuid,
            string eventName,
            DateTime startTime,
            TimeSpan startTC,
            TimeSpan?requestedStartTime,
            TimeSpan transitionTime,
            TimeSpan transitionPauseTime,
            TTransitionType transitionType,
            TEasing transitionEasing,
            double?audioVolume,
            UInt64 idProgramme,
            string idAux,
            bool isEnabled,
            bool isHold,
            bool isLoop,
            AutoStartFlags autoStartFlags,
            bool isCGEnabled,
            byte crawl,
            byte logo,
            byte parental,
            short routerPort,
            RecordingInfo recordingInfo)
        {
            _engine              = engine;
            _rundownSync         = engine.RundownSync;
            Id                   = idRundownEvent;
            IdEventBinding       = idEventBinding;
            _layer               = videoLayer;
            _eventType           = eventType;
            _startType           = startType;
            _playState           = playState == TPlayState.Paused ? TPlayState.Scheduled: playState == TPlayState.Fading ? TPlayState.Played : playState;
            _scheduledTime       = scheduledTime;
            _duration            = duration;
            _scheduledDelay      = scheduledDelay;
            _scheduledTc         = scheduledTC;
            _eventName           = eventName;
            _startTime           = startTime;
            _startTc             = startTC;
            _requestedStartTime  = requestedStartTime;
            _transitionTime      = transitionTime;
            _transitionPauseTime = transitionPauseTime;
            _transitionType      = transitionType;
            _transitionEasing    = transitionEasing;
            _audioVolume         = audioVolume;
            _idProgramme         = idProgramme;
            _idAux               = idAux;
            _isEnabled           = isEnabled;
            _isHold              = isHold;
            _isLoop              = isLoop;
            _isCGEnabled         = isCGEnabled;
            _crawl               = crawl;
            _logo                = logo;
            _parental            = parental;
            _autoStartFlags      = autoStartFlags;
            _mediaGuid           = mediaGuid;
            _subEvents           = new Lazy <SynchronizedCollection <Event> >(() =>
            {
                var result = new SynchronizedCollection <Event>();
                if (Id == 0)
                {
                    return(result);
                }
                var seList = DatabaseProvider.Database.ReadSubEvents(_engine, this);
                foreach (Event e in seList)
                {
                    e.Parent = this;
                    result.Add(e);
                }
                return(result);
            });

            _next = new Lazy <Event>(() =>
            {
                var next = (Event)DatabaseProvider.Database.ReadNext(_engine, this);
                if (next != null)
                {
                    next.Prior = this;
                }
                return(next);
            });

            _prior = new Lazy <Event>(() =>
            {
                Event prior = null;
                if (startType == TStartType.After && IdEventBinding > 0)
                {
                    prior = (Event)DatabaseProvider.Database.ReadEvent(_engine, IdEventBinding);
                }
                if (prior != null)
                {
                    prior.Next = this;
                }
                return(prior);
            });

            _parent = new Lazy <Event>(() =>
            {
                if ((startType == TStartType.WithParent || startType == TStartType.WithParentFromEnd) && IdEventBinding > 0)
                {
                    return((Event)DatabaseProvider.Database.ReadEvent(_engine, IdEventBinding));
                }
                return(null);
            });

            _rights = new Lazy <List <IAclRight> >(() =>
            {
                var rights = DatabaseProvider.Database.ReadEventAclList <EventAclRight>(this, _engine.AuthenticationService as IAuthenticationServicePersitency);
                rights.ForEach(r => ((EventAclRight)r).Saved += AclEvent_Saved);
                return(rights);
            });
            _routerPort    = routerPort;
            _recordingInfo = recordingInfo;

            FieldLengths = DatabaseProvider.Database.EventFieldLengths;
        }
Exemplo n.º 47
0
    public static void Main()
    {
        SynchronizedCollection <int> sc = new SynchronizedCollection <int>();

        Console.WriteLine(sc.SyncRoot);
    }
Exemplo n.º 48
0
        private SynchronizedCollection <Packet> GetPacketIndexesFromLines(string[] lines)
        {
            mainForm.toolStripStatusLabel_FileStatus.Text = "Current status: Getting packet indexes...";
            mainForm.Update();

            SynchronizedCollection <Packet> packetIndexesDictionary = new SynchronizedCollection <Packet>();

            Parallel.For(0, lines.Length, index =>
            {
                foreach (var packetName in Enum.GetNames(typeof(Packet.PacketTypes)))
                {
                    if (lines[index].Contains(packetName))
                    {
                        long i = index;

                        Enum.TryParse(packetName, out Packet.PacketTypes packetType);

                        switch (packetType)
                        {
                        case Packet.PacketTypes.SMSG_UPDATE_OBJECT:
                            {
                                Dictionary <long, long> indexesDictionary = new Dictionary <long, long>();
                                bool hasDestroyObjects = false;

                                do
                                {
                                    i++;

                                    if (!hasDestroyObjects && lines[i].Contains("DestroyObjectsCount") && !lines[i].Contains("DestroyObjectsCount : 0"))
                                    {
                                        hasDestroyObjects = true;
                                    }

                                    if (lines[i].Contains("UpdateType:") || ((lines[i].Contains("DestroyObjectsCount") || lines[i].Contains("DataSize")) && hasDestroyObjects) || lines[i] == "")
                                    {
                                        if (indexesDictionary.Count() == 0)
                                        {
                                            indexesDictionary.Add(i, 0);
                                        }
                                        else if (indexesDictionary.Last().Value == 0)
                                        {
                                            indexesDictionary[indexesDictionary.Last().Key] = i;

                                            if (lines[i] != "" && !lines[i].Contains("DataSize"))
                                            {
                                                indexesDictionary.Add(i, 0);
                                            }
                                        }
                                        else
                                        {
                                            indexesDictionary.Add(i, 0);
                                        }
                                    }
                                }while (lines[i] != "");

                                packetIndexesDictionary.Add(new Packet(packetType, LineGetters.GetTimeSpanFromLine(lines[index]), LineGetters.GetPacketNumberFromLine(lines[index]), indexesDictionary));
                                break;
                            }

                        case Packet.PacketTypes.SMSG_AURA_UPDATE:
                            {
                                Dictionary <long, long> indexesDictionary = new Dictionary <long, long>();

                                do
                                {
                                    i++;

                                    if (lines[i].Contains("Slot") || lines[i] == "")
                                    {
                                        if (indexesDictionary.Count() == 0)
                                        {
                                            indexesDictionary.Add(i, 0);
                                        }
                                        else if (indexesDictionary.Last().Value == 0)
                                        {
                                            indexesDictionary[indexesDictionary.Last().Key] = i - 1;

                                            if (lines[i] != "")
                                            {
                                                indexesDictionary.Add(i, 0);
                                            }
                                        }
                                    }
                                }while (lines[i] != "");

                                packetIndexesDictionary.Add(new Packet(packetType, LineGetters.GetTimeSpanFromLine(lines[index]), LineGetters.GetPacketNumberFromLine(lines[index]), indexesDictionary));

                                break;
                            }

                        default:
                            {
                                do
                                {
                                    i++;
                                }while (lines[i] != "");

                                packetIndexesDictionary.Add(new Packet(packetType, LineGetters.GetTimeSpanFromLine(lines[index]), LineGetters.GetPacketNumberFromLine(lines[index]), index, i));
                                break;
                            }
                        }

                        break;
                    }
                }
            });

            return(packetIndexesDictionary);
        }
Exemplo n.º 49
0
 public DHCPACKInjection(WinPcapDevice device, SynchronizedCollection <Data.Attack> attacks)
 {
     this.device  = device;
     this.attacks = attacks;
 }
        private void dialog_DialogEvent(object source, DialogEventArgs e)
        {
            Dialogs.AddDBDocDialog dialog = e.Dialog as Dialogs.AddDBDocDialog;
            if (dialog == null)
            {
                return;
            }
            Form form;

            Document.Objects.TmpFile tf = null;
            if (!string.IsNullOrEmpty(dialog.OldFileName))
            {
                Environment.DocToSave.TryRemove(dialog.OldFileName, out form);

                tf = Environment.GetTmpFileByValue(dialog.OldFileName);
            }
            switch (dialog.DialogResult)
            {
            case DialogResult.Yes:
            case DialogResult.Retry:
            case DialogResult.OK:
            {
                int docID   = dialog.DocID;
                int imageID = dialog.ImageID;

                Console.WriteLine("{0}: DocID: {1} ImageID: {2}", DateTime.Now.ToString("HH:mm:ss fff"), docID, imageID);
                if (docID > 0 && imageID > 0)
                {
                    bool work = dialog.DialogResult != DialogResult.Yes;
                    if (work && dialog.AddToWork)
                    {
                        Console.WriteLine("{0}: Add to Work", DateTime.Now.ToString("HH:mm:ss fff"));
                        Environment.WorkDocData.AddDocToEmployee(docID, Environment.CurEmp.ID);
                    }
                    DocumentSavedEventArgs doc = new DocumentSavedEventArgs(docID, imageID, work && dialog.GotoDoc, work && dialog.CreateEForm, dialog.CreateSlaveEForm);

                    if (work)
                    {
                        force        = !dialog.AddToWork;
                        sendMail     = dialog.SendMessage && !dialog.CreateSlaveEForm;
                        parentDocIDs = dialog.ParentDocIDs;
                        childDocIDs  = dialog.ChildDocIDs;
                        sendString   = GetStringToSave();
                        if (dialog.NeedOpenDoc)
                        {
                            Environment.OnNewWindow(this, doc);
                        }
                        Send(dialog.DocID);
                    }
                    Console.WriteLine("{0}: Save event", DateTime.Now.ToString("HH:mm:ss fff"));
                    OnDocumentSaved(doc);
                    Console.WriteLine("{0}: event", DateTime.Now.ToString("HH:mm:ss fff"));
                }
            }
                if (tf != null && tf.Window != null)
                {
                    tf.AscBeforeClose = false;
                    tf.Window.Close();
                }
                break;
            }

            if (tf != null)
            {
                tf.CurAct = Environment.ActionBefore.None;
                tf.LinkCnt--;
            }
        }
Exemplo n.º 51
0
 /// <summary>
 /// Tests if an appender with the given name already exixts
 /// </summary>
 /// <param name="list">List of appender</param>
 /// <param name="name">Name of the appender to test</param>
 /// <returns>bool</returns>
 public static bool IsAnAppenderName(this SynchronizedCollection <IAppender> list, string name)
 {
     return(list.Any(li => li.AppenderName == name));
 }
Exemplo n.º 52
0
        private List <object> GetDataFromPackets(string[] lines, SynchronizedCollection <Packet> packets)
        {
            mainForm.toolStripStatusLabel_FileStatus.Text = "Current status: Getting data from packets...";
            mainForm.Update();

            List <object> packetsList = new List <object>();

            foreach (Packet packet in packets)
            {
                switch (packet.type)
                {
                case Packet.PacketTypes.SMSG_UPDATE_OBJECT:
                {
                    foreach (var updatePacket in UpdateObjectPacket.ParseObjectUpdatePacket(lines, packet))
                    {
                        packetsList.Add(updatePacket);
                    }

                    break;
                }

                case Packet.PacketTypes.SMSG_SPELL_START:
                case Packet.PacketTypes.SMSG_SPELL_GO:
                {
                    SpellStartPacket spellPacket = SpellStartPacket.ParseSpellStartPacket(lines, packet);

                    if (spellPacket.guid != "")
                    {
                        packetsList.Add(spellPacket);
                    }

                    break;
                }

                case Packet.PacketTypes.SMSG_ON_MONSTER_MOVE:
                {
                    MonsterMovePacket monsterMovePacket = MonsterMovePacket.ParseMovementPacket(lines, packet);

                    if (monsterMovePacket.guid != "" && (monsterMovePacket.waypoints.Count() != 0 || monsterMovePacket.HasJump() ||
                                                         monsterMovePacket.HasOrientation() || monsterMovePacket.hasFacingToPlayer))
                    {
                        packetsList.Add(monsterMovePacket);
                    }

                    break;
                }

                case Packet.PacketTypes.SMSG_PLAY_ONE_SHOT_ANIM_KIT:
                {
                    PlayOneShotAnimKit playOneShotAnimKitPacket = PlayOneShotAnimKit.ParsePlayOneShotAnimKitPacket(lines, packet);

                    if (playOneShotAnimKitPacket.guid != "")
                    {
                        packetsList.Add(playOneShotAnimKitPacket);
                    }

                    break;
                }

                case Packet.PacketTypes.SMSG_CHAT:
                {
                    ChatPacket chatPacket = ChatPacket.ParseChatPacket(lines, packet);

                    if (chatPacket.guid != "")
                    {
                        packetsList.Add(chatPacket);
                    }

                    break;
                }

                case Packet.PacketTypes.SMSG_EMOTE:
                {
                    EmotePacket emotePacket = EmotePacket.ParseEmotePacket(lines, packet);

                    if (emotePacket.guid != "")
                    {
                        packetsList.Add(emotePacket);
                    }

                    break;
                }

                case Packet.PacketTypes.SMSG_AURA_UPDATE:
                {
                    foreach (var auraPacket in AuraUpdatePacket.ParseAuraUpdatePacket(lines, packet))
                    {
                        packetsList.Add(auraPacket);
                    }

                    break;
                }

                case Packet.PacketTypes.SMSG_SET_AI_ANIM_KIT:
                {
                    SetAiAnimKit setAiAnimKitPacket = SetAiAnimKit.ParseSetAiAnimKitPacket(lines, packet);

                    if (setAiAnimKitPacket.guid != "")
                    {
                        packetsList.Add(setAiAnimKitPacket);
                    }

                    break;
                }

                case Packet.PacketTypes.SMSG_PLAY_SPELL_VISUAL_KIT:
                {
                    PlaySpellVisualKit playSpellVisualKitPacket = PlaySpellVisualKit.ParsePlaySpellVisualKitPacket(lines, packet);

                    if (playSpellVisualKitPacket.guid != "")
                    {
                        packetsList.Add(playSpellVisualKitPacket);
                    }

                    break;
                }

                default:
                    break;
                }
            }

            SpellStartPacket.FilterSpellPackets(packetsList);

            return(packetsList);
        }
Exemplo n.º 53
0
 public EachConnection(ILogger logger, CookieContainer cc, ICommentOptions options, IYouTubeLibeServer server,
                       YouTubeLiveSiteOptions siteOptions, Dictionary <string, int> userCommentCountDict, SynchronizedCollection <string> receivedCommentIds,
                       ICommentProvider cp, IUserStoreManager userStoreManager)
 {
     _logger               = logger;
     _cc                   = cc;
     _options              = options;
     _server               = server;
     _siteOptions          = siteOptions;
     _userCommentCountDict = userCommentCountDict;
     _receivedCommentIds   = receivedCommentIds;
     _cp                   = cp;
     _userStoreManager     = userStoreManager;
 }
 internal XmlSerializerFaultFormatter(SynchronizedCollection <FaultContractInfo> faultContractInfoCollection,
                                      SynchronizedCollection <XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo> xmlSerializerFaultContractInfos)
     : base(faultContractInfoCollection)
 {
     Initialize(xmlSerializerFaultContractInfos);
 }
 public AllStaffRepository(SynchronizedCollection <Employee> repository) : base(repository)
 {
 }
 private void Initialize(SynchronizedCollection <XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo> xmlSerializerFaultContractInfos)
 {
     _xmlSerializerFaultContractInfos = xmlSerializerFaultContractInfos ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(xmlSerializerFaultContractInfos));
 }
Exemplo n.º 57
0
 public InvalidMacSpoofIPV4(WinPcapDevice device, SynchronizedCollection <Data.Attack> attacks)
 {
     this.device  = device;
     this.attacks = attacks;
 }