Anda di halaman 1dari 39

EX. NO: 3 DATE: 08.08.

12

C# Client with C#.Net Server using OLEDB and .Net Remoting

AIM
The aim of the program is to implement Banking System using C# Client with C#.Net Server using OLEDB and .Net remoting.

SOFTWARE REQUIREMENT
C# (as programming language) Visual Studio 2008(Development environment) SQL Server 2005 Express edition (Database) Oracle 10g (Database) Windows7 32 bit or 64 bit (Operating System)

TECHNOLOGY DESCRIPTION Microsoft .NET Framework 3.5: The Microsoft .NET Framework 3.5 is a software technology that is available with several Microsoft Windows operating systems. It is a programming infrastructure created by Microsoft for building, deploying, and running applications and services that use .NET technologies, such as desktop applications and Web services. It includes a large library of pre-coded solutions to common programming problems and a virtual machine that manages the execution of programs written specifically for the framework. The .NET Framework is a key Microsoft offering and is intended to be used by most new applications created for the Windows platform.

Figure 1:The .NET Platform


54

The pre-coded solutions that form the framework's Base Class Library cover a large range of programming needs in a number of areas, including user interface, data access, database connectivity, cryptography, web application development, numeric algorithms, and network communications. The class library is used by programmers, who combine it with their own code to produce applications. Programs written for the .NET Framework execute in a software environment that manages the program's runtime requirements. Also part of the .NET Framework, this runtime environment is known as the Common Language Runtime (CLR). The CLR provides the appearance of an application virtual machine so that programmers need not consider the capabilities of the specific CPU that will execute the program. The CLR also provides other important services such as security, memory management, and exception handling. The class library and the CLR together compose the .NET Framework. LINQ (Language Integrated Query) is a new added feature in .net framework 3.5. It adds native data querying capability to C# and VB.NET along with the compiler and Intellisense support. LINQ is a component of .NET 3.5. LINQ defines operators that allow you to code your query in a consistent manner over databases, objects and XML. The ASP.NET LinqDataSource control allows you to use LINQ to filter, order and group data before binding to the List controls.

Figure 1: C# .Net Architecture

55

C# programs run on the .NET Framework, an integral component of Windows that includes a virtual execution system called the common language runtime (CLR) and a unified set of class libraries. The CLR is the commercial implementation by Microsoft of the common language infrastructure (CLI), an international standard that is the basis for creating execution and development environments in which languages and libraries work together seamlessly. Source code written in C# is compiled into an intermediate language (IL) that conforms to the CLI specification. The IL code and resources, such as bitmaps and strings, are stored on disk in an executable file called an assembly, typically with an extension of .exe or .dll. An assembly contains a manifest that provides information about the assembly's types, version, culture, and security requirements. When the C# program is executed, the assembly is loaded into the CLR, which might take various actions based on the information in the manifest. Then, if the security requirements are met, the CLR performs just in time (JIT) compilation to convert the IL code to native machine instructions. The CLR also provides other services related to automatic garbage collection, exception handling, and resource management. Code that is executed by the CLR is sometimes referred to as "managed code," in contrast to "unmanaged code" which is compiled into native machine language that targets a specific system. C#.Net Features: C# is the programming language that most directly reflects the underlying Common Language Infrastructure (CLI). Most of C#'s intrinsic types correspond to value-types implemented by the CLI framework. However, the C# language specification does not state the code generation requirements of the compiler: that is, it does not state that a C# compiler must target a Common Language Runtime (CLR), or generate Common Intermediate Language (CIL), or generate any other specific format. Theoretically, a C# compiler could generate machine code like traditional compilers of C++ or FORTRAN; in practice, all existing C# implementations target CIL. C# is a simple, modern, object-oriented, and type-safe programming language. C# has its roots in the C family of languages and will be immediately familiar to C, C++, and Java programmers. C# is an object-oriented language, but C# further includes support for component-oriented programming. Contemporary software design increasingly relies on software components in the form of self-contained and self-describing packages of functionality. Key to such components is that they present a programming model with properties, methods, and events; they have attributes that provide declarative information about the component; and they incorporate their own documentation. C# provides language constructs to directly support these concepts, making C# a very natural language in which to create and use software components. Several C# features aid in the construction of robust and durable applications: Garbage collection automatically reclaims memory occupied by unused objects; exception
56

handling provides a structured and extensible approach to error detection and recovery; and the type-safe design of the language makes it impossible to read from uninitialized variables, to index arrays beyond their bounds, or to perform unchecked type casts. C# has a unified type system. All C# types, including primitive types such as int and double, inherit from a single root object type. Thus, all types share a set of common operations, and values of any type can be stored, transported, and operated upon in a consistent manner. Furthermore, C# supports both user-defined reference types and value types, allowing dynamic allocation of objects as well as in-line storage of lightweight structures. To ensure that C# programs and libraries can evolve over time in a compatible manner, much emphasis has been placed on versioning in C#s design. Many programming languages pay little attention to this issue, and, as a result, programs written in those languages break more often than necessary when newer versions of dependent libraries are introduced. Aspects of C#s design that were directly influenced by versioning considerations include the separate virtual and override modifiers, the rules for method overload resolution, and support for explicit interface member declarations. C# is a type-safe, object-oriented language that is simple yet powerful, allowing programmers to build a breadth of applications. Combined with the .NET Framework, Visual C# enables the creation of Windows applications, Web services, database tools, components, controls, and more.

.NET REMOTING ARCHITECTURE: All .NET remoting applications have three common components regardless of their complexity: a Remotable object , a server application that hosts the remotable object and handles incoming service requests, and a client application that utilizes the services of the remotely-hosted object. .NET remoting enables objects in different application domains to talk to each other. The real strength of remoting is in enabling the communication between objects when their application domains are separated across the network. Remoting takes an indirect approach to application domain communication by creating proxy objects as shown in Figure 2. Both application domains communicate with each other by following these steps:

57

Figure 2 .Net Remoting Architecture 1. When a client object requests an instance of the server object, the remoting system at the client side instead creates a proxy of the server object. The proxy object lives at the client but behaves just like the remote object; this leaves the client with the impression that the server object is in the clients process. 2. When the client object calls a method on the server object, the proxy passes the call information to the remoting system on the client. This remoting system in turn sends the call over the channel to the remoting system on the server. 3. The remoting system on the server receives the call information and, on the basis of it, invokes the method on the actual object on the server (creating the object if necessary). 4. The remoting system on the server collects the result of the method invocation and passes it through the channel to the remoting system on the client. 5. The remoting system at the client receives the servers response and returns the results to the client object through the proxy. key components and terminology of .NET remoting: Object Marshaling: The process of packaging and sending method calls among objects, across application boundaries, via serialization and deserialization, is known as marshaling. Remotable objects are the objects that can be marshaled across the application domains. In contrast, all other objects are known as nonremotable objects. There are two types of remotable objects :
58

1. Marshal-by-value Objects: These objects are copied and passed out of the server application domain to the client application domain. MBV objects reside on the server. When a client invokes a method on the MBV object, the MBV object is serialized, transferred over the network, and restored on the client as an exact copy of the server-side object. Now, the MBV object is locally available and therefore any method calls to the object do not require any proxy object or marshaling. The MBV objects can provide faster performance by reducing the network roundtrips, but in the case of large objects, the time taken to transfer the serialized object from server to the client can be very significant. Furthermore, the MBV objects do not provide the privilege of running the remote object in the server environment. 2. Marshal-by-reference Objects: A proxy is used to access these objects on the client side. The clients hold just a reference to these objects. The MBR objects are remote objects. They always reside on the server and all methods invoked on these objects are executed at the server side. The client communicates with the MBR object on the server by using a local proxy object that holds the reference to the MBR object. Although the use of MBR objects increases the number of network roundtrips, they are a likely choice when the objects are prohibitively large or when the functionality of the object is available only in the server environment on which it is created. Channels: Channels are the objects that transport messages across remoting boundaries such as application domains, processes, and computers. When a client calls a method on the remote objects, the details of the method callsuch as parameters and so onare transported to the remote object through a channel. Any results returned from the remote object are communicated back to the client again through the same channel. The .NET remoting framework ensures that before a remote object can be called, it has registered at least one channel with the remoting system on the server. Similarly, the client object should specify a channel before it can communicate with a remote object. If the remote object offers more than one channel, the client can connect by using the channel that best suits its requirements. A channel has two end points. The channel object at the receiving end of a channel (the server) listens to a particular protocol through the specified port number, whereas the channel object at the sending end of the channel (the client) sends information to the receiving end by using the protocol and port number specified by the channel object on the receiving end.

59

The .NET Framework provides implementation for TCP ( Transmission Control Protocol). If you want to use a different protocol, you can define your own channel by implementing the IChannelReceiver and IChannelSender interfaces. 1.TCP Channels The TCP channel uses TCP for establishing communication between the two ends. The TCP channel is implemented through various classes of the System.Runtime.Remoting.Channels.Tcp namespace. The classes available in this namespace include: TcpServerChannel - An implementation for a server channel that uses the TCP to receive messages. TcpClientChanel - An implementation for a client channel that uses the TCP to send messages. TcpChannel - An implementation of a combined channel that provides the functionality for both and TcpServerChannel and TcpClientChannel classes. Formatters: Formatters are the objects that are used to encode and serialize data into messages before they are transmitted over a channel. At the other end of the channel, when the messages are received, formatters decode and deserialize the messages. To participate in the .NET remoting framework, the formatter classes must implement the IFormatter interface. The .NET Framework packages two formatter classes for common scenarios: the BinaryFormatter class and the SoapFormatter class. The SOAP Formatter: SOAP (Simple Object Access Protocol) is a simple, XML-based protocol for exchanging types and messages between applications. SOAP is an extensible and modular protocol; it is not bound to a particular transport mechanism such as HTTP or TCP. The SOAP formatter is implemented in the SoapFormatter class of the System.Runtime.Serialization.Formatters.Soap namespace. SOAP formatting is an ideal way of communicating between applications that use non-compatible architectures. However, SOAP is very verbose. SOAP messages require more bytes to represent the data as compared to the binary format. The Binary Formatter: Unlike SOAP, the binary format used by the .NET Framework is proprietary and can be understood only within .NET applications. However, as compared to SOAP, the binary format of representing messages is very compact and efficient.

60

The binary formatter is implemented in the BinaryFormatter class of the System.Runtime.Serialization.Formatters.Binary namespace. Remote Object Activation: Based on the activation mode, MBR objects are classified in the following two categories: Server-activated objects Client-activated objects Server-Activated Objects: Server-activated objects (SAOs) are those remote objects whose lifetime is directly controlled by the server. When a client requests an instance of a server-activated object, a proxy to the remote object is created in the clients application domain. The remote object is only instantiated (or activated) on the server when the client calls a method on the proxy object. The server-activated objects provide limited flexibility because only their default (parameter-less) constructors can be used to instantiate them. There are two possible activation modes for a server-activated object: o SingleCall activation mode o Singleton activation mode SingleCall activation mode: In the SingleCall activation mode, an object is instantiated for the sole purpose of responding to just one client request. After the request is fulfilled, the .NET remoting framework deletes the object and reclaims its memory. Objects activated in the SingleCall mode are also known as stateless because the objects are created and destroyed with each client request and therefore do not maintain state across the requests. This behavior of the SingleCall mode accounts for greater server scalability as an object consumes server resources for only a small period, therefore allowing the server to allocate resources to other objects. Scenarios that are often well suited for the SingleCall activation mode are those applications where the object is required by the client to do a small amount of work and then the object is no longer required. Some common examples include retrieving the inventory level for an item, displaying tracking information for a shipment, and so on. Singleton Activation Mode: In the Singleton activation mode, there is at most one instance of the remote object, regardless of the number of clients accessing it. A Singleton mode object can maintain state information across the method calls. Therefore, they are also sometimes known as stateful objects. The state maintained by the Singleton mode
61

server-activated object is globally shared by all its clients. A Singleton object does not exist on the server forever. Singleton activation mode is useful in scenarios such as in a chat server where multiple clients talk to the same remote object and share data between one another. Client-Activated Objects: Client-activated objects (CAOs) are those remote objects whose lifetime is directly controlled by the client. This is in direct contrast with SAOs, where the server, not the client, has complete control over objects lifetimes. Client-activated objects are instantiated on the server as soon as the client requests the object to be created. Unlike SAOs, CAOs do not delay object creation until the first method is called on the object. .Net Remoting using configuration files: There are two ways to configure remote objects. One is by code, and the other is by using a configuration file, both on the server and the client. The advantage of using a configuration file is we dont have to compile the code every time we change the configuration, so we can change the configuration of the application at any time without disturbing the code or executables. By convention, the configuration file name has the format executablename.config. Configuration files A typical configuration file includes the following, among other, information:

Host application information Name of the objects URI of the objects Channels being registered (multiple channels can be registered at the same time) Lease time information for the server objects

Server remoting configuration (Listener.config):


<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.runtime.remoting> <application> <service> <wellknown mode="Singleton" type="ServerApp.ServerClass, ServerApp" objectUri="ServerClass"> </wellknown> </service> <channels>

62

<channel ref="tcp" port="1234" /> </channels> </application> </system.runtime.remoting> </configuration

>

Client remoting configuration (client.config)


<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.runtime.remoting> <application name="ClientApp"> <client> <wellknown mode="Singleton" type="ServerApp.ServerClass, ServerApp" url="tcp://localhost:1234/ServerClass"> </wellknown> </client> <channels> <channel ref="tcp" /> </channels> </application> </system.runtime.remoting> </configuration>

To use these configuration files in our Remoting test application, place those files (Listener.config and client.config) in the directory that contains the server.exe and client.exe programs. Using application configuration files greatly simplifies the code required to set up a remoting application. The single line shown here takes the place of all the configuration code in the Listener.cs program's Main method:
RemotingConfiguration.Configure("server.config");

ARCHITECTURE
Client C# Winform
TCP/IP

Database Server C#.NET OLEDB Database Oracle


63

OLEDB

SQL Server

DATABASE INTEROPERABILITY: Database Interoperability is a property referring to the ability of an application to access various databases (inter-operate). The databases may be in MS Access, SQL database, oracle databases, etc. The application can access databases of different types. In particular, for a single query to be executed the application can access tables from two or more databases. OLE DB: OLE DB (Object Linking and Embedding, Database, is an API designed by Microsoft for accessing data from a variety of sources in a uniform manner. It is a set of interfaces implemented using the Component Object Model (COM); it is otherwise unrelated to OLE. It was designed as a higher-level replacement for, and successor to, ODBC, extending its feature set to support a wider variety of non-relational databases, such as object databases and spreadsheets that do not necessarily implement SQL. OLE DB separates the data store from the application that needs access to it through a set of abstractions that include the data source, session, command and row sets. This was done because different applications need access to different types and sources of data and do not necessarily want to know how to access functionality with technology-specific methods. OLE DB is conceptually divided into consumers and providers.

64

The consumers are the applications that need access to the data, and the provider is the software component that implements the interface and therefore provides the data to the consumer. OLE DB is part of the Microsoft Data Access Components (MDAC) stack.The consumers are the applications that need access to the data, and the provider is the software component that implements the interface and therefore provides the data to the consumer. OLE DB is part of the Microsoft Data Access Components (MDAC) stack. MDAC is a group of Microsoft technologies that interact together as a framework that allows programmers a uniform and comprehensive way of developing applications for accessing almost any data store. OLE DB providers can be created to access such simple data stores as a text file and spreadsheet, through to such complex databases as Oracle, SQL Server and Sybase ASE. It can also provide access to hierarchical data stores such as email systems. SAMPLE CODE: //ole db connection string for oracle String str = "Provider=MSDAORA;Data Source=RANGA;UserID= SYSTEM; Password=ranga;"; //ole db connection string for ms sql server String str1 = "Provider=SQLOLEDB;Data Source=RANGA\\SQLEXPRESS;Initial Catalog=master; UserID=sa; Password=ranga;"; OleDbConnection comm = new OleDbConnection(str); OleDbCommand cmd = new OleDbCommand("INSERT INTO student VALUES(" + regNo + ",'" + name + "','" + dept + "'," + cgpa + "," + phNo + ",'" + addr + "','" + arrear + "')", comm); cmd.ExecuteNonQuery(); comm = new OleDbConnection(str1); OleDbCommand cmd1 = new OleDbCommand("INSERT INTO student VALUES(" + regNo + ",'" + name + "','" + dept + "'," + cgpa + "," + phNo + ",'" + addr + "','" + arrear + "')", comm); Cmd1.ExecuteNonQuery(); comm.Close();

65

CODING:
SERVER SIDE: ServerClass.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Data.OleDb; using System.Data; using System.Data.Odbc; using System.Net.Mail; using System.Net.Security; using System.Net.Mime; namespace ServerApp { public class ServerClass : MarshalByRefObject { string stud = "Provider=MSDAORA;Data Source=RANGA;User Id=system;Password=ranga;"; String sqlol = "Provider=SQLOLEDB;Data Source=RANGA\\sqlexpress;Persist Security Info=True;User ID=sa;Password=ranga;Initial Catalog=master"; String custid = null; String custname = null; String custbalance = null; public string Insert(String accname,String phno,String addr,String eid) { string lsRet = null; String ls = null; try { OleDbConnection conn = new OleDbConnection(stud); int b = 10000; conn.Open(); OleDbCommand cmd = new OleDbCommand("Insert into Account (accholder, balance,password,phonenumber,address,email)values('" + accname + "'," + b + ",'" + accname + "','"+phno+"','"+addr+"','"+eid+"')", conn); cmd.ExecuteReader(); DataSet ds = new DataSet(); OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from account", conn); adapter.Fill(ds); DataTable dt = ds.Tables[0]; foreach (DataRow dr in dt.Rows) { ls = dr["accid"].ToString(); } lsRet= "Account Holder Name : "+ accname + " "+"Account ID : "+ls; conn.Close(); conn.Dispose(); } catch (Exception ex) { Console.Write(ex.Message); Console.Write(ex.StackTrace); } return lsRet }

66

public int[] addtocombo() { String ls=null; int[] l=new int[10]; int i = 0; try { OleDbConnection conn = new OleDbConnection(stud); conn.Open(); DataSet ds = new DataSet(); OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from account", conn); adapter.Fill(ds); DataTable dt = ds.Tables[0]; foreach (DataRow dr in dt.Rows) { ls = dr["accid"].ToString(); l[i] = Convert.ToInt32(ls); i++; } conn.Close(); conn.Dispose(); } catch (Exception ex) { Console.Write(ex.Message); Console.Write(ex.StackTrace); } return l; } public string delete(int id) { String de=null; String dls = null; int dl = 0; try { OleDbConnection conn = new OleDbConnection(stud); conn.Open(); DataSet ds = new DataSet(); OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from account", conn); adapter.Fill(ds); DataTable dt = ds.Tables[0]; foreach (DataRow dr in dt.Rows) { dls = dr["accid"].ToString(); dl = Convert.ToInt32(dls); if (dl==id) { OleDbCommand cmd = new OleDbCommand("Delete from Account where accid="+id, conn); cmd.ExecuteReader(); de = "Account deleted :"+ id; } } conn.Close(); conn.Dispose(); }

67

catch (Exception ex) { Console.Write(ex.Message); Console.Write(ex.StackTrace); } return de; } public String withDraw(int wid,int amt) { String wmsg = null; String wls = null; String bal1 = null; int wl = 0,bal; int minbal = 1000; int flag = 0; try { OleDbConnection conn = new OleDbConnection(stud); conn.Open(); OleDbConnection sq = new OleDbConnection(sqlol); sq.Open(); DataSet ds = new DataSet(); OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from account", conn); adapter.Fill(ds); DataTable dt = ds.Tables[0]; foreach (DataRow dr in dt.Rows) { wls = dr["accid"].ToString(); wl = Convert.ToInt32(wls); if (wl==wid) { flag = 1; bal1 = dr["balance"].ToString(); ; bal = Convert.ToInt32(bal1); if (minbal < (bal - amt)) { bal = bal - amt; OleDbCommand cmd = new OleDbCommand("Update account set balance=" + n bal + "where accid=" + wl, conn); cmd.ExecuteReader(); wmsg = " withdraw done!!!"; custbalance = bal.ToString(); OleDbCommand scmd = new OleDbCommand("insert into TransactionDetails values(" + wid + ",'withdraw'," + amt + ",'" + DateTime.Now + "')", sq); scmd.ExecuteReader(); } else wmsg = "Minimum balance exceeded!!! you have only "+bal; break; } if ( flag==0) { wmsg = "incorrect account id"; } } conn.Close(); conn.Dispose();

68

catch (Exception ex) { Console.Write(ex.Message); Console.Write(ex.StackTrace); } return wmsg; } public String deposit(int depid, int depamt) { String depmsg = null; String depls = null; String depbal1 = null; int fla = 0; int depl = 0, depbal; try { OleDbConnection conn = new OleDbConnection(stud); OleDbConnection sq = new OleDbConnection(sqlol); conn.Open(); sq.Open(); DataSet ds = new DataSet(); OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from account", conn); adapter.Fill(ds); DataTable dt = ds.Tables[0]; foreach (DataRow dr in dt.Rows) { depls = dr["accid"].ToString(); depl = Convert.ToInt32(depls); if (depl == depid) { fla = 1; depbal1 = dr["balance"].ToString(); depbal = Convert.ToInt32(depbal1); depbal = depbal +depamt; OleDbCommand cmd = new OleDbCommand("Update account set balance=" + depbal + "where accid=" + depl, conn); cmd.ExecuteReader(); depmsg = " deposit done!!! your current balance="+depbal; custbalance = depbal.ToString(); ; try { OleDbCommand scmd = new OleDbCommand("insert into TransactionDetails values(" + depid + ",'deposit'," + depamt + ",'" + DateTime.Today.ToShortDateString() + "','" + DateTime.Now.ToString("HH:mm:ss tt") + "')", sq); scmd.ExecuteReader(); } catch (Exception ex) { Console.Write(ex.Message); depmsg = ex.Message.ToString(); } MailMessage m = new MailMessage("rsabankpondy@gmail.com", dr["email"].ToString()); m.Subject = "Transaction information"; String mailmsg = " <p>Dear customer, </p>" + "\r\n" + "<p>you have deposited Rs " + depamt + " in your account.</p>" + "\r\n" +

69

" <p>your current balance is Rs " + depbal + " <p> Have a nice day !!!</p>"; m.Attachments.Add(new Attachment(@"F:\IV year\CT lab\logo \logo1.png")); m.IsBodyHtml = true; SmtpClient smtp = new SmtpClient("smtp.gmail.com"); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.EnableSsl = true; smtp.Host = "smtp.gmail.com"; smtp.Port = 25; LinkedResource logo = new LinkedResource(@"F:\IV year\CT lab\logo\logo1.png", "image/png"); logo.ContentId = "companylogo"; AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:companylogo/><br></body></html>" + mailmsg, null, MediaTypeNames.Text.Html); av1.LinkedResources.Add(logo); m.AlternateViews.Add(av1); System.Net.NetworkCredential authinfo = new System.Net.NetworkCredential("rsabankpondy@gmail.com", "anandhi080392"); smtp.UseDefaultCredentials = false; smtp.Credentials = authinfo; try { smtp.Send(m); depmsg = "mail sent"; } catch (Exception ex) { Console.WriteLine(ex); if (ex.InnerException != null) { Console.WriteLine("InnerException is: {0}", ex.InnerException); String InnerExcep = ex.InnerException.ToString(); depmsg = InnerExcep; } } } } if(fla == 0) { depmsg = "incorrect account id"; } conn.Close(); conn.Dispose(); } catch (Exception ex) { Console.Write(ex.Message); Console.Write(ex.StackTrace); } return depmsg; }

70

public String login(string na, String pas) { String logmsg = null; int f = 0; try { if (na == "Admin") { if (pas == "password") { logmsg = "Welcome Admin!!"; } else if (na == "") { logmsg = "Enter password!!"; } else logmsg = "Invalid password!!"; } else { OleDbConnection conn = new OleDbConnection(stud); conn.Open(); DataSet ds = new DataSet(); OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from account", conn); adapter.Fill(ds); DataTable dt = ds.Tables[0]; //DataRow dr = dt.Rows[1]; foreach (DataRow dr in dt.Rows) { if (na == dr["accid"].ToString()) { f = 1; custname = dr["accholder"].ToString(); custbalance = dr["balance"].ToString(); if (pas == dr["password"].ToString()) { logmsg = "Welcome " + na; custid = na; } else logmsg = "Invalid password!!"; break; } } if (f == 0) { logmsg = "NOT A VALID ACCOUNT ID!!"; } } } catch (Exception ex) { Console.Write(ex.Message);

71

Console.Write(ex.StackTrace); } return logmsg; } public String update(int uid,String name,string phone,string addr) { String umsg = null; String uls = null; int ul = 0; int flag = 0; Int64 pn = 0; pn = Convert.ToInt64(phone); try { OleDbConnection conn = new OleDbConnection(stud); conn.Open(); DataSet ds = new DataSet(); OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from account", conn); adapter.Fill(ds); DataTable dt = ds.Tables[0]; //DataRow dr = dt.Rows[1]; foreach (DataRow dr in dt.Rows) { uls = dr["accid"].ToString(); ul = Convert.ToInt32(uls); if (ul == uid) { flag = 1; OleDbCommand cmd = new OleDbCommand("Update account set accholder='"+name+"',address='"+addr+"',phonenumber ="+pn+" where accid=" + uid, conn); cmd.ExecuteReader(); umsg = "update done!!!"; break; } } if (flag == 0) { umsg = "incorrect account id"; } conn.Close(); conn.Dispose(); } catch (Exception ex) { Console.Write(ex.Message); Console.Write(ex.StackTrace); } return umsg; } public DataTable view() { DataTable dt = new DataTable(); try { OleDbConnection sq = new OleDbConnection(sqlol); sq.Open(); DataSet ds = new DataSet(); OleDbDataAdapter adapter =

72

new OleDbDataAdapter("Select * from TransactionDetails", sq); adapter.Fill(ds); dt = ds.Tables[0]; } catch (Exception ex) { Console.Write(ex.Message); Console.Write(ex.StackTrace); } return dt ; } public String setext(int a) { if (a == 1) return custid; else if (a == 3) return custbalance; else return custname; } } }

CLIENT SIDE : Bank.cs


using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.Runtime.Remoting; System.Reflection;

namespace ClientApp { public partial class bank : Form { public bank() { InitializeComponent(); } private void bank_Load(object sender, EventArgs e) { RemotingConfiguration.Configure( Assembly.GetExecutingAssembly().GetName().Name + ".exe.config", false); } private void btnadmin_Click(object sender, EventArgs e) { adlogin ad = new adlogin();

73

ad.Show(); } private void btnadmin_mouseMove(object sender, EventArgs e) { adlogin ad = new adlogin(); ad.Show(); } private void btnacchold_Click(object sender, EventArgs e) { aclogin ac = new aclogin(); ac.Show(); } private void openToolStripMenuItem_Click(object sender, EventArgs e) { Open op = new Open(); op.Show(); } private void closeToolStripMenuItem_Click(object sender, EventArgs e) { Close cl = new Close(); cl.Show(); } } }

AdminLogin.cs
using using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; ServerApp; System.Runtime.Remoting; System.Reflection;

namespace ClientApp { public partial class adlogin : Form { ServerClass serv; string result; public adlogin() { InitializeComponent(); } public void btnlog_Click(object sender, EventArgs e) {

74

result = serv.login(txtadid.Text, txtadpass.Text); if(result.Equals("Welcome Admin!!")) { MessageBox.Show("Server returned: '" + result + "'.", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Hide(); MainForm m = new MainForm(); m.Show(); this.Close(); } else if(result.Equals("Enter password!!")) { MessageBox.Show("Server returned: '" + result + "'.", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Server returned: '" + result + "'.", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Information); } }

private void adlogin_Load(object sender, EventArgs e) { txtadid.Text = "Admin"; serv = new ServerClass(); } } }

MainForm.cs
using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.Runtime.Remoting; System.Reflection;

namespace ClientApp { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } public void btnOp_Click(object sender, EventArgs e) { Open o1 = new Open();

75

o1.Show(); } private void btnClose_Click(object sender, EventArgs e) { Close c1 = new Close(); c1.Show(); } private void button1_Click(object sender, EventArgs e) { modify m = new modify(); m.Show(); } private void button2_Click(object sender, EventArgs e) { transaction t = new transaction(); t.Show(); } } }

Open.cs
using using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; ServerApp; System.Runtime.Remoting; System.Reflection;

namespace ClientApp { public partial class Open : Form { ServerClass serv; string result; public Open() { InitializeComponent(); } private void Open_Load(object sender, EventArgs e) { try { serv = new ServerClass(); } catch (Exception ex) { MessageBox.Show("Unable to connect to remote object.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Console.WriteLine("Message " + ex.Message);

76

Console.WriteLine(ex.StackTrace); } } private void btnAdd_Click(object sender, EventArgs e) { try { result = serv.Insert(txtName.Text,txtpn.Text,txtadd.Text,txteid.Text); MessageBox.Show("Server returned: '" + result + "'.", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show("Error Occured: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Console.WriteLine(ex.ToString()); } } } }

Close.cs
using using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; ServerApp; System.Runtime.Remoting; System.Reflection;

namespace ClientApp { public partial class Close : Form { ServerClass servcl; string result; int[] res=new int[15]; public Close() { InitializeComponent(); } private void Close_Load(object sender, EventArgs e) { { try

77

{ servcl = new ServerClass(); res = servcl.addtocombo(); int n = res.Length; for (int i = 0; i < n; i++) { if(res[i] !=0) comId.Items.Add(res[i]); } } catch (Exception ex) { MessageBox.Show("Unable to connect to remote object.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Console.WriteLine("Message " + ex.Message); Console.WriteLine(ex.StackTrace); } } } private void btncl_Click(object sender, EventArgs e) { String dres=null; int did=0; did = Convert.ToInt32(comId.Text); dres = servcl.delete(did); MessageBox.Show("Server returned: '" + dres + "'.", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } }

Modify.cs
using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; ServerApp;

namespace ClientApp { public partial class modify : Form { ServerClass servmd; string result; int[] res = new int[15]; public modify() { InitializeComponent(); }

78

private void btnmod_Click(object sender, EventArgs e) { String mres = null; int did = 0; long pn = 0; did = Convert.ToInt32(comId.Text); mres = servmd.update(did, txtName.Text, txtpn.Text, txtadd.Text); MessageBox.Show("Server returned: '" + mres + "'.", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } private void modify_Load(object sender, EventArgs e) { servmd = new ServerClass(); res = servmd.addtocombo(); int n = res.Length; for (int i = 0; i < n; i++) { if (res[i] != 0) comId.Items.Add(res[i]); } } } }

TransactionDetails.cs
using using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; ServerApp; System.Runtime.Remoting; System.Reflection;

namespace ClientApp { public partial class transaction : Form { ServerClass ser; public transaction() { InitializeComponent(); } private void transaction_Load(object sender, EventArgs e) { ser = new ServerClass(); DataTable d = new DataTable(); d = ser.view(); DataRow dr = d.Rows[1]; dataGridView1.DataSource = d;

79

} } }

AccountLogin.cs
using using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; ServerApp; System.Runtime.Remoting; System.Reflection;

namespace ClientApp { public partial class aclogin : Form { ServerClass server; string result; ServerClass servcl; int[] res = new int[15]; public aclogin() { InitializeComponent(); } private void btnlog_Click(object sender, EventArgs e) { server = new ServerClass(); result = server.login(comboBox1.Text, txtadpass.Text); if (result.StartsWith("Welcome")) { this.Hide(); cust c = new cust(); c.Show(); this.Close(); } else { MessageBox.Show("Server returned: '" + result + "'.", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void aclogin_Load(object sender, EventArgs e) { servcl = new ServerClass(); res = servcl.addtocombo(); int n = res.Length; for (int i = 0; i < n; i++) { if (res[i] != 0)

80

comboBox1.Items.Add(res[i]); } } } }

Cust.cs
using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; ServerApp;

namespace ClientApp { public partial class cust : Form { ServerClass serve,ser; public cust() { InitializeComponent(); } private void btnwith_Click(object sender, EventArgs e) { Withdraw w1 = new Withdraw(); w1.Show(); } private void btndepo_Click(object sender, EventArgs e) { Deposit d1 = new Deposit(); d1.Show(); } private void cust_Load(object sender, EventArgs e) { serve=new ServerClass(); label1.Text = "Welcome "+" "+serve.setext(2)+"!!!"; } private void btnch_Click(object sender, EventArgs e) { String bal; ser = new ServerClass(); bal = ser.setext(3); MessageBox.Show("Your Account Balance:" + bal, "BALANCE", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }

81

Withdraw.cs
using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; ServerApp;

namespace ClientApp { public partial class Withdraw : Form { ServerClass ser; string result; String res = null; int wid = 0; int amt = 0; public Withdraw() { InitializeComponent(); } private void Withdraw_Load(object sender, EventArgs e) { try { ser = new ServerClass(); txtwid.Text = ser.setext(1); txtwid.ReadOnly = true; } catch (Exception ex) { MessageBox.Show("Unable to connect to remote object.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Console.WriteLine("Message " + ex.Message); Console.WriteLine(ex.StackTrace); } } private void btnwithdraw_Click(object sender, EventArgs e) { wid = Convert.ToInt32(txtwid.Text); amt = Convert.ToInt32(txtwamt.Text); res = ser.withDraw(wid, amt); MessageBox.Show(res); } } }

82

Deposit.cs
using using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; ServerApp; System.Runtime.Remoting; System.Reflection;

namespace ClientApp { public partial class Deposit : Form { ServerClass ser,serv; string result=null; int depid = 0; int depamt = 0; public Deposit() { InitializeComponent(); } private void btndepos_Click(object sender, EventArgs e) { progressBar1.PerformStep(); ser = new ServerClass(); progressBar1.PerformStep(); depid = Convert.ToInt32(txtdid.Text); depamt = Convert.ToInt32(txtdamt.Text); progressBar1.PerformStep(); result = ser.deposit(depid, depamt); MessageBox.Show(result); } private void Deposit_Load(object sender, EventArgs e) { serv = new ServerClass(); txtdid.Text = serv.setext(1); txtdid.ReadOnly = true; progressBar1.Minimum = 1; progressBar1.Maximum = 100; progressBar1.Step = 35; } } }

83

PROCEDURE FOR DEVELOPING THE APPLICATION: For creating the C#.net application one should create a Class Library (Server), Listener and Client. Procedure for creating the Class Library: 1. Create a new class library project in visual studio 2008 Start Visual Studio 2008 File New Project Visual C# Class Library

2. Give a name for your Class Library(namely ServerApp) 3. Note that the class should inherit MarshalByRefObject, which it must do in order to be remotely instantiated.

4. Add your Business methods in this Class 5. Build the class Library

84

Procedure for creating the Listener: Next we will create the Listener component. In Visual Studio, within the same Remoting solution in which we created the Class Library project, create another new project. This one will be a Windows Forms Application 1. Create a new Windows Forms Application in visual studio 2008 Start Visual Studio 2008 File New Project Visual C# Windows Forms Application

2. Give a name for your Listener(namely Listener) 3. Next we need to add configuration file to specify the remoting details Right-click on the Listener project Click Add Click New Item Choose Application Configure File from the dialog box 4. Add the contents of Listener.config file given earlier 5.Add the following header files to Form1.cs file
using System.Runtime.Remoting; using System.Reflection;

6. In the form_load() method call the Listener.config file using


RemotingConfiguration.Configure(Assembly.GetExecutingAssembly().GetName().Na me + ".exe.config", false);

Procedure for creating the Client: Now we will create application. 1. Create a new Windows Forms Application in visual studio 2008 Start Visual Studio 2008 File New Project Visual C# Windows Forms Application 2. Give a name for your Client Project(namely Client App) 3. Next we have add a reference to the ServerApp application. Right-click the newly created ClientApp project click Add Reference, and in the Add Reference dialog box, click the Browse tab and Browse to ~\ServerApp.dll

85

4. Add configuration file as specified in the procedure for Listener and add the contents of Client.config given above 5. Add the following header files
using System.Runtime.Remoting; using System.Reflection; using System.ServerApp; 6. Add the following class level variables:

ServerClass server; string result; 7. In the form_load() method call the Client.config file using

RemotingConfiguration.Configure(Assembly.GetExecutingAssembly().GetName(
).Name +".exe.config", false); server = new ServerClass(); 8. Call the business mehods using the server object server.Insert(txtData.Text) SCREEN SHOTS MAIN

86

ADMIN LOGIN

87

OPEN ACCOUNT

DELETE ACCOUNT

88

UPDATE

TRANSACTION DETAILS

89

ACCOUNT HOLDER LOGIN

WITHDRAW

90

DEPOSIT

CHECK BALANCE

91

LISTENER

RESULT: Thus the C# .Net Application to create a banking system has been done using the required clients, server and class library

92

Anda mungkin juga menyukai