Difference between revisions of "DD Class9"

esse quam videri
Jump to: navigation, search
(Logon)
m (Text replacement - "syntaxhighlight lang="csharp" line="1" " to "syntaxhighlight lang="csharp"")
 
(44 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
[[Category:Data Design]]
 
[[Category:Data Design]]
  
review Bios and Logon
+
==Repo Pattern==
  
==Logon==
+
Definition from P of EE http://martinfowler.com/eaaCatalog/repository.html
 +
MSDN [http://msdn.microsoft.com/en-us/library/ff649690.aspx The Repository Pattern]
  
Insert into the People Table
+
The repository pattern is a nice way to abstract data fetching logic and easily separate concerns from different layers of your app. It allows of to quickly refactor and swap repos.
  
<sql>
+
First we can start with the cheese definition
INSERT into People
 
(salutationID, firstName, lastName, logonName, passwd)
 
values
 
(1, 'jeff', 'meyers', 'jmeyers', 'monkey')
 
</sql>
 
  
Check the new users PeopleID
+
<syntaxhighlight lang="csharp">
 +
public class Cheese
 +
    {
 +
       
 +
        public int CheeseID { get; set; }
 +
       
 +
        public string CheeseName { get; set; }
 +
       
 +
        public string CheeseDescription { get; set; }
 +
    }
 +
</syntaxhighlight>
 +
Then interface for the repo
 +
<syntaxhighlight lang="csharp">
 +
public interface IRepository<T>
 +
    {
 +
        T GetById(int id);
 +
        List<T> GetItems();
 +
        void Add(T entity);
 +
        void Remove(T entity);
 +
    }
 +
</syntaxhighlight>
 +
Now we want to expand the interface definition to cheeses
 +
<syntaxhighlight lang="csharp">
 +
/// <summary>
 +
    /// ICheeseRepo Changes the type of the Generic Repo To Cheese
 +
    /// </summary>
 +
    public interface ICheeseRepo : IRepository<Cheese>
 +
    {
 +
        List<Cheese> GetItems();
 +
        List<Cheese> GetCheeses();  //New Method To Get Cheeses
 +
        //May want to expand the definition to get cheese by name
 +
        //Cheese GetByName(string name)
 +
    }
 +
</syntaxhighlight>
 +
Finally the repo interface can then be implemented like this
 +
<syntaxhighlight lang="csharp">
 +
public class TestCheeseRepository : ICheeseRepo
 +
    {
  
<sql>
+
        //could grab these from the Application Object
SELECT PeopleID from People WHERE firstName = 'jeff' and lastName='meyers' and logonName='jmeyers'
+
        private static List<Cheese> fakeCheeses =
</sql>
+
            new List<Cheese> { new Cheese { CheeseID=1, CheeseName="test1", CheeseDescription = "test desc 1" },
 +
                new Cheese { CheeseID=2, CheeseName="test2", CheeseDescription = "test desc 2" },
 +
                new Cheese { CheeseID=2, CheeseName="test3", CheeseDescription = "test desc 3" }
 +
            };
  
results PeopleID = 1
 
  
Give the new user a Role by inserting the PeopleID and a roleID into the roles table
+
        #region ICheeseRepo Members
 +
        public List<Cheese> GetItems()
 +
        {
 +
            return GetCheeses();
 +
        }
  
<sql>
 
INSERT into roles
 
( PeopleID, roleTypeID, RoleActive )
 
values
 
( 1, 1, 1)
 
</sql>
 
  
  Note that we need two INSERT statements to create a working account and role. Since these two statements
+
        public List<Cheese> GetCheeses()
depend on each other and we will be left with an Person without a role or a role without a person if one
+
        {
statement fails the entrire operation should be wrapped in a transaction. More on this next week...
+
            return fakeCheeses.ToList();
 +
        }
  
Now we have a user and that user has a role. We need to be able to read back the userName, passowrd, roleActive and roleTypeName in order to check if a user is valid.
+
        #endregion
  
The easiest way to do this is with a view
+
        #region IRepository<Cheese> Members
  
[[Image:Logon_wv.png]]
+
        public Cheese GetById(int id)
 +
        {
 +
            //linq statement to find cheese by ID
 +
            var currentCheese = from c in fakeCheeses where c.CheeseID == id select c;
 +
            return currentCheese.FirstOrDefault();
 +
        }
  
<sql>
+
        public void Add(Cheese entity)
SELECT dbo.people.peopleID, dbo.people.firstName, dbo.people.lastName, dbo.people.logonName,
+
        {
      dbo.people.passwd, dbo.peopleSalutationTypes.salutationID,
+
            fakeCheeses.Add(entity);
      dbo.peopleSalutationTypes.salutation, dbo.roles.roleActive, dbo.roleTypes.RoleTypeID,
+
        }
      dbo.roleTypes.RoleTypeName, dbo.roleTypes.RoleTypeHier,
 
      dbo.roleTypes.roleTypeActive
 
FROM dbo.people
 
INNER JOIN
 
      dbo.peopleSalutationTypes ON dbo.people.salutationID = dbo.peopleSalutationTypes.salutationID
 
INNER JOIN
 
      dbo.roles ON dbo.people.peopleID = dbo.roles.PeopleID
 
INNER JOIN
 
      dbo.roleTypes ON dbo.roles.RoleTypeID = dbo.roleTypes.RoleTypeID
 
</sql>
 
  
Now we can use the view to test a logon SELECT statement
+
        public void Remove(Cheese entity)
<sql>
+
        {
SELECT peopleID, firstName, lastName, logonName, passwd, salutationID,
+
            fakeCheeses.Remove(entity);
      salutation, roleActive, RoleTypeID, RoleTypeName, RoleTypeHier,
+
         }
      roleTypeActive
 
FROM logon_vw
 
WHERE 
 
logonName = 'jmeyers' and
 
passwd = 'monkey' and
 
         roleActive = 1 and
 
roleTypeActive = 1
 
</sql>
 
  
Now that we have the DataBase working correctly we can move on to the c#
+
        #endregion
  
==Review ADO==
+
        //added statement to find cheese by name
 +
        public Cheese GetByName(string name)
 +
        {
 +
            //linq statement to find cheese by name
 +
            var currentCheese = from c in fakeCheeses where c.CheeseName == name select c;
 +
            return currentCheese.FirstOrDefault();
 +
        }
 +
    }
 +
</syntaxhighlight>
  
{{Template:ADO.NET Diagram}}
+
Link to the implememtation http://iam.colum.edu/datadesign/gbrowser.php?file=/App_code/Repo/CheeseRepo.cs
  
[[Template:ADO.NET Diagram]]
+
Now to use the Repo
  
==Simple ADO Binding==
+
http://iam.colum.edu/datadesign/classsource/repo/Default.aspx
  
<csharp>
+
http://iam.colum.edu/datadesign/gbrowser.php?file=/classsource/repo/Default.aspx.cs
//Connection string comes from web config
 
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["IamConnectionJeff"].ConnectionString);           
 
       
 
        string strSQL = "Select * from Course"; 
 
       
 
        SqlCommand dc = new SqlCommand(strSQL , conn);
 
        SqlDataAdapter da = new SqlDataAdapter(dc);
 
        DataSet ds = new DataSet();
 
        DataTable dt = new DataTable();
 
       
 
        da.Fill(ds, "Course");          //Use the DataAdapter to fill the DataSet with a named Table
 
        dt = ds.Tables["Course"];      //Retreive the named table from the DataSet
 
       
 
        gvTestOrig.DataSource = dt;    //Set the DataTable as the source for the GridView noe AutoGenerateColumns = true
 
        gvTestOrig.DataBind();          //Bind the data form the table to the GridView
 
</csharp>
 
  
The above code binds to a control called gvTestOrig
+
<syntaxhighlight lang="csharp">
 +
ICheeseRepo db = new TestCheeseRepository();
 +
        gv1.DataSource = db.GetCheeses();
 +
        gv1.DataBind();
 +
</syntaxhighlight>
  
<csharp>
 
<asp:GridView ID="gvTestOrig" runat="server" AutoGenerateColumns="true" />
 
</csharp>
 
  
http://iam.colum.edu/dd/classsource/class8/SimpleADO.aspx [http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class8/SimpleADO.aspx - source]
 
  
Same code but I moved some of the code into a function and split the declareation and initialization of some object to that they are scoped to the page not to Page_Load. This allows other functions on the page to use these objects.
+
You can add LINQ helpers to the class
 
+
<syntaxhighlight lang="csharp">
http://iam.colum.edu/dd/classsource/class8/ADOTest1.aspx [http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class8/ADOTest1.aspx - source]
+
/// <summary>
 
+
    /// Cheese Class for Our Repo
==Inserting Editing Deleteing With ADO==
+
    /// </summary>
 
+
    [Table(Name = "Cheese")]
Add to a DataTable
+
    public class Cheese
<csharp>
+
    {
        DataTable dt = ds.Tables["Course"];
+
         [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
         DataRow dr = dt.NewRow();
+
         public int CheeseID { get; set; }
        dr["CourseName"] = "Applcations Design";
+
         [Column]
         dr["CourseNumber"] = "36-3601";
+
         public string CheeseName { get; set; }
        dt.Rows.Add(dr);
+
         [Column]
</csharp>
+
         public string CheeseDescription { get; set; }
 
+
    }
Modify and DataTable
+
</syntaxhighlight>
<csharp>
 
         DataTable dt = ds.Tables["Course"];
 
         DataRow dr = dt.Rows[3];           //Hack hard coded index
 
        dr["CourseName"] = "Application Design";
 
         dr["CourseNumber"] = "36-4601";
 
</csharp>
 
 
 
Delete from a DataTable
 
<csharp>
 
         DataTable dt = ds.Tables["Course"];
 
        DataRow dr = dt.Rows[1];           //Hack hard coded index
 
        dt.Rows.Remove(dr);
 
</csharp>
 
 
 
There are better method to select which row to modify see the example below
 
  
http://iam.colum.edu/dd/classsource/class8/ADOTest2AddModifyDelete.aspx [http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class8/ADOTest2AddModifyDelete.aspx - source]
+
and then create a new cheese repo
  
notice that changes made to the DataSet are not synchronized back to the Data Provider.
+
and update your repo initialization
The DataAdapter is able to sync these changes, remeber that the DataAdapter acts as a bridge between the
 
DataSet and the DataProvider.
 
  
The DataAdapter can use the SqlStringBuilder class to create select, update, and delete statements. Once these statements are built the DataAdapter can update the DataProvider.
+
<syntaxhighlight lang="csharp">
 +
ICheeseRepo db = new CheeseRepository(ConfigurationManager.ConnectionStrings["cheeseConnectionString"].ToString());
 +
        gv1.DataSource = db.GetCheeses();
 +
        gv1.DataBind();
 +
</syntaxhighlight>
  
<csharp>
+
LINQ classes in MVC must use the entire namespace
//Uses an SqlBuilder to update the DataAdapter also displays the generated sql in a lable
+
<syntaxhighlight lang="csharp">
     public void CommitChanges()
+
/// <summary>
 +
    /// Cheese Class for Our Repo
 +
    /// </summary>
 +
     [System.Data.Linq.Mapping.Table(Name = "Cheese")]
 +
    public class Cheese
 
     {
 
     {
         //Get a stringBuilder from out DataAdapter
+
         [System.Data.Linq.Mapping.Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
        SqlCommandBuilder cb = new SqlCommandBuilder(da);
+
         public int CheeseID { get; set; }
         da.UpdateCommand = cb.GetUpdateCommand();
+
         [System.Data.Linq.Mapping.Column]
         lblUpdateCommand.Text = da.UpdateCommand.CommandText;   //Display the update Command in a Label
+
        public string CheeseName { get; set; }
         da.Update(ds.Tables["Course"]);         //User tha DataAdpater to update the Data Provider
+
         [System.Data.Linq.Mapping.Column]
 +
        public string CheeseDescription { get; set; }
 
     }
 
     }
</csharp>
+
</syntaxhighlight>
  
http://iam.colum.edu/dd/classsource/class8/ADOTest3Commit.aspx
+
==Homework==
[http://iam.colum.edu/dd/gbrowser.php?file=/classsource/class8/ADOTest3Commit.aspx - source]
 
  
==Homework==
+
Use the repo pattern to create a repo for you own class. The the class should map to a table in your database. The repo should be able to show items in you db, add items and remove items.
  
Course adder example
+
Add the repo to your Web from site and your MVC site. The repose should be able to list items from the DB. Either the MVC site or the WebForms site should be able to add and delete items.
 +
I'll give 1 pt extra for updating items and 1 pt for adding/deleting in MVC and Web Forms.

Latest revision as of 03:20, 9 February 2016


Repo Pattern

Definition from P of EE http://martinfowler.com/eaaCatalog/repository.html MSDN The Repository Pattern

The repository pattern is a nice way to abstract data fetching logic and easily separate concerns from different layers of your app. It allows of to quickly refactor and swap repos.

First we can start with the cheese definition

 public class Cheese
    {
        
        public int CheeseID { get; set; }
        
        public string CheeseName { get; set; }
        
        public string CheeseDescription { get; set; }
    }

Then interface for the repo

public interface IRepository<T>
    {
        T GetById(int id);
        List<T> GetItems();
        void Add(T entity);
        void Remove(T entity);
    }

Now we want to expand the interface definition to cheeses

/// <summary>
    /// ICheeseRepo Changes the type of the Generic Repo To Cheese
    /// </summary>
    public interface ICheeseRepo : IRepository<Cheese>
    {
        List<Cheese> GetItems();
        List<Cheese> GetCheeses();  //New Method To Get Cheeses
        //May want to expand the definition to get cheese by name
        //Cheese GetByName(string name)
    }

Finally the repo interface can then be implemented like this

public class TestCheeseRepository : ICheeseRepo
    {

        //could grab these from the Application Object
        private static List<Cheese> fakeCheeses =
            new List<Cheese> { new Cheese { CheeseID=1, CheeseName="test1", CheeseDescription = "test desc 1" },
                new Cheese { CheeseID=2, CheeseName="test2", CheeseDescription = "test desc 2" },
                new Cheese { CheeseID=2, CheeseName="test3", CheeseDescription = "test desc 3" }
            };


        #region ICheeseRepo Members
        public List<Cheese> GetItems()
        {
            return GetCheeses();
        }


        public List<Cheese> GetCheeses()
        {
            return fakeCheeses.ToList();
        }

        #endregion

        #region IRepository<Cheese> Members

        public Cheese GetById(int id)
        {
            //linq statement to find cheese by ID
            var currentCheese = from c in fakeCheeses where c.CheeseID == id select c;
            return currentCheese.FirstOrDefault();
        }

        public void Add(Cheese entity)
        {
            fakeCheeses.Add(entity);
        }

        public void Remove(Cheese entity)
        {
            fakeCheeses.Remove(entity);
        }

        #endregion

        //added statement to find cheese by name
        public Cheese GetByName(string name)
        {
            //linq statement to find cheese by name
            var currentCheese = from c in fakeCheeses where c.CheeseName == name select c;
            return currentCheese.FirstOrDefault();
        }
    }

Link to the implememtation http://iam.colum.edu/datadesign/gbrowser.php?file=/App_code/Repo/CheeseRepo.cs

Now to use the Repo

http://iam.colum.edu/datadesign/classsource/repo/Default.aspx

http://iam.colum.edu/datadesign/gbrowser.php?file=/classsource/repo/Default.aspx.cs

ICheeseRepo db = new TestCheeseRepository();
        gv1.DataSource = db.GetCheeses();
        gv1.DataBind();


You can add LINQ helpers to the class

/// <summary>
    /// Cheese Class for Our Repo
    /// </summary>
    [Table(Name = "Cheese")]
    public class Cheese
    {
        [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
        public int CheeseID { get; set; }
        [Column]
        public string CheeseName { get; set; }
        [Column]
        public string CheeseDescription { get; set; }
    }

and then create a new cheese repo

and update your repo initialization

ICheeseRepo db = new CheeseRepository(ConfigurationManager.ConnectionStrings["cheeseConnectionString"].ToString()); 
        gv1.DataSource = db.GetCheeses();
        gv1.DataBind();

LINQ classes in MVC must use the entire namespace

/// <summary>
    /// Cheese Class for Our Repo
    /// </summary>
    [System.Data.Linq.Mapping.Table(Name = "Cheese")]
    public class Cheese
    {
        [System.Data.Linq.Mapping.Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
        public int CheeseID { get; set; }
        [System.Data.Linq.Mapping.Column]
        public string CheeseName { get; set; }
        [System.Data.Linq.Mapping.Column]
        public string CheeseDescription { get; set; }
    }

Homework

Use the repo pattern to create a repo for you own class. The the class should map to a table in your database. The repo should be able to show items in you db, add items and remove items.

Add the repo to your Web from site and your MVC site. The repose should be able to list items from the DB. Either the MVC site or the WebForms site should be able to add and delete items. I'll give 1 pt extra for updating items and 1 pt for adding/deleting in MVC and Web Forms.