11611_cap 406 home work 4

Upload: simran-chauhan

Post on 06-Apr-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 11611_CAP 406 Home Work 4

    1/12

    CAP 406 Home Work

    Homework Title / No. : HOMEWORK 3 _____ Course Code: _ CAP-406 _

    Course Instructor: _______ Course Tutor (if applicable): PROF.ROHIT OHRI _

    Date of Allotment: ___11/ 04/ 2011 ______ Date of submission: _ 18/04/2011 _

    Students Roll No.___ RTb011A02 _______ Section No. : _ TBO11 ____ Declaration:I declare that this assignment is my individual work. I have not copied from any other students work or from any other source except where due acknowledgment is madeexplicitly in the text, nor has any part been written for me by another person.

    Students Signature: Seema KumariEvaluators comments:

    _____________________________________________________________________ Marks obtained : ___________ out of ______________________

    Part A ( Attempt any three from Q1. to Q.4)Q1. WAP to read a file in Binary Mode.?

    using System;using System.IO;

    class MainClass{ public static void Main()

    {FileStream outStream = File.Create("c:\\BinaryTest.dat"

    );

    BinaryWriter bw = new BinaryWriter(outStream);

    bw.Write( ( int ) 3);bw.Write( (decimal) 4.5);string s = "Test String";bw.Write(s);

    bw.Flush();bw.Close();

  • 8/3/2019 11611_CAP 406 Home Work 4

    2/12

    FileStream inStream = File.OpenRead("c:\\BinaryTest.dat");

    BinaryReader br = new BinaryReader(inStream);

    int

    i = br.ReadInt32();decimal d = br.ReadDecimal();string s2 = br.ReadString();

    Console.WriteLine(i);Console.WriteLine(d);Console.WriteLine(s2);

    br.Close();}

    }

    Q2. WAP to Write a file in Text Mode?

    using System;using System.IO;

    class MainClass{ static void Main(string[] args) { StreamWriter MyStream = null ; string MyString = "Hello World" ;

    try { MyStream = File.CreateText( "MyFile.txt" ); MyStream.Write(MyString); } catch (IOException e) { Console.WriteLine(e); }

    catch (Exception e) { Console.WriteLine(e); } finally { if (MyStream != null ) MyStream.Close();

  • 8/3/2019 11611_CAP 406 Home Work 4

    3/12

    } }}

    Q3. what is ADO.Net ? WAP to Access/ Read a Databse using ADO.NetTechnology

    Ans:-

    ADO.NET is the new database technology of the .NET (Dot Net) platform, and it builds on Microsoft ActiveX Data Objects (ADO).

    ADO is a language-neutral object model that is the keystone of Microsoft's UniversalData Access strategy.

    ADO.NET is an integral part of the .NET Compact Framework, providing access torelational data, XML documents, and application data. ADO.NET supports a varietyof development needs. You can create database-client applications and middle-tier

    business objects used by applications, tools, languages or Internet browsers.

    ADO.NET defines DataSet and DataTable objects which are optimized for moving disconnected sets of data across intranets and Internets, including throughfirewalls. It also includes the traditional Connection and Command objects, as wellas an object called a Data Read er that resembles a forward-only, read -only ADOrecordset . If you create a new application, your application requires some form of data access most of the time.

    ADO.NET provides data access services in the Microsoft .NET platform.

    You can use ADO.NET to access data by using the new .NET Framework data providers which are:

    Data Provider for SQL Server ( System.Data.SqlClient ). Data Provider for OLEDB ( System.Data.OleDb ). Data Provider for ODBC ( System.Data.Odbc ). Data Provider for Oracle ( System.Data.OracleClient ).

    ADO.NET is a set of classes that expose data access services to the .NET developer.The ADO.NET classes are found in System.Data.dll and are integrated with the XMLclasses in System.Xml.dll .

    There are two central components of ADO.NET classes: the DataSet , and the .NETFramework Data Provider .

    Data Provider is a set of components including:

  • 8/3/2019 11611_CAP 406 Home Work 4

    4/12

    the Connection object ( SqlConnection , OleDbConnection ,OdbcConnection , OracleConnection )

    the Command object ( SqlCommand , OleDbCommand , OdbcCommand ,OracleCommand )

    the DataReader object (SqlData Read er , OleDbData Read er ,

    OdbcData Read er , OracleData Read er ) and the DataAdapter object (SqlDataAdapter , OleDbDataAdapter ,

    OdbcDataAdapter , OracleDataAdapter ).

    DataSet object represents a disconnected cache of data which is made up of DataTable s and DataRelation s that represent the result of the command.

    using System;using System.Data;using System.Data.Common;using System.Data.OleDb;

    class MainClass{ static void Main(string[] args)

    {string connectionString = "Provider=Microsoft.JET.OLEDB

    .4.0;data source=C:\\Northwind.mdb";

    OleDbConnection conn = new OleDbConnection(connectionString);

  • 8/3/2019 11611_CAP 406 Home Work 4

    5/12

    string sql = "SELECT * FROM Orders";

    OleDbCommand cmd = new OleDbCommand(sql, conn);

    conn.Open();OleDbDataReader reader;reader = cmd.ExecuteReader();

    while (reader.Read()){

    Console.Write(reader.GetString(0).ToString() + " ," ;Console.Write(reader.GetString(1).ToString() + " ," ;Console.WriteLine("");

    }

    reader.Close();conn.Close();

    }}

    Q4. WAP to Update an Database using ADO.Net?

    using System;using System.Data;using System.Data.SqlClient;

    class PropagateChanges { static void Main(){

    string connString = "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";string qry = @"select * from employee ";string upd = @"update employee set firstname = @fi

    rstname where id = @id";

    SqlConnection conn = new SqlConnection(connString);

  • 8/3/2019 11611_CAP 406 Home Work 4

    6/12

    try {SqlDataAdapter da = new SqlDataAdapter();da.SelectCommand = new SqlCommand(qry, conn);

    DataSet ds = new DataSet();

    da.Fill(ds, "employee");DataTable dt = ds.Tables["employee"];

    dt.Rows[0]["firstname"] = "W";

    foreach (DataRow row in dt.Rows){Console.WriteLine(

    "{0} {1}",row["firstname"].ToString().PadRight(15),row["lastname"].ToString().PadLeft(25));

    }

    // Update employeesSqlCommand cmd = new SqlCommand(upd, conn);cmd.Parameters.Add("@firstname",SqlDbType.NVarC

    har,15, "firstname");SqlParameter parm = cmd.Parameters.Add("@id",Sq

    lDbType.Int,4,"id");parm.SourceVersion = DataRowVersion.Original;da.UpdateCommand = cmd;da.Update(ds, "employee");

    } catch (Exception e)

    {Console.WriteLine("Error: " + e);

    }finally

    {conn.Close();

    }}

    }

    Part- B (Attempt any three from Q5. to Q8.)

    Q5. Elaborate XML as part of C#.net?

  • 8/3/2019 11611_CAP 406 Home Work 4

    7/12

    for the Write button.

    private void wb_Click ( object sender, System.EventArgs e ){

    String constr = @Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\book.mdb;OleDbConnection con = new OleDbConnection ( constr );con.Open( );String comstr = SELECT Name, Email, Phone FROMaddressbook;OleDbCommand com = new OleDbCommand ( comstr, con );OleDbDataAdapter adapt = new OleDbDataAdapter ( com );adapt.Fill ( dset, addressbook );dg.SetDataBinding ( dset, addressbook );dset.WriteXml ( addressbook.xml );xmltext.Text = dset.GetXml( );con.Close( );

    }

    Interacting with a database using ADO.NET involves connection and command objects.Since we have used OLEDB to access the database, the connection must be established

    between the database and OLEDB .NET Provider. The class OleDbConnection is usedfor this job. So, in this method we have firstly created an object of this class passing to itthe connection string.

    The connection string contains the name of the OLEDB .NET Provider and that of thedatasource. Our datasource is book.mdb that maintains an address book. This file isalready created using Microsoft Access. It contains details like names, e-mail IDs and

    phone numbers.

    Only creating an object of connection class does not physically open a connection to thedatabase. Calling the Open( ) method does. So we have called the Open() method in thenext statement.

    The Command object allows us to execute an SQL statement or a stored procedure in adata source. We have created the command object using the OleDbCommand class andare passing to it the command string. The command string contains the SQL statement toselect all the records from thedatasource.

    The command object is used to connect the connection object to a DataAdapter object.A DataAdapter is used to fill data from the database into the DataSet object. To read therecords into the DataSet we have used the OleDbDataAdapter.Fill( ) method. To thismethod we have passed the DataSet object dset and the table name. Add the data member dset of type DataSet to the form class. Initialise the data set object in the constructor as

  • 8/3/2019 11611_CAP 406 Home Work 4

    8/12

  • 8/3/2019 11611_CAP 406 Home Work 4

    9/12

    [email protected]

    Click the Read button. The following handler would get called:

    private void rb_Click ( object sender,System.EventArgs e ){

    StreamWriter sw = new StreamWriter( addressbook.xml, false );sw.Write ( xmltext.Text );sw.Close( );dset.ReadXml ( addressbook.xml );dg.SetDataBinding ( dset, addressbook );

    }

    Here, we have used the StreamWriter class to write the contents from textbox to theXML file. To read new contents of the file and fill the DataSet with it we have used theReadXml( ) method. Again to fill the grid control we have called the SetDataBinding( )method. The result is shown in the following figure.

    Note that we must add the following declarations at the beginning of the program.

    using System.Data.OleDb;using System.IO;

  • 8/3/2019 11611_CAP 406 Home Work 4

    10/12

    Q6. WAP to represent Data using XML in C#.net?Q7. WAP to show the working of XML Reader Class in C#.net.

    Ans:-using System;using System.Collections.Generic;using System.ComponentModel;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Data;using System.Data.SqlClient;using System.Xml;using System.IO;using System.Diagnostics;

    public class MainClass{

    public static void Main(){

    SqlConnection cnn = new SqlConnection(@"data source=.\sqlexpress;initial catalog=northwind;integrated security=true");

    SqlCommand cmd = new SqlCommand();cmd.Connection = cnn;cmd.CommandType = CommandType.Text;cmd.CommandText = "select * from Employee FOR X

    ML AUTO";cnn.Open();XmlReader reader=cmd.ExecuteXmlReader();StreamWriter writer= File.CreateText(Applicatio

    n.StartupPath + @"\temp.xml");writer.Write("");

    while (reader.Read()){

    writer.Write(reader.ReadOuterXml());}writer.Write("");

    writer.Close();reader.Close();cnn.Close();Process.Start(Application.StartupPath + @"\temp

    .xml");}

    }

  • 8/3/2019 11611_CAP 406 Home Work 4

    11/12

    Q8. WAP to show the working of XML Writer Class in C#.net.

    using System;using System.IO;using System.Xml;

    using System.Xml.Schema;class MainClass{ static void Main(string[] args)

    {

    XmlTextWriter myXmlTextWriter = null ;

    myXmlTextWriter = new XmlTextWriter("books.xml", null );myXmlTextWriter.Formatting = Formatting.Indented;myXmlTextWriter.WriteStartDocument( false );myXmlTextWriter.WriteDocType("bookstore", null, "books.

    dtd", null );myXmlTextWriter.WriteComment("comment");myXmlTextWriter.WriteStartElement("bookstore");myXmlTextWriter.WriteStartElement("book", null );myXmlTextWriter.WriteAttributeString("genre", "autobiog

    raphy");myXmlTextWriter.WriteAttributeString("publicationdate",

    "1979");myXmlTextWriter.WriteAttributeString("ISBN", "0-9999-

    9999-9");myXmlTextWriter.WriteElementString("title", null, "Titl

    e");myXmlTextWriter.WriteStartElement("Author", null );myXmlTextWriter.WriteElementString("first-name", "first

    ");myXmlTextWriter.WriteElementString("last-name", "last");myXmlTextWriter.WriteEndElement();myXmlTextWriter.WriteElementString("price", "799.99");myXmlTextWriter.WriteEndElement();myXmlTextWriter.WriteEndElement();

    //Write the XML to file and close the writermyXmlTextWriter.Flush();myXmlTextWriter.Close();

    if (myXmlTextWriter != null )myXmlTextWriter.Close();

    }}

  • 8/3/2019 11611_CAP 406 Home Work 4

    12/12