Sachirou Inoue avatar Sachirou Inoue committed 7e8dc40

Take some optimize to code.

Comments (0)

Files changed (15)

UserControl/Login.cs

         /// <summary>
         /// login idを示します。loginしていない場合にはnullを返します。
         /// </summary>
-        /// <param name="session"></param>
-        /// <returns></returns>
         public string LoginID
         {
             get
         /// <summary>
         /// userIDとpassが正当か否か確認します。正当であれば、Sessionのlogin処理を行います。
         /// </summary>
-        /// <param name="session"></param>
         /// <param name="userID"></param>
         /// <param name="pass"></param>
         /// <returns></returns>
         /// <summary>
         /// Sessionをlog outさせます。
         /// </summary>
-        /// <param name="session"></param>
         public void Logout()
         {
             Session["id"] = null;

UserControl/User.cs

 using System;
+using System.Text.RegularExpressions;
 
 namespace UserControl
 {
         private string _ID;
         public string ID {
             get { return _ID; }
+            /// <summary>
+            /// 5字以内の英数文字列である必要があります。空文字列は受け付けられません。違反していればFormatExceptionを投げます。
+            /// </summary>
             set
             {
-                if (value.Length == 0 || value.Length > 5)
+                if (value == string.Empty || value.Length > 5 || !Regex.IsMatch(value, "[A-Za-z0-9]{1,5}"))
                     throw new FormatException("ID has illegal format.");
                 _ID = value;
             }
         private string _Name;
         public string Name {
             get { return _Name; }
+            /// <summary>
+            /// 20字以内の文字列である必要があります。空文字列は受け付けられません。違反していればFormatExceptionを投げます。
+            /// </summary>
             set
             {
-                if (value.Length == 0 || value.Length > 20)
+                if (value == string.Empty || value.Length > 20)
                     throw new FormatException("Name has illegal format.");
                 _Name = value;
             }
         public string Pass
         {
             get { return _Pass; }
+            /// <summary>
+            /// 3字以内の英数文字列である必要があります。空文字列は受け付けられません。違反していればFormatExceptionを投げます。
+            /// </summary>
             set
             {
-                if (value.Length == 0 || value.Length > 3)
+                if (value == string.Empty || value.Length > 3 || !Regex.IsMatch(value, "[A-Za-z0-9]{1,3}"))
                     throw new FormatException("Pass has illegal format.");
                 _Pass = value;
             }
         }
 
+        public static readonly uint DefaultAge = 0;
         public uint Age { get; set; }
 
+        /// <summary>
+        /// 各parameterの書式が正しい必要があります。違反していればFormatExceptionを投げます。
+        /// </summary>
+        /// <param name="id">5字以内の英数文字列である必要があります。空文字列は受け付けられません。</param>
+        /// <param name="name">20字以内の文字列である必要があります。空文字列は受け付けられません。</param>
+        /// <param name="pass">3字以内の英数文字列である必要があります。空文字列は受け付けられません。</param>
+        /// <param name="age"></param>
         public User(string id, string name, string pass, uint age)
         {
             ID = id;
             Age = age;
         }
 
+        /// <summary>
+        /// 各parameterの書式が正しい必要があります。違反していればFormatExceptionを投げます。
+        /// </summary>
+        /// <param name="id">5字以内の英数文字列である必要があります。空文字列は受け付けられません。</param>
+        /// <param name="name">20字以内の文字列である必要があります。空文字列は受け付けられません。</param>
+        /// <param name="pass">3字以内の英数文字列である必要があります。空文字列は受け付けられません。</param>
         public User(string id, string name, string pass)
         {
             ID = id;
             Name = name;
             Pass = pass;
-            Age = 0;
+            Age = DefaultAge;
         }
     }
 }

UserControl/confirm.aspx.cs

 {
     public partial class confirm : System.Web.UI.Page
     {
+        private static string MainPageUrl = "view.aspx";
+
+        private User _TargetUser;
+        private User TargetUser
+        {
+            get
+            {
+                if (_TargetUser == null && Session["TargetUser"] != null)
+                    _TargetUser = (User)Session["TargetUser"];
+                return _TargetUser;
+            }
+            set {
+                Session["TargetUser"] = _TargetUser = value;
+            }
+        }
+
         private void ShowError(string message)
         {
             LabelError.Text = HttpUtility.HtmlEncode(message);
             }
             else LabelNotification.Text = string.Empty;
 
-            if (Session["UpdateUserID"] == null) Response.Redirect("view.aspx");
-            LabelUserID.Text = HttpUtility.HtmlEncode((string)Session["UpdateUserID"]);
-            LabelName.Text = HttpUtility.HtmlEncode((string)Session["UpdateName"]);
-            LabelPass.Text = HttpUtility.HtmlEncode((string)Session["UpdatePass"]);
-            LabelAge.Text = ((uint)Session["UpdateAge"]).ToString();
+            if (TargetUser == null) Response.Redirect(MainPageUrl);
+            LabelUserID.Text = HttpUtility.HtmlEncode(TargetUser.ID);
+            LabelName.Text = HttpUtility.HtmlEncode(TargetUser.Name);
+            LabelPass.Text = HttpUtility.HtmlEncode(TargetUser.Pass);
+            LabelAge.Text = TargetUser.Age.ToString();
         }
 
         protected void ButtonUserForm_Click(object sender, EventArgs e)
         {
             var users = new Users();
-            string userID = (string)Session["UpdateUserID"];
             try
             {
-                User user = new User(userID,
-                       (string)Session["UpdateName"],
-                       (string)Session["UpdatePass"],
-                       (uint)Session["UpdateAge"]);
-                users.UpdateUser(user);
-            }
-            catch (FormatException err)
-            {
-                ShowError(err.Message);
-                return;
+                users.UpdateUser(TargetUser);
             }
             catch (InvalidOperationException err)
             {
                 ShowError(err.Message);
                 return;
             }
-            Session["UpdateUserID"] = null;
-            Session["UpdateName"] = null;
-            Session["UpdatePass"] = null;
-            Session["UpdateAge"] = null;
-            Session["notification"] = string.Format("既存のUser「{0}」の情報を更新しました!", userID);
-            Response.Redirect("view.aspx");
+            Session["notification"] = string.Format("既存のUser「{0}」の情報を更新しました!", TargetUser.ID);
+            TargetUser = null;
+            Response.Redirect(MainPageUrl);
         }
     }
 }

UserControl/delete.aspx

                     <asp:Label ID="LabelAge" runat="server" Text=""></asp:Label>
                 </div>
             </div>
+            <div id="loginFormError">
+                <asp:Label ID="LabelError" CssClass="error" runat="server" Text="" Visible="False"></asp:Label>
+            </div>
             <asp:Button ID="ButtonUserForm" runat="server" Text="Delete" 
                 onclick="ButtonUserForm_Click" />
         </div>

UserControl/delete.aspx.cs

 {
     public partial class delete : System.Web.UI.Page
     {
-        private string UserID;
+        private static string MainPageUrl = "view.aspx";
+
+        private string _LoginID;
+        private string LoginID
+        {
+            get
+            {
+                if (_LoginID == null) _LoginID = new Login(Session).LoginID;
+                return _LoginID;
+            }
+        }
+
+        private string _TargetUserID;
+        private string TargetUserID
+        {
+            get
+            {
+                if (_TargetUserID == null) _TargetUserID = HttpUtility.UrlDecode(Request.QueryString["id"]);
+                return _TargetUserID;
+            }
+        }
+
+        private void ShowError(string message)
+        {
+            LabelError.Text = HttpUtility.HtmlEncode(message);
+            LabelError.Visible = true;
+        }
 
         protected void Page_Load(object sender, EventArgs e)
         {
-            string loginID = new Login(Session).LoginID;
-            if (loginID == null) Response.Redirect(Login.LoginUrl);
+            if (LoginID == null) Response.Redirect(Login.LoginUrl);
             if (Session["notification"] != null)
             {
                 LabelNotification.Text = HttpUtility.HtmlEncode((string)Session["notification"]);
             }
             else LabelNotification.Text = string.Empty;
 
-            var users = new Users();
-            UserID = HttpUtility.UrlDecode(Request.QueryString["id"]);
-            if (UserID == null) Response.Redirect("view.aspx");
-            User user = users.FindUserByID(UserID);
-            if (user == null) Response.Redirect("view.aspx");
-            LabelUserID.Text = HttpUtility.HtmlEncode(UserID);
+            if (TargetUserID == null) Response.Redirect(MainPageUrl);
+            User user = new Users().FindUserByID(TargetUserID);
+            if (user == null) Response.Redirect(MainPageUrl);
+            LabelUserID.Text = HttpUtility.HtmlEncode(TargetUserID);
             LabelName.Text = HttpUtility.HtmlEncode(user.Name);
             LabelPass.Text = "********";
             LabelAge.Text = user.Age.ToString();
-            if (loginID == UserID) ButtonUserForm.Enabled = false;
+            if (LoginID == TargetUserID) ButtonUserForm.Enabled = false;
         }
 
         protected void ButtonUserForm_Click(object sender, EventArgs e)
         {
-            var users = new Users();
+            if (LoginID == TargetUserID)
+            {
+                ShowError("自分のアカウントを消すことはできません。");
+                return;
+            }
             try
             {
-                users.DeleteUser(UserID);
-                Session["notification"] = string.Format("User「{0}」を削除しました!", UserID);
-                Response.Redirect("view.aspx");
+                new Users().DeleteUser(TargetUserID);
             }
             catch (InvalidOperationException err)
             {
-                Session["notification"] = err.Message;
+                ShowError(err.Message);
+                return;
             }
+            Session["notification"] = string.Format("User「{0}」を削除しました!", TargetUserID);
+            Response.Redirect(MainPageUrl);
         }
     }
 }

UserControl/delete.aspx.designer.cs

         protected global::System.Web.UI.WebControls.Label LabelAge;
         
         /// <summary>
+        /// LabelError コントロール。
+        /// </summary>
+        /// <remarks>
+        /// 自動生成されたフィールド。
+        /// 変更するには、フィールドの宣言をデザイナ ファイルから分離コード ファイルに移動します。
+        /// </remarks>
+        protected global::System.Web.UI.WebControls.Label LabelError;
+        
+        /// <summary>
         /// ButtonUserForm コントロール。
         /// </summary>
         /// <remarks>

UserControl/insert.aspx

                 <div class="userFormItemName">ID</div>
                 <div class="userFormItemInput">
                     <asp:TextBox ID="TextBoxUserID" runat="server" 
-                        ontextchanged="TextBoxUserID_TextChanged"></asp:TextBox>
+                        ontextchanged="TextBoxUserID_TextChanged" AutoPostBack="True"></asp:TextBox>
                 </div>
             </div>
             <div class="userFormItem">
                     ValidationExpression="[A-Za-z0-9]{1,3}"></asp:RegularExpressionValidator>
                 <asp:RegularExpressionValidator ID="RegularExpressionValidatorAge" 
                     runat="server" ErrorMessage="年齢の書式が違います。" ControlToValidate="TextBoxAge" 
-                    ValidationExpression="[1-9][0-9]+" CssClass="error"></asp:RegularExpressionValidator>
+                    ValidationExpression="[1-9][0-9]*" CssClass="error"></asp:RegularExpressionValidator>
             </div>
             <asp:Button ID="ButtonUserForm" runat="server" Text="追加" 
                 onclick="ButtonUserForm_Click" style="height: 21px" />

UserControl/insert.aspx.cs

 
         protected void ButtonUserForm_Click(object sender, EventArgs e)
         {
-            var users = new Users();
             string userID = TextBoxUserID.Text;
-            if (users.IsExistID(userID))
-            {
-                ShowErrorUserIDIsAlreadyExist();
-                return;
-            }
             uint age;
             if (!uint.TryParse(TextBoxAge.Text, out age)) age = 0;
             try
             {
                 User user = new User(userID, TextBoxName.Text, TextBoxPass.Text, age);
-                users.AddUser(user);
+                new Users().AddUser(user);
             }
             catch (FormatException err)
             {
                 ShowErrorIllegalFormat(err.Message);
                 return;
             }
+            catch (InvalidOperationException)
+            {
+                ShowErrorUserIDIsAlreadyExist();
+                return;
+            }
             Session["notification"] = string.Format("新たなUser「{0}」を追加しました!", userID);
             Response.Redirect("view.aspx");
-
         }
 
         protected void TextBoxUserID_TextChanged(object sender, EventArgs e)
         {
-            var users = new Users();
-            if (users.IsExistID(TextBoxUserID.Text)) ShowErrorUserIDIsAlreadyExist();
+            if (new Users().IsExistID(TextBoxUserID.Text)) ShowErrorUserIDIsAlreadyExist();
             else HideErrorUserIDIsAlreadyExist();
         }
     }

UserControl/style/loginForm.scss

 
   #loginFormError {}
 
-  #ButtonLogin { @include formButton; }
+  #ButtonLogin { @include userFormButton; }
 }

UserControl/style/style.scss

   background: linear-gradient($start, $from, $to);
 }
 
-@mixin formButton {
+@mixin userFormButton {
   bottom: 10px;
   clear: both;
   position: absolute;

UserControl/style/userForm.scss

 
   #userFormError {}
 
-  #ButtonUserForm { @include formButton; }
+  #ButtonUserForm { @include userFormButton; }
 }

UserControl/update.aspx

                 </div>
             </div>
             <div id="userFormError">
+                <asp:Label ID="LabelError" CssClass="error" runat="server" Text="" Visible="False"></asp:Label>
                 <asp:RegularExpressionValidator ID="RegularExpressionValidatorName" 
                     runat="server" ErrorMessage="名前の書式が違います。" ControlToValidate="TextBoxName" 
                     ValidationExpression=".{1,20}" CssClass="error"></asp:RegularExpressionValidator>
                     ValidationExpression="[A-Za-z0-9]{1,3}"></asp:RegularExpressionValidator>
                 <asp:RegularExpressionValidator ID="RegularExpressionValidatorAge" 
                     runat="server" ErrorMessage="年齢の書式が違います。" ControlToValidate="TextBoxAge" 
-                    ValidationExpression="[1-9][0-9]+" CssClass="error"></asp:RegularExpressionValidator>
+                    ValidationExpression="[1-9][0-9]*" CssClass="error"></asp:RegularExpressionValidator>
             </div>
             <asp:Button ID="ButtonUserForm" runat="server" Text="修正" 
             onclick="ButtonUserForm_Click" />

UserControl/update.aspx.cs

 {
     public partial class update : System.Web.UI.Page
     {
+        private static string MainPageUrl = "view.aspx";
+
+        private void ShowError(string message)
+        {
+            LabelError.Text = HttpUtility.HtmlEncode(message);
+            LabelError.Visible = true;
+        }
+
         protected void Page_Load(object sender, EventArgs e)
         {
             if (new Login(Session).LoginID == null) Response.Redirect(Login.LoginUrl);
 
             if (!IsPostBack)
             {
-                var users = new Users();
                 string userID = HttpUtility.UrlDecode(Request.QueryString["id"]);
-                if (userID == null) Response.Redirect("view.aspx");
-                User user = users.FindUserByID(userID);
-                if (user == null) Response.Redirect("view.aspx");
+                if (userID == null) Response.Redirect(MainPageUrl);
+                User user = new Users().FindUserByID(userID);
+                if (user == null) Response.Redirect(MainPageUrl);
                 LabelUserID.Text = HttpUtility.HtmlEncode(userID);
                 TextBoxName.Text = user.Name;
                 TextBoxPass.Text = user.Pass;
 
         protected void ButtonUserForm_Click(object sender, EventArgs e)
         {
-            Session["UpdateUserID"] = Request.QueryString["id"];
-            Session["UpdateName"] = TextBoxName.Text;
-            Session["UpdatePass"] = TextBoxPass.Text;
             uint age;
             if (!uint.TryParse(TextBoxAge.Text, out age)) age = 0;
-            Session["UpdateAge"] = age;
+            User user;
+            try
+            {
+                user = new User(Request.QueryString["id"],
+                    TextBoxName.Text,
+                    TextBoxPass.Text,
+                    age);
+            }
+            catch (FormatException err)
+            {
+                ShowError(err.Message);
+                return;
+            }
+            Session["TargetUser"] = user;
             Response.Redirect("confirm.aspx");
         }
     }

UserControl/update.aspx.designer.cs

         protected global::System.Web.UI.WebControls.TextBox TextBoxAge;
         
         /// <summary>
+        /// LabelError コントロール。
+        /// </summary>
+        /// <remarks>
+        /// 自動生成されたフィールド。
+        /// 変更するには、フィールドの宣言をデザイナ ファイルから分離コード ファイルに移動します。
+        /// </remarks>
+        protected global::System.Web.UI.WebControls.Label LabelError;
+        
+        /// <summary>
         /// RegularExpressionValidatorName コントロール。
         /// </summary>
         /// <remarks>

UserControl/view.aspx.cs

 {
     public partial class view : System.Web.UI.Page
     {
-        private Users _Users;
-        private Users GetUsers()
+        private const string Ascending = "asc";
+        private const string Descending = "desc";
+
+        private Users _RequestUsers;
+        private Users RequestUsers
         {
-            if (_Users == null) _Users = new Users(Request.QueryString);
-            return _Users;
+            get
+            {
+                if (_RequestUsers == null) _RequestUsers = new Users(Request.QueryString);
+                return _RequestUsers;
+            }
         }
 
         private void ChangeOrder(string order)
         {
-            Users users = GetUsers();
-            if (users.Order == order)
+            if (RequestUsers.Order == order)
             {
-                if (users.Direction == "asc") users.Direction = "desc";
-                else users.Direction = "asc";
+                if (RequestUsers.Direction == Ascending) RequestUsers.Direction = Descending;
+                else RequestUsers.Direction = Ascending;
             }
             else
             {
-                users.Order = order;
-                users.Direction = "asc";
+                RequestUsers.Order = order;
+                RequestUsers.Direction = Ascending;
             }
-            Response.Redirect("view.aspx" + users.GetViewQuery());
+            Response.Redirect("view.aspx" + RequestUsers.GetViewQuery());
         }
 
         private void ShowPageNumber(uint lastPage)
         {
-            Users users = GetUsers();
-            uint currentPage = users.Page;
+            uint currentPage = RequestUsers.Page;
             string fragment = string.Empty;
             uint startPage = 1;
             if (lastPage > 10)
             }
             for (uint i = startPage; i <= lastPage; ++i)
             {
-                users.Page = i;
+                RequestUsers.Page = i;
                 if (i == currentPage) fragment += string.Format("<span class=\"pageNumber currentPageNumber\">{0}</span>", i);
                 else fragment += string.Format("<a class=\"pageNumber\" href=\"view.aspx{0}\">{1}</a>",
-                    HttpUtility.HtmlEncode(users.GetViewQuery()),
+                    HttpUtility.HtmlEncode(RequestUsers.GetViewQuery()),
                     i);
             }
-            users.Page = currentPage;
+            RequestUsers.Page = currentPage;
             LabelPageNumbers.Text = fragment;
         }
 
         private void ShowUsersView()
         {
-            Users users = GetUsers();
             string fragment = string.Empty;
-            foreach (var user in users.GetUsers())
+            foreach (var user in RequestUsers.GetUsers())
             {
                 fragment += string.Format(@"<tr><td>{0}</td><td>{1}</td><td>{2}</td>
                     <td><a href=""update.aspx?id={3}"">修正</a></td><td><a href=""delete.aspx?id={3}"">削除</a></td></tr>",
             const string blackBottomArrow = "▼";
             const string blackUpArrow = "▲";
             const string whiteBottomArrow = "▽";
-            Users users = GetUsers();
-            switch (users.Order)
+            switch (RequestUsers.Order)
             {
                 case "id":
-                    if (users.Direction == "asc") LinkButtonOrderUserID.Text = blackBottomArrow;
+                    if (RequestUsers.Direction == Ascending) LinkButtonOrderUserID.Text = blackBottomArrow;
                     else LinkButtonOrderUserID.Text = blackUpArrow;
                     LinkButtonOrderName.Text = whiteBottomArrow;
                     LinkButtonOrderAge.Text = whiteBottomArrow;
                     break;
                 case "name":
                     LinkButtonOrderUserID.Text = whiteBottomArrow;
-                    if (users.Direction == "asc") LinkButtonOrderName.Text = blackBottomArrow;
+                    if (RequestUsers.Direction == Ascending) LinkButtonOrderName.Text = blackBottomArrow;
                     else LinkButtonOrderName.Text = blackUpArrow;
                     LinkButtonOrderAge.Text = whiteBottomArrow;
                     break;
                 case "age":
                     LinkButtonOrderUserID.Text = whiteBottomArrow;
                     LinkButtonOrderName.Text = whiteBottomArrow;
-                    if (users.Direction == "asc") LinkButtonOrderAge.Text = blackBottomArrow;
+                    if (RequestUsers.Direction == Ascending) LinkButtonOrderAge.Text = blackBottomArrow;
                     else LinkButtonOrderAge.Text = blackUpArrow;
                     break;
                 default:
 
         private void ShowContents(string loginID)
         {
-            Users users = GetUsers();
-            LiteralCurrentUserName.Text = HttpUtility.HtmlEncode(users.FindUserByID(loginID).Name);
+            LiteralCurrentUserName.Text = HttpUtility.HtmlEncode(RequestUsers.FindUserByID(loginID).Name);
             ShowUsersView();
-            if (users.Search != null) TextBoxSearch.Text = users.Search;
+            if (RequestUsers.Search != null) TextBoxSearch.Text = RequestUsers.Search;
             ShowOrderMark();
-            int count = users.UserNumber();
+            int count = RequestUsers.UserNumber();
             ShowPageNumber(Convert.ToUInt32(count % 10 == 0 ? count / 10 : count / 10 + 1));
         }
 
 
         protected void ButtonSearch_Click(object sender, EventArgs e)
         {
-            Users users = GetUsers();
-            users.Search = TextBoxSearch.Text;
-            Response.Redirect("view.aspx" + users.GetViewQuery());
+            RequestUsers.Search = TextBoxSearch.Text;
+            Response.Redirect("view.aspx" + RequestUsers.GetViewQuery());
         }
 
         protected void LinkButtonOrderUserID_Click(object sender, EventArgs e)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.