Пример #1
0
        // quick submit  -dont care if works or not as sync should capture any fails
        public void SubmitMoodResponse(MoodResponse response)
        {
            if (response != null)
            {
                var app = ApplicationState.Current;

                lock (_lock) {
                    this.Log("Submitting response - " + response.Mood.Name, "", 2);
                    WebServiceJsonRequestStatus status = ServerJsonRequest("SubmitMoodResponse",
                                                                           new SubmitResponseModel()
                    {
                        rid = app.ResponderId,
                        reg = app.ResponderRegion,
                        apn = app.APNSId,
                        r   = new MoodResponseUpdateModel()
                        {
                            i = response.Id,
                            m = response.Mood.Name,
                            t = response.TimeStamp,
                            p = response.Prompt != null ? response.Prompt.Id : null
                        }
                    });
                }
            }
        }
Пример #2
0
        public MoodResponseColumnView(int columnIndex, MoodResponse response)
            : base(columnIndex)
        {
            this.Response = response;

            this.backgroundImage.Image = Resources.GetMoodResponseTimelineImage(response.Mood);

            if (this.Response.Mood.MoodType == MoodType.Positive)
            {
                this.timeLabel  = new UILabel(new RectangleF(20, 357, 100, 21));
                this.titleLabel = new UILabel(new RectangleF(17, 380, 106, 50));
            }
            else
            {
                this.titleLabel = new UILabel(new RectangleF(18, 128, 106, 50));
                this.timeLabel  = new UILabel(new RectangleF(20, 180, 100, 22));
            }
            this.timeLabel.Font               = UIFont.FromName("HelveticaNeue-CondensedBold", 16.0f);
            this.timeLabel.TextColor          = UIColor.White;
            this.timeLabel.BackgroundColor    = UIColor.Clear;
            this.timeLabel.Text               = response.TimeStamp.ToLocalTime(ApplicationState.Current.EventTimeOffset).ToString("H:mm");
            this.timeLabel.TextAlignment      = UITextAlignment.Center;
            this.timeLabel.BaselineAdjustment = UIBaselineAdjustment.AlignBaselines;
            this.Add(this.timeLabel);

            this.titleLabel.Font               = UIFont.FromName("HelveticaNeue-CondensedBold", 16.0f);
            this.titleLabel.TextColor          = UIColor.White;
            this.titleLabel.BackgroundColor    = UIColor.Clear;
            this.titleLabel.Text               = response.Prompt == null ? "My Mood" : response.Prompt.Title;
            this.titleLabel.TextAlignment      = UITextAlignment.Center;
            this.titleLabel.BaselineAdjustment = UIBaselineAdjustment.AlignBaselines;
            this.Add(this.titleLabel);
        }
Пример #3
0
 protected IEnumerable <MoodResponseUpdateModel> GetResponsesToSaveToServer(DateTime?lastSyncDate)
 {
     return(MoodResponse.GetConfirmedResponses().Where(r => lastSyncDate == null || r.CreatedOn > lastSyncDate.Value)
            .Select(r => new MoodResponseUpdateModel()
     {
         i = r.Id,
         t = r.TimeStamp,
         m = r.Mood.Name,
         p = r.Prompt == null ? null : r.Prompt.Id
     }).ToList());
 }
Пример #4
0
        public void ShowSnapshot(DateTime?snapshotTime)
        {
            Console.WriteLine("Show snapshot in chart view");
            if (snapshotTime != null)
            {
                this.ShowPosition(snapshotTime);
                Console.WriteLine("showed position");
                var eventNow = MoodResponse.GetRoundedResponseTime(DateTime.UtcNow.ToLocalTime(this.eventTimeOffset));
                Console.WriteLine("got event now");
                var roundedSnapshotTime = MoodResponse.GetRoundedResponseTime(snapshotTime.Value);
                Console.WriteLine("got roundedSnapshotTime");
                if (snapshotTime.Value <= eventNow)
                {
                    var sameSnapshot = IsCurrentSnapshotValid(roundedSnapshotTime);
                    Console.WriteLine("got iscurrentsnapshot");
                    var snapshot = sameSnapshot ? this.currentSnapshot : ReportManager.GetClosestSnapshot(report, roundedSnapshotTime);
                    Console.WriteLine("got closest snapshot : {0}", sameSnapshot);
                    this.lastRefresh = DateTime.Now;
                    if (snapshot != null)
                    {
                        Console.WriteLine("got snapshot");
                        if (this.currentSnapshot == null || snapshot.Id != this.currentSnapshot.Id)
                        {
                            Console.WriteLine("new snapshot");
                            this.currentSnapshot = snapshot;
                            if (this.chart == null)
                            {
                                Console.WriteLine("lets build chart");
                                this.BuildChart(snapshotTime);
                            }
                            else
                            {
                                Console.WriteLine("lets refresh chart");
                                this.RefreshChart(snapshotTime);
                            }
                            this.lastSnapshotTime = roundedSnapshotTime;
                        }
                        this.chart.Hidden = false;
                        this.Hidden       = false;

                        return;
                    }
                    this.currentSnapshot  = null;
                    this.lastSnapshotTime = null;
                }
                else
                {
                    return;
                }
            }
            this.Hidden = true;
        }
Пример #5
0
 protected WebServiceJsonRequestStatus SendSyncRequest(ApplicationState app, IEnumerable <MoodResponseUpdateModel> responsesToUpdate)
 {
     return(ServerJsonRequest("SyncData",
                              new UpdateServiceFromAppModel()
     {
         rid = app.ResponderId,
         reg = app.ResponderRegion,
         apn = app.APNSId,
         Responses = responsesToUpdate,
         ResTotal = MoodResponse.GetConfirmedResponseCount(),
         LastUpdate = app.LastSuccessfulServiceUpdate
     }));
 }
Пример #6
0
        protected void SyncPrompts(IEnumerable <MoodPromptModel> prompts)
        {
            if (prompts != null)
            {
                var delete = MoodPrompt.List().Where(mp => !prompts.Any(p => p.Id == mp.Id)).ToList();
                foreach (var p in delete)
                {
                    var r = p.Response;
                    if (p.Response.Mood == null)
                    {
                        r.Delete();
                    }
                    else
                    {
                        r.Prompt = null;
                        r.Save();
                    }
                    p.Delete();
                }
                foreach (var p in prompts)
                {
                    MoodPrompt prompt = MoodPrompt.ReadSafe(p.Id);
                    if (prompt == null)
                    {
                        prompt    = MoodPrompt.New();
                        prompt.Id = p.Id.ToString();
                        prompt.Save();

                        MoodResponse response = MoodResponse.New();
                        response.Id        = System.Guid.NewGuid().ToString();
                        response.Prompt    = prompt;
                        response.TimeStamp = p.Activity.TimeStamp;
                        response.Save();
                    }
                    prompt.Name               = p.Name;
                    prompt.NotificationText   = p.NotificationText;
                    prompt.Title              = p.Activity.Title;
                    prompt.TimeStamp          = p.Activity.TimeStamp;
                    prompt.ActiveFrom         = p.ActiveFrom;
                    prompt.ActiveTil          = p.ActiveTil;
                    prompt.Response.TimeStamp = prompt.TimeStamp;
                    prompt.Response.Save();
                    prompt.Save();
                }
            }
        }
Пример #7
0
        protected MoodSnaphotReportModel GetSnapshot(MoodCategory category, DateTime timeOfSnapshot, bool includeMoodInfo, int roundPercentagesToNPlaces)
        {
            var moodIsStale = category.Event.ApplicationConfig.ReportMoodIsStaleMins;

            timeOfSnapshot = MoodResponse.GetRoundedResponseTime(timeOfSnapshot);
            var staleTime = timeOfSnapshot.AddMinutes(-(moodIsStale));
            var snapshot  = this.db.Get <Snapshot>().Where(s => s.Category.Id == category.Id && s.TimeStamp <= timeOfSnapshot && s.TimeStamp >= staleTime).OrderByDescending(s => s.TimeStamp).Select(s => s.TimeStamp).FirstOrDefault();

            if (snapshot == DateTime.MinValue)
            {
                return(GetDefaultSnapshot(category, timeOfSnapshot, includeMoodInfo));
            }
            var snapshotsAt    = this.db.Get <Snapshot>().Where(s => s.TimeStamp == snapshot).OrderBy(s => s.Mood.DisplayIndex);
            var allMoods       = this.db.Get <Mood>().Where(m => m.Category.Id == category.Id).OrderBy(m => m.DisplayIndex);
            var totalResponses = snapshotsAt.Sum(r => r.ResponseCount);

            return(new MoodSnaphotReportModel()
            {
                t = snapshot,
                r = totalResponses,
                d = snapshotsAt.Select(r => new MoodSnapshotDataModel()
                {
                    c = r.ResponseCount,
                    i = r.Mood.DisplayIndex,
                    p = Math.Round(((decimal)r.ResponseCount / (decimal)totalResponses) * 100M, roundPercentagesToNPlaces)
                }),
                m = includeMoodInfo ?
                    allMoods.ToList().Select(m => new MoodModel()
                {
                    Id = m.Id,
                    DisplayIndex = m.DisplayIndex,
                    DisplayColor = m.DisplayColor,
                    Name = m.Name,
                    MoodType = m.MoodType
                })
                                       : null
            });
        }
Пример #8
0
        private void GenerateTimelineColumns()
        {
            Console.WriteLine("Generating timeline");


            //Console.WriteLine("Get current prompt");

            var currentPrompt = MoodPrompt.GetCurrentPrompt();

            //Console.WriteLine("Get unprompted responses");

            var responses = MoodResponse.OrderedList("TimeStamp", "TimeStamp <= @Now", new{ Now = DateTime.UtcNow }).ToList();

            //Console.WriteLine("Got responses");

            timelineColumns = new List <TimelineColumnView> ();
            int index = 0;

            StartDate = responses.Any()
                                ? responses.First().TimeStamp.ToLocalTime(ApplicationState.Current.EventTimeOffset).Date
                                        : DateTime.UtcNow.ToLocalTime(ApplicationState.Current.EventTimeOffset).Date;
            var date = StartDate;

            timelineColumns.Add(new DayMarkerColumnView(index, StartDate, 1));
            index++;


            foreach (var i in responses)
            {
                //Console.WriteLine("Add column - " + i.TimeStamp.ToString());
                if (i.TimeStamp.Date > date)
                {
                    date = i.TimeStamp.Date;
                    var dayIndex = date.Subtract(StartDate).Days + 1;
                    timelineColumns.Add(new DayMarkerColumnView(index, date, dayIndex));
                }
                if (i.Mood == null)
                {
                    if (i.Prompt != null)
                    {
                        var respondToPromptCol = new MoodPromptColumnView(index, i.Prompt);
                        respondToPromptCol.AddNewMood += (object sender, AddNewResponseEventArgs e) => {
                            if (this.AddNewMood != null)
                            {
                                AddNewMood(sender, e);
                            }
                        };
                        timelineColumns.Add(respondToPromptCol);
                    }
                }
                else
                {
                    timelineColumns.Add(new MoodResponseColumnView(index, i));
                }
                index++;
            }

            var addNewMoodCol = new AddResponseColumnView(index, currentPrompt == null ? null : currentPrompt);

            addNewMoodCol.AddNewMood += (object sender, AddNewResponseEventArgs e) => {
                if (this.AddNewMood != null)
                {
                    AddNewMood(sender, e);
                }
            };
            timelineColumns.Add(addNewMoodCol);

            Console.WriteLine("Timline columns done");
        }
Пример #9
0
 public MyMoodSetEventArgs(MoodResponse moodResponse) : base()
 {
     this.MoodResponse = moodResponse;
 }
Пример #10
0
        protected GlobalMoodReportModel GetGlobalMoodReport(Event evnt, MoodCategory cat, DateTime reportStart, DateTime reportEnd, int moodIsStaleMins, bool includeActivities, int roundPercentagesToNPlaces)
        {
            var moods = this.db.Get <Mood>().Where(m => m.Category.Id == cat.Id);

            // get last previous snapshot
            var roundedReportEnd = MoodResponse.GetRoundedResponseTime(reportEnd);


            var snapshots = (from s in this.db.Get <Snapshot>()
                             where s.Category.Id == cat.Id &&
                             s.Category.Id == cat.Id && s.TimeStamp >= reportStart && s.TimeStamp <= roundedReportEnd
                             group s by s.TimeStamp into sg
                             select new MoodSnaphotReportModel()
            {
                t = sg.Key,
                r = sg.Sum(r => r.ResponseCount),
                d = sg.Select(r => new MoodSnapshotDataModel()
                {
                    c = r.ResponseCount,
                    i = r.Mood.DisplayIndex,
                    p = Math.Round(((decimal)r.ResponseCount / (decimal)sg.Sum(sgr => sgr.ResponseCount)) * 100M, roundPercentagesToNPlaces)
                })
            }).OrderBy(s => s.t).ToList();

            var first = snapshots.FirstOrDefault();

            if (first == null || first.t != reportStart)
            {
                var startSnapTime = (from s in this.db.Get <Snapshot>()
                                     where s.Category.Id == cat.Id &&
                                     s.Category.Id == cat.Id && s.TimeStamp < reportStart
                                     orderby s.TimeStamp descending
                                     select s.TimeStamp).FirstOrDefault();
                if (startSnapTime != DateTime.MinValue && startSnapTime >= reportStart.AddMinutes(-(evnt.ApplicationConfig.ReportMoodIsStaleMins)))
                {
                    var startSnap = (from s in this.db.Get <Snapshot>()
                                     where s.Category.Id == cat.Id &&
                                     s.Category.Id == cat.Id && s.TimeStamp == startSnapTime
                                     group s by s.TimeStamp into sg
                                     select new MoodSnaphotReportModel()
                    {
                        //t = sg.Key,
                        t = reportStart,
                        r = sg.Sum(r => r.ResponseCount),
                        d = sg.Select(r => new MoodSnapshotDataModel()
                        {
                            c = r.ResponseCount,
                            i = r.Mood.DisplayIndex,
                            p = Math.Round(((decimal)r.ResponseCount / (decimal)sg.Sum(sgr => sgr.ResponseCount)) * 100M, roundPercentagesToNPlaces)
                        })
                    }).Single();
                    snapshots.Insert(0, startSnap);
                }
                else
                {
                    var allMoods = this.db.Get <Mood>().Where(m => m.Category.Event.Id == evnt.Id).OrderBy(m => m.DisplayIndex).ToList();
                    snapshots.Insert(0, new MoodSnaphotReportModel()
                    {
                        t = reportStart,
                        r = 0,
                        d = allMoods.Select(m => new MoodSnapshotDataModel()
                        {
                            c = 0,
                            i = m.DisplayIndex,
                            p = Math.Round(100M / (decimal)allMoods.Count(), roundPercentagesToNPlaces)
                        })
                    });
                }
            }


            var prompts = this.db.Get <MoodPrompt>().Where(p => p.Event.Id == evnt.Id && p.Activity.TimeStamp >= reportStart && p.Activity.TimeStamp <= reportEnd).OrderBy(p => p.Activity.TimeStamp);


            var activities = from a in this.db.Get <Activity>()
                             join p in prompts on a.Id equals p.Activity.Id into ga
                             from pa in ga.DefaultIfEmpty()
                             select new { Activity = a, HasPrompt = pa != null };



            var model = new GlobalMoodReportModel()
            {
                Snapshots = snapshots,
                Prompts   = includeActivities ? prompts.Select(p => new GlobalActivityModel()
                {
                    Id        = p.Id,
                    Title     = p.Activity.Title,
                    TimeStamp = p.Activity.TimeStamp
                }).ToList() : null,
                Activities = includeActivities ? activities.Where(a => a.HasPrompt == false).Select(e => new GlobalActivityModel()
                {
                    Id        = e.Activity.Id,
                    Title     = e.Activity.Title,
                    TimeStamp = e.Activity.TimeStamp
                }).ToList() : null,
                Moods = moods.Select(m => new MoodModel()
                {
                    Id           = m.Id,
                    Name         = m.Name,
                    DisplayColor = m.DisplayColor,
                    DisplayIndex = m.DisplayIndex,
                    MoodType     = m.MoodType
                }).ToList()
            };

            return(model);
        }
Пример #11
0
        private void SetMyMood()
        {
            Console.WriteLine("Set my mood");
            var mood = Mood.Read(currentMood.Id);

            Console.WriteLine("Setting my mood to " + mood.Name);
            MoodResponse response = MoodResponse.New();

            if (CurrentPrompt == null)
            {
                response.Id        = System.Guid.NewGuid().ToString();
                response.TimeStamp = DateTime.UtcNow;
            }
            else
            {
                response = CurrentPrompt.Response;
            }
            response.Mood      = mood;
            response.CreatedOn = DateTime.UtcNow;
            response.Save();
            Console.WriteLine("Mood response saved");
            var app = ApplicationState.Current;

            if (app.RunningMode != RunningMode.Normal)
            {
                app.RunningMode = RunningMode.Normal;
                app.Save();
            }

            MyMoodLogger.Current.Log("Mood Response - " + mood.Name, CurrentPrompt == null ? "No prompt" : "Prompt: " + CurrentPrompt.Title, 2);

            //NSNotificationCenter.DefaultCenter.PostNotificationName("SyncDataAndNotifications",null);
            Console.WriteLine("Lets create a thread for pushing response");



            System.Threading.Tasks.Task.Factory.StartNew(() => {
                //NSTimer.CreateScheduledTimer (5, delegate {
                Console.WriteLine("Submit response to server");
                MyMoodService.Current.SubmitMoodResponse(response);
                Console.WriteLine("Mood response submitted");
                //});
            });


            if (CurrentPrompt != null)
            {
                Console.WriteLine("Cancel notification");
                //if we have gone vie the timeline then we need to cancel the prompt so the user doesn't select it again from the notification drop down
                NotificationManager.CancelLocalNotification(CurrentPrompt);

                Console.WriteLine("Update badge numbers");
                //decrease mood prompt badges
                UIApplication.SharedApplication.ApplicationIconBadgeNumber = MoodPrompt.GetOutstandingPrompts().Count();
                //UIApplication.SharedApplication.ApplicationIconBadgeNumber = UIApplication.SharedApplication.ApplicationIconBadgeNumber -1;
            }

            CurrentPrompt = null;

            Console.WriteLine("Done with setting mood - navigate back");
            this.NavigationController.PopViewControllerAnimated(true);
        }
Пример #12
0
        protected static void ProcessQueuedMoodResponseWorkItems()
        {
            var db     = DependencyResolver.Current.GetService <IDomainDataContext>() as System.Data.Entity.DbContext;
            var logger = DependencyResolver.Current.GetService <ILogger>();

            MoodResponseWorkItem workItem;

            try
            {
                // try and process as many submissions as we can with a single db context
                while (responseSubmissionQueue.TryDequeue(out workItem))
                {
                    //var evnt = db.Get<Event>().FirstOrDefault(e => e.Name.Equals(workItem.EventName, StringComparison.InvariantCultureIgnoreCase));
                    //if (evnt == null) throw new ArgumentException("Invalid event");

                    //var responder = evnt.AddResponder(new Guid(workItem.ResponderId), workItem.Submission.reg, workItem.Submission.apn);

                    foreach (var moodResponse in workItem.MoodResponses)
                    {
                        var processingStartTime = DateTime.UtcNow;

                        try
                        {
                            logger.Info("App", string.Format("Request to set new mood response - mood=[{0}] responder=[{1}] responseId=[{2}]", moodResponse.m, workItem.ResponderId, moodResponse.i));

                            db.Database.ExecuteSqlCommand("exec SubmitResponse {0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}",
                                                          workItem.EventName,
                                                          workItem.ResponderId,
                                                          workItem.Region,
                                                          workItem.DeviceId,
                                                          moodResponse.i,
                                                          moodResponse.m,
                                                          moodResponse.p,
                                                          moodResponse.t,
                                                          MoodResponse.GetRoundedResponseTime(moodResponse.t)
                                                          );

                            //if (workItem.Submission.r != null)
                            //{
                            //    logger.Info("App", string.Format("Request to set new mood response - mood=[{0}] responder=[{1}] responseId=[{2}]", workItem.Submission.r.m, workItem.Submission.rid, workItem.Submission.r.i));

                            //    Guid responseId;
                            //    if (!Guid.TryParse(workItem.Submission.r.i, out responseId)) throw new ArgumentException("Invalid response = id is not a Guid");

                            //    var mood = evnt.MoodCategories.SelectMany(mc => mc.Moods).FirstOrDefault(m => m.Name.Equals(workItem.Submission.r.m, StringComparison.InvariantCultureIgnoreCase));
                            //    //var mood = db.Get<Mood>().FirstOrDefault(m => m.Category.Event.Id == evnt.Id && m.Name.Equals(workItem.Submission.r.m, StringComparison.InvariantCultureIgnoreCase));
                            //    if (mood == null) throw new ArgumentException("Invalid mood");

                            //    var prompt = string.IsNullOrWhiteSpace(workItem.Submission.r.p) ? null : evnt.MoodPrompts.FirstOrDefault(p => p.Id == new Guid(workItem.Submission.r.p));
                            //    //var prompt = string.IsNullOrWhiteSpace(workItem.Submission.r.p) ? null : db.Get<MoodPrompt>().FirstOrDefault(p => p.Id == new Guid(workItem.Submission.r.p));

                            //    responder.AddResponse(responseId, mood, workItem.Submission.r.t, prompt);
                            //}

                            //db.SaveChanges();
                        }
                        catch (Exception ex)
                        {
                            logger.Error("App", ex, string.Format("Failed submitting response - responder=[{0}]  error=[{1}] model=[{2}]", workItem.ResponderId, ex.Message, moodResponse.m));
                        }

                        System.Diagnostics.Debug.WriteLine(string.Format("Thread {0} processed submission from {1} in {2}ms", System.Threading.Thread.CurrentThread.ManagedThreadId, workItem.ResponderId, DateTime.UtcNow.Subtract(processingStartTime).TotalMilliseconds));
                    }
                }

                System.Diagnostics.Debug.WriteLine(string.Format("Thread {0} found no more work items", System.Threading.Thread.CurrentThread.ManagedThreadId));
            }
            finally
            {
                new StructureMap.Pipeline.HybridLifecycle().FindCache().DisposeAndClear();
            }
        }