示例#1
0
        public async Task <OverallStats> SetStats(FlightLog flightLog)
        {
            long   ticks      = flightLog.FlightLogAnalyse.FlightTime.Ticks;
            double sec        = TimeSpan.FromTicks(ticks).TotalSeconds;
            float? kilometers = flightLog.FlightLogAnalyse.Kilometers;
            byte   flightno   = 1;

            OverallStats stats = await _db.Stats.Where(f => f.Id == 1).FirstOrDefaultAsync();

            if (stats == null)
            {
                _db.Stats.Add(new OverallStats()
                {
                    TimeInSeconds = sec, Kilometers = kilometers, FlightsNo = flightno
                });
            }
            else
            {
                stats.TimeInSeconds += sec;
                stats.Kilometers    += kilometers;
                stats.FlightsNo     += flightno;
            }

            return(stats);
        }
        protected void Page_LoadComplete(object sender, EventArgs e)
        {
            if (Session["UserBasicStatsPlayer"] != null)
            {
                BindGoalsStats();
                BindPartnersStats();
                BindRivalsStats();
                BindPlayerRatingStats();
                BindPlayerRatingChart();
                BindPlayerRankChart();
                phAllUsersStats.Visible = false;
                phUserStats.Visible     = true;
            }
            else
            {
                List <BestStat> stats = new List <BestStat>();
                if (Cache[DataAccess.OverallStatsCacheName] == null)
                {
                    stats = OverallStats.CalculateBestStats();

                    Cache.Insert(DataAccess.OverallStatsCacheName, stats, null, DateTime.Now.AddSeconds(DataAccess.CacheTimeInSeconds), TimeSpan.Zero);
                }
                else
                {
                    stats = (List <BestStat>)Cache[DataAccess.OverallStatsCacheName];
                }

                repItems.DataSource = stats;
                repItems.DataBind();

                phUserStats.Visible     = false;
                phAllUsersStats.Visible = true;
            }
        }
示例#3
0
        public async Task <ICollection <FlightLog> > DeleteFlightWithUser(string id)
        {
            ICollection <FlightLog> flight = await _db.FlightLogs.Include(f => f.FlightLogAnalyse).Include(f => f.User).Where(fa => fa.UserId == id).ToListAsync();

            ApplicationUser Users = await _db.Pilots.Where(f => f.Id == id).FirstOrDefaultAsync();

            OverallStats stats = await _db.Stats.FindAsync(1);

            if (flight != null)
            {
                foreach (var flightDelete in flight)
                {
                    Users.SumKilometers -= flightDelete.FlightLogAnalyse.Kilometers;
                    long   ticks = flightDelete.FlightLogAnalyse.FlightTime.Ticks;
                    double sec   = TimeSpan.FromTicks(ticks).TotalSeconds;
                    Users.TimeInSec     -= sec;
                    Users.FlightsNo     -= 1;
                    stats.FlightsNo     -= 1;
                    stats.Kilometers    -= flightDelete.FlightLogAnalyse.Kilometers;
                    stats.TimeInSeconds -= sec;
                    if (flightDelete.FlightLogAnalyse.Topflight == true)
                    {
                        Users.TopScore -= flightDelete.FlightLogAnalyse.Score;
                    }

                    _db.FlightLogs.Remove(flightDelete);

                    await _db.SaveChangesAsync();
                }
            }
            return(flight);
        }
        private async Task LoadDatas()
        {
            IsBusy = true;
            NotificationMessage = Properties.Resources.NotificationLoading;
            List <Demo> demos = await _cacheService.GetFilteredDemoListAsync();

            OverallStats datas = await _accountStatsService.GetGeneralAccountStatsAsync(demos);

            MatchCount               = datas.MatchCount;
            KillCount                = datas.KillCount;
            AssistCount              = datas.AssistCount;
            DeathCount               = datas.DeathCount;
            HeadshotCount            = datas.HeadshotCount;
            HeadshotRatio            = datas.HeadshotRatio;
            KnifeKillCount           = datas.KnifeKillCount;
            FiveKillCount            = datas.FiveKillCount;
            FourKillCount            = datas.FourKillCount;
            ThreeKillCount           = datas.ThreeKillCount;
            TwoKillCount             = datas.TwoKillCount;
            EntryKillCount           = datas.EntryKillCount;
            KillDeathRatio           = datas.KillDeathRatio;
            BombDefusedCount         = datas.BombDefusedCount;
            BombExplodedCount        = datas.BombExplodedCount;
            BombPlantedCount         = datas.BombPlantedCount;
            KillPerRoundPercentage   = datas.KillPerRoundPercentage;
            AssistPerRoundPercentage = datas.AssistPerRoundPercentage;
            DeathPerRoundPercentage  = datas.DeathPerRoundPercentage;
            ClutchWinPercentage      = datas.ClutchWinPercentage;
            AverageDamagesPerRound   = datas.AverageDamagesPerRound;
            MvpCount    = datas.MvpCount;
            DamageCount = datas.DamageCount;
            RoundCount  = datas.RoundCount;
            HltvRating  = datas.HltvRating;
            TimeSpan totalTime = TimeSpan.FromSeconds(datas.TotalMatchesDuration);

            TotalMatchTime = string.Format(Properties.Resources.TotalMatchTimeValue, totalTime.Hours, totalTime.Minutes);
            TimeSpan avgTotalTime = TimeSpan.FromSeconds(datas.AverageMatchDuration);

            AverageMatchTime = string.Format(Properties.Resources.AverageMatchTimeValue, avgTotalTime.Minutes);
            DatasMatchStats  = new List <GenericDoubleChart>
            {
                new GenericDoubleChart
                {
                    Label = Properties.Resources.Win,
                    Value = datas.MatchWinCount
                },
                new GenericDoubleChart
                {
                    Label = Properties.Resources.Loss,
                    Value = datas.MatchLossCount
                },
                new GenericDoubleChart
                {
                    Label = Properties.Resources.Draw,
                    Value = datas.MatchDrawCount
                }
            };
            IsBusy = false;
        }
示例#5
0
 public void CopyFrom(OverallStats updated)
 {
     Storage = updated.Storage;
     foreach (var p in typeof(OverallStats).GetProperties().Where(p => p.CanWrite))
     {
         p.SetValue(this, p.GetValue(updated, null), null);
     }
 }
示例#6
0
        private void GetOtherStatistics()
        {
            DashboardViewModel dashboard = new DashboardViewModel();

            dashboard.ViewModelEvent += dashboard_ViewModelEvent;

            OverallStats overall = dashboard.GetOtherStatistics(ConfigurationManager.ConnectionStrings["CPDatabase"].ConnectionString);

            if (overall != null)
            {
                spanUsers.Attributes.Add("data-value", overall.TotalUsers.ToString());
                spanResellers.Attributes.Add("data-value", overall.TotalResellers.ToString());
                spanCompanies.Attributes.Add("data-value", overall.TotalCompanies.ToString());

                spanMailboxes.Attributes.Add("data-value", overall.TotalMailboxes.ToString());
                spanDistributionGroups.Attributes.Add("data-value", overall.TotalDistributionGroups.ToString());
                spanContacts.Attributes.Add("data-value", overall.TotalMailContacts.ToString());

                spanTotalCitrixUsers.Attributes.Add("data-value", overall.TotalCitrixUsers.ToString());
                spanTotalApps.Attributes.Add("data-value", overall.TotalCitrixApps.ToString());
                spanTotalServers.Attributes.Add("data-value", overall.TotalCitrixServers.ToString());

                spanTodayNewCompanies.Attributes.Add("data-value", overall.TodayCompanies.ToString());
                spanTodayNewUsers.Attributes.Add("data-value", overall.TodayUsers.ToString());

                // Set mailbox space allocated
                lbUsedVsAllocatedMailbox.Text = string.Format("{0}{1} / {2}{3}", overall.TotalUsedEmailSpace.ToString("#.##"), overall.TotalUsedEmailSpaceSizeType, overall.TotalAllocatedEmailSpace.ToString("#.##"), overall.TotalAllocatedEmailSpaceSizeType);
                if (overall.TotalUsedEmailSpaceInKB > 0 && overall.TotalAllocatedEmailSpaceInKB > 0)
                {
                    progBarMailboxesUsedVsAllocated.Attributes.Add("data-percentage", string.Format("{0}%", (int)Math.Round((decimal)(100 * overall.TotalUsedEmailSpaceInKB) / overall.TotalAllocatedEmailSpaceInKB)));
                }

                // Set mailbox progress bar
                lbTotalMailboxes.Text = overall.TotalMailboxes.ToString();
                if (overall.TotalMailboxes > 0 && overall.TotalUsers > 0)
                {
                    progBarMailboxes.Attributes.Add("data-percentage", string.Format("{0}%", (int)Math.Round((double)(100 * overall.TotalMailboxes) / overall.TotalUsers)));
                }

                // Set citrix progress bar
                lbTotalCitrixUsers.Text = overall.TotalCitrixUsers.ToString();
                if (overall.TotalCitrixUsers > 0 && overall.TotalUsers > 0)
                {
                    progBarCitrix.Attributes.Add("data-percentage", string.Format("{0}%", (int)Math.Round((double)(100 * overall.TotalCitrixUsers) / overall.TotalUsers)));
                }

                // Set lync progress bar
                lbTotalLyncUsers.Text = overall.TotalLyncUsers.ToString();
                if (overall.TotalLyncUsers > 0 && overall.TotalUsers > 0)
                {
                    progBarLync.Attributes.Add("data-percentage", string.Format("{0}%", (int)Math.Round((double)(100 * overall.TotalLyncUsers) / overall.TotalUsers)));
                }
            }
        }
        private async Task LoadDatas()
        {
            IsBusy = true;
            NotificationMessage = "Loading...";
            List <Demo> demos = await _cacheService.GetFilteredDemoListAsync();

            OverallStats datas = await _accountStatsService.GetGeneralAccountStatsAsync(demos);

            MatchCount               = datas.MatchCount;
            KillCount                = datas.KillCount;
            AssistCount              = datas.AssistCount;
            DeathCount               = datas.DeathCount;
            HeadshotCount            = datas.HeadshotCount;
            HeadshotRatio            = datas.HeadshotRatio;
            KnifeKillCount           = datas.KnifeKillCount;
            FiveKillCount            = datas.FiveKillCount;
            FourKillCount            = datas.FourKillCount;
            ThreeKillCount           = datas.ThreeKillCount;
            TwoKillCount             = datas.TwoKillCount;
            EntryKillCount           = datas.EntryKillCount;
            KillDeathRatio           = datas.KillDeathRatio;
            BombDefusedCount         = datas.BombDefusedCount;
            BombExplodedCount        = datas.BombExplodedCount;
            BombPlantedCount         = datas.BombPlantedCount;
            KillPerRoundPercentage   = datas.KillPerRoundPercentage;
            AssistPerRoundPercentage = datas.AssistPerRoundPercentage;
            DeathPerRoundPercentage  = datas.DeathPerRoundPercentage;
            ClutchWinPercentage      = datas.ClutchWinPercentage;
            AverageDamagesPerRound   = datas.AverageDamagesPerRound;
            MvpCount        = datas.MvpCount;
            DamageCount     = datas.DamageCount;
            RoundCount      = datas.RoundCount;
            HltvRating      = datas.HltvRating;
            DatasMatchStats = new List <GenericDoubleChart>
            {
                new GenericDoubleChart
                {
                    Label = "Win",
                    Value = datas.MatchWinCount
                },
                new GenericDoubleChart
                {
                    Label = "Loss",
                    Value = datas.MatchLossCount
                },
                new GenericDoubleChart
                {
                    Label = "Draw",
                    Value = datas.MatchDrawCount
                }
            };
            IsBusy = false;
        }
示例#8
0
        private void PopulateCompanyDetails()
        {
            CompanyOverviewViewModel viewModel = new CompanyOverviewViewModel();

            viewModel.ViewModelEvent += viewModel_ViewModelEvent;

            CompanyObject company = viewModel.GetCompany(WebSessionHandler.SelectedCompanyCode);

            if (company != null)
            {
                lbCompanyName.Text  = company.CompanyName;
                lbCompanyCode.Text  = company.CompanyCode;
                lbContactsName.Text = company.AdminName;
                lbTelephone.Text    = company.Telephone;
                lbWhenCreated.Text  = company.Created.ToString();

                Address = string.Format("{0}, {1}, {2} {3}", company.Street, company.City, company.State, company.ZipCode);

                // Set the plan
                ListItem item = ddlCurrentPlan.Items.FindByValue(company.CompanyPlanID.ToString());
                if (item != null)
                {
                    ddlCurrentPlan.SelectedValue = item.Value;
                }
                else
                {
                    alertmessage.SetMessage(AlertID.WARNING, "Company plan is not set!");
                    ddlCurrentPlan.SelectedIndex = 0;
                }

                if (company.CompanyPlanObject != null)
                {
                    // Get product details
                    OverallStats statistics = viewModel.GetCompanyStats(WebSessionHandler.SelectedCompanyCode);
                    if (statistics != null)
                    {
                        lbUsers.Text = string.Format("({0} / {1})", statistics.TotalUsers, company.CompanyPlanObject.MaxUser);
                        progBarUsers.Attributes.Add("data-percentage", string.Format("{0}%", (int)Math.Round((double)(100 * statistics.TotalUsers) / company.CompanyPlanObject.MaxUser)));

                        lbDomains.Text = string.Format("({0} / {1})", statistics.TotalDomains, company.CompanyPlanObject.MaxDomains);
                        progBarDomains.Attributes.Add("data-percentage", string.Format("{0}%", (int)Math.Round((double)(100 * statistics.TotalDomains) / company.CompanyPlanObject.MaxDomains)));

                        lbTotalMailboxes.Text = string.Format("({0} / {1})", statistics.TotalMailboxes, company.CompanyPlanObject.MaxExchangeMailboxes);
                        progBarMailboxes.Attributes.Add("data-percentage", string.Format("{0}%", (int)Math.Round((double)(100 * statistics.TotalMailboxes) / company.CompanyPlanObject.MaxExchangeMailboxes)));
                    }
                }
            }
        }
        /// <summary>
        /// Checks if there were any changes in major stats
        /// Major stats are: Level, Quickplay Wins, Competitive Wins, Competitive Rank
        /// </summary>
        /// <param Name="oldStats">OStatsResult representing the stats before the Timer elapsed</param>
        /// <param Name="newStats">OStatsResult representing the stats after the Timer elapsed</param>
        /// <returns>A Dictionary with changed stats as Key, and a string presenting them as Value</returns>
        private async Task <Dictionary <string, string> > getChangedStatsAsync(OStatsResult oldStats, OStatsResult newStats)
        {
            Dictionary <string, string> changedStats = new Dictionary <string, string>();

            OverallStats quickNew = newStats.getNotNull().stats.quickplay.overall_stats;
            OverallStats quickOld = oldStats.getNotNull().stats.quickplay.overall_stats;

            var curLevel = await OverallStats.GetLevelAsync(Name);

            if (StatGraph.PlotDataPoints.Last().Value.Value < curLevel)
            {
                changedStats.Add("Level", (curLevel) +
                                 $" (+{(curLevel) - (StatGraph.PlotDataPoints.Last().Value.Value)})");
            }

            if (quickNew.wins > quickOld.wins)
            {
                changedStats.Add("Games won", quickNew.wins.ToString() +
                                 $" (+{quickNew.wins - quickOld.wins})");
            }

            if (oldStats.getNotNull().stats.competitive != null)
            {
                OverallStats compNew = newStats.getNotNull().stats.competitive.overall_stats;
                OverallStats compOld = oldStats.getNotNull().stats.competitive.overall_stats;

                if (compNew.comprank != compOld.comprank)
                {
                    int difference = compNew.comprank - compOld.comprank;
                    changedStats.Add("Comp Rank", compNew.comprank.ToString() +
                                     $" ({(difference > 0 ? "+" : "") + difference})");
                }

                if (compNew.wins > compOld.wins)
                {
                    changedStats.Add("Comp Games won", compNew.wins.ToString() +
                                     $" (+{compNew.wins - compOld.wins})");
                }
            }

            if (quickNew.endorsement_level != quickOld.endorsement_level)
            {
                changedStats.Add("Endorsement Level", quickNew.endorsement_level.ToString());
            }

            return(changedStats);
        }
示例#10
0
        private async Task LoadDatas()
        {
            OverallStats datas = await _demosService.GetGeneralAccountStatsAsync();

            MatchCount               = datas.MatchCount;
            KillCount                = datas.KillCount;
            AssistCount              = datas.AssistCount;
            DeathCount               = datas.DeathCount;
            HeadshotCount            = datas.HeadshotCount;
            HeadshotRatio            = datas.HeadshotRatio;
            KnifeKillCount           = datas.KnifeKillCount;
            FiveKillCount            = datas.FiveKillCount;
            FourKillCount            = datas.FourKillCount;
            ThreeKillCount           = datas.ThreeKillCount;
            TwoKillCount             = datas.TwoKillCount;
            EntryKillCount           = datas.EntryKillCount;
            KillDeathRatio           = datas.KillDeathRatio;
            BombDefusedCount         = datas.BombDefusedCount;
            BombExplodedCount        = datas.BombExplodedCount;
            BombPlantedCount         = datas.BombPlantedCount;
            KillPerRoundPercentage   = datas.KillPerRoundPercentage;
            AssistPerRoundPercentage = datas.AssistPerRoundPercentage;
            DeathPerRoundPercentage  = datas.DeathPerRoundPercentage;
            ClutchWinPercentage      = datas.ClutchWinPercentage;
            MvpCount        = datas.MvpCount;
            DamageCount     = datas.DamageCount;
            RoundCount      = datas.RoundCount;
            DatasMatchStats = new List <GenericDoubleChart>
            {
                new GenericDoubleChart
                {
                    Label = "Win",
                    Value = datas.MatchWinCount
                },
                new GenericDoubleChart
                {
                    Label = "Loss",
                    Value = datas.MatchLossCount
                },
                new GenericDoubleChart
                {
                    Label = "Draw",
                    Value = datas.MatchDrawCount
                }
            };
        }
示例#11
0
        public OverallStats GetCompanyStats(string companyCode)
        {
            CPDatabase database = null;

            try
            {
                database = new CPDatabase();

                OverallStats companyStats = new OverallStats();

                companyStats.TotalUsers = (from s in database.Users
                                           where s.CompanyCode == companyCode
                                           select s.UserPrincipalName).Count();

                companyStats.TotalDomains = (from d in database.Domains
                                             where d.CompanyCode == companyCode
                                             select d.Domain1).Count();

                companyStats.TotalMailboxes = (from m in database.Users
                                               where m.CompanyCode == companyCode
                                               where m.MailboxPlan > 0
                                               select m.UserPrincipalName).Count();

                companyStats.TotalLyncUsers = (from l in database.Users
                                               where l.CompanyCode == companyCode
                                               where l.LyncPlan > 0
                                               select l.UserPrincipalName).Count();


                return(companyStats);
            }
            catch (Exception ex)
            {
                this.logger.Error("Error retrieving company statistics from the database for " + companyCode, ex);
                ThrowEvent(Base.Enumerations.AlertID.FAILED, ex.Message);
                return(null);
            }
            finally
            {
                if (database != null)
                {
                    database.Dispose();
                }
            }
        }
示例#12
0
        ///<summary>Builds an embed out of the changed stats, and sends it as a Discord message </summary>
        /// <param Name="overwatchInformation">All fetched stats of the user </param>
        /// <param Name="changedStats">All changed stats of the user, together with a string presenting them </param>
        /// <param Name="mostPlayed">The most played Hero of the session, together with a string presenting them </param>
        private Embed createEmbed(OStatsResult overwatchInformation, Dictionary <string, string> changedStats, Tuple <string, string> mostPlayed)
        {
            OverallStats stats = overwatchInformation.getNotNull().stats.quickplay.overall_stats;

            EmbedBuilder e = new EmbedBuilder();

            e.Color = new Color(255, 152, 0);
            e.Title = "New Stats!";
            e.Url   = $"https://playoverwatch.com/en-us/career/pc/eu/{Name}";

            EmbedAuthorBuilder author = new EmbedAuthorBuilder();

            author.Name    = Name.Split("-")[0];
            author.Url     = $"https://playoverwatch.com/en-us/career/pc/eu/{Name}";
            author.IconUrl = stats.avatar;
            e.Author       = author;

            EmbedFooterBuilder footer = new EmbedFooterBuilder();

            footer.IconUrl = "http://i.imgur.com/YZ4w2ey.png";
            footer.Text    = "Overwatch";
            e.Timestamp    = DateTime.Now;
            e.Footer       = footer;

            foreach (var kvPair in changedStats)
            {
                e.AddField(kvPair.Key, kvPair.Value, true);
            }

            e.AddField("Sessions most played Hero", $"{mostPlayed.Item2}");
            if (mostPlayed.Item1.Equals("Ana") || mostPlayed.Item1.Equals("Moira") || mostPlayed.Item1.Equals("Orisa") || mostPlayed.Item1.Equals("Doomfist") ||
                mostPlayed.Item1.Equals("Sombra") || mostPlayed.Item1.Equals("Brigitte") || mostPlayed.Item1.Equals("Wrecking-Ball") || mostPlayed.Item1.Equals("Ashe"))
            {
                e.ThumbnailUrl = $"https://blzgdapipro-a.akamaihd.net/hero/{mostPlayed.Item1.ToLower()}/full-portrait.png";
            }
            else
            {
                e.ThumbnailUrl = $"https://blzgdapipro-a.akamaihd.net/media/thumbnail/{mostPlayed.Item1.ToLower()}-gameplay.jpg";
            }

            e.ImageUrl = StatGraph.DrawPlot();

            return(e.Build());
        }
示例#13
0
        public async Task RebuildOverall()
        {
            var newStorage = new Storage();
            var newOverall = new OverallStats(newStorage);

            var sessions = (await GetSessionsStorageAsync()).ToList();
            await Task.Run(() => {
                for (var i = 0; i < sessions.Count; i++)
                {
                    var session = sessions[i].Parsed;
                    if (session != null)
                    {
                        newOverall.Extend(session);
                    }
                }
            });

            Overall.CopyFrom(newOverall);
            newStorage.SetObject(KeyOverall, Overall);
            GetMainStorage().CopyFrom(newStorage);
        }
示例#14
0
        /// <summary>
        /// Event for the Timer, to check for changed stats
        /// </summary>
        /// <param Name="stateinfo"></param>
        public async override void CheckForChange_Elapsed(object stateinfo)
        {
            try
            {
                OStatsResult newInformation;

                lock (APILock)
                {
                    newInformation = FetchJSONDataAsync <OStatsResult>($"https://owapi.net/api/v3/u/{Name}/blob").Result;
                    Task.Delay(2500).Wait();
                }

                //OWAPI or PlayOverwatch messed up
                if (newInformation.getNotNull() == null)
                {
                    return;
                }

                if (StatGraph == null)
                {
                    StatGraph = new DatePlot(Name, "Date", "Level", "dd-MMM", false);
                    StatGraph.AddValue("Level", await OverallStats.GetLevelAsync(Name));
                    await UpdateTracker();
                }

                if (information == null)
                {
                    information = newInformation;
                }

                if (newInformation == null)
                {
                    return;
                }

                var changedStats = await getChangedStatsAsync(information, newInformation);

                if (changedStats.Count != 0)
                {
                    StatGraph.AddValue("Level", StatGraph.PlotDataPoints.Last().Value.Value);
                    StatGraph.AddValue("Level", await OverallStats.GetLevelAsync(Name));

                    foreach (ulong channel in ChannelConfig.Keys.ToList())
                    {
                        await OnMajorChangeTracked(channel, createEmbed(newInformation, changedStats, getSessionMostPlayed(information.getNotNull().heroes.playtime, newInformation.getNotNull().heroes.playtime)), (string)ChannelConfig[channel]["Notification"]);
                    }

                    information = newInformation;
                    await UpdateTracker();
                }
            }
            catch (Exception e)
            {
                await Program.MopsLog(new LogMessage(LogSeverity.Error, "", $" error by {Name}", e));

                if (e.Message.Contains("TOO MANY REQUESTS"))
                {
                    //var nextElapse = StaticBase.ran.Next(10000, 300000);
                    //checkForChange.Change(nextElapse, 300000);
                    await Program.MopsLog(new LogMessage(LogSeverity.Info, "", $"Trying again next cycle", e));
                }
            }
        }
示例#15
0
        private void GetTotalAllocatedMailboxSize(string entityConnectionString, ref OverallStats stats)
        {
            SqlConnection sql = null;
            SqlCommand    cmd = null;

            try
            {
                string providerConnectionString = new EntityConnectionStringBuilder(entityConnectionString).ProviderConnectionString;


                sql = new SqlConnection(providerConnectionString);
                cmd = new SqlCommand(@"SELECT UserPrincipalName, MailboxPlan, AdditionalMB, 
                                       (SELECT MailboxSizeMB FROM Plans_ExchangeMailbox WHERE MailboxPlanID=Users.MailboxPlan) AS MailboxPlanSize,
                                       ((SELECT MailboxSizeMB FROM Plans_ExchangeMailbox WHERE MailboxPlanID=Users.MailboxPlan) + AdditionalMB) AS TotalSize
                                       FROM Users WHERE MailboxPlan > 0", sql);

                sql.Open();

                // Keep track of total
                decimal total = 0;

                // Read data
                SqlDataReader r = cmd.ExecuteReader();
                if (r.HasRows)
                {
                    while (r.Read())
                    {
                        if (r["TotalSize"] == DBNull.Value)
                        {
                            total = total + decimal.Parse(r["MailboxPlanSize"].ToString(), CultureInfo.InvariantCulture);
                        }
                        else
                        {
                            total = total + decimal.Parse(r["TotalSize"].ToString(), CultureInfo.InvariantCulture);
                        }
                    }

                    // Convert to GB, TB, etc
                    if (total > 0)
                    {
                        if (total >= 1048576)
                        {
                            stats.TotalAllocatedEmailSpace         = (total / 1024) / 1024;
                            stats.TotalAllocatedEmailSpaceSizeType = "TB";
                        }
                        else if (total >= 1024)
                        {
                            stats.TotalAllocatedEmailSpace         = total / 1024;
                            stats.TotalAllocatedEmailSpaceSizeType = "GB";
                        }

                        // Convert the MB to KB for the progress bars
                        stats.TotalAllocatedEmailSpaceInKB = total * 1024;
                    }
                }

                r.Close();
                r.Dispose();

                if (total < 0)
                {
                    stats.TotalAllocatedEmailSpaceInKB     = 0;
                    stats.TotalAllocatedEmailSpace         = 0;
                    stats.TotalAllocatedEmailSpaceSizeType = "?";
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error getting Exchange allocated mailbox sizes", ex);
            }
            finally
            {
                if (cmd != null)
                {
                    cmd.Dispose();
                }

                if (sql != null)
                {
                    sql.Dispose();
                }
            }
        }
示例#16
0
        /// <summary>
        /// Queries the API to fetch a JSON containing all the stats for the player
        /// Then converts it into OStatsResult
        /// </summary>
        /// <returns>An OStatsResult representing the fetched JSON as an object</returns>
        public static async Task <Embed> GetStatEmbedAsync(string owName)
        {
            OStatsResult info;

            lock (APILock)
            {
                info = FetchJSONDataAsync <OStatsResult>($"https://owapi.net/api/v3/u/{owName}/blob").Result;
                Task.Delay(2500).Wait();
            }

            //OWAPI messed up
            if (info.getNotNull() == null)
            {
                return(new EmbedBuilder().WithDescription("The API yielded no results.\nIf the player exists and is not private, this may be due to a temporary outage.").Build());
            }

            Quickplay stats      = info.getNotNull().stats.quickplay;
            var       mostPlayed = getMostPlayed(info.getNotNull().heroes.playtime);

            EmbedBuilder e = new EmbedBuilder();

            e.Color = new Color(255, 152, 0);
            e.Title = "Stats";
            e.Url   = $"https://playoverwatch.com/en-us/career/pc/eu/{owName}";

            EmbedAuthorBuilder author = new EmbedAuthorBuilder();

            author.Name = owName.Split("-")[0];
            author.Url  = $"https://playoverwatch.com/en-us/career/pc/eu/{owName}";

            e.Author = author;

            EmbedFooterBuilder footer = new EmbedFooterBuilder();

            footer.IconUrl = "http://i.imgur.com/YZ4w2ey.png";
            footer.Text    = "Overwatch";
            e.Timestamp    = DateTime.Now;
            e.Footer       = footer;

            e.ThumbnailUrl = stats.overall_stats.avatar;

            e.AddField("Damage", $"Total: {stats.game_stats.all_damage_done}" +
                       $"\nBest: {stats.game_stats.all_damage_done_most_in_game}" +
                       $"\nAverage: {stats.rolling_average_stats.all_damage_done * 1000}", true);

            e.AddField("Eliminations", $"Total: {stats.game_stats.eliminations}" +
                       $"\nKPD Best: {stats.game_stats.kill_streak_best}" +
                       $"\nKPD Average: {stats.game_stats.kpd}", true);

            e.AddField("Healing", $"Total: {stats.game_stats.healing_done}" +
                       $"\nBest: {stats.game_stats.healing_done_most_in_game}" +
                       $"\nAverage: {stats.rolling_average_stats.healing_done * 1000}", true);

            e.AddField("Medals", $"Bronze: {stats.game_stats.medals_bronze}" +
                       $"\nSilver: {stats.game_stats.medals_silver}" +
                       $"\nGold: {stats.game_stats.medals_gold}", true);

            e.AddField("General", $"Time played: {stats.game_stats.time_played}hrs" +
                       $"\nLevel: {await OverallStats.GetLevelAsync(owName)}" +
                       $"\nWon Games: {stats.overall_stats.wins}" +
                       $"\n Endorsement Level: {stats.overall_stats.endorsement_level}", true);

            if (info.getNotNull().stats.competitive != null)
            {
                author.IconUrl = info.getNotNull().stats.competitive.overall_stats.tier_image;
                e.AddField("Competitive", $"Time played: {info.getNotNull().stats.competitive.game_stats.time_played}hrs" +
                           $"\nWin Rate: {info.getNotNull().stats.competitive.overall_stats.win_rate}%" +
                           $"\nRank: {info.getNotNull().stats.competitive.overall_stats.comprank}", true);
            }


            e.AddField("Most Played", mostPlayed.Item2);

            if (mostPlayed.Item1.Equals("Ana") || mostPlayed.Item1.Equals("Moira") || mostPlayed.Item1.Equals("Orisa") ||
                mostPlayed.Item1.Equals("Doomfist") || mostPlayed.Item1.Equals("Sombra") || mostPlayed.Item1.Equals("Wrecking-Ball") ||
                mostPlayed.Item1.Equals("Brigitte"))
            {
                e.ImageUrl = $"https://blzgdapipro-a.akamaihd.net/hero/{mostPlayed.Item1.ToLower()}/full-portrait.png";
            }
            else
            {
                e.ImageUrl = $"https://blzgdapipro-a.akamaihd.net/media/thumbnail/{mostPlayed.Item1.ToLower()}-gameplay.jpg";
            }

            return(e.Build());
        }
示例#17
0
        private void GetTotalUsedMailboxSize(string entityConnectionString, ref OverallStats stats)
        {
            SqlConnection sql = null;
            SqlCommand    cmd = null;

            try
            {
                string providerConnectionString = new EntityConnectionStringBuilder(entityConnectionString).ProviderConnectionString;


                sql = new SqlConnection(providerConnectionString);
                cmd = new SqlCommand(@"SELECT UserPrincipalName, Retrieved, TotalItemSizeInKB FROM SvcMailboxSizes 
                                        WHERE CONVERT(date, Retrieved) = (SELECT TOP 1 CONVERT(date, Retrieved) FROM SvcMailboxSizes ORDER BY Retrieved DESC)
                                        ORDER BY Retrieved DESC", sql);

                sql.Open();

                // Keep track of total
                decimal total = 0;

                // Read data
                SqlDataReader r = cmd.ExecuteReader();
                if (r.HasRows)
                {
                    while (r.Read())
                    {
                        decimal parsed = 0;
                        decimal.TryParse(r["TotalItemSizeInKB"].ToString(), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out parsed);

                        total = total + parsed;
                    }

                    // Convert to MB, GB, TB, etc
                    if (total > 0)
                    {
                        if (total >= 1073741824)
                        {
                            stats.TotalUsedEmailSpace         = ((total / 1024) / 1024) / 1024;
                            stats.TotalUsedEmailSpaceSizeType = "TB";
                        }
                        else if (total >= 1048576)
                        {
                            stats.TotalUsedEmailSpace         = (total / 1024) / 1024;
                            stats.TotalUsedEmailSpaceSizeType = "GB";
                        }
                        else if (total >= 1024)
                        {
                            stats.TotalUsedEmailSpace         = total / 1024;
                            stats.TotalUsedEmailSpaceSizeType = "MB";
                        }

                        stats.TotalUsedEmailSpaceInKB = total;
                    }
                }

                r.Close();
                r.Dispose();

                if (total < 0)
                {
                    stats.TotalUsedEmailSpaceInKB     = 0;
                    stats.TotalUsedEmailSpace         = 0;
                    stats.TotalUsedEmailSpaceSizeType = "?";
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error getting Exchange mailbox sizes", ex);
            }
            finally
            {
                if (cmd != null)
                {
                    cmd.Dispose();
                }

                if (sql != null)
                {
                    sql.Dispose();
                }
            }
        }
示例#18
0
 public void CopyFrom(OverallStats updated) {
     foreach (var p in typeof(OverallStats).GetProperties().Where(p => p.CanWrite)) {
         p.SetValue(this, p.GetValue(updated, null), null);
     }
 }
示例#19
0
        public async Task <OverallStats> GetGeneralAccountStatsAsync()
        {
            OverallStats stats = new OverallStats();

            List <Demo> demos = await _cacheService.GetDemoListAsync();

            if (demos.Any())
            {
                List <Demo> demosPlayerList = demos.Where(demo => demo.Players.FirstOrDefault(p => p.SteamId == Settings.Default.SelectedStatsAccountSteamID) != null).ToList();
                if (demosPlayerList.Any())
                {
                    stats.MatchCount = demosPlayerList.Count;
                    foreach (Demo demo in demosPlayerList)
                    {
                        stats.KillCount         += demo.TotalKillSelectedAccountCount;
                        stats.AssistCount       += demo.AssistSelectedAccountCount;
                        stats.DeathCount        += demo.DeathSelectedAccountCount;
                        stats.KnifeKillCount    += demo.KnifeKillSelectedAccountCount;
                        stats.EntryKillCount    += demo.EntryKillSelectedAccountCount;
                        stats.FiveKillCount     += demo.FiveKillSelectedAccountCount;
                        stats.FourKillCount     += demo.FourKillSelectedAccountCount;
                        stats.ThreeKillCount    += demo.ThreeKillSelectedAccountCount;
                        stats.TwoKillCount      += demo.TwoKillSelectedAccountCount;
                        stats.HeadshotCount     += demo.HeadshotSelectedAccountCount;
                        stats.BombDefusedCount  += demo.BombDefusedSelectedAccountCount;
                        stats.BombExplodedCount += demo.BombExplodedSelectedAccountCount;
                        stats.BombPlantedCount  += demo.BombPlantedSelectedAccountCount;
                        stats.MvpCount          += demo.MvpSelectedAccountCount;
                        stats.DamageCount       += demo.TotalDamageHealthSelectedAccountCount;
                        stats.RoundCount        += demo.Rounds.Count;
                        stats.ClutchCount       += demo.ClutchSelectedAccountCount;
                        stats.ClutchWin         += demo.ClutchWinCountSelectedAccountCount;
                        switch (demo.MatchVerdictSelectedAccountCount)
                        {
                        case -1:
                            stats.MatchLossCount++;
                            break;

                        case 0:
                            stats.MatchDrawCount++;
                            break;

                        case 1:
                            stats.MatchWinCount++;
                            break;
                        }
                    }
                }

                if (stats.KillCount != 0 && stats.DeathCount != 0)
                {
                    stats.KillDeathRatio = Math.Round(stats.KillCount / (decimal)stats.DeathCount, 2);
                }
                if (stats.KillCount != 0 && stats.HeadshotCount != 0)
                {
                    stats.HeadshotRatio = Math.Round(((decimal)stats.HeadshotCount * 100) / stats.KillCount, 2);
                }
            }

            return(stats);
        }
示例#20
0
        public OverallStats GetOtherStatistics(string entityConnectionString)
        {
            CPDatabase database = null;

            try
            {
                database = new CPDatabase();

                OverallStats stats = null;

                // Get all users
                var users = from u in database.Users
                            select u;

                // Don't continue we don't find any users
                if (users != null)
                {
                    stats                = new OverallStats();
                    stats.TotalUsers     = users.Count();
                    stats.TodayUsers     = (from u in users where DbFunctions.TruncateTime(u.Created) == DbFunctions.TruncateTime(DateTime.Now) select u.UserPrincipalName).Count();
                    stats.TotalMailboxes = (from u in users where u.MailboxPlan > 0 select u.UserPrincipalName).Count();
                    stats.TotalLyncUsers = (from u in users where u.LyncPlan > 0 select u.UserPrincipalName).Count();

                    // Get all companies
                    var companies = from c in database.Companies
                                    select c;

                    if (companies != null)
                    {
                        stats.TotalResellers = (from r in companies where r.IsReseller select r.CompanyCode).Count();
                        stats.TotalCompanies = (from c in companies where !c.IsReseller select c.CompanyCode).Count();
                        stats.TodayCompanies = (from c in companies where DbFunctions.TruncateTime(c.Created) == DbFunctions.TruncateTime(DateTime.Now) select c.CompanyCode).Count();
                    }

                    // Get all domains
                    var domains = from d in database.Domains
                                  select d;

                    if (domains != null)
                    {
                        stats.TotalDomains         = (from d in domains select d.Domain1).Count();
                        stats.TotalAcceptedDomains = (from a in domains where a.IsAcceptedDomain select a.Domain1).Count();
                    }

                    // Get other Exchange stats
                    stats.TotalDistributionGroups = (from d in database.DistributionGroups select d.ID).Count();
                    stats.TotalMailContacts       = (from c in database.Contacts select c.DistinguishedName).Count();

                    // Get Citrix users
                    var citrix = (from c in database.UserPlansCitrices
                                  select c.UserID).Distinct().Count();
                    stats.TotalCitrixUsers = citrix;

                    // Get Citrix data
                    var citrixApps = from c in database.Plans_Citrix
                                     select c;

                    if (citrixApps != null)
                    {
                        stats.TotalCitrixApps    = (from c in citrixApps where !c.IsServer select c).Count();
                        stats.TotalCitrixServers = (from c in citrixApps where c.IsServer select c).Count();
                    }


                    // Get total allocated space
                    GetTotalAllocatedMailboxSize(entityConnectionString, ref stats);

                    // Get total used spaces
                    GetTotalUsedMailboxSize(entityConnectionString, ref stats);
                }

                // Return data
                return(stats);
            }
            catch (Exception ex)
            {
                this.logger.Error("Error getting other statistics.", ex);
                return(null);
            }
            finally
            {
                if (database != null)
                {
                    database.Dispose();
                }
            }
        }