Friday 20 April 2012

Visual Studio 2010 - MS Sql 2012 - ASP.NET - How to create server and client using WCF PART 3

Watch this example on YouTube:





Part 1
Part 2
Part 3


Add System.Data.Services.Client reference from .NET tab

Add new web form to the project, name it Test

Set it as start up page

Add to the form
- drop down menu called departmentList
- text box called departmentName
- button called saveChanges
- button called deleteRecord

Open Text.aspx.cs file and add the following
using System.Data.Services.Client;
using Client.SchoolService;

declare some private variables and implement on page load procedure that will populate departmentList drop down.  Remember - you can always watch video below to view all the steps.
Whole code so far looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Services.Client;
using Client.SchoolService;

namespace Client
{
    public partial class Test : System.Web.UI.Page
    {
        private SchoolEntities context;
        private Uri svcUri = new Uri("http://localhost:50433/SchoolService.svc");

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                loadDepartments();
            }
        }

        private void loadDepartments()
        {
            context = new SchoolEntities(svcUri);
            var departments = from d in context.Dpts
                              orderby d.DepartmentName
                              select new
                              {
                                  Id = d.DepartmentId,
                                  Name = d.DepartmentName
                              };
            departmentList.DataTextField = "Name";
            departmentList.DataValueField = "Id";
            departmentList.DataSource = departments;
            departmentList.DataBind();
            departmentList.Items.Insert(0, new ListItem("Create new department", ""));
        }
    }
}

Run project and notice that drop down menu has been populated with some records from database

Now let's implement selected index changed of our departmentList - first ensure that AutoPostBack is set to true


Code looks like this:
        protected void departmentList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (departmentList.SelectedValue == "")
            {
                departmentName.Text = "";
            }
            else
            {
                context = new SchoolEntities(svcUri);
                int id = Convert.ToInt32(departmentList.SelectedValue);
                List<Dpt> departments = (from d in context.Dpts
                                         where d.DepartmentId == id
                                         select d).ToList();
                if (departments.Count() > 0)
                {
                    Dpt dep = departments[0];
                    departmentName.Text = dep.DepartmentName;
                }
                else
                {
                    departmentName.Text = "";
                }
            }
        }
Run to see that now departmentName text box is populated with selected department.  This is very simple example, both drop down menu and text box display same info - I just want to illustrate how to perform CRUD operations using WCF DataServices....


Next step is to implement Save function
Code looks like this:
        protected void Changes_Click(object sender, EventArgs e)
        {
            context = new SchoolEntities(svcUri);
            Dpt dep = new Dpt();
            dep.DepartmentName = departmentName.Text;
            // NEW RECORD - INSERT

            if (departmentList.SelectedValue == "")
            {
                context.AddObject("Dpts", dep);
            }
            else
            {
                //EXISTING RECORD - UPDATE
                dep.DepartmentId = Convert.ToInt32(departmentList.SelectedValue);
                context.AttachTo("Dpts", dep);
                context.UpdateObject(dep);
            }
            context.SaveChanges();
            loadDepartments();
            departmentList.Items.FindByValue(dep.DepartmentId.ToString()).Selected = true;
        }
Again, test, to see if both  insert and update functionality is working properly.
Last - delete
Code looks like this:

        protected void deleteRecord_Click(object sender, EventArgs e)
        {
            if (departmentList.SelectedValue != "")
            {
                context = new SchoolEntities(svcUri);
                Dpt dep = new Dpt();
                dep.DepartmentId = Convert.ToInt32(departmentList.SelectedValue);
                context.AttachTo("Dpts", dep);
                context.DeleteObject(dep);
                context.SaveChanges();
                loadDepartments();
                departmentName.Text = "";
            }
        }

That's it! Here is whole code from our web form
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Services.Client;
using Client.SchoolService;

namespace Client
{
    public partial class Test : System.Web.UI.Page
    {
        private SchoolEntities context;
        private Uri svcUri = new Uri("http://localhost:50433/SchoolService.svc");

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                loadDepartments();
            }
        }

        private void loadDepartments()
        {
            context = new SchoolEntities(svcUri);
            var departments = from d in context.Dpts
                              orderby d.DepartmentName
                              select new
                              {
                                  Id = d.DepartmentId,
                                  Name = d.DepartmentName
                              };
            departmentList.DataTextField = "Name";
            departmentList.DataValueField = "Id";
            departmentList.DataSource = departments;
            departmentList.DataBind();
            departmentList.Items.Insert(0, new ListItem("Create new department", ""));
        }

        protected void departmentList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (departmentList.SelectedValue == "")
            {
                departmentName.Text = "";
            }
            else
            {
                context = new SchoolEntities(svcUri);
                int id = Convert.ToInt32(departmentList.SelectedValue);
                List<Dpt> departments = (from d in context.Dpts
                                         where d.DepartmentId == id
                                         select d).ToList();
                if (departments.Count() > 0)
                {
                    Dpt dep = departments[0];
                    departmentName.Text = dep.DepartmentName;
                }
                else
                {
                    departmentName.Text = "";
                }
            }
        }

        protected void Changes_Click(object sender, EventArgs e)
        {
            context = new SchoolEntities(svcUri);
            Dpt dep = new Dpt();
            dep.DepartmentName = departmentName.Text;

            if (departmentList.SelectedValue == "")
            {
                context.AddObject("Dpts", dep);
            }
            else
            {
                dep.DepartmentId = Convert.ToInt32(departmentList.SelectedValue);
                context.AttachTo("Dpts", dep);
                context.UpdateObject(dep);
            }
            context.SaveChanges();
            loadDepartments();
            departmentList.Items.FindByValue(dep.DepartmentId.ToString()).Selected = true;
        }

        protected void deleteRecord_Click(object sender, EventArgs e)
        {
            if (departmentList.SelectedValue != "")
            {
                context = new SchoolEntities(svcUri);
                Dpt dep = new Dpt();
                dep.DepartmentId = Convert.ToInt32(departmentList.SelectedValue);
                context.AttachTo("Dpts", dep);
                context.DeleteObject(dep);
                context.SaveChanges();
                loadDepartments();
                departmentName.Text = "";
            }
        }
    }
}