예제 #1
0
        /// <summary>
        /// Method that will update the controls on the page.
        /// </summary>
        private void UpdateControls()
        {
            Device.BeginInvokeOnMainThread(() => {
                // Populate the selected Date/Horse labels
                this.SelectedDateLabel.Text =
                    RecordBookTabbedPage.SelectedDate.ToString("MMM. dd, yyyy");
                this.SelectedHorseLabel.Text =
                    (HorseManager.GetInstance().ActiveHorse == null) ?
                    "-" : HorseManager.GetInstance().ActiveHorse.Name;

                // Update the name display for the current month
                DateTime date = new DateTime(
                    this.DisplayedDate.Year,
                    this.DisplayedDate.Month,
                    1);
                this.MonthNameLabel.Text =
                    date.ToString("MMMM yyyy");

                // Update the name display for the navigation buttons
                this.MonthBackButton.Text =
                    date.AddMonths(-1).ToString("< MMM");
                this.MonthForwardButton.Text =
                    date.AddMonths(1).ToString("MMM >");
            });
        }
예제 #2
0
        /// <summary>
        /// Method for when the project plan frame is tapped.
        /// </summary>
        /// <param name="sender">Object that sent the event.</param>
        /// <param name="e">Arguments for the tap event.</param>
        private async void ProjectPlan_Tapped(object sender,
                                              System.EventArgs e)
        {
            // If the current page is set to be locked, do not render a new
            // page on top of it
            if (this._locked)
            {
                return;
            }

            // Check if there is no active horse
            if (HorseManager.GetInstance().ActiveHorse == null)
            {
                // If there is no active horse, send a toast to the screen to
                // tell the user to create a horse
                ToastController.ShortToast("Please create a horse first!");
                return;
            }

            // Lock the main thread from opening another page until the current
            // page has been closed.
            this._locked = true;

            // Push the page to the top of the navigation stack
            await this.Navigation.PushAsync(new ProjectPlanPage());

            // Unlock the page after the page has been created
            this._locked = false;
        }
예제 #3
0
        /// <summary>
        /// Method that is first called when the page appears.
        /// </summary>
        protected override void OnAppearing()
        {
            // Invoke the base OnAppearing method
            base.OnAppearing();

            // Check if the active horse is null - if so, display an error
            // message and navigate to the horse management page
            Device.BeginInvokeOnMainThread(async() => {
                // Check if there is no active/created horse
                if (HorseManager.GetInstance().ActiveHorse != null)
                {
                    return;
                }

                // Wait one second to make sure the page loaded properly
                await Task.Delay(500);

                // Indicate that the user will need to create a horse
                await this.DisplayAlert("Alert",
                                        "Please make a horse before you manage your record book.",
                                        "Ok");

                // Navigate to the horse management page
                MainPage.NavigateTo(MainPage.PageType.HorseManagerPage);
            });
        }
예제 #4
0
        /// <summary>
        /// Method for when the page appears.
        /// </summary>
        protected override async void OnAppearing()
        {
            // Invoke the base OnAppearing method
            base.OnAppearing();

            // Set the horse/date display at the page bottom
            this.SelectedDateLabel.Text =
                RecordBookTabbedPage.SelectedDate.ToString("MMM. dd, yyyy");
            this.SelectedHorseLabel.Text =
                HorseManager.GetInstance().ActiveHorse.Name;

            // Get all of the records for the page
            this.entries.Clear();
            this.entries = await RecordBookEntry.GetInRange
                           <BeddingRecordEntry>(HorseManager.GetInstance().ActiveHorse.Id,
                                                this.date,
                                                this.date.AddDays(1));

            // Clear all of the contents from the bedding record stack
            this.BeddingRecordStack.Children.Clear();

            // Render all of the entries on the screen
            foreach (BeddingRecordEntry entry in this.entries)
            {
                // Add a new record frame for each bedding
                Device.BeginInvokeOnMainThread(() => {
                    BeddingRecordView view = new BeddingRecordView(entry);
                    this.BeddingRecordStack.Children.Add(view);
                });
            }
        }
예제 #5
0
        /// <summary>
        /// Callback for when the Add Bedding button is clicked.
        /// </summary>
        /// <param name="sender">Object that triggered the event.</param>
        /// <param name="e">Arguments for the click event.</param>
        private async void AddBeddingButton_Clicked(object sender,
                                                    EventArgs e)
        {
            // Check if the maximum number of entries for the day is
            // already reached
            if (this.entries.Count >= MAX_ENTRIES_PER_DAY)
            {
                ToastController.ShortToast("Cannot add any more records for the day!");
                return;
            }

            // Create a new record book entry and insert it into the
            // database to obtain a unique Id
            BeddingRecordEntry entry = new BeddingRecordEntry()
            {
                HorseId = HorseManager.GetInstance().ActiveHorse.Id,
                Date    = date
            };
            await AppDatabase.GetInstance().Save <BeddingRecordEntry>(entry);

            // Add a new record view to the stack
            this.entries.Add(entry);
            BeddingRecordView view = new BeddingRecordView(entry);

            this.BeddingRecordStack.Children.Add(view);
        }
예제 #6
0
        /// <summary>
        /// Method called when the application first opens.
        /// </summary>
        protected override async void OnStart()
        {
            // Start the media manager
            await CrossMedia.Current.Initialize();

            // Handle when your app starts
            HorseManager.GetInstance();
            await PictureManager.Instance.LoadPictures();
        }
예제 #7
0
        /// <summary>
        /// Method that is called when the page first appears.
        /// </summary>
        protected override async void OnAppearing()
        {
            // Invoke the base OnAppearing method
            base.OnAppearing();

            // Check if the user is not in the first level of the program
            if (AppSettings.HorseProgram.Level !=
                AppSettings.HorseProgram.ProgramLevel.First)
            {
                // Disable the "other experiences" fields
                this.OtherExperiencesGrid.IsVisible      = false;
                this.OtherExperiencesSeparator.IsVisible = false;
            }

            // Load the current active horse and bind it to the page.
            this._horse = HorseManager.GetInstance().ActiveHorse;
            int year = (DateTime.Now.Month < 7) ?
                       DateTime.Now.Year - 1 : DateTime.Now.Year;

            // Attempt to get the existing set of project experiences for the
            // current horse at the current program level
            List <ProjectExperiences> experiences = await
                                                    AppDatabase.GetInstance().Query <ProjectExperiences>(
                "SELECT * FROM ProjectExperiences WHERE HorseId = ? AND Level = ? AND Year = ?",
                this._horse.Id, AppSettings.HorseProgram.Level, year);

            // Check if no experiences exist
            if (experiences.Count == 0)
            {
                // Create a new ProjectExperiences collection and add it to the database
                this._experiences = new ProjectExperiences()
                {
                    HorseId = this._horse.Id,
                    Level   = AppSettings.HorseProgram.Level,
                    Year    = (DateTime.Now.Month < 7) ?
                              DateTime.Now.Year - 1 : DateTime.Now.Year,
                };
                await AppDatabase.GetInstance().Save <ProjectExperiences>(this._experiences);

                // Handle if the experiences already existed
            }
            else
            {
                this._experiences = experiences[0];
            }

            // Populate the editors on the page.
            this.FeedCareEditor.Text = this._experiences.FeedCareExperiences;
            this.HealthEditor.Text   = this._experiences.HealthExperiences;
            this.LearningEditor.Text = this._experiences.LearningExperiences;
            this.GoalsEditor.Text    = this._experiences.GoalsExperiences;
            this.OtherEditor.Text    = this._experiences.OtherExperiences;

            // Set the "modified" property of the page to false
            this._modified = false;
        }
예제 #8
0
 /// <summary>
 /// Internal method for refreshing the list view by toggling the data
 /// source.
 /// </summary>
 private void RefreshListView()
 {
     // Run this on the UI thread to prevent screen tearing.
     Device.BeginInvokeOnMainThread(() => {
         // Set the source to null and then back to the actual horse list
         this.HorseManagerListView.ItemsSource = null;
         this.HorseManagerListView.ItemsSource =
             HorseManager.GetInstance().Horses;
     });
 }
예제 #9
0
    void Awake()
    {
        instance = this;
        rBody =  GetComponent<Rigidbody2D> ();
        _animator = horseRef.GetComponent<Animator>();
        _controller = GetComponent<CharacterController2D>();

        // listen to some events for illustration purposes
        _controller.onControllerCollidedEvent += onControllerCollider;
        _controller.onTriggerEnterEvent += onTriggerEnterEvent;
        _controller.onTriggerExitEvent += onTriggerExitEvent;
    }
예제 #10
0
        /// <summary>
        /// Method that is called when "select picture" is pressed.
        /// </summary>
        /// <param name="sender">Object that sent the event.</param>
        /// <param name="e">Arguments for the click event.</param>
        private async void SelectPictureButton_Clicked(object sender,
                                                       System.EventArgs e)
        {
            // Ensure that the device has the ability to select a picture
            if (!CrossMedia.Current.IsPickPhotoSupported)
            {
                await DisplayAlert("Error",
                                   "Picking photos is not supported on this device",
                                   "OK");

                return;
            }

            // Ensure there is an active horse selected
            if (HorseManager.GetInstance().ActiveHorse == null)
            {
                await DisplayAlert("Error",
                                   "A horse must be created before selecting any pictures",
                                   "OK");

                return;
            }

            // Select a photo from the user's gallery
            MediaFile file = await CrossMedia.Current.PickPhotoAsync(
                new PickMediaOptions());

            // Check if the picking operation was cancelled
            if (file == null)
            {
                return;
            }

            // Save the picture to the list of pictures
            Picture picture = new Picture()
            {
                HorseId      = HorseManager.GetInstance().ActiveHorse.Id,
                CreationDate = DateTime.Now,
                FilePath     = file.Path,
            };



            // Save the picture to the database after it has been created
            await PictureManager.Instance.Save(picture);

            // Refresh the photo ListView
            // this.RefreshPictures();
        }
예제 #11
0
        /// <summary>
        /// Method that is called when the page first appears.
        /// </summary>
        protected override async void OnAppearing()
        {
            // Call the base OnAppearing method
            base.OnAppearing();

            // Load the current active horse and bind it to the page.
            this._horse = HorseManager.GetInstance().ActiveHorse;
            int year = (DateTime.Now.Month < 7) ?
                       DateTime.Now.Year - 1 : DateTime.Now.Year;

            // Attempt to get an existing project plan for the current horse
            List <ProjectPlan> plans = await
                                       AppDatabase.GetInstance().Query <ProjectPlan>(
                "SELECT * FROM ProjectPlan WHERE HorseId = ? AND Year = ?",
                this._horse.Id, year);

            // Check if no plan exists for the current horse
            if (plans.Count == 0)
            {
                // Create a new plan and then add it to the database
                this._plan = new ProjectPlan()
                {
                    HorseId = this._horse.Id,
                    Year    = (DateTime.Now.Month < 7) ?
                              DateTime.Now.Year - 1: DateTime.Now.Year,
                };
                await AppDatabase.GetInstance().Save <ProjectPlan>(this._plan);

                // Set the plan if it already exists
            }
            else
            {
                this._plan = plans[0];
            }

            // Populate the editors on the page
            this.HorsePlanEditor.Text    = this._plan.HorsePlans;
            this.CaringPlanEditor.Text   = this._plan.CaringPlans;
            this.LearningPlanEditor.Text = this._plan.LearningPlans;

            // Set the "modified" property of the page to false
            this._modified = false;
        }
예제 #12
0
        /// <summary>
        /// Method to be called when a ListView item is selected.
        /// </summary>
        /// <param name="sender">Object that triggered the event.</param>
        /// <param name="ev">Event arguments for the selected event.</param>
        protected async void OnItemSelected(object sender,
                                            ItemTappedEventArgs ev)
        {
            // Check if the page is already locked
            if (this.locked)
            {
                return;
            }

            // Lock the current page from navigation
            this.locked = true;

            // Check if the sending context is null
            if (ev.Item == null)
            {
                return;
            }

            // Get the selected horse from the event arguments
            Horse horse = ev.Item as Horse;

            this.HorseManagerListView.SelectedItem = null;

            // If the horse is the active horse, open the viewing page
            if (HorseManager.GetInstance().ActiveHorse == horse)
            {
                // Open the viewing page for the selected horse
                Page page = new HorseViewPage(horse);
                await this.Navigation.PushAsync(page, true);
            }

            // Otherwise, set this horse as the active horse
            else
            {
                ToastController.ShortToast(string.Format(
                                               "{0} set as active horse.", horse.Name));
                HorseManager.GetInstance().ActiveHorse = horse;
                this.RefreshListView();
            }

            // Unlock the current page after navigation has occurred
            this.locked = false;
        }
 private void Awake()
 {
     if (instance == null)
     {
         instance = this;
     }
     else if (instance != this)
     {
         // A unique case where the Singleton exists but not in this scene
         if (instance.gameObject.scene.name == null)
         {
             instance = this;
         }
         else
         {
             Destroy(this);
         }
     }
 }
예제 #14
0
        /// <summary>
        /// Method that is called when the page first appears.
        /// </summary>
        protected override async void OnAppearing()
        {
            // Call the base OnAppearing method
            base.OnAppearing();

            // Load the current active horse and bind it to the page
            this._horse = HorseManager.GetInstance().ActiveHorse;
            int year = (DateTime.Now.Month < 7) ?
                       DateTime.Now.Year - 1 : DateTime.Now.Year;

            // Attempt to get the existing project story for the current horse
            List <ProjectStory> stories = await
                                          AppDatabase.GetInstance().Query <ProjectStory>(
                "SELECT * FROM ProjectStory WHERE HorseId = ? AND Year = ?",
                this._horse.Id, year);

            // Check if no story exists for the current horse
            if (stories.Count == 0)
            {
                // Create a new story and then add it to the database
                this._story = new ProjectStory()
                {
                    HorseId = this._horse.Id,
                    Year    = (DateTime.Now.Month < 7) ?
                              DateTime.Now.Year - 1 : DateTime.Now.Year,
                };
                await AppDatabase.GetInstance().Save <ProjectStory>(this._story);

                // Set the plan if it already exists
            }
            else
            {
                this._story = stories[0];
            }

            // Populate the project story editor
            this.ProjectStoryEditor.Text     = this._story.Story;
            this.ProjectStoryEditor.Keyboard = Keyboard.Create(
                KeyboardFlags.All);

            // Set the "modified" property of the page to false
            this._modified = false;
        }
예제 #15
0
        /// <summary>
        /// Default constructor for the application main page.
        /// </summary>
        public MainPage()
        {
            // Create a static reference of this page to user for navigation
            MainPage._Instance = this;

            // Create the dictionary of detail pages in the application
            MainPage.PageDictionary = new Dictionary <PageType, NavigationPage>()
            {
                { PageType.ProfilePage, new NavigationPage(new SettingsPage()) },
                { PageType.HorseManagerPage, new NavigationPage(new HorseManagerPage()) },
                { PageType.RecordBookPage, new NavigationPage(new RecordBookTabbedPage()) },
                { PageType.ProjectPage, new NavigationPage(new ProjectSelectPage()) },
                { PageType.PicturePage, new NavigationPage(new PicturePage()) },
                { PageType.ExportPage, new NavigationPage(new ExportPage()) },
                { PageType.BackupPage, new NavigationPage(new BackupPage()) },
            };

            // Initialize the component and add the item selected callback
            // Initialize the component and add the item selected callback
            InitializeComponent();
            MasterPage.ListView.ItemSelected += ListView_ItemSelected;

            // Set the home page based on the number of horses
            if (HorseManager.GetInstance().Horses.Count == 0)
            {
                this.Detail = MainPage.PageDictionary[PageType.HorseManagerPage];
            }
            else
            {
                this.Detail = MainPage.PageDictionary[PageType.RecordBookPage];
            }

            // Set the toolbar color on the current detail page if the device
            // is an Android device
            if (Device.RuntimePlatform == Device.Android)
            {
                ((NavigationPage)this.Detail).BarBackgroundColor = (Color)
                                                                   Application.Current.Resources["ApplicationGreen"];
            }
        }
예제 #16
0
        /// <summary>
        /// Method for when the page appears.
        /// </summary>
        protected override void OnAppearing()
        {
            // Invoke the base OnAppearing method
            base.OnAppearing();

            // Set the date for the page
            this.date   = RecordBookTabbedPage.SelectedDate;
            this.locked = false;

            Device.BeginInvokeOnMainThread(() => {
                // Populate the selected Date/Horse labels
                this.SelectedDateLabel.Text =
                    RecordBookTabbedPage.SelectedDate.ToString("MMM. dd, yyyy");
                this.SelectedHorseLabel.Text =
                    (HorseManager.GetInstance().ActiveHorse == null) ?
                    "-" : HorseManager.GetInstance().ActiveHorse.Name;
            });

            // Update the record count for each of the cells on a separate
            // thread so as to not bog down the UI
            Task.Run(async() => {
                await this.UpdateRecordCount();
            });
        }
예제 #17
0
        /// <summary>
        /// Method that is called when the delete button is pressed.
        /// </summary>
        /// <param name="sender">Object that sent the event.</param>
        /// <param name="e">Event arguments for the event.</param>
        private void DeleteButton_Clicked(object sender,
                                          System.EventArgs e)
        {
            Device.BeginInvokeOnMainThread(async() => {
                // Display a confirmation dialog asking whether the user actually
                // wants to delete the specified horse.
                bool result = await this.DisplayAlert(
                    "Confirmation",
                    "Are you sure you want to delete this horse?  This action cannot be undone and all associated data will be deleted.",
                    "Delete",
                    "Cancel");

                // If the user selected cancel, exit from the lambda
                if (!result)
                {
                    return;
                }

                // Delete the horse, then navigate up the stack until the
                // HorseManagerPage is reached.
                await HorseManager.GetInstance().Delete(this.Horse);
                await Navigation.PopToRootAsync(true);
            });
        }
예제 #18
0
        /// <summary>
        /// Method for when the page appears.
        /// </summary>
        protected override void OnAppearing()
        {
            // Invoke the base OnAppearing method
            base.OnAppearing();

            Device.BeginInvokeOnMainThread(() => {
                // Populate the current horse label
                this.RecordHorseLabel.Text =
                    (HorseManager.GetInstance().ActiveHorse == null) ?
                    "-" : HorseManager.GetInstance().ActiveHorse.Name;

                // Populate the record level label
                if (AppSettings.HorseProgram.Level ==
                    AppSettings.HorseProgram.ProgramLevel.Other)
                {
                    this.RecordLevelLabel.Text = "-";
                }
                else
                {
                    this.RecordLevelLabel.Text = string.Format(
                        "Level {0}", (int)AppSettings.HorseProgram.Level);
                }
            });
        }
예제 #19
0
        public void HorseManager_GivesMeTheManagerCorrectly()
        {
            var manager = HorseManager.GetInstance();

            Assert.AreEqual(typeof(HorseManager), manager.GetType());
        }
예제 #20
0
        /// <summary>
        /// Method that is called when "take picture" is pressed.
        /// </summary>
        /// <param name="sender">Object that sent the event.</param>
        /// <param name="e">Arguments for the click event.</param>
        private async void TakePictureButton_Clicked(object sender,
                                                     System.EventArgs e)
        {
            // Ensure that the device has a camera
            if (!CrossMedia.Current.IsCameraAvailable)
            {
                await DisplayAlert("No Camera",
                                   "No camera available.",
                                   "OK");

                return;
            }

            // Ensure that the device has the ability to take a picture
            if (!CrossMedia.Current.IsTakePhotoSupported)
            {
                await DisplayAlert("Error",
                                   "Taking photos is not supported on this device",
                                   "OK");

                return;
            }

            // Ensure there is an active horse selected
            if (HorseManager.GetInstance().ActiveHorse == null)
            {
                await DisplayAlert("Error",
                                   "A horse must be created before selecting any pictures",
                                   "OK");

                return;
            }

            // Take a picture using the device camera
            MediaFile file = await CrossMedia.Current.TakePhotoAsync(
                new StoreCameraMediaOptions()
            {
                Name          = string.Format("4h-{0}.jpg", DateTime.Now.Ticks),
                AllowCropping = true,
                RotateImage   = false,
                SaveMetaData  = true,
                SaveToAlbum   = true,
            }
                );

            // Check if the picture operation was cancelled
            if (file == null)
            {
                return;
            }

            // Save the picture to the list of pictures
            Picture picture = new Picture()
            {
                HorseId      = HorseManager.GetInstance().ActiveHorse.Id,
                CreationDate = DateTime.Now,
                FilePath     = file.Path,
            };

            // Save the picture to the database after it has been created
            await PictureManager.Instance.Save(picture);

            // Refresh the photo ListView
            this.RefreshPictures();
        }
예제 #21
0
        /// <summary>
        /// Method that will asynchronously update the count of records.
        /// </summary>
        private async Task UpdateRecordCount()
        {
            // Update the ActivityRecord display
            List <ActivityRecordEntry> activityList = await RecordBookEntry.GetInRange
                                                      <ActivityRecordEntry>(HorseManager.GetInstance().ActiveHorse.Id,
                                                                            this.date,
                                                                            this.date.AddDays(1));

            List <RidingRecordEntry> ridingList = await RecordBookEntry.GetInRange
                                                  <RidingRecordEntry>(HorseManager.GetInstance().ActiveHorse.Id,
                                                                      this.date,
                                                                      this.date.AddDays(1));

            List <FeedRecordEntry> feedList = await RecordBookEntry.GetInRange
                                              <FeedRecordEntry>(HorseManager.GetInstance().ActiveHorse.Id,
                                                                this.date,
                                                                this.date.AddDays(1));

            List <BeddingRecordEntry> beddingList = await RecordBookEntry.GetInRange
                                                    <BeddingRecordEntry>(HorseManager.GetInstance().ActiveHorse.Id,
                                                                         this.date,
                                                                         this.date.AddDays(1));

            List <LaborRecordEntry> laborList = await RecordBookEntry.GetInRange
                                                <LaborRecordEntry>(HorseManager.GetInstance().ActiveHorse.Id,
                                                                   this.date,
                                                                   this.date.AddDays(1));

            List <ServiceRecordEntry> serviceList = await RecordBookEntry.GetInRange
                                                    <ServiceRecordEntry>(HorseManager.GetInstance().ActiveHorse.Id,
                                                                         this.date,
                                                                         this.date.AddDays(1));

            List <ExpenseRecordEntry> expenseList = await RecordBookEntry.GetInRange
                                                    <ExpenseRecordEntry>(HorseManager.GetInstance().ActiveHorse.Id,
                                                                         this.date,
                                                                         this.date.AddDays(1));

            Device.BeginInvokeOnMainThread(() => {
                // Set the contents of the activity record pane
                this.ActivityCountLabel.Text = string.Format("{0} {1}",
                                                             activityList.Count,
                                                             activityList.Count == 1 ? "entry" : "entries");
                this.ActivityCountLabel.TextColor = (activityList.Count == 0) ?
                                                    Color.LightGray : Color.Default;

                // Set the contents of the riding record pane
                this.RidingCountLabel.Text = string.Format("{0} {1}",
                                                           ridingList.Count,
                                                           ridingList.Count == 1 ? "entry" : "entries");
                this.RidingCountLabel.TextColor = (ridingList.Count == 0) ?
                                                  Color.LightGray : Color.Default;

                // Set the contents of the feed record pane
                this.FeedCountLabel.Text = string.Format("{0} {1}",
                                                         feedList.Count,
                                                         feedList.Count == 1 ? "entry" : "entries");
                this.FeedCountLabel.TextColor = (feedList.Count == 0) ?
                                                Color.LightGray : Color.Default;

                // Set the contents of the bedding record pane
                this.BeddingCountLabel.Text = string.Format("{0} {1}",
                                                            beddingList.Count,
                                                            beddingList.Count == 1 ? "entry" : "entries");
                this.BeddingCountLabel.TextColor = (beddingList.Count == 0) ?
                                                   Color.LightGray : Color.Default;

                // Set the contents of the labor record pane
                this.LaborCountLabel.Text = string.Format("{0} {1}",
                                                          laborList.Count,
                                                          laborList.Count == 1 ? "entry" : "entries");
                this.LaborCountLabel.TextColor = (laborList.Count == 0) ?
                                                 Color.LightGray : Color.Default;

                // Set the contents of the service record pane
                this.ServiceCountLabel.Text = string.Format("{0} {1}",
                                                            serviceList.Count,
                                                            serviceList.Count == 1 ? "entry" : "entries");
                this.ServiceCountLabel.TextColor = (serviceList.Count == 0) ?
                                                   Color.LightGray : Color.Default;

                // Set the contents of the expense record pane
                this.ExpenseCountLabel.Text = string.Format("{0} {1}",
                                                            expenseList.Count,
                                                            expenseList.Count == 1 ? "entry" : "entries");
                this.ExpenseCountLabel.TextColor = (expenseList.Count == 0) ?
                                                   Color.LightGray : Color.Default;
            });
        }
예제 #22
0
        /// <summary>
        /// Method that is called when the test button is clicked.
        /// </summary>
        /// <param name="sender">Object that sent the click event.</param>
        /// <param name="e">Arguments for the click event.</param>
        private async void TestExportButton_Clicked(object sender, EventArgs e)
        {
            var   db          = AppDatabase.GetInstance();              // gets the database
            Horse horse       = HorseManager.GetInstance().ActiveHorse; //selects the active horse
            int   currentYear = (DateTime.Now.Month < 7) ?
                                DateTime.Now.Year - 1 : DateTime.Now.Year;

            if (horse == null) //determines if an active horse is selected
            {
                return;
            }

            // Test the PdfSharp.Xamarin functionality
            IFileHelper   director = DependencyService.Get <IFileHelper>();
            IExportHelper helper   = DependencyService.Get <IExportHelper>();

            //establishes the 4-H document path
            string path = director.GenerateLocalAsset("level1book.pdf", horse.Name);

            if (!IsFirstLevel())
            {
                path = director.GenerateLocalAsset("level2-5book.pdf", horse.Name);
            }

            //opens the document for modification
            PdfDocument document = PdfReader.Open(path, PdfDocumentOpenMode.Modify);

            // gets the document's form fillable components
            PdfAcroForm acroForm = document.AcroForm;

            #region Photos
            // get Photos from Picture manager and print onto pages 11&12
            // ***supports upto 6 currently***
            List <Picture> pics = PictureManager.Instance.Pictures;
            int            len  = 6;
            if (pics.Count < len)
            {
                len = pics.Count;
            }
            int pageNo = 10;
            double[,] poses = new double[, ] {
                { 1, 5 }, { 4.25, 5 },
                { 1, 10 }, { 4.25, 10 },
                { 1, 5.5 }, { 4.25, 5.5 }
            };
            for (int i = 0; i < len; i++)
            {
                XImage img = XImage.FromFile(pics[i].FilePath);

                double xPos = poses[i, 0] * 71;
                double yPos = (11 * 71) - (poses[i, 1] * 71);

                if (i >= 2)
                {
                    pageNo = 11;
                }
                XGraphics gfx = XGraphics.FromPdfPage(document.Pages[pageNo]);

                // each photo has up to 3.25 in by 4 in
                // 71 pixels per inch for pdfsharp stuff
                double maxWidth = 3.25 * 71, maxHeight = 4 * 71;
                var    ratioX = (double)maxWidth / img.PixelWidth;
                var    ratioY = (double)maxHeight / img.PixelHeight;
                var    ratio  = Math.Min(ratioX, ratioY);

                var newWidth  = (int)(img.PixelWidth * ratio);
                var newHeight = (int)(img.PixelHeight * ratio);

                gfx.DrawImage(img, xPos, yPos, newWidth, newHeight);
                gfx.Dispose();
            }
            #endregion

            #region Project Plans
            // Sets the project plans page

            var plans = await db.Query <ProjectPlan>(
                "SELECT * FROM ProjectPlan WHERE HorseId = ? AND Year = ?",
                horse.Id, currentYear);

            if (plans.Count > 0)
            {
                acroForm.Fields["horseList"].Value      = new PdfString(plans[0].HorsePlans);
                acroForm.Fields["careList"].Value       = new PdfString(plans[0].CaringPlans);
                acroForm.Fields["experienceList"].Value = new PdfString(plans[0].LearningPlans);
            }
            #endregion

            #region Horse Info
            // Sets the horse info section

            acroForm.Fields["name"].Value     = new PdfString(horse.Name);
            acroForm.Fields["breed"].Value    = new PdfString(horse.Breed);
            acroForm.Fields["sex"].Value      = new PdfString(horse.Sex.ToString());
            acroForm.Fields["height"].Value   = new PdfString(horse.Height.ToString());
            acroForm.Fields["weight"].Value   = new PdfString(horse.Weight.ToString());
            acroForm.Fields["age"].Value      = new PdfString(horse.Age.ToString());
            acroForm.Fields["color"].Value    = new PdfString(horse.Color);
            acroForm.Fields["markings"].Value = new PdfString(horse.Markings);

            // add pedigree information for year 1 book
            if (IsFirstLevel())
            {
                acroForm.Fields["pedigree"].Value          = new PdfString(horse.Pedigree);
                acroForm.Fields["sire"].Value              = new PdfString(horse.Sire);
                acroForm.Fields["dam"].Value               = new PdfString(horse.Dam);
                acroForm.Fields["paternalGrandSire"].Value = new PdfString(horse.PaternalGrandSire);
                acroForm.Fields["paternalGrandDam"].Value  = new PdfString(horse.PaternalGrandDam);
                acroForm.Fields["maternalGrandSire"].Value = new PdfString(horse.MaternalGrandSire);
                acroForm.Fields["maternalGrandDam"].Value  = new PdfString(horse.MaternalGrandDam);
            }

            #endregion

            #region Activities
            // Sets the Participation in activities section

            // set the upper limit on allowed activities
            int activityLimit = (IsFirstLevel()) ? 8 : 11;

            // get the activity records
            var activities = await RecordBookEntry.GetInRange <ActivityRecordEntry>(
                horse.Id, new DateTime(currentYear, 7, 1), new DateTime(currentYear + 1, 6, 30));

            // populate the activites until you hit the limit or you run out of activities
            for (int i = 0; i < activityLimit && i < activities.Count; i++)
            {
                acroForm.Fields["activityDate" + i].Value     = new PdfString(activities[i].Date.ToString());
                acroForm.Fields["activity" + i].Value         = new PdfString(activities[i].Description);
                acroForm.Fields["activityLocation" + i].Value = new PdfString(activities[i].Location);
            }

            #endregion

            #region Stable, Feed, Other
            // In book 1: fills out the Stable Record page
            // In book 2: fills out the Feed record page, the Stable record page, and the Other Expenses section

            int yearCrossover = 0; // helps the program jump the gap from Dec to Jan

            // Year-long aggregates
            float book1OverallCost       = 0;
            float book2OverallFeedCost   = 0;
            float book2OverallStableCost = 0;
            float overallBedWeight       = 0;
            float overallBedCost         = 0;
            var   overallFeedAmounts     = new Dictionary <FeedType, float> {
                { FeedType.Grain, 0 },
                { FeedType.Hay, 0 },
                { FeedType.Pasture, 0 },
                { FeedType.SaltAndMinerals, 0 }
            };
            var overallFeedCosts = new Dictionary <FeedType, float> {
                { FeedType.Grain, 0 },
                { FeedType.Hay, 0 },
                { FeedType.Pasture, 0 },
                { FeedType.SaltAndMinerals, 0 },
                { FeedType.Other, 0 }
            };
            float overallOtherExpenses = 0;
            var   overallServiceCosts  = new Dictionary <ServiceType, float> {
                { ServiceType.Farrier, 0 },
                { ServiceType.HealthCare, 0 },
                { ServiceType.RidingInstruction, 0 },
                { ServiceType.Other, 0 },
            };
            TimeSpan overallLaborHours = new TimeSpan(0, 0, 0);

            for (int j = 6; j < 18; j++)
            {
                int index = (j % 12);
                if (index == 0)
                {
                    yearCrossover = 1;
                }

                // get current month's first/last date
                var    firstOfTheMonth = new DateTime(currentYear + yearCrossover, index + 1, 1);
                var    lastOfTheMonth  = firstOfTheMonth.AddMonths(1).AddDays(-1);
                string fullMonthName   = new DateTime(2015, index + 1, 1).ToString("MMMM");

                // monthly aggregate values
                float book1TotalCost       = 0;
                float book2TotalFeedCost   = 0;
                float book2TotalStableCost = 0;

                #region Bedding
                // get the bedding records
                var bedding = await RecordBookEntry.GetInRange <BeddingRecordEntry>(
                    horse.Id, firstOfTheMonth, lastOfTheMonth);

                // Aggregate and export bedding records
                var totalBeddingWeight = new Dictionary <BeddingType, float> {
                    { BeddingType.Hay, 0 },
                    { BeddingType.Hemp, 0 },
                    { BeddingType.Moss, 0 },
                    { BeddingType.Paper, 0 },
                    { BeddingType.Sawdust, 0 },
                    { BeddingType.Shavings, 0 },
                    { BeddingType.StallMats, 0 },
                    { BeddingType.Straw, 0 },
                    { BeddingType.WoodPellets, 0 }
                };
                float totalBeddingCost = 0;
                foreach (BeddingRecordEntry bed in bedding)
                {
                    totalBeddingWeight[bed.Type] += bed.Amount;
                    totalBeddingCost             += bed.Cost;
                    overallBedWeight             += bed.Amount;
                    overallBedCost       += bed.Cost;
                    book1TotalCost       += bed.Cost;
                    book2TotalStableCost += bed.Cost;
                }

                // format the kind/amount string
                string weightString = "";
                if (totalBeddingWeight[BeddingType.Hay] > 0)
                {
                    weightString = String.Format("{0}Hay, {1}\n", weightString, totalBeddingWeight[BeddingType.Hay]);
                }
                if (totalBeddingWeight[BeddingType.Hemp] > 0)
                {
                    weightString = String.Format("{0}Hemp, {1}\n", weightString, totalBeddingWeight[BeddingType.Hemp]);
                }
                if (totalBeddingWeight[BeddingType.Moss] > 0)
                {
                    weightString = String.Format("{0}Moss, {1}\n", weightString, totalBeddingWeight[BeddingType.Moss]);
                }
                if (totalBeddingWeight[BeddingType.Paper] > 0)
                {
                    weightString = String.Format("{0}Paper, {1}\n", weightString, totalBeddingWeight[BeddingType.Paper]);
                }
                if (totalBeddingWeight[BeddingType.Sawdust] > 0)
                {
                    weightString = String.Format("{0}Sawdust, {1}\n", weightString, totalBeddingWeight[BeddingType.Sawdust]);
                }
                if (totalBeddingWeight[BeddingType.Shavings] > 0)
                {
                    weightString = String.Format("{0}Shavings, {1}\n", weightString, totalBeddingWeight[BeddingType.Shavings]);
                }
                if (totalBeddingWeight[BeddingType.StallMats] > 0)
                {
                    weightString = String.Format("{0}Stall Mats, {1}\n", weightString, totalBeddingWeight[BeddingType.StallMats]);
                }
                if (totalBeddingWeight[BeddingType.Straw] > 0)
                {
                    weightString = String.Format("{0}Straw, {1}\n", weightString, totalBeddingWeight[BeddingType.Straw]);
                }
                if (totalBeddingWeight[BeddingType.WoodPellets] > 0)
                {
                    weightString = String.Format("{0}Wood Pellets, {1}\n", weightString, totalBeddingWeight[BeddingType.WoodPellets]);
                }

                // commit this month's records
                acroForm.Fields["bedding" + index].Value     = new PdfString(weightString);
                acroForm.Fields["beddingCost" + index].Value = new PdfString(String.Format("{0:C2}", totalBeddingCost));
                #endregion

                #region Feed
                // get the feed records
                var feed = await RecordBookEntry.GetInRange <FeedRecordEntry>(
                    horse.Id, firstOfTheMonth, lastOfTheMonth);

                // Aggregate the records
                var totalFeedAmounts = new Dictionary <FeedType, float> {
                    { FeedType.Grain, 0 },
                    { FeedType.Hay, 0 },
                    { FeedType.Pasture, 0 },
                    { FeedType.SaltAndMinerals, 0 }
                };
                var totalFeedCosts = new Dictionary <FeedType, float> {
                    { FeedType.Grain, 0 },
                    { FeedType.Hay, 0 },
                    { FeedType.Pasture, 0 },
                    { FeedType.SaltAndMinerals, 0 },
                    { FeedType.Other, 0 }
                };
                foreach (FeedRecordEntry food in feed)
                {
                    if (food.Type != FeedType.Other)
                    {
                        totalFeedAmounts[food.Type]   += food.Amount;
                        overallFeedAmounts[food.Type] += food.Amount;
                    }
                    totalFeedCosts[food.Type]   += food.Cost;
                    overallFeedCosts[food.Type] += food.Cost;
                    book1OverallCost            += food.Cost;
                    book2OverallFeedCost        += food.Cost;
                }

                // commit this month's feed records
                acroForm.Fields["grain" + index].Value     = new PdfString(totalFeedAmounts[FeedType.Grain].ToString());
                acroForm.Fields["grainCost" + index].Value = new PdfString(String.Format("{0:C2}", totalFeedCosts[FeedType.Grain]));
                acroForm.Fields["hay" + index].Value       = new PdfString(totalFeedAmounts[FeedType.Hay].ToString());
                acroForm.Fields["hayCost" + index].Value   = new PdfString(String.Format("{0:C2}", totalFeedCosts[FeedType.Hay]));
                acroForm.Fields["salt" + index].Value      = new PdfString(totalFeedAmounts[FeedType.SaltAndMinerals].ToString());
                acroForm.Fields["saltCost" + index].Value  = new PdfString(String.Format("{0:C2}", totalFeedCosts[FeedType.SaltAndMinerals]));
                acroForm.Fields["pasture" + index].Value   = new PdfString(totalFeedAmounts[FeedType.Pasture].ToString());

                // these do not go into tier 1 record book
                if (!IsFirstLevel())
                {
                    acroForm.Fields["pastureCost" + index].Value   = new PdfString(String.Format("{0:C2}", totalFeedCosts[FeedType.Pasture]));
                    acroForm.Fields["otherFeedCost" + index].Value = new PdfString(String.Format("{0:C2}", totalFeedCosts[FeedType.Other]));
                }
                #endregion

                #region Service
                // get the service records
                var service = await RecordBookEntry.GetInRange <ServiceRecordEntry>(
                    horse.Id, firstOfTheMonth, lastOfTheMonth);

                // aggregate the service record information
                string otherExpenses     = "";
                float  otherExpensesCost = 0;
                var    serviceStrings    = new Dictionary <ServiceType, string> {
                    { ServiceType.Farrier, "" },
                    { ServiceType.HealthCare, "" },
                    { ServiceType.RidingInstruction, "" },
                    { ServiceType.Other, "" },
                };
                var serviceCosts = new Dictionary <ServiceType, float> {
                    { ServiceType.Farrier, 0 },
                    { ServiceType.HealthCare, 0 },
                    { ServiceType.RidingInstruction, 0 },
                    { ServiceType.Other, 0 },
                };

                foreach (ServiceRecordEntry serve in service)
                {
                    // fills in "other expenses" for a year 1 book
                    if (IsFirstLevel())
                    {
                        if (!serve.Description.Equals(String.Empty))
                        {
                            otherExpenses = String.Format("{0}; {1}", otherExpenses, serve.Description);
                        }
                        otherExpensesCost    += serve.Cost;
                        overallOtherExpenses += serve.Cost;
                    }
                    else     // fills in "Stable Record" for a year 2-5 book
                    {
                        if (!serve.Description.Equals(String.Empty))
                        {
                            serviceStrings[serve.Type] = String.Format(
                                "{0}; {1}", serviceStrings[serve.Type], serve.Description);
                        }
                        serviceCosts[serve.Type]        += serve.Cost;
                        overallServiceCosts[serve.Type] += serve.Cost;
                    }
                    book1OverallCost       += serve.Cost;
                    book2OverallStableCost += serve.Cost;
                }

                // commit the service record information to the pdf
                if (IsFirstLevel())
                {
                    acroForm.Fields["otherExpenses" + index].Value     = new PdfString(otherExpenses);
                    acroForm.Fields["otherExpensesCost" + index].Value = new PdfString(String.Format("{0:C2}", otherExpensesCost));
                }
                else
                {
                    acroForm.Fields["ridingCost" + index].Value = new PdfString(
                        String.Format("{0}, {1:C2}",
                                      serviceStrings[ServiceType.RidingInstruction],
                                      serviceCosts[ServiceType.RidingInstruction]));
                    acroForm.Fields["healthCare" + index].Value     = new PdfString(serviceStrings[ServiceType.HealthCare]);
                    acroForm.Fields["healthCareCost" + index].Value = new PdfString(
                        String.Format("{0:C2}", serviceCosts[ServiceType.HealthCare]));
                    acroForm.Fields["farrier" + index].Value     = new PdfString(serviceStrings[ServiceType.Farrier]);
                    acroForm.Fields["farrierCost" + index].Value = new PdfString(
                        String.Format("{0:C2}", serviceCosts[ServiceType.Farrier]));
                    acroForm.Fields["equipment" + index].Value     = new PdfString(serviceStrings[ServiceType.Other]);
                    acroForm.Fields["equipmentCost" + index].Value = new PdfString(
                        String.Format("{0:C2}", serviceCosts[ServiceType.Other]));
                }

                #endregion

                #region Riding
                // Get the riding records
                var rides = await RecordBookEntry.GetInRange <RidingRecordEntry>(
                    horse.Id, firstOfTheMonth, lastOfTheMonth);

                // set the riding month if the book level is 2-5
                if (!IsFirstLevel())
                {
                    acroForm.Fields["ridingMonth" + index].Value = new PdfString(fullMonthName);
                }

                // aggregate riding hours and descriptions
                TimeSpan rideHours        = new TimeSpan(0, 0, 0);
                string   rideDescriptions = "";
                foreach (RidingRecordEntry ride in rides)
                {
                    rideHours.Add(ride.End.Subtract(ride.Start));
                    if (!ride.Description.Equals(String.Empty))
                    {
                        rideDescriptions = String.Format("{0}; {1}", rideDescriptions, ride.Description);
                    }
                }

                // commit aggregates
                acroForm.Fields["ridingHours" + index].Value = new PdfString(rideHours.ToString(@"hh\:mm"));
                acroForm.Fields["riding" + index].Value      = new PdfString(rideDescriptions);
                #endregion

                #region Labor
                // Get the labor records
                var labor = await RecordBookEntry.GetInRange <LaborRecordEntry>(
                    horse.Id, firstOfTheMonth, lastOfTheMonth);

                // aggregate labor hours and descriptions
                // aggregate riding hours and descriptions
                TimeSpan laborHours        = new TimeSpan(0, 0, 0);
                string   laborDescriptions = "";
                foreach (LaborRecordEntry job in labor)
                {
                    laborHours.Add(job.End.Subtract(job.Start));
                    if (!job.Description.Equals(String.Empty))
                    {
                        laborDescriptions = String.Format("{0}; {1}", laborDescriptions, job.Description);
                    }
                }

                // commit aggregates
                if (IsFirstLevel())
                {
                    acroForm.Fields["labor" + index].Value      = new PdfString(laborDescriptions);
                    acroForm.Fields["laborHours" + index].Value = new PdfString(laborHours.ToString(@"hh\:mm"));
                }
                else
                {
                    acroForm.Fields["labor" + index].Value = new PdfString(laborHours.ToString(@"hh\:mm"));
                }
                #endregion

                #region monthly aggregate commit
                // Commit any aggregated totals for the current month
                if (IsFirstLevel())
                {
                    acroForm.Fields["totalCost" + index].Value = new PdfString(
                        String.Format("{0:C2}", book1TotalCost));
                }
                else
                {
                    acroForm.Fields["totalFeedCost" + index].Value = new PdfString(
                        String.Format("{0:C2}", book2TotalFeedCost));
                    acroForm.Fields["totalFeedCostS" + index].Value = new PdfString(
                        String.Format("{0:C2}", book2TotalFeedCost));
                    acroForm.Fields["totalStableCost" + index].Value = new PdfString(
                        String.Format("{0:C2}", book2TotalStableCost));
                }
                #endregion

                #region aggregate yearly
                // Add aggregate monthly values to their respective year-long totals
                book1OverallCost                             += book1TotalCost;
                book2OverallFeedCost                         += book2TotalFeedCost;
                book2OverallStableCost                       += book2TotalStableCost;
                overallBedCost                               += totalBeddingCost;
                overallBedWeight                             += totalBeddingWeight[BeddingType.Hay];
                overallBedWeight                             += totalBeddingWeight[BeddingType.Hemp];
                overallBedWeight                             += totalBeddingWeight[BeddingType.Moss];
                overallBedWeight                             += totalBeddingWeight[BeddingType.Paper];
                overallBedWeight                             += totalBeddingWeight[BeddingType.Sawdust];
                overallBedWeight                             += totalBeddingWeight[BeddingType.Shavings];
                overallBedWeight                             += totalBeddingWeight[BeddingType.StallMats];
                overallBedWeight                             += totalBeddingWeight[BeddingType.Straw];
                overallBedWeight                             += totalBeddingWeight[BeddingType.WoodPellets];
                overallFeedAmounts[FeedType.Grain]           += totalFeedAmounts[FeedType.Grain];
                overallFeedAmounts[FeedType.Hay]             += totalFeedAmounts[FeedType.Hay];
                overallFeedAmounts[FeedType.Pasture]         += totalFeedAmounts[FeedType.Pasture];
                overallFeedAmounts[FeedType.SaltAndMinerals] += totalFeedAmounts[FeedType.SaltAndMinerals];
                overallFeedCosts[FeedType.Grain]             += totalFeedCosts[FeedType.Grain];
                overallFeedCosts[FeedType.Hay]               += totalFeedCosts[FeedType.Hay];
                overallFeedCosts[FeedType.Pasture]           += totalFeedCosts[FeedType.Pasture];
                overallFeedCosts[FeedType.SaltAndMinerals]   += totalFeedCosts[FeedType.SaltAndMinerals];
                overallFeedCosts[FeedType.Other]             += totalFeedCosts[FeedType.Other];
                overallLaborHours.Add(laborHours);
                #endregion
            }


            #region Year long aggregates commit
            // Commit aggragated totals for the year

            // Universal to both books
            acroForm.Fields["beddingTotal"].Value     = new PdfString(overallBedWeight.ToString());
            acroForm.Fields["beddingCostTotal"].Value = new PdfString(
                String.Format("{0:C2}", overallBedCost));

            if (IsFirstLevel())   // first book only
            {
                acroForm.Fields["hayTotal"].Value = new PdfString(
                    overallFeedAmounts[FeedType.Hay].ToString());
                acroForm.Fields["hayCostTotal"].Value = new PdfString(
                    String.Format("{0:C2}", overallFeedCosts[FeedType.Hay]));
                acroForm.Fields["grainTotal"].Value = new PdfString(
                    overallFeedAmounts[FeedType.Grain].ToString());
                acroForm.Fields["grainCostTotal"].Value = new PdfString(
                    String.Format("{0:C2}", overallFeedCosts[FeedType.Grain]));
                acroForm.Fields["saltTotal"].Value = new PdfString(
                    overallFeedAmounts[FeedType.SaltAndMinerals].ToString());
                acroForm.Fields["saltCostTotal"].Value = new PdfString(
                    String.Format("{0:C2}", overallFeedCosts[FeedType.SaltAndMinerals]));
                acroForm.Fields["pastureTotal"].Value = new PdfString(
                    overallFeedCosts[FeedType.Pasture].ToString());
                acroForm.Fields["otherExpensesCostTotal"].Value = new PdfString(
                    String.Format("{0:C2}", overallOtherExpenses));
                acroForm.Fields["totalCostTotal"].Value = new PdfString(
                    String.Format("{0:C2}", book1OverallCost));
            }
            else     // second book only
            {
                acroForm.Fields["totalFeedCostTotal"].Value = new PdfString(
                    String.Format("{0:C2}", book2OverallFeedCost));
                acroForm.Fields["totalFeedCostSTotal"].Value = new PdfString(
                    String.Format("{0:C2}", book2OverallFeedCost));
                acroForm.Fields["laborTotal"].Value = new PdfString(
                    overallLaborHours.ToString(@"hh\:mm"));
                acroForm.Fields["ridingCostTotal"].Value = new PdfString(
                    String.Format("{0:C2}", overallServiceCosts[ServiceType.RidingInstruction]));
                acroForm.Fields["healthCareCostTotal"].Value = new PdfString(
                    String.Format("{0:C2}", overallServiceCosts[ServiceType.HealthCare]));
                acroForm.Fields["farrierCostTotal"].Value = new PdfString(
                    String.Format("{0:C2}", overallServiceCosts[ServiceType.Farrier]));
                acroForm.Fields["equipmentCostTotal"].Value = new PdfString(
                    String.Format("{0:C2}", overallServiceCosts[ServiceType.Other]));
                acroForm.Fields["totalStableCostTotal"].Value = new PdfString(
                    String.Format("{0:C2}", book2OverallStableCost));
            }
            #endregion

            #region Other Expenses (book 2 only)
            if (!IsFirstLevel())
            {
                // Get the expense records
                var expense = await RecordBookEntry.GetInRange <ExpenseRecordEntry>(
                    horse.Id, new DateTime(currentYear, 7, 1), new DateTime(currentYear + 1, 6, 30));

                float otherExpensesTotal = 0;

                // Commit the extra expenses to the record book
                for (int i = 0; i < 6 && i < expense.Count; i++)
                {
                    acroForm.Fields["otherDate" + i].Value = new PdfString(expense[i].Date.ToString());
                    acroForm.Fields["other" + i].Value     = new PdfString(expense[i].Description);
                    acroForm.Fields["otherCost" + i].Value = new PdfString(String.Format("{0:C2", expense[i].Cost));
                    otherExpensesTotal += expense[i].Cost;
                }
                acroForm.Fields["otherCostTotal"].Value = new PdfString(String.Format("{0:C2}", otherExpensesTotal));
            }
            #endregion

            #endregion

            #region Experiences
            // get the project experiences
            var experiences = await db.Query <ProjectExperiences>(
                "SELECT * FROM ProjectExperiences WHERE HorseId = ? AND Year = ?",
                horse.Id, currentYear);

            // if there are experiences, set them into the PDF
            if (experiences.Count > 0)
            {
                acroForm.Fields["feedSummary"].Value   = new PdfString(experiences[0].FeedCareExperiences);
                acroForm.Fields["healthSummary"].Value = new PdfString(experiences[0].HealthExperiences);
                acroForm.Fields["learnSummary"].Value  = new PdfString(experiences[0].LearningExperiences);
                acroForm.Fields["goalSummary"].Value   = new PdfString(experiences[0].GoalsExperiences);
                if (IsFirstLevel())
                {
                    acroForm.Fields["otherSummary"].Value = new PdfString(experiences[0].OtherExperiences);
                }
            }
            #endregion

            #region Story
            // get the project story
            var story = await db.Query <ProjectStory>(
                "SELECT * FROM ProjectStory WHERE HorseId = ? AND Year = ?",
                horse.Id, currentYear);

            if (story.Count > 0)
            {
                acroForm.Fields["projectStory"].Value = new PdfString(story[0].Story);
            }
            #endregion

            #region User Information
            acroForm.Fields["userName"].Value = new PdfString(
                AppSettings.User.UserName);
            var today = DateTime.Today;
            var age   = today.Year - AppSettings.User.DateOfBirth.Year;
            if (AppSettings.User.DateOfBirth > today.AddYears(-age))
            {
                age--;
            }
            acroForm.Fields["userAge"].Value      = new PdfString(age.ToString());
            acroForm.Fields["userBirthday"].Value = new PdfString(
                AppSettings.User.DateOfBirth.ToString("MM/dd/yyyy"));
            acroForm.Fields["userAddress0"].Value = new PdfString(
                AppSettings.User.Address);
            acroForm.Fields["county"].Value = new PdfString(
                AppSettings.HorseClub.County);
            acroForm.Fields["clubName"].Value = new PdfString(
                AppSettings.HorseClub.ClubName);
            acroForm.Fields["clubLeaderName"].Value = new PdfString(
                AppSettings.HorseClub.LeaderName);
            acroForm.Fields["projectHelperName"].Value = new PdfString(
                AppSettings.HorseProgram.HelperName);
            acroForm.Fields["startDate"].Value = new PdfString(
                AppSettings.HorseProgram.StartDate.ToString("MM/dd/yyyy"));
            acroForm.Fields["endDate"].Value = new PdfString(
                AppSettings.HorseProgram.CloseDate.ToString("MM/dd/yyyy"));

            #endregion

            // Save the file to the device document directory
            string file = Path.Combine(helper.GetDocumentsDirectory(), horse.Name + "4-HRecordBook.pdf");
            document.Save(file);
            helper.SendEmail(file);

            // Set the filepath of the WebView to the new PDF
            //this.PdfView.Path = file;
        }
예제 #23
0
        public static int GetPrice(SimDescription sim)
        {
            if (sim.IsHuman)
            {
                return(0);
            }

            List <SimDescription> parents = Relationships.GetParents(sim);

            if (parents.Count < 2)
            {
                return(0);
            }

            Common.StringBuilder msg = new Common.StringBuilder(sim.FullName);

            int price = 0;

            try
            {
                if ((sim.IsHorse) && (sim.AdultOrAbove))
                {
                    price = HorseManager.GetHorseCost(sim, false);
                }
                else
                {
                    List <Pair <SimDescription, int> > parentLevel = new List <Pair <SimDescription, int> >();

                    foreach (SimDescription parent in parents)
                    {
                        parentLevel.Add(new Pair <SimDescription, int>(parent, 0));
                    }

                    Dictionary <SimDescription, bool> lookup = new Dictionary <SimDescription, bool>();

                    int maxLevel = 0;

                    int index = 0;
                    while (index < parentLevel.Count)
                    {
                        Pair <SimDescription, int> level = parentLevel[index];
                        index++;

                        if (lookup.ContainsKey(level.First))
                        {
                            price -= Consigner.Settings.mInbredPenalty;

                            msg += Common.NewLine + "Inbred: -" + Consigner.Settings.mInbredPenalty;

                            continue;
                        }
                        lookup.Add(level.First, true);

                        if (maxLevel < level.Second)
                        {
                            maxLevel = level.Second;
                        }

                        foreach (SimDescription parent in Relationships.GetParents(level.First))
                        {
                            parentLevel.Add(new Pair <SimDescription, int>(parent, level.Second + 1));
                        }
                    }

                    price += maxLevel * Consigner.Settings.mPedigreeBonus;

                    msg += Common.NewLine + "Pedigree: " + maxLevel + " * " + Consigner.Settings.mPedigreeBonus;

                    if (sim.Child)
                    {
                        price += Consigner.Settings.mSellPrice[0];

                        msg += Common.NewLine + "Child: " + Consigner.Settings.mSellPrice[0];
                    }
                    else if (sim.Adult)
                    {
                        price += Consigner.Settings.mSellPrice[1];

                        msg += Common.NewLine + "Adult: " + Consigner.Settings.mSellPrice[1];
                    }
                    else
                    {
                        price += Consigner.Settings.mSellPrice[2];

                        msg += Common.NewLine + "Elder: " + Consigner.Settings.mSellPrice[2];
                    }

                    foreach (Trait trait in sim.TraitManager.List)
                    {
                        if (trait.Score > 0x0)
                        {
                            price += Consigner.Settings.mGoodTraitBonus;

                            msg += Common.NewLine + trait.TraitName(sim.IsFemale) + ": " + Consigner.Settings.mGoodTraitBonus;
                        }
                        else if (trait.Score < 0x0)
                        {
                            price -= Consigner.Settings.mBadTraitPenalty;

                            msg += Common.NewLine + trait.TraitName(sim.IsFemale) + ": -" + Consigner.Settings.mBadTraitPenalty;
                        }
                    }

                    if (sim.IsGhost)
                    {
                        price += Consigner.Settings.mOccultBonus;

                        msg += Common.NewLine + "Occult: " + Consigner.Settings.mOccultBonus;
                    }

                    {
                        CatHuntingSkill skill = sim.SkillManager.GetSkill <CatHuntingSkill>(SkillNames.CatHunting);
                        if ((skill != null) && (skill.IsVisibleInUI()))
                        {
                            price += (int)(skill.SkillLevel * Consigner.Settings.mSkillLevelBonus);

                            msg += Common.NewLine + "Skill: " + skill.SkillLevel + " * " + Consigner.Settings.mSkillLevelBonus;

                            if (skill.mPreyCaughtTypeStats != null)
                            {
                                int count = 0;

                                foreach (int value in skill.mPreyCaughtTypeStats.Values)
                                {
                                    count += value;
                                }

                                price += (int)(count * Consigner.Settings.mPerPreyBonus);

                                msg += Common.NewLine + "Per Prey: " + count + " * " + Consigner.Settings.mPerPreyBonus;
                            }
                        }
                    }

                    {
                        DogHuntingSkill skill = sim.SkillManager.GetSkill <DogHuntingSkill>(SkillNames.DogHunting);
                        if ((skill != null) && (skill.IsVisibleInUI()))
                        {
                            price += (int)(skill.SkillLevel * Consigner.Settings.mSkillLevelBonus);

                            msg += Common.NewLine + "Skill: " + skill.SkillLevel + " * " + Consigner.Settings.mSkillLevelBonus;

                            if (skill.mNumRGMFound != null)
                            {
                                int count = 0;

                                foreach (int value in skill.mNumRGMFound.Values)
                                {
                                    count += value;
                                }

                                price += (int)(count * Consigner.Settings.mPerPreyBonus);

                                msg += Common.NewLine + "RGM: " + count + " * " + Consigner.Settings.mPerPreyBonus;
                            }
                        }
                    }
                }

                msg += Common.NewLine + "Final Price: " + price;

                return(Math.Max(price, 0));
            }
            finally
            {
                Common.DebugNotify(msg);
            }
        }
예제 #24
0
        public override bool Run()
        {
            try
            {
                Definition interactionDefinition = InteractionDefinition as Definition;
                if (interactionDefinition != null)
                {
                    mLookForAutonomousActionsUponArrival = interactionDefinition.mLookForAutonomousActionsUponArrival;
                }
                else
                {
                    mLookForAutonomousActionsUponArrival = true;
                }

                if ((Target.CommercialLotSubType == CommercialLotSubType.kEP10_Resort) &&
                    (Actor.IsHuman) &&
                    (Actor.SimDescription.ChildOrAbove) &&
                    (Actor.LotHome == null) &&
                    (Autonomous) &&
                    (NumFollowers == 0) &&
                    (Actor.GetSituationOfType <Situation>() == null) &&
                    (!Actor.SimDescription.HasActiveRole) &&
                    (Actor.Service == null))
                {
                    IResortTower[] objects = Target.GetObjects <IResortTower>();
                    if (objects.Length > 0)
                    {
                        IResortTower        randomObjectFromList = RandomUtil.GetRandomObjectFromList <IResortTower>(objects);
                        InteractionInstance instance             = randomObjectFromList.GetExitTowerDefinition().CreateInstance(randomObjectFromList, Actor, new InteractionPriority(InteractionPriorityLevel.Autonomous), Autonomous, false);
                        if (Actor.InteractionQueue.PushAsContinuation(instance, false))
                        {
                            if (!Actor.Household.IsServiceNpcHousehold)
                            {
                                foreach (SimDescription description in Actor.Household.SimDescriptions)
                                {
                                    if ((description.IsHuman && description.ChildOrAbove) && (description.CreatedSim == null))
                                    {
                                        Sim actor = description.InstantiateOffScreen(Target);
                                        InteractionInstance entry = randomObjectFromList.GetExitTowerDefinition().CreateInstance(randomObjectFromList, actor, new InteractionPriority(InteractionPriorityLevel.Autonomous), Autonomous, false);
                                        actor.InteractionQueue.Add(entry);
                                    }
                                }
                            }
                            return(true);
                        }
                    }
                }

                if ((Target.CommercialLotSubType == CommercialLotSubType.kEP10_Diving) && Actor.SimDescription.Child)
                {
                    return(false);
                }

                if (!CarpoolManager.WaitForCarpool(Actor))
                {
                    return(false);
                }

                if (ShouldReenqueueWithStandingPrecondition())
                {
                    ChildUtils.SetPosturePrecondition(this, CommodityKind.Standing, new CommodityKind[0x0]);
                    return(Actor.InteractionQueue.PushAsContinuation(this, false));
                }

                if (mFollowers == null)
                {
                    if (InteractionDefinition is DateDefinition)
                    {
                        mFollowers = new List <Sim>();
                    }
                    else
                    {
                        mFollowers = GetFollowers(Actor);
                        if (Actor.IsNPC)
                        {
                            if (mFollowers.Count == 0)
                            {
                                Sim sim;
                                if (HorseManager.NpcShouldRideHorse(Actor, out sim))
                                {
                                    mFollowers.Add(sim);
                                }
                            }
                            else if ((Autonomous && RandomUtil.RandomChance01(Sim.GoForWalkWithDog.kChanceOfAutonomousDogWalk)) && sAcceptableCommercialLotSubTypes.Contains(Target.CommercialLotSubType))
                            {
                                foreach (Sim sim2 in new List <Sim>(mFollowers))
                                {
                                    if (Sim.GoForWalkWithDog.ActorCanWalkTarget(Actor, sim2))
                                    {
                                        InteractionInstance entry = Sim.GoForWalkWithDog.Singleton.CreateInstance(sim2, Actor, GetPriority(), true, false);
                                        (entry as Sim.GoForWalkWithDog).TargetLot = Target;
                                        Actor.InteractionQueue.AddNext(entry);
                                        return(true);
                                    }
                                }
                            }

                            foreach (Sim sim3 in new List <Sim>(mFollowers))
                            {
                                GroupingSituation.StartGroupingSituation(Actor, sim3, false);
                            }
                        }
                        else
                        {
                            GroupingSituation situationOfType = Actor.GetSituationOfType <GroupingSituation>();
                            if ((situationOfType != null) && !situationOfType.ConfirmLeaveGroup(Actor, "Gameplay/Situations/GroupingSituation:ContinueVisitAloneInteraction"))
                            {
                                return(false);
                            }
                        }
                    }
                }

                if (Sim.SwitchToFormalOutfitIfCocktail(Actor, Target))
                {
                    foreach (Sim sim in new List <Sim> (mFollowers))
                    {
                        sim.OutfitCategoryToUseForRoutingOffLot = OutfitCategories.Formalwear;
                    }
                }

                Occupation occupation = Actor.Occupation;
                if (((occupation != null) && (occupation.ActiveCareerLotID == Target.LotId)) && occupation.IsAllowedToWork())
                {
                    Actor.Occupation.EnsureSimHasOccupationOutfit();
                    if (Actor.Posture == Actor.Standing)
                    {
                        Actor.SwitchToOutfitWithSpin(Sim.ClothesChangeReason.GoingToWork);
                    }
                    else
                    {
                        OutfitCategories categories;
                        Actor.GetOutfitForClothingChange(Sim.ClothesChangeReason.GoingToWork, out categories);
                        Actor.OutfitCategoryToUseForRoutingOffLot = categories;
                    }
                }

                bool flag2 = false;

                MetaAutonomyVenueType metaAutonomyVenueType = Target.LotCurrent.GetMetaAutonomyVenueType();

                // Custom
                if ((mFollowers.Count == 0) && (GoHereEx.Teleport.Perform(Actor, Target, true)))
                {
                    flag2 = true;
                }
                else
                {
                    Door door = Target.FindFrontDoor();
                    if (door != null)
                    {
                        bool wantToBeOutside = true;
                        if (Target.IsOpenVenue())
                        {
                            wantToBeOutside = false;
                        }

                        Route r = null;
                        Target.RouteToFrontDoor(Actor, Sim.MinDistanceFromDoorWhenVisiting, Sim.MaxDistanceFromDoorWhenGoingInside, ref door, wantToBeOutside, ref r, false);
                        if (r != null)
                        {
                            r.DoRouteFail = false;
                            flag2         = GoHereSpace.Helpers.SimRoutingComponentEx.DoRouteWithFollowers(Actor.SimRoutingComponent, r, mFollowers);
                            Lot.ValidateFollowers(mFollowers);
                        }
                    }
                }

                if (!flag2)
                {
                    Actor.RemoveExitReason(ExitReason.RouteFailed);
                    Route route = Actor.CreateRoute();
                    if (Autonomous && mLookForAutonomousActionsUponArrival)
                    {
                        bool flag4 = RandomUtil.RandomChance(Lot.ChanceOfGoingToCommunityLotByCar);
                        if (!flag4)
                        {
                            route.SetOption(Route.RouteOption.EnablePlanningAsCar, flag4);
                        }
                    }
                    route.SetRouteMetaType(Route.RouteMetaType.GoCommunityLot);

                    if ((metaAutonomyVenueType == MetaAutonomyVenueType.Diving) && Actor.SimDescription.IsMermaid)
                    {
                        Lot lotCurrent = Actor.LotCurrent;
                        if ((lotCurrent != null) && lotCurrent.IsHouseboatLot())
                        {
                            route.SetOption2(Sims3.SimIFace.Route.RouteOption2.EnablePlanningAsBoat, true);
                        }
                    }

                    Target.PlanToLotEx(route);
                    if (!route.PlanResult.Succeeded())
                    {
                        foreach (Shell shell in Target.GetObjects <Shell>())
                        {
                            route = shell.GetRouteToShell(Actor);
                            if (route.PlanResult.Succeeded())
                            {
                                break;
                            }
                        }
                    }

                    // Custom Function
                    flag2 = GoHereSpace.Helpers.SimRoutingComponentEx.DoRouteWithFollowers(Actor.SimRoutingComponent, route, mFollowers);
                    Lot.ValidateFollowers(mFollowers);
                }

                if (flag2)
                {
                    NumSuccess++;
                    if (Autonomous)
                    {
                        Target.MakeSimDoSomethingAfterArrivingAtVenue(metaAutonomyVenueType, Actor);
                        if (mFollowers != null)
                        {
                            foreach (Sim sim3 in new List <Sim>(mFollowers))
                            {
                                Target.MakeSimDoSomethingAfterArrivingAtVenue(metaAutonomyVenueType, sim3);
                            }
                        }
                    }

                    // Custom check
                    if ((!GoHere.Settings.DisallowAutoGroup(Actor)) &&
                        (Actor.Household != null) &&
                        (!GroupingSituation.DoesGroupingSituationExistForFamily(Actor)))
                    {
                        bool selectable = false;

                        if (SimTypes.IsSelectable(Actor))
                        {
                            selectable = true;
                        }
                        else
                        {
                            foreach (Sim follower in new List <Sim>(mFollowers))
                            {
                                if (SimTypes.IsSelectable(follower))
                                {
                                    selectable = true;
                                    break;
                                }
                            }
                        }

                        // Stop the romantic prompt from appearing
                        GroupingSituation situation = Actor.GetSituationOfType <GroupingSituation>();
                        if (situation != null)
                        {
                            if (situation.Participants == null)
                            {
                                situation.Exit();
                            }

                            if (!selectable)
                            {
                                situation.RomanticGrouping = false;
                            }
                        }

                        GroupingSituation.StartGroupingSitatuationWithFollowers(Actor, mFollowers);
                    }
                    return(flag2);
                }

                if (((Actor.ExitReason & ExitReason.HigherPriorityNext) == ExitReason.None) && ((Actor.ExitReason & ExitReason.UserCanceled) == ExitReason.None))
                {
                    NumFail++;
                }
                return(flag2);
            }
            catch (ResetException)
            {
                throw;
            }
            catch (Exception e)
            {
                Common.Exception(Actor, Target, e);
                return(false);
            }
        }
예제 #25
0
 public void HorseManager_ThrowsExpectedErrorWithBadHorseID()
 {
     HorseManager.GetInstance().GetHorseById(-10);
 }
예제 #26
0
        /// <summary>
        /// Method to be called when the "add horse" button is pressed.
        /// </summary>
        /// <param name="sender">The item that triggers the event.</param>
        /// <param name="e">The event args for the event.</param>
        private void AddHorseButton_Clicked(object sender, EventArgs e)
        {
            // If the current modal page is set to be locked, do not render a
            // horse modal page
            if (this.locked)
            {
                return;
            }

            // Lock the main thread from opening another page until the current
            // modal display has been closed
            this.locked = true;

            // Invoke a separate operation to create a horse.
            Device.BeginInvokeOnMainThread(async() => {
                try {
                    // Prompt the user for the type of horse that they want to
                    // create, from the types that are available.
                    const string StandardHorseString  = "Standard";
                    const string MiniatureHorseString = "Miniature";
                    const string CancelString         = "Cancel";
                    string result = await this.DisplayActionSheet(
                        "Select A Horse Type",
                        CancelString,
                        null,
                        StandardHorseString,
                        MiniatureHorseString);

                    // Handle the result accordingly
                    HorseType type = HorseType.Standard;
                    switch (result)
                    {
                    // Handle when a standard horse is selected
                    case StandardHorseString:
                        type = HorseType.Standard;
                        break;

                    // Handle when a miniature horse is selected
                    case MiniatureHorseString:
                        type = HorseType.Miniature;
                        break;

                    // Handle when the "cancel" button was pressed, or the
                    // user selects outside the bounds of the select.
                    case CancelString:
                    default:
                        return;
                    }

                    // Get a new horse from the horse manager
                    Horse horse = await HorseManager.GetInstance()
                                  .Create(type);

                    // Push a modal to the top of the navigation stack to
                    // display the selected horse's information
                    Page horsePage = new HorseEditPage(horse);
                    await this.Navigation.PushAsync(horsePage);
                } catch (TooManyHorsesException) {
                    // Show a toast indicating that the horse could not be found
                    ToastController.ShortToast("Cannot create any more horses.");
                } finally {
                    // Unlock the page after the modal has been created
                    this.locked = false;
                }
            });
        }