jump to navigation

Using the ASP.Net Calendar Control September 21, 2009

Posted by fofo in asp.net, C#, Visual Studio 2005, Visual Studio 2008.
Tags: , , , ,
1 comment so far

I have been using my blog to talk primarily about new things and enhancements in the .Net Framework. I have been talking about C# new features,VB new features, LINQ,Entity framework and the new Visual Studio 2010. The other day during a seminar I was asked about a very important ASP.NET 2.0 web server control, the calendar control. So I thought to write a post and look into this very useful control, presenting its basic functionality but also looking into the more advanced functionality it has.

So what is the calendar control.

A simple but powerful definition could be:

It allows the users to select a date or a range of dates withing an application

I will be using VS 2008 and C# to create a simple asp.net application.

1) Launch Visual Studio 2005 or 2008.

2) Create a new website and name it with a meaningful name, e.g CalendarSite

3) Drag and drop a Calendar control from the toolbox into the default.aspx page.Leave the default name

4) Let’s examine some of the most used properties.

SelectedDate: By setting this property to a value, you have this value-date selected in the calendar control. Set the value to a date and run your application

VisibleDate:Whenever we want to use a different month or year, when the control initially loads, we can set the VisibleDate property to a date

If you want to select any particular day just click on the hyperlink on the bottom of each day.

5) But what if we wanted to select all of the days of a particular week or all the days of a particulat month.

Then we need to look into another useful property of the Calendar control, the SelectionMode. For selecting all the days of the week, you can set its value to DayWeek.

For selecting all the days in a month, you can set its value to DayWeekMonth.

Run your application and you will see more selectors (arrows) in the calendar control. By clicking on them you will be able to select a whole week or month.

Some other very important properties are:

  • DayNameFormat , which allow us to change the number of letters the header day text contains
  • FirstDayOfWeek, which allow us to set the first day of the week to Monday if we want to

We have so many options to style the control by setting the values of properties like BorderColor,BordeWidth,BorderStyle,BackColor to the values we want. We can also set the values of various font properties. We can always use the smart tag(little arrow on the top right hand corner) to use one of the many predefined formatting styles for our calendar control.

Now that I have covered some of the basic stuff, I would like to mention

  • Calendar click events
  • Control Calendar cell’s rendering

6) Every time the user selects a date in you calendar control, you capture this selection by the SelectionChanged event.

Add a literal control to the default.aspx page. Name it SelectedDatesLiteral

Just double click on a day in the calendar control. In the event handling routine, type the following

foreach (DateTime selectedDate in Calendar1.SelectedDates)
{
SelectedDatesLiteral.Text = string.Format(“You selected: {0:d}<br/>{1}”, selectedDate, SelectedDatesLiteral.Text);
}

Here, I just loop through the selected dates and append their values to a literal control.Run your application and see for yourself.

7) If we want to add content in a day in the calendar, we must use  the DayRender event. This event is invoked once for every day in the calendar. The table cell and the date are passed to the event handler and can be used to render custom content or look up data in a database etc. We will pull event data from an xml file.Add an xml file to your project and call it events.xml. Place this file in the App_Data special folder. The contents of this file could be something like this

<?xml version=”1.0″ encoding=”utf-8″ ?>
<Events>
<Event Month=”1″ Day=”1″>Happy New Year.</Event>
<Event Month=”2″ Day=”29″>Happy leap day.</Event>
<Event Month=”12″ Day=”25″><![CDATA[Merry Christmas.]]></Event>
<Event Month=”12″ Day=”7″><![CDATA[Bob's Birthday!]]></Event>
<Event Month=”12″ Day=”28″><![CDATA[16th anniverary]]></Event>
</Events>

Add a XMLDataSource control in to your default.aspx page and configure it so it reads the contents of your xml file.

Then in the DayRender Event type the following

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
string xpath = string.Format(“//Event[@Month={0} and @Day={1}]/text()”, e.Day.Date.Month, e.Day.Date.Day);
XmlDocument doc = XmlDataSource1.GetXmlDocument();

StringBuilder content = new StringBuilder(e.Day.DayNumberText);
foreach (XmlNode node in doc.SelectNodes(xpath))
{
content.Append(“<br/>”);
content.Append(node.Value);
}

e.Cell.Text = content.ToString();
}

Make sure you have added these namespaces in the Default.aspx.cs file

using System.Xml;
using System.Text;

I am using an XPath to filter out only the nodes in our xml document that have content.

Then I am opening the xml document and then I am building a string with values that will be displayed in the calendar cell for the current day.

Then I loop through all the items that were returned back from the XML document and append those values together in order to create a string of all of events that happend in this specific day.

Run your application and see the content that is passed from the xml file to the specific dates, e.g Christmas day.

If you need the full code, just email me.

Hope it helps!!!

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Furl

Using the Process Component to launch applications from our .Net application December 3, 2008

Posted by fofo in .NET, VB 2005, VB 9.0, Visual Studio 2005, Visual Studio 2008.
Tags: , , ,
1 comment so far

In this post I will show with a simple example how to use the Process control to launch applications from a windows form application (vb version), with this control that was shipped with the .Net 2.0 version you can launch very easily all sort of applications.

Let’s get started then…

1) Launch Visual Studio 2008/2005-express editions will do

2) Create a windows form application. Choose VB as your development language.

3) Name your solution project with a name of your choice

4) Add 3 buttons on the form. Change the Text properties of the 3 button to “Launch Notepad”, “Launch Wordpad”, “Launch MS Paint”

5) Drag and Drop 3 Process controls from the ToolBox (Under  the Component tab) and name them “NotePadProcess”, “WordPadProcess”,”MSPaintProcess”

6) Add a reference to your project to the System.IO namespace from the Solutions explorer window, by right-clicking on your project name, then Properties, then Reference and select System.IO from the imported namespaces

7) Double Click on the button that is destined to launch Notepad. In the body of the routine type

mypath = System.Environment.GetFolderPath(Environment.SpecialFolder.System)
mypath = Path.Combine(mypath, “notepad.exe”)
NotepadProcess.StartInfo.FileName = mypath
NotepadProcess.Start()

the code is pretty straight forward.We get to the notepad.exe file by finding the path and then we start notepad

8) Run your application, click on the “Notepad” button and see notepad launching

9) Double click on the two other buttons on the form designer. In their respective event handling routines type

for the button the launches wordpad

Dim mypath As String
mypath = System.Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)
mypath = Path.Combine(mypath, “Windows NT\Accessories\wordpad.exe”)
WordPadProcess.StartInfo.FileName = mypath
WordPadProcess.Start()

for the button the launches paint

Dim mypath As String
mypath = System.Environment.GetFolderPath(Environment.SpecialFolder.System)
mypath = Path.Combine(mypath, “mspaint.exe”)
MSPaintProcess.StartInfo.FileName = mypath
MSPaintProcess.Start()

10) Run your application and then click on all the buttons

11) If you need to close all these applications programmatically you can add another 3 buttons on the form and (names:CloseNotepad,CloseWordpad,CloseMsPaint).Double click on the buttons and type respectively

NotepadProcess.Kill()
WordPadProcess.Kill()
MSPaintProcess.Kill()

12) Run your application. In order for this example to work, click once on the buttons to launch all 3 applications and then click on the “close” buttons to close the applications

13) If you try to close “Notepad” without first launching notepad you will receive an error.If you want to avoid that and close all the notepad instances you opened

instead of

NotepadProcess.Kill()

type in the body of the event handling routine

Try
Dim npProc() As Process
npProc = Process.GetProcesses
For Each proc As Process In npProc
If proc.ProcessName.Equals(“notepad”) Then
proc.Kill()
End If
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

14) Do the same for the remaing two event handling routines that close MsPaint,WordPad

15) Now if you want to capture the moment that notepad closes, for any reason you need to add this line of  code

NotepadProcess.EnableRaisingEvents = True

in the button click event that launches Notepad.

So the complete code for the button that launches Notepad is

Dim mypath As String
mypath = System.Environment.GetFolderPath(Environment.SpecialFolder.System)
mypath = Path.Combine(mypath, “notepad.exe”)
NotepadProcess.EnableRaisingEvents = True
NotepadProcess.StartInfo.FileName = mypath
NotepadProcess.Start()

16)  Find the NotepadProcess (if you called it like that) process and choose the event Exited from the code window. The complete code is this

Private Sub NotepadProcess_Exited(ByVal sender As Object, ByVal e As System.EventArgs) Handles NotepadProcess.Exited
MessageBox.Show(“Notepad Exited”)
End Sub

17) Run your application. Launch Notepad. If you close Notepad by either clicking on the respective button on your form or just close Notepad from the close button, the code within this event will run

That is all folks!!!!

If you need the source code email me or leave a message.

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Writing from a windows form to microsoft word 2007 using VSTO November 29, 2008

Posted by fofo in general .net, MS Office, VB 2005, VB 9.0, Visual Studio 2005, Visual Studio 2008.
Tags: , , ,
5 comments

First of all I want to thank all these people who read my posts and thank them for their encouraging comments.

In the feedack I receive I get some “complaints” that my posts are targeted towards the asp.net side of development. Well you are right. I am more knowledgeable in Asp.Net. But I promise to write more about windows forms in the future, starting from this post. And to all VB guys out there, i will try (starting from this post) to write more samples in VB, which is here to stay…

In this post I would like how easy it is to use Visual Studio Tools for Office. If you have never heard before of VSTO just google it. In a few words it is a component of Visual Studio(since Visual Studio 2005) that provides a robust, .NET-based environment for building business applications using classic Office programs like Word and Excel.  So that means you do not have to learn the specific Office object models, and of course you do not need VBA anymore.

Let’s show VSTO with a simple example. We will have a simple table(1 row and 3 cells) in a word 2007 (.docx) document and fill in the values of these 3 cells from a windows form.

1) Start Visual Studio 2008/2005 project.

2) From the “New Project” window  choose a Office 2007 and from the templates Word 2007 Document. Select VB as the development language.Give a name to your project and Press OK

3) In the next window select “Create a new Document” and give name to your new word document, e.g “mydoc”.

4) Click “OK” to any window that asks you for access to the Office programs

5) If you have done everything right up to this point, you will be ablw to see in your visual studio window a blank word document,

6) Add a table with a single row and 3 cells from the ribbon

7) Add a new item in your project, a windows form and call it “wordform”

8) Add 3 Label controls on the form. Name them, Cell1,Cell2,Cell3.

9) Add 3 textbox controls on the form. Leave the default names

10) Add a button on the form. Leave the default name.

11) In the mydoc.vb(this is a file in my example-if you named your word, inputword, it will be inputword.vb) choose the Document.Open event. This is the empty routine.

Private Sub ThisDocument_Open() Handles Me.Open
End Sub

12) Inside this routine we need to show the form we created in the previous steps. So in the body of the routine, type

Dim myform As New wordform()
myform.Show()

13) Now we need to create a procedure (and place it in the same class file) to get the data from the form textboxes and place it in the respective cells. Type this code. It is really simple

Public Sub writeintocells(ByVal cellinput As String, ByVal flag As Integer)
Try
If flag = 1 Then
Globals.ThisDocument.Tables(1).Rows(1).Cells(1).Range.Text = cellinput
ElseIf flag = 2 Then
Globals.ThisDocument.Tables(1).Rows(1).Cells(2).Range.Text = cellinput
Else
Globals.ThisDocument.Tables(1).Rows(1).Cells(3).Range.Text = cellinput
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

14) Go to your form. Double Click on the button.In the body event handling routine type

If String.IsNullOrEmpty(TextBox1.Text) Then
MessageBox.Show(“enter a value”)
TextBox1.Focus()
Else
Globals.ThisDocument.writeintocells(Me.TextBox1.Text, 1)
End If
If String.IsNullOrEmpty(TextBox2.Text) Then
MessageBox.Show(“enter a value”)
TextBox2.Focus()
Else
Globals.ThisDocument.writeintocells(Me.TextBox2.Text, 2)
End If
If String.IsNullOrEmpty(TextBox3.Text) Then
MessageBox.Show(“enter a value”)
TextBox3.Focus()
Else
Globals.ThisDocument.writeintocells(Me.TextBox3.Text, 3)
End If

In this routine we access our document and access the procedure that we created in our document. We pass the values from the textboxes to the procedure and the procedure writes these values in the cells in the word document

15)Add another button on your form. Leave the default name. Double Click the button and in the body of the event handling routine type

Globals.ThisDocument.Save()
Globals.ThisDocument.Close()

In this routine we just save and close the document.

16) Build and run your project. Type 3 values in the textboxes in your form and bress Button1.

See the values inserted in the cells. Click Button2 to save and close the document.

Hopefully everything makes sense…

If you need the source code just email me or leave a comment!!!

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Working with DAL (data access layer), BLL(Business Logic Layer) in asp.net web applications November 26, 2008

Posted by fofo in asp.net 2.0, C#, Sql Server, Sql Server 2005, SQL Server 2008, Visual Studio 2005, Visual Studio 2008.
Tags: , , , , , , , ,
15 comments

In this post I would like to show you step by step how to create a DAL and BLL for an ASP.NET web application.

Well, DAL stands for Data Access Layer and BLL, stands for Business Logic Layer.

We will use strongly Typed DataSets to create the DAL and class files to implement the BLL, which enforces the business rules of our application.

Many developers get puzzled when they come across these terms. I will try to explain these concepts to the best of my ability and I will show how easy is to implement these sort of layers with the tools we have in our disposal. I will also try to explain why we need to implement these layers when we develop a n-tier project that accesses a database.

The most common thing in web/windows development is to store data in a database. We write code to save the data in the database and write code to manipulate the data e.g to insert, update,delete data in the database.

Obviously for this example we will need a database. I will use the Pubs database. This is a well known database and many people are familiar with its schema.

In order to follow this example you need to download this database and attach it in your local instance of the SQL Server. You can download the Pubs database from this link.

If you need some help on how to install the database have a look here

You can download Visual Studio 2008 from here and SQL Server 2008 Express from this link.

It is for free!!! So I assume that by this point you have all the tools downloaded and installed. At this point you must have the Pubs database in the local instance of your SQL Server.

We will create the DAL first. But why we need a DAL? It is not a good idea-strategy (especially if we deal with a big-complex application) to have the data-specific logic put into the presentation layer.So it is wrong to write the ADO.NET code in the .aspx pages of our application. All the data related code should be in the DAL. From the presentation layer we should only make calls to the DAL for all data requests.

Let’s get started then…

1) Fire up Visual studio 2008/2005

2) Create a new ASP.Net web application using C# as the development language

3) Name your project as you wish

4) Go to the Server Explorer in Visual Studio, right-click on the Data Connections node, and choose Add Connection. This will bring up the Add Connection dialog box, where you can specify the server to connect to, the authentication information, and the database name.Have a look at the picture below.

addconnection

Click the OK button. After configuring the database,  the database will be added as a node underneath the Data Connections node. You can expand the node to explore its tables, views, stored procedures of the database.

5) We must add a Typed DataSet to our project. To do this, right-click on the project node in the Solution Explorer and choose Add a New Item. Select the DataSet option from the list of templates and name it Pubs.xsd.

See the  picture below.

add-dataset

Typed DataSets are a set of generated classes (generated by Visual Studio) that inherit directly from the DataSet family of classes.The members of these classes are strongly-typed according to the database schema.

A Typed DataSet is composed of strongly-typed DataTable instances which represents any of the underlying database tables. We need to create a DataTable for the Authors table. Besides having our table properties as objects inside the DataTable object we need to use the TableAdapter class so we can have the necessary methods to access the data from the table.

6) Navigate to the Pubs.xsd, drag and drop a TableAdapter class. The configuration wizard fires up.

See the picture below

wizard-1

7) Save the connection string to the web.config as suggested.

8) Click Next. Have a look at the picture below

wizard-21

In this step we define the query(using the first option-ad hod sql queries) that returns the columns from the table Authors that we want reflected in our DataTable. At the end of the wizard we’ll give a method name to this query.We will use this method to populate the strongly-typed DataSet.

9) Click Next and then from the Query Builder select the Authors table and click Add. We use the Query Builder to graphically construct the query. You must select all the fields from the Authors table. Have a look at the picture below.

wizard-32

10) Click Next. Have a look at the picture below

wizard-4

Rename the Return a DataTable section from GetData to GetAuthors.

We will use this method from our presentation layer to create and fill the DataTable and return it.

11) Click Next and then Finish. The wizard closed. If we go to the DataSet Designer we can see

  • The DataTable we just created, Pubs.authorsDataTable
  • The PubsTableAdapters.AuthorsTableAdapter and the methods (Fill() and GetAuthors())

See the picture below

dataset-designer

12) Switch to the Default.aspx and in the Page_Load event type the following lines of code.

PubsTableAdapters.authorsTableAdapter myadapter = new PubsTableAdapters.authorsTableAdapter();
Pubs.authorsDataTable myauthors;
myauthors = myadapter.GetAuthors();
foreach(Pubs.authorsRow authorrow in myauthors)
Response.Write(“Author: ” + authorrow.au_fname + ”  ” + authorrow.au_lname+  “<br />”);

13) As you can see in the first line we create an instance of our authorsTableAdapter.

Run your application and you will see all the authors.

14) Now we can bind the objects (data) contained in the DataTable to a Gridview web server control.Add a new page by adding a new item in your project.Name it GridviewDataTable.aspx.Set this page as Start Page.

15) Drag and Drop a Gridview control on the page. Leave the default name.

In the Page_Load event of this page type the following code

PubsTableAdapters.authorsTableAdapter myadapter = new PubsTableAdapters.authorsTableAdapter();
GridView1.DataSource = myadapter.GetAuthors();
GridView1.DataBind();

Run your application and you will see the results returned by the Authors table through the DataTable object in the GridView.

16) We need to select a specific row from the table Authors. In order to achieve that we need to create a new method that takes an argument. To create such a method, switch to the DataSet Designer and add a new query. Have a look at the picture below.

addquery

17) Click Next (Leave the first option selected). Click Next again, (Leave the first option selected)

18) Click Next in the wizard and add the following SQL statement

SELECT        au_id, au_lname, au_fname, phone, address, city, state, zip, contract
FROM            authors
where au_id=@au_id

Have a look at the picture below

sql

19) Click Next. In the Return a DataTable, change the name to GetAuthorByID and then click Finish.

20) In the DataSet Designer you will see the new method we just created.

21) Right-Click on this new method (GetAuthorByID) and select Preview Data. In the Preview Data windows type this “172-32-1176″ in the Value fields in the Parameters section. Click Preview.

22) Add a new page to your project. Call it GetAuthorsbyid.aspx.Set it as the Start Page

23) Run your application. In the web page you should see the following result

172-32-1176 White Johnson 408 496-7223 10932 Bigge Rd. Menlo Park CA 94025

24) Obviously we want to insert,update,delete rows in the table. We can do that by using the Insert(), Update(), and Delete() methods of our TableAdapter class that are already created for us.

Have a look at the image below

dataset-methods

25) To insert a new row in the Authors table, we switch to the GridviewDataTable.aspx (make it as a Start Page) and place a button on the page. Change the text property of the button to “Insert” (There is already a gridview in this page). Double click on the button and in the event handler routine type,

PubsTableAdapters.authorsTableAdapter myadapter = new PubsTableAdapters.authorsTableAdapter();
myadapter.Insert(“122-33-5667″, “Austen”, “Jane”, “33216321737”, “12 london street”, “London”, “SO”, “99029”, false);
GridView1.DataSource = myadapter.GetAuthors();
GridView1.DataBind();

Run your application and see the new row is inserted in the gridview and thus in the underlying table

26) Let’s try to update the record we just inserted. Just add a new button on the page. Change the text property of the button to “Update”. Double click on the button and in the event handler routine type,

PubsTableAdapters.authorsTableAdapter myadapter = new PubsTableAdapters.authorsTableAdapter();
myadapter.Update(“122-33-5667″, “Austen”, “Jane”, “33216321737”, “22 london street”, “London”, “SO”, “99029”, false, “122-33-5667″);
GridView1.DataSource = myadapter.GetAuthors();
GridView1.DataBind();

Run your application and see the row updated in the gridview and thus in the underlying table

27) Finally we will try to delete the row we inserted and updated in the previous steps.Just add a new button on the page. Change the text property of the button to “Delete”. Double click on the button and in the event handler routine type,

PubsTableAdapters.authorsTableAdapter myadapter = new PubsTableAdapters.authorsTableAdapter();myadapter.Delete(“122-33-5667″);
GridView1.DataSource = myadapter.GetAuthors();
GridView1.DataBind();

Run your application and see the row is deleted in the gridview and thus in the underlying table.

28) Now we will try to create a new functionality that does a mass update and not just updating a row like the previous example. We will implement the following scenario, for every author that lives in California (state=”CA” ) his contract will be valid (contract=true). Just add a new button on the page. Change the text property of the button to “Update multiple”. Double click on the button and in the event handler routine type,

PubsTableAdapters.authorsTableAdapter myadapter = new PubsTableAdapters.authorsTableAdapter();
Pubs.authorsDataTable myauthors;
myauthors = myadapter.GetAuthors();
foreach (Pubs.authorsRow author in myauthors)
if (author.state == “CA”)
author.contract = true;
myadapter.Update(myauthors);
GridView1.DataSource = myadapter.GetAuthors();
GridView1.DataBind();

29) Now I would like to move on and talk a bit about the BLL. We have covered enough on how to seperate the data access logic from the presentation logic.If we want to have certain business rules that define who is given the authority to do ( e.g delete,update authors) or that for certain states special discounts should be applied, a Business Logic Layer (BLL) that serves as an intermediary for data exchange between the presentation layer and the DAL must be implemented. I will implement the BLL as a  class file because we have one TableAdapter in the DAL. Inside this class we will have methods that map to the data access methods in the DAL.

30 ) Simply right-click in the Solution Explorer and then Add a New Item, and choose the Class template. Name the class BLLAuthors.cs. The first method we will create, is simply a wrapper method for the method GetAuthors() in the DAL and we will call it GetBLLAuthors(). We will create a second method which we will call GetBLLAuthorsByID. This method is still a wrapper method for the GetAuthorsByID in the DAL. In this first example I want to show you how to access the typed datasets of the DAL through BLL. We will see later, methods in the BLL that enforce business rules(which is the point of having a BLL). The code inside the BLLAuthors.cs is as following

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DAL_BLL.PubsTableAdapters;
[System.ComponentModel.DataObject]
public class BLLAuthors
{
private authorsTableAdapter myAdapter = null;
protected authorsTableAdapter Adapter
{
get {
if (myAdapter == null) myAdapter = new authorsTableAdapter();
return myAdapter;
}
}
[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
public DAL_BLL.Pubs.authorsDataTable GetBLLAuthors()
{
return Adapter.GetAuthors();
}
[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
public DAL_BLL.Pubs.authorsDataTable GetBLLAuthorsByID(string authorid)
{
return Adapter.GetAuthorByID(authorid);
}
}

31) Create a new web page and name it GridviewBLL.aspx. Set this page as the Start Page.

Add a Gridview control on the page. In the Page_Load event of this page type,

BLLAuthors authorsall = new BLLAuthors();
GridView1.DataSource = authorsall.GetBLLAuthors();
GridView1.DataBind();

As you can see in the first line we create an instance of our BLLAuthors class which we defined in our BLLAuthors.cs file. It is evident from the code above that from the presentation layer (.aspx page) we access the BLL and then the BLL accesses the DAL, which eventually  “talks” to the database.

32) Let’s see a little example of our second wrapper method in our BLL. Add a button control to the page.Change the text property of the to “SelectSingleAuthor”. Double click the button. In the event handling routine type,

BLLAuthors singleauthor = new BLLAuthors();
GridView1.DataSource = singleauthor.GetBLLAuthorsByID(“172-32-1176″);
GridView1.DataBind();

Run your application. In the web page you should see the following result

172-32-1176 White Johnson 408 496-7223 10932 Bigge Rd. Menlo Park CA 94025

33) Let’s create a third method that applies this business rule (we used the same example in the DAL section),if  the state of the author is California “CA” then the contract should be true.

The code you should put in the BLLAuthors.cs is this

public bool UpdateAuthor()
{
DAL_BLL.Pubs.authorsDataTable authors = Adapter.GetAuthors();
if (authors.Count == 0)
return false;
foreach (DAL_BLL.Pubs.authorsRow authorrow in authors)
if (authorrow.state == “CA”)
authorrow.contract = true;
// Update the author record
int rowsAffected = Adapter.Update(authors);
return rowsAffected == 1;
}

Add a button control to the page.Change the text property of the to “UpDateState”. Double click the button. In the event handling routine type,

BLLAuthors upauthor = new BLLAuthors();
upauthor.UpdateAuthor();
GridView1.DataSource=upauthor.GetBLLAuthors();
GridView1.DataBind();

Run your application. In the web page you should see all records with state=”CA” to have the contract=”True

You could insert the code above in a Try-Catch Statement….

try
{
BLLAuthors upauthor = new BLLAuthors();upauthor.UpdateAuthor();
GridView1.DataSource = upauthor.GetBLLAuthors();
GridView1.DataBind();
}
catch (ArgumentException te)
{
Response.Write(“problem: ” + te.Message);
}

Hope it helps and happy coding!!!

If you need the source code feel free to email me. You can find my email in this page

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Follow

Get every new post delivered to your Inbox.

Join 1,793 other followers