Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Microsoft ASP .NET Professional Projects - Premier Press

.pdf
Скачиваний:
147
Добавлен:
24.05.2014
Размер:
4.63 Mб
Скачать

vDisplay = Display + "000000000000000000000000000000000000000"

FieldsCount = 0

s = "Execute " + procedure + "" If mode = "update" then

For Each r in t.Rows

For Each c in t.Columns

IF vdisplay.chars(FieldsCount) = "0" or c.ToString = KeyField then Else

Dim tb As TextBox

tb = me.FindControl(c.ToString) column = c.ToString

Value = tb.text

If c.DataType.ToString = "System.String" Then s = s + " @" + column + "='" + value + "', "

Else

s = s + " @" + column + "=" + value + ", " End If

End IF

FieldsCount = FieldsCount + 1

Next c

Next r

s = s + "@" + KeyField + "=" + KeyValue

me.Controls.Add(new LiteralControl(s))

RunSql(s)

Else

For Each c in t.Columns

IF vdisplay.chars(FieldsCount) = "0" or c.ToString = KeyField then Else

Dim tb As TextBox

tb = me.FindControl(c.ToString)

column = c.ToString Value = tb.text

If c.DataType.ToString = "System.String" Then s = s + " @" + column + "='" + value + "', " Else

s = s + " @" + column + "=" + value + ", " End If

End IF

FieldsCount = FieldsCount + 1

Next c

s = s + "@" + KeyField + "=NULL"

me.Controls.Add(new LiteralControl(s))

RunSql(s)

End if

End Sub

Sub RunSql(vSql as string) try

Dim s As string

Dim myConnection As OleDbConnection myConnection = New OleDbConnection(ConnStr)

Dim mycommand As New OleDbCommand(vsql,myConnection) myconnection.Open()

myCommand.ExecuteNonQuery()

myconnection.Close()

Catch ex As OleDbException ' SQL error

Dim errItem As OleDbError

Dim errString As String

Dim s As string

For Each errItem In ex.Errors

errString += ex.Message + "<br/>" Next

s = "<br/><br/>SQL Error.Details follow:<br/>" & errString me.Controls.Add(new LiteralControl(s))

Catch myException as Exception

me.Controls.Add(new LiteralControl("Exception: " + myException.ToString())) End try

End Sub

End Class

End Namespace

Using the GenEditAdd Custom Control

I will now show you how to hook up the GenEditAdd control to a DataGrid and use it to add, edit, and delete records in the masters table. Th e code for this discussion can be found in the …GenEditAdd\GenEditAdd_final subfolder on the book's Web site at www.premierpressbooks.com/downloads.asp.

Each DataGrid that uses this control needs a "config" file. I have discussed the config_masters.aspx file earlier in this chapter and this is the config file used in this example. The DataGrid residing on the Web page "masters.aspx" requires two Hyperlink columns: one for the add mode and the other for the Edit mode. These Hyperlinks navigate to the config file and pass on a code_value of 0 in case of the add mode or a valid primary key in case of the edit mode as follows:

<property name="Columns">

<asp:HyperLinkColumn Text="Edit" DataNavigateUrlField="code_value"

DataNavigateUrlFormatString="config_masters.aspx?code_value={0}"/>

<asp:HyperLinkColumn Text="Add" DataNavigateUrlField="code_value"

DataNavigateUrlFormatString="config_masters.aspx?code_value=0"/>

</property>

The following is the complete code listing of Masters.aspx.

Masters.aspx

<%@ Import Namespace="System.Data" %>

<%@ Import Namespace="System.Data.OleDb" %>

<%@ Register TagPrefix="Hersh" Namespace="Generic_chap7" Assembly="GenEditAdd_Chap7" %>

<%@Page Language="VB" %>

<html>

<script language="VB" runat="server"> Dim myConnection As OleDbConnection Dim myCommand As OleDbDataAdapter Dim ds As New DataSet

Dim ConnStr As String

Dim SQL As String

Sub Page_Load(Source As Object, E As EventArgs)

ConnStr = "Provider=SQLOLEDB; Data Source=(local); Initial Catalog=ASPNET;User

ID=sa;"

myConnection = New OleDbConnection(ConnStr) if NOT (isPostBack)

rebind end if

End Sub

Sub ReBind()

'DataSetCommand

SQL = "select m.*, g.code_display as category "

SQL = SQL + "from masters m, groups g "

SQL = SQL + " where m.code_category = g.code_value" myCommand = New OleDbDataAdapter(SQL, myConnection) 'use Fill method of DataSetCommand to populate dataset myCommand.Fill(ds, "masters")

'Binding a Grid

Grid1.DataSource=ds.Tables("masters").DefaultView

Grid1.DataBind()

End Sub

Sub RunSql(sql as string) 'Catch Control Validator errors

if not page.isvalid then

response.write("Stored Procedure did not execute") rebind

exit sub end if

try

Dim mycommand2 As New OleDbCommand(sql,myConnection) myconnection.Open()

myCommand2.ExecuteNonQuery()

myconnection.Close() 'turn off editing Grid1.EditItemIndex = -1

Catch ex As OleDbException ' SQL error

Dim errItem As OleDbError

Dim errString As String

For Each errItem In ex.Errors errString += ex.Message + "<br/>"

Next

Response.write( "SQL Error.Details follow:<br/><br/>" & errString) Catch myException as Exception

Response.Write("Exception: " + myException.ToString()) End try

rebind End Sub

Sub Grid1_delete(sender As Object, e As DataGridCommandEventArgs)

Dim code_value As string = Grid1.DataKeys.Item(E.Item.ItemIndex).ToString Dim sql As string

sql = "Delete from masters where code_value = " + cstr(code_value) RunSql(sql)

End Sub

</script>

<head>

<title>Masters DataGrid 1</title> </head>

<body>

<br>

<form runat=server>

<b>Chart of Accounts:</b><br> <table width="95%">

<tr>

<td valign="top">

<asp:DataGrid id="Grid1" runat="server" AutoGenerateColumns="false" BackColor="White"

BorderWidth="1px" BorderStyle="Solid" BorderColor="Tan"

CellPadding="2" CellSpacing="0"

Font-Name="Verdana" Font-Size="8pt" OnDeleteCommand = "Grid1_delete" DataKeyField="code_value"> <Columns>

<asp:HyperLinkColumn Text="Edit" DataNavigateUrlField="code_value"

DataNavigateUrlFormatString="config_masters.aspx?code_value={0}"/>

<asp:HyperLinkColumn Text="Add" DataNavigateUrlField="code_value"

DataNavigateUrlFormatString="config_masters.aspx?code_value=0"/>

<asp:ButtonColumn Text="Delete" CommandName="Delete" HeaderText="Delete"/>

<asp:BoundColumn HeaderText="Account" DataField="code_display"> <HeaderStyle Width="150px"/>

</asp:BoundColumn>

<asp:BoundColumn HeaderText="Group" DataField="category">

<HeaderStyle Width="150px"/>

</asp:BoundColumn>

<asp:BoundColumn HeaderText="Type" DataField="type">

<HeaderStyle Width="150px"/>

</asp:BoundColumn>

<asp:BoundColumn HeaderText="Opening" DataField="opening">

<HeaderStyle Width="150px"/>

</asp:BoundColumn>

<asp:BoundColumn HeaderText="Closing" DataField="closing">

<HeaderStyle Width="150px"/>

</asp:BoundColumn>

</Columns>

<HeaderStyle BackColor="DarkRed" ForeColor="White" Font-Bold="true"/>

<ItemStyle ForeColor="DarkSlateBlue"/>

<AlternatingItemStyle BackColor="Beige"/>

</asp:DataGrid>

</td>

</tr>

</table>

</form>

</body>

</html>

Summary

The GenEditAdd component that we built in this chapter allows us to provide editing and insert functionality to a DataGrid. The DataGrid does not have a built-in Insert mode and the GenEditAdd custom control fills this void. This control also replaces the Edit mode of the DataGrid (which was not automatic and required us to code a number of events). In the process of building this control I explained the theory underlying building custom controls. In Project 3, we will enhance this control to provide additional functionality as DropDown lists, required fields, read-only fields, and descriptive captions for column names.

Chapter 8: Business Objects

Business Objects are a library of functions and classes that can be used in any project. Commonly used code is encapsulated in a Business Object. This object serves as a "service" class to another object. It is instantiated as required and destroyed after use. A Business Object does not have any user interface.

The Bin Directory

If you have developed COM objects in the past you must know of the pain involved in registering components. A component had to be registered using the regsvr32.exe utility. If the component was modified, the entire Web server had to be stopped in order to reregister the component. ASP.NET has simplified the process of registering components. The components are simply copied and pasted in the bin directory. No registry updates are required, and to unregister you simply delete the component file from the bin directory. The original components may be replaced even when the Web server is running. ASP.NET allows all existing requests to complete and directs new requests to the new component.

Namespaces and Assemblies

Developers can group the internal code components (classes and interfaces) in namespaces. Such a logical organization also prevents collisions with classes written by other developers. A namespace provides a shortcut for referring to long class names. The Imports directive (Visual Basic.NET) and the using directive (in C#) are shortcuts that allow one to use namespaces without providing a fully qualified path.

The metadata for an object records information required to use the object. Typically, this information includes the name of the object, names of all the fields of the object, and their types and details of all member functions including parameter types and names.

An assembly allows for packaging applications into one comprehensive unit. Code compiled by the .NET compiler is converted to an intermediate form, called "IL." An assembly will contain all the IL, the metadata, and other required files.

Each assembly has a manifest, which contains information pertaining to the identity of the assembly (that is, name and version information) and other files contained in the assembly.

A Simple Business Object in Visual Basic

I will now build a simple object, which has one property and one method. The user sets the property message, and the method called test returns it to the calling form. The source code for this example can be found in the ....\basic\vb subfolder on the book's Web site at www.premierpressbooks.com/downloads.asp.

1.Build the Component

2.Imports System

3.Imports System.Text

4.Imports Microsoft.VisualBasic

5.Namespace BasicObjVb

6.Public Class BasicVb

7.Private ls_message as string

8.Public Sub New()

9.MyBase.New()

10.ls_message = ""

11.End Sub

12.Public Property message as string

13.Get

14.Return ls_message

15.End Get

16.Set

17.ls_message = value

18.End Set

19.End Property

20.Public Function test() as string

21.Dim SB As StringBuilder

22.SB = New StringBuilder(ls_message)

23.SB = SB.Append("..returned from function test")

24.test = SB.ToString()

25.End Function

26.End Class

End Namespace

This class is called BasicVb and it resides in the namespace BasicObjVb. It has one property called message, which, as usual, has a Set method, a Get method, and a local variable called ls_message. In a property syntax, the Get method is used to return the value stored in the local variable back to the calling object whereas the calling object writes to this property using the Set method.

The object has a Constructor event. This is the Sub new(). The Constructor event is fired as soon as the object is created. I have initialized the local variable ls_message to a single space in this event. Finally, I have a function called Test that returns a string. I use the StringBuilder class to build the returned string. This class has various methods for string manipulation. Some of its methods are Append, Replace, Remove, and ToString. I assign the message property to the StringBuilder and then use its Append method to add another string to it.

27. Compile the Object

This is done by running the following DOS command:

vbc /t:library /out:g:\aspnetsamples\bin\BasicObjVb.dll BasicObj.vb 28. Build a Web Form

Finally, you build a web form to test out the component. Figure 8.1 shows what the output looks like:

Figure 8.1: Simple Business Object.

BasicObj.aspx

<%@ Import Namespace="BasicObjVb" %>

<html>

<script language="VB" runat="server">

Sub Page_Load(Sender As Object, E As EventArgs)

Dim s As string

Dim Comp As BasicVb

Comp = New BasicVb()

Comp.Message = "Hello World"

s = Comp.test()

response.write(s)

End Sub

</script>

</html>

In the web form, I import the BasicObjVb namespace with the import directive. I then declare a component of type BasicVb and assign Hello World to its message property. I call its test function, which returns the string that I store in a local variable called "s." Finally, I render this string to the browser using response.write.

A Simple Component in C#

I will now show you how to build the same object in C#. The source code for this example can be found in the ....\basic\c subfolder on the book's Web site at www.premierpressbooks.com/downloads.asp.

1. Build the Component

BasicObjC.cs

namespace BasicObjC { using System;

using System.Text; public class BasicC{

private String ls_message; public BasicC()

{

//constructor ls_message = null;

}

public string message

{

get

{

return ls_message;

}

set

{

ls_message = value;

}

}