Imports System.Data.SqlClient
Imports System.Data.Sql
Imports System.Text.RegularExpressions
Imports System.IO
Imports System.Transactions
Imports EntitiesLayer

Public Class frmAddRecipe

    'Keep track of the ingredient combobox changes text
    Dim comboIngredientChanged As Boolean = False

    Dim fractionsRegExpression As String = "^(\d+/\d+|\d+(\s\d+/\d+)?)$"
    Dim validator As New PresentationValidation()
    Dim recipeService As New PresentationServiceReference.UserServicesClient

    Public Event UpdateStatus(ByVal statusString As String)

#Region "Events"

    Private Sub frmAddRecipe_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If recipeService.State = ServiceModel.CommunicationState.Opened Then
            recipeService.Close()
        End If
    End Sub

    Private Sub frmAddRecipe_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
       btnDelete.Enabled = False


        Try
            'Fill Ingredient Type combobox
            With cbIngredientType
                .DataSource = recipeService.retrieveFoodTypes
                .DisplayMember = "Name"
                .ValueMember = "FoodTypeID"
                .SelectedIndex = 0

            End With

            'Fill Ingredient Name combobox
            With cboIngredientName
                .DataSource = recipeService.retrieveIngredients
                .DisplayMember = "Name"
                .ValueMember = "IngredientID"
                .SelectedIndex = 0

            End With

            'Fill Cuisine Type combobox
            With cbCuisineStyle
                .DataSource = recipeService.retrieveCuisines
                .DisplayMember = "Name"
                .ValueMember = "CuisineTypeID"
                .SelectedIndex = 0

            End With

            'Fill Course Type combobox
            With cbCourseType
                .DataSource = recipeService.retrieveCourses()
                .DisplayMember = "Name"
                .ValueMember = "CourseTypeID"
                .SelectedIndex = 0

            End With

            'Fill Unit Measurements combobox
            With cbUnitMeasurements
                .DataSource = recipeService.retrieveUnitMeasurements
                .DisplayMember = "Name"
                .ValueMember = "UnitMeasurementID"
                .SelectedIndex = 0
            End With

            'setup the openfiledialog box
            With OpenFileDialog1
                .AddExtension = True
                .CheckPathExists = True
                .CheckFileExists = True
                .Multiselect = False
                .Filter = "Bitmap (*.bmp)|*.bmp|Jpeg (*.jpeg,*.jpg)|*.jpeg;*.jpg|" & _
                "Icon (*.ico)|*.ico|Gif (*.gif)|*.gif|PNG (*.png)|*.png"
                .InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
                .Title = "Open image files"
                .FilterIndex = 0
                .RestoreDirectory = True
                .FileName = ""

            End With

            txtRecipeName.Focus()
        Catch ex As InvalidOperationException
            MessageBox.Show(ex.Message)
        Catch ex As FieldAccessException
            MessageBox.Show(ex.Message)
        Catch ex As SqlException
            MessageBox.Show(ex.Message)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally

        End Try

    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub

    Private Sub btnBrowsePhoto_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowsePhoto.Click

        OpenFileDialog1.CheckPathExists = True
        OpenFileDialog1.CheckFileExists = True

        Try
            'Open a file open dialog box and if the user presses ok and selected something then continue on
            If OpenFileDialog1.ShowDialog() = DialogResult.OK And Not OpenFileDialog1.FileName.ToString() = "" Then


                Dim filePath As String = OpenFileDialog1.FileName.ToString()
                txtFilePathPhoto.Text = filePath
                AutosizeImage(filePath, pbRecipePhoto, PictureBoxSizeMode.CenterImage)

            End If

        Catch ex As IO.FileNotFoundException
            MessageBox.Show(ex.ToString)
        Catch ex As IO.IOException
            MessageBox.Show(ex.ToString)
        Catch ex As Exception
            MessageBox.Show(ex.ToString)

        End Try

    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Dim regFractions As New Regex(fractionsRegExpression)
        Dim valid As Boolean = True
        Dim isFraction As Boolean = False

        'check to see if the Ingredient Amount is a fraction or a number
        'If not then show error
        If regFractions.IsMatch(txtIngredientAmount.Text) Then
            'If in fraction form

            If txtIngredientAmount.Text.Contains("/") Then
                'Convert the fraction and validate the bounds
                'Else Must be an error
                If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.RecipeIngredientAmount, FractionToDecimal(txtIngredientAmount.Text), True) Then
                    ErrorProviderAddRecipe.SetError(txtIngredientAmount, "")
                Else
                    ErrorProviderAddRecipe.SetError(txtIngredientAmount, "Ingredient amount must be in fractional form or just numeric. Example 1/2")
                    valid = False
                End If

            Else
                'validate the number then, is not a fraction
                'else error
                If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.RecipeIngredientAmount, txtIngredientAmount.Text, True) Then
                    ErrorProviderAddRecipe.SetError(txtIngredientAmount, "")
                Else
                    ErrorProviderAddRecipe.SetError(txtIngredientAmount, "Ingredient amount must be in fractional form or just numeric. Example 1/2")
                    valid = False
                End If
            End If

        Else
            ErrorProviderAddRecipe.SetError(txtIngredientAmount, "Must enter a numeric value or a fraction value, no decimals.")
            valid = False
        End If

        'Validate Ingredient Name
        If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.IngredientsName, cboIngredientName.Text, True) Then
            ErrorProviderAddRecipe.SetError(cboIngredientName, "")
        Else
            ErrorProviderAddRecipe.SetError(cboIngredientName, "Ingredient name must be between 1 and 50 characters.")
            valid = False
        End If

        'if data is valid continue
        If valid Then

            'Check if there are multiple rows already in the datagridview
            If dgvIngredients.RowCount > 0 Then
                'If there are multiple rows check for ingredients with the same name
                'if user selects the no button then the ingredient will not be added and the sub will exit
                For Each row1 As DataGridViewRow In dgvIngredients.Rows
                    If CStr(row1.Cells("colIngredientName").Value) = cboIngredientName.Text Then
                        If Not MessageBox.Show("There is another ingredient with the same name. Would you still like to add it?", "Multiple Ingredient Insert", _
                                           MessageBoxButtons.YesNo, MessageBoxIcon.Information) = Windows.Forms.DialogResult.Yes Then
                            Exit Sub
                        End If
                    End If
                Next
            End If

            btnDelete.Enabled = True


            Dim newIngredientExist As Boolean = recipeService.checkIngredientExist(cboIngredientName.Text)
            Dim returnValue As Integer

            'IF the Ingredient Name combobox has changed AndAlso does not exist
            'AndALSO if user wants to add the new ingredient to the ingredient database
            'Insert ingredient into database THEN 
            'Add row to ingredient datagridview THEN 
            'Update ingredient combo box
            'ELSE add row to ingredient datagridview
            If comboIngredientChanged = True AndAlso newIngredientExist = False AndAlso MessageBox.Show("Would you like to add this ingredient to the ingredient database?", _
                       "Add Ingredient", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
                returnValue = recipeService.insertIngredient(cboIngredientName.Text, CInt(cbIngredientType.SelectedValue))
                If returnValue > 0 Then
                    'Raise event to update status label Add the new row to the Ingredient datagridview
                    RaiseEvent UpdateStatus("Ingredient Inserted Sucessfully")

                    Dim row() As String = {cboIngredientName.Text, txtIngredientAmount.Text, cbUnitMeasurements.Text, _
                                           cbIngredientType.Text, cboIngredientName.ValueMember.ToString, _
                                       cbUnitMeasurements.ValueMember.ToString, cbIngredientType.ValueMember.ToString}
                    dgvIngredients.Rows.Add(row)

                    'ReFill Ingredient Name combobox
                    With cboIngredientName
                        .DataSource = recipeService.retrieveIngredients
                        .DisplayMember = "Name"
                        .ValueMember = "IngredientID"
                        .SelectedIndex = 0
                    End With
                    comboIngredientChanged = False

                Else
                    RaiseEvent UpdateStatus("Ingredient was not inserted")
                End If


            Else
                'Add the new row to the Ingredient datagridview
                Dim row() As String = {cboIngredientName.Text, txtIngredientAmount.Text, cbUnitMeasurements.Text, _
                                       cbIngredientType.Text, cboIngredientName.ValueMember.ToString, _
                                    cbUnitMeasurements.ValueMember.ToString, cbIngredientType.ValueMember.ToString}
                dgvIngredients.Rows.Add(row)
            End If


            'clear textboxes
            txtIngredientAmount.Text = ""
            cbIngredientType.SelectedIndex = 0
            cboIngredientName.SelectedIndex = 0
            cbUnitMeasurements.SelectedIndex = 0
        End If

    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        'if the current row is selected then delete the currently selected row and check to enable the delete button
        If Not dgvIngredients.CurrentRow Is Nothing Then
            dgvIngredients.Rows.Remove(dgvIngredients.CurrentRow)

            If dgvIngredients.RowCount <= 0 Then
                btnDelete.Enabled = False
            End If

        End If

    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

        Try
            'Validate the data in the recipe form and make sure it has ingredients
            If validateRecipeData() = True And dgvIngredients.RowCount > 0 Then

                'Create a new recipe table and row
                Dim recipeTable As New RecipeHolderDatabaseDataSet.RecipesDataTable

                Dim recipeRow As EntitiesLayer.RecipeHolderDatabaseDataSet.RecipesRow = recipeData.Recipes.NewRecipesRow
                'Create a new nutrition table and row
                Dim nutritionTable As New RecipeHolderDatabaseDataSet.NutritionDetailsDataTable
                Dim nutritionRow As EntitiesLayer.RecipeHolderDatabaseDataSet.NutritionDetailsRow = recipeData.NutritionDetails.NewNutritionDetailsRow
                'Create a new ingredient table and row
                Dim ingredientTable As New RecipeHolderDatabaseDataSet.RecipeIngredientDataTable
                Dim ingredientRow As EntitiesLayer.RecipeHolderDatabaseDataSet.RecipeIngredientRow = recipeData.RecipeIngredient.NewRecipeIngredientRow

                'Check to see if file exists and if it does, turn the file into bytes to store in the database
                'Else set field to null and save it like that in the datatbase
                If File.Exists(txtFilePathPhoto.Text) Then
                    Dim tempByte() As Byte = Nothing
                    Dim fileInfo As New IO.FileInfo(txtFilePathPhoto.Text)
                    Dim NumBytes As Long = fileInfo.Length
                    Dim FStream As New IO.FileStream(txtFilePathPhoto.Text, IO.FileMode.Open, IO.FileAccess.Read)
                    Dim BinaryReader As New IO.BinaryReader(FStream)
                    tempByte = BinaryReader.ReadBytes(Convert.ToInt32(NumBytes))
                    recipeRow.Photo = tempByte
                    FStream.Dispose()
                Else
                    Dim nullArray() As Byte = Nothing
                    recipeRow.Photo = nullArray
                End If

                'Add data to the recipe row and add it to the dataset
                With recipeRow
                    .Name = txtRecipeName.Text
                    .CookTime = CInt(txtCookTime.Text)
                    .PreparationTime = CInt(txtPreparationTime.Text)
                    .Directions = txtDirections.Text
                    .Temperature = CInt(txtTemperature.Text)
                    .CourseTypeID = CInt(cbCourseType.SelectedValue)
                    .CuisineTypeID = CInt(cbCuisineStyle.SelectedValue)
                    .AccountId = 18 'CInt(modGlobals.CurrentUserId)
                End With
                Me.recipeData.Recipes.Rows.Add(recipeRow)

                'Add data to the nutrion row and add it to the dataset
                With nutritionRow
                    .Calories = CDbl(txtCalories.Text)
                    .CaloriesFromFat = CDbl(txtCaloriesFromFay.Text)
                    .Cholesteral = CDbl(txtCholesteral.Text)
                    .DietaryFiber = CDbl(txtDietaryFiber.Text)
                    .SaturatedFat = CDbl(txtSaturatedFat.Text)
                    .TotalCarbohydrates = CDbl(txtTotalCarbohydrate.Text)
                    .TotalFat = CDbl(txtTotalFat.Text)
                    .TransFat = CDbl(txtTransFat.Text)
                    .Protein = CDbl(txtProtein.Text)
                    .Sodium = CDbl(txtSodium.Text)
                    .Sugar = CDbl(txtSugar.Text)
                    .VitaminC = CInt(txtVitaminC.Text)
                    .VitaminA = CInt(txtVitaminA.Text)
                    .Iron = CInt(txtIron.Text)
                    .Calcium = CInt(txtCalcium.Text)
                    .RecipeID = recipeRow.RecipeID
                End With
                Me.recipeData.NutritionDetails.Rows.Add(nutritionRow)

                'Add ingredient rows to the typed dataset
                For Each row As DataGridViewRow In dgvIngredients.Rows

                    With ingredientRow
                        .RecipeID = recipeRow.RecipeID
                        .IngredientID = CInt(row.Cells("colIngredientId").Value)
                        .UnitMeasurementID = CInt(row.Cells("colUnitMeasurementId").Value)
                        .IngredientAmount = CDec(row.Cells("colIngredientAmount").Value)

                    End With

                    Me.recipeData.RecipeIngredient.Rows.Add(ingredientRow)
                Next

                'If dataset has errors...send an error out
                'Else is the dataset has changes ....go and save it
                If recipeData.HasErrors Then
                    For Each row As RecipeHolderDatabaseDataSet.RecipesRow In recipeData.Recipes.Rows
                        Console.WriteLine(row.RowError)
                    Next
                ElseIf recipeData.HasChanges Then
                    recipeService.saveRecipe(recipeData)
                End If

            End If

        Catch ex As DataException
            MessageBox.Show(ex.Message)
        Catch ex As SqlException
            MessageBox.Show(ex.Message)
        Catch ex As InvalidCastException
            MessageBox.Show(ex.Message)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub

    Private Sub btnView_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnView.Click
        If File.Exists(txtFilePathPhoto.Text) Then
            ErrorProviderAddRecipe.SetError(txtFilePathPhoto, "")
            AutosizeImage(txtFilePathPhoto.Text, pbRecipePhoto)
        Else
            ErrorProviderAddRecipe.SetError(txtFilePathPhoto, "File path is not valid.")
        End If

        ' Catch ex As System.Security.SecurityException
        '    ' Let the user know the save won't work. 
        '    MessageBox.Show("Permission to save the file was denied, " & _
        '       "and the bitmap was not saved.")
        'Catch ex As System.Exception
        '    ' React to other exceptions here.
        '    MessageBox.Show("Unable to create and save the bitmap.")
        'End Try

    End Sub

    Private Sub cboIngredientName_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboIngredientName.SelectedIndexChanged
        comboIngredientChanged = False
    End Sub

    Private Sub cboIngredientName_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboIngredientName.TextChanged
        comboIngredientChanged = True
    End Sub

    ''' <summary>
    ''' Allows only digits in a textbox
    ''' </summary>
    ''' <param name="sender">Object that raised the event</param>
    ''' <param name="e">Information about the evnet</param>
    ''' <remarks></remarks>
    Private Sub allowOnlyDigits_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtPreparationTime.KeyPress, txtTemperature.KeyPress, _
    txtCookTime.KeyPress, txtCalories.KeyPress, txtCaloriesFromFay.KeyPress, txtTotalFat.KeyPress, txtSaturatedFat.KeyPress, _
    txtTransFat.KeyPress, txtCholesteral.KeyPress, txtSodium.KeyPress, txtTotalCarbohydrate.KeyPress, txtDietaryFiber.KeyPress, _
    txtSugar.KeyPress, txtProtein.KeyPress, txtVitaminA.KeyPress, txtVitaminC.KeyPress, txtCalcium.KeyPress, txtIron.KeyPress

        validator.ValidateAddRecipeFormInstance.textboxOnlyDigits(sender, e)

    End Sub

    Private Sub txtIngredientAmount_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtIngredientAmount.KeyPress
        validator.ValidateAddRecipeFormInstance.validateIngredientAmount(sender, e)
    End Sub

#End Region

#Region "Custom Subs, Functions"

    ''' <summary>
    ''' Autozizes an image to fit the picture box
    ''' </summary>
    ''' <param name="imagePath">The path to the image</param>
    ''' <param name="picBox">The picturebox that will hold the image being resized</param>
    ''' <param name="pSizeMode">Optional mode on the picture box. User can center image as default</param>
    ''' <remarks></remarks>
    Public Sub AutosizeImage(ByVal imagePath As String, ByVal picBox As PictureBox, Optional ByVal pSizeMode As PictureBoxSizeMode = PictureBoxSizeMode.CenterImage)
        Try
            picBox.Image = Nothing
            picBox.SizeMode = pSizeMode
            If System.IO.File.Exists(imagePath) Then
                Dim imgOrg As Bitmap
                Dim imgShow As Bitmap
                Dim g As Graphics
                Dim divideBy, divideByH, divideByW As Double
                imgOrg = DirectCast(Bitmap.FromFile(imagePath), Bitmap)

                divideByW = imgOrg.Width / picBox.Width
                divideByH = imgOrg.Height / picBox.Height
                If divideByW > 1 Or divideByH > 1 Then
                    If divideByW > divideByH Then
                        divideBy = divideByW
                    Else
                        divideBy = divideByH
                    End If

                    imgShow = New Bitmap(CInt(CDbl(imgOrg.Width) / divideBy), CInt(CDbl(imgOrg.Height) / divideBy))
                    imgShow.SetResolution(imgOrg.HorizontalResolution, imgOrg.VerticalResolution)
                    g = Graphics.FromImage(imgShow)
                    g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
                    g.DrawImage(imgOrg, New Rectangle(0, 0, CInt(CDbl(imgOrg.Width) / divideBy), CInt(CDbl(imgOrg.Height) / divideBy)), 0, 0, imgOrg.Width, imgOrg.Height, GraphicsUnit.Pixel)
                    g.Dispose()
                Else
                    imgShow = New Bitmap(imgOrg.Width, imgOrg.Height)
                    imgShow.SetResolution(imgOrg.HorizontalResolution, imgOrg.VerticalResolution)
                    g = Graphics.FromImage(imgShow)
                    g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
                    g.DrawImage(imgOrg, New Rectangle(0, 0, imgOrg.Width, imgOrg.Height), 0, 0, imgOrg.Width, imgOrg.Height, GraphicsUnit.Pixel)
                    g.Dispose()
                End If
                imgOrg.Dispose()

                picBox.Image = imgShow
            Else
                picBox.Image = Nothing
            End If

        Catch ex As IO.DirectoryNotFoundException
            MessageBox.Show(ex.ToString)
        Catch ex As IO.FileNotFoundException
            MessageBox.Show(ex.ToString)
        Catch ex As IOException
            MsgBox(ex.ToString)
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

    End Sub

    Function decimalToFractionc(ByVal dblDecimal As Double) As String


        Dim intNumerator, intDenominator, intNegative As Integer
        ' Declare integer variables 
        Dim dblFraction, dblAccuracy As Double
        ' Declare floating point variables as double precision.
        Dim txtDecimal As String
        ' need a string representation of the input value
        ' in order to determine the required accuracy.

        ' Find the accuracy needed for the output by checking the number of digits behind the decimal point
        '   of the input value.
        '
        '    dblAccuracy = 1 / 10 ^ (Len(CStr(dblDecimal - Fix(dblDecimal))) - 2)
        '
        '   While the formula above should work, there is a serious error in the way Excel handles
        '   decimal numbers and there's a huge rounding error issue.  Subtracting the int() of
        '   12.1 from 12.1 produces 0.0999999999 or something similar.  Obviously that won't
        '   work for our desired accuracy of the magnitude of the fractional part of the number
        '   so a slower more cumbersome method has to be used...

        dblAccuracy = 0.1                                       ' Set the initial Accuracy level.
        txtDecimal = dblDecimal.ToString                        ' Get a  string representation of the input number.

        For i As Integer = 0 To (txtDecimal.Length - 1)                                 ' Check each character to see if it's a decimal point...
            If txtDecimal.Substring(i, 1) = "." Then                    ' if it is then we get the number of digits behind the decimal
                dblAccuracy = 1 / 10 ^ (txtDecimal.Length - i)    '   assign the new accuracy level, and
                Exit For                                            '   exit the for loop.
            End If
        Next

        intNumerator = 0                                ' Set the initial numerator value to 0.
        intDenominator = 1                              ' Set the initial denominator value to 1.
        intNegative = 1                                 ' Set the negative value flag to positive.

        If dblDecimal < 0 Then
            intNegative = -1 ' If the desired decimal value is negative,
            '   then set the negative value flag to
            '   negative.
        End If

        dblFraction = 0                                 ' Set the fraction value to be 0/1.

        Do While Math.Abs(dblFraction - dblDecimal) > dblAccuracy   ' As long as we're still outside the
            '   desired accuracy, then...
            If Math.Abs(dblFraction) > Math.Abs(dblDecimal) Then      ' If our fraction is too big,
                intDenominator += 1         '   increase the denominator
            Else                                            ' Otherwise
                intNumerator += intNegative   '   increase the numerator.
            End If

            dblFraction = intNumerator / intDenominator     ' Set the new value of the fraction.

        Loop

        Return intNumerator.ToString & "/" & intDenominator.ToString ' Display the numerator and denominator
    End Function

    ''' <summary>
    ''' Converts a fraction to its decimal equivalent
    ''' </summary>
    ''' <param name="frac">The fraction to convert to decimal</param>
    ''' <returns>Decimal value</returns>
    ''' <remarks></remarks>
    Public Function FractionToDecimal(ByVal frac As String) As String

        Dim decimalVal As String = "0"
        Dim upper As Decimal = 0
        Dim lower As Decimal = 0
        Dim remain As Decimal = 0
        If frac.IndexOf("/") <> -1 Then

            If frac.IndexOf(" ") <> -1 Then
                remain = CType(frac.Substring(0, frac.IndexOf(" ")), Decimal)
                frac = frac.Substring(frac.IndexOf(" "))
            End If

        End If
        upper = CType(frac.Substring(0, frac.IndexOf("/")), Decimal)
        lower = CType(frac.Substring(frac.IndexOf("/") + 1), Decimal)
        If upper > lower Then
            Return "Error Please Check Fraction"
        Else
            decimalVal = (remain + (upper / lower)).ToString
        End If

        Return decimalVal
    End Function

    ''' <summary>
    ''' Validates the data on the add recipe form. Sends the data to the PresentationValidation module
    ''' </summary>
    ''' <returns>True, the data is valid or false, the data is not valid.</returns>
    ''' <remarks></remarks>
    Public Function validateRecipeData() As Boolean
        Dim valid As Boolean = True

        'txtRecipeName
        If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.RecipeName, txtRecipeName.Text, True) Then
            ErrorProviderAddRecipe.SetError(txtRecipeName, "")
        Else
            ErrorProviderAddRecipe.SetError(txtRecipeName, "Recipe name must be between 1 and 50 characters.")
            valid = False
        End If
        'txtCookTime
        If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.RecipeCookTime, txtCookTime.Text, True) Then
            ErrorProviderAddRecipe.SetError(txtCookTime, "")
        Else
            ErrorProviderAddRecipe.SetError(txtCookTime, "Cook time must be between 0 and 100000 minutes.")
            valid = False
        End If
        'txtPreparationTime
        If String.IsNullOrEmpty(txtPreparationTime.Text) Then
            ErrorProviderAddRecipe.SetError(txtPreparationTime, "")
            txtPreparationTime.Text = "0"
        Else
            If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.RecipePreparation, txtPreparationTime.Text, False) Then
                ErrorProviderAddRecipe.SetError(txtPreparationTime, "")
            Else
                ErrorProviderAddRecipe.SetError(txtPreparationTime, "Preparation time must be between 0 and 100000 minutes.")
                valid = False
            End If

        End If

        'txtTemperature
        If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.RecipeTemperature, txtTemperature.Text, True) Then
            ErrorProviderAddRecipe.SetError(txtTemperature, "")
        Else
            ErrorProviderAddRecipe.SetError(txtTemperature, "Temperature must be between 0 and 2000 degrees.")
            valid = False
        End If
        'txtDirections
        If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.RecipeDirections, txtDirections.Text, True) Then
            ErrorProviderAddRecipe.SetError(txtDirections, "")
        Else
            ErrorProviderAddRecipe.SetError(txtDirections, "Directions must be between 1 and 3000 characters.")
            valid = False
        End If
        'txtFilePathPhoto
        If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.RecipePhoto, txtFilePathPhoto.Text, False) Then
            ErrorProviderAddRecipe.SetError(txtFilePathPhoto, "")
        Else
            valid = False
            ErrorProviderAddRecipe.SetError(txtFilePathPhoto, "Recipe photo needs a valid file path but is not required.")
        End If
        'Course Type
        If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.CourseTypesName, cbCourseType.Text, True) Then
            ErrorProviderAddRecipe.SetError(cbCourseType, "")
        Else
            ErrorProviderAddRecipe.SetError(cbCourseType, "Course Type must be between 1 and 50 characters.")
            valid = False
        End If

        'Cuisine Style
        If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.CuisineTypesName, cbCuisineStyle.Text, True) Then
            ErrorProviderAddRecipe.SetError(cbCuisineStyle, "")
        Else
            ErrorProviderAddRecipe.SetError(cbCuisineStyle, "Cuisine style must be between 1 and 50 characters.")
            valid = False
        End If


        Dim errorMess As String = "Not required. Must be between 0 - 999999."
        'Calories
        If String.IsNullOrEmpty(txtCalories.Text) Then
            ErrorProviderAddRecipe.SetError(txtCalories, "")
            txtCalories.Text = "0.0"
        Else
            If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.NutritionCalories, txtCalories.Text, False) Then
                ErrorProviderAddRecipe.SetError(txtCalories, "")
            Else
                valid = False
                ErrorProviderAddRecipe.SetError(txtCalories, errorMess)

            End If
        End If
        'Calories From Fat
        If String.IsNullOrEmpty(txtCaloriesFromFay.Text) Then
            ErrorProviderAddRecipe.SetError(txtCaloriesFromFay, "")
            txtCaloriesFromFay.Text = "0.0"
        Else
            If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.NutritionCaloriesFromFat, txtCaloriesFromFay.Text, False) Then
                ErrorProviderAddRecipe.SetError(txtCaloriesFromFay, "")
            Else
                valid = False
                ErrorProviderAddRecipe.SetError(txtCaloriesFromFay, errorMess)

            End If
        End If
        'Total Fat
        If String.IsNullOrEmpty(txtTotalFat.Text) Then
            ErrorProviderAddRecipe.SetError(txtTotalFat, "")
            txtTotalFat.Text = "0.0"
        Else
            If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.NutritionTotalFat, txtTotalFat.Text, False) Then
                ErrorProviderAddRecipe.SetError(txtTotalFat, "")
            Else
                valid = False
                ErrorProviderAddRecipe.SetError(txtTotalFat, errorMess)

            End If
        End If
        'Saturated Fat
        If String.IsNullOrEmpty(txtSaturatedFat.Text) Then
            ErrorProviderAddRecipe.SetError(txtSaturatedFat, "")
            txtSaturatedFat.Text = "0.0"
        Else
            If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.NutritionSaturatedFat, txtSaturatedFat.Text, False) Then
                ErrorProviderAddRecipe.SetError(txtSaturatedFat, "")
            Else
                valid = False
                ErrorProviderAddRecipe.SetError(txtSaturatedFat, errorMess)

            End If
        End If
        'Trans Fat
        If String.IsNullOrEmpty(txtTransFat.Text) Then
            ErrorProviderAddRecipe.SetError(txtTransFat, "")
            txtTransFat.Text = "0.0"
        Else
            If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.NutritionTransFat, txtTransFat.Text, False) Then
                ErrorProviderAddRecipe.SetError(txtTransFat, "")
            Else
                valid = False
                ErrorProviderAddRecipe.SetError(txtTransFat, errorMess)

            End If
        End If

        If String.IsNullOrEmpty(txtCholesteral.Text) Then
            ErrorProviderAddRecipe.SetError(txtCholesteral, "")
            txtCholesteral.Text = "0.0"
        Else
            If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.NutritionCholesteral, txtCholesteral.Text, False) Then
                ErrorProviderAddRecipe.SetError(txtCholesteral, "")
            Else
                valid = False
                ErrorProviderAddRecipe.SetError(txtCholesteral, errorMess)

            End If
        End If

        If String.IsNullOrEmpty(txtSodium.Text) Then
            ErrorProviderAddRecipe.SetError(txtSodium, "")
            txtSodium.Text = "0.0"
        Else
            If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.NutritionSodium, txtSodium.Text, False) Then
                ErrorProviderAddRecipe.SetError(txtSodium, "")
            Else
                valid = False
                ErrorProviderAddRecipe.SetError(txtSodium, errorMess)

            End If
        End If

        If String.IsNullOrEmpty(txtTotalCarbohydrate.Text) Then
            ErrorProviderAddRecipe.SetError(txtTotalCarbohydrate, "")
            txtTotalCarbohydrate.Text = "0.0"
        Else
            If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.NutritionTotalCarbohydrates, txtTotalCarbohydrate.Text, False) Then
                ErrorProviderAddRecipe.SetError(txtTotalCarbohydrate, "")
            Else
                valid = False
                ErrorProviderAddRecipe.SetError(txtTotalCarbohydrate, errorMess)

            End If
        End If

        If String.IsNullOrEmpty(txtDietaryFiber.Text) Then
            ErrorProviderAddRecipe.SetError(txtDietaryFiber, "")
            txtDietaryFiber.Text = "0.0"
        Else
            If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.NutritionDietaryFiber, txtDietaryFiber.Text, False) Then
                ErrorProviderAddRecipe.SetError(txtDietaryFiber, "")
            Else
                valid = False
                ErrorProviderAddRecipe.SetError(txtDietaryFiber, errorMess)

            End If
        End If

        If String.IsNullOrEmpty(txtSugar.Text) Then
            ErrorProviderAddRecipe.SetError(txtSugar, "")
            txtSugar.Text = "0.0"
        Else
            If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.NutritionSugar, txtSugar.Text, False) Then
                ErrorProviderAddRecipe.SetError(txtSugar, "")
            Else
                valid = False
                ErrorProviderAddRecipe.SetError(txtSugar, errorMess)

            End If
        End If

        If String.IsNullOrEmpty(txtProtein.Text) Then
            ErrorProviderAddRecipe.SetError(txtProtein, "")
            txtProtein.Text = "0.0"
        Else
            If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.NutritionProtein, txtProtein.Text, False) Then
                ErrorProviderAddRecipe.SetError(txtProtein, "")
            Else
                valid = False
                ErrorProviderAddRecipe.SetError(txtProtein, errorMess)

            End If
        End If

        If String.IsNullOrEmpty(txtVitaminA.Text) Then
            ErrorProviderAddRecipe.SetError(txtVitaminA, "")
            txtVitaminA.Text = "0"
        Else
            If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.NutritionVitaminA, txtVitaminA.Text, False) Then
                ErrorProviderAddRecipe.SetError(txtVitaminA, "")
            Else
                valid = False
                ErrorProviderAddRecipe.SetError(txtVitaminA, errorMess)

            End If
        End If

        If String.IsNullOrEmpty(txtVitaminC.Text) Then
            ErrorProviderAddRecipe.SetError(txtVitaminC, "")
            txtVitaminC.Text = "0"
        Else
            If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.NutritionVitaminC, txtVitaminC.Text, False) Then
                ErrorProviderAddRecipe.SetError(txtVitaminC, "")
            Else
                valid = False
                ErrorProviderAddRecipe.SetError(txtVitaminC, errorMess)

            End If
        End If

        If String.IsNullOrEmpty(txtCalcium.Text) Then
            ErrorProviderAddRecipe.SetError(txtCalcium, "")
            txtCalcium.Text = "0"
        Else
            If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.NutritionCalcium, txtCalcium.Text, False) Then
                ErrorProviderAddRecipe.SetError(txtCalcium, "")
            Else
                valid = False
                ErrorProviderAddRecipe.SetError(txtCalcium, errorMess)

            End If
        End If

        If String.IsNullOrEmpty(txtIron.Text) Then
            ErrorProviderAddRecipe.SetError(txtIron, "")
            txtIron.Text = "0"
        Else
            If validator.ValidateAddRecipeFormInstance.validateRecipeData(PresentationValidation.ValidateAddRecipeForm.FieldNames.NutritionIron, txtIron.Text, False) Then
                ErrorProviderAddRecipe.SetError(txtIron, "")
            Else
                valid = False
                ErrorProviderAddRecipe.SetError(txtIron, errorMess)

            End If
        End If

        'return if there are any errors or not
        Return valid

    End Function



#End Region

End Class