Beispiel #1
0
        private void SelectTypeDialog_DialogEvent(object source, DialogEventArgs e)
        {
            if (!keyLocker.Contains(Keys.Return))
            {
                keyLocker.Add(Keys.Return);
                try
                {
                    Form form = FindForm();
                    if (form != null)
                    {
                        form.Enabled = true;
                        form.Focus();
                    }

                    var dialog = e.Dialog as SelectTypeDialog;
                    if (dialog != null && (dialog.DialogResult == DialogResult.OK && dialog.TypeID > 0))
                    {
                        ThrowEvent(dialog.TypeID, dialog.Type);
                        text.SelectAll();
                    }
                    else
                    {
                        ID = 0;
                    }
                }
                catch (Exception ex)
                {
                    Data.Env.WriteToLog(ex);
                }
                finally
                {
                    keyLocker.Remove(Keys.Return);
                }
            }
        }
Beispiel #2
0
        static void socketServer_NewSessionConnected(WebSocketSession session)
        {
            string name = "null", data = string.Empty;
            int    ifor = 0;

            int.TryParse(session.Host[0].ToString(), out ifor);
            msgFor mfor = (msgFor)ifor;

            switch (mfor)
            {
            case msgFor.API:
            case msgFor.EVENT:
                data = session.Origin;
                session.Close();
                db.process_MSG(mfor, data);
                break;

            default:
                m_Sessions.Add(session);
                name = session.Cookies["name"] == null?Guid.NewGuid().ToString().Substring(0, 8) : session.Cookies["name"];

                //SendToAll(name + ": " + e);
                SendToAll("System: " + name + " connected");
                break;
            }
        }
Beispiel #3
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);
            }
        }
Beispiel #4
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);
            }
        }
        public void OnJobReady(ScheduleJob job)
        {
            switch (job.mPriority)
            {
            case ScheduleJob.Priorities.SMALL:
                var existsSmall = mSmallJobs.Any(anyJob => anyJob.Key.mFilePath == job.mFilePath);
                if (!existsSmall)
                {
                    mSmallJobs.TryAdd(job, null);
                }
                break;

            case ScheduleJob.Priorities.MEDIUM:
                var existsMedium = mMediumJobs.Any(anyJob => anyJob.mFilePath == job.mFilePath);
                if (!existsMedium)
                {
                    mMediumJobs.Add(job);
                }
                break;

            case ScheduleJob.Priorities.BIG:
                var existsBig = mBigJobs.Any(anyJob => anyJob.mFilePath == job.mFilePath);
                if (!existsBig)
                {
                    mBigJobs.Add(job);
                }
                break;
            }

            FetchSignal.waitHandle.Set();
        }
 public void MarkProductAsNotProcessed(List <XElement> productsToRemove)
 {
     foreach (var item in productsToRemove)
     {
         _productImageElementsToRemoveOnArchive.Add(item);
     }
 }
Beispiel #7
0
        public void OnCommentReceived(ICommentData data)
        {
            if (!Options.IsEnabled || data.IsNgUser || data.IsFirstComment)
            {
                return;
            }

            var a = new Data
            {
                Comment  = data.Comment,
                Nickname = data.Nickname,
                SiteName = data.SiteName,
            };

            _commentCollection.Add(a);
        }
Beispiel #8
0
        /// <summary>
        /// 注册Ajax节点
        /// </summary>
        /// <param name="node"></param>
        /// <param name="e"></param>
        private void AjaxMark(HtmlElement node, EventHandler e)
        {
            if (_ajaxSet == null)
            {
                _ajaxSet    = new SynchronizedCollection <Tuple <HtmlElement, EventHandler> >();
                _ajaxRaiser = new JobTimer(state =>
                {
                    foreach (var item in _ajaxSet.Where(p => p.Item1.GetAttribute(AjaxBlockEntity.AjaxBlock) == "0").ToArray())
                    {
                        item.Item2(item.Item1, EventArgs.Empty);
                    }
                }, Timeout.InfiniteTimeSpan)
                {
                    AutoDispose = false
                };
            }
            node.SetAttribute(AjaxBlockEntity.AjaxBlock, "0");
            var q = from t in _ajaxSet
                    where t.Item1 == node
                    select t;
            var tuple = q.SingleOrDefault();

            if (tuple != null)
            {
                _ajaxSet.Remove(tuple);
            }
            _ajaxSet.Add(Tuple.Create(node, e));
        }
Beispiel #9
0
        public void CreateFaxRoot <T>(SynchronizedCollection <T> faxNodes, Func <String, DataTable> execFunc, Func <int, string, string, T> CreateRoot) where T : FaxNode
        {
            faxNodes = new SynchronizedCollection <T>();

            using (DataTable dt = execFunc(Environment.CurCultureInfo.TwoLetterISOLanguageName))
                using (DataTableReader dr = dt.CreateDataReader())
                {
                    while (dr.Read())
                    {
                        var nodeID   = (int)dr[Environment.FaxFolderData.IDField];
                        var nodeName = (string)dr[Environment.FaxFolderData.NameField];
                        var nodePath = (string)dr[Environment.FaxFolderData.NetworkPathField];
                        var server   = Lib.Win.Document.Environment.GetServers().FirstOrDefault(t => Directory.Exists(Path.Combine(t.FaxPath, nodePath)));

                        if (server != null && !string.IsNullOrEmpty(server.FaxPath))
                        {
                            if (DirectoryAnalyser.IsAccessible(Path.Combine(server.FaxPath, nodePath)))
                            {
                                T node = CreateRoot(nodeID, nodeName, Path.Combine(server.FaxPath, nodePath));
                                PrepareAndAdd(node);
                                faxNodes.Add(node);
                            }
                        }
                    }
                    dr.Close();
                    dr.Dispose();
                    dt.Dispose();
                }
        }
Beispiel #10
0
        private void PrepareAndAddWorkFolder(Employee emp, EventHandler LoadComplete = null)
        {
            WorkFolderNode workFolderNode = WorkFolderNode.CreateRoot(emp, LoadComplete);

            PrepareAndAdd(workFolderNode);
            workFolderNodes.Add(new KeyValuePair <int, WorkFolderNode>(emp.ID, workFolderNode));
        }
Beispiel #11
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="this"></param>
        /// <param name="item"></param>
        /// <param name="match"></param>
        /// <returns></returns>
        public static bool UpdateOrInsert <T>(this SynchronizedCollection <T> @this, T item, Predicate <T> match)
        {
            var _result = false;

            lock (@this.SyncRoot)
            {
                for (var _offset = 0; _offset < @this.Count; _offset++)
                {
                    if (match(@this[_offset]) == true)
                    {
                        @this[_offset] = item;
                        _result        = true;

                        break;
                    }
                }

                if (_result == false)
                {
                    @this.Add(item);
                }
            }

            return(_result);
        }
Beispiel #12
0
        /// <summary>
        /// Callback for accepting connections.
        /// </summary>
        public virtual void OnAccept(IAsyncResult AR)
        {
            Socket AcceptedSocket = m_ListenerSock.EndAccept(AR);

            if (AcceptedSocket != null)
            {
                Console.WriteLine("\nNew client connected!\r\n");

                //Let sockets linger for 5 seconds after they're closed, in an attempt to make sure all
                //pending data is sent!
                AcceptedSocket.LingerState = new LingerOption(true, 5);
                NetworkClient NewClient = new NetworkClient(AcceptedSocket, this, m_EMode);

                switch (m_EMode)
                {
                case EncryptionMode.AESCrypto:
                    NewClient.ClientEncryptor = new AESEncryptor("");
                    break;
                }

                m_LoginClients.Add(NewClient);
                if (OnConnected != null)
                {
                    OnConnected(NewClient);
                }
            }

            m_ListenerSock.BeginAccept(new AsyncCallback(OnAccept), m_ListenerSock);
        }
Beispiel #13
0
        public static IEnumerable <AssemblyInfo> GetInfoByFilePath(string path)
        {
            var assemblyInfos = new SynchronizedCollection <AssemblyInfo>();
            var mod           = ModuleDefMD.Load(FileHelper.FileToByteArray(path));
            var fileName      = Path.GetFileName(path);

            foreach (var type in mod.GetTypes())
            {
                if (!(type.BaseType is null) && type.BaseType.FullName == "Spark.Abstractions.Job")
                {
                    var keyPropery = type.Properties.FirstOrDefault(_ => _.Name == "Key");
                    if (keyPropery != null)
                    {
                        dynamic method   = keyPropery.GetMethod.MethodBody;
                        var     keyValue = method.Instructions[0].Operand;
                        assemblyInfos.Add(new AssemblyInfo
                        {
                            Key = keyValue,
                            AssemblyFileName      = fileName,
                            AssemblyFullName      = type.FullName,
                            AssemblyName          = type.Name,
                            AssemblyQualifiedName = type.AssemblyQualifiedName
                        });
                    }
                }
            }
            return(assemblyInfos);
        }
 public void AddDisposableObj(IDisposable disposableObj)
 {
     if (!_objList.Contains(disposableObj))
     {
         _objList.Add(disposableObj);
     }
 }
Beispiel #15
0
        private async Task <List <TResult> > GetStatisDataAsync <TResult>(Func <IQueryable, Task <TResult> > access, IQueryable newSource = null)
        {
            newSource = newSource ?? _source;
            var tables = ShardingConfig.ConfigProvider.GetReadTables(_absTableName, _absDbName);
            List <Task <TResult> > tasks             = new List <Task <TResult> >();
            SynchronizedCollection <IRepository> dbs = new SynchronizedCollection <IRepository>();

            tasks = tables.Select(aTable =>
            {
                IRepository db;
                if (_repository.OpenedTransaction)
                {
                    db = _repository.GetMapRepository(aTable.conString, aTable.dbType);
                }
                else
                {
                    db = DbFactory.GetRepository(aTable.conString, aTable.dbType);
                }

                dbs.Add(db);
                var targetTable = MapTable(aTable.tableName);
                var targetIQ    = db.GetIQueryable(targetTable);
                var newQ        = newSource.ChangeSource(targetIQ);

                return(access(newQ));
            }).ToList();
            var res = (await Task.WhenAll(tasks)).ToList();

            if (!_repository.OpenedTransaction)
            {
                dbs.ForEach(x => x.Dispose());
            }

            return(res);
        }
Beispiel #16
0
        public static async void Block([NotNull] string key, [NotNull] Func <Task> taskFactory)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (taskFactory == null)
            {
                throw new ArgumentNullException(nameof(taskFactory));
            }

            if (Running.Contains(key))
            {
                // block if running
                return;
            }

            Running.Add(key);

            try
            {
                await taskFactory();
            }
            finally
            {
                Running.Remove(key);
            }
        }
Beispiel #17
0
        private void UpdateBestPlayers(Player player)
        {
            if (player.TotalMatches < 10 || player.TotalDeaths == 0)
            {
                return;
            }
            if (player.KD < minKD)
            {
                return;
            }
            var newList  = new SynchronizedCollection <Player> ();
            var count    = 0;
            var inserted = false;

            foreach (var elem in bestPlayers)
            {
                if (count >= 50)
                {
                    return;
                }
                if (elem.Name == player.Name)
                {
                    continue;
                }
                if (player.KD > elem.KD && !inserted)
                {
                    newList.Add(player);
                    inserted = true;
                }
                else
                {
                    newList.Add(elem);
                }
                count += 1;
                if (count == 50)
                {
                    minKD = elem.KD;
                }
            }
            if (count < 50)
            {
                newList.Add(player);
                minKD = player.KD;
            }
            minKD       = newList.Last().KD;
            bestPlayers = newList;
        }
Beispiel #18
0
        void timer_Tick(object sender, EventArgs e)
        {
            int         previousMeasurementTotalWeight = -1;
            Measurement currentMeasurement;

            /////////////////////////////////////////////////////////////////
            // take data from rawMeasurements and add it to Measurements List

            // add only stable
            // remove glitches
            // delete from rawMeasurements after adding? or keep track of last item added
            // add a global for currently added measurement so not to add 2 times

            if (rawMeasurements.Count > 0)
            {
                // we could already have added this measurement in the previous timer tick but it still continues as a stable measurement
                if (lastAddedMeasurement.TotalWeight != -1)
                {
                    currentMeasurement = lastAddedMeasurement;
                }
                else
                {
                    currentMeasurement = rawMeasurements[0];
                }

                for (int i = 0; i < rawMeasurements.Count; i++)
                {
                    previousMeasurementTotalWeight = currentMeasurement.TotalWeight; // cannot use i-1 because we deleted that. Cannot save elsewhere because of multiple branches
                    currentMeasurement             = rawMeasurements[i];
                    rawMeasurements.RemoveAt(i--);

                    // find first stable
                    if (!currentMeasurement.IsStable)
                    {
                        // reset everything here and continue
                        stableCounter = 0;
                        lastAddedMeasurement.TotalWeight = -1;
                        continue;
                    }

                    if (previousMeasurementTotalWeight == currentMeasurement.TotalWeight)
                    {
                        stableCounter++;

                        if (stableCounter == requiredConsecutiveStableMeasurements - 1) // Starts at 0
                        {
                            Measurements.Add(currentMeasurement);
                            lastAddedMeasurement = currentMeasurement;
                        }
                    }
                    else
                    {
                        stableCounter = 0;
                        lastAddedMeasurement.TotalWeight = -1;
                        continue;
                    }
                }
            }
        }
        private void textEmp_KeyUp(object sender, KeyEventArgs e)
        {
            if (keyLocker.Contains(e.KeyData))
            {
                return;
            }

            keyLocker.Add(e.KeyData);
            try
            {
                string txt = textEmp.Text.Trim();
                lastKeyData = e.KeyData;
                if (lastEmployeeText != textEmp.Text &&
                    !(textEmp.Text.Length == 1 && Regex.IsMatch(textEmp.Text, "[A-Za-z]")))
                {
                    if (e.KeyData == Keys.Enter)
                    {
                        if (findEmployeeID > 0)
                        {
                            OnFindEmployee(findEmployeeID);
                        }
                        else
                        {
                            parser.Parse(ref txt);
                            if (txt.Length > 0 && parser.CandidateCount > 0)
                            {
                                OnFindEmployee((int)parser.CandidateEmployees[0]["КодСотрудника"]);
                            }
                        }
                    }
                    if ((lastKeyData != Keys.Delete) && (lastKeyData != Keys.Back) && e.KeyData != Keys.Down &&
                        e.KeyData != Keys.Up && e.KeyData != Keys.Space)
                    {
                        ParseEmployee(false);
                    }
                    else if (lastKeyData == Keys.Delete || lastKeyData == Keys.Back)
                    {
                        findEmployeeID = 0;
                        if (comboBoxEmp.DroppedDown)
                        {
                            comboBoxEmp.DroppedDown = false;
                        }
                        if (textEmp.Text.Trim().Length == 0)
                        {
                            OnFindEmployee(0);
                        }
                    }
                }
                lastEmployeeText = textEmp.Text;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                keyLocker.Remove(e.KeyData);
            }
        }
Beispiel #20
0
 //private
 internal static void AddWindow(Window window)
 {
     if (windows.Contains(window))
     {
         return;
     }
     windows.Add(window);
 }
Beispiel #21
0
        private void PrepareAndAddFoundNode(Employee employee)
        {
            FoundNode foundNode =
                FoundNode.CreateRoot(employee);

            PrepareAndAdd(foundNode);
            foundNodes.Add(new KeyValuePair <int, FoundNode>(employee.ID, foundNode));
        }
Beispiel #22
0
 internal void Synchronized(string entityName, string propertyName)
 {
     if (!SynchronizedCollection.ContainsKey(entityName))
     {
         SynchronizedCollection.Add(entityName, new List <string>());
     }
     SynchronizedCollection[entityName].Add(propertyName);
 }
Beispiel #23
0
        /**
         * {@inheritDoc}
         */
        //@Override
        public override void addResponse(Response response)
        {
            Logger.Warn("Security response " + response + " triggered for user: " + response.GetUser().getUsername());

            responses.Add(response);

            base.notifyListeners(response);
        }
Beispiel #24
0
        public string CreateAggregateId()
        {
            var count = Interlocked.Increment(ref _count);
            var id    = $"{_prefix}-{DateTime.Now:yyyyMMddHHmmss}-{count:D2}-{Process.GetCurrentProcess().Id}-{Thread.CurrentThread.ManagedThreadId}";

            _generatedIds.Add(id);
            return(id);
        }
Beispiel #25
0
 private void _cpu_OnStep(object sender, OpCode e)
 {
     lastOpCodes.Add(e);
     if (lastOpCodes.Count > 10)
     {
         lastOpCodes.RemoveAt(0);
     }
 }
Beispiel #26
0
 /**
  * Register an {@link ResponseListener} to notify when {@link Response}s are added
  *
  * @param listener the {@link ResponseListener} to register
  */
 public void registerListener(ResponseListener listener)
 {
     //if (! listeners.Contains(listener)) {
     if (!listeners.Contains(listener))
     {
         listeners.Add(listener);
     }
 }
Beispiel #27
0
        public static PooledObject GetObject()
        {
            PooledObject po = null;

            if (avaiable.Count == 0)
            {
                po = new PooledObject();
                inUse.Add(po);
            }
            else
            {
                po = avaiable[0];
                inUse.Add(po);
                avaiable.RemoveAt(0);
            }
            return(po);
        }
Beispiel #28
0
        //public UndirectedAdjacencyMatrix(int size)
        //{
        //    Values = new bool[size][];
        //    for (int i = 0; i < size; i++)
        //    {
        //        Values[i] = new bool[size];
        //        for (int j = 0; j < size; j++)
        //        {
        //            Values[i][j] = false;
        //        }
        //    }

        //}
        // For thread-safe enumeration, see: http://www.codeproject.com/Articles/56575/Thread-safe-enumeration-in-C
        public void Add(int vertexPosition)
        {
            // first we must check if the vertexPosition is larger than size of array.
            var size = Values.Count;

            if (vertexPosition < size)
            {// then we must check if the identity element is true. If so, the array is already occupied there, so throw an exception.
                if (Values[vertexPosition][vertexPosition] == true)
                {
                    throw new DuplicateNameException("Error: Element already exists at specified position in UndirectedAdjacencyMatrix.");
                }
                else
                {// Else, we can set the identity for that position to true.
                    Values[vertexPosition][vertexPosition] = true;
                }
            }
            else
            {
                var difference = vertexPosition - size; // 2 = 10 - 8.
                for (int i = 0; i <= difference; i++)
                {
                    // for each place in the gap, we must construct a row with size equal to our new position.
                    var newRow = new SynchronizedCollection <bool>(vertexPosition);
                    // we need to first initialize the values of the new row.
                    for (int j = 0; j <= vertexPosition; j++) // the number of column values we must add increases with the number of rows.
                    {
                        newRow.Add(false);                    // initialize to default as false.
                    }

                    Values.Add(newRow); // If any rows have fewer elements (i.e. columns) than newRow, we must add elements (false) to them.
                    // Get rows that have fewer elements than newRow.
                    var newRowColumns = newRow.Count;
                    for (int j = 0; j < Values.Count; j++)
                    {
                        int currentRowCount = Values[j].Count;
                        if (currentRowCount < newRow.Count)
                        {
                            var elementCountDiff = newRowColumns - currentRowCount;
                            for (int k = 0; k < elementCountDiff; k++)
                            {
                                Values[j].Add(false); // Add default elements to the row until the number of elements matches newRow.
                            }
                        }
                    }

                    // At this point, all of the rows should have equal numbers of columns.

                    for (int j = 0; j < vertexPosition; j++)
                    {
                        // all of the new row values should be false except for the row value at our vertexPosition.
                        var pos = size + i;
                        var row = Values[pos];
                        Values[size + i][j] = false;
                    }
                }
                Values[vertexPosition][vertexPosition] = true;
            }
        }
Beispiel #29
0
        /// <summary>
        /// Resoloves the song info.
        /// </summary>
        /// <param name="song">The song to resolve.</param>
        /// <returns>The resolved song.</returns>
        public static SongInformation Resolve(SongInformation song)
        {
            if (song != null && !string.IsNullOrEmpty(song.Location))
            {
                SongInformation found = null;
                lock (_resolvedSongs)
                {
                    found = _resolvedSongs.ToList().FirstOrDefault(s => s.Location.ToLower() == song.Location.ToLower());
                }

                if (found != null)
                {
                    return(found);
                }

                try
                {
                    var file = TagLib.File.Create(song.Location);

                    try
                    {
                        using (var reader = new MediaFoundationReader(song.Location))
                        {
                            double?time = reader?.TotalTime.TotalSeconds;
                            song.Duration = time == null ? 0 : (long)time;
                        }
                    }
                    catch
                    {
                    }

                    song.Genre     = string.Join(", ", file.Tag.Genres);
                    song.Album     = file.Tag.Album;
                    song.Band      = string.Join(", ", file.Tag.Composers.Union(file.Tag.Artists));
                    song.DateAdded = new FileInfo(song.Location).CreationTime;

                    if (file.Tag.Year > 0)
                    {
                        song.DateCreated = new DateTime((int)file.Tag.Year, 1, 1);
                    }

                    song.Title      = string.IsNullOrEmpty(file.Tag.Title) ? song.Title : file.Tag.Title;
                    song.Image      = file.Tag.Pictures?.FirstOrDefault()?.Data?.Data;
                    song.IsResolved = true;
                    lock (_resolvedSongs)
                    {
                        _resolvedSongs.Add(song);
                    }

                    file.Dispose();
                }
                catch
                {
                }
            }

            return(song);
        }
Beispiel #30
0
        public void CollectFanArt(Guid mediaItemId, IDictionary <Guid, IList <MediaItemAspect> > aspects)
        {
            if (_checkCache.Contains(mediaItemId))
            {
                return;
            }

            Guid?collectionMediaItemId = null;
            IDictionary <Guid, string> actorMediaItems = new Dictionary <Guid, string>();
            SingleMediaItemAspect      videoAspect;
            List <string> actors = new List <string>();

            if (MediaItemAspect.TryGetAspect(aspects, VideoAspect.Metadata, out videoAspect))
            {
                IEnumerable <string> actorObjects = videoAspect.GetCollectionAttribute <string>(VideoAspect.ATTR_ACTORS);
                if (actorObjects != null)
                {
                    actors.AddRange(actorObjects);
                }
            }

            IList <MultipleMediaItemAspect> relationAspects;

            if (MediaItemAspect.TryGetAspects(aspects, RelationshipAspect.Metadata, out relationAspects))
            {
                foreach (MultipleMediaItemAspect relation in relationAspects)
                {
                    if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == MovieCollectionAspect.ROLE_MOVIE_COLLECTION)
                    {
                        collectionMediaItemId = (Guid)relation[RelationshipAspect.ATTR_LINKED_ID];
                    }
                    if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == PersonAspect.ROLE_ACTOR)
                    {
                        int?index = (int?)relation[RelationshipAspect.ATTR_RELATIONSHIP_INDEX];
                        if (index.HasValue && actors.Count > index.Value && index.Value >= 0)
                        {
                            actorMediaItems[(Guid)relation[RelationshipAspect.ATTR_LINKED_ID]] = actors[index.Value];
                        }
                    }
                }
            }

            _checkCache.Add(mediaItemId);
            Task.Run(() => ExtractFanArt(mediaItemId, aspects, collectionMediaItemId, actorMediaItems));
        }
Beispiel #31
0
        public void CollectFanArt(Guid mediaItemId, IDictionary <Guid, IList <MediaItemAspect> > aspects)
        {
            if (_checkCache.Contains(mediaItemId))
            {
                return;
            }

            Guid?albumMediaItemId = null;
            IDictionary <Guid, string> artistMediaItems = new Dictionary <Guid, string>();
            SingleMediaItemAspect      audioAspect;
            List <string> artists = new List <string>();

            if (MediaItemAspect.TryGetAspect(aspects, AudioAspect.Metadata, out audioAspect))
            {
                IEnumerable <string> artistObjects = audioAspect.GetCollectionAttribute <string>(AudioAspect.ATTR_ALBUMARTISTS);
                if (artistObjects != null)
                {
                    artists.AddRange(artistObjects);
                }
            }

            IList <MultipleMediaItemAspect> relationAspects;

            if (MediaItemAspect.TryGetAspects(aspects, RelationshipAspect.Metadata, out relationAspects))
            {
                foreach (MultipleMediaItemAspect relation in relationAspects)
                {
                    if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == AudioAlbumAspect.ROLE_ALBUM)
                    {
                        albumMediaItemId = (Guid)relation[RelationshipAspect.ATTR_LINKED_ID];
                    }
                    if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == PersonAspect.ROLE_ALBUMARTIST)
                    {
                        int?index = (int?)relation[RelationshipAspect.ATTR_RELATIONSHIP_INDEX];
                        if (index.HasValue && artists.Count > index.Value && index.Value >= 0)
                        {
                            artistMediaItems[(Guid)relation[RelationshipAspect.ATTR_LINKED_ID]] = artists[index.Value];
                        }
                    }
                }
            }

            _checkCache.Add(mediaItemId);
            Task.Run(() => ExtractFanArt(mediaItemId, aspects, albumMediaItemId, artistMediaItems));
        }
Beispiel #32
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"));
        }
 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);
 }
        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();
        }
Beispiel #35
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();
        }
 private static void _runOperation(SynchronizedCollection<FileOperation> queue, ref bool queueRunningIndicator)
 {
     FileOperation op;
     lock (queue.SyncRoot)
         op = queue.FirstOrDefault();
     while (op != null)
     {
         queue.Remove(op);
         if (!op.Aborted)
         {
             if (op.Do())
             {
                 if (OperationCompleted != null)
                     OperationCompleted(op);
                 if (op.SuccessCallback != null)
                     op.SuccessCallback();
             }
             else
             {
                 if (op.TryCount > 0)
                 {
                     System.Threading.Thread.Sleep(500);
                     queue.Add(op);
                 }
                 else
                 {
                     op.Fail();
                     if (OperationCompleted != null)
                         OperationCompleted(op);
                 }
             }
         }
         lock (queue.SyncRoot)
             op = queue.FirstOrDefault();
     }
     lock (queue.SyncRoot)
         queueRunningIndicator = false;
 }
                private void GenerateXmlSerializerFaultContractInfos()
                {
                    SynchronizedCollection<XmlSerializerFaultContractInfo> faultInfos = new SynchronizedCollection<XmlSerializerFaultContractInfo>();
                    for (int i = 0; i < this.Operation.Faults.Count; i++)
                    {
                        FaultDescription fault = this.Operation.Faults[i];
                        FaultContractInfo faultContractInfo = new FaultContractInfo(fault.Action, fault.DetailType, fault.ElementName, fault.Namespace, this.Operation.KnownTypes);

                        XmlQualifiedName elementName;
                        XmlMembersMapping xmlMembersMapping = this.ImportFaultElement(fault, out elementName);

                        SerializerStub serializerStub = _parent._generation.AddSerializer(xmlMembersMapping);
                        faultInfos.Add(new XmlSerializerFaultContractInfo(faultContractInfo, serializerStub, elementName));
                    }
                    _xmlSerializerFaultContractInfos = faultInfos;
                }
Beispiel #38
0
    // This Unit test is based from full framework test
    public static void SynchronizedCollectionPublicMembersTest()
    {
        SynchronizedCollection<int> coll = new SynchronizedCollection<int>();
        int size = 100;
        for (int i = 0; i < size; i++)
            coll.Add(i);

        Assert.True(coll.Count == size, string.Format("collection count was wrong! Expected: {0} got: {1}", size, coll.Count));

        for (int i = 0; i < size; i++)
        {
            Assert.True(coll[i] == i, string.Format("coll element {0} was wrong! Expected: {1} got: {2} ", i, i, coll[i]));
            Assert.True(coll.IndexOf(i) == i, string.Format("coll IndexOf wasn't right! Expected: {0} got: {1}" , i, coll.IndexOf(i)));
            Assert.True(coll.Contains(i), string.Format("coll Contains failed to find the value {0}.", i));
        }

        SynchronizedCollection<int> coll2 = new SynchronizedCollection<int>(new object(), new List<int>(coll));
        for (int i = 0; i < size; i++)
        {
            Assert.True(coll2[i] == i, string.Format("coll2 element was wrong! expected: {0} got: {1} ", i, coll2[i]));
        }

        SynchronizedCollection<int> coll3 = new SynchronizedCollection<int>(new object(), 1, 2, 3, 4, 5 , 6);
        for (int i = 0; i < 5; i++)
        {
            Assert.True(coll3[i] == i + 1, string.Format("coll3 element {0} was wrong! expected: {1} got: {2}", i, i+1, coll3[i]));
        }
        int newValue = 80;
        coll3[5] = newValue;
        Assert.True(coll3[5] == newValue);

        IEnumerator <int> e = coll.GetEnumerator();
        int n = 0;
        while (e.MoveNext())
        {
            Assert.True(e.Current.Equals(n++), string.Format("Expected: {0}, got:{1}", n-1, e.Current));
        }

        Assert.True(n == 100, string.Format("Expect number of elements: {0}, got:{1}", 100, n));

        int[] array = new int[size + 1];
        coll.CopyTo(array, 1);
        for (int i = 0; i < size; i++)
        {
            Assert.True(array[i + 1] == i, string.Format("After CopyTo, Element {0} was wrong!  Expected: {1} got:  {2}", i, i+1, array[i + 1]));
        }

        coll.Add(coll.Count);
        coll.Insert(0, -1);
        coll.RemoveAt(0);
        coll.Remove(coll.Count - 1);
        Assert.True(coll.Count == size, string.Format("Expect number of elements after modification: {0}, got: {1}", size, coll.Count));

        for (int i = 0; i < size; i++)
        {
            Assert.True(coll[i] == i, string.Format("coll element was wrong after modification! Expected: {0} got: {1} ", i, coll[i]));
        }

        coll.Clear();
        Assert.True(coll.Count == 0, string.Format("Clear operation failed!, expected: 0, actual {0}", coll.Count));

        // Negative cases
        Assert.Throws<ArgumentNullException>("syncRoot", () =>
        {
            new SynchronizedCollection<int>(null);
        });

        Assert.Throws<ArgumentNullException>("list", () =>
        {
            new SynchronizedCollection<int>(new object(), null);
        });

        Assert.Throws<ArgumentNullException>("syncRoot", () =>
        {
            new SynchronizedCollection<int>(null, new List<int>());
        });

        Assert.Throws<ArgumentNullException>("syncRoot", () =>
        {
            new SynchronizedCollection<int>(null, 1, 2, 3, 4);
        });

        Assert.Throws<ArgumentOutOfRangeException>(() =>
        {
            coll[1000] = 5;
        });

        Assert.Throws<ArgumentOutOfRangeException>(() =>
        {
            coll[-1] = 5;
        });

        Assert.Throws<ArgumentOutOfRangeException>(() =>
        {
            coll.Insert(1000, 5);
        });

        Assert.Throws<ArgumentOutOfRangeException>(() =>
        {
            coll.Insert(-1, 5);
        });

        Assert.False(coll.Remove(100000));

        Assert.Throws<ArgumentOutOfRangeException>(() =>
        {
            coll.RemoveAt(-1);
        });

        Assert.Throws<ArgumentOutOfRangeException>(() =>
        {
            coll.RemoveAt(10000);
        });
    }
Beispiel #39
0
        /// <summary>
        /// Generates builds based on the instances variables.
        /// </summary>
        /// <param name="top">If non-zero, runs until N builds are generated</param>
        /// <param name="time">If non-zero, runs for N seconds</param>
        /// <param name="printTo">Periodically gives progress% and if it failed</param>
        /// <param name="progTo">Periodically gives the progress% as a double</param>
        /// <param name="dumpBads">If true, will only track new builds if they score higher than an other found builds</param>
        public void GenBuilds(int top = 0, int time = 0, Action<string> printTo = null, Action<double> progTo = null, bool dumpBads = false, bool saveStats = false)
        {
            if (runes.Any(r => r == null))
                return;

            // if to get awakened
            if (DownloadAwake && !mon.downloaded)
            {
                var mref = MonsterStat.FindMon(mon);
                if (mref != null)
                {
                    // download the current (unawakened monster)
                    var mstat = mref.Download();
                    // if the retrieved mon is unawakened, get the awakened
                    if (!mstat.Awakened && mstat.AwakenRef != null)
                    {
                        mon = mstat.AwakenRef.Download().GetMon(mon);
                    }
                }
            }
            // 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)
            {
                var mref = MonsterStat.FindMon(mon);
                if (mref != null)
                {
                    mon = mref.Download().GetMon(mon);
                }
            }

            try
            {
                Best = null;
                SynchronizedCollection<Monster> tests = new SynchronizedCollection<Monster>();
                long count = 0;
                long total = runes[0].Count();
                total *= runes[1].Count();
                total *= runes[2].Count();
                total *= runes[3].Count();
                total *= runes[4].Count();
                total *= runes[5].Count();
                long complete = total;

                if (total == 0)
                {
                    if (printTo != null)
                        printTo.Invoke("0 perms");
                    Console.WriteLine("Zero permuations");
                    return;
                }
                if (!AllowBroken && BuildSets.Count == 1 && Rune.SetRequired(BuildSets[0]) == 4)
                {
                    if (printTo != null)
                        printTo.Invoke("Bad sets");
                    Console.WriteLine("Cannot use 4 set with no broken");
                    return;
                }

                bool hasSort = false;
                foreach (string stat in statNames)
                {
                    if (Sort[stat] != 0)
                    {
                        hasSort = true;
                        break;
                    }
                }
                foreach (string extra in extraNames)
                {
                    if (Sort.ExtraGet(extra) != 0)
                    {
                        hasSort = true;
                        break;
                    }
                }
                if (top == 0 && !hasSort)
                {
                    if (printTo != null)
                        printTo.Invoke("No sort");
                    Console.WriteLine("No method of determining best");
                    return;
                }

                DateTime begin = DateTime.Now;
                DateTime timer = DateTime.Now;

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

                // build the scoring function
                Func<Stats, double> sort = (m) =>
                {
                    double pts = 0;

                    foreach (string stat in statNames)
                    {
                    // if this stat is used for sorting
                    if (Sort[stat] != 0)
                        {
                        // sum points for the stat
                        pts += m[stat] / Sort[stat];
                        // if exceeding max, subtracted the gained points and then some
                        if (Threshold[stat] != 0)
                                pts -= Math.Max(0, m[stat] - Threshold[stat]) / Sort[stat];
                        }
                    }
                    // look, cool metrics!
                    foreach (string extra in extraNames)
                    {
                        if (Sort.ExtraGet(extra) != 0)
                        {
                            pts += m.ExtraValue(extra) / Sort.ExtraGet(extra);
                            if (Threshold.ExtraGet(extra) != 0)
                                pts -= Math.Max(0, m.ExtraValue(extra) - Threshold.ExtraGet(extra)) / Sort.ExtraGet(extra);
                        }
                    }
                    return pts;
                };

                int[] slotFakes = new int[6];
                bool[] slotPred = new bool[6];

                // crank the rune prediction
                for (int i = 0; i < 6; i++)
                {
                    Rune[] rs = runes[i];
                    int raiseTo = 0;
                    bool predictSubs = false;

                    // find the largest number to raise to
                    // if any along the tree say to predict, do it
                    if (runePrediction.ContainsKey("g"))
                    {
                        int glevel = runePrediction["g"].Key;
                        if (glevel > raiseTo)
                            raiseTo = glevel;
                        predictSubs |= runePrediction["g"].Value;
                    }
                    if (runePrediction.ContainsKey(((i % 2 == 0) ? "o" : "e")))
                    {
                        int mlevel = runePrediction[((i % 2 == 0) ? "o" : "e")].Key;
                        if (mlevel > raiseTo)
                            raiseTo = mlevel;
                        predictSubs |= runePrediction[((i % 2 == 0) ? "o" : "e")].Value;
                    }
                    if (runePrediction.ContainsKey((i + 1).ToString()))
                    {
                        int slevel = runePrediction[(i + 1).ToString()].Key;
                        if (slevel > raiseTo)
                            raiseTo = slevel;
                        predictSubs |= runePrediction[(i + 1).ToString()].Value;
                    }

                    slotFakes[i] = raiseTo;
                    slotPred[i] = predictSubs;

                }

                // set to running
                isRun = true;

                // Parallel the outer loop
                var loopRes = Parallel.ForEach<Rune>(runes[0], (r0, loopState) =>
                {
                    if (!isRun)
                    //break;
                    loopState.Break();

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

                    foreach (Rune r1 in runes[1])
                    {
                        if (!isRun) // Can't break to a lable, don't want to goto
                        break;
                        foreach (Rune r2 in runes[2])
                        {
                            if (!isRun)
                                break;
                            foreach (Rune r3 in runes[3])
                            {
                                if (!isRun)
                                    break;
                                foreach (Rune r4 in runes[4])
                                {
                                    if (!isRun)
                                        break;
                                    foreach (Rune r5 in runes[5])
                                    {
                                        if (!isRun)
                                            break;

                                        Monster test = new Monster(mon);
                                        test.Current.shrines = shrines;
                                        test.Current.leader = leader;

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

                                        test.ApplyRune(r0);
                                        test.ApplyRune(r1);
                                        test.ApplyRune(r2);
                                        test.ApplyRune(r3);
                                        test.ApplyRune(r4);
                                        test.ApplyRune(r5);

                                        if (saveStats)
                                        {
                                            foreach (Rune r in test.Current.runes)
                                            {
                                                r.manageStats_LoadGen++;
                                            }
                                        }

                                        var cstats = test.GetStats();

                                        bool maxdead = false;

                                        if (Maximum != null)
                                        {
                                            foreach (var stat in statNames)
                                            {
                                                if (Maximum[stat] > 0 && cstats[stat] > Maximum[stat])
                                                {
                                                    maxdead = true;
                                                    break;
                                                }
                                            }
                                        }

                                        // check if build meets minimum
                                        if (Minimum != null && !(cstats > Minimum))
                                        {
                                            kill++;
                                        }
                                        else if (maxdead)
                                        {
                                            kill++;
                                        }
                                        // if no broken sets, check for broken sets
                                        else if (!AllowBroken && !test.Current.SetsFull)
                                        {
                                            kill++;
                                        }
                                        // if there are required sets, ensure we have them
                                        else if (RequiredSets != null && RequiredSets.Count > 0
                                        // this Linq adds no overhead compared to GetStats() and ApplyRune()
                                            && !RequiredSets.All(s => test.Current.sets.Count(q => q == s) >= RequiredSets.Count(q => q == s)))
                                        {
                                            kill++;
                                        }
                                        else
                                        {
                                            // we found an okay build!
                                            plus++;

                                            if (saveStats)
                                            {
                                                foreach (Rune r in test.Current.runes)
                                                {
                                                    r.manageStats_LoadFilt++;
                                                }
                                            }

                                            // if we are to track all good builds, keep it
                                            if (!dumpBads)
                                            {
                                                tests.Add(test);
                                            }
                                            // if we only want to track really good builds
                                            else
                                            {
                                                // if there are currently no good builds, keep it
                                                if (tests.FirstOrDefault() == null)
                                                {
                                                    tests.Add(test);
                                                    Best = test;
                                                }
                                                else
                                                {
                                                    // if this build is better than the best, keep it
                                                    if (sort(Best.GetStats()) < sort(test.GetStats()))
                                                    {
                                                        Best = test;
                                                        tests.Add(test);
                                                    }
                                                }
                                            }
                                        }

                                        // every second, give a bit of feedback to those watching
                                        if (DateTime.Now > timer.AddSeconds(1))
                                        {
                                            timer = DateTime.Now;
                                            Console.WriteLine(count + "/" + total + "  " + String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));
                                            if (printTo != null)
                                                printTo.Invoke(String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));
                                            if (progTo != null)
                                                progTo.Invoke((double)(count + complete - total) / (double)complete);

                                            if (time > 0)
                                            {
                                                if (DateTime.Now > begin.AddSeconds(time))
                                                {
                                                    isRun = false;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    // sum up what work we've done
                                    Interlocked.Add(ref total, -kill);
                                    kill = 0;
                                    Interlocked.Add(ref count, plus);
                                    plus = 0;

                                    // if we've got enough, stop
                                    if (top > 0 && count >= top)
                                    {
                                        isRun = false;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                });

                // write out completion
                Console.WriteLine(isRun + " " + count + "/" + total + "  " + String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));
                if (printTo != null)
                    printTo.Invoke("100%");
                if (progTo != null)
                    progTo.Invoke(1);

                // sort *all* the builds
                loads = tests.Where(t => t != null).OrderByDescending(r => sort(r.GetStats())).Take((top > 0 ? top : 1));

                // dump everything to console, if nothing to print to
                if (printTo == null)
                    foreach (var l in loads)
                    {
                        Console.WriteLine(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.Count() == 0)
                {
                    Console.WriteLine("No builds :(");
                    if (printTo != null)
                        printTo.Invoke("Zero :(");
                }
                else
                {
                    // remember the good one
                    Best = loads.First();
                    foreach (Rune r in Best.Current.runes)
                    {
                        r.manageStats_In = true;
                    }
                    for (int i = 0; i < 6; i++)
                    {
                        if (mon.Current.runes[i] != null && mon.Current.runes[i].ID != Best.Current.runes[i].ID)
                            mon.Current.runes[i].Swapped = true;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error " + e);
                if (printTo != null)
                    printTo.Invoke(e.ToString());
            }
        }
 private void GenerateXmlSerializerFaultContractInfos()
 {
     SynchronizedCollection<XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo> synchronizeds = new SynchronizedCollection<XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo>();
     for (int i = 0; i < this.Operation.Faults.Count; i++)
     {
         XmlQualifiedName name;
         FaultDescription fault = this.Operation.Faults[i];
         FaultContractInfo faultContractInfo = new FaultContractInfo(fault.Action, fault.DetailType, fault.ElementName, fault.Namespace, this.Operation.KnownTypes);
         XmlMembersMapping mapping = this.ImportFaultElement(fault, out name);
         XmlSerializerOperationBehavior.Reflector.SerializerStub serializerStub = this.parent.generation.AddSerializer(mapping);
         synchronizeds.Add(new XmlSerializerOperationBehavior.Reflector.XmlSerializerFaultContractInfo(faultContractInfo, serializerStub, name));
     }
     this.xmlSerializerFaultContractInfos = synchronizeds;
 }
Beispiel #41
0
        public static Loadout MakeBuild(Monster mon, IEnumerable<Rune>[] runesSlot, Func<Stats, double> sort, Predicate<RuneSet[]> reqsets = null, Predicate<Stats> minimum = null)
        {
            System.Collections.Generic.SynchronizedCollection<Monster> tests = new SynchronizedCollection<Monster>();//new List<Monster>();
            long count = 0;
            long total = runesSlot[0].Count();
            total *= runesSlot[1].Count();
            total *= runesSlot[2].Count();
            total *= runesSlot[3].Count();
            total *= runesSlot[4].Count();
            total *= runesSlot[5].Count();
            long complete = total;

            DateTime timer = DateTime.Now;

            Console.WriteLine(count + "/" + total + "  " + String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));

            Parallel.ForEach<Rune>(runesSlot[0], r0 =>
            {
                int kill = 0;
                int plus = 0;

                foreach (Rune r1 in runesSlot[1])
                {
                    foreach (Rune r2 in runesSlot[2])
                    {
                        foreach (Rune r3 in runesSlot[3])
                        {
                            foreach (Rune r4 in runesSlot[4])
                            {
                                foreach (Rune r5 in runesSlot[5])
                                {
                                    Monster test = new Monster(mon);
                                    test.ApplyRune(r0);
                                    test.ApplyRune(r1);
                                    test.ApplyRune(r2);
                                    test.ApplyRune(r3);
                                    test.ApplyRune(r4);
                                    test.ApplyRune(r5);

                                    if (minimum != null && !minimum.Invoke(test.GetStats()))
                                    {
                                        //total--;
                                        kill++;
                                        //Interlocked.Decrement(ref total);
                                    }
                                    else if (reqsets != null && !reqsets.Invoke(test.Current.sets))
                                    {
                                        kill++;
                                        //Interlocked.Decrement(ref total);
                                    }
                                    else
                                    {
                                        plus++;
                                        tests.Add(test);
                                        //Interlocked.Increment(ref count);
                                        //count++;
                                    }

                                    if (DateTime.Now > timer.AddSeconds(1))
                                    {
                                        timer = DateTime.Now;
                                        Console.WriteLine(count + "/" + total + "  " + String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));
                                    }
                                }
                                Interlocked.Add(ref total, -kill);
                                kill = 0;
                                Interlocked.Add(ref count, plus);
                                plus = 0;
                            }
                        }
                    }
                }
            });
            Console.WriteLine(count + "/" + total + "  " + String.Format("{0:P2}", (double)(count + complete - total) / (double)complete));

            var desc = tests.Where(t => t != null).OrderByDescending(r => sort(r.GetStats())).Take(10).ToArray();
            foreach (var l in desc)
            {
                Console.WriteLine(l.GetStats().Health + "  " + l.GetStats().Attack + "  " + l.GetStats().Defense + "  " + l.GetStats().Speed
                    + "  " + l.GetStats().CritRate + "%" + "  " + l.GetStats().CritDamage + "%" + "  " + l.GetStats().Resistance + "%" + "  " + l.GetStats().Accuracy + "%");
            }

            if (desc.Count() == 0)
            {
                Console.WriteLine("No builds :(");
                return null;
            }

            var best = desc.First().Current;

            foreach (Rune r in best.runes)
            {
                r.Locked = true;
            }

            return best;
        }
Beispiel #42
0
        static HtmlProviders()
        {
            ParserProviders = new SynchronizedCollection<IHtmlParserProvider>( _parserProvidersSync );
              ContentProviders = new SynchronizedCollection<IHtmlContentProvider>( _contentProvidersSync );
              RequestMappers = new SynchronizedCollection<IRequestMapper>( _mappersSync );
              CachePolicyProviders = new SynchronizedCollection<ICachePolicyProvider>( _cachePoliciesSync );

              ContentProviders.Add( new StaticFileLoader() );
              ContentProviders.Add( new AspxFileLoader() );

              RequestMappers.Add( new DefaultRequestMapper() );
        }
 public bool Initialize(string sIPWebServer, string sIPShare, List<IGServer> lServerPorts)
 {
     if (m_bIsInitialized)
         return true;
     lock (m_lockObject)
     {
         if (!base.Initialize(sIPShare, lServerPorts))
             return false;
         m_ipWebServer = IPAddress.Parse(sIPWebServer);
         if (sIPShare.Substring(0, sIPWebServer.LastIndexOf('.')) != m_sSubNetwork)
             throw new ApplicationException("starting: Share and Client must be in the same subnetwork.");
         UpdateLogPath();
         if (lServerPorts != null)
         {
             m_nNbInitialServers = lServerPorts.Count;
             m_lServers = new SynchronizedCollection<IGServer>();
             foreach (IGServer server in lServerPorts)
                 m_lServers.Add(new IGServerLocal(m_endPoint.Address.ToString(), server.m_endPoint.Port, sIPWebServer));
             m_timer.Start();
         }
         m_timerAddServer = new System.Timers.Timer();
         m_timerAddServer.Elapsed += new ElapsedEventHandler(onTimedEvent_addServer);
         m_timerAddServer.Interval = ADDSERVERINTERVAL;
         m_timerAddServer.Start();
         if (IGServerManager.AppSettings["DO_MOUNT"] == "Yes")
         {
             if (!mountDrives())
                 return false;
         }
         if (!ConnectToAllServers())
             return false;
         m_bIsInitialized = true;
         return true;
     }
 }
 public override SynchronizedCollection<IGConnection> GetConnections()
 {
     SynchronizedCollection<IGConnection> lUserConnections = new SynchronizedCollection<IGConnection>();
     foreach (IGConnectionLocal connection in m_lConnections)
     {
         if ((connection.IsUserConnected()) || connection.IsUserConnecting())
             lUserConnections.Add(connection);
     }
     return lUserConnections;
 }
        private void GetMemberStats()
        {
            while (true)
            {
                if (ffxivProcess == null)
                {
                    new System.Threading.ManualResetEvent(false).WaitOne(1000);
                    continue;
                }

                List<Combatant> combatantList = GetCombatantList();
                List<uint> partyListIDs = GetCurrentPartyList();
                SynchronizedCollection<Combatant> partyTemp = new SynchronizedCollection<Combatant>();
                SynchronizedCollection<Combatant> partyTempSorted = new SynchronizedCollection<Combatant>();

                SynchronizedCollection<Combatant> enemyTemp = new SynchronizedCollection<Combatant>();

                if (partyListIDs != null)
                {
                    foreach (uint ID in partyListIDs) //Find party members
                    {
                        foreach (Combatant combatant in combatantList)
                        {
                            if (ID == combatant.ID)
                            {
                                partyTemp.Add(combatant);

                                break;
                            }
                        }
                    }

                    if (partyTemp.Count > 0)
                    {

                        { //SCH
                            foreach (Combatant c in partyTemp)
                            {
                                if (c.Job == 0x1C)
                                {
                                    partyTempSorted.Add(c);
                                }
                            }
                            { //WHM
                                foreach (Combatant c in partyTemp)
                                {
                                    if (c.Job == 0x18)
                                    {
                                        partyTempSorted.Add(c);

                                    }
                                }
                            }

                        }
                        { //AST
                            foreach (Combatant c in partyTemp)
                            {
                                if (c.Job == 0x21)
                                {
                                    partyTempSorted.Add(c);
                                }
                            }
                            { //PLD
                                foreach (Combatant c in partyTemp)
                                {
                                    if (c.Job == 0x13)
                                    {
                                        partyTempSorted.Add(c);
                                    }
                                }
                            }
                            { //WAR
                                foreach (Combatant c in partyTemp)
                                {
                                    if (c.Job == 0x15)
                                    {
                                        partyTempSorted.Add(c);
                                    }
                                }
                            }
                            { //DRK
                                foreach (Combatant c in partyTemp)
                                {
                                    if (c.Job == 0x20)
                                    {
                                        partyTempSorted.Add(c);
                                    }
                                }
                            }
                            { //MNK
                                foreach (Combatant c in partyTemp)
                                {
                                    if (c.Job == 0x14)
                                    {
                                        partyTempSorted.Add(c);
                                    }
                                }

                            }
                            { //DRG
                                foreach (Combatant c in partyTemp)
                                {
                                    if (c.Job == 0x16)
                                    {
                                        partyTempSorted.Add(c);
                                    }
                                }

                            }
                            { //NIN
                                foreach (Combatant c in partyTemp)
                                {
                                    if (c.Job == 0x1E)
                                    {
                                        partyTempSorted.Add(c);
                                    }
                                }
                            }
                            { //BRD
                                foreach (Combatant c in partyTemp)
                                {
                                    if (c.Job == 0x17)
                                    {
                                        partyTempSorted.Add(c);
                                    }
                                }
                            }
                            { //BLM
                                foreach (Combatant c in partyTemp)
                                {
                                    if (c.Job == 0x19)
                                    {
                                        partyTempSorted.Add(c);
                                    }
                                }

                            }
                            { //SMN
                                foreach (Combatant c in partyTemp)
                                {
                                    if (c.Job == 0x1B)
                                    {
                                        partyTempSorted.Add(c);
                                    }
                                }
                            }
                            { //MCH
                                foreach (Combatant c in partyTemp)
                                {
                                    if (c.Job == 0x1F)
                                    {
                                        partyTempSorted.Add(c);
                                    }
                                }
                            }
                        }
                        if (partyTemp[0].Job == 0x1C || partyTemp[0].Job == 0x1B && partyTempSorted.Count > 0)
                        {
                            foreach (Combatant combatant in combatantList) //Add user's pet
                            {
                                if (combatant.OwnerID == partyTempSorted[0].ID && (combatant.Name == "Eos" || combatant.Name == "Selene" || combatant.Name == "Garuda-Egi" || combatant.Name == "Ifrit-Egi" || combatant.Name == "Titan-Egi"))
                                {
                                    combatant.Job = 100;
                                    partyTempSorted.Add(combatant);

                                    break;
                                }
                            }
                        }

                        PartyMemberInfo = partyTempSorted;
                        FocusInfo = enemyTemp;
                    }
                    new System.Threading.ManualResetEvent(false).WaitOne(50);
                }

            }
        }
 internal static SynchronizedCollection<Event> DbReadSubEvents(this Event eventOwner)
 {
     if (Connect())
     {
         var EventList = new SynchronizedCollection<Event>();
         MySqlCommand cmd;
         if (eventOwner != null)
         {
             cmd = new MySqlCommand("SELECT * FROM RundownEvent where idEventBinding = @idEventBinding and typStart=@StartType;", connection);
             cmd.Parameters.AddWithValue("@idEventBinding", eventOwner.IdRundownEvent);
             if (eventOwner.EventType == TEventType.Container)
                 cmd.Parameters.AddWithValue("@StartType", TStartType.Manual);
             else
                 cmd.Parameters.AddWithValue("@StartType", TStartType.With);
             Event NewEvent;
             lock (connection)
             {
                 using (MySqlDataReader dataReader = cmd.ExecuteReader())
                 {
                     try
                     {
                         while (dataReader.Read())
                         {
                             NewEvent = _EventRead(eventOwner.Engine, dataReader);
                             NewEvent._parent = eventOwner;
                             EventList.Add(NewEvent);
                         }
                     }
                     finally
                     {
                         dataReader.Close();
                     }
                 }
             }
         }
         return EventList;
     }
     else
         return null;
 }