C#Web Basics SQL
C#Web Basics SQL
C#Web Basics SQL
Every Thing About Technology(Mob:9762059130 , 02027240087 ). Subject: C#, Web Basics & SQL
--------------------------------------------------------------------------------------------------------------------------------
Microsoft.Net Basics
What is Microsoft.Net?
Microsoft.Net is object oriented & Service Oriented application development platform which allow
you design and develop computer applications. As we say it is application development platform that
means it contains set of tools, compilers, programming languages, editors, debuggers and so many
other facilities using which you can design and develop the Computer/IT Applications.
Currently Micrsofot.NET comes in two flavours –
A. .NET Framework
B. .NET Core
Functional Approach:-
This is classical and simple approach to design and develop the software. Throughout this approach
our whole concentration will be on functions. At every step of SDLC we think about the functions and
create design, development of the system in terms of functions. We find the functions. We draw
DFD, DT, Flow Chart etc to create the functional model of the system. We also implement the system
by writing the functions. Over a period it had been found that the system designed and developed
using the functional approach are difficult to enhance or maintain since functions are tightly coupled
with each other (more dependent).
Object Oriented Approach:-
This is new approach designed to solve the problems of functional approach. In case of object
oriented approach we think about system in terms objects and their interactions. We analyze the
system in terms of object. We create the design of the system in terms of objects as well as we
implement the system using object oriented programming language. Over a period it had been found
by the computer scientist that system designed and developed using object oriented approach is
easy to maintain and enhance since the objects are less coupled (dependent) on each other.
Object oriented approach is little bit complex to implement and cannot consume the dynamic
business logic.
Service Oriented Approach:-
Service oriented approach allow you to design develop the applications or software’s by considering
services or Service Oriented Architecture (SOA). SOA is very simple and power full architecture it has
three stake holders Service, Service Producer & Service Consumer. Service is any in tangible thing
XML and Web Services (Available Microsoft.Net 2.0): - XML web services is facility provided by
.net framework using which you can design and develop the service oriented applications or
applications based on SOA architecture. XML web services has following features –
Open Source.
Communicate using XML.
Can be secure with the help of the SOAP.
ADO.NET & XML:-
ADO.Net is new technology for data manipulation from the databases; this technology comes with
Microsoft.Net framework. This technology is also based on the XML standard and we had already
seen the advantages of XML. ADO.NET has following advantages –
Object Oriented
Language Independent
Supports Connected as well as disconnected architecture.
Huge support for XML
CLR Architecture:-
CLR is core component of the .Net, it has responsibility from loading the program into the computer
memory till its execution. It has various components dedicated for specific execution task those are –
Class Loader and Class Specifier: -
Class specifier finds the details or specifications of the classes used by the Microsoft.Net application
from the Framework Class Library and class loader will load it, in memory. Class specifier and class
loader works together to perform this task.
Some Concepts: -
What is Side by Side Execution?
In case of Microsoft.Net we can have more than one versions of dll files used in single application
due to the concept of the assembly. Their might be the possibility that two same dll files with
different version will be used and executed by Microsoft.Net application and both of them will be
loaded simultaneously and will be executed. This execution is called Side by Side Execution.
What is Managed and Unmanaged Code?
Manage code is that code which runs under the control of CLR. The code that will be executed by CLR
(Intermediate Language Code) is called the Managed Code. The code other than IL code like com
code will be executed without CLR with the Help of the COM Marshalar called Unmanaged Code.
ASP.NET Core(MVC 6)
ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern,
cloud-based, Internet-connected applications. With ASP.NET Core, you can:
Build web apps and services, IoT apps, and mobile backends.
Use your favorite development tools on Windows, macOS, and Linux.
Deploy to the cloud or on-premises.
Run on .NET Core or .NET Framework.
C#.NET:-
C#.Net is a programming language supported by Microsoft.Net framework has n number of
features -
C#.NET Features:-
> C# is pure object oriented programming language.
> Compatible with Microsoft.Net framework. So whatever features that we have with Microsoft.Net
frame work will be also available in C#.
Like –
Assemblies
CTS (Common Type Specification),
CLS (Common Language Specification),
Code Based Security
XML, SOAP (Simple Object Access protocol)
CLR (Common Language Runtime) etc.
C# inherits all it’s syntax from C++.
A. Console Application:-
Console Application will have CUI where user has to interact with application or software using
character commands.
Basics C#.NET:-
When we say any programming it is going to provide you following facilities –
Keywords: -
Keywords are the predefined words whose meaning can not be changed.
Constants: -
These are the defined keywords or symbols whose values can not be changed.
Operators: -
Data Type: -
Data types are the keywords by which we tell computer what type of value should be stored in a
memory block allocated by variable so that computer will make all arrangements in memory. In case
of C# data types are divided into two types –
Reference type:-
The variables created using reference type of data type will be get created into heap section of the
data segment of the program hence before using reference type of variable we should have to
allocate memory for that variable explicitly. If you do not allocate memory explicitly you will not be
able to use it. In case of reference type of data type we use new and delete keywords to allocate or
de allocate memory for the variable. Reference type of data types includes-
1. Arrays.
2. Classes.
Value type: -
Value type of variable will be getting created on stack; stack is auto data structure so we do not
need to allocate memory for these types of variables explicitly. When where you create the variable
it will get memory automatically. In case of value type we have following data types –
3. Numeric Data Types: - int (int16, int32, int64), double, single, decimal etc.
4. boolean:- true /false
5. char
e. g. int num=10;
Libraries
Namespace name space name
{
class class name
{
static void Main(String [] args) // Starting point of the C# Program.
{
statements;
}
}
}
Write and WriteLine also support the format strings and escape sequence characters, you
can specify the format string in {} brackets.
Convert Class:-
C# provides you one built in class called the convert class which allow you to convert one data type
to another data type,. It has some following methods –
ToInt16(parameter):- It will convert given parameter to int16.
ToInt32(parameter):- It will convert given parameter to int32.
ToInt64(parameter):- It will convert given parameter to int64.
ToString(parameter):- It will convert it to string.
ToDate(parameter): - It will convert given parameter to date.
2. Click on the file and new project menu It will get you following window –
3. In project types select Visual C# and Console Application.
4. In Name specify the name of the project.
5. In Location specify the directory where you want to store the project or application. It will
get you following environment where you can type the code in main window –
6. To build the solution we use F6 (go to Built menu and Click on Built).
7. To run the application or solution press ctl + F5 key or go to debug and Start, it will show
you output.
E.g. accept two numbers from the user and display its Addition.
namespace FirstProgram
{
class Program
{
static void Main(string[] args)
{
int a, b, c;
Console.Write("Enter First Number:");
a = Convert.ToInt16(Console.ReadLine());
Console.Write("Enter SEcond Number:");
b = Convert.ToInt16(Console.ReadLine());
c = a + b;
Console.WriteLine("Addition is :" + Convert.ToString(c));
Console.Read();
}
}
}
E.g. accept the radius of the circle from the user and display area of the circle.
namespace secondprogram
{
class Program
{
static void Main(string[] args)
Conditional Statements:-
Condition is an expression when evaluated will generate any of the two values that are true or false.
To implement the conditions C# provides us following statements -
if Statement: - This is used to implement the condition but able to handle only true part of the
condition. It has following syntax –
if(condition)
{
Statements;
}
if-else: - This is used to implement the condition which is able to handle both the parts of the parts
of the condition that are true or false. It has following syntax -
if(condition)
{
Statements;
}
else
{
Statements;
}
e.g. Accept a number from user and display weather it is odd or even.
namespace ConditionExample
{
class Program
{
static void Main(string[] args)
{
int num;
Console.Write("Enter Number:");
num = Convert.ToInt32(Console.ReadLine());
if (num % 2 == 0)
Console.WriteLine("Even Number");
else
Console.WriteLine("Odd Number");
}
}
}
e.g. Accept a number from user and display weather it is odd or even.
namespace ConditionExample{
class Program
{
static void Main(string[] args)
{
int num;
Console.Write("Enter Number:");
num = Convert.ToInt32(Console.ReadLine());
if (num % 2 == 0)
Console.WriteLine("Even Number");
else
Console.WriteLine("Odd Number");
}
}
e.g. Accept three numbers from the user and display the maximum from it.
namespace ConsoleApplication1{
class Program
{
static void Main(string[] args)
{
int a, b, c;
Console.Write("Enter first numbers==>");
a = Convert.ToInt16(Console.ReadLine());
Console.Write("Enter second numbers==>");
b = Convert.ToInt16(Console.ReadLine());
Looping Statements:-
loop is a mechanism which will take care of performing the any task again and again. Every loop will
have –
The loop that do not have end point then we will call it as the inifnite loop. C# provides you following
looping statements –
For loop :-
is generally used when you know in advance how many times loop is going to execute. It has
following syntax –
At initlization part we can declare the multiple varaibles as well as we can do the multiple varaible
initilization. Similar the case with next value. But every for loop will have only one terminating
condition, if you want to use more than one condition then you have to use the logical operators.
e.g. Accept 10 numbers from the user and display the addition of them.
namespace AdditionofDigits
{
class Program
{
static void Main(string[] args)
{
int num;
int add = 0;
// int cnt;
While :-
While loop is used when you do not know in advance how many times loop is going to execute. It
will have the following syntax –
while(condition)
{
Statements;
}
e.g. Accept one number form the user and display the addition of digits of the number.
namespace AdditionDigits1
{
class Program
{
static void Main(string[] args)
{
int num,dig,add=0;
Console.Write("Enter Number");
num = Convert.ToUInt16(Console.ReadLine());
while(num!=0)
{
dig = num % 10;
add = add + dig;
num = num / 10;
}
Console.WriteLine("Addition of Digits :" + Convert.ToString(add));
Console.Read();
}
Do-while:-
In case of do while loop, the loop will be executed at least for one time and it’s next exectuion
depends on condition. If condition is true then it will execute it, if condition is not true then it will not
execute it. It has following syntax –
do
{
Statements;
}while(condition);
e.g. Accept charcters from user till user do not say no, and display how many vowels and
consonents are their.
namespace Dowhile
{
class Program
{
static void Main(string[] args)
{
char ch,option='n';
int vcnt=0,ccnt=0;
do
{
Console.Write("Enter Character:");
ch = Convert.ToChar(Console.ReadLine());
if( ch =='a' || ch =='e' || ch=='i' || ch=='o' || ch=='u')
vcnt ++;
else
ccnt ++;
Console.Write("Do you want to Continue?[y/n]") ;
option =Convert.ToChar(Console.ReadLine());
}while(option == 'y');
Console.WriteLine("Vowels are :" + Convert.ToString(vcnt) + " Consonent:" +
Convert.ToString(ccnt));
Console.Read();
}
}
}
Accept a number and replace its odd digits by zero. E.g. 12345 – 2040
namespace odddigit
{
class Program
{
static void Main(string[] args)
{
int num,dig;
Console.Write("enter number");
num = Convert.ToInt32(Console.ReadLine());
Console.Write("Output is:");
do
{
Break and Continue: - Break statement is used to come out from the loop and continue
statement will be going to skip the statements just similar to C++.
case 'e':
// Console.WriteLine("Ovwel");
// break;
case 'i':
// Console.WriteLine("Ovwel");
// break;
case 'o':
//Console.WriteLine("Ovwel");
//break;
case 'u':
Console.WriteLine("Ovwel");
break;
default:
Console.WriteLine("Conso");
break;
We use the indexing mechanism to access the elements of the array. In case indexing mechanism
when array get created inmemory every element of array will get one unique index number assigned
to it starting from 0 and goes up to size-1. Now to refer individual element of array we use folllwoing
synatx –
Arrayname[indexnumber];
In case of C# Array is refrence type of data type,it means before using array variale we have to
allocate the memory to array explicitly. In C# We can define the array as follows –
Data type [] arrayname=[new datatype[size]];
e.g. Accept 10 numbers from the users in array and replace ith position element with
l+1th position and vice versa.
namespace Array1
{
class Program
{
static void Main(string[] args)
{
int[] num = new int[10];
int cnt,temp;
//Accepting 10 elements from user
for (cnt = 0; cnt < 10; cnt++)
{
Console.Write("Etner Number:");
num[cnt] = Convert.ToInt16(Console.ReadLine());
}
// Swaping
for (cnt = 0; cnt < 10; cnt+=2)
{
temp = num[cnt];
num[cnt] = num[cnt + 1];
num[cnt + 1] = temp;
}
// Displaying Array Elements.
1. Public.
2. Private.
3. Protected.
4. Internal.
Note: - if you do not use any access type by default it will be private for members of the
class and internal for class.
Continue ..
Using the class:-
To use the class you have to create the object or instance of that class and it can be created using
following syntax –
Classname objectname[=new classname()];
Once you create the object of the class you can access the properties and methods of the class using
dot operator.
class Program
{
static void Main(string[] args)
{
Student s = new Student();
int r; string sn, ad, ph;
Console.Write("Plz Enter RollNo:");
r =Convert.ToInt32(Console.ReadLine());
If you want to define and use the destructors you have to do it explicitly , while creating the
destructors you have to again has following rules –
Destructor Name should be same as that of class name but prefixed with ~ symbol.
Their can be only one destructor in side the class.
In case of C# we do not guarantee that when destructors will be executed.
Use destructors; explicitly in C# class is bad idea because object collection task will be conducted
automatically by the C# garbage collector component.
Array of Objects: -
Just like normal array we can also create the array of objects as follows –
Classname [] objectname=new classname[size];
In case of normal array you have to initialize only the array, in case of array of objects we not only
have to initialize the array but also the elements of the array since the elements of the array is of
again type reference.
using System;
namespace ArrayOfObjects
{
class Flight
{
private int Fno;
private string Fname;
private string Fsource;
private string Fdestination;
private double Fair;
public void AddFlight(int fn,string fnm,string fs,string fd,double ff)
{
Fno = fn;
Fname = fnm;
Fsource = fs;
Fdestination = fd;
Fair = ff;
}
public void Dispflight()
{
Console.WriteLine("Flight No:" + Fno.ToString () );
Console.WriteLine("Flight Name:" + Fname );
Console.WriteLine("Flight Source:" + Fsource);
Console.WriteLine("Flight Destination:" + Fdestination);
Console.WriteLine("Flight Fair:" + Fair.ToString());
//Accepting Information
string fnm;
int fn;
string fs;
string fd;
double fr;
Properties enable a class to expose a public way of getting and setting values, while hiding
implementation or verification code.
In C# properties can be created using following syntax –
Access type property data type propertyname
{
set
{
Allow you to write the value.
}
get
{
Allow you to read the value.
}
}
Set Accessor allows you to write the value, where you can use the value keyword which will get the
value assigned to the property.
Get Accessor allows you to read the value of the property which can be returned using return
keyword.
Why properties?
Properties allow you to expose the private data members of the class outside the class, it also
provides you extra arrangement (blocks where you can write C# code to validate the property value
assigned to property or the value read from the property) by which you can control the value
assigned to property or value read from the property.
e. g. c# properties example
namespace Properties
{
class Myclss
{
private int dval;
public int propdval
Indexers in C#:-
Indexers are the facility provided by c# using which you can access class objects as an array,
indexers can be used at two level to expose the field from the class which is of type collection out
side the class or to expose whole class object as array. Defining an indexer allows you to create
classes that act like "virtual arrays." Instances of that class can be accessed using the [] array
access operator
Properties can not expose members of the class outside the class which contains more than one
element (arrays / collections etc), instead of that you can use the indexers.
To create the indexer in C# we use the following syntax –
Access type data type this[int index]
{
set
{
Write the value inside the indexer.
Value keyword can be used to assign the value.
}
get
{
Get the value from indexer;
}
}
e. g. Using indexers.
Static Keyword:-
It is an access modifier can be used with class data members, method, constructor and class as well.
Static data Members: - when you use the static keyword with data members of the class those
data members will be get created before creation of the first object of the class in memory only once
and all the objects of the class is going to use those data members. Generally we create the static
Static methods: - static keyword when used with method those methods will become static, what it
means you will be able to invoke those methods with class name, it will not have the reference inside
the class object. Static methods are basically created to process static data members. When you
create the static method you will not able to invoke the non static method in static method.
Static constructors: - static constructors are the constructor functions from the class those will be
define using the static keyword those will have following features –
Static constructors will be gets executed only once before creation of object of the class generally
used to initialize the static data members of the class. Static constructors will not have the
parameters. One class can contain only one static constructor.
Static class: - you can also use the static access type with class, when you use the static access
type with class that class will become static with following rules –
static class can contain only static members
You will not be able to create the object of the static class.
e. g . Create a team class with pid, pname, pindscore with proper data members and
methods to accept and display –
- Player Information
- Team Score Information
Use static keyword.
namespace teamstatic
{
class team
{
private int pid;
private string pname;
private int indscore;
private static int totalscore=0;
public void accept(int id, string pn, int inds)
{
pid = id;
pname = pn;
indscore = inds;
totalscore = totalscore + indscore;
}
public void disp()
{
Console.WriteLine("\n pid="+pid);
Console.WriteLine("name=" + pname);
Console.WriteLine("ind score=" + indscore);
}
public static void disptotal()
{
Console.WriteLine("\n\ntotal score=" + totalscore);
}
}
class Program
{
static void Main(string[] args)
{
int r = Math.AddNums(45, 56);
Console.WriteLine(r);
r = Math.SubNum(34, 56);
Console.WriteLine(r);
}
}
}
Inheritance: -
Is the process by which we acquire the properties and methods of one class into another class. In
case of C# we can not implement the multiple inheritances. To implement the inheritance we use
following syntax-
In case of inheritance child will inherit all the properties of parent including private, public and
protected but can not access private properties. Inheritance provides you two advantages –
Reusability of code.
Enhancements.
e. g.
namespace Inheritance
{
class Salesmen
{
protected int salesid;
protected string sname;
protected int target;
}
class SalesmenSales : Salesmen
{
private int totalsales;
private string date;
private double comm;
public void setSalesmenSales(int si, string sn, int t, int ts, string dt, double cm)
{
salesid = si;
sname = sn;
target = t;
totalsales = ts;
date = dt;
comm = cm;
}
public void dispSalesmenSales()
{
Console.WriteLine("Salesmen ID:" + salesid);
Console.WriteLine("Salesmen Name:" + sname);
Console.WriteLine("Salesmen Target:" + target);
Console.WriteLine("Total Sales:" + totalsales);
Console.WriteLine(" Date :" + date);
Console.WriteLine(" Commission:" + comm);
}
}
class Program
{
static void Main(string[] args)
{
SalesmenSales s = new SalesmenSales();
s.setSalesmenSales(1, "Rajesh", 12000, 10000, "1/2/2009", 12);
s.dispSalesmenSales();
}
}
}
What ever may be the type of object of child class, it will always first execute the default constructor
of parent, if you want to execute the parent parameterized constructor then you have to use the
base keyword as follows –
namespace ConstructorExecutionSequenceininheritance
{
class Test
{
public Test()//defualt
{
Console.WriteLine("Parent Default Constructor Called");
}
public Test(int a)
{
Console.WriteLine("Parent Parameterized Constructor Called");
Polymorphism:-
It is mechanism by which we can implement any thing in such a way that , that particular thing is
going to change it’s behavior (functionality) depending on external interface. There are two types of
polymorphisms, compile time polymorphism and runtime polymorphism. In case of C# we can
implement the polymorphism by two ways –
1. Overloading.
2. Overriding.
Overloading: - It allows you to implement the compile time polymorphism. Overloading is a process
by which we can create multiple implementations with single identity. Overloading can be
implemented by two ways –
Function Overloading: - Function overloading is a mechanism using which we can implement
multiple functions having same name. When you create multiple functions with same name, to avoid
the ambiguity we differentiate them using any of the following criteria –
Number of parameters should be different
Data Types of the parameter should be different
Sequence of data types of the parameter should be different.
But we will not be able to differentiate them using variable names or return data type.
e. g.
namespace Overloading
{
class Student
{
private int sid;
if (r == 0)
Console.WriteLine("Logged In");
else
if (r == 1)
Console.WriteLine("Wrong User Name and Password");
else
Console.WriteLine("Not Qualified");
Teacher t = new Teacher();
t.SetTeacher(1, "Rakesh", 12);
r = l.CheckLogin("SA", "S", t);
if (r == 0)
Console.WriteLine("Logged In");
else
if (r == 1)
Console.WriteLine("Wrong User Name and Password");
else
Console.WriteLine("Not Qualified");
}
}
}
In case of function overloading compiler can decide at compile time which function will be
called at which place, hence it is also called as static binding or compile time binding and
the process is called compile time polymorphism.
Operator Overloading:-
Here we enhance the basic functionalities of the operator so that they can operate on different type
of data. To implement the operator overloading we have to define the function inside the class called
operator overloaded function having following syntax –
Access type static return data type operator operator symbol (parameters)
{
This function will be executed in place of operator specified by the operator symbol.
namespace OperatorOverloading{
class weight {
private int gm;
private int kg;
public void setWeight(int k, int g)
{
kg = k;
gm = g;
}
public void dispWeight()
{
Console.WriteLine("Kg:" + kg);
Console.WriteLine("Gn :" + gm );
}
public static weight operator +(weight wt,weight wt1)
{
int tkg = 0;
weight temp = new weight();
Overriding:-
Basically when you inherit any class from some another class, all the things (properties /methods)
will be get inherited in child, some times the parent methods inherited by the child are not sufficient
according to the child, so child need to redefine those methods from scratch or child want to add
some new features to those methods, that is possible by redefining the inherited parent methods in
child. Hence overriding is a process by which child can redefine the virtual or abstract methods of the
parent.
If child redefine any non abstract or non virtual method of the parent the process is not overriding
but it is called as method hiding. Hence when child want to redefine the virtual or abstract method of
parent child have to use override keyword to redefine those methods.
e. g. Method Overriding
using System;
namespace ConsoleApplication11
{
class ParentClass
{
public virtual void DispMethod()
{
Console.WriteLine("Parent Class");
}
}
class ChildClass:ParentClass
{
public override void DispMethod()
{
Console.WriteLine("Child Class");
}
}
class Program
{
static void Main(string[] args)
{
ChildClass sc = new ChildClass();
sc.DispMethod();
}
}
}
To Make Method hiding explicit you have to define the overridden method using new keyword in child
class otherwise c# compiler will give you warning.
e. g. Method hiding
namespace ConsoleApplication5{
class Parent {
public void SampleMethod()
{
Console.WriteLine("Sample parent method");
Object Slicing: -
When we assign the child object in parent object the child initialize the parent by parent portion of
the child object and the process is called object slicing and when you call the overridden method of
parent when parent has the reference of child object and it will not execute the method of parent,
instead of the it will execute the method from child.
namespace ConsoleApplication11{
class ParentClass {
private int x;
public virtual void DispMethod()
{
Console.WriteLine("Parent Class");
}
}
class ChildClass:ParentClass
{
private int y;
public override void DispMethod()
{
Console.WriteLine("Child Class");
}
}
class Program
{
static void Main(string[] args)
{
ChildClass sc = new ChildClass();
// sc.DispMethod();
ParentClass pc = new ParentClass();
pc = sc; // object slicing
pc.DispMethod();
}
}
}
a = new Cat();
In Above example if you see, you will not be able to predict which function will be get called at
a.create() at compile time, since which function call at this point depends on user input and it will
be available at run time and then we can predict which function will be get called hence here function
call bind to function definition at run time called runtime or dynamic binding and the polymorphism is
called Run Time Polymorphism.
Abstract keyword can be used with class as well as class method, when you use the abstract
keyword with class, you can not create the instance or that class. You can use the abstract keyword
with class as follows –
Abstract Class: -
namespace ConsoleApplication2
{
abstract class Student
{
private int rollno;
private string sname;
private string address;
private string sclass;
public void setStudent(int r, string sn, string add, string scl)
{
rollno = r;
sname = sn;
address = add;
sclass = scl;
}
public void dispStudent()
{
Console.WriteLine("Roll No:" + rollno.ToString());
Console.WriteLine("Student Name :" + sname);
Console.WriteLine("Student Address:" + address);
class Program
{
static void Main(string[] args)
{
Abstract Method:-
When you use the abstract keyword with method, the method will become abstract it means method
can not have the body, such methods can be defined only in abstract class which should be
overridden by the child classes of the abstract class. It means it will be compulsory to child class to
override all abstract methods from the parent, if child does not override any abstract method from
the parent then it will also become abstract class.
e.g.
namespace ConsoleApplication2
{
abstract class Search
{
public abstract Boolean search(int a, int[] nm);
public void disp()
{
Console.WriteLine(" Display method from search");
}
}
class SeqSearch : Search
{
public override bool search(int a, int[] nm)
{
{
bool flag = false;
for (int i = 0; i < nm.Length ; i++)
{
if (a == nm[i])
{
flag = true;
break;
}
}
return flag;
}
}
}
class Program
{
static void Main(string[] args)
{
SeqSearch sq = new SeqSearch();
int[] nm ={ 1, 2, 3, 4, 56 };
if (sq.search(23, nm))
Console.WriteLine(" Element is found ");
else
Console.WriteLine(" Element is not Found ");
Sealed Keyword:-
Sealed keyword in C# can be used with method or class. When you use the sealed keyword with
class that class can not be inherited, it means you wiil not be able to do the modification or
enhancement in the sealed class. When you define the method using sealed keyword that method
can not be overriden, so can not be modified.
namespace ConsoleApplication2
{
sealed class Student
{
private int rollno;
private string sname;
private string address;
private string sclass;
public void setStudent(int r, string sn, string add, string scl)
{
rollno = r;
sname = sn;
address = add;
sclass = scl;
}
public void dispStudent()
{
Console.WriteLine("Roll No:" + rollno.ToString());
Console.WriteLine("Student Name :" + sname);
2. Structured Approach : - This is most popular way of exception handling in object oriented
programming languages where it provides us following keywords –
try
catch
finally
throw
Try: - Try keyword is used to define the try block which contains statements or instructions where
exception supposed to occur. Try block contains normal program statements.
Catch: - Catch keyword allows you to define the code block that will be executed as an action when
exception occurs. It contains statement that is action to the exception.
Try and Catch works together to define the try catch block as follows –
try
{
Statements;
}catch(Exception Object)
{
Statements;
}
Where exception object is exception identifier using which we can identify that the action specified in
a catch block will be for specified exception. It is necessary to use the Exception identifier in catch
block since try contains multiple statements which may generates the multiple exceptions hence
multiple exceptions needs multiple actions and single catch block can specify only a action. Hence we
need to use the multiple catch blocks with single try block for specifying different and unique action
for different type of exception and hence needs the exception identifier. We can use multiple catch
blocks with single try as follows –
try
{
Statements;
}catch(Exception object1)
{
Statements;
}
catch(Exception object2)
{
Statements;
}
catch(Exception object3)
{
Statements;
}
….
Finally keyword: - Finally keyword is used to define the finally block, finally block will contains the
statements those supposed to be executed in both situations weather exception occurs or weather
exception does not occurs. It is used to define the compulsory actions. Single try block can have only
one finally block.
Throw keyword: - throw keyword is used to raise the exceptions if it is not begin raised by the
CLR.
Execution Process:- try block contains the normal program statements those will be executed by
the CLR one after another, if any exception occurs then it will identify that exception and transfer the
program control to the catch block where the action for that exception is being specified by skipping
the rest of the statements from the try block. Once program control transferred to catch block then it
will be executed in response to the exception and it will terminate the program normally.
1. Built in Exceptions: - are the exceptions provided by CLR, to whom CLR can identify, raise
as well as can handle. For built in exceptions CLR provides you a exception class using which
we can create exception object to identify the exception and transfer the execution control to
the catch block. What ever may be the type of exception there is class called Exception; it will
be super class of all exception classes.
Built in Exceptions Example: -
namespace ExceptionHan
{
class Program
{
static void Main(string[] args)
{
int n;
int[] nm = new int[3];
try
{
Console.Write("Enter Number");
n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("VAlue of N:" + n);
nm[3] = 23;
}
catch (FormatException ex)
{
Console.WriteLine(" Plz Enter Proper Value");
Console.WriteLine(ex.ToString());
}
finally
{
Console.WriteLine(“ Finally block Executed “);
}
}
}
}
User defined exception: -
These are the exceptions those can not be provided by CLR, but generated and identified by the
User, depending on some custom conditions. User can generate the user defined exception using
throw keyword. To implement the user defined exception you have to follow –
> Create special class dedicated to handle the exception
> This class Should Inherit from Exception class
> Throw its object from the normal class where exception occurs.
> Catch the object in catch block where perform the action
e. g. Built in Exception
namespace UserDefined
{
class PriceException : Exception
{
private string str;
public PriceException(string s)
{
str = s;
}
public void DispPriceException()
{
Console.WriteLine("Price Exception Occured" + str);
}
}
class Product
{
private int pid;
private string pname;
private double price;
public void SetProduct(int pi, string pn, double pr)
{
if (pr <= 0)
throw new PriceException("Price Should Be Greater Than Zero");
pid = pi;
pname = pn;
price = pr;
}
public void DispProduct()
{
Console.WriteLine(" Product ID:" + pid);
Console.WriteLine(" Product Name :" + pname);
Console.WriteLine(" Product Price :" + price);
}
Note: - You can also use the catch block without exception identifier, if you use the catch
block without exception identifier it is just similar to catch with exception as a parameter.
Namespaces in C#:-
Namespace is facility provided by C# using which you can logically group the classes, together.
Namespace allow you to implement the modularity inside your application.
Namespace can contain definitions of –
>Class
>Interface
>Delegates
>Structures
>Enumerations
Default access type or modifier of the namespace is public which can not be modified. By namespace
you will be able to create and maintain more than one type in C# having same name but define in
different namespace.
{
// create definitions here.
}
To use the namespace C# provides us using statement, it can be used as follows –
Using namespace name;
Namespace can contain the nested namespaces those can be accessed using dot operator (.) as –
Using namespace firstnamespace.innernamespace;
e. g.
using x;
will allow you to use all the definitions from x.
using x.y;
Will allow you to use all the definitions from y;
Structures:-
A structure in C# is simply a composite data type consisting of number elements of other types
(different type). C# structure is hybrid type since it is get created as value type on stack, so
member accessibility will be just like value type. By default structure members will not be get
- Structure can not implement inheritance means you can not inherit structure as well as structure
in class or class in structure etc.
- Structure can not contain default constructor, structure can have parameterized constructor.
- Structure can use the static keyword for methods, fields.
- Structure is light weight than class, hence used instead of class if there is less behavior.
e. g.
namespace Structures
{
struct item
{
public int itemid;
public string itemname;
public double itemprice;
public void setItem(int id, string nm, double pr)
{
itemid = id;
itemname = nm;
itemprice = pr;
}
public void dispItem()
{
Console.WriteLine("Item id :" + itemid);
Console.WriteLine("Item Name:" + itemname);
Console.WriteLine("Item Price :" + itemprice);
}
}
class Program
{
static void Main(string[] args)
{
item t = new item();
t.setItem(1, "Pen", 234);
t.dispItem();
}
}
}
>Interfaces consist of methods, properties, events, indexers, or any combination of those four
member types
> An interface cannot contain constants, fields, operators, instance constructors, destructors, or
types.
> It cannot contain static members. Interfaces members are automatically public, and they cannot
include any access modifiers.
> When a class or struct implements an interface, the class or struct provides an implementation for
all of the members defined by the interface.
> The interface itself provides no functionality that a class or struct can inherit in the way that base
class functionality can be inherited.
> However, if a base class implements an interface, the derived class inherits that implementation.
The derived class is said to implement the interface implicitly.
> You can not create the object of interface directly.
e. g. interface
namespace BiilSpecificationExample
{
interface billint
{
void GenBill(int bn, string cn, string fd, string td);
}
class msebbill : billint
{
private int meterno;
private int noofunits;
private int rateperunit;
public void SetBill(int mn, int nfu, int rpu)
{
meterno = mn;
noofunits = nfu;
rateperunit = rpu;
}
public void GenBill(int bn,string cn,string fd,string td)
{
Console.WriteLine("Bill No:" + bn.ToString());
Console.WriteLine("Customer Name :" + cn);
Console.WriteLine(" From Date :" +fd);
Console.WriteLine(" To Date:" + td);
Console.WriteLine("Meter No: " + meterno.ToString() );
Console.WriteLine(" N of Units :" + noofunits.ToString());
}
}
}
}
}
Generics in C#: -
Generic: this is facility provided by C#.net using which you can implement any thing that will be data
type independent. To implement the generic we have to type symbol that will be act as temp. data
type will be replaced by the actual data type. To use the generic you have to specify the type symbol
with class declaration –
Class classname <A,B> A!=B
{
A a;
B b;
}
e. g. Create stack class to push and pop the integers using array.
namespace StackExample
{
class gstack<A>
{
A [] data;
int top;
public gstack()
{
data = new A[10];
top = -1;
}
gt.push(23);
gt.push(45);
Console.WriteLine(gt.pop());
Console.WriteLine(gt.pop());
gstack<string> gtstr = new gstack<string>();
gtstr.push("Hello");
gtstr.push("Bye");
Console.WriteLine(gtstr.pop());
Console.WriteLine(gtstr.pop());
gstack<student> gstd = new gstack<student>();
student[] s = new student[3];
for (int i = 0; i < 3; i++)
{
s[i] = new student();
}
s[0].setstudent(1, "Ramesh");
E.g. Class which will have the search method implement that search method using generic.
namespace GenericSearch1
{
class search1<T>
{
public void search(T[] a, T n)
{
int f = 0;
for (int i = 0; i < a.Length; i++)
{
if (Convert.ToString (a[i])==Convert.ToString(n))
{
f = 1;
//Console.WriteLine("Element Found");
break;
}
You can apply restrictions to generic classes, by using where clause but you can restrict
the generic types only up to class, structure or interface.
UnBoxing: - unboxing is process which happens when you store reference (object type) of value back
to value type of variable.
e. g.
object obj=34;
int a=(int)obj;
While doing unboxing you have to explicitly type cast the value.
Collections
Collection is facility provided by the C#.net using which you can manipulate group of objects or
values using built in methods. C#.net provides you two types of collections generic and non generic
collections, generic collections are the collections those are data type independent and non generic
collections are not data type independent.
C# provides you so many built in collections those are generic and or of object type. What ever may
be the type of the collection it follows following ways to manipulate those collections –
Generic Collections: -
these are the collections implemented using generic concept capable to store any type of value.
> List , Stack, Queue are generic collection
To use the collections and generic collections you have to use the namespaces –
System.Collections;
System.Collections.Generic;
In general every collection will have following facilities –
Internally collection implements indexing mechanism using which you can refer the
collection elements, it always starts with zero.
It provides you following methods(general collection): –
Add: - to add the element.
Remove: - to remove the element.
Count: - property used to count how many elements are their.
Clear: - allow you to clear all the elements of the collection.
Contains: -allows you to find the element in a collection.
IndexOf: - will give the index number of the specified element.
Etc.
Notes: To use the collections you have to use the namespace system. Collections
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace HCollection
{
class emp
{
private int eno;
private string name;
public void setEmp(int no, string nm)
{
eno = no;
name = nm;
}
public void dispEmp()
{
Console.WriteLine("Emp No:" + eno);
Console.WriteLine("Emp Name:" + name);
}
}
In case of C# delegate you can store reference of static method or instance method who matches
the delegate signature, delegate in c# will not worry about the other details of the methods to create
the reference. Delegate can store reference of any method whose signature matches with delegate
type.
1 Delegates are just similar to function pointers in C++ but are type safe
2 Delegate type in case of C# is sealed.
3 Delegates allow you to send the methods as a parameter to the functions.
4 Delegates are used to implement the events.
5 Due Covariance and Contra variance method does not need to be match delegate signature
exactly.
6 Delegates allow you to implement and use Anonymous methods.
Anonymous Methods: - Anonymous methods are the methods without name, just a code method
code block without any kind of functions specifications. By using anonymous methods, you reduce
the coding overhead in instantiating delegates by eliminating the need to create a separate method.
e. g. Delegate Example
namespace DelegateExample
{
public delegate void Test();
public delegate int TestM(int a,int b);
public delegate void TestR(bool b);
class Method
{
public void Method1()
{
Console.WriteLine(" Method 1 invoked");
}
public int Method2(int a, int b)
{
Console.WriteLine("Method2 Invoked");
return a+b;
}
public void Method3(bool t)
{
Console.WriteLine("Method3 invoked");
}
public int Method4(int a, int b, int c)
{
Console.WriteLine("Method4 invoked");
class Program
{
Lambda Expressions:-
Lambda Calculus is formal system for function definition, function application and recursion it was
introduced in 1930. The expressions developed using Lambda Calculus area called Lambda
Expressions (pronounced Expression Lambda).
All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the
lambda operator specifies the input parameters (if any) and the right side hold the expression or
statement block. The lambda expression x => x * x is read "x goes to x times x."
Lambda Expression:-
Without parameters: () => expression
With One Parameter: (parameter) => expression
With Two parameters: (parameter1, parameter2) =>expression
Lambda Statements: parameters => {Statements}
Advantages:-
Help to reduce the complexity of the anonymous methods, Executes faster than normal sequential
statements.
e. g.
namespace LExpessions
{
public delegate void Test();
public delegate int TestM(int a, int b);
public delegate void TestR(bool b);
class Program
{
static void Main(string[] args)
using System;
namespace MultiCastDelegateEx
{
public delegate void Tdel(int a,int b);
class MathC
{
public void addNum(int a, int b)
{
Console.WriteLine(" Addition is : " + (a+ b));
}
public void mulNum(int a,int b)
{
Console.WriteLine(" Multification is : " + (a * b));
}
public void divNum(int a, int b)
{
Console.WriteLine(" Division is :" + (a / b));
}
}
class Program
{
static void Main(string[] args)
{
MathC mc = new MathC();
Tdel td =mc.addNum;
td += mc.mulNum;
td += mc.divNum;
td(200, 10);
Events: -
Events are the process by which object notify about some change or activity or user action to the
application. Event will be generally a member of the object which enables object to notify some
change or activity. All GUI based applications are event based, without event we can not implement
the events. Event is best way to implement inter process communication. Event processing involves
two classes one who publish events those can be used by another class to subscribe or register its
methods called event subscriber. So when that event occur the method who had registered to that
will be invoked automatically. Event does not know which method is going to handle or execute the
code when event occurs hence we have to use the delegates so that any method can be invoked
when event occurs automatically.
// publisher class
class EventPublisher
{
public event EventDel customevent;
public void Execute()
{
customevent();
}
}
// class FirstSubsc
class FirstSub
{
public void FirstHandler()
{
Console.WriteLine("First handler executed ");
}
}
class SecondSub
{
public void SecondHandler()
{
Console.WriteLine("Second Hander Executed ");
}
}
class Program
{
static void Main(string[] args)
{
methods into the existing String class you can do it quite easily. Here's a couple of rules to consider
when deciding on whether or not to use extension methods:
e. g. Extension methods
namespace ExtensionMethods
{
public static class ExString
{
public static string CapChar(this string s, int i)
{
char [] temp = s.ToCharArray();
if (s.Length > i)
{
for(int j=0;j<s.Length;j++)
if (i == j)
{
if (Char.IsLower(temp[j]))
temp[j]= Char.ToUpper(temp[j]);
}
}
string t="";
for(int k=0;k<temp.Length;k++)
t+=temp[k].ToString();
return t;
}
}
}
.NET Reflections:-
Assemblies contain modules, modules contain types, and types contain members. Reflection provides
objects that encapsulate assemblies, modules, and types. You can use reflection to dynamically
create an instance of a type, bind the type to an existing object, or get the type from an existing
Attributes in C#:-
Attribute facility provided by C# allow you to specify extra information about C# type that can not be
specified while decleration or defination of that type. C# Attributes can be used with–
> Types
>methods
> Properties
Etc.
You can restrict the attribute uses by using attributeuses tag, you can restrict attribute uses to -
> Class
> Struct
> Enum
> Method
> Property
Etc.
To create the attributes you have to create a public class which inherits form the attribute class. It
should contain public constructors and positional or named paramters. It can have following types of
paramters –
> Simple types (bool, byte, char, short, int, long, float, and double)
> String
> System.Type
> Enums
>object (The argument to an attribute parameter of type object must be a constant value of one of
the above types.)
> One-dimensional arrays of any of the above types
e. g.
using System;
namespace AttributesExample
{
[AttributeUsage(AttributeTargets.All)]
class HelpAttribute:Attribute
{
private string _version;
private string _mgname;
public string Version
{
HTML Tags:-
HTML tags are used to mark-up HTML elements
HTML tags are surrounded by the two characters < and >
The surrounding characters are called angle brackets
HTML tags normally come in pairs like <b> and </b>
Layout Tags:-
Html provides you following layouts –
1. Table : - <table> tag is used for table layout, which is fixed layout attached with
borders of the container.
2. Div: - <div> tag is used for floating layout, the layout that is not attached to the
borders of the table.
3. Frame (Not used in ASP.NET): - allow you to divide the browser area into sections
where you can load another html documents or web supported files, this is attached
with the borders.
4. IFrame(Not Used in ASP.NET): - allow you to divide the browser area into sections
where you can load other html documents which is floating, not attached with the
borders of the browser.
HTML Tables:-
To create tables in HTML we use the <Table> tag with </Table>. Table tag is used to
represent the tabular format of data (data in rows and columns).
Table tag has following attributes:-
Bgcolor: - Allow you to specify the background color to the table.
Background: - allow you to specify the URL of the image that will be displayed in
background.
Width: - Allow you to specify the numeric value to decide the width of the table in pixel.
Height: - Allow you to specify the height of the table in pixel.
Cell Padding: - allow you to specify how much space should be left blank between the
content of the cell and the borders of the cell.
Cell Spacing: - allow you to specify the space that should be left between two cells of the
table.
Border: - allow you to specify the thickness of the border, 0 means now border.
Align: - can take values right, left or center to align the table in page.
Brodercolor: - you can specify the border color here.
Table Architectures:-
Table contains rows and rows contains cells. Cells can be of two types – (Heading / Normal).
As Table -> Rows -> Cells (Threading / Normal).
Rows (<TR> </TR>):- rows will be created using the <tr> tag. Rows can contain the table
data or heading. TR tag has following attributes –
Align: - allow you to specify values left,right or center to align the content of the row.
Bgcolor: - Allow you to specify the background color to the row.
Cells :- Html table row can contain the cells of tow types the cells for heading and the cells
containing the data. The cells containing the heading can be defined using tags <th>
</th> as follows –
<th> hading of cell or coloumn </th>
The cells containing the cell data can be defined using tag <td> </td> as follows –
<td> data </td>
To create the html form in html document we use the form tag as follows –
Form Elements:-
Html elements are html tags using which you can create the graphical components; those
can be used to accept the input from the user. Html form can have the following elements to
accept the input from the user –
A. Input Tag: - input tag is used to provide user html elements (controls) using which user
can provide the input (data, event) has following syntax –
Where
Type: - is used to specify what type of input you want to create. Html provides you following
types –
Text: - is used if you want to provide the Text Field (Editable Rectangular Area) to the
user where user can input data. By default size of the Text Field in most browsers will be 20
characters. Can be used as follows –
Button: - is used if you want to provide user button where user can click to generate the
click event. It can be used as follows –
Submit: - is used if you want to provide such button when user click on this button it will
submit form automatically to the server. It can be used as follows –
Reset: - is used if you want to provide the button when you click on that button the content
of the form will be get automatically cleared or all the values of the html elements present
on the form will be get cleared. It can be used as follows –
Radio: - is used if you want to provide the user the options and where from user can select
only on at a time. When we say options we have to create the multiple radio buttons every
button from which provides some option where from user can select only one at a time. In
case of radio buttons user can select only one from the group of radio buttons only if name
attribute value of the radio button will be same for all radio buttons.
Checkbox: - This is used if you want to show the check box in your website, checkbox are
again used to provide the options to the user where from user can select multiple at a time.
File:-allow you to create the file upload box that can be used to upload the files to the server.
Hidden: - Allow you to store some value in html form that will be submitted to the server
but will not visible to the user.
TextArea tag: - Text Area tag allows you to display the muti column and multi row box
where user can input multiple line of text. It can be used as follows –
<TextArea name=”ta” cols=”value” rows=”value”> </TextArea>
Select tag: - Select tag allows you to create a facility where from you can provide the options
to the user where user can select one or multiple. Select will contain the options those can
be created using the options tag. It can be used as follows –
<select >
<option> First Option </option>
<option> Second Option </option>
<option> Third Option </option>
<option> Fourth Option </option>
</select>
CSS:-
Cascading Style Sheet is a web technology which provides you huge amount of attributes
those attributes can be used to format the content of the html tags.
Html tags has very less amount of attributes those attributes does not allow you to create
the complex design hence we use the CSS. Cascading style sheets those can be used to
generate or extend the attribute capabilities of the browser to generate the complex
presentation structure of the html document. Collection of CSS attribute placed together in
file is called Style Sheet.
CSS attribute can be applied directly to html tag using style attribute or using selectors.
All CSS attributes are in small case and their values are also in small case, when ever you
use the attribute and value together those should be separated using : operator and if you
want to use more than one attributes those should be separated using ;.
In case of css class name always starts with dot (.). Then you will have the freedom to use
those classes according to your requirements as follows –
<tag class=”name of class without dot”> Content </tag>
e.g. implement above example with inline style classes.
<html>
<head>
<title>Div Ex2 </title>
<style>
.head
{
background-color:red;
color:white;
}
#admin
{
background-color:blue;
color:white;
}
.test
{
background-color:cyan;
}
</style>
</head>
<body>
<h1 class="head"> Heading with style </h1>
<h1> heading without style </h1>
<table id="admin">
<tr> <td> Table with style </td> <td> Table with style </td> </tr>
</table>
External CSS:-
in case of external style sheet we define the external file which contains the css style which
can be style with tag or style with class. In case of external style sheet you will get the
flexibility to apply it to any html document according to your need. To use the external style
sheet we have to use the link tag as follows –
You have to place this tag in head section of the html document.
E.g.
Creating CSS file with name “MyCSS.css” with following content -
h1
{
background-color:orange;
font-size:14px;
color:blue;
}
p
{
background-color:yellow;
font-size:16px;
color:orange;
}
table
{
border-style:solid;
border-width:2px;
border-color:yellow;
background-color:#000aaaa;
}
.admin
{
background-color:navy;
height:100px;
weight:100px;
}
Creating html file where we want to apply “MyCSS.css”
HTML DOM has following structure or tree of objects or elements those can be accessed by
javascript or vbscript.
Window
Right know we should have to worry about only document object, document object provided
by DOM will have following methods –
getElementByID(id): - will return you reference of element if found by id.
getElementByName(name): - will return you reference of element if found by name.
getElementByTagName(name):- will return you reference of element if found by tag name.
A. Client Side Scripting: - the programs or code blocks those will be executed on the
client (in web browser), using which we can provide some dynamic ness to the exiting
html representation of the data. Some are the popular client side scripting languages
are javascript, vbscript etc.
B. Server Side Scripting: - these are the small script code block those will be executed
on the server computer. This is generally used to process data sent from the client to
the server. It will be executed on the server by the special program called web server.
Some of the popular scripts are php, asp, jsp etc.
HTML SCRIPT TAG:-to use the client side scripting in the html document the html
provides us script tag can be used as follows-
<script language=”langaguge name” >
Script code
</script>
You can place the script tag any where in the html document but in general we place
the script tag in head section of the html document.
Variables in JavaScript: - to create the variables in java script we use the following
syntax –
var variablename[=initial value];
var statement is used to create the variable in javascript. Javascript variables will be of
variant data type.
Input: - To accept the input in javascript we have two ways, you can use the html controls
like input. Java script also has a function called prompt used to accept the input from the
user.
prompt:- prompt function of java script is used to accept the input from the user. It shows
you the rectangular box using which you can accept the input from the user. It has following
syntax-
prompt(“Message”,”Title”);
prompt returns you string type of the value.
Output: - to generate the output from the javascript, we have two ways –
1. document.write: - write method of the document object from the dom model
can be used to write some content on the client browser.
2. alert: - alert box is used to show the message to the user in a box with ok
button. It has following syntax –
alert (“Message”);
e. g. Accept two numbers from the user using prompt and display it’s addition.
e.g. Accept a number from the user and display weather it is odd or even.
<html>
<head>
<title> Even and odd digit </title>
<script language=”javascript”>
var num;
num = parseInt(prompt(“Plz enter number”));
if(num%==0)
alert (“Even”);
else
alert(“Odd”);
</script>
</head>
<body>
</body>
</html>
B. while loop:- used when you do not know how many times the given loop is going to
execute. It has following syntax –
while(condition)
{
Statements;
}
C. do-while loop:- used when you want to execute the loop at least for one time and
later execution depends on condition.
do
{
Statements;
}while(condition);
break and continue Statement:- break and continue statements is used to break the loop or
continue the execution of the loop just similar to c and c++.
e .g. for loop (write a program Number is prime or Not)
<html>
<head>
<script language="javascript">
var nm,cnt,f=0;
nm=parseInt(prompt("Plz Enter Value"));
for(cnt=2;cnt<nm;cnt++)
{
if(nm % cnt==0)
{
f=1; break;
}
}
if(f==1)
alert("Not an prime number");
else
alert("Prime number");
</script>
</head>
<body>
</body>
</html>
e. g. while (accept a number from the user and display the addition of digits of that
number)
Write a program Number is prime or Not
}
var max=ar[0];
for(cnt=1;cnt<10;cnt++)
{
if(max < ar[cnt])
max =ar[cnt];
}
alert(max);
</script>
</head>
<body>
</body>
</html>
Functions: - just like c you can also create the functions in java, to create the functions in
java we use function keyword with the name of the functions you can also return the value
HTML Form elements and Event Handling: - Html provides you the form which will
have the elements those ca n be used by the javascript for any kind of processing using
DOM. While accessing the form elements in javascript we have to follow
document.form.element structure where we can access the value of that element. There is
no use of access the elements in normal script block of javascript, instead of that we can
access it in a javascript function and that functions can be called on any of the html
elements events.
HTML Elements (Controls Events):- All html events start with on keyword. Html elements
supports following events –
OnClick: - will occur when you click the button or hyper link or submit or reset button.
OnDblClick: - will be executed when you double click on the html form element.
OnBlur: - it will occur when you move the courser from given control out or in.
OnFocus: - it will be executed when you move the cursor inside the control.
OnKeyUp: - it will be executed when you pressed key is in up state.
OnKeyDown: - it will be executed when you press the key.
OnKeyPresss: - will be executed when you press or release the key.
OnMouseOver: - will be executed when you move the mouse over the control.
OnmouseOut: - will be executed when you move the mouse out from the control.
Onload: - will be executed when the page get loaded.
OnSubmit: - will be executed when you submit the form.
OnReset: - will be executed when you reset the form.
E.g.
<html>
<head>
<title> Addition of numbers </title>
<script language=”javascript”>
function DoAddition() {
var fnum = parseInt(document.additionfrm.firstnumber.value);
var snum= parseInt(document.additionfrm.secondnumber.value);
<html>
<head>
<title> Select Ex </title>
<script language="javascript">
function opr() {
var v=document.frm.op.value;
var a,b,c;
a= parseInt(document.frm.fn.value);
b= parseInt(document.frm.sn.value);
switch(v)
{
case "+":
c=a+b;
break;
SQL Server
DBMS: -
A database management system (DBMS) is a software package with computer programs
that control the creation, maintenance, and use of a database. It allows organizations to
conveniently develop databases for various applications by database administrators (DBAs)
and other specialists. A database is an integrated collection of data records, files, and other
objects. A DBMS allows different user application programs to concurrently access the same
database. DBMSs may use a variety of database models, such as the relational model or
object model, to conveniently describe and support applications. It typically supports query
languages, which are in fact high-level programming languages, dedicated database
languages that considerably simplify writing database application programs.
DBMS maintains data only in tabular format; it was having some draw backs so computer
scientist had developed RDBMS Software.
RDBMS:-
RDBMS stands for Relational Database Management System. RDBMS data is structured in
database tables, fields and records. Each RDBMS table consists of database table rows.
Each database table row consists of one or more database table fields.
RDBMS store the data into collection of tables, which might be related by common fields
(database table columns). RDBMS also provide relational operators to manipulate the data
stored into the database tables. Most RDBMS use SQL as database query language.
Edgar Codd introduced the relational database model. Many modern DBMS do not conform
to the Codd’s definition of a RDBMS, but nonetheless they are still considered to be
RDBMS.
The most popular RDBMS are MS SQL Server, DB2, Oracle and MySQL
Every RDBMS has following two important features –
Every RDBMS supports a Database Independent Programming Language, which allows you
to manipulate the data by writing commands.
Every RDBMS stores data only in the form table, everything that exits in RDBMS will be in
the form of table.
DDL: - data definition language provides you commands, and queries using which you can
create the structure of database or db.
DCL: - data control language provides you command using which you can control inflow and
outflow of the data from database.
DML: - data manipulation language provides you command using which you can
manipulate the data from database.
DDL: -
Data Definition Language, which provides us following, set of statements. DDL gives
you Create, Alter and Drop statements can be used to create, modify and remove database
objects as follows –
Create Table: - this statement is used to create the table, can be used as follows –
Create table tablename (fieldname data type (Size), fieldname datatype (Size),
fieldname datatype (Size) ….)
Identity: - this is facility provided by SQL server using which you can generate the
automatic numbers where first value indicates seed and next value indicates the
increment(e.g. identity(seed, increment).
DML: -
It provides you following set of statements where used to manipulate the data –
Select: - this statement is used to fetch the data from the databases. It can be used as
follows –
Select [top n] * /field names from table name where condition order by field name1, field
name2 group by fieldname1, fieldname2 having condition.
Simple select:-
Select * from tablename;
This will select all the records and all columns from the specified table.
e. g. select * from emptbl
Column Filter:-
You can apply the column filter, to the selected data from the column as-
Select column_name1, column_name2 … from table_name.
Top clause: - T SQL provides you top clause, using which you can select the specified
number of top records from the database, it can be used as follows –
e. g.
Select top 3 from table_name;
Condition: - conditions are generally used to filter the rows. In case of T SQL we can use
the conditions with where clause we can use the relational operators (>, <=, >=,!=, ==, >), we
can also use the logical operators (and , or , not), beside this the TSQL provide us following
operators for conditions –
Like: - is used to find the pattern of strings.
And between: - is used to find the value between the specified range.
Not in: - check the existence of the specified value in given list of data.
In: - check the existence of the specified value in given list of data.
Exists: -
This is used with inner queries, to find out the existence of the record in database.
e. g.
select * from empttbl where emp_salary >1000.
This will select all information of employee whose salary is greater than 1000.
select * from empttbl where emp_salary between 1000 and 10000.
This will select all the information of employee whose salary is in the range >=1000 and
<=10000.
This will select all information of employee whose name starts with R and contains any
number of characters.
Group by: - is used to group the data selected using select so that we can apply the
aggregate functions to find the summary of the data. We can use the following aggregate
functions as follows –
Avg: - average is used for finding the average of the data.
Sum: - to find the sum of data
Count: - to count the number of records.
Min: - to find the minimum
Max: - to find the maximum
This will display all the cities and total salary paid to employee from that city.
Insert Statement: - Insert statement is used to add the new data in database table. It can
be used as follows -
Insert into tablename( List of fields) values(List of values).
Here list of fields, will be optional if you want to insert all the values.
Update Statement: - update is DML statement used to update the data from the database.
It is used as follows –
e. g.
Consider following structure –
Select * from emptbl where areaid = (select Areaid from araetbl where
areaname=’nigdi’)
This query will first find the areaid of the nigid and then it will find out the
employee details.
Suppose now you want to find out the information of employees leaving in area
nigdi, pimpri, pune then you can not use the equal to operator in inner query.
Query can be created and used as follows –
Select * from emptbl where araeid in (select areaid from areatbl where areaname
in(‘nigdi’,’pimpri’,’pune’);
DCL: -
DCL is used to control the inflow and outflow of the data. It also defines the accessibility of
the data. Basically here we apply the constraints, or we define the permissions to the users.
2. Foreign key: -
This constraints forces referential integrity ( i.e. when you define the foreign key constraint
it will take values from only specified column which should be created using primary key
constraints), it can take duplicate values.
5. Unique: -
This will allow forcing the column value to be unique.
create table student(sid bigint primary key,sname varchar(30) unique, address
varchar(30))
6. check: -
This constraint allows you to specify any condition that will be checked for specified field
value.
You can also use the alter statement to alter the constraints those can be used as follows -
CityTbl AreaTbl
CityId AreaID
CityName AreName
CityID
DeptTbl Employee
DeptID EmployeeID
DeptName EmployeeName
AreaID DeptId
Address
Phone
Salary
Q3. Display all employees working in computer department and pune city.
Asn:-
select * from employee where deptid in (select deptid from depttbl where areaid in
(select areaid from areatbl where cityid=(select cityid from citytbl where
cityname='Pune'))
and deptid =(select deptid from depttbl where deptname='Computer')
Q4. Update salary of all employees by 10% working computer department from
city mumbai.
Ans:
upate employee set salary=saalry + salary*0.1 where deptid in (select deptid from
depttbl where areaid in (select areaid from areatbl where cityid=(select cityid from
citytbl where cityname='Mumbai'))
and deptid =(select deptid from depttbl where deptname='Computer')
1. Inner Join: -
This join allow you to fetch data from more than one table if the matching data present
into both the tables on join field. To create the inner join we use the following syntax -
Outer join:-
Outer joins are used when you want to get the dat from both the tables. Outer join is
classified into following types of joins –
e. g.
select atbl.*,btbl.* from atbl left outer join btbl on atbl.aid=btbl.aid
It will fetch all records from atbl and only matching records from btbl.
It will fetch all records from btbl and matching records from atbl.
e.g.
select atbl.*,btbl.* from atbl full outer join btbl on atbl.aid=btbl.aid
It will fetch all records from atbl as well as btbl and replace remaining by null if there is no
match.
Cross Join: -
When you implement the Cross Join
It will preform the cross product of the records , in case of cross join we does not require on
clause
e.g.
It fetch all records for the single record of atbl from btbl.
Self Join:-
We create join in same table on same field or diff field. Self join can be inner join/left outer
join/right outer join/full outer join but it should be on same table (only on table involved in
join), here you have to use the alias since same table name cannot be used on both the side
in on clause.
e.g.
select A.* from btbl as A inner join btbl as B on A.aid =B.aid
Join Examples:-
T-SQL Inner Join example:
We have two tables: Orders and Products. The Orders table has the column orderdate and
we want to see the date each productsku is ordered on. The way to do this is INNER JOIN
with the Products table. Now will will see the date that each productsku was ordered on.
We have two tables: Products and OldProducts. We want to see all the oldproducts.sku that
are in the products table. A LEFT JOIN will shows every products.sku and all the matching
oldproducts.sku
We have two tables: Products and OldProducts. The RIGHT JOIN in the example will show
us every oldproducts.sku and any products.sku that match.
PL/SQL is a small set of programming constructs using which you can write the programs
which are suppose to manipulate the data from databases. In case of SQL server to write
the pl/sql block we use keywords -
Begin
SQL Statements or PL SQL Code.
End
Built in Variables: -
These variables are being provided by the SQL server we can write the value in them, but
we can read the value. All built in variables will starts with @@ symbol.
e.g. declare @num int
Output Statement: -
Plsql provides us the statment print using which you can output string or varchar type of
data can be used as follows -
print 'Message'
Convert:
Convert function allow you to convert from one data type to another data type can be used
as follows -
convert(datatype,value)
It will convert the specified value to specified data type.
Conditional Statements:-
Imposes conditions on the execution of a Transact-SQL statement. The Transact-SQL
statement that follows an IF keyword and its condition is executed if the condition is
satisfied: the Boolean expression returns TRUE. The optional ELSE keyword introduces
another Transact-SQL statement that is executed when the IF condition is not satisfied: the
Boolean expression returns FALSE.
Only if:-
IF Boolean_expression
Begin
Statements
End
Will handle only true part of the condition, begin and end is needed only if there is more
than one statement.
If and Else:-
IF Boolean_expression
Begin
sql_statement | statement_block
End
ELSE
Begin
sql_statement | statement_block
End
Looping :-
PLSQL provides you the while loop using which we can perform the repeat.
It can be used as follows -
while(condition)
Begin
Statements
End
With while you can use breaks and continues statement to break and continue the loop.
Program:-
DECLARE @Counter Int
SET @Counter = 1
WHILE @Counter < 4
Begin
Declare @nm varchar(30)
Declare @ad varchar(30)
select @nm=cust_name,@ad=cust_address from custtbl where cust_id=2
print 'Customer Name :' + @nm
print 'Customer Address : ' + @ad
End
Calling Function -
Begin
Declare @c int
set @c=dbo.addnum(12,23)
print 'Value is' + convert(varchar,@c)
End
Calling:-
begin
declare @sn varchar(30)
set @sn=dbo.getroll(4)
print 'Student Name' + convert(varchar,@sn)
end
-> Self executable code block (can be called from font end application)
-> Stored as a database object in database.
-> Compiled once and executed again and again.
-> Maintains internal transaction.
To create the stored procedure we use the following syntax –
Create procedure procedurename(parameters)
as
Begin
Statements
End
Where parameters can be three types –
In: - it is default type, means when do not specify any parameter type, it will be by default
in used for getting the value of parameter inside the procedure.
e.g.
create proc procsq(@num as int,@sq as int out)
as
begin
set @sq= @num * @num
end
begin
declare @s int
exec procsq 12,@s out
print 'Squre is:' + convert(varchar,@s)
end
e.g.
Create proc incnum(@n as int out)
as
Begin
set @n=@n + 10
End
Begin
Declare @v int
set @v=12
exec incnum @v out
print 'Value is' + convert(varchar,@v)
end
e.g.
Create procedure which accept the employeeid and display the total salary of that
employee.
Create procedure which will display the employeenames and total salary from
specified department
alter proc procacc(@empid as int)
e.g.
alter proc dept(@depnm as varchar(30))
as
begin
declare @empn varchar(30)
declare @bs as bigint
declare @hr as bigint
declare @t1 as bigint
declare @d1 as bigint
declare @de as bigint
declare @gros as bigint
declare @deptname as bigint
select
@empn=emp_name,@bs=Basic_sal,@hr=hra,@t1=ta,@d1=da,@de=d
educ
from emptbl inner join empsaltbl
on emptbl.emp_id=empsaltbl.emp_id where emptbl.dept_id=(select dept_id from
depttbl where dept_name=@depnm)
set @gros = (@bs+@hr+@t1+@d1)-@de
print 'empname: '+ @empn + ' grosssal:'+
convert(varchar,@gros)+' deptname=>'+@deptname
end