Click here to Skip to main content
15,881,588 members
Articles / Programming Languages / C#

CooksMate

Rate me:
Please Sign up or sign in to vote.
3.32/5 (8 votes)
21 Jan 2008GPL32 min read 56.1K   1K   23  
A simple program to help get the timing of a roast dinner
/*
 * Created by SharpDevelop.
 * User: andy
 * Date: 21/12/2007
 * Time: 18:41
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.IO;
using System.Data;
using System.Drawing;
using System.Resources;
using System.Reflection;
using System.Drawing.Text;
using System.Collections;
using System.Windows.Forms;
using log4net;

using uk.org.aspellclark.common;
using uk.org.aspellclark.cooksmate.engine;

namespace uk.org.aspellclark.cooksmate
{
    /// <summary>
    ///   <name>MainForm</name>
    ///   <namespace>uk.org.aspellclark.todolist</namespace>
    ///   <version>1.0</version>
    ///   <author>Andy Aspell-Clark</author>
    ///   <description>This is the main form of the todolist application
    ///   </description>
    ///   <history>
    ///     <historyitem> 1 Jan 2008  1.0 ARAC  Initial Version.</historyitem>
    ///   </history>
    /// </summary>
    public class MainForm : Form
    {
    	private const string PREF_LAST_OPENED_FILE = "LastOpenedFile";
    	
        #region members

        // Create a logger for use in this class
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private const string CREATE_NEW_RECIPE_STRING = "New Recipe...";
        private const string NEW_RECIPE_NAME = "New Recipe";
        
		private PrivateFontCollection pfc = new PrivateFontCollection();
	
        private PreferencesXml prefs = null;
        private DataEngine dataEngine=null;

        private System.ComponentModel.IContainer components;
        private System.Windows.Forms.MenuItem mnuFile;
        private System.Windows.Forms.MenuItem mnuFileNew;
        private System.Windows.Forms.MenuItem mnuFileOpen;
        private System.Windows.Forms.MenuItem mnuFileSave;
        private System.Windows.Forms.MenuItem mnuFileSaveAs;
        private System.Windows.Forms.MenuItem mnuFileExit;
        private System.Windows.Forms.MenuItem mnuRecipe;
        private System.Windows.Forms.MenuItem mnuRecipeNew;
        private System.Windows.Forms.MenuItem mnuRecipeEdit;
        private System.Windows.Forms.MenuItem mnuRecipeDelete;
        private System.Windows.Forms.MenuItem mnuHelp;
        private System.Windows.Forms.MenuItem mnuHelpAbout;
        private System.Windows.Forms.MainMenu mainMenu1;
        

        private bool tablesAlreadySetup = false;
        private DataSet dataSetActions = new DataSet("actionsData"); 
        private DataTable dataTblActions = new DataTable("actionsTbl");
        private DataColumn datColActionDone = new DataColumn("done", typeof(System.Boolean));
        private DataColumn datColActionMins = new DataColumn("mins", typeof(string));
        private DataColumn datColActionName = new DataColumn("name", typeof(string));
        private DataColumn datColActionWeight = new DataColumn("weight", typeof(string));
        private DataColumn datColActionMethod = new DataColumn("method", typeof(string));
        private DataColumn datColActionStart = new DataColumn("start", typeof(string));
        
        #endregion      
        
        
        /// <summary>
        /// main form constructor
        /// </summary>
        public MainForm(PreferencesXml prefs)
        {
            log.Info("Constructing");
            this.prefs = prefs;
            //LoadFonts();
            
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();
            
            dataEngine = new DataEngine();
        }

        private void LoadFonts()
        {
        	log.Info("Loading fonts");

        	//load the resource
			Stream fontStream = this.GetType().Assembly.GetManifestResourceStream("uk.org.aspellclark.cooksmate.PIPED.TTF");

			byte[] fontdata = new byte[fontStream.Length];
			fontStream.Read(fontdata,0,(int)fontStream.Length);
			fontStream.Close();
			
			unsafe
			{
				fixed(byte * pFontData = fontdata)
				{
					pfc.AddMemoryFont((System.IntPtr)pFontData,fontdata.Length);
				}
			}
        }
        

        #region Windows Forms Designer generated code
        /// <summary>
        /// This method is required for Windows Forms designer support.
        /// Do not change the method contents inside the source code editor. The Forms designer might
        /// not be able to load this method if it was changed manually.
        /// </summary>
        private void InitializeComponent() {
        	this.components = new System.ComponentModel.Container();
        	this.mainMenu1 = new System.Windows.Forms.MainMenu();
        	this.mnuFile = new System.Windows.Forms.MenuItem();
        	this.mnuFileNew = new System.Windows.Forms.MenuItem();
        	this.mnuFileOpen = new System.Windows.Forms.MenuItem();
        	this.mnuFileSave = new System.Windows.Forms.MenuItem();
        	this.mnuFileSaveAs = new System.Windows.Forms.MenuItem();
        	this.mnuFileExit = new System.Windows.Forms.MenuItem();
        	this.mnuHelp = new System.Windows.Forms.MenuItem();
        	this.mnuHelpAbout = new System.Windows.Forms.MenuItem();
        	this.cmbRecipeSelection = new System.Windows.Forms.ComboBox();
        	this.pnlPictures = new System.Windows.Forms.Panel();
        	this.pictureStatus = new System.Windows.Forms.PictureBox();
        	this.pictureAction = new System.Windows.Forms.PictureBox();
        	this.statusStrip1 = new System.Windows.Forms.StatusStrip();
        	this.label1 = new System.Windows.Forms.Label();
        	this.timePicker = new System.Windows.Forms.DateTimePicker();
        	this.dataGridActions = new System.Windows.Forms.DataGrid();
        	this.lblCurrTime = new System.Windows.Forms.Label();
        	this.timerCurrentTime = new System.Windows.Forms.Timer(this.components);
        	this.timerActionDue = new System.Windows.Forms.Timer(this.components);
        	this.lblNextStep = new System.Windows.Forms.Label();
        	this.pnlPictures.SuspendLayout();
        	((System.ComponentModel.ISupportInitialize)(this.pictureStatus)).BeginInit();
        	((System.ComponentModel.ISupportInitialize)(this.pictureAction)).BeginInit();
        	((System.ComponentModel.ISupportInitialize)(this.dataGridActions)).BeginInit();
        	this.SuspendLayout();
        	// 
        	// mainMenu1
        	// 
        	this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
        	        	        	this.mnuFile,
        	        	        	this.mnuHelp});
        	// 
        	// mnuFile
        	// 
        	this.mnuFile.Index = 0;
        	this.mnuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
        	        	        	this.mnuFileNew,
        	        	        	this.mnuFileOpen,
        	        	        	this.mnuFileSave,
        	        	        	this.mnuFileSaveAs,
        	        	        	this.mnuFileExit});
        	this.mnuFile.Text = "File";
        	// 
        	// mnuFileNew
        	// 
        	this.mnuFileNew.Index = 0;
        	this.mnuFileNew.Text = "New";
        	this.mnuFileNew.Click += new System.EventHandler(this.MnuFileNewClick);
        	// 
        	// mnuFileOpen
        	// 
        	this.mnuFileOpen.Index = 1;
        	this.mnuFileOpen.Text = "Open";
        	this.mnuFileOpen.Click += new System.EventHandler(this.MnuFileOpenClick);
        	// 
        	// mnuFileSave
        	// 
        	this.mnuFileSave.Index = 2;
        	this.mnuFileSave.Text = "Save";
        	this.mnuFileSave.Click += new System.EventHandler(this.MnuFileSaveClick);
        	// 
        	// mnuFileSaveAs
        	// 
        	this.mnuFileSaveAs.Index = 3;
        	this.mnuFileSaveAs.Text = "Save As";
        	this.mnuFileSaveAs.Click += new System.EventHandler(this.MnuFileSaveAsClick);
        	// 
        	// mnuFileExit
        	// 
        	this.mnuFileExit.Index = 4;
        	this.mnuFileExit.Text = "Exit";
        	this.mnuFileExit.Click += new System.EventHandler(this.MnuFileExitClick);
        	// 
        	// mnuHelp
        	// 
        	this.mnuHelp.Index = 1;
        	this.mnuHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
        	        	        	this.mnuHelpAbout});
        	this.mnuHelp.Text = "Help";
        	// 
        	// mnuHelpAbout
        	// 
        	this.mnuHelpAbout.Index = 0;
        	this.mnuHelpAbout.Text = "About";
        	this.mnuHelpAbout.Click += new System.EventHandler(this.MnuHelpAboutClick);
        	// 
        	// cmbRecipeSelection
        	// 
        	this.cmbRecipeSelection.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
        	        	        	| System.Windows.Forms.AnchorStyles.Right)));
        	this.cmbRecipeSelection.FormattingEnabled = true;
        	this.cmbRecipeSelection.Location = new System.Drawing.Point(190, 3);
        	this.cmbRecipeSelection.Name = "cmbRecipeSelection";
        	this.cmbRecipeSelection.Size = new System.Drawing.Size(309, 21);
        	this.cmbRecipeSelection.TabIndex = 1;
        	this.cmbRecipeSelection.SelectedIndexChanged += new System.EventHandler(this.CmbRecipeSelectionSelectedIndexChanged);
        	// 
        	// pnlPictures
        	// 
        	this.pnlPictures.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
        	        	        	| System.Windows.Forms.AnchorStyles.Left)));
        	this.pnlPictures.Controls.Add(this.pictureStatus);
        	this.pnlPictures.Controls.Add(this.pictureAction);
        	this.pnlPictures.Location = new System.Drawing.Point(7, 77);
        	this.pnlPictures.Name = "pnlPictures";
        	this.pnlPictures.Size = new System.Drawing.Size(172, 180);
        	this.pnlPictures.TabIndex = 3;
        	this.pnlPictures.Resize += new System.EventHandler(this.PnlPicturesResize);
        	// 
        	// pictureStatus
        	// 
        	this.pictureStatus.Anchor = System.Windows.Forms.AnchorStyles.None;
        	this.pictureStatus.Location = new System.Drawing.Point(0, 101);
        	this.pictureStatus.Margin = new System.Windows.Forms.Padding(0);
        	this.pictureStatus.Name = "pictureStatus";
        	this.pictureStatus.Size = new System.Drawing.Size(171, 79);
        	this.pictureStatus.TabIndex = 1;
        	this.pictureStatus.TabStop = false;
        	// 
        	// pictureAction
        	// 
        	this.pictureAction.Anchor = System.Windows.Forms.AnchorStyles.None;
        	this.pictureAction.Location = new System.Drawing.Point(0, -2);
        	this.pictureAction.Margin = new System.Windows.Forms.Padding(0);
        	this.pictureAction.Name = "pictureAction";
        	this.pictureAction.Size = new System.Drawing.Size(172, 47);
        	this.pictureAction.TabIndex = 0;
        	this.pictureAction.TabStop = false;
        	// 
        	// statusStrip1
        	// 
        	this.statusStrip1.Location = new System.Drawing.Point(0, 268);
        	this.statusStrip1.Name = "statusStrip1";
        	this.statusStrip1.Size = new System.Drawing.Size(499, 22);
        	this.statusStrip1.TabIndex = 4;
        	this.statusStrip1.Text = "statusStrip1";
        	// 
        	// label1
        	// 
        	this.label1.Location = new System.Drawing.Point(6, 8);
        	this.label1.Name = "label1";
        	this.label1.Size = new System.Drawing.Size(61, 15);
        	this.label1.TabIndex = 5;
        	this.label1.Text = "Serve At:";
        	// 
        	// timePicker
        	// 
        	this.timePicker.Format = System.Windows.Forms.DateTimePickerFormat.Time;
        	this.timePicker.Location = new System.Drawing.Point(61, 4);
        	this.timePicker.Name = "timePicker";
        	this.timePicker.ShowUpDown = true;
        	this.timePicker.Size = new System.Drawing.Size(118, 20);
        	this.timePicker.TabIndex = 6;
        	this.timePicker.ValueChanged += new System.EventHandler(this.DateTimePicker1ValueChanged);
        	// 
        	// dataGridActions
        	// 
        	this.dataGridActions.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
        	        	        	| System.Windows.Forms.AnchorStyles.Left) 
        	        	        	| System.Windows.Forms.AnchorStyles.Right)));
        	this.dataGridActions.DataMember = "";
        	this.dataGridActions.HeaderForeColor = System.Drawing.SystemColors.ControlText;
        	this.dataGridActions.Location = new System.Drawing.Point(190, 30);
        	this.dataGridActions.Name = "dataGridActions";
        	this.dataGridActions.ReadOnly = true;
        	this.dataGridActions.Size = new System.Drawing.Size(307, 175);
        	this.dataGridActions.TabIndex = 7;
        	this.dataGridActions.Click += new System.EventHandler(this.DataGridActionsClick);
        	// 
        	// lblCurrTime
        	// 
        	this.lblCurrTime.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
        	this.lblCurrTime.Font = new System.Drawing.Font("Alba", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        	this.lblCurrTime.Location = new System.Drawing.Point(6, 30);
        	this.lblCurrTime.Name = "lblCurrTime";
        	this.lblCurrTime.Size = new System.Drawing.Size(172, 44);
        	this.lblCurrTime.TabIndex = 8;
        	this.lblCurrTime.Text = "label2";
        	this.lblCurrTime.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
        	// 
        	// timerCurrentTime
        	// 
        	this.timerCurrentTime.Enabled = true;
        	this.timerCurrentTime.Tick += new System.EventHandler(this.Timer1Tick);
        	// 
        	// timerActionDue
        	// 
        	this.timerActionDue.Interval = 15000;
        	this.timerActionDue.Tick += new System.EventHandler(this.TimerActionDueTick);
        	// 
        	// lblNextStep
        	// 
        	this.lblNextStep.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) 
        	        	        	| System.Windows.Forms.AnchorStyles.Right)));
        	this.lblNextStep.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        	this.lblNextStep.ForeColor = System.Drawing.Color.Red;
        	this.lblNextStep.Location = new System.Drawing.Point(190, 208);
        	this.lblNextStep.Name = "lblNextStep";
        	this.lblNextStep.Size = new System.Drawing.Size(306, 49);
        	this.lblNextStep.TabIndex = 9;
        	this.lblNextStep.Text = "Next Step";
        	this.lblNextStep.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
        	// 
        	// MainForm
        	// 
        	this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        	this.ClientSize = new System.Drawing.Size(499, 290);
        	this.Controls.Add(this.lblNextStep);
        	this.Controls.Add(this.lblCurrTime);
        	this.Controls.Add(this.dataGridActions);
        	this.Controls.Add(this.timePicker);
        	this.Controls.Add(this.label1);
        	this.Controls.Add(this.statusStrip1);
        	this.Controls.Add(this.pnlPictures);
        	this.Controls.Add(this.cmbRecipeSelection);
        	this.Menu = this.mainMenu1;
        	this.MinimumSize = new System.Drawing.Size(507, 298);
        	this.Name = "MainForm";
        	this.Text = "Cooks Mate";
        	this.Load += new System.EventHandler(this.MainFormLoad);
        	this.pnlPictures.ResumeLayout(false);
        	((System.ComponentModel.ISupportInitialize)(this.pictureStatus)).EndInit();
        	((System.ComponentModel.ISupportInitialize)(this.pictureAction)).EndInit();
        	((System.ComponentModel.ISupportInitialize)(this.dataGridActions)).EndInit();
        	this.ResumeLayout(false);
        	this.PerformLayout();
        }
        private System.Windows.Forms.Timer timerCurrentTime;
        private System.Windows.Forms.PictureBox pictureStatus;
        private System.Windows.Forms.Panel pnlPictures;
        private System.Windows.Forms.Timer timerActionDue;
        private System.Windows.Forms.Label lblNextStep;
        private System.Windows.Forms.Label lblCurrTime;
        private System.Windows.Forms.DataGrid dataGridActions;
        private System.Windows.Forms.PictureBox pictureAction;
        private System.Windows.Forms.DateTimePicker timePicker;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.StatusStrip statusStrip1;
        private System.Windows.Forms.ComboBox cmbRecipeSelection;
        #endregion
        
        #region File Menu Callbacks
        
        void MnuFileNewClick(object sender, System.EventArgs e)
        {
            log.Info("Create new recipe file");
        }
        void MnuFileOpenClick(object sender, System.EventArgs e)
        {
            log.Info("Open recipe file");
        }
        void MnuFileSaveClick(object sender, System.EventArgs e)
        {
            log.Info("Save recipe file");
        }
        void MnuFileSaveAsClick(object sender, System.EventArgs e)
        {
            log.Info("Save recipe file as");
        }
        void MnuFileExitClick(object sender, System.EventArgs e)
        {
            log.Info("Shutting Down");
            Close();
        }
        #endregion
        
        #region Help Menu Callbacks
        void MnuHelpAboutClick(object sender, System.EventArgs e)
        {
			log.Info("Showing about box");
			common.gui.AboutBox about = new common.gui.AboutBox();
			about.ApplicationName = "CooksMate";
			about.ApplicationVersion = AppVersion.VersionString;
			about.ShowDialog();
        }
        #endregion
    

        
        /// <summary>
        ///  Create own Table/Column Styles
        /// </summary>
        private void SetupDataGridColumns()
        {
            log.Info("set up data grid columns");
            
            // Create the first DataGridTableStyle which is used
            // for the "Customers" Table
            DataGridTableStyle ts1 = new DataGridTableStyle();
            ts1.MappingName = "actionsTbl";
            
            // Set other properties.
            ts1.AlternatingBackColor = Color.LightBlue;
            
            DataGridBoolColumn stepDoneCol = new DataGridBoolColumn();
            stepDoneCol.ReadOnly = false;
            stepDoneCol.MappingName = "done";
            stepDoneCol.HeaderText = "Done?";
            stepDoneCol.Width = 35;


            DataGridTextBoxColumn stepNameCol = new DataGridTextBoxColumn();
            stepNameCol.MappingName = "name";
            stepNameCol.HeaderText = "Action";
            stepNameCol.Width = 150;
            stepNameCol.ReadOnly = true;

            
            DataGridColumnStyle minsCol = new DataGridTextBoxColumn();
            minsCol.MappingName = "mins";
            minsCol.HeaderText = "Duration";
            minsCol.Width = 40;
            minsCol.ReadOnly = true;

            
            DataGridColumnStyle weightCol = new DataGridTextBoxColumn();
            weightCol.MappingName = "weight";
            weightCol.HeaderText = "Kg";
            weightCol.Width = 30;
            weightCol.ReadOnly = false;

            
            DataGridColumnStyle startTimeCol = new DataGridTextBoxColumn();
            startTimeCol.MappingName = "start";
            startTimeCol.HeaderText = "Time";
            startTimeCol.Width = 50;
            startTimeCol.ReadOnly = true;

            
            DataGridColumnStyle methodCol = new DataGridTextBoxColumn();
            methodCol.MappingName = "method";
            methodCol.HeaderText = "Method";
            methodCol.Width = 60;
            methodCol.ReadOnly = true;
            

            ts1.GridColumnStyles.Add(stepDoneCol);
            ts1.GridColumnStyles.Add(stepNameCol);
            ts1.GridColumnStyles.Add(weightCol);
            ts1.GridColumnStyles.Add(minsCol);
            ts1.GridColumnStyles.Add(startTimeCol);
            ts1.GridColumnStyles.Add(methodCol);
            
            
            // Add the DataGridTableStyle instances to
            // the GridTableStylesCollection
            dataGridActions.TableStyles.Clear();
            dataGridActions.TableStyles.Add(ts1);
            
            tablesAlreadySetup = true;
        }
        
        
        public void MainFormLoad(object sender, EventArgs e)
        {
            this.prefs.readFromFile();

        	string lastopenedfile = prefs.getPreference(PREF_LAST_OPENED_FILE);
        	
    		if (File.Exists(lastopenedfile))
    		{
    			dataEngine.Filename = lastopenedfile;
    			log.Info(String.Format("reloading file [{0}]", lastopenedfile));
    			dataEngine.ReadFromXml();
    		}
    		else
    		{
	            dataEngine.DummyData();
	            dataEngine.writeToFile();
	            prefs.setPreference(PREF_LAST_OPENED_FILE, dataEngine.Filename);
	            prefs.writeToFile();
        	}

            //statPlatform.Text = CommonFunctions.OsVersion;

            //log.Info("Environment Os ["+SystemInfo.OsVersion+"]");
            //log.Info("Environment Host ["+SystemInfo.OsHostname+"]");

            //log.Info("Application Version Number ["+AppVersion.VersionString+"]");

            UpdateRecipeList();
            //lblCurrTime.Font.FontFamily = pfc.Families[0];
            EnableNextActionTimer();
        }
        
        
        private void CmbRecipeSelectionSelectedIndexChanged(object sender, EventArgs e)
        {
            //log.Info("Selected Recipe text  ["+cmbRecipeSelection.SelectedText+"]");
            //log.Info("Selected Recipe index ["+cmbRecipeSelection.SelectedIndex+"]");
            //log.Info("Selected Recipe item ["+cmbRecipeSelection.SelectedItem+"]");
            if ( cmbRecipeSelection.SelectedItem.ToString().Equals(CREATE_NEW_RECIPE_STRING) )
            {
            	Recipe tmpRecipe = dataEngine.CreateNewRecipe(NEW_RECIPE_NAME);
            	DlgEditRecipe dlg = new DlgEditRecipe();
            	dlg.recipe = tmpRecipe;
            	UpdateRecipeList();
            }
            else
            {
	            PreferencesXml.Preferences.setPreference("SelectedRecipeName", cmbRecipeSelection.SelectedItem.ToString());
	            timePicker.Value = dataEngine.GetServeTime(cmbRecipeSelection.SelectedItem.ToString());
	            UpdateActionList();
	            EnableNextActionTimer();
	            CheckForNextAction();
            }
        }
        
        
        private void UpdateRecipeList()
        {
            cmbRecipeSelection.Items.Clear();
            ArrayList recipes= dataEngine.GetRecipes();
            cmbRecipeSelection.Items.Add(CREATE_NEW_RECIPE_STRING);
            foreach (Recipe recp in recipes)
            {
                cmbRecipeSelection.Items.Add(recp.Title);
            }
        }
        private void UpdateActionList()
        {
            log.Info("Selected Recipe ["+cmbRecipeSelection.SelectedItem+"]");
            ArrayList actions = dataEngine.GetActionSteps(cmbRecipeSelection.SelectedItem.ToString());
            
            if (!tablesAlreadySetup)
            {
        		datColActionDone = new DataColumn("done");
    			datColActionDone.DataType = System.Type.GetType("System.Boolean"); 
    			datColActionDone.DefaultValue = false; 
    			
                dataTblActions.Columns.Add(datColActionDone);
                dataTblActions.Columns.Add(datColActionName);
                dataTblActions.Columns.Add(datColActionWeight);
                dataTblActions.Columns.Add(datColActionStart);
                dataTblActions.Columns.Add(datColActionMethod);
                dataTblActions.Columns.Add(datColActionMins);
                SetupDataGridColumns();
            }
            
            dataTblActions.Rows.Clear();
            DateTime serveTime = timePicker.Value;

            DataRow newRow;
            foreach (ActionStep step in actions)
            {
                newRow = dataTblActions.NewRow();
                newRow["done"]    = step.Done;
                newRow["name"]    = step.Name;
                newRow["weight"]  = step.WeightKg;
                newRow["mins"]    = step.MinsDuration;
                newRow["method"]  = step.Type;
                newRow["start"]   = step.StartTime(serveTime).ToString("HH:mm");
                dataTblActions.Rows.Add(newRow);
            }
            
			dataSetActions.Tables.Clear();
			dataSetActions.Tables.Add(dataTblActions);
			//DumpDataSet(dataSetActions);
			dataGridActions.SetDataBinding(dataSetActions, dataTblActions.TableName);
        }
        private void DumpDataSet(DataSet ds)
        {
            log.Info("Dumping DataSet ["+ds.DataSetName+"]");
            log.Info("DatSet namespace ["+ds.Namespace+"]");
            log.Info("DatSet prefix ["+ds.Prefix+"]");
            log.Info("DatSet ["+ds.ToString()+"]");
            log.Info("dataset has ["+ds.Tables.Count+"] tables");
            foreach (DataTable dt in ds.Tables)
            {
                log.Info("dumping table ["+dt.TableName+"]");
                log.Info("table has ["+dt.Rows.Count+"] rows");
                foreach (DataRow dr in dt.Rows)
                {
                    string itemInfo = "DataRow :[";
                    foreach (Object obj in dr.ItemArray)
                    {
                        itemInfo += (" ["+obj.ToString()+"]");
                    }
                    log.Info(itemInfo+" ]");
                }
            }
        }
        
        
        private void DateTimePicker1ValueChanged(object sender, EventArgs e)
        {
            log.Info("Serve At ["+timePicker.Value+"]");
            dataEngine.SetServeTime(cmbRecipeSelection.SelectedItem.ToString(), timePicker.Value);
            UpdateActionList();
        }        
        
        
        private void EnableNextActionTimer()
        {
        	if ((cmbRecipeSelection.SelectedItem==null) || (cmbRecipeSelection.SelectedItem.ToString().Equals("")))
        	{
        		timerActionDue.Enabled = false;
        	}
        	else
        	{
        		timerActionDue.Enabled = true;
        	}
        }
        
        /// <summary>
        /// update current time
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer1Tick(object sender, EventArgs e)
        {
            DateTime now = DateTime.Now;
            lblCurrTime.Text = now.ToString("HH:mm:ss");
        }
        
        /// <summary>
        /// Check which action is next and how long until it is due
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TimerActionDueTick(object sender, EventArgs e)
        {
        	CheckForNextAction();
        }
        
        private void CheckForNextAction()
        {
        	if (cmbRecipeSelection==null || cmbRecipeSelection.SelectedItem==null) {return;}
        	if (cmbRecipeSelection.SelectedItem.ToString().Equals("")) {return;}
        	
        	//is it time to do something?
        	ActionStep nxtStep = null;
        	nxtStep = dataEngine.GetNextAction(cmbRecipeSelection.SelectedItem.ToString(), DateTime.Now);

        	if (nxtStep != null)
        	{
        		int minsleft=MinsUntil(nxtStep);
        		String nxtStepString = "'" + nxtStep.Name + "' in " + minsleft + " mins";
        		lblNextStep.Text = nxtStepString;
        		UpdateImage(nxtStep);
        	}
        }

    	private int MinsUntil(ActionStep nxtStep)
    	{
    		DateTime strtTime = nxtStep.StartTime(dataEngine.GetRecipe(cmbRecipeSelection.SelectedItem.ToString()).ServeTime);
    		TimeSpan tmSpn = strtTime - DateTime.Now;
    		return Convert.ToInt16(tmSpn.TotalMinutes);
    	}

    	private void UpdateImage(ActionStep nxtStep)
    	{
    		int minsleft = MinsUntil(nxtStep);
			log.Info(minsleft + " mins left");

			try
			{
    		if (minsleft > 15)
    		{
    			// more than 15 mins until next action
    			UpdateActionImage("armchair");
    			UpdateStatusImage("eggtimer");
        		lblNextStep.ForeColor = Color.Black;
    			return;
    		}
    		else if (minsleft > 10)
    		{
    			// 10 to 15 mins until next action
    			UpdateActionImage(nxtStep.Type.ToString().ToLower());
    			UpdateStatusImage("traffic_light_green");
	        	lblNextStep.ForeColor = Color.Green;
    			return;
    		}
    		else if (minsleft > 5)
    		{
    			// 5 to 10 mins until next action
    			UpdateActionImage(nxtStep.Type.ToString().ToLower());
    			UpdateStatusImage("traffic_light_green");
	        	lblNextStep.ForeColor = Color.Green;
    			return;
    		}
    		else if (minsleft > 2)
    		{
    			// 2 to 5 mins until next action
    			UpdateActionImage(nxtStep.Type.ToString().ToLower());
    			UpdateStatusImage("traffic_light_amber");
	        	lblNextStep.ForeColor = Color.Orange;
    			return;
    		}
    			// < 2 mins until next action
    			UpdateActionImage(nxtStep.Type.ToString().ToLower());
    			UpdateStatusImage("traffic_light_red");
        		lblNextStep.ForeColor = Color.Red;
    			return;
			}
			catch (Exception e)
			{
				log.Error("Exception: " + e.Message + " caught");
			}
    	}
    	
    	private void UpdateActionImage(string imgName)
    	{
			//log.Info("Setting Status Image to [" + imgName + "]");
			ResourceManager rm = new ResourceManager ("uk.org.aspellclark.cooksmate.Properties.StatusImages", Assembly.GetExecutingAssembly());
			Bitmap bmp = (Bitmap)rm.GetObject(imgName);
			pictureAction.Image = ImageFunctions.ConvertImage(bmp,pictureAction.Width,pictureAction.Height);
    	}
    	
    	private void UpdateStatusImage(string imgName)
    	{
			//log.Info("Setting Status Image to [" + imgName + "]");
			ResourceManager rm = new ResourceManager ("uk.org.aspellclark.cooksmate.Properties.StatusImages", Assembly.GetExecutingAssembly());
			Bitmap bmp = (Bitmap)rm.GetObject(imgName);
			pictureStatus.Image = ImageFunctions.ConvertImage(bmp,pictureStatus.Width,pictureStatus.Height);
    	}
    	
        void PnlPicturesResize(object sender, EventArgs e)
        {
        	//log.Info("new panel size [" + pnlPictures.Size.ToString() + "]");
        	//log.Info("pictureAction size before [" + pictureAction.Size.ToString() + "]");
        	pictureAction.Size = new Size(pnlPictures.Width, pnlPictures.Height/2);

        	pictureStatus.Size = pictureAction.Size;

        	pictureAction.Location = new Point(0,0);
        	pictureStatus.Location = new Point(0,pictureAction.Size.Height+1);
        	//log.Info("pictureAction size after [" + pictureAction.Size.ToString() + "]");

        	CheckForNextAction();
        }



        private void DataGridActionsClick(object sender, EventArgs e)
        {
        	int checkColNbr = 0;
			Point pt = this.dataGridActions.PointToClient(Control.MousePosition);
			DataGrid.HitTestInfo hti = this.dataGridActions.HitTest(pt);
			BindingManagerBase bmb = this.BindingContext[this.dataGridActions.DataSource, this.dataGridActions.DataMember];

			//log.Info("pt        : " + pt.ToString());
			//log.Info("hti.row   : " + hti.Row.ToString());
			//log.Info("hti.column: " + hti.Column.ToString());
			//log.Info("hti.type  : " + hti.Type.ToString());
			//log.Info("bmb.count : " + bmb.Count);

			if(    hti.Row < bmb.Count
				&& hti.Type == DataGrid.HitTestType.Cell 
				&& hti.Column == checkColNbr )
			{	
				DataRowView drv = bmb.Current as DataRowView;
				Object[] obj = drv.Row.ItemArray;
				//int x = 0;
				//foreach (Object str in obj)
				{
					//log.Info(String.Format("obj[{2}] str : [{0}] [{1}]", typeof(string), str.ToString(), x++));
				}
				//log.Info("obj : " + obj.ToString());
				ActionStep stp =  dataEngine.GetAction(cmbRecipeSelection.SelectedItem.ToString(), obj[1].ToString());
				if (stp == null)
				{
			    	log.Info("step      : null");
			    	return;
				}
			    //log.Info("step      : " + stp.ToString());
			    dataEngine.ActionDone(cmbRecipeSelection.SelectedItem.ToString(), stp);
				this.dataGridActions[hti.Row, checkColNbr] = !(bool)this.dataGridActions[hti.Row, checkColNbr];
				RefreshRow(hti.Row);
			}
        }

		// Forces a repaint of given row.
		private void RefreshRow(int row)
		{
			UpdateActionList();
			//Rectangle rect = this.dataGridActions.GetCellBounds(row, 0);
			//rect = new Rectangle(rect.Right, rect.Top, this.dataGridActions.Width, rect.Height);
			//this.dataGridActions.Invalidate(rect);
		}

        
    }//class
}//namespace

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


Written By
Software Developer (Senior) Airbus Defense and Space
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions