Getting Started – Using the XmlPropertyObject for COP4834

1.   Getting Started – Using the XmlPropertyObject for COP4834
i. Step 1 – Create a Web Project Using the Web Forms Project Template
  ii. Step 2 – Create a XmlPropertyObject Class in Your Project
    a. Create the Class File
    b. Copy Code Into File
  iii. Step 3 – Create an Inherited Class
    a. Create a Class File
    b. Add Properties
  iv. Step 4 – Setting Up The Database
    a. How The Database Works
    b. Creating the Database
    c. Creating the XmlPropertyObject Table
    d. Creating Database in Azure
    e. Get the Connection String
    f. Place ConnectionString in web.config
    g. Reading String From web.config
  v. Code Used in Tutorial
  vi. Code for XmlProperty Object
  vii. More About the XmlPropertyObject Code

Step 1 – Create a Web Project Using the Web Forms Project Template

Once this is complete you will have a form that looks something like this;

Visual Studio 2012 
Visual Studio 2013 

Step 2 – Create a XmlPropertyObject Class in Your Project

Create the Class File

Using Visual Studio Create a Directory under your project called App_Code. Just right click on the project, select Add – and create the directory. I do like to put all my classes in App_Code. Once that is done we will create a new class called XmlPropertyObject. To put it in the App_code directory create it by right clicking on the directory and select Add again – in this case select Class and call it XmlPropertyObject. This will give you a new class window with the new class in it.

Note that the Namespace declaration will be Your_Project.App_Code – I recommend changing this to just Your_Project. Unless you project is going to be very large and you need to organize all your code into different namespaces, this will simplify accessing your class.

Copy Code Into File

This class is currently blank – you can get the code from Topic – Creating a Single Table Database Object Storage – you can copy and paste directly into the cs file, replacing the existing code. After you do this change the namespace declaration to be the name of your project.

Your solution Explorer will look like this;

The file open in Visual Studio will look like this

If you have completed this step properly you should see the Interface IXmlPropertyObject, and 2 Classes XmlPropertyObject and XmlObjectDatabase when you view the file in the solution Explorer.

Step 3 – Create an Inherited Class

The next step is pretty easy. You will create a new class in App_Code. The sample class I will be creating here will be called UserProfile. Same as before Right Click on App_Code, select Add New Class and enter the name.

Create a Class File

Once you are done editing the file will look something like this in the editor

Add Properties

You still need to add properties to the class. You should understand how properties work and how to create and use them. For this example we are going to have some very simple properties based on the assignment. Here is how it looks with the properties set;

Step 4 – Setting Up The Database

How The Database Works

If you look at the class DatabaseXmlStore in the XmlPropertyObject.cs file (yes you can have more than one class per file) – you will see a method called SqlConnection and in that method you will see a hard coded string named cs. This will not work with the current string as your computer will not have access to the computer in that string. This should contain a connection to a valid database that you do have access to.

In addition this database also need to have the table XmlPropertyObject in it. The SQL defining the structure of this database is in the comments of DatabaseXmlStore.

Version 1 of Object 
Database Version 2 

If this table exists in a database, and the connection string used in the class points to this database you will be able to insert and retrieve objects from the database.

Creating the Database

Your first though might be that you do not have a database, but in reality you do. A database is created when you created the project. This database is used to maintain the login and user information that is part of the Membership classes the project uses. If you have not created any users this database will not exist, if you have – it will exist. By default the database will be in the same directory as your project in the App_Data folder. Take a look (if you have run your project and created a user) there will be an mdf and an ldf file in the folder – that is the database that hold the user login information.

I do not recommend using this database for your objects – however creating a database is as easy as creating a class. Click on the App_Data folder in the solution Explorer, Right Click, Add, New Item… – and you can create a SQL Server Database (name it ObjectDatabase). Once you create the database you will see the mdf and ldf files show up in the App_Data directory.

Creating the XmlPropertyObject Table

To work with the database you will want to be able to use the Server Explorer window in Visual Studio. This is available from the View menu.

The ObjectDatabase will be available in the Server Explorer. If you right click on the Tables and click New Query – a query window will open and you will be able to paste the Table creation SQL in this Window.

Click the Green arrow to execute the SQL and the table will be created.

Creating Database in Azure

I often use Azure to create and work with databases. In Azure you can easily create a SQL Database

Simply click the SQL Databases, Click New and name your database. Once complete you can manage your database through Azure. The Quick Start steps on the main screen will take you through most of the steps necessary. In the Azure Database Manager – you can open a SQL window that will make your life easier if you know SQL (just click New Query).

You can also view all the tables and database objects by clicking on the Design Link in the same window.

Get the Connection String

You will need the Connection String to this database. Right click on the Database in Server Explorer and click Properties. The Database properties will show up in the properties window and one of these properties will be ConnectionString

Place ConnectionString in web.config

We will want to put this Connection String into the web.config file. This is pretty easy to do with a little cut and paste. In the web.config there will be a section called connectionstrings. It will already have a connection string named DefaultConnection. Make a copy of this in the same section and change the name of the copy to ObectDatabase and the connectionString to the one from ObjectDatabase properties.You may have to remove some quotes to get the string to work correctly – just use the existing DefaultConnection connection to help you format the string.

Reading String From web.config

The last step is to read the string in the DatabaseXmlStore class from the web.config – rather than using the hard coded one. Simply replace the line where we define the variable cs in the method SqlConnection with;

string cs = ConfigurationManager.ConnectionStrings["ObjectDatabase"].ConnectionString;

and you will now be reading the string from the web.config file. Note that you may have to add the using System.Configuration;  to the using statements at the top of the XmlPropertyObject.cs file.

You can now use the XmlPropertyObject in your project.

Code Used in Tutorial

EditUserProfile.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"  CodeBehind="EditUserProfile.aspx.cs" Inherits="COP4834Spring2014WebForms.Pages.EditUserProfile" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
    <div class="InputForm">
    <table>
        <tr>
            <td>Full Name</td>
            <td>
                <asp:TextBox ID="tbFullName" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td>Address</td>
            <td>
                <asp:TextBox ID="tbAddress" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td>City</td>
            <td>
                <asp:TextBox ID="tbCity" runat="server"></asp:TextBox></td>
        </tr>
         <tr>
            <td>State</td>
            <td>
                <asp:TextBox ID="tbState" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td>Phone</td>
            <td>
                <asp:TextBox ID="tbPhone" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td>Email</td>
            <td>
                <asp:TextBox ID="tbEmail" runat="server"></asp:TextBox></td>
        </tr>
    </table>
        <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
        <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" />
        </div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
 
</asp:Content> 

EditUserProfile.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Security;
using System.Web.UI.WebControls;
using COP4834Spring2014WebForms;
namespace COP4834Spring2014WebForms.Pages
{
    public partial class EditUserProfile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            SetFormValues();
        }
        protected void SetFormValues()
        {
            MembershipUser mu = Membership.GetUser(Context.User.Identity.Name);
            tbEmail.Text = mu.Email;
        }
        protected void GetFormValues()
        {
           UserProfile up = new UserProfile();
            up.Address = tbAddress.Text;
            up.City = tbCity.Text;
            up.EMail = tbEmail.Text;
            up.FullName = tbFullName.Text;
            up.Phone = tbPhone.Text;
            up.State = tbState.Text;
            up.UserName = Context.User.Identity.Name;
            
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Default.aspx");
        }
    }
} 

UserProfile.aspx

namespace COP4834Spring2014WebForms
{
    public class UserProfile : XmlPropertyObject
    {
        public string FullName { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Phone { get; set; }
        public string UserName { get { return Name; } set { Name = value; } }
        public string EMail { get { return Description; } set { Description = value; } }
        // Note Name and Description are inherited from XmlPropertyObject
        // We are storing the email in Description
        // We are storing the UserName in Name
    }
} 

Code for XmlProperty Object

Version 
Link 
Description 
Database

XmlPropertyObject.cs   
Version documented here 
CREATE TABLE XmlObject (
          id INT PRIMARY KEY IDENTITY(1,1),
          ParentId INT NULL,
          ZOrder INT NULL,
          Class VARCHAR(255) NOT NULL,
          Name VARCHAR(255) NULL,
          Description VARCHAR(500) NULL,
          XMLData VARCHAR(MAX) NULL,
          OwnerUserID VARCHAR(255) NOT NULL,
          CreatedDate DATETIME NULL,
          LastEditedUserID VARCHAR(255) NULL,
          LastEditedDate DATETIME NULL,
          Version INT NULL) 

XmlPropertyObject(2).cs 
Adds ability to store and
retrieve List and Dictionary
Adds database fields for
Parent and more metadata
CREATE TABLE XmlObject (
          id INT PRIMARY KEY IDENTITY(1,1),
          ParentId INT NULL,
          ZOrder INT NULL,
          Class VARCHAR(255) NOT NULL,
          Name VARCHAR(255) NULL,
          Description VARCHAR(500) NULL,
          XMLData VARCHAR(MAX) NULL,
          OwnerUserID VARCHAR(255) NOT NULL,
          CreatedDate DATETIME NULL,
          LastEditedUserID VARCHAR(255) NULL,
          LastEditedDate DATETIME NULL,
          Version INT NULL)

More About the XmlPropertyObject Code

Step by Step – Using the XmlPropertyObject – Covers the items in this tutorial in a lecture

Lecture – Creating a Form Using XmlPropertyObject – Covers creating forms to save and update inherited XmlPropertyObject classes

Topic – Creating a Single Table Database Object Storage  – Inner details on how the code works.