public void AddLine(string msg)
        {
            msg = msg.Replace("\n", "");

            Log.Add($"[{DateTime.Now.ToShortTimeString()}] {msg}");
            LogList.GetChild <ScrollViewer>().ScrollToBottom();
        }
 private void AddSortedDragons()
 {
     _npcList.Add(_holdedDragons.First(x => x.TemplateId == 1102));
     _npcList.Add(_holdedDragons.First(x => x.TemplateId == 1100));
     _npcList.Add(_holdedDragons.First(x => x.TemplateId == 1101));
     _npcList.Add(_holdedDragons.First(x => x.TemplateId == 1103));
     _holdedDragons.Clear();
 }
        //from method event callback
        private void StartSearch()
        {
            ClearNames();

            //local renderer setup
            RendererDeviceNames.Add("Local Renderer");
            _rendererDevices.Add(new LocalRenderer());
            SetUpPlayerRenderer();

            _discovery.StartScan();
        }
示例#4
0
 public void AddNotification(NotifyFlashMessage flash)
 {
     if (flash == null)
     {
         return;
     }
     if (flash.Balloon != null && flash.Balloon.DisplayTime >= 500)
     {
         var existing = notificationBalloons.ToSyncArray().FirstOrDefault(x => x.TitleText == flash.Balloon.TitleText && x.Icon == flash.Balloon.Icon);
         if (existing == null)
         {
             if (!SnappedToBottom)
             {
                 notificationBalloons.Add(flash.Balloon);
             }
             else
             {
                 notificationBalloons.Insert(0, flash.Balloon);
             }
         }
         else
         {
             if (flash.Balloon.EventType == EventType.Whisper)
             {
                 if (!SnappedToBottom)
                 {
                     notificationBalloons.Add(flash.Balloon);
                 }
                 else
                 {
                     notificationBalloons.Insert(0, flash.Balloon);
                 }
             }
             else
             {
                 existing.UpdateBody(flash.Balloon.BodyText);
                 existing.Refresh();
             }
         }
         Topmost = false;
         Topmost = true;
         if (!IsVisible)
         {
             ShowWindow();
         }
     }
     if (!BasicTeraData.Instance.WindowData.MuteSound && flash.Sound != null)
     {
         Task.Run(() => flash.Sound.Play());
     }
 }
示例#5
0
        private SynchronizedObservableCollection <AaronCarPartAttribute> PrepareAttributes(DBCarPart dbCarPart)
        {
            SynchronizedObservableCollection <AaronCarPartAttribute> attributes = new SynchronizedObservableCollection <AaronCarPartAttribute>();
            AttributeOffsetTable attributeOffsetTable = _attributeOffsetTables[dbCarPart.AttributeTableOffset];

            foreach (var offset in attributeOffsetTable.Offsets)
            {
                var rawAttribute = _attributes[offset];
                AaronCarPartAttribute newAttribute = this.ConvertAttribute(rawAttribute);
                //AaronCarPartAttribute newAttribute = new AaronCarPartAttribute();
                //newAttribute.Name = HashResolver.Resolve(rawAttribute.NameHash);
                //newAttribute.Value = rawAttribute.iParam;


                //switch (newAttribute.Hash)
                //{
                //    case 0xB1027477:
                //    case 0x46B79643:
                //    case 0xFD35FE70:
                //    case 0x7D65A926:
                //        this.LoadSingleAttribString(newAttribute, rawAttribute);
                //        break;
                //    case 0xFE613B98:
                //        this.LoadDoubleAttribString(newAttribute, rawAttribute);
                //        break;
                //}

                attributes.Add(newAttribute);
            }

            return(attributes);
        }
 private void AddMediaServer(UPnPDevice pDevice)
 {
     MediaServerNames.Add(pDevice.FriendlyName);
     _serverDevices.Add(new OpenMediaServer(pDevice));
     SetUpPlayerServer();
     MediaServerSelectedIndex = 0;
 }
示例#7
0
        public AppWnd_VM(INavigationService NavigationService_)
        {

            LongTasks = new SynchronizedObservableCollection<ProgressBar_Model>();

            if (!IsInDesignMode)
            {
                NavigationService = NavigationService_;
            
                NavigationService.SetAppWndVM(this);
                NavigationService.NavigateForward(Form.Login);

                NavigationBack = new RelayCommand(NavigateBack_cmd);

                ViewModelLocator.Instance.MainMetroWindow.Closed += MainMetroWindow_Closed;

                CommandDispatcher = new RelayCommand<string>(CmdDispatcher);
            }

            if (IsInDesignMode)
            {
                LongTasks.Add(new ProgressBar_Model() { Text = "A very long task",IsIndeterminate=true});    
            }
            
        }
示例#8
0
 public void AddCarPartCollection(AaronCarPartCollection collection)
 {
     if (_carPartCollections.Contains(collection))
     {
         throw new ArgumentException("Attempted to add a duplicate car part collection");
     }
     _carPartCollections.Add(collection);
 }
        public Download_ViewModel(
            INavigationService NavigationService_,
            IDialogService DialogService_,
            AppSetting AppSetting_,
            IStore Store_,
            ILocalization Loc_,
            ILogger logger_) : base()
        {

            if (!IsInDesignMode)
            {
                NavigationService = NavigationService_;
                DialogService = DialogService_;
                AppSettings = AppSetting_;
                Store = Store_;
                Tx = Loc_;
                logger = logger_;

                CommandDispatcher = new MvxCommand<string>(CmdDispatcher);
                Command_DownloadStoreItem = new MvxCommand<StoreItemExt>((x)=>CmdDispatcher_StoreItem(x,"Download"));
            }
            
            StoreItems = new SynchronizedObservableCollection<StoreItemExt>();
            
            if (IsInDesignMode)
            {

                StoreItemExt item;

                item = new StoreItemExt { Name = "South Park" };
                item.DownloadButton.State1 = true;
                StoreItems.Add(item);

                item = new StoreItemExt { Name = "Chuggington" };
                item.DownloadButton.State2 = true;
                StoreItems.Add(item);

                item = new StoreItemExt { Name = "Futurama" };
                item.DownloadButton.State3 = true;
                StoreItems.Add(item);

            }
            

        }
 public void DeviceAdded_EventHandler(UPnPSmartControlPoint cp, UPnPDevice pDevice)
 {
     //Add to full device list
     _upnpDevices.Add(pDevice);
     UPnpDeviceNames.Add(pDevice.FriendlyName);
     //Add to MediaServer or MediaRenderer list
     AddRenderers(pDevice);
     AddMediaServers(pDevice);
 }
示例#11
0
        public void AddCar(AaronCarRecord aaronCarRecord)
        {
            if (_carRecords.Contains(aaronCarRecord))
            {
                throw new ArgumentException("Attempted to add a car record that is already known", nameof(aaronCarRecord));
            }

            _carRecords.Add(aaronCarRecord);
        }
示例#12
0
 public GroupAbnormalityVM(Abnormality ab)
 {
     _dispatcher = Dispatcher.CurrentDispatcher;
     Abnormality = ab;
     Classes     = new SynchronizedObservableCollection <ClassToggle>(_dispatcher);
     for (int i = 0; i < 13; i++)
     {
         var ct = new ClassToggle((Class)i, ab.Id);
         if (SettingsManager.GroupAbnormals.ContainsKey(ct.Class))
         {
             ct.Selected = SettingsManager.GroupAbnormals[ct.Class].Contains(ab.Id);
         }
         Classes.Add(ct);
     }
     Classes.Add(new ClassToggle(Class.Common, ab.Id)
     {
         Selected = SettingsManager.GroupAbnormals[Class.Common].Contains(ab.Id)
     });
 }
 public GroupAbnormalityVM(Abnormality ab)
 {
     Dispatcher  = Dispatcher.CurrentDispatcher;
     Abnormality = ab;
     Classes     = new SynchronizedObservableCollection <ClassToggle>(Dispatcher);
     for (var i = 0; i < 13; i++)
     {
         var ct = new ClassToggle((Class)i, ab.Id);
         if (SettingsHolder.GroupAbnormals.TryGetValue(ct.Class, out var list))
         {
             ct.Selected = list.Contains(ab.Id);
         }
         Classes.Add(ct);
     }
     Classes.Add(new ClassToggle(Class.Common, ab.Id)
     {
         Selected = SettingsHolder.GroupAbnormals[Class.Common].Contains(ab.Id)
     });
 }
示例#14
0
        private void FindAndUpdate(SynchronizedObservableCollection <SkillCooldown> list, SkillCooldown sk)
        {
            var existing = list.ToSyncArray().FirstOrDefault(x => x.Skill.IconName == sk.Skill.IconName);

            if (existing == null)
            {
                list.Add(sk);
                return;
            }
            existing.Refresh(sk.Cooldown);
        }
        private async void AddToFavourites(object param)
        {
            if (m_selectedResult == null)
            {
                return;
            }

            if (m_selectedResult.State == PartDatasheetState.Saved)
            {
                if (Global.MessageBox(this, Global.GetStringResource("StringDoYouWantToRemoveFromFavourites"), MessageBoxExPredefinedButtons.YesNo) != MessageBoxExButton.Yes)
                {
                    return;
                }
                m_selectedResult.RemovePdf();
                m_savedParts.Remove(m_selectedResult);
                if (IsFavouritesMode)
                {
                    m_searchResults.Remove(m_selectedResult);
                    Global.SaveSavedParts();
                }
                return;
            }

            try
            {
                ActionsCount++;
                PartViewModel part = m_selectedResult;
                await part.SavePdf();

                m_savedParts.Add(part);
                Global.SaveSavedParts();
            }
            catch
            {
                Global.MessageBox(this, Global.GetStringResource("StringDownloadError"), MessageBoxExPredefinedButtons.Ok);
            }
            finally
            {
                ActionsCount--;
            }
        }
示例#16
0
            public void It_invokes_PropertyChanged()
            {
                var collection = new SynchronizedObservableCollection <string>();
                var propertyChangedEventArgs = new List <PropertyChangedEventArgs>();

                ((INotifyPropertyChanged)collection).PropertyChanged += (sender, args) => { propertyChangedEventArgs.Add(args); };
                collection.Add("4");

                Assert.That(propertyChangedEventArgs.Count, Is.EqualTo(2));
                Assert.That(propertyChangedEventArgs.Any(p => p.PropertyName.Equals("Count")), Is.True);
                Assert.That(propertyChangedEventArgs.Any(p => p.PropertyName.Equals("Item[]")), Is.True);
            }
        public static void UpdateLanguageServiceCollection()
        {
            LangServCollection_ = new SynchronizedObservableCollection<LanguageService>();
            List<LanguageService> servs= EFDbConnect.Main.Table<LanguageService>().ToList();
            foreach(LanguageService serv in servs)
            {
                LanguageService ls = (LanguageService)serv.Clone(Type.GetType("OpenLearningPlayer.Shared.API.LanguageServices." + serv.Discriminator));
                //LanguageService ls = (LanguageService)Activator.CreateInstance(Type.GetType("OpenLearningPlayer.Shared.Domain."+serv.Discriminator));
                LangServCollection_.Add(ls);

                ls.Languages = new SynchronizedObservableCollection<LanguageService.LanguageOfService>(EFDbConnect.Main.Table<LanguageService.LanguageOfService>().Where(x => x.LanguageService_id == serv.id).ToList());
            }
        }
示例#18
0
            public void It_invokes_CollectionChanged()
            {
                var collection = new SynchronizedObservableCollection <string>(new List <string> {
                    "1", "2", "3"
                });
                NotifyCollectionChangedEventArgs collectionChangedEventArgs = null;

                collection.CollectionChanged += (sender, args) => { collectionChangedEventArgs = args; };
                collection.Add("4");

                Assert.That(collectionChangedEventArgs.Action, Is.EqualTo(NotifyCollectionChangedAction.Add));
                Assert.That(collectionChangedEventArgs.NewItems[0], Is.EqualTo("4"));
                Assert.That(collectionChangedEventArgs.NewStartingIndex, Is.EqualTo(3));
            }
示例#19
0
        public GroupConfigVM()
        {
            _dispatcher    = Dispatcher.CurrentDispatcher;
            GroupAbnormals = new SynchronizedObservableCollection <GroupAbnormalityVM>(_dispatcher);
            foreach (var abnormality in Abnormalities)
            {
                var abVM = new GroupAbnormalityVM(abnormality);

                GroupAbnormals.Add(abVM);
            }
            AbnormalitiesView = new CollectionViewSource {
                Source = GroupAbnormals
            }.View;
            AbnormalitiesView.CurrentChanged += OnAbnormalitiesViewOnCurrentChanged;
            AbnormalitiesView.Filter          = null;
        }
示例#20
0
            public void It_does_not_throw_exception_if_collection_is_modified()
            {
                var count      = 0;
                var collection = new SynchronizedObservableCollection <string>(new List <string> {
                    "1", "2", "3"
                });

                // ReSharper disable once UnusedVariable
                foreach (var item in (IEnumerable)collection)
                {
                    collection.Add($"{count + 4}");
                    count++;
                }

                Assert.That(count, Is.EqualTo(3));
                Assert.That(collection.Count, Is.EqualTo(6));
            }
示例#21
0
        public SystemMessagesConfigWindow()
        {
            InitializeComponent();
            DataContext     = this;
            _hiddenMessages = new SynchronizedObservableCollection <SystemMessageViewModel>();
            _showedMessages = new SynchronizedObservableCollection <SystemMessageViewModel>();

            SettingsHolder.UserExcludedSysMsg.ForEach(opc =>
            {
                _hiddenMessages.Add(new SystemMessageViewModel(opc, SessionManager.DB.SystemMessagesDatabase.Messages[opc]));
            });
            SessionManager.DB.SystemMessagesDatabase.Messages.ToList().ForEach(keyVal =>
            {
                if (SettingsHolder.UserExcludedSysMsg.Contains(keyVal.Key))
                {
                    return;
                }
                _showedMessages.Add(new SystemMessageViewModel(keyVal.Key, keyVal.Value));
            });

            _hiddenMessages.CollectionChanged += (_, args) =>
            {
                switch (args.Action)
                {
                case System.Collections.Specialized.NotifyCollectionChangedAction.Add:
                    foreach (var item in args.NewItems)
                    {
                        SettingsHolder.UserExcludedSysMsg.Add((item as SystemMessageViewModel)?.Opcode);
                    }
                    break;

                case System.Collections.Specialized.NotifyCollectionChangedAction.Remove:
                    foreach (var item in args.OldItems)
                    {
                        SettingsHolder.UserExcludedSysMsg.Remove((item as SystemMessageViewModel)?.Opcode);
                    }
                    break;
                }
                SettingsWriter.Save();
            };

            ShowedMessagesView = CollectionViewUtils.InitLiveView(null, ShowedMessages, new string[] { }, new SortDescription[] { });
            HiddenMessagesView = CollectionViewUtils.InitLiveView(null, HiddenMessages, new string[] { }, new SortDescription[] { });
            ((ICollectionView)ShowedMessagesView).CollectionChanged += GcPls;
            ((ICollectionView)HiddenMessagesView).CollectionChanged += GcPls;
        }
示例#22
0
        /// <summary>
        /// Method for refreshing local Companies cache.
        /// </summary>
        public void RefreshCache(string orderByField = null)
        {
            _orderByField = orderByField;

            Context.Refresh(RefreshMode.StoreWins, Context.Companies);

            if (_companiesCache == null)
            {
                _companiesCache = new SynchronizedObservableCollection <Company>(new ObservableCollection <Company>());
            }

            _companiesCache.Clear();

            foreach (Company company in orderCompaniesByField(orderByField))
            {
                _companiesCache.Add(company);
            }
        }
示例#23
0
 public void enumeratorTestInternalEntry()
 {
     //test object
     SynchronizedObservableCollection<int> testCol = new SynchronizedObservableCollection<int>();
     //the items to add
     var r = (Enumerable.Range(0, 100));
     var z = (Enumerable.Range(100, 100));
     //add a range of numbers (0-4) to increment on
     foreach (int i in r)
     {
         testCol.Add(i);
     }
     //the list that will contain the enumerated items.
     List<int> k = new List<int>();
     Thread s = new Thread(new ThreadStart(() =>
     {
         //for-each item in the test wait a bit so the adder
         //thread has a chance to add more items then add to the
         //counter of how many items the enumerator got.
         foreach (int i in testCol)
         {
             Thread.Sleep(10);
             k.Add(i);
         }
     }));
     s.Start();
     //add more numbers during the execution of the other thread. adds
     //(5-14) at a random location.
     Random rnd = new Random();
     foreach (int i in z)
     {
         testCol.Insert(rnd.Next(0, testCol.Count-1),i);
     }
     s.Join();
     //assert that there are no duplicate items. (that the enumerator did
     //not back over something already enumerated) all items in testCol
     //are distinct in this test.
     Assert.AreEqual(k.Distinct().Count(), k.Count());
     //assert that the enumerator is not adding any items.
     Assert.IsTrue(k.Count() <= testCol.Count);
 }
        private static bool FindAndUpdate(SynchronizedObservableCollection <Cooldown> list, Cooldown sk)
        {
            var existing = list.ToSyncList().FirstOrDefault(x => x.Skill.IconName == sk.Skill.IconName);

            if (existing == null)
            {
                list.Add(sk);
                return(true);
            }

            if (existing.Mode == CooldownMode.Pre && sk.Mode == CooldownMode.Normal)
            {
                existing.Start(sk);
                return(true);
            }
            else
            {
                existing.Refresh(sk.Skill.Id, sk.Duration, sk.Mode);
                return(true);
            }
        }
示例#25
0
 public void getEnumeratorTest()
 {
     //test object
     SynchronizedObservableCollection<int> testCol = new SynchronizedObservableCollection<int>();
     var r = (Enumerable.Range(0, 5));
     var z = (Enumerable.Range(5, 10));
     //add a range of numbers (0-4) to increment on
     foreach (int i in r)
     {
         testCol.Add(i);
     }
     //the counter to use to make sure the thread is getting updates to
     //the enumerator while it is computing.
     int k = 0;
     Thread s = new Thread(new ThreadStart(() =>
             {
                 //for-each item in the test wait a bit so the adder
                 //thread has a chance to add more items then add to the
                 //counter of how many items the enumerator got.
                 foreach (int i in testCol)
                 {
                     Thread.Sleep(10);
                     k++;
                 }
             }));
     s.Start();
     //add more numbers during the execution of the other thread. adds
     //(5-14)
     foreach (int i in z)
     {
         testCol.Add(i);
     }
     s.Join();
     //assert that the number of items counted by the enumerator is equal
     //to that of the final count.
     Assert.Equals(k, testCol.Count);
 }
        public void Read(SynchronizedObservableCollection <Character> dest)
        {
            if (File.Exists(_path))
            {
                _doc = XDocument.Load(_path);
            }
            if (_doc == null)
            {
                return;
            }

            ParseEliteStatus();

            _doc.Descendants().Where(x => x.Name == CharacterTag).ToList().ForEach(xChar =>
            {
                var ch = new Character();
                ParseGeneralCharInfo(xChar, ch);
                ParseDungeonCharInfo(xChar, ch);
                ParseGearCharInfo(xChar, ch);
                ParseBuffsInfo(xChar, ch);
                ParseInventoryInfo(xChar, ch);
                dest.Add(ch);
            });
        }
示例#27
0
        public async Task<SynchronizedObservableCollection<StoreItemExt>> GetStoreItems(int from =0,int quantity = 0)
        {

            SynchronizedObservableCollection<StoreItemExt> itemsext = new SynchronizedObservableCollection<StoreItemExt>();
            List<StoreItem> items = await WebAPI_LearningItems.GetCollection(from,quantity);
            foreach (StoreItem item in items)
            {
                StoreItemExt itemext = item.Clone<StoreItem,StoreItemExt>();
                itemext.LearningItem =  EFDbContext.Context.Find<LearningItem>(new UUID(itemext.id));
                itemext.isInstalled = itemext.LearningItem != null;
                itemext.CoverFileFullPath = UriHelper.Combine(new string[] { StaticProperties.StoreAddress,"App_Data",itemext.id.ToString(),itemext.CoverFile});

                itemext.UpdateDownloadButtonStatus();

                itemsext.Add(itemext);
            }
            return itemsext;
        }
        public AppWnd_ViewModel()
        {

            LongTasks = new SynchronizedObservableCollection<ProgressBar_Model>();

            if (!IsInDesignMode)
            {
                WindowTitle = Tx.T("AppWnd.ApplicationHeader") + " " + Assembly.GetExecutingAssembly().GetName().Version;
            }

            if (IsInDesignMode)
            {
                LongTasks.Add(new ProgressBar_Model() {
                    Text = "A very long task",
                    IsIndeterminate =true,
                    Title="This is a title"});
                WindowTitle = "Open learning player 1.1.1.2";   
            }
        }
示例#29
0
 public void Add(IWuEndpoint item) => _endpoints.Add(item);
示例#30
0
        public static void ToTeraDpsApi(ExportType exportType, DamageTracker damageTracker, TeraData teraData)
        {
            if (exportType == ExportType.None)
            {
                return;
            }

            //if we want to upload, primary target must be dead
            if (exportType.HasFlag(ExportType.Upload) && !damageTracker.IsPrimaryTargetDead)
            {
                return;
            }

            var exportToExcel = (exportType & (ExportType.Excel | ExportType.ExcelTemp)) != 0;
            //if we're not exporting to excel and credentials aren't fully entered, return
            //if (!exportToExcel
            //    && (string.IsNullOrEmpty(SettingsHelper.Instance.Settings.TeraDpsToken)
            //        || string.IsNullOrEmpty(SettingsHelper.Instance.Settings.TeraDpsUser)))
            //    return;

            //ignore if not a boss
            var entity = damageTracker.PrimaryTarget;

            if (!(entity?.Info.Boss ?? false))
            {
                return;
            }

            var abnormals = damageTracker.Abnormals;

            bool timedEncounter = false;

            //Nightmare desolarus
            if (entity.Info.HuntingZoneId == 759 && entity.Info.TemplateId == 1003)
            {
                timedEncounter = true;
            }

            var firstHit  = damageTracker.StatsByUser.SelectMany(x => x.SkillLog).Where(x => x.Target == entity).Min(x => x.Time as DateTime?) ?? new DateTime(0);
            var lastHit   = damageTracker.StatsByUser.SelectMany(x => x.SkillLog).Where(x => x.Target == entity).Max(x => x.Time as DateTime?) ?? new DateTime(0);
            var firstTick = firstHit.Ticks;
            var lastTick  = lastHit.Ticks;
            var interval  = lastTick - firstTick;
            var seconds   = interval / TimeSpan.TicksPerSecond;

            if (seconds == 0)
            {
                return;
            }
            long totaldamage;

            if (timedEncounter)
            {
                totaldamage =
                    damageTracker.StatsByUser.SelectMany(x => x.SkillLog)
                    .Where(x => x.Time >= firstHit && x.Time <= lastHit)
                    .Sum(x => (long)x.Damage);
            }
            else
            {
                totaldamage =
                    damageTracker.StatsByUser.SelectMany(x => x.SkillLog)
                    .Where(x => x.Target == entity)
                    .Sum(x => (long)x.Damage);
            }

            var partyDps    = TimeSpan.TicksPerSecond * totaldamage / interval;
            var teradpsData = new EncounterBase
            {
                encounterUnixEpoch = DateTimeTools.DateTimeToUnixTimestamp(damageTracker.LastAttack?.ToUniversalTime() ?? DateTime.UtcNow),
                areaId             = entity.Info.HuntingZoneId + "",
                bossId             = entity.Info.TemplateId + "",
                fightDuration      = seconds + "",
                partyDps           = partyDps + ""
            };

            foreach (var debuff in abnormals.Get(entity).OrderByDescending(x => x.Value.Duration(firstTick, lastTick)))
            {
                long percentage = debuff.Value.Duration(firstTick, lastTick) * 100 / interval;
                if (percentage == 0)
                {
                    continue;
                }
                teradpsData.debuffUptime.Add(new KeyValuePair <string, string>(
                                                 debuff.Key.Id + "", percentage + ""
                                                 ));
            }

            foreach (var user in damageTracker.StatsByUser.OrderByDescending(x => x.Dealt.Damage))
            {
                var filteredSkillog = timedEncounter
                    ? user.SkillLog.Where(x => x.Time >= firstHit && x.Time <= lastHit).ToList()
                    : user.SkillLog.Where(x => x.Target == entity).ToList();

                long damage = filteredSkillog.Sum(x => x.Damage);
                if (damage <= 0)
                {
                    continue;
                }

                var teradpsUser = new Members();

                teradpsUser.playerTotalDamage = damage + "";
                var buffs = abnormals.Get(user.Player);
                teradpsUser.playerClass           = user.Class.ToString();
                teradpsUser.playerName            = user.Name;
                teradpsUser.playerServer          = SettingsHelper.Instance.BasicTeraData.Servers.GetServerName(user.Player.ServerId);
                teradpsUser.playerAverageCritRate = Math.Round(100 * (double)filteredSkillog.Count(x => x.IsCritical && x.Damage > 0) / filteredSkillog.Count(x => x.Damage > 0)) + "";
                teradpsUser.healCrit  = user.Player.IsHealer ? Math.Round(100 * (double)filteredSkillog.Count(x => x.IsCritical && x.Heal > 0) / filteredSkillog.Count(x => x.Heal > 0)) + "" : null;
                teradpsUser.playerDps = TimeSpan.TicksPerSecond * damage / interval + "";
                teradpsUser.playerTotalDamagePercentage = damage * 100 / totaldamage + "";

                var death = buffs.Death;
                teradpsUser.playerDeaths        = death.Count(firstTick, lastTick) + "";
                teradpsUser.playerDeathDuration = death.Duration(firstTick, lastTick) / TimeSpan.TicksPerSecond + "";

                var aggro = buffs.Aggro(entity);
                teradpsUser.aggro = 100 * aggro.Duration(firstTick, lastTick) / interval + "";

                foreach (var buff in buffs.Times.OrderByDescending(x => x.Value.Duration(firstTick, lastTick)))
                {
                    long percentage = (buff.Value.Duration(firstTick, lastTick) * 100 / interval);
                    if (percentage == 0)
                    {
                        continue;
                    }
                    teradpsUser.buffUptime.Add(new KeyValuePair <string, string>(
                                                   buff.Key.Id + "", percentage + ""
                                                   ));
                }

                var aggregated = new List <AggregatedSkillResult>();
                var collection = new SynchronizedObservableCollection <SkillResult>();
                foreach (var skill in filteredSkillog)
                {
                    collection.Add(skill);
                    if (aggregated.All(asr => !skill.IsSameSkillAs(asr)))
                    {
                        aggregated.Add(new AggregatedSkillResult(skill.SkillShortName, skill.IsHeal,
                                                                 AggregationType.Name, collection));
                    }
                }
                foreach (var skill in aggregated.OrderByDescending(x => x.Damage))
                {
                    var skillLog    = new SkillLog();
                    var skilldamage = skill.Damage;
                    if (skilldamage == 0)
                    {
                        continue;
                    }

                    skillLog.skillAverageCrit   = skill.AverageCrit + "";
                    skillLog.skillAverageWhite  = skill.AverageWhite + "";
                    skillLog.skillCritRate      = Math.Round(skill.CritRate * 100) + "";
                    skillLog.skillDamagePercent = Math.Round(skill.DamagePercent * 100) + "";
                    skillLog.skillHighestCrit   = skill.HighestCrit + "";
                    skillLog.skillHits          = skill.Hits + "";
                    skillLog.skillId            = teraData.SkillDatabase.GetSkillByPetName(skill.NpcInfo?.Name, user.Player.RaceGenderClass)?.Id.ToString() ?? skill.SkillId.ToString();
                    skillLog.skillLowestCrit    = skill.LowestCrit + "";
                    skillLog.skillTotalDamage   = skilldamage + "";

                    teradpsUser.skillLog.Add(skillLog);
                }
                teradpsData.members.Add(teradpsUser);
            }

            //export to excel if specified
            if (exportToExcel)
            {
                Task.Run(() => ExcelExport.ExcelSave(exportType, teradpsData, teraData));
            }

            //return if we don't need to upload
            if (!exportType.HasFlag(ExportType.Upload))
            {
                return;
            }

            /*
             * Validation, without that, the server cpu will be burning \o
             */
            var areaId = int.Parse(teradpsData.areaId);

            if (
                //areaId != 886 &&
                //areaId != 467 &&
                //areaId != 767 &&
                //areaId != 768 &&
                //areaId != 468 &&
                areaId != 770 &&
                areaId != 769 &&
                areaId != 916 &&
                areaId != 969 &&
                areaId != 970 &&
                areaId != 950
                )
            {
                return;
            }

            try
            {
                using (var client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(40);
                    var response = client.GetAsync("http://moongourd.com/shared/servertime");
                    var timediff = (response.Result.Headers.Date.Value.UtcDateTime.Ticks - DateTime.UtcNow.Ticks) / TimeSpan.TicksPerSecond;
                    teradpsData.encounterUnixEpoch += timediff;
                }
            }
            catch (Exception)
            {
                Debug.WriteLine("Get server time error");
                return;
            }
            var json = JsonConvert.SerializeObject(teradpsData, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });

            Task.Run(() => Send(entity, json, 3));
        }
示例#31
0
        //public ConcurrentDictionary<string, ServerListing> Servers
        //{
        //    get { return servers; }
        //} private ConcurrentDictionary<string, ServerListing> servers = new ConcurrentDictionary<string, ServerListing>();

        #endregion

        public void Query(string[] metaservers = null)
        {
            l.Info("[META] Querying metaservers.");

            if (metaservers == null)
            {
                metaservers = DefaultMetaservers;
            }

            foreach (var metaserver in DefaultMetaservers)
            {
                IPHostEntry host = Dns.GetHostEntry(metaserver);

                if (host == null)
                {
                    l.Error("Host DNS lookup failed for metaserver: " + metaserver);
                    continue;
                }

                Socket socket = null;

                try
                {
                    try
                    {
                        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP);
                        socket.Connect(host.AddressList, NetConstants.MetaserverPort);
                    }
                    catch (Exception ex)
                    {
                        l.Warn("Failed to connect to: " + host.HostName + ".  Exception: " + ex.ToString());
                        continue;
                    }

                    if (!socket.Connected)
                    {
                        socket.Dispose();
                        continue;
                    }

                    byte[] sendBytes = ASCIIEncoding.ASCII.GetBytes("?version=_");

                    try
                    {
                        socket.Send(sendBytes);
                    }
                    catch (Exception ex)
                    {
                        l.Warn("Error sending to metaserver '" + metaserver + "': " + ex.ToString());
                        continue;
                    }

                    int packetsReceived = 0;

receive:
                    if (packetsReceived > 1)
                    {
                        l.Trace("packetsReceived > 1");
                    }

                    byte[] recvBuffer = new byte[8192];
                    int    bytesRead  = 0;
                    try
                    {
                        if (packetsReceived == 0 || socket.Poll(250, SelectMode.SelectRead))
                        {
                            socket.ReceiveTimeout = 5000; // HARDTIME TIMEOUT
                            bytesRead             = socket.Receive(recvBuffer);
                        }
                    }
                    catch (Exception ex)
                    {
                        l.Warn("Error receiving from metaserver: " + ex.ToString());
                        continue;
                    }

                    if (bytesRead == 0)
                    {
                        if (packetsReceived == 0)
                        {
                            l.Warn("Received nothing from metaserver'" + metaserver + "'");
                        }
                        continue;
                    }

                    packetsReceived++;

                    string result = ASCIIEncoding.ASCII.GetString(recvBuffer);

                    string[] lines = result.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

                    int    lineCount    = 0;
                    string protocolType = null;
                    string protocolUnknown2;
                    foreach (var line in lines)
                    {
                        if (line.StartsWith(((char)0).ToString()))
                        {
                            break;
                        }

                        string[] cells = line.Split(',');

                        if (lineCount++ == 0)
                        {
                            protocolType = cells[0];
                            if (protocolType.Equals("r"))
                            {
                                protocolUnknown2 = cells[1];
                            }
                            continue;
                        }

                        ServerListing listing = null;
                        if (protocolType.Equals("r"))
                        {
                            listing         = new ServerListing(cells[0]);
                            listing.Source  = protocolType;
                            listing.Port    = Convert.ToInt32(cells[1]);
                            listing.Status  = cells[2];
                            listing.Age     = Convert.ToInt32(cells[3]);
                            listing.Players = Convert.ToInt32(cells[4]);
                            listing.Queue   = Convert.ToInt32(cells[5]);
                            listing.Type    = cells[6];
                            listing.Comment = String.Empty;
                        }
                        else if (protocolType.Equals("s"))
                        {
                            listing         = new ServerListing(cells[0]);
                            listing.Source  = protocolType;
                            listing.Type    = cells[1];
                            listing.Comment = cells[2];
                            listing.Port    = Convert.ToInt32(cells[4]);
                            listing.Players = Convert.ToInt32(cells[5]);
                            listing.Queue   = Convert.ToInt32(cells[6].Trim());
                            listing.Status  = "2"; // TODO  REVIEW
                            if (listing.Type.Equals("unknown"))
                            {
                                listing.Status = "3";                                 // TODO  REVIEW
                            }
                            listing.Age = 0;
                        }
                        else
                        {
                            l.Warn("Unknown metaserver protocol: " + protocolType);
                        }

                        if (listing != null && listing.IsSupported)
                        {
                            l.Debug("[meta] " + listing.ToString());
                            if (ServerListings.Contains(listing))
                            {
                                ServerListings.Remove(listing);
                            }
                            ServerListings.Add(listing);
                            servers.Set(listing.Key, listing);
                        }
                    }
                    goto receive;
                }
                finally
                {
                    try
                    {
                        if (socket != null)
                        {
                            socket.Dispose();
                            socket = null;
                        }
                    }
                    catch (Exception ex) { l.Trace(ex.ToString()); }
                }
            }
        }