private void OnStatisticListSelectionChanged()
        {
            if (this.statisticNameSelectedItems == null || this.statisticNameSelectedItems.Count == 0)
            {
                return;
            }

            if (this.statisticNameSelectedItems.Count == 0 || this.statisticNameSelectedItems.Contains(StatisticsViewModel.DefaultStatText))
            {
                this.LoadDefaultList();
            }
            else
            {
                this.sortByList = this.statisticNameSelectedItems.Select(o => StatisticHelper.FromDisplayText(o.ToString())).ToList();
                var newPages = new List <StatValueViewModel>(this.sortByList.Count);

                foreach (var stat in this.sortByList)
                {
                    var newPage  = new StatValueViewModel(StatisticHelper.GetDisplayText(stat));
                    var statList = this.Settings.Statistics.Select(st => st[stat]).Distinct().ToList();
                    statList.Sort((o1, o2) => StatisticComparer.Default.Compare(o1, o2));
                    newPage.StatisticValues  = statList;
                    newPage.PropertyChanged += this.newPage_PropertyChanged;
                    newPages.Add(newPage);
                }

                this.Pages        = newPages;
                this.SelectedPage = newPages[0];
            }
        }
    void ShowPageContent()
    {
        contentText.text = "";
        content          = StatisticHelper.ReadFromFile();
        if (content == null)
        {
            max_page         = current_page;
            contentText.text = "There are no played games";
        }
        else
        {
            max_page = content.Count / items_per_page;
            int temp = content.Count % items_per_page;
            if (temp != 0)
            {
                max_page++;
            }

            pages.text = string.Format("{0}/{1}", current_page, max_page);

            int up_bound = current_page * items_per_page;
            if (up_bound >= content.Count)
            {
                up_bound = content.Count;
            }

            for (int i = (current_page - 1) * items_per_page; i < up_bound; i++)
            {
                contentText.text += content[i] + '\n';
            }
        }
        //Console.Write(current_page);
    }
        public ActionResult GetContextEditor(int sportId, StatTargetType targetType, string elements, StatTargetType contextType)
        {
            ViewBag.ContextType = contextType;
            var selectList = StatisticHelper.GetContextEditor(sportId, targetType, elements.Split(',').Select(int.Parse).ToArray(), contextType, DataContext);

            return(PartialView("_ContextEditor", selectList));
        }
        private string GetAverageValue(IEnumerable <IStatisticsModule> modules, Statistic stat)
        {
            if (stat == Statistic.MatchCount)
            {
                return(modules.Count().ToString());
            }

            var statType = StatisticHelper.GetType(stat);

            if (statType.IsPrimitive)
            {
                var average = modules.Average(module => (double)Convert.ChangeType(module[stat], typeof(double)));
                return(average.ToString("0.00"));
            }
            if (statType == typeof(DateTime))
            {
                var average = (int)modules.Select(module => (((DateTime)module[stat]).Hour * 60) + ((DateTime)module[stat]).Minute).Average();
                var time    = new DateTime(1, 1, 1, (int)Math.Floor(average / 60d), average % 60, 0, DateTimeKind.Local);
                return(time.ToString("h:mm tt", CultureInfo.CurrentCulture.DateTimeFormat));
            }
            else
            {
                var average = modules.GroupBy(module => module[stat]).OrderByDescending(g => g.Count());
                return(average.ElementAt(0).Key.ToString());
            }
        }
        private void newPage_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName != "SelectedValue")
            {
                return;
            }

            var model = (StatValueViewModel)sender;
            var index = this.pages.IndexOf(model);
            var stats = new List <KeyValuePair <Statistic, object> >(index + 1);

            for (var i = 0; i < this.pages.Count; i++)
            {
                var selectedValue = this.pages[i].SelectedValue;
                if (selectedValue != null)
                {
                    stats.Add(new KeyValuePair <Statistic, object>(this.sortByList[i], selectedValue));
                }
            }

            if (stats.Count == 0)
            {
                this.ValueHeader   = "Value";
                this.StatisticList = this.GetDefaultList();
                return;
            }

            var moduleList = this.Settings.Statistics.Where(st => this.HasAllValues(st, stats)).ToArray();
            var statList   = new List <StatDisplay>();

            if (moduleList.Length == 0)
            {
                var statDisplay = new StatDisplay(
                    StatisticHelper.GetDisplayText(Statistic.MatchCount),
                    "0",
                    StatisticHelper.GetDescription(Statistic.MatchCount));
                statList.Add(statDisplay);
            }
            else
            {
                foreach (var stat in this.GetStatDisplayList())
                {
                    var statDisplay = new StatDisplay(
                        StatisticHelper.GetDisplayText(stat),
                        this.GetAverageValue(moduleList, stat),
                        StatisticHelper.GetDescription(stat));
                    statList.Add(statDisplay);
                }
            }

            this.ValueHeader   = "Average Value";
            this.StatisticList = statList;
        }
        public ActionResult GetStatistic(StatisticRequest model)
        {
            var statistic = StatisticHelper.GetStatistic(model, DataContext);

            var eventTypes = model.TargetEvents == null
                ? DataContext.EventTypes.Where(x => x.SportId == model.SportId && !x.IsSystemEventType).ToList()
                : DataContext.EventTypes.Where(x => model.TargetEvents.Contains(x.Id)).ToList();

            ViewBag.RequestModel = model;
            ViewBag.EventTypes   = eventTypes;
            return(PartialView("_StatisticResult", statistic));
        }
Exemple #7
0
 /// <summary>
 /// Starts a new thread that adds a login to the statistics file.
 /// </summary>
 /// <param name="context"></param>
 /// <param name="userId"></param>
 public void AddLogin(HttpContext context, Guid userId)
 {
     if (IsStatisticEnabled)
     {
         // Bots will be ignored.
         if (!StatisticHelper.IsBot(context.Request))
         {
             LoginWorker worker = new LoginWorker(this, context, userId);
             Thread      t      = new Thread(new ThreadStart(worker.AddLogin));
             t.Start();
         }
     }
 }
Exemple #8
0
    protected override void SetResults()
    {
        DateTime dateTime = DateTime.UtcNow.Date;

        ResultStatConfig.Date   = dateTime.ToString("d");
        ResultStatConfig.Name   = FieldConfig.Name;
        ResultStatConfig.Result = isWin ? "Win" : "Lose";
        ResultStatConfig.Steps  = controlManager.steps.ToString();
        ResultStatConfig.Time   = spend_time.ToString();
        ResultStatConfig.Type   = "SinglePlayer";

        StatisticHelper.WriteResult();
    }
Exemple #9
0
 /// <summary>
 /// Starts a new thread that writes informations about the current visit to the statistics.
 /// </summary>
 /// <param name="context"></param>
 public void AddVisit(HttpContext context)
 {
     if (IsStatisticEnabled)
     {
         // Bots will be ignored.
         if (!StatisticHelper.IsBot(context.Request))
         {
             RequestWorker worker = new RequestWorker(this, context);
             Thread        t      = new Thread(new ThreadStart(worker.AddVisit));
             t.Start();
         }
     }
 }
        public static string GetVotedUserList(int classId, DateTime startDate, DateTime endDate, string userId, string departmentId)
        {
            Dictionary <string, object> dicResult = new Dictionary <string, object>();

            startDate = new DateTime(startDate.Year, startDate.Month, startDate.Day, 0, 0, 0);
            endDate   = new DateTime(endDate.Year, endDate.Month, endDate.Day, 23, 59, 59);
            List <VotedUserDTO> result = StatisticHelper.GetVotedUserList(classId, startDate, endDate, userId, departmentId, "-1");

            dicResult["Data"]  = result;
            dicResult["Count"] = result.Count;
            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            return(js.Serialize(dicResult));
        }
        public StatisticsViewModel()
        {
            var statList = StatisticHelper.GetGameStatistics().Select(StatisticHelper.GetDisplayText).OrderBy(s => s).ToList();

            statList.Insert(0, StatisticsViewModel.DefaultStatText);

            this.Pages                      = new List <StatValueViewModel>();
            this.sortByList                 = new List <Statistic>();
            this.StatisticNameList          = statList;
            this.StatisticNameSelectedItems = new List <object> {
                statList[0]
            };
        }
        public static string GetListClass()
        {
            List <ClassDTO> modelDTO = new List <ClassDTO>();
            //SessionManager.DoWork(session =>
            //{
            //    List<Class> classList = session.Query<Class>().ToList();
            //    modelDTO = classList.Map<ClassDTO>();
            //});
            List <Class> classList = StatisticHelper.GetClassListByUser();

            modelDTO = classList.Map <ClassDTO>();
            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            return(js.Serialize(modelDTO));
        }
Exemple #13
0
        public StatisticHelper GetStatisticByCountry(string name)
        {
            StatisticHelper statisticHelper      = new StatisticHelper();
            Dictionary <DateTime, decimal> rates = new Dictionary <DateTime, decimal>();

            statisticHelper.rates = rates;
            statisticHelper.Name  = name;
            var result = _context.Currency.Where(x => x.Name.Equals(name)).Include(x => x.DailyRates).ThenInclude(x => x.DailyRate).FirstOrDefault();

            foreach (var item in result.DailyRates)
            {
                rates.Add(item.DailyRate.Date.Date, (decimal)item.Rate);
            }
            return(statisticHelper);
        }
        public static string GetOlogyList(string classId, string departmentId)
        {
            string result;

            //if (departmentId != "-1")
            //{
            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            if (classId == "10")
            {
                result = js.Serialize(StatisticHelper.GetSubDepartmentByDepartment(departmentId));
            }
            else
            {
                result = js.Serialize(StatisticHelper.GetOlogyListByDepartment(departmentId));
            }
            //}
            return(result);
        }
        public void Update()
        {
            var lastRawIncomeTime = rawManager.GetLast().time;
            ////Day Start////
            var currentDay = UnixTimeHelper.GetCurrentDay();

            dayIncome = rawManager.GetLast().value - rawManager.GetRow(currentDay).value;
            var recentIncome      = manager.GetLast().value;
            var penultimateIncome = manager.GetPenultimate().value;

            dayTrend = recentIncome / penultimateIncome - 1;

            var lastDayIncomeArray = rawManager.GetInvertSlice(lastRawIncomeTime - 86400);
            var lastDayAmountArray = lastDayIncomeArray.Select(r => r.value).ToArray();

            dayAver     = StatisticHelper.GetAverageSpeed(lastDayAmountArray, 86400);
            dayExpected = StatisticHelper.GetMedianSpeed(lastDayAmountArray, 86400);
            ////Day End////

            ////Week Start////
            var weekDayIncome = manager.GetIncome(7);

            weekIncome = weekDayIncome;
            var twoWeekDayIncome = manager.GetIncome(14);
            var weeksDiff        = twoWeekDayIncome - weekDayIncome;

            weekTrend = (weeksDiff > 0) ? weekDayIncome / weeksDiff - 1 : 0.0;

            var weekIncomeArray       = rawManager.GetInvertSlice(lastRawIncomeTime - 604800);
            var weekIncomeAmountArray = weekIncomeArray.Select(r => r.value).ToArray();

            weekAver     = StatisticHelper.GetAverageSpeed(weekIncomeAmountArray, 604800);
            weekExpected = StatisticHelper.GetMedianSpeed(weekIncomeAmountArray, 604800);
            ////Week End////

            ////Total Start////
            var allIncome = manager.GetAll().Select(d => d.value);

            totalIncome = allIncome.Sum();
            totalTrend  = StatisticHelper.GetGlobalTrend(allIncome.ToArray());
            ////Total End////
        }
        public static string GetVoteResults(Guid voteFormId, string departmentId, string ologyId)
        {
            bool isObligate = StatisticHelper.IsObligateVoteForm(voteFormId);
            List <VotedUserDTO> voteUserList = new List <VotedUserDTO>();
            int totalRowCount = GeneralResult.GetVoteResults(voteFormId, departmentId, ologyId).Count();
            List <Statistic_VoteResultDTO> voteResults = GeneralResult.GetVoteResults(voteFormId, departmentId, ologyId).ToList();

            if (isObligate)
            {
                voteUserList = GeneralResult.GetAllVotedUserList_Obligate(voteFormId, departmentId, ologyId, DateTime.MinValue.AddYears(1899), DateTime.Now, "-1");
            }
            else
            {
                voteUserList = GeneralResult.GetAllVotedUserList(voteFormId, departmentId, ologyId, DateTime.MinValue.AddYears(1899), DateTime.Now);
            }
            var voteResultUserList = (from vote in voteResults
                                      from user in voteUserList
                                      where (vote.UserId == user.Id && vote.VoteObjectId.Equals(user.MLHP, StringComparison.OrdinalIgnoreCase))
                                      select new
            {
                vote.VoteFormId,
                vote.Id,
                vote.UserId,
                vote.VoteObjectId,
                vote.VoteTime,
                user.Name,
                user.DepartmentId,
                user.DepartmentName,
                user.OlogyId,
                user.OlogyName,
                user.ClassStudentID,
                user.ClassStudentName
            }).ToList();
            Dictionary <string, object> resultDics = new Dictionary <string, object>();

            resultDics.Add("draw", 0);
            resultDics.Add("recordsTotal", totalRowCount);
            resultDics.Add("recordsFiltered", totalRowCount);
            resultDics.Add("data", voteResultUserList);
            return(JsonConvert.SerializeObject(resultDics));
        }
Exemple #17
0
        public void Update()
        {
            var lastRawIncomeTime     = rawManager.GetLast().time;
            var hourIncomeArray       = rawManager.GetInvertSlice(lastRawIncomeTime - 3600);
            var hourIncomeAmountArray = hourIncomeArray.Select(r => r.value).ToArray();

            ////Day Start////
            var dayIncomeArray       = rawManager.GetInvertSlice(lastRawIncomeTime - 86400);
            var dayIncomeAmountArray = dayIncomeArray.Select(r => r.value).ToArray();

            fullDayAverage = StatisticHelper.GetAverageSpeed(dayIncomeAmountArray, 86400);
            fullDayMedian  = StatisticHelper.GetMedianSpeed(dayIncomeAmountArray, 86400);
            hourDayAverage = StatisticHelper.GetAverageSpeed(hourIncomeAmountArray, 86400);
            hourDayMedian  = StatisticHelper.GetMedianSpeed(hourIncomeAmountArray, 86400);
            ////Day End////

            ////Week Start////
            var weekIncomeArray       = rawManager.GetInvertSlice(lastRawIncomeTime - 604800);
            var weekIncomeAmountArray = weekIncomeArray.Select(r => r.value).ToArray();

            fullWeekAverage = StatisticHelper.GetAverageSpeed(weekIncomeAmountArray, 604800);
            fullWeekMedian  = StatisticHelper.GetMedianSpeed(weekIncomeAmountArray, 604800);
            hourWeekAverage = StatisticHelper.GetAverageSpeed(hourIncomeAmountArray, 604800);
            hourWeekMedian  = StatisticHelper.GetMedianSpeed(hourIncomeAmountArray, 604800);
            ////Week End////

            ////Month Start////
            var monthIncomeArray = manager.GetInvertSlice(lastRawIncomeTime - 2629743);

            if (monthIncomeArray.Count() > 27)
            {
                var monthIncomeAmountArray = monthIncomeArray.Select(r => r.value).ToArray();
                fullMonthAverage = StatisticHelper.GetAverageSpeed(monthIncomeAmountArray, 2629743);
                fullMonthMedian  = StatisticHelper.GetMedianSpeed(monthIncomeAmountArray, 2629743);
            }

            hourMonthAverage = StatisticHelper.GetAverageSpeed(hourIncomeAmountArray, 2629743);
            hourMonthMedian  = StatisticHelper.GetMedianSpeed(hourIncomeAmountArray, 2629743);
            ////Month End////
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            String weekText = NSBundle.MainBundle.LocalizedString("Vernacular_P0_stats_week_label", null).PrepareForLabel();

            lblWeekText.Text      = weekText;
            lblWeekText.TextColor = StyleSettings.TextOnDarkColor();

            String overallText = NSBundle.MainBundle.LocalizedString("Vernacular_P0_stats_overall_label", null).PrepareForLabel();

            lblOverallText.Text      = overallText;
            lblOverallText.TextColor = StyleSettings.TextOnDarkColor();

            String lastTrackText = NSBundle.MainBundle.LocalizedString("Vernacular_P0_stats_last_track_label", null).PrepareForLabel();

            lblLastTrackText.Text      = lastTrackText;
            lblLastTrackText.TextColor = StyleSettings.TextOnDarkColor();

            try
            {
                using (var conn = DatabaseUtility.OpenConnection())
                {
                    var week    = StatisticHelper.GetPeriodSummary(conn, StatisticPeriod.Week);
                    var overall = StatisticHelper.GetPeriodSummary(conn, StatisticPeriod.Overall);
                    var last    = StatisticHelper.GetLastTrack(conn);

                    UpdateKmCounter(lblLastTrack, last?.DistanceTraveled);
                    UpdateKmCounter(lblWeek, week.Distance);
                    UpdateKmCounter(lblOverall, overall.Distance);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to load statistics");
            }

            // TODO: add share button
        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.activity_stats);

            //Toolbar support
            var toolbar = this.FindViewById <global::Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);

            if (toolbar != null)
            {
                SetSupportActionBar(toolbar);
                SupportActionBar.SetDisplayHomeAsUpEnabled(true);
            }
            if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
            {
                FindViewById(Resource.Id.toolbar_shadow).Visibility = ViewStates.Gone;
            }

            try {
                using (var conn = DatabaseUtility.OpenConnection()) {
                    var week    = StatisticHelper.GetPeriodSummary(conn, StatisticPeriod.Week);
                    var overall = StatisticHelper.GetPeriodSummary(conn, StatisticPeriod.Overall);
                    var last    = StatisticHelper.GetLastTrack(conn);

                    UpdateKmCounter(FindViewById <TextView>(Resource.Id.label_last_track_kms), last?.DistanceTraveled);
                    UpdateKmCounter(FindViewById <TextView>(Resource.Id.label_last_week_kms), week.Distance);
                    UpdateKmCounter(FindViewById <TextView>(Resource.Id.label_overall_kms), overall.Distance);
                }
            }
            catch (Exception ex) {
                Log.Error(ex, "Failed to load statistics");
            }

            FindViewById <Button>(Resource.Id.button_share).Click += HandleShareClick;
        }
Exemple #20
0
        public object GetVoteResults()
        {
            DataTables result = new DataTables();

            result.data = new DataTable();
            JObject jsonData2;

            try
            {
                using (System.IO.Stream stream = HttpContext.Current.Request.InputStream)
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
                    {
                        stream.Seek(0, System.IO.SeekOrigin.Begin);
                        string bodyText = reader.ReadToEnd();
                        jsonData2 = (JObject)JsonConvert.DeserializeObject(bodyText);
                    }
                DataTable data = new DataTable();
                if (jsonData2 != null)
                {
                    string search         = Regex.Replace(jsonData2["search"]["value"].ToString(), @"\s{2,}", " ").TrimStart(' ').TrimEnd(' ');
                    string draw           = jsonData2["draw"].ToString();               //draw
                    string order          = jsonData2["order"][0]["column"].ToString(); //order[0][column]
                    string orderDir       = jsonData2["order"][0]["dir"].ToString();    //order[0][dir]
                    string sortColumnName = jsonData2["columns"][int.Parse(order)]["data"].ToString();
                    int    startRec       = int.Parse(jsonData2["start"].ToString());   //start
                    int    pageSize       = int.Parse(jsonData2["length"].ToString());  //length
                    Guid   voteFormId     = !string.IsNullOrEmpty(jsonData2["voteFormId"].ToString()) ? Guid.Parse(jsonData2["voteFormId"].ToString()) : Guid.Empty;
                    string departmentId   = !string.IsNullOrEmpty(jsonData2["departmentId"].ToString()) ? jsonData2["departmentId"].ToString() : "-1";
                    string ologyId        = !string.IsNullOrEmpty(jsonData2["ologyId"].ToString()) ? jsonData2["ologyId"].ToString() : "-1";
                    bool   isObligate     = StatisticHelper.IsObligateVoteForm(voteFormId);
                    int    totalRecords   = 0;
                    int    recFilter      = 0;
                    using (SqlConnection con = new SqlConnection(connectionString))
                    {
                        con.Open();
                        using (SqlCommand cmd = new SqlCommand("sp_VoteResultUserInfor", con))
                        {
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.AddWithValue("@VoteFormId", voteFormId.ToString());
                            cmd.Parameters.AddWithValue("@DepartmentId", departmentId);
                            cmd.Parameters.AddWithValue("@OlogyId", ologyId);
                            cmd.Parameters.AddWithValue("@TuNgay", DateTime.MinValue.AddYears(1899));
                            cmd.Parameters.AddWithValue("@DenNgay", DateTime.Now);
                            cmd.Parameters.AddWithValue("@SearchString", search);
                            cmd.Parameters.AddWithValue("@PageSize", pageSize);
                            cmd.Parameters.AddWithValue("@PageStart", startRec);
                            cmd.Parameters.AddWithValue("@SortColumn", sortColumnName);
                            cmd.Parameters.AddWithValue("@SortType", orderDir);

                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                if (reader.HasRows)
                                {
                                    DataTable dt = new DataTable();
                                    dt.Clear();
                                    dt.Load(reader);
                                    data = dt;
                                    while (reader.Read())
                                    {
                                        totalRecords = DatabaseHelper.ContainsColumn(reader, "recordsTotal") ? int.Parse(reader["recordsTotal"].ToString()) : 0;
                                    }
                                    reader.NextResult();
                                    while (reader.Read())
                                    {
                                        recFilter = DatabaseHelper.ContainsColumn(reader, "recordsFiltered") ? int.Parse(reader["recordsFiltered"].ToString()) : 0;
                                    }
                                }
                            }
                        }
                        con.Close();
                    }
                    result.draw            = Convert.ToInt32(draw);
                    result.recordsTotal    = totalRecords;
                    result.recordsFiltered = recFilter;
                    result.data            = data;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return(result);
        }
 public static string GetDepartmentList()
 {
     System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
     return(js.Serialize(StatisticHelper.GetDepartmentList()));
 }
        private async Task PrepareImageAndShare()
        {
            Bitmap source = null, output = null;
            Canvas canvas = null;

            try {
                double kms = await Task.Run(() => {
                    using (var conn = DatabaseUtility.OpenConnection()) {
                        var overall = StatisticHelper.GetPeriodSummary(conn, StatisticPeriod.Overall);
                        return(overall.Distance);
                    }
                });

                var formatted = kms.ToString("0.0");
                Log.Debug("Preparing sharable badge for '{0}'", formatted);

                source = await BitmapFactory.DecodeResourceAsync(Resources, Resource.Drawable.award_laurel_template);

                output = Bitmap.CreateBitmap(source.Width, source.Height, Bitmap.Config.Argb8888);

                canvas = new Canvas(output);
                canvas.DrawBitmap(source, 0f, 0f, null);

                Paint paintText = new Paint(PaintFlags.AntiAlias);
                paintText.SetTypeface(Typeface.DefaultBold);
                paintText.TextSize = source.Width / (float)formatted.Length; // TODO: correctly compute text size to fill area
                paintText.Color    = Color.White;
                paintText.SetStyle(Paint.Style.Fill);

                // Text bounds computation taken from https://chris.banes.me/2014/03/27/measuring-text/
                Rect outTextBounds = new Rect();
                paintText.GetTextBounds(formatted, 0, formatted.Length, outTextBounds);
                var textWidth  = paintText.MeasureText(formatted);
                var textHeight = (float)outTextBounds.Height();

                canvas.DrawText(
                    formatted,
                    canvas.ClipBounds.CenterX() - (textWidth / 2f),
                    canvas.ClipBounds.CenterY() + (textHeight / 2f),
                    paintText
                    );

                // Store
                var outputPath = global::System.IO.Path.Combine(ApplicationContext.GetExternalFilesDir(null).AbsolutePath, "smartroadsense_badge.jpg");
                using (var outputStream = new System.IO.FileStream(outputPath, System.IO.FileMode.Create)) {
                    await output.CompressAsync(Bitmap.CompressFormat.Jpeg, 95, outputStream);
                }

                Log.Debug("Written output image to {0}", outputPath);

                // Get sharing URI
                var shareUri = global::Android.Support.V4.Content.FileProvider.GetUriForFile(
                    this, "it.uniurb.smartroadsense.fileprovider", new Java.IO.File(outputPath));

                // Share
                var i = new Intent(Intent.ActionSend);
                i.SetType("image/jpeg");
                i.AddFlags(ActivityFlags.NewTask);
                i.PutExtra(Intent.ExtraStream, shareUri);
                var shareText = string.Format(GetString(Resource.String.Vernacular_P0_share_badge_text), kms);
                i.PutExtra(Intent.ExtraText, shareText);
                i.PutExtra(Intent.ExtraTitle, shareText);

                var cm = (global::Android.Content.ClipboardManager)GetSystemService(ClipboardService);
                cm.PrimaryClip = ClipData.NewPlainText("share text", shareText);

                Toast.MakeText(ApplicationContext, Resource.String.Vernacular_P0_share_badge_clipboard, ToastLength.Long).Show();

                StartActivity(i);

                Log.Debug("Started sharing activity");
            }
            catch (Exception ex) {
                Log.Error(ex, "Failed preparing sharable bitmap");
                Toast.MakeText(ApplicationContext, Resource.String.Vernacular_P0_share_badge_failure, ToastLength.Short).Show();
            }
            finally {
                if (canvas != null)
                {
                    canvas.Dispose();
                }
                if (output != null)
                {
                    output.Dispose();
                }
                if (source != null)
                {
                    source.Dispose();
                }
            }
        }
        private IEnumerable <Statistic> GetStatDisplayList()
        {
            var displayStats = StatisticHelper.GetGlobalStatistics().OrderBy(StatisticHelper.GetDisplayText).Concat(StatisticHelper.GetGameStatistics().Where(stat => !this.IsSelected(stat)).OrderBy(StatisticHelper.GetDisplayText));

            return(displayStats);
        }
Exemple #24
0
        public void StatisticImportTest()
        {
            DbManagerFactory.SetSqlFactory(Config.GetSetting("EidssConnectionString", ""));
            EidssUserContext.Init();
            using (var context = EidssUserContext.Instance)
            {
                StatisticHelper helper = new StatisticHelper();
                int             result = helper.Import(PathToTestFolder.Get(TestFolders.Db) + "Data\\StatisticData_Errors.csv", false);
                Assert.AreEqual(0, result);
                //Assert.AreEqual(4, helper.RowsAffected);
                Assert.AreEqual(10, helper.Errors.Count);
                Assert.AreEqual("errMissingField", helper.Errors[0].MessageID);
                Assert.AreEqual(0, helper.Errors[0].LineNumber);
                Assert.AreEqual("errInvalidStatisticType", helper.Errors[1].MessageID);
                Assert.AreEqual(1, helper.Errors[1].LineNumber);
                Assert.AreEqual("errInvalidStatisticValue", helper.Errors[2].MessageID);
                Assert.AreEqual(2, helper.Errors[2].LineNumber);
                Assert.AreEqual("errInvalidDateFormat", helper.Errors[3].MessageID);
                Assert.AreEqual(3, helper.Errors[3].LineNumber);
                Assert.AreEqual("errInvalidYearStartDate", helper.Errors[4].MessageID);
                Assert.AreEqual(4, helper.Errors[4].LineNumber);
                Assert.AreEqual("errInvalidCountry", helper.Errors[5].MessageID);
                Assert.AreEqual(5, helper.Errors[5].LineNumber);
                Assert.AreEqual("errInvalidRegion", helper.Errors[6].MessageID);
                Assert.AreEqual(6, helper.Errors[6].LineNumber);
                Assert.AreEqual("errInvalidRayon", helper.Errors[7].MessageID);
                Assert.AreEqual(7, helper.Errors[7].LineNumber);
                Assert.AreEqual("errInvalidParameter", helper.Errors[8].MessageID);
                Assert.AreEqual(8, helper.Errors[8].LineNumber);
                Assert.AreEqual("errMalFormedCvs", helper.Errors[9].MessageID);
                Assert.AreEqual(9, helper.Errors[9].LineNumber);
                Assert.IsTrue(helper.RowsAffected <= 3);

                result = helper.Import(PathToTestFolder.Get(TestFolders.Db) + "Data\\StatisticData_BadHeader.csv", false);
                Assert.AreEqual(-1, result);
                Assert.AreEqual(1, helper.Errors.Count);
                Assert.AreEqual("errStatisticImportFieldsQty", helper.Errors[0].MessageID);
                Assert.AreEqual(-1, helper.Errors[0].LineNumber);

                result = helper.Import(PathToTestFolder.Get(TestFolders.Db) + "Data\\StatisticData_BadHeader1.csv", false);
                Assert.AreEqual(-1, result);
                Assert.AreEqual(1, helper.Errors.Count);
                Assert.AreEqual("errStatisticImportFieldsQty", helper.Errors[0].MessageID);
                Assert.AreEqual(-1, helper.Errors[0].LineNumber);

                result = helper.Import(PathToTestFolder.Get(TestFolders.Db) + "Data\\StatisticData_Good.csv", false);
                Assert.AreEqual(0, result);
                Assert.AreEqual(9, helper.Errors.Count);
                Assert.AreEqual("errMissingField", helper.Errors[0].MessageID);
                Assert.AreEqual(0, helper.Errors[0].LineNumber);
                Assert.AreEqual("errInvalidStatisticType", helper.Errors[1].MessageID);
                Assert.AreEqual(1, helper.Errors[1].LineNumber);
                Assert.AreEqual("errInvalidStatisticValue", helper.Errors[2].MessageID);
                Assert.AreEqual(2, helper.Errors[2].LineNumber);
                Assert.AreEqual("errInvalidDateFormat", helper.Errors[3].MessageID);
                Assert.AreEqual(3, helper.Errors[3].LineNumber);
                Assert.AreEqual("errInvalidYearStartDate", helper.Errors[4].MessageID);
                Assert.AreEqual(4, helper.Errors[4].LineNumber);
                Assert.AreEqual("errInvalidCountry", helper.Errors[5].MessageID);
                Assert.AreEqual(5, helper.Errors[5].LineNumber);
                Assert.AreEqual("errInvalidRegion", helper.Errors[6].MessageID);
                Assert.AreEqual(6, helper.Errors[6].LineNumber);
                Assert.AreEqual("errInvalidRayon", helper.Errors[7].MessageID);
                Assert.AreEqual(7, helper.Errors[7].LineNumber);
                Assert.AreEqual("errInvalidParameter", helper.Errors[8].MessageID);
                Assert.AreEqual(8, helper.Errors[8].LineNumber);
                Assert.IsTrue(helper.RowsAffected <= 3);
            }
        }
        public UserControl GetUC(StatisticTypes types)
        {
            UserControl UC = null;

            switch (types)
            {
            case StatisticTypes.EquInspectionSticType:
                if (!GetUI(ActivityStep.FreqPlanning))
                {
                    return(null);
                }
                EquInspectionStatisticControl _uc1 = new EquInspectionStatisticControl();
                _uc1.ShowStatisticList = false;
                _uc1.ShowLegend        = false;
                _uc1.StatisticSource   = (StatisticHelper.StatisticEquInspection(CO_IA.Client.RiasPortal.ModuleContainer.Activity.Guid) as IList <EquInspectionStatisticData>).ToList();
                UC     = _uc1;
                UC.Tag = "设备检测统计";
                break;

            case StatisticTypes.FreqAssignStatisticType:
                if (!GetUI(ActivityStep.FreqPlanning))
                {
                    return(null);
                }
                FreqAssignStatisticControl _uc2 = new FreqAssignStatisticControl();
                _uc2.ShowStatisticList = false;
                _uc2.ShowLegend        = false;
                _uc2.StatisticSource   = (StatisticHelper.StatisticFreqAssign(CO_IA.Client.RiasPortal.ModuleContainer.Activity.Guid) as IList <FreqAssignStatisticData>).ToList();
                UC     = _uc2;
                UC.Tag = "频率指配统计";
                break;

            case StatisticTypes.FreqPartPlanStatisticType:
                if (!GetUI(ActivityStep.FreqPlanning))
                {
                    return(null);
                }
                FreqPartPlanStatisticControl _uc3 = new FreqPartPlanStatisticControl();
                _uc3.ShowStatisticList = false;
                _uc3.ShowLegend        = false;
                _uc3.StatisticSource   = (StatisticHelper.StatisticFreqPartPlan(CO_IA.Client.RiasPortal.ModuleContainer.Activity.Guid) as IList <FreqPartPlanStatisticData>).ToList();
                UC     = _uc3;
                UC.Tag = "频率保障方案统计";
                break;

            case StatisticTypes.ORGAndEQUStatisticType:
                if (!GetUI(ActivityStep.FreqPlanning))
                {
                    return(null);
                }
                ORGAndEQUStatisticControl _uc4 = new ORGAndEQUStatisticControl();
                _uc4.ShowStatisticList = false;
                _uc4.ShowLegend        = false;
                System.Collections.IList list = StatisticHelper.StatisticEquipment(CO_IA.Client.RiasPortal.ModuleContainer.Activity.Guid);
                _uc4.StatisticSource = (StatisticHelper.StatisticEquipment(CO_IA.Client.RiasPortal.ModuleContainer.Activity.Guid) as IList <EquStatisticData>).ToList();
                UC     = _uc4;
                UC.Tag = "参保单位统计";
                break;

            case StatisticTypes.SurroundStatStatisticType:
                if (!GetUI(ActivityStep.StationPlanning))
                {
                    return(null);
                }
                RoundStatStatisticControl _uc5 = new RoundStatStatisticControl();
                _uc5.ShowStatisticList = false;
                _uc5.ShowLegend        = false;
                _uc5.StatisticSource   = (StatisticHelper.StatisticSurroundStation(CO_IA.Client.RiasPortal.ModuleContainer.Activity.Guid) as IList <SurroundStatStatisticData>).ToList();
                UC     = _uc5;
                UC.Tag = "周围台站统计";
                break;

            case StatisticTypes.PersonPlanStatisticType:
                if (!GetUI(ActivityStep.StaffPlanning))
                {
                    return(null);
                }
                PersonPlanStatisticControl _uc6 = new PersonPlanStatisticControl();
                _uc6.ShowStatisticList = false;
                _uc6.ShowLegend        = false;
                IList _statisticSource = StatisticHelper.StatisticPersonPlan(CO_IA.Client.RiasPortal.ModuleContainer.Activity.Guid);
                _uc6.PersonPlanStatisticSource = _statisticSource as IList <PersonPlanStatisticData>;
                _uc6.StatisticSource           = _statisticSource;
                UC     = _uc6;
                UC.Tag = "人员预案统计";
                break;

            default:
                return(null);
            }


            return(UC);
        }