Archive for the ‘CSLA’ Category

CSLA 3.6!

Monday, June 22nd, 2009

CSLA 3.6 introduces a host of new ways to do the things we used to do, one primary change is the use of LINQ and LINQ to SQL entities as your data layer. This change is pretty cool and the code reduction is even cooler! It is a bit of a mindset change so I seriously recommend reading Rocky Lhotka’s latest book on the framework before diving into it;it’ll make your life easier in the long run.

In this latest version of my CSLA: Step-by-Step guide, we’ll once again go through the process of creating business objects, bind them to Windows and Web UI’s and we’ll even throw in a WPF UI;

So without further ado let’s get started.

Step one: If you haven’t done so already, head over to Apress and buy a copy of Rocky Lhotka’s latest book to get a good understanding of the framework before you start using it.

Step two: Get the latest Codesmith templates from Codeplex. Not sure how to use Codesmith? read this post.

Step three: We’re going to be using a altered version of the Northwind database for this example, so download it here.

Right, so we’ve got our database, we’ have our code-gen templates. Fire up Visual Studio and create a new Windows Solution called NorthwindWPF, add a new Class Library Project, named Northwind.Library, add another Class Library Project named Northwind.DalLinq and finally add a VB.Net Windows Forms Application Project named Northwind.WinUI(Yes, I’m not forgetting my VB brethren)

Your Solution Explorer should look something like this:

image

Next, expand your Northwind.DalLinq project, and add a new LINQ to SQL Class called Northwind. Next, from the Server Explorer, drag the following tables to the Object Relational Designer window:

  • Customers
  • Orders
  • OrderDetails
  • Categories
  • Products

The result should look something like this:

image

Next, add a new Class named Database.cs to your project. In here we’ll store the connection string to the database, use the following code:

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5:  

   6: namespace Northwind.DalLinq

   7: {

   8:     public class Database

   9:     {

  10:         public const string Northwind = "Data Source=(local);" +

  11:         "Initial Catalog=Northwind;Integrated Security=True";

  12:     }

  13: }

That’s all we need for now in the DalLinq project, so expand your Northwind.Library project. Add a Reference to Csla.dll, and add a New Class called Customer to your project.

Next, open Codesmith and double-click on the EditableRoot Template. We’re going to generate an Editable Root object for our Customers table. The properties window should look like this:

image

You’ll notice a new property called DalNamespace, this tells your object where to look for the LINQ to SQL entities. Right, click Generate and viola! our Customer class is generated. Copy and paste the generated code to your Customer.cs class. Next, change this line :

   1: using (var mgr = ContextManager<Northwind.DalLinq.NorthwindDataContext>

   2:                         .GetManager(Northwind.DalLinq.Database.Northwind))

to:

   1: using (var mgr = ContextManager<Northwind.DalLinq.NorthwindDataContext>

   2:             .GetManager(Northwind.DalLinq.Database.Northwind,false))

This tells CSLA not to check in the configuration file for the connection string, but in our Database class.

Right! We’re ready to test our class, add a unit test to the bottom of the Customer Class, it’ll look something like this:

   1: [TestFixture]

   2: public class Customer_Tests

   3: {

   4:     [Test]

   5:     public void Load()

   6:     {

   7:         Northwind.Library.Customer myCustomer = Northwind.Library.Customer.GetCustomer(1);

   8:         Console.WriteLine(myCustomer.CompanyName);

   9:     }

  10: }

Run it and if you see Alfreds Futter in the Output window, you know our business object is working! And guess what? We did all this without a single line of SQL! LINQ handles all the queries for us. Pretty cool stuff.

Check back next time, where we’ll look at adding and updating a customer, as well as generating some parent-child objects.

CSLA.Net:Step-by-Step – Using the BindingNavigator

Thursday, March 6th, 2008

I was recently asked how to use the BindingNavigator to scroll through a list of objects. It is actually a very simple process, and here’s how:

I’m using the same Northwind BO Library as with the previous posts. We have a Customer object, and the table design looks something like this:

image

Right, next create a new class called Customers. This class will inherit from EditableRootListBase . You can paste the following into the class:

 _
Public Class Customers
Inherits EditableRootListBase(Of Customer)
#Region " Business Methods "
Protected Overrides Function AddNewCore() As Object
Dim item As Customer = Customer.NewCustomer
Add(item)
Return item
End Function
#End Region
#Region " Factory Methods "
Public Shared Function GetList() As Customers
Return DataPortal.Fetch(Of Customers)()
End Function
Private Sub New()
Me.AllowEdit = True
Me.AllowNew = True
Me.AllowRemove = True
End Sub
#End Region
#Region " Data Access "
Private Overloads Sub DataPortal_Fetch()
Me.RaiseListChangedEvents = False
Using sqlconn As New SqlConnection(Database.NorthwindConnection)
sqlconn.Open()
Using cm As SqlCommand = sqlconn.CreateCommand
cm.CommandType = CommandType.Text
cm.CommandText = "SELECT * FROM Customers WITH (NOLOCK)"
Using dr As New SafeDataReader(cm.ExecuteReader())
While dr.Read
Add(Customer.GetCustomer(dr.GetInt32("CustomerID")))
End While
dr.Close()
End Using
End Using
sqlconn.Close()
End Using
Me.RaiseListChangedEvents = True
End Sub
#End Region
End Class 

Compile your project and add a new form. Drag the Customers object from the Data Sources window to your newly created form. It should automatically add a BindingNavigator and a Datagridview to your form. Go ahead and delete the grid.

Next, drag the CustomerTextID, CompanyName, ContactName fields onto your form. Your form should look something like this:

image_3

Select the Save button on the BindingNavigator and set it’s Enabled property to True. Switch to Code view and add the following declaration:

Dim _cust As Customer

Next, add the following code to your form’s Load Event:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
CustomersBindingSource.DataSource = Customers.GetList
End Sub 

Now, we need to handle the BindingNavigator’s Save event. You do not need to worry about the AddNew or Delete Events, the business object handles those for you.

Add the following code to the BindingSource’s PositionChanged event:

Private Sub CustomersBindingSource_PositionChanged(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles CustomersBindingSource.PositionChanged
_cust = CType(CustomersBindingSource.Current, Customer)
End Sub 

Finally, add the following to the Save button’s click event:

Private Sub CustomersBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles CustomersBindingNavigatorSaveItem.Click
_cust.ApplyEdit()
_cust.Save(True)
End Sub 

Press F5 and see your handy work, it should look something like this:

image_4 

There you go, a quick and neat way to use the BindingNavigator with CSLA objects. Until next time, keep coding…

CSLA.Net: Step-by-Step – Web forms Episode II: The Update strikes back.

Saturday, February 16th, 2008

Welcome back! See I told you, you needn’t wait another 2 months for the next installment.

Today, we’ll have a look at updating an existing customer and adding a new customer via our web interface. I would like to mention that, these tutorials barely touch the surface of the CSLA.Net framework. To fully grasp the framework, buy Rockford Lhotka’s book Expert VB.Net Business Object, the value you’ll get by reading the book will definitely be worth the cost.

Also, to get a more detailed look at how to do things, be sure to check out the ProjectTracker project that comes with the framework.

Right, with that out of the way, let’s get started. Open the NorthwindWEB project; we created in the last post. Select the detailsview control, in my case it has the very original name of DetailsView1, and click on the little arrow top-right. Tick the Enable Inserting and Enable Editing checkboxes. It should look something like this:

clip_image002

You’ll notice that the DetailsView control now has 2 hyperlinks entitled Edit and New

image

You’ll notice that when you click on either of the links, it automatically changes the detailsview to edit mode and the hyperlinks’ text to either Update or Insert, depending on which link you clicked:

image_3

I’m just going to show you the quick and dirty way, managing your application state and object persistence is up to you.

Let’s first look at updating your customer. Open up your code view and add the following code:

Protected Sub dsCustomer_UpdateObject(ByVal sender As Object, ByVal e As Csla.Web.UpdateObjectArgs)
Handles dsCustomer.UpdateObject
Csla.Data.DataMapper.Map(e.Values, myCustomer)
myCustomer.Save()
End Sub

Remember we declared our Customer object, earlier. As soon as you click on update your changes will be saved. Now that was easy, wasn’t it?

Now for the Insert. In the global.asax file I’ve added the following in the Session_Start sub, this is to ensure I can persist the current object throughout the application:

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
Dim myCustomer As Northwind.Library.Customer = Northwind.Library.Customer.GetCustomer(3)
Session.Add("CustomerObject", myCustomer)
End Sub

Next in the DetailsView’s ItemCommand Sub I’ve added the following:

Protected Sub DetailsView1_ItemCommand(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.DetailsViewCommandEventArgs) Handles DetailsView1.ItemCommand
If e.CommandName = "New" Then
myCustomer = Customer.NewCustomer
Session("CustomerObject") = myCustomer
End If
End Sub

and then in the datasource’s InsertObject sub add the following:

Protected Sub dsCustomer_InsertObject(ByVal sender As Object, ByVal e As Csla.Web.InsertObjectArgs)
Handles dsCustomer.InsertObject
myCustomer = Session("CustomerObject")
Csla.Data.DataMapper.Map(e.Values, myCustomer, "CustomerID")
myCustomer.Save()
End Sub

So what’ll happen is that as soon as you click on the new link. A Customer.NewCustomer Object will be save in your Session’s CustomerObject. The as the page reloads, it shows the Customer object stored in the session. This object is then saved to the database.

I hope this made sense, it certainly is a quick and dirty way of doing it. Check the Project Tracker’s web project to see a proper implementation.

Until next time..cheerio.


Google Analytics integration offered by Wordpress Google Analytics Plugin