2018年4月30日月曜日

開発環境

Head First C# ―頭とからだで覚えるC#の基本 (Andrew Stellman (著)、Jennifer Greene (著)、佐藤 嘉一 (監修, 監修)、木下 哲也 (翻訳)、オライリージャパン)の8章(例外処理 - 消火は時代遅れ)、エクササイズ(p. 373)を取り組んでみる。

コード

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace WindowsFormsApp21
{
    public partial class Form1 : Form
    {
        private Excuse currentExcuse = new Excuse();
        private bool formChanged = false;
        private string selectedPath = "";
        private Random random = new Random();

        public Form1()
        {
            InitializeComponent();

            save.Enabled = false;
            open.Enabled = false;
            randomExcuse.Enabled = false;

            currentExcuse.Description = description.Text;
            currentExcuse.Results = results.Text;
            currentExcuse.DateTime = lastUsed.Value;
        }

        [Serializable]
        public class Excuse
        {
            private string description;
            private string results;
            private DateTime dateTime;
            private string excusePath;

            public Excuse()
            {
                excusePath = "";
            }
            public Excuse(string filename)
            {
                openFile(filename);
            }
            public Excuse(Random random, string path)
            {
                string[] files = Directory.GetFiles(path, "*.excuse");
                string file = files[random.Next(files.Length)];
                openFile(file);
            }

            public string Description
            {
                get { return description; }
                set { this.description = value; }
            }
            public string Results
            {
                get { return results; }
                set { this.results = value; }
            }
            public DateTime DateTime
            {
                get { return dateTime; }
                set { this.dateTime = value; }
            }
            public string ExcusePath
            {
                get { return excusePath; }
            }
            public void openFile(string excusePath)
            {
                this.excusePath = excusePath;
                using (Stream input = File.OpenRead(excusePath))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    Excuse excuse = (Excuse)formatter.Deserialize(input);
                    description = excuse.description;
                    results = excuse.results;
                    dateTime = Convert.ToDateTime(excuse.dateTime);
                }
            }

            public void save(string filename)
            {
                using (Stream output = File.Create(filename))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(output, this);
                }
                this.excusePath = filename;
            }
        }
        private void UpdateForm(bool changed)
        {
            if (!changed)
            {
                this.description.Text = currentExcuse.Description;
                this.results.Text = currentExcuse.Results;
                this.lastUsed.Value = currentExcuse.DateTime;
                if (!string.IsNullOrEmpty(currentExcuse.ExcusePath))
                {
                    fileDate.Text =
                        File.GetLastWriteTime(
                            currentExcuse.ExcusePath).ToString();
                }
                this.Text = "口実マネージャ";
            }
            else
            {
                this.Text = "口実マネージャ*";
            }
            this.formChanged = changed;
        }
        private void folder_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.SelectedPath = selectedPath;
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                selectedPath = folderBrowserDialog1.SelectedPath;
                save.Enabled = true;
                open.Enabled = true;
                randomExcuse.Enabled = true;
            }
        }

        private void save_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(description.Text) ||
                string.IsNullOrEmpty(excuse.Text))
            {
                MessageBox.Show(
                    "口実とその結果を入力してください。",
                    "保存できません",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Exclamation);
            }
            else
            {
                saveFileDialog1.InitialDirectory = selectedPath;
                saveFileDialog1.Filter =
                    "excuseファイル(*.excuse)|すべてのファイル(*.*)";
                saveFileDialog1.FileName = description.Text + ".excuse";
                DialogResult result = saveFileDialog1.ShowDialog();
                if (result == DialogResult.OK)
                {
                    currentExcuse.save(saveFileDialog1.FileName);
                    UpdateForm(false);
                }
            }
        }

        private void open_Click(object sender, EventArgs e)
        {
            if (formChanged)
            {
                DialogResult dialogResult =
                    MessageBox.Show(
                    "この口実は保存されません。よろしいですか?",
                    "警告",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Exclamation);
                if (dialogResult == DialogResult.No)
                {
                    return;
                }
            }
            openFileDialog1.InitialDirectory = selectedPath;
            openFileDialog1.FileName = description.Text + ".excuse";
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                bool clearForm = false;
                try
                {
                    currentExcuse = new Excuse(openFileDialog1.FileName);
                    try
                    {
                        UpdateForm(false);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(
                            "'" + openFileDialog1.FileName + "'\n" +
                            "無効な口実ファイルを読み込もうとしました\n" +
                            ex.Message,
                            "口実ファイルを開けません",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                        clearForm = true;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(
                        "次の口実ファイルを開くときにエラーが発生しました'" +
                        openFileDialog1.FileName + "'\n" +
                        ex.Message,
                        "口実ファイルを開けません",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    clearForm = true;
                }
                finally
                {
                    if (clearForm)
                    {
                        description.Text = "";
                        results.Text = "";
                        lastUsed.Value = DateTime.Now;
                    }
                }
            }
        }

        private void randomExcuse_Click(object sender, EventArgs e)
        {
            if (formChanged)
            {
                DialogResult dialogResult =
                    MessageBox.Show(
                    "この口実は保存されません。よろしいですか?",
                    "警告",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Exclamation);
                if (dialogResult == DialogResult.No)
                {
                    return;
                }
            }
            currentExcuse = new Excuse(random, selectedPath);
            UpdateForm(false);
        }

        private void description_TextChanged(object sender, EventArgs e)
        {
            currentExcuse.Description = description.Text;
            UpdateForm(true);
        }

        private void results_TextChanged(object sender, EventArgs e)
        {
            currentExcuse.Results = results.Text;
            UpdateForm(true);
        }

        private void lastUsed_ValueChanged(object sender, EventArgs e)
        {
            currentExcuse.DateTime = lastUsed.Value;
            UpdateForm(true);
        }
    }
}

0 コメント:

コメントを投稿