标签: c#

  • Redirection in a Page with Validation Objects

    I’ve been up to a new C# with ASP.NET project lately, and I plan to record down the problems occurred along the development, of course, with solutions.

    Here is the first one, about Redirection and Validation. It’s pretty simple, or, I should say amateur. You got it, amateur is who I am. ^^

    I encountered this problem that, Okay, here comes the

    Problem Description

    I’ve got a Button object with OnClick Event in page1, which, when clicked, Response.Redirect to page2. Meanwhile, I have some Validator objects in page1, too. The thing is, the client-side Validation occurs before even reaching the Event for the Button. That is to say, the Validators prevent Redirection from happening.

    Solution

    You’ll love this because it’s so easy. In the Button’s properties list, find "CausesValidation" and set it to false. That’s it.

    My thought is, there’s always some property control if an operation is generated on the server-side.

  • Displaying DateTime Object as Desired

    DateTime is a common type we deal with frequently in the development of C#-ASP.NET project. As a result, how to display a DateTime object properly is the knowledge we have to know as a web service developer.

    In the following paragraphs, I made a summary of formatting DateTime object in several circumstances to get it displayed as needed:

    • Format DateTime string retrieved from database and to be binded to Data Controls.
      <ASP:BoundColumn DataField="JoinTime" DataFormatString="{0:yyyy-MM-dd}" >
      </ASP:BoundColumn>
      <ASP:BoundColumn DataField="CheckoutTime" DataFormatString="{0:yyyy-MM-dd HH24:mm:ss}">
      </asp:BoundColumn>

    • Statement in the CodeFile to get a DateTime string.
      e.Item.Cell[0].Text = Convert.ToDateTime(e.Item.Cell[0].Text).ToShortDateString();

    • With the help of String class.
      String.Format( "yyyy-MM-dd ", theDateTimeObj);

    • With the help of Convert method.
      Convert.ToDateTime("2008-12-09").ToString;
      Convert.ToDateTime(dr["PubDate"]).ToShortDateString();

    • ToString method of DateTime class.
      DateTime.Now.ToString("yyyyMMddhhmmss");
      DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");

    • Show only year and month.
      DataBinder.Eval(Container.DataItem,"starttime","{0:yyyy-MM}");

    Certainly, there are more situations when you have to format a DateTime object, and the rules could be deduced from above.

    Technorati Tags: ,,
  • Dynamic Tree Construction according to User Role and Page

    In the developing environment of C# and .NET, dynamic data binding isn’t anything new at all. I’m here just to make a summary of how to do the job to a TreeView object, and add a few contents depending on my practical experience.

    Keywords: dynamic tree construction, user role, page.

    Problem Description

    In the classic three-layer architecture adopted by my project, we have

    1. data tables that are dealt with by a DAL-located class database.cs;

    2. a series of corresponding BLL classes to manipulate data retrieved from those tables;

    3. aspx pages and aspx.cs code files in the presentation layer.

    which means following elements are involved:

    1. data table User, UserRole, RoleTree;

    2. class User.cs, UserRole.cs, RoleTree.cs;

    3. example page sampleTree.aspx and its code file sampleTree.aspx.cs.

    A picture speaks more than a thousand words. Let’s first take a look at the chart below to get an overview of how this work is going to be done.

    Solution Pt1: User Login

    By the input username and password, we first get the userId, through which user role(s) are obtained and stored in a Session object. In case of more than one role for a specific user, we take an ArrayList as the role container.

    if (Page.IsValid)
    {
        User usr = new User();
        string userId = "";
        SqlDataReader recs = usr.GetUserLogin(txtUserName.Text.Trim(), txtPassword.Text.Trim());

        if (recs.Read())
        {
            userId = recs["UserID"].ToString();
        }
        recs.Close();

        if ((userId != String.Empty) && (userId != ""))
        {
            // get user roles, put them into session
            ArrayList alRoleIDs = new ArrayList();
            UserRole ur = new UserRole();
            SqlDataReader dr = ur.GetRoleByUserID(Int32.Parse(userId));
            while (dr.Read())
            {
                alRoleIDs.Add(Int32.Parse(dr["RoleID"].ToString()));
            }
            Session.Add("RoleIDs", alRoleIDs);
            dr.Close();
        }

    Solution Pt2: Tree Construction

    Then we take the RoleIDs of ArralyList above and some PageID of int as arguments to get the tree. Codes below are sample codes from sampleTree.aspx.cs:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindTreeData(treeSidebar, (ArrayList)Session["RoleIDs"]);
        }
    }

    private void BindTreeData(TreeView tv, ArrayList al)
    {
        RoleTree rt = new RoleTree();
        // when applied to different pages, take RoleIDs of ArrayList and PageID of int as arguments
        DataTable dt = rt.GetTreeByRoleIDandPageID(al, 3); // 3 is an exmaple of pageId
        tv.Nodes.Clear();

        foreach (DataRow row in dt.Select())
        {
            TreeNode tempNode = new TreeNode();
            tempNode.Text = row["Title"].ToString();
            tempNode.Value = row["NodeID"].ToString();
            tempNode.Expanded = false;
            tempNode.NavigateUrl = row["Url"].ToString();

            tv.Nodes.Add(tempNode);
        }
    }

    Further Notice

    //It is especially useful when applied to MasterPages.

    //This solution does not take node’s parent into account, which means the TreeView object constructed is not a real tree, strictly speaking.