public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            timeLoggingController = TimeLoggingController.GetInstance();
            stateHandler          = new StateChangedEventHandler(timeLoggingStateChanged);

            activityView                  = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.WhiteLarge);
            activityView.Frame            = View.Frame;
            activityView.BackgroundColor  = UIColor.FromRGBA(0, 0, 0, 0.6f);
            activityView.Center           = View.Center;
            activityView.HidesWhenStopped = true;
            View.AddSubview(activityView);

            completeBtn.TouchUpInside += delegate
            {
                newCompleteDatePicker();
                completedDateText.BecomeFirstResponder();
            };

            projectNameBtn.TitleLabel.TextAlignment             = UITextAlignment.Center;
            projectNameBtn.TitleLabel.Lines                     = 2;
            projectNameBtn.TitleLabel.AdjustsFontSizeToFitWidth = true;

            taskNameBtn.TitleLabel.TextAlignment             = UITextAlignment.Center;
            taskNameBtn.TitleLabel.Lines                     = 3;
            taskNameBtn.TitleLabel.AdjustsFontSizeToFitWidth = true;

            projectNameBtn.TouchUpInside += ProjectNameBtnOnClick;
            taskNameBtn.TouchUpInside    += TaskNameBtnOnClick;
            pauseBtn.TouchUpInside       += PauseBtnOnClick;
            playBtn.TouchUpInside        += PlayBtnOnClick;
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            if (task == null)
            {
                return;
            }

            timeLoggingController = TimeLoggingController.GetInstance();
            stateHandler          = new StateChangedEventHandler(timeLoggingStateChanged);

            if (NavigationController.NavigationBar.TopItem.Title.Equals("Process Dashboard"))
            {
                NavigationController.NavigationBar.TopItem.Title = "Back";
            }

            TdPlayBtn.TouchUpInside  += PlayBtnOnClick;
            TdPauseBtn.TouchUpInside += PauseBtnOnClick;
            refreshControlButtons();

            TdCheckboxBtn.TouchUpInside += delegate
            {
                ((TaskDetailTableSource)PlanTable.Source).completeDateText.BecomeFirstResponder();
            };

            tdProjectNameBtn.SetTitle(task.Project != null ? task.Project.Name : "", UIControlState.Normal);
            tdProjectNameBtn.SetTitleColor(UIColor.Black, UIControlState.Normal);
            TdTaskNameLb.Text = task.FullName ?? "";

            TdNotesTf.Layer.BorderColor  = UIColor.LightGray.CGColor;
            TdNotesTf.Layer.BorderWidth  = 2.0f;
            TdNotesTf.Layer.CornerRadius = 10.0f;
            TdNotesTf.Text = task.Note ?? "";

            PlanTable.Source = new TaskDetailTableSource(task, this);
            View.AddSubview(PlanTable);
        }
Ejemplo n.º 3
0
        private async void AddData(View view)
        {
            var projectName  = view.FindViewById <TextView>(Resource.Id.TaskDetails_ProjectName);
            var taskName     = view.FindViewById <TextView>(Resource.Id.TaskDetails_TaskName);
            var notes        = view.FindViewById <EditText>(Resource.Id.TaskDetails_Notes);
            var timeinfo     = view.FindViewById <ListView>(Resource.Id.TaskDetails_TimeInfo);
            var taskComplete = view.FindViewById <CheckBox>(Resource.Id.TaskDetails_TaskComplete);

            if (_completionDate.HasValue)
            {
                taskComplete.Checked = true;
            }

            _play  = view.FindViewById <Button>(Resource.Id.TaskDetails_Play);
            _pause = view.FindViewById <Button>(Resource.Id.TaskDetails_Pause);

            Debug.WriteLine("We are in the begining ");
            if (TimeLoggingController.GetInstance().IsTimerRunning() && TimeLoggingController.GetInstance().GetTimingTaskId().Equals(_taskId))
            {
                ModifyPlayPauseState(true);
            }
            var pb = new ProgressDialog(_mActivity)
            {
                Indeterminate = true
            };

            pb.SetTitle("Loading");
            pb.SetCanceledOnTouchOutside(false);
            if (_taskName != null)
            {
                taskName.Text = _taskName;
            }

            if (_projectName != null)
            {
                projectName.Text = _projectName;
            }

            Debug.WriteLine(" 0 ");
            Entry[] output = new Entry[3];

            output[0] = new Entry();
            output[1] = new Entry();
            output[2] = new Entry();

            output[0].name = "Planned Time";

            if (_estimatedTime.HasValue)
            {
                Debug.WriteLine("We have a value in estimated time");
                output[0].value = "" + TimeSpan.FromMinutes(_estimatedTime.Value).ToString(@"hh\:mm");
            }
            else
            {
                Debug.WriteLine("No value in estimated time");
                output[0].value = "";
            }
            Debug.WriteLine(" 1 ");


            output[1].name = "Actual Time";
            if (_actualTime.HasValue)
            {
                output[1].value = "" + TimeSpan.FromMinutes(_actualTime.Value).ToString(@"hh\:mm");
            }
            else
            {
                output[1].value = "";
            }

            output[2].name = "Completion Date";
            Debug.WriteLine(" 2 ");
            if (_completionDate.HasValue)
            {
                output[2].value = Util.GetInstance().GetLocalTime(_completionDate.Value).ToShortDateString();
            }
            else
            {
                output[2].value = "-";
            }

            var listAdapter = new TaskDetailsAdapter(Activity, Resource.Layout.TimeLogEntryListItem,
                                                     output);


            Debug.WriteLine("We have reached the end ");

            timeinfo.Adapter = listAdapter;

            pb.Show();
            Task taskDetail = null;

            try

            {
                // Get data from server
                taskDetail = await((MainActivity)Activity).Ctrl.GetTask(AccountStorage.DataSet, _taskId);

                _play.Click += (sender, args) =>
                {
                    Debug.WriteLine("Play Clicked");

                    //var timerServiceIntent = new Intent("com.tumasolutions.processdashboard.TimerService");

                    //var timerServiceConnection = new TimerServiceConnection((MainActivity)this.Activity);

                    //Activity.ApplicationContext.BindService(timerServiceIntent, timerServiceConnection, Bind.AutoCreate);
                    Intent intent = new Intent(Activity, typeof(TimerService));
                    intent.PutExtra("taskId", taskDetail.Id);
                    Activity.StartService(intent);
                };



                _pause.Click += (sender, args) =>
                {
                    Debug.WriteLine("Pause Clicked");
                    Activity.StopService(new Intent(Activity, typeof(TimerService)));
                    Toast.MakeText(this.Activity, "Time Log Entry Saved", ToastLength.Short).Show();
                };

                projectName.Click += (obj, args) =>
                {
                    var projectId   = taskDetail.Project.Id;
                    var projectname = taskDetail.Project.Name;

                    ((MainActivity)Activity).ListOfProjectsCallback(projectId, projectname);
                };
            }
            catch (CannotReachServerException)
            {
                if (pb.IsShowing)
                {
                    pb.Dismiss();
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                builder.SetTitle("Unable to Connect")
                .SetMessage("Please check your network connection and try again")
                .SetNeutralButton("Okay", (sender, args) =>
                {
                    builder.Dispose();
                    ((MainActivity)Activity).FragmentManager.PopBackStack();
                })
                .SetCancelable(false);
                AlertDialog alert = builder.Create();
                alert.Show();
            }
            catch (WebException we)
            {
                if (we.Status == WebExceptionStatus.ProtocolError)
                {
                    var response = we.Response as HttpWebResponse;
                    if (response != null)
                    {
                        Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
                        if (response.StatusCode == HttpStatusCode.Forbidden)
                        {
                            try
                            {
                                if (pb.IsShowing)
                                {
                                    pb.Dismiss();
                                }
                                Toast.MakeText(this.Activity, "Username and password error.", ToastLength.Long).Show();
                                AccountStorage.ClearStorage();
                                Activity.FragmentManager.PopBackStack(null, PopBackStackFlags.Inclusive);
                                ((MainActivity)(Activity)).SetDrawerState(false);
                                ((MainActivity)(Activity)).SwitchToFragment(MainActivity.FragmentTypes.Login);
                            }
                            catch (System.Exception e)
                            {
                                System.Diagnostics.Debug.WriteLine("We encountered an error :" + e.Message);
                            }
                        }
                    }
                    else
                    {
                        // no http status code available
                        Toast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show();
                    }
                }
                else
                {
                    // no http status code availableToast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show();
                }
            }
            catch (StatusNotOkayException se)
            {
                if (pb.IsShowing)
                {
                    pb.Dismiss();
                }

                AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                builder.SetTitle("An Error has occured")
                .SetMessage("Error :" + se.GetMessage())
                .SetNeutralButton("Okay", (sender, args) =>
                {
                    builder.Dispose();
                })
                .SetCancelable(false);
                AlertDialog alert = builder.Create();
                alert.Show();
            }
            catch (Exception e)
            {
                // For any other weird exceptions
                if (pb.IsShowing)
                {
                    pb.Dismiss();
                }

                AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                builder.SetTitle("An Error has occured")
                .SetNeutralButton("Okay", (sender, args) =>
                {
                    builder.Dispose();
                })
                .SetMessage("Error :" + e.Message)
                .SetCancelable(false);
                AlertDialog alert = builder.Create();
                alert.Show();
            }
            if (taskDetail == null)
            {
                Debug.WriteLine("T is null");
            }

            if (taskDetail != null)
            {
                projectName.Text = taskDetail.Project.Name;

                timeinfo.ItemClick += (sender, args) =>
                {
                    if (args.Position == 0)
                    {
                        LinearLayout ll = new LinearLayout(Activity);
                        ll.Orientation = (Orientation.Horizontal);

                        NumberPicker aNumberPicker = new NumberPicker(Activity);
                        aNumberPicker.MaxValue = (100);
                        aNumberPicker.MinValue = (0);

                        double temp;

                        temp = taskDetail.EstimatedTime;


                        aNumberPicker.Value = TimeSpan.FromMinutes(temp).Hours;

                        NumberPicker aNumberPickerA = new NumberPicker(Activity)
                        {
                            MaxValue = (59),
                            MinValue = (0),
                            Value    = TimeSpan.FromMinutes(temp).Minutes
                        };


                        LinearLayout.LayoutParams parameters = new LinearLayout.LayoutParams(50, 50);
                        parameters.Gravity = GravityFlags.Center;

                        LinearLayout.LayoutParams numPicerParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
                        numPicerParams.Weight = 1;

                        LinearLayout.LayoutParams qPicerParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
                        qPicerParams.Weight = 1;

                        ll.LayoutParameters = parameters;
                        ll.AddView(aNumberPicker, numPicerParams);
                        ll.AddView(aNumberPickerA, qPicerParams);

                        //((TaskDetailsAdapter)(timeinfo.Adapter)).GetEntry()


                        //var ts = DateTime.ParseExact("", "HH.mm", CultureInfo.InvariantCulture);

                        AlertDialog.Builder np = new AlertDialog.Builder(Activity).SetView(ll);

                        np.SetTitle("Update Planned Time");
                        np.SetNegativeButton("Cancel", (s, a) =>
                        {
                            np.Dispose();
                        });
                        np.SetPositiveButton("Ok", (s, a) =>
                        {
                            //Update Planned Time
                            string number = aNumberPicker.Value.ToString("D2") + ":" + aNumberPickerA.Value.ToString("D2");
                            Debug.WriteLine(number);
                            double val = Convert.ToDouble(TimeSpan.ParseExact(number, @"hh\:mm", CultureInfo.InvariantCulture).TotalMinutes);
                            Debug.WriteLine("The updated val is :" + val);
                            try
                            {
                                ((MainActivity)(Activity)).Ctrl.UpdateATask(AccountStorage.DataSet,
                                                                            _taskId, val, null, false);
                            }
                            catch (CannotReachServerException)
                            {
                                AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                                builder.SetTitle("Unable to Connect")
                                .SetMessage("Please check your network connection and try again")
                                .SetNeutralButton("Okay", (sender2, args2) =>
                                {
                                    builder.Dispose();
                                    ((MainActivity)Activity).FragmentManager.PopBackStack();
                                })
                                .SetCancelable(false);
                                AlertDialog alert = builder.Create();
                                alert.Show();
                            }
                            catch (WebException we)
                            {
                                if (we.Status == WebExceptionStatus.ProtocolError)
                                {
                                    var response = we.Response as HttpWebResponse;
                                    if (response != null)
                                    {
                                        Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
                                        if (response.StatusCode == HttpStatusCode.Forbidden)
                                        {
                                            try
                                            {
                                                if (pb.IsShowing)
                                                {
                                                    pb.Dismiss();
                                                }
                                                Toast.MakeText(this.Activity, "Username and password error.", ToastLength.Long).Show();
                                                System.Diagnostics.Debug.WriteLine("We are about to logout");
                                                AccountStorage.ClearStorage();
                                                System.Diagnostics.Debug.WriteLine("Main Activity is :" + Activity == null);
                                                System.Diagnostics.Debug.WriteLine("Items in the backstack :" + Activity.FragmentManager.BackStackEntryCount);
                                                System.Diagnostics.Debug.WriteLine("Main Activity is :" + Activity == null);
                                                Activity.FragmentManager.PopBackStack(null, PopBackStackFlags.Inclusive);
                                                System.Diagnostics.Debug.WriteLine("Items in the backstack 2 :" + Activity.FragmentManager.BackStackEntryCount);
                                                ((MainActivity)(Activity)).SetDrawerState(false);
                                                ((MainActivity)(Activity)).SwitchToFragment(MainActivity.FragmentTypes.Login);
                                            }
                                            catch (System.Exception e)
                                            {
                                                System.Diagnostics.Debug.WriteLine("We encountered an error :" + e.Message);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        // no http status code available
                                        Toast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show();
                                    }
                                }
                                else
                                {
                                    // no http status code availableToast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show();
                                }
                            }
                            catch (StatusNotOkayException se)
                            {
                                AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                                builder.SetTitle("An Error has occured")
                                .SetMessage("Error :" + se.GetMessage())
                                .SetNeutralButton("Okay", (sender2, args2) =>
                                {
                                    builder.Dispose();
                                })
                                .SetCancelable(false);
                                AlertDialog alert = builder.Create();
                                alert.Show();
                            }
                            catch (Exception e)
                            {
                                // For any other weird exceptions


                                AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                                builder.SetTitle("An Error has occured")
                                .SetNeutralButton("Okay", (sender2, args2) =>
                                {
                                    builder.Dispose();
                                })
                                .SetMessage("Error :" + e.Message)
                                .SetCancelable(false);
                                AlertDialog alert = builder.Create();
                                alert.Show();
                            }
                            output[0].value = TimeSpan.FromMinutes(val).ToString(@"hh\:mm");

                            listAdapter = new TaskDetailsAdapter(Activity, Resource.Layout.TimeLogEntryListItem,
                                                                 output);
                            Debug.WriteLine("We have changed content ");
                            timeinfo.Adapter = listAdapter;

                            Toast.MakeText(_mActivity, "Planned Time Updated", ToastLength.Short).Show();
                            np.Dispose();
                        });
                        np.Show();
                        //Planned Time
                    }
                    else if (args.Position == 1)
                    {
                        //Actual Time
                        ((MainActivity)Activity).PassTimeLogInfo(taskDetail.Id, taskDetail.Project.Name,
                                                                 taskDetail.FullName);
                    }
                    else if (args.Position == 2)
                    {
                        // Completion Date


                        DatePickerFragment frag = DatePickerFragment.NewInstance(delegate(DateTime time)
                        {
                            Debug.WriteLine("The received date is :" + time.ToShortDateString());

                            output[2].value = time.ToShortDateString();

                            listAdapter = new TaskDetailsAdapter(Activity, Resource.Layout.TimeLogEntryListItem,
                                                                 output);
                            Debug.WriteLine("We have changed content ");
                            timeinfo.Adapter = listAdapter;

                            try
                            {
                                ((MainActivity)(Activity)).Ctrl.UpdateATask(AccountStorage.DataSet,
                                                                            _taskId, null, Util.GetInstance().GetServerTime(time), false);
                            }
                            catch (CannotReachServerException)
                            {
                                AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                                builder.SetTitle("Unable to Connect")
                                .SetMessage("Please check your network connection and try again")
                                .SetNeutralButton("Okay", (sender2, args2) =>
                                {
                                    builder.Dispose();
                                    ((MainActivity)Activity).FragmentManager.PopBackStack();
                                })
                                .SetCancelable(false);
                                AlertDialog alert = builder.Create();
                                alert.Show();
                            }
                            catch (WebException we)
                            {
                                if (we.Status == WebExceptionStatus.ProtocolError)
                                {
                                    var response = we.Response as HttpWebResponse;
                                    if (response != null)
                                    {
                                        Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
                                        if (response.StatusCode == HttpStatusCode.Forbidden)
                                        {
                                            try
                                            {
                                                if (pb.IsShowing)
                                                {
                                                    pb.Dismiss();
                                                }
                                                Toast.MakeText(this.Activity, "Username and password error.", ToastLength.Long).Show();
                                                System.Diagnostics.Debug.WriteLine("We are about to logout");
                                                AccountStorage.ClearStorage();
                                                System.Diagnostics.Debug.WriteLine("Main Activity is :" + Activity == null);
                                                System.Diagnostics.Debug.WriteLine("Items in the backstack :" + Activity.FragmentManager.BackStackEntryCount);
                                                System.Diagnostics.Debug.WriteLine("Main Activity is :" + Activity == null);
                                                Activity.FragmentManager.PopBackStack(null, PopBackStackFlags.Inclusive);
                                                System.Diagnostics.Debug.WriteLine("Items in the backstack 2 :" + Activity.FragmentManager.BackStackEntryCount);
                                                ((MainActivity)(Activity)).SetDrawerState(false);
                                                ((MainActivity)(Activity)).SwitchToFragment(MainActivity.FragmentTypes.Login);
                                            }
                                            catch (System.Exception e)
                                            {
                                                System.Diagnostics.Debug.WriteLine("We encountered an error :" + e.Message);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        // no http status code available
                                        Toast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show();
                                    }
                                }
                                else
                                {
                                    // no http status code availableToast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show();
                                }
                            }
                            catch (StatusNotOkayException se)
                            {
                                AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                                builder.SetTitle("An Error has occured")
                                .SetMessage("Error :" + se.GetMessage())
                                .SetNeutralButton("Okay", (sender2, args2) =>
                                {
                                    builder.Dispose();
                                })
                                .SetCancelable(false);
                                AlertDialog alert = builder.Create();
                                alert.Show();
                            }
                            catch (Exception e)
                            {
                                // For any other weird exceptions


                                AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                                builder.SetTitle("An Error has occured")
                                .SetNeutralButton("Okay", (sender2, args2) =>
                                {
                                    builder.Dispose();
                                })
                                .SetMessage("Error :" + e.Message)
                                .SetCancelable(false);
                                AlertDialog alert = builder.Create();
                                alert.Show();
                            }


                            Toast.MakeText(_mActivity, "Completion Date Updated", ToastLength.Short).Show();
                        });
                        //frag.StartTime = DateTime.SpecifyKind(DateTime.Parse(""+output[2].value), DateTimeKind.Local);

                        if (taskDetail.CompletionDate.HasValue)
                        {
                            frag.StartTime = Util.GetInstance().GetLocalTime(taskDetail.CompletionDate.Value);
                        }
                        Debug.WriteLine(frag.StartTime);
                        frag.Show(FragmentManager, DatePickerFragment.TAG);
                    }
                };

                taskName.Text   = taskDetail.FullName;
                output[0].value = TimeSpan.FromMinutes(taskDetail.EstimatedTime).ToString(@"hh\:mm");
                output[1].value = TimeSpan.FromMinutes(taskDetail.ActualTime).ToString(@"hh\:mm");
                output[2].value = taskDetail.CompletionDate.HasValue ? Util.GetInstance().GetLocalTime(taskDetail.CompletionDate.Value).ToShortDateString() : "-";
                listAdapter     = new TaskDetailsAdapter(Activity, Resource.Layout.TimeLogEntryListItem,
                                                         output);


                Debug.WriteLine("We have changed content ");

                timeinfo.Adapter = listAdapter;
                if (string.IsNullOrEmpty(taskDetail.Note))
                {
                    notes.Text    = "-";
                    notes.Gravity = GravityFlags.Center;
                }
                else
                {
                    notes.Text = taskDetail.Note;
                }

                var timeLogs = view.FindViewById <Button>(Resource.Id.TaskDetails_TimeLogButton);
                timeLogs.Click +=
                    (sender, args) =>
                {
                    ((MainActivity)Activity).PassTimeLogInfo(taskDetail.Id, taskDetail.Project.Name,
                                                             taskDetail.FullName);
                };


                if (taskDetail.CompletionDate.HasValue && taskDetail.CompletionDate.Value != DateTime.MinValue)
                {
                    taskComplete.Checked = true;
                }
                else
                {
                    taskComplete.Checked = false;
                }

                taskComplete.CheckedChange += (sender, args) =>
                {
                    string text;
                    if (args.IsChecked)
                    {
                        // Mark a task as complete
                        DateTime convertedTime = Util.GetInstance().GetServerTime(DateTime.UtcNow);
                        taskDetail.CompletionDate = convertedTime;

                        try
                        {
                            ((MainActivity)(this.Activity)).Ctrl.UpdateATask(AccountStorage.DataSet,
                                                                             _taskId, null, convertedTime, false);

                            output[2].value = DateTime.Now.ToShortDateString();
                        }
                        catch (CannotReachServerException)
                        {
                            output[2].value      = "-";
                            taskComplete.Checked = false;
                            Toast.MakeText(Activity, "Please check your internet connection and try again.", ToastLength.Long).Show();
                        }
                        catch (WebException we)
                        {
                            if (we.Status == WebExceptionStatus.ProtocolError)
                            {
                                var response = we.Response as HttpWebResponse;
                                if (response != null)
                                {
                                    Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
                                    if (response.StatusCode == HttpStatusCode.Forbidden)
                                    {
                                        try
                                        {
                                            if (pb.IsShowing)
                                            {
                                                pb.Dismiss();
                                            }
                                            Toast.MakeText(this.Activity, "Username and password error.", ToastLength.Long).Show();
                                            System.Diagnostics.Debug.WriteLine("We are about to logout");
                                            AccountStorage.ClearStorage();
                                            System.Diagnostics.Debug.WriteLine("Main Activity is :" + Activity == null);
                                            System.Diagnostics.Debug.WriteLine("Items in the backstack :" + Activity.FragmentManager.BackStackEntryCount);
                                            System.Diagnostics.Debug.WriteLine("Main Activity is :" + Activity == null);
                                            Activity.FragmentManager.PopBackStack(null, PopBackStackFlags.Inclusive);
                                            System.Diagnostics.Debug.WriteLine("Items in the backstack 2 :" + Activity.FragmentManager.BackStackEntryCount);
                                            ((MainActivity)(Activity)).SetDrawerState(false);
                                            ((MainActivity)(Activity)).SwitchToFragment(MainActivity.FragmentTypes.Login);
                                        }
                                        catch (System.Exception e)
                                        {
                                            System.Diagnostics.Debug.WriteLine("We encountered an error :" + e.Message);
                                        }
                                    }
                                }
                                else
                                {
                                    // no http status code available
                                    Toast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show();
                                }
                            }
                            else
                            {
                                // no http status code availableToast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show();
                            }
                        }
                        catch (StatusNotOkayException)
                        {
                            output[2].value      = "-";
                            taskComplete.Checked = false;
                            Toast.MakeText(Activity, "An error occured. Please try again.", ToastLength.Short).Show();
                        }
                        catch (Exception)
                        {
                            // For any other weird exceptions
                            taskComplete.Checked = false;
                            output[2].value      = "-";
                            Toast.MakeText(Activity, "Unable to make the change. Please try again.", ToastLength.Short).Show();
                        }

                        text = "Task Marked Complete";
                    }
                    else
                    {
                        var previousValue = output[2].value;
                        // Unmark the task
                        taskDetail.CompletionDate = null;

                        try
                        {
                            ((MainActivity)(this.Activity)).Ctrl.UpdateATask(AccountStorage.DataSet,
                                                                             _taskId, null, null, true);

                            output[2].value = "-";
                        }
                        catch (CannotReachServerException)
                        {
                            taskComplete.Checked = true;
                            output[2].value      = previousValue;
                            Toast.MakeText(Activity, "Please check your internet connection and try again.", ToastLength.Long).Show();
                        }
                        catch (WebException we)
                        {
                            if (we.Status == WebExceptionStatus.ProtocolError)
                            {
                                var response = we.Response as HttpWebResponse;
                                if (response != null)
                                {
                                    Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
                                    if (response.StatusCode == HttpStatusCode.Forbidden)
                                    {
                                        try
                                        {
                                            if (pb.IsShowing)
                                            {
                                                pb.Dismiss();
                                            }
                                            Toast.MakeText(this.Activity, "Username and password error.", ToastLength.Long).Show();
                                            System.Diagnostics.Debug.WriteLine("We are about to logout");
                                            AccountStorage.ClearStorage();
                                            System.Diagnostics.Debug.WriteLine("Main Activity is :" + Activity == null);
                                            System.Diagnostics.Debug.WriteLine("Items in the backstack :" + Activity.FragmentManager.BackStackEntryCount);
                                            System.Diagnostics.Debug.WriteLine("Main Activity is :" + Activity == null);
                                            Activity.FragmentManager.PopBackStack(null, PopBackStackFlags.Inclusive);
                                            System.Diagnostics.Debug.WriteLine("Items in the backstack 2 :" + Activity.FragmentManager.BackStackEntryCount);
                                            ((MainActivity)(Activity)).SetDrawerState(false);
                                            ((MainActivity)(Activity)).SwitchToFragment(MainActivity.FragmentTypes.Login);
                                        }
                                        catch (System.Exception e)
                                        {
                                            System.Diagnostics.Debug.WriteLine("We encountered an error :" + e.Message);
                                        }
                                    }
                                }
                                else
                                {
                                    // no http status code available
                                    Toast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show();
                                }
                            }
                            else
                            {
                                // no http status code availableToast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show();
                            }
                        }
                        catch (StatusNotOkayException)
                        {
                            taskComplete.Checked = true;
                            output[2].value      = previousValue;
                            Toast.MakeText(Activity, "An error has occured. Please try again.", ToastLength.Short).Show();
                        }
                        catch (Exception)
                        {
                            // For any other weird exceptions
                            taskComplete.Checked = true;
                            output[2].value      = previousValue;
                            Toast.MakeText(Activity, "Unable to make the change. Please try again.", ToastLength.Short).Show();
                        }

                        text = "Task Marked Incomplete";
                    }
                    listAdapter = new TaskDetailsAdapter(Activity, Resource.Layout.TimeLogEntryListItem, output);
                    Debug.WriteLine("We have changed content ");
                    timeinfo.Adapter = listAdapter;
                    Toast.MakeText(Activity, text, ToastLength.Short).Show();
                    // await (((MainActivity)(Activity)).Ctrl).UpdateTimeLog(Settings.GetInstance().Dataset,)
                };
            }
            if (pb.IsShowing)
            {
                pb.Dismiss();
            }

            // Dismiss Dialog
        }
 public TimerService()
 {
     _tlc = TimeLoggingController.GetInstance();
 }
Ejemplo n.º 5
0
        private async void LoadData(View v, Controller ctrl)
        {
            play  = v.FindViewById <Button>(Resource.Id.Home_Play);
            pause = v.FindViewById <Button>(Resource.Id.Home_Pause);
            var taskComplete   = v.FindViewById <CheckBox>(Resource.Id.Home_TaskComplete);
            var recentTask     = v.FindViewById <Button>(Resource.Id.Home_RecentTask);
            var recentProject  = v.FindViewById <Button>(Resource.Id.Home_CurrentProject);
            var expandableList = v.FindViewById <ExpandableListView>(Android.Resource.Id.List);


            var pb = new ProgressDialog(_mActivity)
            {
                Indeterminate = true
            };

            pb.SetTitle("Loading");

            //TODO: This is under the assumption that whatever task is on the top of the recent task list
            // is the currently logged timer task. Check whether this assumption is valid or not.

            if (TimeLoggingController.GetInstance().IsTimerRunning())
            {
                ModifyPlayPauseState(true);
            }

            play.Click += (sender, args) =>
            {
                Debug.WriteLine("Play Clicked");

                //var timerServiceIntent = new Intent("com.tumasolutions.processdashboard.TimerService");
                //var timerServiceConnection = new TimerServiceConnection((MainActivity)this.Activity);
                //Activity.ApplicationContext.BindService(timerServiceIntent, timerServiceConnection, Bind.AutoCreate);
                if (TimeLoggingController.GetInstance().WasNetworkAvailable)
                {
                    Intent intent = new Intent(Activity, typeof(TimerService));
                    intent.PutExtra("taskId", _currenttaskid);
                    Activity.StartService(intent);
                }
                else
                {
                    AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                    builder.SetTitle("Previous changes not saved")
                    .SetMessage("An earlier time log entry has not yet been synchronized with the server. Please try again later.")
                    .SetNeutralButton("Okay", (sender2, args2) =>
                    {
                        builder.Dispose();
                    })
                    .SetCancelable(false);
                    AlertDialog alert = builder.Create();
                    alert.Show();
                }
            };

            pause.Click += (sender, args) =>
            {
                Debug.WriteLine("Pause Clicked");
                Activity.StopService(new Intent(Activity, typeof(TimerService)));
                Toast.MakeText(this.Activity, "Time Log Entry Saved", ToastLength.Short).Show();
            };


            taskComplete.CheckedChange += (sender, args) =>
            {
                string text = "";
                if (args.IsChecked)
                {
                    // Mark a task as complete
                    DateTime convertedTime = Util.GetInstance().GetServerTime(DateTime.UtcNow);
                    //taskDetail.CompletionDate = convertedTime;

                    try
                    {
                        ((MainActivity)(Activity)).Ctrl.UpdateATask(AccountStorage.DataSet,
                                                                    _currenttaskid, null, convertedTime, false);
                        text = "Task Marked Complete";
                    }
                    catch (CannotReachServerException)
                    {
                        if (pb.IsShowing)
                        {
                            pb.Dismiss();
                        }
                        Debug.WriteLine("We could not reach the server");
                        taskComplete.Checked = false;
                        text = "Please check your internet connection and try again.";
                        Toast.MakeText(this.Activity, text, ToastLength.Short).Show();
                    }
                    catch (StatusNotOkayException)
                    {
                        pb.Dismiss();
                        taskComplete.Checked = false;
                        //TODO: Should we report this ?
                        text = "An error has occured. Please try again.";
                        Toast.MakeText(this.Activity, text, ToastLength.Short).Show();
                    }
                    catch (Exception e)
                    {
                        // For any other weird exceptions
                        pb.Dismiss();

                        taskComplete.Checked = false;
                        // Sending to HockeyApp
                        ExceptionHandler.SaveException(Java.Lang.Throwable.FromException(e), null, null);
                        text = "Unable to make the change. Please try again.";
                        Toast.MakeText(this.Activity, text, ToastLength.Short).Show();
                    }
                }
                else
                {
                    // Unmark the task

                    try
                    {
                        ((MainActivity)(Activity)).Ctrl.UpdateATask(AccountStorage.DataSet,
                                                                    _currenttaskid, null, null, true);
                        text = "Task Marked Incomplete";
                    }
                    catch (CannotReachServerException)
                    {
                        if (pb.IsShowing)
                        {
                            pb.Dismiss();
                        }
                        Debug.WriteLine("We could not reach the server");
                        taskComplete.Checked = true;
                        text = "Please check your internet connection and try again.";
                        Toast.MakeText(this.Activity, text, ToastLength.Short).Show();
                    }
                    //TODO: Should we handle this ?
                    catch (StatusNotOkayException)
                    {
                        pb.Dismiss();
                        taskComplete.Checked = true;
                        text = "An error has occured. Please try again.";
                        Toast.MakeText(this.Activity, text, ToastLength.Short).Show();
                    }
                    catch (Exception e)
                    {
                        // For any other weird exceptions
                        taskComplete.Checked = true;
                        ExceptionHandler.SaveException(Java.Lang.Throwable.FromException(e), null, null);
                        text = "Unable to make the change. Please try again.";
                        Toast.MakeText(this.Activity, text, ToastLength.Short).Show();
                    }
                }
                Debug.WriteLine("We have changed content ");
                Toast.MakeText(Activity, text, ToastLength.Short).Show();
            };
            recentTask.Text = "Loading..";

            recentProject.Text = "Loading..";

            pb.SetCanceledOnTouchOutside(false);
            pb.Show();

            try
            {
                var output = await ctrl.GetRecentTasks(AccountStorage.DataSet);

                pb.Dismiss();

                var recent = output[0];

                recentTask.Text    = recent.FullName;
                recentProject.Text = recent.Project.Name;
                _currenttaskid     = recent.Id;

                _headings.Add(recent.Project.Name, new List <Task>());

                output.RemoveAt(0);

                foreach (Task t in output)
                {
                    if (_headings.ContainsKey(t.Project.Name))
                    {
                        List <Task> tt = _headings[t.Project.Name];
                        tt.Add(t);
                        _headings[t.Project.Name] = tt;
                    }
                    else
                    {
                        List <Task> tt = new List <Task>();
                        tt.Add(t);
                        _headings[t.Project.Name] = tt;
                    }
                }

                //var listAdapter = new TaskAdapter(_mActivity, Android.Resource.Layout.SimpleListItem1, output.ToArray());
                var listAdapter = new HomeListAdapter(this.Activity, _headings);
                expandableList.SetAdapter(listAdapter);
                //ListAdapter = listAdapter;

                var refresher = v.FindViewById <SwipeRefreshLayout>(Resource.Id.refresher);

                refresher.Refresh += async delegate
                {
                    try
                    {
                        output = await ctrl.GetRecentTasks(AccountStorage.DataSet);

                        recent             = output[0];
                        _headings          = new Dictionary <string, List <Task> >();
                        recentTask.Text    = recent.FullName;
                        recentProject.Text = recent.Project.Name;
                        _headings.Add(recent.Project.Name, new List <Task>());

                        output.RemoveAt(0);
                        foreach (Task t in output)
                        {
                            if (_headings.ContainsKey(t.Project.Name))
                            {
                                List <Task> tt = _headings[t.Project.Name];
                                tt.Add(t);
                                _headings[t.Project.Name] = tt;
                            }
                            else
                            {
                                List <Task> tt = new List <Task>();
                                tt.Add(t);
                                _headings[t.Project.Name] = tt;
                            }
                        }
                        listAdapter = new HomeListAdapter(this.Activity, _headings);
                        expandableList.SetAdapter(listAdapter);

                        refresher.Refreshing = false;
                    }
                    catch (CannotReachServerException)
                    {
                        AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                        builder.SetTitle("Unable to Connect")
                        .SetMessage("Please check your network connection and try again")
                        .SetNeutralButton("Okay", (sender, args) =>
                        {
                            builder.Dispose();
                        })
                        .SetCancelable(false);
                        AlertDialog alert = builder.Create();
                        refresher.Refreshing = false;
                        alert.Show();
                    }
                    catch (StatusNotOkayException se)
                    {
                        AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                        builder.SetTitle("An Error has occured")
                        .SetMessage("Error :" + se.GetMessage())
                        .SetNeutralButton("Okay", (sender, args) =>
                        {
                            builder.Dispose();
                        })
                        .SetCancelable(false);
                        AlertDialog alert = builder.Create();
                        refresher.Refreshing = false;
                        alert.Show();
                    }
                    catch (Exception e)
                    {
                        // For any other weird exceptions
                        AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                        builder.SetTitle("An Error has occured")
                        .SetNeutralButton("Okay", (sender, args) =>
                        {
                            builder.Dispose();
                        })
                        .SetMessage("Error :" + e.Message)
                        .SetCancelable(false);
                        AlertDialog alert = builder.Create();
                        refresher.Refreshing = false;
                        alert.Show();
                    }
                };

                recentProject.Click += (sender, args) =>
                {
                    ((MainActivity)Activity).ListOfProjectsCallback(recent.Project.Id, recent.Project.Name);
                };

                recentTask.Click += (sender, args) =>
                {
                    ((MainActivity)Activity).PassTaskDetailsInfo(recent.Id, recent.FullName, recent.Project.Name,
                                                                 recent.CompletionDate,
                                                                 recent.EstimatedTime, recent.ActualTime);
                };
            }
            catch (CannotReachServerException)
            {
                pb.Dismiss();
                AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                builder.SetTitle("Unable to Connect")
                .SetMessage("Please check your network connection and try again")
                .SetNeutralButton("Okay", (sender, args) =>
                {
                    builder.Dispose();
                })
                .SetCancelable(false);
                AlertDialog alert = builder.Create();
                alert.Show();
            }
            catch (StatusNotOkayException se)
            {
                pb.Dismiss();
                AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                builder.SetTitle("An Error has occured")
                .SetMessage("Error :" + se.GetMessage())
                .SetNeutralButton("Okay", (sender, args) =>
                {
                    builder.Dispose();
                })
                .SetCancelable(false);
                AlertDialog alert = builder.Create();
                alert.Show();
            }
            catch (WebException we)
            {
                if (we.Status == WebExceptionStatus.ProtocolError)
                {
                    var response = we.Response as HttpWebResponse;
                    if (response != null)
                    {
                        Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
                        if (response.StatusCode == HttpStatusCode.Forbidden)
                        {
                            try
                            {
                                Toast.MakeText(this.Activity, "Username and password error.", ToastLength.Long).Show();
                                System.Diagnostics.Debug.WriteLine("We are about to logout");
                                AccountStorage.ClearStorage();
                                System.Diagnostics.Debug.WriteLine("Main Activity is :" + Activity == null);
                                System.Diagnostics.Debug.WriteLine("Items in the backstack :" + Activity.FragmentManager.BackStackEntryCount);
                                System.Diagnostics.Debug.WriteLine("Main Activity is :" + Activity == null);
                                Activity.FragmentManager.PopBackStack(null, PopBackStackFlags.Inclusive);
                                System.Diagnostics.Debug.WriteLine("Items in the backstack 2 :" + Activity.FragmentManager.BackStackEntryCount);
                                ((MainActivity)(Activity)).SetDrawerState(false);
                                ((MainActivity)(Activity)).SwitchToFragment(MainActivity.FragmentTypes.Login);
                            }
                            catch (System.Exception e)
                            {
                                System.Diagnostics.Debug.WriteLine("We encountered an error :" + e.Message);
                            }
                        }
                    }
                    else
                    {
                        // no http status code available
                        Toast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show();
                    }
                }
                else
                {
                    // no http status code available
                    Toast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show();
                }
            }
            catch (Exception e)
            {
                // For any other weird exceptions
                pb.Dismiss();
                AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                builder.SetTitle("An Error has occured")
                .SetNeutralButton("Okay", (sender, args) =>
                {
                    builder.Dispose();
                })
                .SetMessage("Error :" + e.Message)
                .SetCancelable(false);
                AlertDialog alert = builder.Create();
                alert.Show();
            }

            /*
             *  private void LoadDummyData(View v)
             *  {
             *
             *      ListView lv = v.FindViewById<ListView>(Android.Resource.Id.List);
             *      var items = new[] { "Vegetables", "Fruits", "Flower Buds", "Legumes", "Bulbs", "Tubers" };
             *      ArrayAdapter listAdapter = new ArrayAdapter<String>(_mActivity, Android.Resource.Layout.SimpleListItem1, items);
             *      ListAdapter = listAdapter;
             *
             *      TextView recentTask = v.FindViewById<TextView>(Resource.Id.Home_RecentTask);
             *      recentTask.Text = "Project / Mobile App l1 / Iteration 1 / View Skeletons / Create Android Skeletons / Home Screen ";
             *
             *  }
             */
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            activityView                  = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.WhiteLarge);
            activityView.Frame            = View.Frame;
            activityView.BackgroundColor  = UIColor.FromRGBA(0, 0, 0, 0.6f);
            activityView.Center           = View.Center;
            activityView.HidesWhenStopped = true;
            View.AddSubview(activityView);

            tlc = TimeLoggingController.GetInstance();

            if (timeLogEntry == null)
            {
                throw new ArgumentException("timeLogEntry is null.");
            }

            if (isAddingMode)
            {
                barBtnItem = new UIBarButtonItem(UIBarButtonSystemItem.Save, async(s, e) =>
                {
                    activityView.StartAnimating();
                    try
                    {
                        await PDashAPI.Controller.AddATimeLog(timeLogEntry.Comment, timeLogEntry.StartDate, timeLogEntry.Task.Id, timeLogEntry.LoggedTime, timeLogEntry.InterruptTime, false);
                        activityView.StopAnimating();
                        NavigationController.PopViewController(true);
                    }
                    catch (Exception ex)
                    {
                        activityView.StopAnimating();
                        ViewControllerHelper.ShowAlert(this, "Add Time Log", ex.Message + " Please try again later.");
                    }
                });
            }
            else
            {
                barBtnItem = new UIBarButtonItem(UIBarButtonSystemItem.Trash, (s, e) =>
                {
                    UIAlertController actionSheetAlert = UIAlertController.Create(null, "This time log will be deleted", UIAlertControllerStyle.ActionSheet);

                    actionSheetAlert.AddAction(UIAlertAction.Create("Delete", UIAlertActionStyle.Destructive, async(action) =>
                    {
                        if (isActiveTimeLog())
                        {
                            ViewControllerHelper.ShowAlert(this, "Oops", "You are currently logging time to this time log. Please stop the timmer first.");
                        }
                        else
                        {
                            activityView.StartAnimating();
                            try
                            {
                                await PDashAPI.Controller.DeleteTimeLog(timeLogEntry.Id.ToString());
                                activityView.StopAnimating();
                                NavigationController.PopViewController(true);
                            }
                            catch (Exception ex)
                            {
                                activityView.StopAnimating();
                                ViewControllerHelper.ShowAlert(this, "Delete Time Log", ex.Message + " Please try again later.");
                            }
                        }
                    }));

                    actionSheetAlert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (action) => Console.WriteLine("Cancel button pressed.")));

                    UIPopoverPresentationController presentationPopover = actionSheetAlert.PopoverPresentationController;
                    if (presentationPopover != null)
                    {
                        presentationPopover.SourceView = this.View;
                        presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Up;
                    }

                    // Display the alertg
                    this.PresentViewController(actionSheetAlert, true, null);
                });
            }

            NavigationItem.RightBarButtonItem = barBtnItem;

            ProjectNameLabel.Text = timeLogEntry.Task.Project.Name;
            TaskNameLabel.Text    = timeLogEntry.Task.FullName;
            StartTimeText.Text    = Util.GetInstance().GetLocalTime(timeLogEntry.StartDate).ToString("g");

            // set up start time customized UIpicker

            StartTimePicker = new UIDatePicker(new CoreGraphics.CGRect(10f, this.View.Frame.Height - 250, this.View.Frame.Width - 20, 200f));
            StartTimePicker.BackgroundColor = UIColor.FromRGB(220, 220, 220);

            StartTimePicker.UserInteractionEnabled = true;
            StartTimePicker.Mode        = UIDatePickerMode.DateAndTime;
            StartTimePicker.MaximumDate = ViewControllerHelper.DateTimeUtcToNSDate(DateTime.UtcNow);

            startTimeSelectedDate = Util.GetInstance().GetServerTime(timeLogEntry.StartDate);

            StartTimePicker.ValueChanged += (Object sender, EventArgs e) =>
            {
                startTimeSelectedDate = ViewControllerHelper.NSDateToDateTimeUtc((sender as UIDatePicker).Date);
            };

            StartTimePicker.BackgroundColor = UIColor.White;
            StartTimePicker.SetDate(ViewControllerHelper.DateTimeUtcToNSDate(Util.GetInstance().GetServerTime(timeLogEntry.StartDate)), true);

            //Setup the toolbar
            toolbar                 = new UIToolbar();
            toolbar.BarStyle        = UIBarStyle.Default;
            toolbar.BackgroundColor = UIColor.FromRGB(220, 220, 220);
            toolbar.Translucent     = true;
            toolbar.SizeToFit();

            // Create a 'done' button for the toolbar and add it to the toolbar

            saveButton = new UIBarButtonItem("Save", UIBarButtonItemStyle.Bordered, null);

            saveButton.Clicked += async(s, e) =>
            {
                this.StartTimeText.Text = Util.GetInstance().GetLocalTime(startTimeSelectedDate).ToString();
                timeLogEntry.StartDate  = startTimeSelectedDate;
                this.StartTimeText.ResignFirstResponder();

                if (!isAddingMode)
                {
                    try
                    {
                        await PDashAPI.Controller.UpdateTimeLog(timeLogEntry.Id.ToString(), null, timeLogEntry.StartDate, timeLogEntry.Task.Id, null, null, false);
                    }
                    catch (Exception ex)
                    {
                        ViewControllerHelper.ShowAlert(this, "Change Start Time", ex.Message + " Please try again later.");
                    }
                }
            };

            var spacer = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace)
            {
                Width = 50
            };

            cancelButton = new UIBarButtonItem("Cancel", UIBarButtonItemStyle.Bordered,
                                               (s, e) =>
            {
                this.StartTimeText.ResignFirstResponder();
            });

            toolbar.SetItems(new UIBarButtonItem[] { cancelButton, spacer, saveButton }, true);

            this.StartTimeText.InputView          = StartTimePicker;
            this.StartTimeText.InputAccessoryView = toolbar;

            DeltaText.Text = TimeSpan.FromMinutes(timeLogEntry.LoggedTime).ToString(@"hh\:mm");

            IntText.Text = TimeSpan.FromMinutes(timeLogEntry.InterruptTime).ToString(@"hh\:mm");

            CommentText.SetTitle(timeLogEntry.Comment ?? "No Comment", UIControlState.Normal);

            CommentText.TouchUpInside += (sender, e) =>
            {
                UIAlertView alert = new UIAlertView();
                alert.Title = "Comment";
                alert.AddButton("Cancel");
                alert.AddButton("Save");
                alert.Message        = "Please enter new Comment";
                alert.AlertViewStyle = UIAlertViewStyle.PlainTextInput;
                UITextField textField = alert.GetTextField(0);
                textField.Placeholder = timeLogEntry.Comment ?? "No Comment";
                alert.Clicked        += CommentButtonClicked;
                alert.Show();
            };

            /////Delta Picker
            DeltaPicker = new UIPickerView(new CoreGraphics.CGRect(10f, this.View.Frame.Height - 250, this.View.Frame.Width - 20, 200f));
            DeltaPicker.BackgroundColor = UIColor.FromRGB(220, 220, 220);

            DeltaPicker.UserInteractionEnabled = true;
            DeltaPicker.ShowSelectionIndicator = true;

            string[] hours   = new string[24];
            string[] minutes = new string[60];

            for (int i = 0; i < hours.Length; i++)
            {
                hours[i] = i.ToString();
            }
            for (int i = 0; i < minutes.Length; i++)
            {
                minutes[i] = i.ToString("00");
            }

            StatusPickerViewModel deltaModel = new StatusPickerViewModel(hours, minutes);

            int h = (int)timeLogEntry.LoggedTime / 60;
            int m = (int)timeLogEntry.LoggedTime % 60;

            this.deltaSelectedHour   = h.ToString();
            this.deltaSelectedMinute = m.ToString("00");

            deltaModel.NumberSelected += (Object sender, EventArgs e) =>
            {
                this.deltaSelectedHour   = deltaModel.selectedHour;
                this.deltaSelectedMinute = deltaModel.selectedMinute;
            };

            DeltaPicker.Model           = deltaModel;
            DeltaPicker.BackgroundColor = UIColor.White;
            DeltaPicker.Select(h, 0, true);
            DeltaPicker.Select(m, 1, true);

            //Setup the toolbar
            toolbar                 = new UIToolbar();
            toolbar.BarStyle        = UIBarStyle.Default;
            toolbar.BackgroundColor = UIColor.FromRGB(220, 220, 220);
            toolbar.Translucent     = true;
            toolbar.SizeToFit();

            // Create a 'done' button for the toolbar and add it to the toolbar
            saveButton = new UIBarButtonItem("Save", UIBarButtonItemStyle.Bordered, null);

            saveButton.Clicked += async(s, e) =>
            {
                this.DeltaText.Text = this.deltaSelectedHour + ":" + this.deltaSelectedMinute;
                double oldLoggedTime = timeLogEntry.LoggedTime;
                timeLogEntry.LoggedTime = int.Parse(this.deltaSelectedHour) * 60 + int.Parse(this.deltaSelectedMinute);
                this.DeltaText.ResignFirstResponder();

                if (!isAddingMode)
                {
                    if (isActiveTimeLog())
                    {
                        tlc.SetLoggedTime((int)timeLogEntry.LoggedTime);
                    }
                    else
                    {
                        try
                        {
                            await PDashAPI.Controller.UpdateTimeLog(timeLogEntry.Id.ToString(), null, null, timeLogEntry.Task.Id, timeLogEntry.LoggedTime - oldLoggedTime, null, false);
                        }
                        catch (Exception ex)
                        {
                            ViewControllerHelper.ShowAlert(this, "Change Logged Time", ex.Message + " Please try again later.");
                        }
                    }
                }
            };

            cancelButton = new UIBarButtonItem("Cancel", UIBarButtonItemStyle.Bordered,
                                               (s, e) =>
            {
                this.DeltaText.ResignFirstResponder();
            });

            toolbar.SetItems(new UIBarButtonItem[] { cancelButton, spacer, saveButton }, true);

            this.DeltaText.InputView          = DeltaPicker;
            this.DeltaText.InputAccessoryView = toolbar;

            ////// Int Picker
            IntPicker = new UIPickerView(new CoreGraphics.CGRect(10f, this.View.Frame.Height - 200, this.View.Frame.Width - 20, 200f));
            IntPicker.BackgroundColor = UIColor.FromRGB(220, 220, 220);

            IntPicker.UserInteractionEnabled = true;
            IntPicker.ShowSelectionIndicator = true;
            IntPicker.BackgroundColor        = UIColor.White;

            IntPicker.Select(0, 0, true);

            StatusPickerViewModel intModel = new StatusPickerViewModel(hours, minutes);

            intModel.NumberSelected += (Object sender, EventArgs e) =>
            {
                this.intSelectedHour   = intModel.selectedHour;
                this.intSelectedMinute = intModel.selectedMinute;
            };

            IntPicker.Model = intModel;

            IntPicker.Select((int)timeLogEntry.InterruptTime / 60, 0, true);
            IntPicker.Select((int)timeLogEntry.InterruptTime % 60, 1, true);

            //Setup the toolbar
            toolbar                 = new UIToolbar();
            toolbar.BarStyle        = UIBarStyle.Default;
            toolbar.BackgroundColor = UIColor.FromRGB(220, 220, 220);
            toolbar.Translucent     = true;
            toolbar.SizeToFit();

            saveButton = new UIBarButtonItem("Save", UIBarButtonItemStyle.Bordered, null);

            saveButton.Clicked += async(s, e) =>
            {
                this.IntText.Text          = this.intSelectedHour + ":" + this.intSelectedMinute;
                timeLogEntry.InterruptTime = int.Parse(this.intSelectedHour) * 60 + int.Parse(this.intSelectedMinute);
                this.IntText.ResignFirstResponder();

                if (!isAddingMode)
                {
                    if (isActiveTimeLog())
                    {
                        tlc.SetInterruptTime((int)timeLogEntry.InterruptTime);
                    }
                    else
                    {
                        try
                        {
                            await PDashAPI.Controller.UpdateTimeLog(timeLogEntry.Id.ToString(), null, null, timeLogEntry.Task.Id, null, timeLogEntry.InterruptTime, false);
                        }
                        catch (Exception ex)
                        {
                            ViewControllerHelper.ShowAlert(this, "Change Interrupt Time", ex.Message + " Please try again later.");
                        }
                    }
                }
            };

            cancelButton = new UIBarButtonItem("Cancel", UIBarButtonItemStyle.Bordered,
                                               (s, e) =>
            {
                this.IntText.ResignFirstResponder();
            });

            toolbar.SetItems(new UIBarButtonItem[] { cancelButton, spacer, saveButton }, true);

            this.IntText.InputView          = IntPicker;
            this.IntText.InputAccessoryView = toolbar;
        }
Ejemplo n.º 7
0
        private bool isActiveTimeLog(TimeLogEntry log)
        {
            TimeLoggingController tlc = TimeLoggingController.GetInstance();

            return(tlc.IsTimerRunning() && tlc.GetActiveTimeLogEntryId().Equals(log.Id.ToString()));
        }