private void HandleOpen() { try { OpenFileDialog openFileDialog = new OpenFileDialog(); if (openFileDialog.ShowDialog() == DialogResult.OK) { FileStream fs = (FileStream)openFileDialog.OpenFile(); using (StreamReader s = new StreamReader(fs)) spreadsheet = new Spreadsheet(s, new Regex("")); resetView(); foreach (string name in spreadsheet.GetNamesOfAllNonemptyCells().ToList()) { int col = name.ToCharArray()[0] - 65; int row = int.Parse(name.Substring(1)); spreadsheetView.SetCellValue(col, row - 1, spreadsheet.GetCellValue(name).ToString()); } } } catch (Exception e) { MessageBox.Show("Error reading file : " + e.Message); } }
/// <summary> /// what happens when I press enter/return and the edit box is filled /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CellContents_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Return || e.KeyChar == (char)Keys.Enter) { try { sheetModel.SetContentsOfCell(ColRow_To_string(col, row), CellContents.Text); CellVal.Text = PrintableValue(sheetModel.GetCellValue(ColRow_To_string(col, row))); } catch { CellVal.Text = "Eval Error"; return; } Panel.SetValue(col, row, CellContents.Text); //CellContents.Clear(); this.Panel.Select(); PanelFocus = true; } }
/// <summary> /// Deals with the second SpreadsheetController Constructor that passes a file path /// so that the file to load can be accessed and read here. /// </summary> /// <param name="filename"></param> private void DoLoad(string filename) { //Create a new Regex for the param of Spreadsheet(TextWriter dest, Regex isValid) Regex reg = new Regex("^.*$"); TextReader read = File.OpenText(filename); //Create a new Spreadsheet model using the two params model = new Spreadsheet(read, reg); //Create a new dicitonary to pass to UpdateAll Dictionary <string, string> newVals = new Dictionary <string, string>(); //For each cell in the new Spreadsheet model, we update the view to reflect the addition var newCells = model.GetNamesOfAllNonemptyCells(); foreach (string name in newCells) { newVals.Add(name, model.GetCellValue(name).ToString()); } //Send all nonempty cells to be updated in view spreadsheetView.toUpdate = newVals; }
/// <summary> /// Handles a request to open file /// </summary> /// <param name="filename"></param> public void HandleOpenFile(string filename) { StreamReader inputFile = null; try { inputFile = File.OpenText(filename.Replace("\\", "/")); model = new Spreadsheet(inputFile, new Regex("^[A-Z][1-9]|[A-Z][1-9]$")); HashSet <string> cells = new HashSet <string>(model.GetNamesOfAllNonemptyCells()); window.ClearSpreadsheetPanel(); foreach (string name in cells) { object content = model.GetCellValue(name); int col, row; ConvertCellName(out col, out row, name); window.SetCellValue(col, row, content.ToString()); } SaveLocation = filename.Replace("\\", "/"); } catch (Exception) { MessageBox.Show("There was an error loading the file"); SaveLocation = null; } inputFile.Close(); window.SetCellSelection(0, 0); HandleGetCellContents("A1"); }
private void HandleUpdateSelection(string content) { var initialContent = spreadsheet.GetCellContents(window.CellName); try { foreach (string cell in spreadsheet.SetContentsOfCell(window.CellName, content)) { string[] rowAndCol = Regex.Split(cell, @"(\d+)"); window.SetCell((rowAndCol[0].ToCharArray()[0] - 'A'), int.Parse(rowAndCol[1]) - 1, spreadsheet.GetCellValue(cell).ToString()); } window.CellValue = spreadsheet.GetCellValue(window.CellName).ToString(); window.CellContent = (spreadsheet.GetCellContents(window.CellName) is Formula ? "=" : "") + spreadsheet.GetCellContents(window.CellName).ToString(); window.Changed = spreadsheet.Changed; } catch (Exception e) { window.Message = "Error: \n" + e.Message; HandleUpdateSelection(initialContent.ToString()); } }
/// <summary> /// Loads dataGraphChart from the data of Spreadsheet object /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DataGraph_Load(object sender, EventArgs e) { List <string> list = _spreadsheet.GetNamesOfAllNonemptyCells().ToList(); try { // create series' names from the values of B1, C1, D1 dataGraphChart.Series.Add(_spreadsheet.GetCellValue("B1").ToString()); if (list.Contains("C1")) { dataGraphChart.Series.Add(_spreadsheet.GetCellValue("C1").ToString()); } if (list.Contains("D1")) { dataGraphChart.Series.Add(_spreadsheet.GetCellValue("D1").ToString()); } // loop through Spreadsheet, and update the corresponding data to the series foreach (string name in list) { if (name != "B1" && name != "C1" && name != "D1") { string xVal = _spreadsheet.GetCellValue("A" + name[1]).ToString(); string yVal = _spreadsheet.GetCellValue(name).ToString(); switch (name[0]) { case 'B': dataGraphChart.Series[0].Points.AddXY(xVal, yVal); break; case 'C': dataGraphChart.Series[1].Points.AddXY(xVal, yVal); break; case 'D': dataGraphChart.Series[2].Points.AddXY(xVal, yVal); break; } } } } catch (Exception e1) { MessageBox.Show(e1.Message, "Error"); this.Close(); } }
/// <summary> /// Re-evaluate each individual cell. /// </summary> /// <param name="spreadsheet"></param> /// <param name="cellName"></param> private void UpdateCell(Spreadsheet spreadsheet, string cellName) { GetColandRow(cellName, out int col, out int row); string cellValue = spreadsheet.GetCellValue(cellName).ToString(); // Display cell value in spreadsheetPanel panelDic[tabControl1.SelectedTab].SetValue(col, row, cellValue); }
/// <summary> /// Handles a request to change the selected cell. /// The view should handle highliting the new cell, itself. /// </summary> private void HandleSelectedCellChanged(string name) { window.DisplayContents(spreadsheet.GetCellContents(name).ToString()); object val = spreadsheet.GetCellValue(name); string toDisplay; if (val.GetType().Equals(typeof(FormulaError))) { toDisplay = "FormErr"; } else { toDisplay = val.ToString(); } window.DisplayValue(name, toDisplay); }
/// <summary> /// When a cell is selected, /// updates the textboxes for contents, name, and value. /// </summary> /// <param name="name"></param> private void HandleChange(String name) { Object content = ssModule.GetCellContents(name); String convertContents; if (content.GetType() == typeof(Formula)) { convertContents = "=" + content.ToString(); } else { convertContents = content.ToString(); } window.UpdateContentBox(convertContents); window.UpdateValueBox(ssModule.GetCellValue(name).ToString()); window.UpdateNameBox(name); }
/// <summary> /// display content and values of selection /// </summary> /// <param name="sender"></param> private void displaySelection(SpreadsheetPanel sender) { string name = GetCellName(); if (model.GetCellContents(name).GetType().ToString() == "System.String" && model.GetCellValue(name).GetType().ToString() == "System.Double") { window.setContentBox("=" + model.GetCellContents(name).ToString()); } else { window.setContentBox(model.GetCellContents(name).ToString()); } window.setValueBox(model.GetCellValue(name).ToString()); window.setCellBox(GetCellName()); updateCell(name); }
/// <summary> /// Returns the cell value from a given spreadsheet. /// </summary> public string GetCellValue(Spreadsheet spreadsheet) { var cellValue = spreadsheet.GetCellValue(CellName); if (cellValue is FormulaError) { FormulaError error = (FormulaError)cellValue; return(error.Reason); } return(cellValue.ToString()); }
/// <summary> /// Handles the cell with name changed contents. /// </summary> /// <param name="name">The name.</param> /// <param name="newContents">The new contents.</param> private void HandleCellWithNameChangedContents(string name, string newContents) { var previousContents = model.GetCellContents(name); var updateDict = new Dictionary <string, string>(); try { var cellsChanged = model.SetContentsOfCell(name, newContents); foreach (string s in cellsChanged) { updateDict.Add(s, model.GetCellValue(s).ToString()); } spreadsheetView.toUpdate = updateDict; } catch (Exception e) { spreadsheetView.message = e.Message; model.SetContentsOfCell(name, previousContents.ToString()); } }
/// <summary> /// Helper method that updates all text boxes when something changes /// </summary> /// <param name="s"></param> private void updateTextBox(SpreadsheetPanel s) { String name; cellValueTextBox.Focus(); //Assigns the cell name textbox to name for the selected cell name = getCellName(); cellContentsBox.Text = name; //Checks the cell if its a formula so it knows to add a '=' or not in front of the value if (ss.GetCellContents(name).GetType() == typeof(Formula)) { cellValueTextBox.Text = "=" + ss.GetCellContents(name).ToString(); } else { cellValueTextBox.Text = ss.GetCellContents(name).ToString(); } cellValueWindow.Text = ss.GetCellValue(name).ToString(); }
/// <summary> /// Helper method that updates the spreadsheet, including the text boxes that display /// the cell name, value, and content, and also the cell value displayed in the cell itself /// </summary> private void UpdateSpreadsheet() { // get the name, content, and value of the current cell String cellName = GetCellName(); Object cellContents = spreadsheet.GetCellContents(cellName); Object cellValue = spreadsheet.GetCellValue(cellName); // set the contents of the textbox equal to that cell name cellNameBox.Text = cellName; // if the cell content is a Formula, add the '=' back on if (spreadsheet.GetCellContents(cellName) is Formula) { cellContentsBox.Text = "=" + cellContents.ToString(); } else // otherwise just set the textbox equal to the content { cellContentsBox.Text = cellContents.ToString(); } // check if the cell value is a formula error, say so if (spreadsheet.GetCellValue(cellName) is FormulaError) { // if the value is a formula error, put the message in the text box FormulaError error = (FormulaError)spreadsheet.GetCellValue(cellName); cellValueBox.Text = error.Reason; } else // otherwise just set the textbox equal to the value { cellValueBox.Text = cellValue.ToString(); } }
/// <summary> /// helper method that updates the cell value box and the cell name and the cell selected. /// </summary> private void SpreadsheetUpdater() { String CellNameText = GetCellName(); Object cellContents = spreadsheet.GetCellContents(CellNameText); Object cellValue = spreadsheet.GetCellValue(CellNameText); cellNameBox.Text = CellNameText; if (spreadsheet.GetCellContents(CellNameText) is Formula) { cellContentsBox.Text = "=" + cellContents.ToString(); } else // otherwise just set the textbox equal to the content { cellContentsBox.Text = cellContents.ToString(); } if (spreadsheet.GetCellValue(CellNameText) is FormulaError) { FormulaError error = (FormulaError)spreadsheet.GetCellValue(CellNameText); cellValueBox.Text = error.Reason; } cellValueBox.Text = cellValue.ToString(); }
/// <summary> /// Update the text inside the cell in the spreadsheet to /// reflect the evaluated value. /// </summary> /// <param name="cellName">The name of the cell being refreshed.</param> private void UpdateCell(string cellName) { int colIndex; int rowIndex; string cellValue; // Helper methods to decode the index of the cell's row and column colIndex = GetColumnIndex(cellName); rowIndex = GetRowIndex(cellName); // Refresh the value of the cell (a FormulaError or a value) if ((spreadsheet.GetCellValue(cellName) is FormulaError)) { FormulaError error = (FormulaError)spreadsheet.GetCellValue(cellName); cellValue = error.Reason; } else { cellValue = spreadsheet.GetCellValue(cellName).ToString(); } window.SetCellValue(rowIndex, colIndex, cellValue); }
/// <summary> /// When cell is selected, get contents and val to put in text boxes /// </summary> public void cellSelect(SpreadsheetPanel ss) { //Gets cell name ss.GetSelection(out int x, out int y); string cellName = coordsToCell(x, y); //Gets contents and value object contents = sheet.GetCellContents(cellName); object value = sheet.GetCellValue(cellName); //Gets contents if formula if (contents is Formula) { contents = "=" + contents.ToString(); } //Gets value if formula error if (value is FormulaError) { value = "FormulaError"; } //Returns contents and value form.endCellSelect(contents.ToString(), value.ToString(), cellName); }
/// <summary> /// Every time the selection changes, this method is called with the /// Spreadsheet as its parameter. We display the current time in the cell. /// </summary> /// <param name="sender"></param> private void displaySelection(SpreadsheetPanel sender) { int row, col; String value; sender.GetSelection(out col, out row); sender.GetValue(col, row, out value); // set the cellname on my spreadsheet and result value of cell content CellName.Text = convertToCellName(col, row); CellValue.Text = myspreadsheet.GetCellValue(CellName.Text).ToString(); // if the cell content is formula, then compute it. Object tempcontent = myspreadsheet.GetCellContents(CellName.Text); if (tempcontent is Formula) { CellContent.Text = "=" + tempcontent; } else { CellContent.Text = tempcontent.ToString(); } }
/// <summary> /// Method that handles the Event of the Evaluate buttom being clicked, which means that /// we add elements of the cell to the spread sheet and calculate the value while we are at it /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Evaluate_Click(object sender, EventArgs e) { int row, col; spreadsheetPanel1.GetSelection(out col, out row); try { try { // Setting the value in spreadsheet based on the GUI cell spreadsheet.SetContentsOfCell(columnRowToCellNameConverter(col, row), BoxCellContent.Text); } // Catching numerous exceptions that otherwise would terminate the GUI program // A Message Dialogue is shown to prevent abropt cancellation of the program catch (EvaluateException evaluateError) { MessageBox.Show(evaluateError.Message, "Note: Error occured evaulating your cell", MessageBoxButtons.OK); } catch (FormulaEvaluationException evaluateError) { MessageBox.Show(evaluateError.Message, "Note: Error occured evaulating your cell", MessageBoxButtons.OK); } // This error should never occur catch (CircularException circularError) { MessageBox.Show(circularError.Message, "An Error occured because your data entry causes a Circular Dependency", MessageBoxButtons.OK); } BoxCellValue.Text = spreadsheet.GetCellValue(columnRowToCellNameConverter(col, row)).ToString(); // Going the all of the empty cells that aren't empty in the spreadsheet and setting the different cells in the GUI foreach (String cellName in spreadsheet.GetNamesOfAllNonemptyCells()) { cellNameToColumnRowConverter(cellName, out col, out row); spreadsheetPanel1.SetValue(col, row, spreadsheet.GetCellValue(cellName).ToString()); } } catch (Exception) { MessageBox.Show("Note: Error occured entering the value into a cell. Please check if your cell name is Valid.", "Error", MessageBoxButtons.OK); } }
/// <summary> /// Handles a request to update Cell /// </summary> /// <param name="col"></param> /// <param name="row"></param> /// <param name="content"></param> private void HandleUpdateCell(int col, int row, string content) { string name; ConvertCellName(col, row, out name); if (model.GetCellContents(name).Equals("") && content.Equals("")) { return; } try { HashSet <string> CellsToUpdate = new HashSet <string>(model.SetContentsOfCell(name, content)); foreach (string s in CellsToUpdate) { ConvertCellName(out col, out row, s); window.SetCellValue(col, row, model.GetCellValue(s).ToString()); } } catch (Exception) { MessageBox.Show("There was an error updating the cell to \"" + content + "\""); window.SetCellValue(col, row, model.GetCellValue(name).ToString()); } }
/// <summary> /// Called whenever the contents of a cell are modified. Uses a Spreadsheet to update cell information. /// </summary> /// <param name="col"></param> /// <param name="row"></param> private void UpdateSingleCell(string name, string contents) { HashSet <string> cellDependents; cellDependents = new HashSet <string>(spreadsheet.SetContentsOfCell(name, contents)); if (cellDependents.Count > 1) { UpdateCells(cellDependents); } else { object value = spreadsheet.GetCellValue(name); if (value is FormulaError) { value = "ERROR"; } int col, row; col = name.ElementAt(0) - 'A'; int.TryParse(name.Substring(1), out row); row -= 1; spreadsheetPanel.SetValue(col, row, value.ToString()); } }
/// <summary> /// Update the spreadsheet. /// </summary> private void UpdateSpreadsheet() { // Auto focus on the text box for immediate typing contentTextBox.Focus(); Spreadsheet spreadsheet = sheetDic[tabControl1.SelectedTab]; panelDic[tabControl1.SelectedTab].GetSelection(out int col, out int row); String cellName = GetCellName(col, row); Object cellContents = spreadsheet.GetCellContents(cellName); Object cellValue = spreadsheet.GetCellValue(cellName); // Display selected cell name cellNameTextBox.Text = cellName; // When cell contains formula, display the formula with prefix "=" if (spreadsheet.GetCellContents(cellName) is Formula) { contentTextBox.Text = "=" + cellContents.ToString(); } else { contentTextBox.Text = cellContents.ToString(); } // When cell value is FormulaError, display error message if (spreadsheet.GetCellValue(cellName) is FormulaError) { valueTextBox.Text = ((FormulaError)cellValue).Reason; } else { valueTextBox.Text = cellValue.ToString(); } }
/// <summary> /// Handles request to add content to selected cell /// </summary> /// <param name="content"></param> private void HandleSetContent(int column, int row, string content) { Spreadsheet oldSpreadsheet = new Spreadsheet(); foreach (string name in spreadsheet.GetNamesOfAllNonemptyCells()) { oldSpreadsheet.SetContentsOfCell(name, spreadsheet.GetCellContents(name).ToString()); } try { if (content != "") { foreach (string name in spreadsheet.SetContentsOfCell(getCellName(column, row), content)) { int col = name.ToCharArray()[0] - 65; int ro = int.Parse(name.Substring(1)); object contentToCheck = spreadsheet.GetCellValue(name); if (contentToCheck is FormulaError) { spreadsheetView.DisplayMessage(String.Format("Formula error {0}", contentToCheck.ToString())); spreadsheet = oldSpreadsheet; break; } spreadsheetView.SetCellValue(col, ro - 1, spreadsheet.GetCellValue(name).ToString()); } } } catch (FormulaFormatException e) { spreadsheetView.DisplayMessage("Formula format invalid"); } catch (CircularException e) { spreadsheetView.DisplayMessage("Circular exception"); } }
/// <summary> /// Creates a new controller that is based off of the passed in window and contains all of /// the data stored in the passed in file. Error checking will have been done by a previous /// controller, so the passed in file will always be readable. /// </summary> /// <param name="_window">The GUI that the controller can interact with</param> /// <param name="filename">The name of the file containing the data to be read</param> public Controller(ISpreadsheetView _window, string filename) : this(_window) { int col, row; Regex r = new Regex(@"^[a-zA-Z][1-9][0-9]?$"); using (StreamReader sw = new StreamReader(filename)) { spreadsheet = new Spreadsheet(sw, r); } foreach (string cell in spreadsheet.GetNamesOfAllNonemptyCells()) { toCoordinates(cell, out col, out row); window.SetValue(col, row, spreadsheet.GetCellValue(cell).ToString()); } window.SetTitle(filename); HandleNewCellSelected(); }
/// <summary> /// A private Event Handler that is called whenever the ChangeContents event is fired. /// </summary> private void HandleChangeContents() { // Obtain the name of the currently selected cell and its desired contents. window.GetSelection(out int col, out int row); string cellName = toCellName(col, row); string contents = window.GetDesiredContents(); ISet <string> dependents = new HashSet <string>(); // Try and change the contents of the spreadsheet to the new contents. try { dependents = spreadsheet.SetContentsOfCell(cellName, contents); } catch (Exception e) { // Show the appropriate error message if the passed in contents aren't allowed. if (e is FormulaFormatException) { window.InvalidFormula(); } else if (e is CircularException) { window.CircularFormula(); } return; } // Update all of the cells so they show the correct value foreach (string s in dependents) { object value = spreadsheet.GetCellValue(s); toCoordinates(s, out int currentCol, out int currentRow); if (value is FormulaError) { value = "#ERROR"; } window.SetValue(currentCol, currentRow, value.ToString()); } // Update the text box to show the correct contents. HandleNewCellSelected(); }
/// <summary> /// Begins controlling window. /// </summary> public Controller(IAnalysisView window, Spreadsheet ss) { this.window = window; this.sheet = ss; var setvalues = new Dictionary <string, string>(); foreach (string s in ss.GetNamesOfAllNonemptyCells()) { setvalues.Add(s, ss.GetCellValue(s).ToString()); } window.UpdateView(setvalues); //window.FileChosenEvent += HandleFileChosen; window.SetContents += UpdateContents; window.GetContents += PassBackContents; window.FileCloseEvent += HandleClose; window.NewEvent += HandleNew; window.FileSaveEvent += HandleSave; window.FileOpenEvent += HandleOpen; }
/// <summary> /// Updates a specified cell and it's dependencies. /// /// If it's empty, it just returns out of this method. /// /// This also catches any exceptions that occur /// </summary> /// <param name="col">Column of the cell that's being updated</param> /// <param name="row">Row of the cell that's being updated</param> private void UpdateCells(int col, int row) { string cellName = SelectedCellName(col, row); try { IList <string> dependencies = mainSpreadsheet.SetContentsOfCell(cellName, CellContentsBox.Text); foreach (string cell in dependencies) { int rowToChange = Int32.Parse(cell.Substring(1)) - 1; int letterToNumberCol = char.ToUpper(cell[0]) - 65; //Sets the visuals to the string "Formula Error" if the value is a FormulaError if (mainSpreadsheet.GetCellValue(cell) is FormulaError) { SpreadsheetGrid.SetValue(letterToNumberCol, rowToChange, "Formula Error"); } else { SpreadsheetGrid.SetValue(letterToNumberCol, rowToChange, mainSpreadsheet.GetCellValue(cell).ToString()); } } SpreadsheetGrid.SetSelection(col, row); // Visual change in cell string cellValue = mainSpreadsheet.GetCellValue(cellName).ToString(); VisualUpdate(cellName); //Adds an asterisk to the title if the file has changed if (mainSpreadsheet.Changed) { Text = Path.GetFileName(FileName) + "*"; } } //Catches any exceptions while updating the value and creates a dialog to show it. catch { MessageBox.Show("An error occured while trying to change the contents of a cell", "Contents of Cell Error", MessageBoxButtons.OK); VisualUpdate(cellName); } }
/// <summary> /// Open a file and fill the speadsheet window with the file information /// </summary> /// <param name="window"></param> /// <param name="sheet"></param> /// <param name="title"></param> public Controller(ISpreadsheetView window, Spreadsheet sheet, string title) { Inititalize(window, sheet, title); int[] temp; // Fill all nonempty cell with value in the source file foreach (string cell in sheet.GetNamesOfAllNonemptyCells()) { GetCellNumber(cell, out int col, out int row); temp = new int[2] { col, row }; view.SelectedCellAddress = temp; view.SetCellValueOnPanel(temp, sheet.GetCellValue(cell).ToString()); } HandleSelectionChanged(new int[2] { 0, 0 }); }
/// <summary> /// Determines the type of the value stored in specified cell and sets the spreadsheetpanel's appropriate cell value. /// Value can either be a double, string, or a formula error. /// Used as a private helper method in method redoAllAffectedCells. /// </summary> /// <param name="col"></param> /// <param name="row"></param> /// <param name="cell"></param> private void setPanelValue(int col, int row, string cell) { lock (ss) { object ssValue = ss.GetCellValue(cell); //Make sure other threads dont set the spreadsheet value at the same time. lock (CellEditLock) { if (ssValue is double) { spreadsheetPanel1.SetValue(col, row, ((double)ssValue).ToString()); } else if (ssValue is string) { spreadsheetPanel1.SetValue(col, row, (string)ssValue); } else { spreadsheetPanel1.SetValue(col, row, "error"); } } } }
/// <summary> /// Updates cell values in the spreadsheet panel /// </summary> public static void updateCells(Spreadsheet sheet, SpreadsheetPanel ss, List <string> cells) { object contents; object value; foreach (string cellName in cells) { contents = sheet.GetCellContents(cellName); value = sheet.GetCellValue(cellName); //Gets contents if formula if (contents is Formula) { contents = "=" + contents.ToString(); } //Gets value if formula error if (value is FormulaError) { value = "FormulaError"; } //Updates cell values and returns contents and value cellToCoords(cellName, out int x, out int y); ss.SetValue(x, y, value.ToString()); } }