Anda di halaman 1dari 18

AJAY KUMAR GARG ENGINEERING COLLEGE GHAZIABAD

DEPARTMENT OF MCA
Model Solution University Test
Course:
MCA
Semester:
V
Session:
2014-15
Section:
A+B
Subject:
.Net Framework & C#
Sub. Code:
MCA-512
Max Marks: 100
Time:
3HR
1.Attempt any four questions
(5x4=20)
1(a) Enumerate major services the CLR.
[5]
ANS: The primary role of the CLR is to locate, load, and manage .NET types on your behalf.
The CLR also takes care of a number of low-level details such as
memory management,
application hosting,
handling threads,
and performing various security checks.
The CLR provides a number of services that include:
Loading and execution of codes
Memory isolation for application
Verification of type safety
Compilation of IL into native executable code
Providing metadata
Automatic garbage collection
Enforcement of Security
Interoperability with other systems
Managing exceptions and errors
Provide support for debugging and profiling
1(b) Define inter-operability. How does Net framework achieve this feature?
[5]
ANS: Interoperability enables you to preserve and take advantage of existing investments in
unmanaged code. Code that runs under the control of the common language runtime (CLR) is called
managed code, and code that runs outside the CLR is called unmanaged code. COM, COM+, C++
components, ActiveX components, and Microsoft Win32 API are examples of unmanaged code.
Running unmanaged code inside managed code is called inter-operability.
The .NET Framework enables interoperability with unmanaged code through platform invoke
services, the System.Runtime.InteropServices namespace, C++ interoperability, and COM
interoperability (COM interop).
Managed code calling unmanaged DLL functions Let's say your application needs to
interface to a C-like DLL and the company that wrote the DLL isn't adopting .NET as quickly
as your company is. In this case, you still need to call into that DLL from a .NET application.

Managed code using COM components You might also need to continue supporting COM
components. You do this by creating a .NET wrapper for the COM component so that the
managed client thinks it's working with a .NET class.
Unmanaged code using .NET services You want to access .NET from unmanaged code. It's
solved using a reciprocal approach: a COM client is fooled into thinking it's using a COM
server, which is actually a .NET service of some sort.

1(c) Discuss CLR activities for program execution with flow chart diagram.
ANS:

[5]

CLR activities for program execution can listed in following ways:


1. The compilers of CLS-compliant languages compile the source code and generate an intermediate
code, called MSIL code, and metadata.
2. Before we execute the MSIL code, CLR need to compile it into CPU-specific instructions. To
execute the code, the runtime requires information about the code that is in the metadata. The metadata
describes the code and defines the types that the code contains as well as references to other types that
the code uses at run time. MSIL Code and metadata both located in the .PE (portable executable) file.
3. When CLR execute .PE file, the class loader loads the MSIL code and metadata from the portable
executable file into the run-time memory.
4. After the MSIL code and metadata are loaded into the memory, the code manager calls the entry
point method, which is Main, Win Main or DllMain method. An entry-point method is the first
method to be executed when you run your application.
5. The garbage collector performs periodic checks on the managed heap to identify the objects that
are no longer required by the program and removes them from memory.
6. The applications running within the common language runtime can utilize the
managed multithreading support.
7. The common language runtime also allows managed code to interoperate with unmanaged code.
One of the components of the common language runtime is the COM marshaler, which performs
marshaling of data when data passes between managed and unmanaged execution environments.
8. Then with the help of JIT the IL code is converted into Native code or we can say Intermediate set
of instructions are converted into CPU set of instruction.
1(d) Differentiate between managed code and unmanaged code.
[5]
ANS:
Managed Code
Managed code is code that is written to target the services of the managed runtime execution
environment (like Common Language Runtime in .NET Framework).

The managed code is always executed by a managed runtime execution environment rather
than the operating system directly. Managed refers to a method of exchanging information
between the program and the runtime environment.
Because the execution of code is governed by the runtime environment, the environment can
guarantee what the code is going to do and provide the necessary security checks before
executing any piece of code. Because of the same reason the managed code also gets different
services from the runtime environment like Garbage Collection, type checking, exception
handling, bounds checking, etc. This way managed code does not have to worry about memory
allocations, type safety, etc.
Applications written in Java, C#, VB.NET, etc target a runtime environment which manages
the execution and the code written using these types of languages is known as Managed Code.
Managed code is always compiled into an Intermediate Language (MSIL in case of .NET
Framework). The compiler used by .NET framework to compile managed code compiles it into
Intermediate Language and generates the necessary metadata, symbolic information that
describes all of the entry points and the constructs exposed in the Intermediate Language (e.g.,
methods, properties) and their characteristics.
The Common Language Infrastructure (CLI) Standard describes how the information is to be
encoded, and programming languages that target the runtime emit the correct encoding.
Managed code also provides platform independence. As the managed code is first compiled to
intermediate language, the CLRs JIT Compiler takes care of compiling this intermediate
language into the architecture specific instructions.
Unmanaged Code
Code that is directly executed by the Operating System is known as un-managed code.
Typically applications written in VB 6.0, C++, C, etc are all examples of unmanaged code.
Unmanaged code typically targets the processor architecture and is always dependent on the
computer architecture.
Unmanaged code is always compiled to target a specific architecture and will only run on the
intended platform. This means that if you want to run the same code on different architecture
then you will have to recompile the code using that particular architecture.
Unmanaged code is always compiled to the native code which is architecture specific. When
we compile unmanaged code it gets compiled into a binary X86 image. And this image always
depends on the platform on which the code was compiled and cannot be executed on the other
platforms that are different that the one on which the code was compiled.
Unmanaged code does not get any services from the managed execution environment.
In unmanaged code the memory allocation, type safety, security, etc needs to be taken care of
by the developer. This makes unmanaged code prone to memory leaks like buffer overruns and
pointer overrides and so forth.
Unmanaged executable files are basically a binary image, x86 code, loaded into memory. The
program counter gets put there and thats the last the Operating System knows. There are
protections in place around memory management and port I/O and so forth, but the system
doesnt actually know what the application is doing.
1(e) What is Just-In-time Compilation? How it is using in connection with Intermediate
Language?
[5]
Ans:

Just-In-time Compilation
The .Net languages , which is conforms to the Common Language Specification (CLS), uses its
corresponding runtime to run the application on different Operating Systems . During the code
execution time, the Managed Code compiled only when it is needed, that is it converts the
appropriate instructions to the native code for execution just before when each function is called.
This process is called Just In Time (JIT) compilation, also known as Dynamic Translation . With
the help of Just In Time Compiler (JIT) the Common Language Runtime (CLR) doing these tasks.
Before MSIL(MS Intermediate Language) can be executed, it must converted by .net Framework
Just in time (JIT) compiler to native code, which is CPU specific code that run on some computer
architecture as the JIT compiler. Rather than using time and memory to convert all the MSIL in
portable executable (PE) file to native code, it converts the MSIL as it is needed during execution
and stored in resulting native code so it is accessible for subsequent calls. The runtime supplies
another mode of compilation called install-time code generation. The install-time code generation
mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger
units of code at a time, storing the resulting native code for use when the assembly is subsequently
loaded and executed. As part of compiling MSIL to native code, code must pass a verification
process unless an administrator has established a security policy that allows code to bypass
verification. Verification examines MSIL and metadata to find out whether the code can be
determined to be type safe, which means that it is known to access only the memory locations it is
authorized to access.
2
Attempt any two questions
(10x2=20)
2(a) Create a base class called Shape. Use this class to store two double type values that could be
used to compute the area of figures Derive two specialized classes called Triangle and Rectangle
from the base Shape.
- Add to the base class, a method Set to initialize base class data members and
another method Area to compute and display the area of figures.
- It is mandatory to implement the method Area in Derived class.
Design a Program that will accept dimensions of a triangle or rectangle interactively and
display the area.
[10]
ANS:
class Shape{
double x;
double y;
public void Set()
{
Console.WriteLine(Enter the value of x);
x= Convert.ToDouble(Console.ReadLine());
Console.WriteLine(Enter the value of y);
y= Convert.ToDouble(Console.ReadLine());
}
public virtual double Area(){
return x*y;
}

}
class Triangle:Shape{
public override double Area()
{
return (.5*x*y);
}
}
class Rectangle:Shape{
public new double Area()
{
return (*x*y);
}
}
public class MainTest
{
public static void Main()
{
Shape tri=new Triangle();
Shape rect=new Rectangle();
tri.Set()
Console.WriteLine(tri.Area());
rect.Set()
Console.WriteLine(rect.Area());
}
}
2(b) Enumerate the steps involved in creating and using a delegate with an example.
ANS:
1. Declare a delegate.
delegate void Del(string str);
2. Declare a method with the same signature as the delegate.
static void Notify(string name)
{
Console.WriteLine("Notification received for: {0}", name);
}
3. Create an instance of the delegate.
Del del1 = new Del(Notify);
or
Del del2 = Notify;
or

[10]

Instantiate Del by using an anonymous method.


Del del3 = delegate(string name)
{ Console.WriteLine("Notification received for: {0}", name); };
or
Instantiate Del by using a lambda expression.
Del del4 = name => { Console.WriteLine("Notification received for: {0}", name); };
using System;
class Program
{
public delegate int AddDelegate(int num1, int num2);
static void Main(string[] args)
{
AddDelegate funct1= new AddDelegate(Add);
int k=funct1(7,2);
Console.WriteLine(" Sumation = {0}",k);
Console.Read();
}
public static int Add(int num1, int num2)
{
Console.WriteLine("I am called by Delegate");
int sumation;
sumation= num1+ num2;
return sumation;
}
}
2(c) Discuss compile time Polymorphism in C#. Write a program to overload = = operator
for the complex class.
[10]
ANS:
using System;
classt Complex
{
float real;
float imaginary;
public Complex(float real, float imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public float Real

{
get
{
return(real);
}
set
{
real = value;
}
}
public float Imaginary
{
get
{
return(imaginary);
}
set
{
imaginary = value;
}
}
public override string ToString()
{
return(String.Format("({0}, {1}i)", real, imaginary));
}
public static bool operator==(Complex c1, Complex c2)
{
if ((c1.real == c2.real) && (c1.imaginary == c2.imaginary))
return(true);
else
return(false);
}
public static bool operator!=(Complex c1, Complex c2)
{
return(!(c1 == c2));
}
public override bool Equals(object o2)
{
Complex c2 = (Complex) o2;
return(this == c2);

}
}
class MainClass
{
public static void Main()
{
Complex c1 = new Complex(3, 1);
Complex c2 = new Complex(1, 2);
Console.WriteLine("c1 == c2: {0}", c1 == c2);
Console.WriteLine("c1 != c2: {0}", c1 != c2);
}
}
3.Attempt any two questions:
(10X2=20)
3(a) What are the types of stream in C# ? Write a program in Cit to copy the data from one file
to another.
[10]
ANS:Stream is an object which is used to transfer the data. we have file streaming,memory streaming
etc. Stream is an abstract class.
There is a generic stream class,System.IO.Stream, from which all streams are derived. Reader
writer streams such as StreamReader and StreamWriter are not streams by their meaner, they
are not derived from System.IO.Stream, they are designed to help to write and read data from
and to stream.
Streams in CLR come in three forms:
Binary or Byte streams that read and write bytes,
Character or Text streams that read and write characters,
Binary Streams or Byte streams
Binary streams, as their name suggests, work with binary (raw) data. You probably
guess that that makes them universal and they can be used to read information from all sorts of
files (images, music and multimedia files, text files etc.). We will take a brief look over them,
because we will currently focus on working with text files.
The main classes that we use to read and write from and to binary streams are:
FileStream, BinaryReader and BinaryWriter.
The class FileStream provides us with various methods for reading and writing from a
binary file (read / write one byte and a sequence of bytes), skipping a number of bytes,
checking the number of bytes available and, of course, a method for closing the stream. We can
get an object of that class by calling him his constructor with parameter-a file name.

The class BinaryWriter enables you to write primitive types and binary values in a
specific encoding to a stream. It has one main method Write(), which allows recording of
any primitive data types integers, characters, Booleans, arrays, strings and more.
BinaryReader allows you to read primitive data types and binary values recorded using
a BinaryWriter. Its main methods allow us to read a character, an array of characters, integers,
floating point, etc. Like the previous two classes, we can get on object of that class by calling
its constructor.
Character orText Streams
Text streams are very similar to binary, but only work with text data or rather a
sequence of characters (char) and strings (string). Text streams are ideal for working with text
files. On the other hand, this makes them unusable when working with any binaries.
The main classes for working with text streams in .NET are TextReader and TextWriter.
They are abstract classes, and they cannot be instantiated. These classes define the basic
functionality for reading and writing for the classes that inherit them. Their more important
methods are:
- ReadLine() reads one line of text and returns a string.
- ReadToEnd() reads the entire stream to its end and returns a string.
- Write() writes a string to the stream.
- WriteLine() writes one line of text into the stream.
As you know, the characters in .NET are Unicode characters, but streams can also work
with Unicode and other. The classes StreamReader and StreamWriter directly inherit the
TextReader and TextWriter classes and implement functionality for reading and writing textual
information to and from a file.
To create an object of type StreamReader or StreamWriter, we need a file or a string,
containing the file path. Reading and writing to the console is much like reading and writing
respectively with StreamReader and StreamWriter.
3(b) What is multi-threading ? Write a program for creating and starting a thread. [10]
ANS:
Multithreading: A thread is defined as the execution path of a program. Each thread defines a
unique flow of control. If your application involves complicated and time consuming
operations then it is often helpful to set different execution paths or threads, with each thread
performing a particular job. So working with multiple threads at a time is called
multithreading.
using System;
using System.Threading;
class Thread1
{
public static void Show()

{
Console.WriteLine("Child thread starts");
int sl = 5000;
Console.WriteLine("Child Thread Paused for {0} seconds", sleep for / 1000);
Thread.Sleep(sl);
Console.WriteLine("Child thread continues");
}
static void Main(string[] args)
{
ThreadStart f = new ThreadStart(Show);
Console.WriteLine("Creating the thread");
Thread t1 = new Thread(f); //Creating a thread
t1.Start();
//Starting Thread
Console.ReadKey();
}
}

3(c) Write a program that will read a name from the keyboard and display it on screen.
The program should throw an exception when the length of the name is more than 15
characters. Design your own exception mechanism.
[10]
using System;
public class MyException : Exception
{
public MyException() : base() { }
public MyException(string message) : base(message) { }
public MyException(string message, Exception e) : base(message, e) { }
private string eInfo;
public string eInfo
{
get
{
return eInfo;
}
set
{
eInfo = value;
}
}

public class TestMyException


{
public static void Main()
{
String s=Console.ReadLine();
try
{
if(s.Lenghth>15){
MyException m;
m = new MyException("My Exception Occured");
m.Info = "length is greater than 15";
throw m;
}
else
Console.WriteLine(s);
}
catch (MyException e)
{
Console.WriteLine(String.Concat(e.StackTrace, e.Message));
Console.WriteLine(e.eInfo);
}
Console.ReadLine();
}
}
}
4
Attempt any two questions:
(10x2=20)
4(a) Explain the following parts of ASP.Net web application.
[10]
(i) Web Forms or .aspx pages
(ii) Code-behind pages
(iii) Configuration files
(iv) Global.asax file
ANS:
(i) Web Forms or .aspx pages
Web Forms is the oldest ASP.NET programming model, with event driven web pages written
as a combination of HTML, server controls, and server code.Web Forms are compiled and
executed on the server, which generates the HTML that displays the web pages.
Web Forms comes with hundreds of different web controls and web components to build userdriven web sites with data access.
When a website or web application is created a web page is created with an extension of .aspx.
This is called web form and all the user controls are put on this form to desighn user interactive
forms
(ii) Code-behind pages
The code-behind page model for Web Forms allows you to keep the markup in one filethe
.aspx fileand the programming code in another file. The name of the code file varies

according to what programming language you are using. For example, if you are working with
a page named SamplePage, the markup is in the file SamplePage.aspx and the code is in a file
SamplePage.aspx.cs in C#.
In the code-behind model, the example used in the preceding section for the single-file page
would be in two parts. The markup would be in one file (in this example, SamplePage.aspx)
and would be similar to the single-file page, as shown in the following code example.
<%@ Page Language="C#" CodeFile="SamplePage.aspx.cs" Inherits="SamplePage"
AutoEventWireup="true" %>
<html>
<head runat="server" >
<title>Code-Behind Page Model</title>
</head>
<body>
<form id="form1" runat="server">
<div>
The following code example shows a code-behind
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SamplePage : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Clicked at " + DateTime.Now.ToString();
}
}
The code-behind file contains the complete class declarations in the default namespace.
However, the class is declared with the partial keyword, which indicates that the class is not
contained entirely in one file. Instead, the compiler reads the .aspx page and the file it
references in the @ Page directive, and assembles them into a single class.The partial class file
inherits from the page Page class
(iii) Configuration files
The behavior of an ASP.NET application is affected by different settings in the configuration
files:
machine.config
web.config
The machine.config file contains default and the machine-specific value for all supported
settings. The machine settings are controlled by the system administrator and applications are
generally not given access to this file. An application however, can override the default values
by creating web.config files in its roots folder.
The web.config file is a subset of the machine.config file.If the application contains child
directories, it can define a web.config file for each folder. Scope of each configuration file is
determined in a hierarchical top-down manner. Any web.config file can locally extend, restrict,

or override any settings defined on the upper level. Visual Studio generates a default
web.config file for each project. An application can execute without a web.config file,
however, you cannot debug an application without a web.config file.
(iv) Global.asax file
The Global.asax file, also known as the ASP.NET application file, is an optional file that
contains code for responding to application-level events raised by ASP.NET or by
HttpModules.
The Global.asax file resides in the root directory of an ASP.NET-based application. The
Global.asax file is parsed and dynamically compiled by ASP.NET.
The Global.asax file itself is configured so that any direct URL request for it is
automatically rejected; external users cannot download or view the code written within
it.
The Global.asax file does not need recompilation if no changes have been made to it.
There can be only one Global.asax file per application and it should be located in the
application's root directory only.
The Global.asax contains two types of events those are
Events which are fired for every request
Events which are not fired for every request
4(b) What are the new features in Graphical Device Interface Plus (GDI+) ? Explain
them in detail. Differentiate between GDI and GDI+.
[10]
ANS:
The new features in Graphical Device Interface Plus (GDI+)
1. Gradient Brushes
2. Cardinal Splines
3. Independent Path Objects
4. Transformations and the Matrix Object
5. Scalable Regions
6. Alpha Blending
7. Support for Multiple Image Formats
1. Gradient Brushes:GDI+ expands on Windows Graphics Device Interface (GDI) by
providing linear gradient and path gradient brushes for filling shapes, paths, and regions.
Gradient brushes can also be used to draw lines, curves, and paths.
2. Cardinal spline: A cardinal spline is a sequence of individual curves joined to form a
larger curve. The spline is specified by an array of points and passes through each point in
that array. A cardinal spline passes smoothly (no sharp corners) through each point in the
array and thus is more refined than a path created by connecting straight lines. The
following illustration shows two paths, one created by connecting straight lines and one
created as a cardinal spline.
3. Independent Path Objects: In GDI, a path belongs to a device context, and the path is
destroyed as it is drawn. With GDI+, drawing is performed by a Graphics object, and you
can create and maintain several GraphicsPath objects that are separate from
the Graphicsobject. A GraphicsPath object is not destroyed by the drawing action, so you
can use the same GraphicsPath object to draw a path several times.
4. Transformations and the Matrix Object:GDI+ provides the Matrix object, a powerful
tool that makes transformations (rotations, translations, and so on) easy and flexible. A

matrix object works in conjunction with the objects that are transformed. For example,
a GraphicsPathobject has a GraphicsPath::Transform method that receives the address
of a Matrix object as an argument. A single 33 matrix can store one transformation or a
sequence of transformations. The following illustration shows a path before and after a
sequence of two transformations (first scale, then rotate).
5. Scalable Regions:GDI+ expands greatly on GDI with its support for regions. In GDI,
regions are stored in device coordinates, and the only transformation that can be applied to
a region is a translation. GDI+ stores regions in world coordinates and allows a region to
undergo any transformation (scaling, for example) that can be stored in a transformation
matrix. The following illustration shows a region before and after a sequence of three
transformations: scale, rotate, and translate.
6. Alpha Blending:Note that in the previous figure, you can see the untransformed region
(filled with red) through the transformed region (filled with a hatch brush). This is made
possible by alpha blending, which is supported by GDI+. With alpha blending, you can
specify the transparency of a fill color. A transparent color is blended with the background
color the more transparent you make a fill color, the more the background shows
through. The following illustration shows four ellipses that are filled with the same color
(red) at different transparency levels.
7. Support for Multiple Image Formats
GDI+ provides the Image, Bitmap, and Metafile classes, which allow you to load, save and
manipulate images in a variety of formats. The following formats are supported:
BMP
Graphics Interchange Format (GIF)
JPEG
Exif
PNG
TIFF
ICON
WMF
EMF
4(c) Discuss in detail about WSDL, UDDI, SOAP and the concept behind Web Services.
[10]
ANS: Web services are open standard ( XML, SOAP, HTTP etc.) based Web applications that
interact with other web applications for the purpose of exchanging data Web Services can
convert your existing applications into Web-applications.
Components of Web Services
The basic Web services platform is XML + HTTP. All the standard Web Services works using
following components
1. SOAP (Simple Object Access Protocol)
2. UDDI (Universal Description, Discovery and Integration)
3. WSDL (Web Services Description Language)
SOAP
SOAP is an XML-based protocol for exchanging information between computers.
SOAP is a communication protocol

SOAP is for communication between applications


SOAP is a format for sending messages
SOAP is designed to communicate via Internet
SOAP is platform independent
SOAP is language independent
SOAP is simple and extensible
SOAP allows you to get around firewalls
SOAP will be developed as a W3C standard
WSDL
WSDL is an XML-based language for describing Web services and how to access them.
WSDL stands for Web Services Description Language
WSDL is an XML based protocol for information exchange in decentralized and distributed
environments.
WSDL is the standard format for describing a web service.
WSDL definition describes how to access a web service and what operations it will
perform.
WSDL is a language for describing how to interface with XML-based services.
WSDL is an integral part of UDDI, an XML-based worldwide business registry.
WSDL is the language that UDDI uses.
WSDL was developed jointly by Microsoft and IBM.
WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'
UDDI
UDDI is an XML-based standard for describing, publishing, and finding Web services.
UDDI stands for Universal Description, Discovery and Integration.
UDDI is a specification for a distributed registry of Web services.
UDDI is platform independent, open framework.
UDDI can communicate via SOAP, CORBA, Java RMI Protocol.
UDDI uses WSDL to describe interfaces to web services.
UDDI is seen with SOAP and WSDL as one of the three foundation standards of web
services.
UDDI is an open industry initiative enabling businesses to discover each other and define
how they interact over the Internet.
5
Attempt any two questions: (10X2=20)
5(a) What do you understand about .Net Assemblies? What is the difference between
Private and Shared Assemblies?
[10]
ANS:
Assemblies are defined as physical files that consist of one or more portable executable
(PE) files generated by a .NET compiler.
An assembly is the packaging of a manifest, one or more modules, and, optionally, one or
more resources.

Using assemblies allows you to semantically group functional units into a single file for
purposes of deployment, versioning, and maintenance.
Assemblies have Metadata stored to provide version information along with a complete
description of methods and types. Part of this metadata is a Manifest. The manifest
includes identification information, public types and a list of other used assemblies.
Difference between Private and shared assembly
1. Private Assemblies, used for single programs, and Global Assemblies shared among
several applications
2. Private assembly will be stored in the specific application's directory or sub-directory.
assembly is stored in GAC (Global Assembly Cache).
3. There is no other name for private assembly. Public assembly is also termed as shared
assembly.
4. Strong name is not required for private assembly where as it is required for the shared
assembly
5. Private assembly doesn't have any version constrain where as version number is required
for shared assembly..
5(b) What do you mean by attribute? Discuss built-in attribute and Custom attribute.
[10]
ANS:
Attributes:
C# allows you to add declarative information to a program in the form of an attribute.
An attribute defines additional information (metadata) that is associated with a class,
structure, method, and so on.
For example, you might define an attribute that determines the type of button that a class
will display.
Attributes are specified between square brackets, preceding the item to which they apply.
Thus, an attribute is not a member of a class. Rather, an attribute specifies supplemental
information that is attached to an item.
An attribute is supported by a class that inherits System.Attribute.
Built-in Attributes
The .Net Framework provides three pre-defined attributes:
AttributeUsage
Conditional
Obsolete
AttributeUsage: The pre-defined attribute AttributeUsage describes how a custom attribute
class can be used. It specifies the types of items to which the attribute can be applied.
Conditional:This predefined attribute marks a conditional method whose execution depends
on a specified preprocessing identifier. It causes conditional compilation of method calls,
depending on the specified value such as Debug or Trace.
Obsolete: This predefined attribute marks a program entity that should not be used. It enables
you to inform the compiler to discard a particular target element. For example, when a new
method is being used in a class, but you still want to retain the old method in the class, you
may mark it as obsolete by displaying a message the new method should be used, instead of the
old method.

5(c) Write a program to connect a SQL server database with a Windows Form
Application made in C#. Explain the necessary steps to deploy such an application. [10]
ANS:
Step 1: Create a Windows Forms Form: Open Visual Studio and create a new project and
select Windows Forms application and provide it the name "First_Csharp app".
Step 2: Drag and drop a button: Now from the toolbox drag and drop a button and click on
the button.
Step 3: Database table: Create a database table in SQL Server. Here the database name is
"windowapp" and "tablename" is the data.
Step 4: Code for button click: First insert a namespace "using System.Data.SqlClient".
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MyForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
String str = "server=MY-PC;database=windowapp;UID=sa;password=123";
String query = "select * from data";
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
DataSet ds = new DataSet();
MessageBox.Show("connect with sql server");
con.Close();
}
catch (Exception es)
{
MessageBox.Show(es.Message);

}
}
}
}
Step 5: Run the application.

Anda mungkin juga menyukai