Windows

January 7, 2017 | Author: Rakesh Gundu | Category: N/A
Share Embed Donate


Short Description

Download Windows...

Description

Deccansoft Software Services – MS.NET

Overview of .NET Framework

According to Microsoft .Net is a platform built on open internet protocols & standards with tools and services that meld computing and communication in new ways It’s an environment for developing and running software applications featuring ease of development of web based services, rich standard runtime services available to components written in variety of programming languages & provides inter language & inter machine inoperability The .NET Framework is a new computing platform that simplifies application development in the highly distributed environment of the Internet. The .NET Framework is designed to fulfill the following objectives: • Preserve consistency between objects that are stored and executed locally, objects that are Internet-distributed but are executed locally, and objects that are stored and executed remotely on a server. • Avoid deployment and versioning conflicts. No DLL update upon deployment. Solves the DLL Hell Syndrome. • Guarantee safe execution of code, even if written by unknown semi-trusted third party. Avoid the slowness of scripted or interpreted languages. • Preserve development environment consistency between windows-based applications and webbased applications. The .NET framework includes two main components: 1. The .NET Class library 2. The Common Language Runtime. .NET Base Class Libraries (also called as Framework Class Libraries (FCL) The .NET base class library is a collection of object-oriented types and interfaces that provide object models and services for many of the complex programming tasks you will face. Most of the types presented by the .NET base class library are fully extensible, allowing you to build types that incorporate your own functionality into your managed code. These class libraries are distributed with MS.NET Framework and works with any language under the common language runtime environment. Therefore if you are familiar with one .NET language then you can easily migrate to other .NET Languages All the base class libraries are grouped under the root namespace System. Namespace: A namespace is a logical collection of classes and other types with unique name. The structure of the namespace is like a tree where all the related classes are like leaves. The most important namespaces in the .NET class library are: • System • System.IO • System.Collections • System.Threading • System.Reflection • System.Security • System.Net • System.Data • System.XML • System.Web • System.Web.Services • System.Windows.Forms • System.Drawing • System.Globalization • System.Resources

1

Deccansoft Software Services – MS.NET

Overview of .NET Framework

CLR (COMMON LANGUAGE RUNTIME)

CLR is the foundation of .NET Framework. The common Language Runtime manages code at execution time. It does Memory management, thread management, and runs the code on different platforms (Client or Server). It enforces strict variable type definitions, security, and robustness. CLR provides the following benefits for the application developers: • Vastly simplified development. • Seamless integration of the code written in various languages. • Evidence-based security with code identity. • Assembly-based deployment that eliminates DLL Hell. • Side-by-side versioning of reusable components. • Code reuse through implementation inheritance. • Automatic object lifetime management. • Self describing objects. CLR is a component divided in sub components which perform their own respective tasks. CLR as the name specifies provides a common runtime environment for different languages like VC++, C#, VB.NET, J# and JavaScript. The code written in these languages is compiled with their respective language compliers to give a common intermediate language called MSIL (Microsoft Intermediate Language) and Metadata. This files generated are called as PE (Portable Executable). The CLR is a multi-language execution environment MS Intermediate Language: MSIL is an intermediate instruction set which is processor and hardware independent. The source code when compiled gives MSIL which is an input to the operating system and with the help of CLR is converted into native code which is processor specific. Microsoft supply a tool called Ildasm, which can be used to view the metadata and IL for an assembly. Source code can be reverse-engineered from IL, it is often relatively straightforward to regenerate high-level source (e.g. C#) from IL. You can write IL programs directly, for example: .assembly MyAssembly {} .class MyApp { .method static void Main() { .entrypoint ldstr Hello, IL!" call void System.Console::WriteLine(class System.Object) ret } } Note: Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will be generated.

2

Deccansoft Software Services – MS.NET

Overview of .NET Framework

Portable Executable (PE) is a Microsoft Win32 compatible format file for .Net applications which contains the MSIL code and Metadata in binary form. It has the extension .exe or .dll. PE has COFF (Common Object File Format) specification. Metadata: Metadata is the information that describes every element managed by the runtime i.e. an assembly, a loadable file, type, methods etc. This can also include information required for debugging and garbage collection, security attributes, marshalling data, extended classes and member definitions, version binding etc. To enable the runtime to provide services to managed code, language compilers must emit metadata that describes the types, members, and references in your code. Metadata is stored with Code; every loadable common Language runtime Portable Executable (PE) file contains metadata. The runtime uses metadata to locate and load classes, lay out instances in memory, resolve method invocations, generate native code, enforce security, and set run-time context boundaries. What is Type safety? Defining the data types in a language to be specific and strict in their behaviour. Datatypes are different in different languages and hence cannot be compiled with a single compiler. In .net languages CLR takes the responsibility of verifying the typesafety of the code being executed both at compile time and runtime. Hence the code is Managed. CTS (COMMON TYPE SYSTEM) CTS is the main component of the CLR. It is a specification where different datatypes are defined. This .net datatype collection is used by the language compilers to map the language datatypes to datatypes defined in CTS. This ensures the interoperability at runtime as the code written in one language when invoked from another language would not be misinterpret the data because the calling language datatypes would map the same CTS datatypes to which the called language datatypes are mapped. CTS provide a framework for cross-language integration and address a number of issues: • • •

Similar but subtly different, types (for example, Integer is 16 bits in VB6, but int in C++ is 32 bits; strings in VB6 are represented as BSTRs and in C++ as char pointers or a string class of some sort; and so on) Limited code reuse(for example, you can’t define a new type in one language and impart into another language) Inconsistent object models.

For example, an integer variable in C# is written as int, whereas in Visual Basic it is written as integer. Therefore in .Net Framework you have single type called System.Int32 to interpret these variables. Similarly, for the ArrayList datatype .Net framework has a common type called System.Collections.ArrayList. In .Net Framework, System.Object is the common base type from where all the other types are derived.

3

Deccansoft Software Services – MS.NET

Overview of .NET Framework

COMMON LANGUAGE SPECIFICATION CLS = Common Language Specification. This is a subset of the CTS, which all .NET languages are expected to support. The idea is that any program, which uses CLS-compliant types, can interoperate with any .NET program written in any language. The CLS is a set of constructs and constraints that serves as a guide for library writers and compiler writers. It allows libraries to be fully usable from any language supporting the CLS, and for those languages to integrate with each other. The CLS is a subset of the CTS. The CTS is also important to application developers who are writing code that will be used by other developers. When developers design publicly accessible APIs following the rules of the CLS, those APIs are easily used from all other programming languages that target the common language runtime. In short, this allows very tight interoperability between different .NET languages, for example allowing a C# class to inherit from a VB class. NOTE: CLS is not a part of CLR Specification. Few .NET Framework Supported Languages: APL, C++, C#, COBOL, Component Pascal, Curriculum, Eiffel, Forth, Fortran, Haskell, Java Language, Microsoft Jscript, Mercury, Mondrian, Oberon, Oz, Pascal, Perl, Python, RPG, Scheme, Small Talk, Standard Ml, Microsoft Visual Basic. JIT (JUST IN TIME COMPILER) JIT compiler compiles the managed or MSIL code into native code. JIT compiles only the required code for execution i.e. as the code is being visited for execution and also the compiled code is cached so that if the block of code is called again the same cached copy is directly executed. Advantage of managed code being compiled in small required fractions is processor time. There are three types of JIT compilers • Standard JIT • Econo JIT = Standard JIT – Caching (this is ideal for small devices) • Pre JIT Standard JIT: This compiles a block of code as it is visited for execution. The compiled code is cached so that the subsequent call to the same block of code is directly reused. Pre JIT: was planned in the initial draft of .NET but was never supported instead Microsoft provided a utility program called NGen.exe (Native Generator) the complete MSIL code is compiled to native code for that machine and is stored in GAC (GLOBAL ASSEMBLY CACHE) The advantage being the first time execution is also very fast because its already in precompiled form, but the output of the NGen is not portable and is always machine dependent. Note: we don’t have any facility to set our choice of JIT. For desktops Standard JIT is used and for Compact devices Econo JIT is used.

Garbage Collection The variables in the application can be allocated memory either in Global memory or Stack memory or Heap memory. All global variables are allocated memory when the program starts execution and would remain in memory for the lifetime of the application. All local variables and parameters of a function are allocated memory when the function is called and they are deallocated memory automatically when the function returns. Heap memory is used for all dynamic memory requirements i.e. variables like pointers for which until runtime we don’t know the amount of memory required would be allocated memory from the heap. But the size of heap is limited and all allocations done on heap must be also deallocated when that pointer doesn’t need the memory anymore. The deallocated heap memory then can be used for another pointer dynamic memory allocation. Memory Leakage: If some pointers are allocated memory on the heap and are never deallocated from the heap before the pointer itself goes out of scope then such memory can never be freed and would remain as Leakage from the heap as it cannot be allocated to another pointer. In .Net the memory de-allocation in .Net is handled by Garbage Collector. It gets activated when the heap is full and there is a need for release of memory. Garbage Collector a background thread running within the application / CLR and is responsible for destroying all the

4

Deccansoft Software Services – MS.NET

Overview of .NET Framework

unreferenced objects (objects which are no longer in use). When garbage collector is initiated all other threads running within the application are temporarily suspended and hence the sooner the garbage collector finishes its job the better would be the performance of the application. To optimize the work of garbage collector Microsoft has divided the heap memory into three equal parts called Generations: GEN0, GEN1, and GEN2. This is compact garbage collection. New objects are always created in GEN0 and are promoted to other generations based on their lifespan. Long lived objects would be destroyed last as these objects would move from GEN0 to GEN1 and from GEN1 to GEN2. Note: In .net the address of object can changes at runtime as it goes from one generation to another. In .Net the object once created are never guaranteed to be destroyed because they might get promoted to higher generations and GC would not visit those generations as memory is mostly available in lower generations itself.

Security Manager Security manager is a component in CLR. There are three types of security models supported in .Net. • Code Access Security(CAS) • Role Based Security • Asp .Net Web Application Security. Code Access Security CAS determines whether or not a piece of code is allowed to run and also what resources to use. For example, CAS will prevent malicious code from entering your system and causing havoc. It is an integrated security model that grants permission to resources based on evidence and the evidence may include 1. From where the assembly is being loaded. 2. If downloaded from web what is the URL of the source directory? 3. What is the Strong Name 4. Who is the publisher, if digitally signed? The CAS security policy revolves around two key concepts - code groups and permissions. Each .NET assembly is a member of a particular code group and each code group is granted the permissions specified in a named permission set. An example: Using the default security policy, a control downloaded from a web site belongs to the 'Zone - Internet' code group which complies with the permissions defined by the 'Internet' named permission set. Microsoft defines some default policies but you can modify these and even create your own. To view the code groups defined on your system; Run 'caspol' from the command-line and checkout the different options on display When a program code is using another code from another machine the security manager in CLR is responsible for managing the implementation of CAS based on the identity or evidence of that machine from which the code is being used.

Class Loader It is a sub component in CLR and is responsible for loading classes and other types as and when needed .It also loads the PE if it’s not already loaded.

Assemblies: Assemblies are building blocks of .Net framework applications. They form the fundamental unit of code execution, deployment, version control, reusability, activation scoping and security permissions. It can be made of one file or made of multiple files An assembly can be a single file or it may consist of the multiple files. In case of multi-file, there is one master module containing the manifest while other assemblies exist as non-manifest modules. A module in .NET is a sub part of a multi-file .NET assembly. Assembly is one of the most interesting and extremely useful areas of .NET architecture along with reflections and attributes, but unfortunately very few people take interest in learning such theoretical looking topics Assemblies are self-describing by means of their manifest, which is an integral part of every assembly. The manifest: (also called as Assembly Metadata) • Establishes the assembly identity (in the form of a text name), version, culture, and digital signature (if the assembly is to be shared across applications). • Defines what files make up the assembly implementation.

5

Deccansoft Software Services – MS.NET • • •

Overview of .NET Framework

Specifies the types and resources that make up the assembly, including which are exported from the assembly. Itemizes the compile-time dependencies on other assemblies. Specifies the set of security permissions required for the assembly to run properly.

This information is used at run time to resolve references, enforce version-binding policy, and validate the integrity of loaded assemblies. The runtime can determine and locate the assembly for any running object, since every type is loaded in the context of an assembly. Assemblies are also the unit at which code access security permissions are applied. The identity evidence for each assembly is considered separately when determining what permissions to grant the code it contains. The self-describing nature of assemblies also helps makes zero-impact install and XCOPY deployment feasible. Types of Assemblies Private Assembly: An assembly which is present in the same directory as the exe with every application refining to it. Shared Assembly: A single copy of it is in GAC and is shared by all the applications referring to that assembly. Satellite Assembly: A resource only assembly for a given culture. We can have more than one satellite assembly for one application.

Assembly Manifest (Meta Data) Type Meta Data MSIL Resources

.NET Module contains 1. Type Meta Data 2. MSIL Resource DLL

Managed code: by managed code, it means that the complete life cycle and execution is managed by the .NET Common Language Runtime (CLR). The .NET CLR manages the memory on behalf of the managed code, performs garbage collection on the managed heap, perform assembly validation and assembly (component) resolution on behalf of the program. The CLR also maintains the security constraints applied to the managed code. Note: By un-safe code, it means that the managed program can access the memory address using pointers. There are two points to remember here • Un-safe code is different from un-managed as it is still managed by the CLR • You still can not perform pointer arithmetic in un-safe code. Un-managed code runs outside the CLR control while the unsafe code runs inside the CLR’s control. Both un-safe and unmanaged codes may use pointers and direct memory addresses.

6

Deccansoft Software Services

Console- Main



Solution is a Collection of Projects. One Solution can have many projects and each project can be of different language. This file has the extension .sln. • A Project is a collection of files including Source Code (.vb/.cs), Resources(.resx), Configuration(.config) files etc…The project file has the extension .vbproj or .csproj • A project when build (Compilation + Linking) generates a EXE/DLL as output. Module Module1 Sub Main() Console.WriteLine("Module1") End Sub End Module Commandline Arguments: The best way of providing input to the commandline application is using commandline arguments. Module Module1 Sub Main(ByVal args As String()) Console.WriteLine("Hello " & args(0)) End Sub End Module args is the commandline arguments. View Æ Solution Explorer Æ Project Æ Right Click Æ Properties Æ Debug Tab Æ Command Line Arguments Æ Provide string separated by space Return value of Main: Module Module1 Function Main(ByVal args() As String) as Integer Console.WriteLine("Hello " & args(0)) Return 0 End Function End Module The return value of Main is used by the current application to communicate its state to the parent process when it terminates. The Interger return value can be predefined with some meaning and same will be used by the parent process to know the state of child process terminated. This return value of an application is called as EXIT CODE. Multiple Modules in One Project One Project can have multiple modules but only one of many module with valid Main can be treated as Startup or entry point. Module Module2 Sub Main() Console.WriteLine("Module2") End Sub End Module To Set Startup Object:View Æ Solution Explorer Æ Project Æ Right Click Æ Properties Æ Application Tab Æ Starup Object Æ Select Module whose Main should be used as entry point. Every Module in the project can be placed in same file or in different files. In either case the compiler is going to compile together. To Add another File with Module to Project: Goto Solution Explorer Æ Right Click on Project Æ Add ÆModule Following are the possible forms of Main which can be used in a module so that the module can be marked as startup object. If Main is written in Class it must be marked as Shared. Module Module1 Class Class1 Sub Main() Shared Sub Main() Console.WriteLine("Module1") Console.WriteLine("Module1") End Sub End Sub Sub Main(ByVal args As String()) Shared Sub Main(ByVal args As String()) Console.WriteLine("Hello " & args(0)) Console.WriteLine("Hello " & args(0)) End Sub End Sub Function Main() As Integer Shared Function Main() As Integer Console.WriteLine("Hello") Console.WriteLine("Hello") Return 0 Return 0 End Function End Function Function Main(ByVal args() As String) Shared Function Main(ByVal args() As String)

Deccansoft Software Services as Integer. Console.WriteLine("Hello " & args(0)) Return 0 End Function End Module

Console- Main as Integer. Console.WriteLine("Hello " & args(0)) Return 0 End Function End Class

As an Object Oriented programmer its always better to avoid usage of Module in a project. This is because every member of a module is by default treated as Global Member and it has free access through out the project and this is against object orientation principles

Deccansoft Software Services – VB.NET Integral Types DataType Byte SByte Short UShort Integer UInteger Long ULong

Size 1 1 2 2 4 4 8 8

. Net (CTS) System.Byte System.SByte System.Int16 System.UInt16 System.Int32 System.Unt32 System.Int64 System.UInt64

VB.NET Language Basics

Comments 0 - 255 It is Unsigned -128 to 127 - Signed Signed short Unsigned short Range For n – bits signed numbers: -2n-1 to 2n-1 - 1 n-bits unsigned numbers = 0 to 2n - 1

Floating Types Decimal 16 Single 4 Double 8

System.Decimal System.Single System.Double

Has up to 28 digits after decimal Has up to 8 digits after decimal Has up to 15 digits after decimal

Other DataTypes Char 2 4 String * Boolean 2 Object * Date 8

System.Char Systring.String System.Boolean System.Object System.DateTime

Uses Unicode Charset Uses Unicode Charset True / False Generic Datatype

All the above datatypes are ValueTypes but String and Object are Reference Types. Value Types directly hold the valueValueType All Basic Types, Structures & Enum

Var = Value Reference Types hold the reference to the value – Sring, Object, Class, Arrays, Delegates

Variable Declaration Syntax: Dim var1, var2 as Dim n1, n2 as Integer. Dim n1 as Integer = 10 Dim n1, n2 as Integer = 10 ‘ Invalid Dim n1 as Integer = 10, n2 as Integer = 10 ‘Valid

Heap Mem Ref type

Value

Var

• • •

Based on datatype every variable declared is set to default value A variable declared in a block is local to the block in which it is declared A variable declared in outer block cannot be re-declared in the inner block.

If “Option Explicit Off” is mentioned then we don’t need to declare the variable and by default it is treated to be of type “Object” But if “Option Explicit On” is mentioned then every variable used must be declared otherwise it gives compilation error. Literal Constants I – Integer, L – Long, D – Decimal, F – Single, R – Double, C – Char Example: 10L is Long, “A” is String, “A”c is Char. Alternate Variable Declaration Syntax: % - Interger, & - Long, @ - Decimal, ! – Single, # - Double, $ - String Dim n as Integer or Dim n% Implicit Casting: Conversions between types can normally be achieved automatically only if by doing so we can guarantee that the value is not changed in any way. To convert one data type say byte to another data type say integer, no data is lost during conversion that’s why compiler directly casts byte to integer .This is called implicit casting. Explicit Casting: There are some conversions that cannot be implicitly made between data types and the compiler will give an error if we are attempted. However we can explicitly carryout such transactions using conversion functions. When we cast one type to another we deliberately force the compiler to make the transformation.

1

Deccansoft Software Services – VB.NET

VB.NET Language Basics

Conversion Functions: CByte CDec CStr CShort CDbl CDate CInt CSng CLng CBool CChar CType/DirectCast/TryCast In VB.NET Explicit Casting is needed only if “Option Strict On” is mentioned on top of the file and only then the VB.NET language compiler treats the code as Strongly Typed Programming Language. Increasing order of Range: Byte Æ Short Æ Integer Æ Long Æ Decimal Æ Single Æ Double Casting is done based on range and not based on size of the datatype. Byte can be implicitly assigned to any datatype. Short can be implicitly assigned to all datatypes except Byte and So on… Dim b as Byte : Dim n as Integer n = b ‘Because has no chance of overflow allows Implicit Casting is done 'b = n 'Invalid because not all values of n can be assigned b b = CByte(n) 'Explicit Casting b = Convert.ToByte(n) 'Explicit Casting - If the value of n is not in range of 0 to 255 (range of byte) then OverFlowException is thrown. In VB.net by default integral Overflows are checked at runtime, this ensures the type safety of the code, but at the same time it adds to performance overhead at the runtime To Disable Overflow checks at runtime: Project Æ Properties Æ Compile Æ Advanced Compile Options Æ Remove Overflow Checks – Check It

Boxing & Unboxing Boxing is the term used to describe the transformation from value type to reference type (Object). The runtime creates a temporary reference-type box for the object on the heap. Dim n as integer = 20 Dim o as object = n ‘Boxing – The value of n is boxed on Heap memory and ref to that is stored in “o” UnBoxing is the term used to describe the transformation from reference type (Object) to value type. We use the term cast here, as this has to be done explicitly. Dim m as integer = 20 Dim o as object = m ‘Boxing – Storing Value type as Object Dim n as integer = CInt (o) ‘Unboxing – Extracting the value of ValueType from Object. • •

When a value is boxed to an object type the object type cannot be used in mathematical operations. When the value of object type variable cannot be assigned to variable on LHS, an Exception of type InvalidCastException is thrown.

Example: IIf (condition as Boolean, exp1 as Object, exp2 as Object) as Object Dim m, n, max as Integer max = CInt (IIf (m>n, m, n)) ‘m and n are boxed to Object but return value has to be unboxed. Some more Special Cases of Casting. We cannot cast integer to char or vice versa directly. For that we have to use special ‘chr = n ‘Invalid functions like AscW and ChrW 'n = chr 'Invalid chr = ChrW(n) chr = CChar(n) 'Invalid n = AscW(chr) 'n = CInt(c) 'Invalid Casting of String to any datatype str = "65" 'n = str 'Invalid 'str = n 'Invalid n = CInt(str) n = Integer.Parse(str) ‘Throws FormatException if Parsing fails n = Convert.ToInt32(str) If (Integer.TryParse(str, n)) Then

'Casting between integer and bool Dim n As Integer Dim bln As Boolean 'n = bln 'Invalid 'bln = n 'Invalid n = CInt(bln) 'Explicit casting bln = CBool(n) 'Explicit casting ‘Casting any datatype to string str = n.ToString()

2

Deccansoft Software Services – VB.NET Console.WriteLine("Success")

VB.NET Language Basics str = n & "" str = CStr(n) str = Convert.ToString(n)

Else

Console.WriteLine("Failed") End If In TryParse if Parsing fails, the value of second parameter (“n”) is set to default value. Constant Declaration Const PI As Double = 3.14 'PI = 10 'Invalid – The value of constant cannot be changed. Note: It is recomemded to have the name of constant variable always in upper case.

Enumerated Datatype • •

Enums can be subtype of integral types only. Enum is a collection of constants.

Enum WeekDays as Integer Sun = 1 Mon Tues Wed Thus Fri Sat End Enum

Dim wd As WeekDays wd = WeekDays.Tues n=1 'wd = 1 ‘Invalid – Casting is needed. wd = CType(n, WeekDays) 'explicit casting n = wd 'implicit casting Console.WriteLine(wd) ‘Prints the Numeric Value Console.WriteLine(wd.ToString()) ‘Print the String Value

About String and StringBuilder Strings in .net are called as Immutable (not modifiable) objects. They are Reference Types and hence are allocated memory on heap. Immutable means once the value of string is set it cannot be changed. Dim s as String S = “Deccan” ‘Creates a new string on the heap. S = S & “soft” ‘Creates another string on the heap by value “Deccansoft” and the old string “Deccan” is ready for garbage collection. Because of the above behavour it is not recommended that the string datatype is used for those variables which need frequent modifications in their value. Instead we should use the class called as “System.Text.StringBuilder” for those operations which need very frequent modification to the string. It allocates memory to the string in blocks and the capacity is automatically managed. Dim sb As New System.Text.StringBuilder(100) Console.WriteLine(sb.Capacity) For i As Integer = 0 To 50 sb.Append(i) Next Console.WriteLine(sb.Capacity) str = sb.ToString()

Modified value of string must be assinged to it again otherwise the value of it doesn’t change str = "Demo String" str.Replace(" ", "-") ‘Incorrect Usage – str doesn’t change. Console.WriteLine(str) str = str.Replace(" ", "-") ‘Correct Usage Console.WriteLine(str)

Operators Arithmetic Operators: +, - , *, / (Floating Type Division), \ (Integral Division), Mod (Modulus / Remainder), ^ (Power), +=, -=, *=, ^=, /=, \= • ^= & /= Operators can be only used with float variables. • Dividing a Integral Type with zero throws DivideByZeroException Floating Point Division by zero is not a runtime exception but the value would be either PositiveInfinity (if numerator is greater than zero) or NegativeInfinity (if nuderator is less than zero) or NaN(if numerator is also zero) Dim n as Integer Dim m as Double = -4.0 / n If (Double.IsNaN(m)) Then Console.WriteLine(“Not a Number”) ElseIf (Double.IsPositiveInfinity(m)) Then Console.WriteLine("Positive Infinity")

3

Deccansoft Software Services – VB.NET

VB.NET Language Basics

ElseIf (Double.IsNegativeInfinity(m)) Then Console.WriteLine("Negative Infinity") Logical Operators: A B A AndAlso B True True True True False False False True False False False False

A OrElse B True True True False

A XOR B False True True False

Not A False False True True



Is and IsNot are used to compare two reference types Ex: (a1 Is a2) is true if both a1 and a2 are referencing to the same object. (a1 IsNot a2) is true if both a1 and a2 are not referencing to the same object.



TypeOf: Is used to check if a given reference variable is referencing to an object of a give class. Ex: a TypeOf CA is True if a is referencing to an object of class CA or any of its subclass

Relational Operators: , =, , = (for both equal and assignment operator) Bitwise Operators: And and OR are the only two bitwise operators supported in VB.NET • • • •

If (E1 and E2) – If E1is false then also E2 is evaluated even though result will be false only. If (E1 AndAlso E2) - – If E1 is false then E2 is not evaluated and the result will be false only. If (E1 Or E2) – If E1 is True then also E2 is evaluated even though result will be True only. If (E1 OrElse E2) - – If E1 is True then E2 is not evaluated and the result will be True only.

• •

a = b = c will not be allowed for any datatype other than Boolean. Note: Operators not supported in VB.NET: ++, --, ?:,

Statements If (C1) Then S1 ---------------If (C1) Then S1() ElseIf (C2) Then S2() ElseIf (C3) Then S3() Else S4() End If • ( ) are optional with condition

While Loop While (n < 10) n += 1 If (n = 5) Then Continue While If (n = 7) Then Exit While Console.WriteLine(n) End While

For Loops For i As Integer = 1 To 10 Step 1 If (i = 5) Then Continue For End If If (i = 7) Then Exit For

Select Case n Case 1 S1() ‘if n=1 Case 2, 3 S2 ‘If n=2 or 3 Case Is < 6 S3() ‘if n= 4,5 and 0 & –ve numbers If (n = 5) Then Exit Select S4() ‘if n= 4 and 0 & –ve numbers Case 6 To 9 S5() ‘if n=6,7,8,9 Case Else S6() ‘if n > 9 End Select

GoTo Statement Dim n1 as Integer = 0 la: Console.WriteLine("s1") n1 += 1 If (n1 = 5) Then GoTo cont GoTo la cont: Goto is generally avoided in programming because then the clarity in code is lost.

Do While (c1) ‘Excutes if c1 is True If (c2) Then Exit Do If (c2) Then Continue Do Loop

Do ‘First Executes the statents and then checks for the condition Loop Until (C1) Do

Do Until (c1) ‘Excutes if c1 is False Loop

Loop While(C1)

Prints all command line arguments For i = 0 To args.Length - 1 Console.WriteLine(args(i)) Next Same result can be also achieved as below For Each s As String In args

What is the output of the below prog For i As Integer = 1 To 3 Step 1 For j As Integer = 1 To 3 Step 1 If (i = j) Then Exit For End If Console.WriteLine(i & " " & j)

4

Deccansoft Software Services – VB.NET

VB.NET Language Basics

End If Console.WriteLine(s) Next Console.WriteLine(i) Next Next Next i What is the o/p? What is the o/p ? Note: "For Each” statement can be used only for arrays and collections i.e objects which have implemented the interface IEnumerable With Statement Console.WriteLine(args.Length) Console.WriteLine(args.Rank)

With (args) Console.WriteLine(.Length) Console.WriteLine(.Rank) End With

Its not supported in C#

Working with Arrays • • • •

Arrays are reference types and thus are allocated memory on heap. All arrays irrespective of their type are by default inherited from System.Array class They always dynamic because we can set the size of the arrays at runtime. Size of array can never be changed at runtime.

Dim ar(X) as Integer ‘X is the variable Dim ar(10) As Integer ‘Declared and Initialized and array of lengh 11 Dim ar(0 To 10) As Integer Dim ar as Integer(10) ‘Invalid Dim ar As Integer() ‘Only declaration and “ar” is by default is set to “Nothing” Dim ar() as Integer ReDim ar(10) ‘Initializes an array of lengh 11 ReDim ar(0 To 10) Console.WriteLine(ar.Length) ReDim Preserve ar(0 To 20) ‘Creates a new array of 21 elements and because of the keyword Preserve copies the data from the old array into new array and the old array would be ready for garbage collection. Dim ar() as Integer = {1, 2, 3} ‘Declares and Initializes and array of 3 elements i.e Length 3. ar = New Integer() {1, 2, 3} Dim ar(-1) as Integer – Declares and Intialzes an Array with “0” length. Multidimensional Arrays: Dim ar(2, 3) As Integer Console.WriteLine(ar.Length) ‘12 Console.WriteLine(ar.Rank) ‘2 – Gives the total number of dimensions Console.WriteLine(ar.GetLength(0)) ‘ 3 – Gives the number of elements in 1st dimension. Console.WriteLine(ar.GetLength(1)) ‘ 4 – Gives the number of elements in 2nd dimension. Dim ar( , ) As Integer ReDim ar(2, 3) ReDim ar(3, 4) 'No Exception and both the dimension sizes can be changed as preserve is not used. ReDim Preserve ar(3, 5) –No Exception as only outer Dimension size is changed. ReDim Preserve ar(4, 5) 'Throws runtime ArrayTypeMisMatchException because only the Outermost dimension size can be changed if keyword preserve is used and here the inner dimension size is changed. Dim ar(,) As Integer = {{1, 2}, {3, 4}, {5, 6}} Console.WriteLine(ar.Length) 'Prints - 6 Console.WriteLine(ar.Rank) ' Prints - 2 Console.WriteLine(ar.GetLength(0)) ' Prints - 3 ‘Gives the number of rows in a matrix. Console.WriteLine(ar.GetLength(1)) ' Prints - 2 ‘Gives the number of columns in a matrix Console.WriteLine(ar(1,1)) ‘Prints – 4

Workiing with Methods Types of Procedues : 1. Sub Procedures – Do not return any value 2. Function Procedures – Returns a value.

5

Deccansoft Software Services – VB.NET 3.

VB.NET Language Basics

Property Procedures – To be covered in OOPS

In VB.NET the name of the function is treated as Variable in that function. The return type of the function is the datatype of that variable and the last value assigned to that becomes the return value of that function. Public Class Program Shared Sub Main(ByVal args() As String) Dim n1, n2 As Integer n1 = Integer.Parse(args(0)) ‘Converts the command line argment to Integer. n2 = CInt(args(1)) Dim res As Integer res = Add(n1, n2) ‘Uses the default value for third parameter Console.WriteLine(res) Console.Write("Enter first number : ") n1 = Integer.Parse(Console.ReadLine()) Console.Write("Enter second number : ") n2 = Integer.Parse(Console.ReadLine()) res = Add(n1, n2) Console.WriteLine("Result: " & res) Console.WriteLine(Add("Deccan", "soft")) ‘Invokes the string parameter method res = Add(1, 2, 3, 4) res = Add(1, 2, 3) res = Add(1, 2) res = Add(1, 2, , 4) res = Add(1, 2, d:=4, c:=3) ‘Named Arguments – Sequence of paramets is not important. res = Add(b:=1, a:=2, d:=4, c:=3) Dim mar() As Integer = {1, 2, 3} res = Add(mar) ‘Invokes the Version with array parameter Console.WriteLine(res) Console.WriteLine(Add(1, 2, 3)) ‘Invokes the version with 3 parameters Console.WriteLine(Add(1, 2, 3, 4, 5, 6)) ‘Invokes the ParamArray Version Console.WriteLine(Add(1, 2, 3, 4, 5, 6, 7)) Console.WriteLine(Add(1, 2, 3, 4, 5, 6, 7, 8)) Console.WriteLine(Add(1, 2, 3, 4, 5, 6, 7, 8, 9)) Console.WriteLine(Add(1)) End Sub 'Shared Function Add(ByVal a As Integer, ByVal b As Integer) As Integer ' Return a + b 'End Function Shared Function Add(ByVal a As Integer, ByVal b As Integer, Optional ByVal c As Integer = 0, Optional ByVal d As Integer = 0) As Integer Return a + b + c + d End Function Shared Function Add(ByVal s1 As String, ByVal s2 As String) As String Return s1 & s2 End Function Shared Function Add(ByVal ParamArray ar() As Integer) As Integer For Each n As Integer In ar Add += n Next End Function End Class Method Overloading: • Having two or more methods with same name and different parameters • Parameters must be different either in their datatype or in their count. • Method cannot be overloaded based on Return Type or ByVal/ByRef or Parameter names. • Call to the Overloaded method is resolved at compile time and is done based on datatype and count of arguments passed to the method. Optional Parameters • Every Optional Parameter must have default value • Once a parameter is declared as optional all subsequent parameters in the list also must be declared as optional

6

Deccansoft Software Services – VB.NET

VB.NET Language Basics

Named Arguments: • While calling a method we can pass arguments based on parameter names and we don’t have to then pass them in sequence. ParamArray Parameter: • Only Parameters which are of type array can be marked as ParamArray • If parameter is marked as ParamArray either a reference to the array can be passed as argument or otherwise 0 or more individual argurements can be passed. • Only one parameter of a method can be declared as ParamArray Parameter. • It must be always the last parameter in the list of parameters for a given method. • If we have other parameters in the list they must be before the ParamArray parameter and they cannot be declared as optional. Static Local Variable Public Class Program1 Public Shared Sub Main() Foo() Foo() Foo() End Sub Shared Sub Foo() Static Dim n As Integer n += 1 Console.WriteLine(n) End Sub End Class

A local variable can be declared as static and in such case it is allocated memory when the method is called for the first time and it retains its value for the subsequent call to the same method. It doesn’t get removed from the memory unlike other local variables or parameters of a method. Note: Static Local Variables are not supported in C# Output of the program 1 2 3

Value Type passed ByVal and ByRef Public Class Program Public Shared Sub Main() Dim n1, n2 As Integer n1 = 10 n2 = 10 Demo(n1, n2) Console.WriteLine(n1 & " " & n2) End Sub Shared Sub Demo(ByVal a As Integer, ByRef b As Integer) a += 1 b += 1 End Sub End Class In Main Before Foo is Called In Foo n1 = 10 a = 10 11 n1 = 10 n2 = 10 b/n2 = 10 11

The argument “n1” is passed by value (ByVal) i.e a dublicate copy of that variable is created on the stack of the function by name “a”. Any change made to parameter “a” is not reflected in “n1” The argument “n2” is passed by reference to “b”, i.e both “b” and “n2” reference to same memory and hence change made to “b” is also reflected in “n2”. Result: 10 11

In Main After Foo is returned n1 = 10 n2 = 11

Reference Type can also be passed ByVal and ByRef (this topic will be covered in OOPS) General Points: • “:” is the Statement terminator ex: a=1 : b=2 • “_” is the Statement Continuation char Ex: a = b _ +_ c • If Keywords have to be used as Identifiers enclose them in [ ] ex: Function [Sub](a as Integer, b as Integer) as Integer return a-b End Function • If Strings have the value as "(Quote) replace that with Double Quote ("") ex: Console.WriteLine("This is a ""Quoted"" word") • vbCRLF is a New Line charater and vbTab is the Tab character.

7

Deccansoft Software Services- MS.NET Program to check the range of a datatype Public Class Max_Min_Values Public Shared Sub Main() Console.WriteLine(Integer.MaxValue) Console.WriteLine(Integer.MinValue) Console.WriteLine(Short.MaxValue) Console.WriteLine(Short.MinValue) End Sub End Class Program for type-casting Public Class Type_Casting Public Shared Sub Main() Dim n As Integer = 50 Dim s As Short = 5 Dim str As String = "100" Dim m As Integer ‘TO CONVERT FROM STRING TO INTEGER 'm = CInt(str) 'm = Integer.Parse(str) 'm = Convert.ToInt32(str) ' Dim bl As Boolean ' To check if string is convertible to integer and try parsing ' bl = Integer.TryParse(str, m) m += 1 ' TO CONVERT FROM INTEGER TO STRING 'str = CStr(n) 'str = n.ToString str = n & "" str = str + " Days" Console.WriteLine(str) End Sub End Class Program to demonstrate In-Built Ascii Function: Public Class Ascii_Functions Public Shared Sub Main() Console.WriteLine(ChrW(65)) Console.WriteLine(AscW("B")) End Sub End Class Program to demonstrate Boxing and UnBoxing Public Class Boxing Public Shared Sub Main() Dim n As Integer = 65 Dim o As Object o = n 'This is Boxing Console.WriteLine(o) n = CInt(o) ' This is UnBoxing Console.WriteLine(n) End Sub End Class Program to demonstrate IIF function an alternative to Ternary operator Option Strict On

VB.NET Examples Public Class IIF_Example Public Shared Sub Main() Dim n, m, o As Integer m=5 n = 10 o = CInt(IIf(m < 10, m, n)) Console.WriteLine(o) End Sub End Class Program to demonstrate If Statement Dim grade As String Console.WriteLine("Enter a grade") grade = Console.ReadLine() If (grade = "E" OrElse grade = "e") Then Console.WriteLine("Excellent") ElseIf (grade = "G" OrElse grade = "g") Then Console.WriteLine("Good") Else Console.WriteLine("No Such Grades") End If Program to demonstrate Select Statement Dim grade As String Console.WriteLine("Enter a grade") grade = Console.ReadLine() Select Case (grade) Case "E" or “e” Console.WriteLine("Excellent") Case "G" or “g” Console.WriteLine("Good") Case Else Console.WriteLine("No Such Grades") End Select Program to demonstrate GoTo statement Public Class Label_Example Public Shared Sub Main() Console.WriteLine("One") GoTo Five Console.WriteLine("Two") Console.WriteLine("Three") Console.WriteLine("Four") Five: Console.WriteLine("Five") Console.WriteLine("Six") Console.WriteLine("Seven") Console.WriteLine("Eight") Console.WriteLine("Nine") Ten: Console.WriteLine("Ten") End Sub End Class Program to demonstrate Select statement Public Class Select_Example Public Shared Sub Main() Dim n As Integer = 1 Select Case n Case 1

1

Deccansoft Software Services- MS.NET Console.WriteLine(1) Case 2, 3 Console.WriteLine(2 & " & " & 3) Case Is < 6 Console.WriteLine("Less Than 6") Case 6 To 9 Console.WriteLine("6 To 9") If (n = 7) Then Exit Select Console.WriteLine("Not 7") Case Else Console.WriteLine("Else Case") End Select End Sub End Class Program to demonstrate While loop Public Class While_Example Public Shared Sub Main() Dim n As Integer = 5 While (n > 0) Console.WriteLine(n) n=n-1 End While Console.WriteLine() Do While (n < 5) Console.WriteLine(n) n=n+1 Loop Console.WriteLine() Do Console.WriteLine(n) n=n-1 Loop While (n > 0) End Sub End Class Public Class WhileDemo Shared Sub Main() Dim marks, count, avg, total As Integer Console.WriteLine("Enter 6 Subject marks") While (count < 6) marks = Console.ReadLine() total += marks count += 1 End While avg = total / 6 Console.WriteLine("Total is " & total) Console.WriteLine("Average is " & avg) End Sub End Class Program to demonstrate Do Until..Loop Public Class Until_Example Public Shared Sub Main() Dim n As Integer Do Until (n = 5) Console.WriteLine(n) n=n+1 Loop

VB.NET Examples Console.WriteLine() Do Console.WriteLine(n) n=n-1 Loop Until (n = 0) End Sub End Class Program to generate tables from 1 to 5 using For loop Class table Public Shared Sub Main() Dim n, m As Integer For n = 1 To 10 For m = 1 To 5 Console.Write(m & "*" & n & "=" & n * m & vbTab) Next Console.WriteLine() Next End Sub End Class Program to generate a triangle using For loop Class triangle Public Shared Sub Main() Dim n, m, o As Integer For n = 10 To 1 Step -1 For o = 0 To n - 1 Console.Write(" ") Next For m = n To 10 Console.Write("* ") Next Console.WriteLine() Next End Sub End Class Program to demonstrate Arrays Public Class Array_Example Public Shared Sub Main() Dim ar() As Integer = {1, 2, 3, 4, 5} Console.WriteLine(ar.Length) For Each tmp As Integer In ar Console.WriteLine(tmp) Next ReDim ar(10) For Each tmp As Integer In ar Console.WriteLine(tmp) Next 'ReDim Preserve ar(10) ‘For Each tmp As Integer In ar ‘Console.WriteLine(tmp) ‘Next End Sub End Class Program to demonstrate Function Overloading Public Class Functions_Example

2

Deccansoft Software Services- MS.NET Public Shared Sub Main() Dim m, n As Integer Dim o As Short = 12 m = 10 : n=5 'Console.WriteLine(Add("Hello", "Harish")) 'Console.WriteLine(m, n) 'Console.WriteLine(Add(o, 5)) Console.WriteLine(Add(b:=10, a:=50)) End Sub Shared Function Add(ByVal a As Short, ByVal b As Integer) As Integer Console.WriteLine("One") Add = a + b End Function Shared Function Add(ByVal a As Integer, ByVal b As Integer) As Integer Console.WriteLine("Two") Add = a + b End Function Shared Function Add(ByVal a As String, ByVal b As String) As String Add = a & b End Function End Class Program to demonstrate static variable Public Class Static_Local_Variable Public Shared Sub Main() Foo () Foo () Foo () Foo() End Sub Shared Sub Foo() Static Dim a As Integer a += 1 Console.WriteLine(a) End Sub End Class Program to demonstrate Call-By-Value and Call-ByReference Public Class ByRef_ByVal Public Shared Sub Main() 'Dim m, n As Integer 'm = 5 'n = 10 'Console.WriteLine("a: " & m) 'Console.WriteLine("b: " & n) 'Foo(m, n) 'Console.WriteLine("After Foo():") 'Console.WriteLine("a: " & m) 'Console.WriteLine("b: " & n) Dim ar1() As Integer = {10, 10} Dim ar2() As Integer = {10, 10} Console.WriteLine(ar1(0) & " " & ar2(0)) Console.WriteLine(ar1(1) & " " & ar2(1)) Foo(ar1, ar2) Console.WriteLine("After Foo():")

VB.NET Examples Console.WriteLine(ar1(0) & " " & ar2(0)) Console.WriteLine(ar1(1) & " " & ar2(1)) End Sub Shared Sub Foo(ByVal a As Integer, ByRef b As Integer) a += 1 b += 1 End Sub Shared Sub Foo(ByVal a() As Integer, ByRef b() As Integer) ReDim a(1) ReDim b(1) End Sub End Class Program to demonstrate passing an array of fixed length to a function: Public Class Array_Sum Public Shared Sub Main() Dim a() As Integer = {1, 2, 3, 4, 5} Console.WriteLine(Add(a)) End Sub Shared Function Add(ByVal a() As Integer) As Integer For Each a1 As Integer In a Add += a1 Next End Function End Class Program to demonstrate passing an arrays of variable length to a function Public Class ParamArray_Example Public Shared Sub Main() Dim m, n, o As Integer m=5 n = 10 o = 15 Console.WriteLine(Add(m, n, o, 2, 3, 4, 5, 6, 7, 8, 9, 1)) Console.WriteLine(Add(1,2,3)) Console.WriteLine(Add(m,1,n,2,0,3,4) End Sub Shared Function Add(ByVal ParamArray a() As Integer) As Integer For Each tmp As Integer In a Add += tmp Next End Function End Class

3

Deccansoft Software Services Integral Types DataType byte sbyte short ushort int uint long ulong

Size 1 1 2 2 4 4 8 8

Floating Types decimal 16 4 float double 8

. Net (CTS) System.Byte System.SByte System.Int16 System.UInt16 System.Int32 System.Unt32 System.Int64 System.UInt64

System.Decimal System.Single System.Double

C# - Language Basics Comments 0 - 255 It is Unsigned -128 to 127 - Signed

Has up to 28 digits after decimal Has up to 8 digits after decimal Has up to 15 digits after decimal

Other DataTypes char 2 System.Char Uses Unicode Charset 4 Systring.String Uses Unicode Charset string * bool 2 System.Boolean System.Object Generic Datatype object * Variable Declaration Syntax: int a,b; int a=10, b=20; • A local variable declared must be explicitly initialized before used in an expression otherwise gives an compilation error. • byte, short, char types when used in an expression are automatically raised to the rank of Integer. using System; class Program { public static void Main() { int n; byte b=0; n = b; //Implicit casting //b = n; //Invalid – Explicit casting is required n = 255; b = (byte) n; Console.WriteLine(b); checked //-always checks for Overflow { b = (byte)n; //If overflows exception is thrown } unchecked //-Neverchecks for Overflow { b = (byte)n; //Exception in never thrown Console.WriteLine(b); } float f = 0.6F; Console.WriteLine(f); decimal dec = 0.6M; double dbl = 0.6D; //float and decimal requires casting dec = 10; //Integer to decimal //f = dec; //Invalid //dec = f; //Invalid f = (float)dec; dec = (decimal)f; string s = "Demo";

char c = 'S'; //int to char. n = c; //c = n; //invalid c = (char)n; //Explicit Casting //bool – int/anydatatype explicit or implicit casting is not allowed either ways //string to int s = "100"; n = int.Parse(s); n = Convert.ToInt32(s); //n = (int)s;//Invalid //int to string s = n.ToString(); s = n + ""; s = Convert.ToString(n); //long to float long lng = 10; f = lng; //Long can be casted to float lng = (long) f; object obj = n; //Boxing n = (int)obj; //Unboxing const double PI = 3.14; byte b1, b2, b3; b1 = b2 = b3 = 10; b1 = b2 + b3 //Compilation Error

1

Deccansoft Software Services

C# - Language Basics

//if byte, short or char are used in an expression they are automatically raised to the rank of int. b1 = (byte) (b2 + b3); Console.WriteLine(3 / 2); //Result 1 Console.WriteLine(3.0 / 2); //Result 1.5 n = 10; int m = n++; //m=n; n=n+1 - Post Increment Console.WriteLine(n + " " + m); m = ++n; //n=n+1; m=n - Pre Increment Console.WriteLine(n + " " + m); //?: Conditional Operator int max; max = n > m ? n : m; //?: Operator

//Enum Sample n = 2; //n is int WeekDays wd = WeekDays.Sat; wd = (WeekDays) n; //n = wd; //Invalid n = (int) wd; //In VB.NET casting is not required } } enum WeekDays : int { Sun=1, Mon, Tues, Wed, Thus, Fri, Sat } Enum is a subtype of any integral type.

Note: You cannot use the checked and unchecked keywords to control floating point (non-integer) arithmetic. The checked and unchecked keywords control only integer arithmetic. Floating point arithmetic never throws OverflowException — not even when you divide by 0.0 Operators Arithmetic Logical Operators Ternary Operator String concatenation Increment, decrement Bitwise Relational Assignment Type information Indirection and Address

+, -, * , / , % (mod) ^ (XOR), !, && , || ?: + ++ , ->, & , | , ~ = = , != , < , > , = = , += , -= , *= , /= , %= , &= , | = , ^= , = is , sizeof , typeof, as * , -> , [] , &

Note for VB.NET Programmers: • In C# the arithmetic operator ‘/ ’ is the same for both floating point and integer datatypes and the result depends on the operands. Control Statements if-statement: if (BooleanExpression) { statement; } else if (Boolean-Expression) { statement; } else { statement; }

while…..loop while (BooleanExpression) { Statements; }

Switch Statement int n; switch (expr) //expr can only integral type / char / string { case 0: //value of case must be a constant. statements; goto default; // or break can be used. case 1: case 2: statements; break; //break must be preset after every case with statements default: statements; break; //break must be present after default also. } do { Statements; }while (BooleanExpression)

2

Deccansoft Software Services for and foreach statements for ( initializer; condition; iterator ) { statements; } foreach (DataType identifier in ) { embedded-statements; } for (int i = 0; i < 10; i++) { if (i == 7) break; if (i == 3) continue; Console.WriteLine(i); } foreach (string s in args) Console.WriteLine(s); • •

C# - Language Basics class Program { static void Main(string[] args) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == j) break; Console.WriteLine(i + " " + j); } } } }

break and continue statements can be used in for and while loops. C# doesn’t support with statement

Working with Arrays 1.Single-Dimensional Arrays int [] myArray = new int [5]; string myStringArray = new string[5]; int [] myArray = new int [] {1 , 2 , 3 }; string[] weekdays = new string[] {“Sunday”, “Monday”, ”Tuesday”}; When you initialize an array upon declaration, it is possible to use the following shortcuts: int[] myArray = {1, 3, 5, 7, 9}; string[] weekDays = {"Sun", "Sat", "Mon", "Tue"}; It is possible to declare an array variable without initialization, but you must use the new operator when you assign an array to this variable. For example: int[] myArray; myArray = new int[] {1, 3, 5, 7, 9}; // OK myArray = {1, 3, 5, 7, 9}; // Error 2.MultiDimensional Arrays int[,] myArray = new int[4,2]; Also, the following declaration creates an array of three dimensions, 4, 2, and 3: int[,,] myArray = new int [4,2,3]; You can initialize the array upon declaration as shown in the following example: int[,] myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}}; You can also initialize the array without specifying the rank: int[,] myArray = {{1,2}, {3,4}, {5,6}, {7,8}}; If you choose to declare an array variable without initialization, you must use the new operator to assign an array to the variable. For example: int[,] myArray; myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}}; // OK myArray = {{1,2}, {3,4}, {5,6}, {7,8}}; // Error class Program { static void Main(string[] args) { int[] ar = new int[ ] {1,2,3,4}; Console.WriteLine(a.Length); Console.WriteLine(a.Rank); foreach (int n in ar) Console.WriteLine(n); //To increase the size of existing array and also retaining data in it. i.e equivalent of Redim Preserve in VB. int[] temp =ar; ar = new int[temp.Length +1];

3

Deccansoft Software Services

C# - Language Basics

Array.Copy(temp, ar, temp.length); temp=null; foreach (int n in ar) Console.WriteLine(n); } } 3.Jagged Arrays(Array-of-Arrays) A jagged array is an array whose elements are arrays. A jagged array is sometimes called an "array-of-arrays." The following is a declaration of a single-dimensional array that has three elements, each of which is a single-dimensional array of integers: int[][] myJaggedArray = new int[3][]; Before you can use myJaggedArray, its elements must be initialized. You can initialize the elements like this example: myJaggedArray[0] = new int[5]; myJaggedArray[1] = new int[4]; myJaggedArray[2] = new int[2]; It is also possible to use initializers to fill the array elements with values, in which case youDon’t need the array size, Example myJaggedArray[0]=new int[] {1,2,3,4,5}; myJaggedArray[1]=new int[] {1,2,3,4}; myJaggedArray[2]=new int[] {1,2}; You can also initialize the array upon declaration like this int[][] myJaggedArray = {new int[]{1,2,3,4,5},new int[]{1,2,3,4}, new int[]{1,2}}; int[][] myJaggedArray; myJaggedArray = new int[][] {new int[]{1,2,3,4,5},new int[]{1,2,3,4},new int[]{1,2}}; Working with functions using System; static int Add(int a, int b) class Program2 { { return Add(a, b, 0); public static void Main() } { static int Add(int a, int b, int c) int res = Add(10, 2); { int[] mar = { 1, 2, 3, 4 }; return a + b + c; res = Add(mar); } res = Add(); static string Add(string s1, string s2) res = Add(1, 2, 3, 4, 5); { res = Add(1, 2, 3, 4, 5, 6); return s1 + s2; res = Add(1, 2, 3, 4, 5, 6, 7); } int n1, n2, n3; static int Add(params int[] ar) n1 = n3 = 10; { Foo(n1, out n2, ref n3); int sum = 0; Console.WriteLine(n1 + " " + n2 + " " + n3); //for (int i = 0; i < ar.Length; i++) } // sum += ar[i]; //Pass by value and reference example static void Foo(int a, out int b, ref int c) foreach (int n in ar) { sum += n; a++; b = 20; return sum; c++; } } } • • •

If a function has return type anything other than “void”, it must return a value. Out parameter must be initialized in the method and are generally used in situtions where we want to return more than one value from the function. C# doesn’t support Optional parameters with default values and Named arguments.

General Points; For String: @”C:\Demo” or “C:\\Demo”, “This is \”Quoted\” String”

4

Deccansoft Software Services

C# - Language Basics

class ProgramForPyramid { static void Main(string[] args) { int k=0; for (int i = 0; i < 4; i++) { for (int j = 0; j n2 ? n1 : n2; max = max > n3 ? max : n3; Console.WriteLine(max); } } class ProgramForMaxOf3Numbers { static void Main(string[] args) { string str = Console.ReadLine(); string[] ar = str.Split(' '); int sum = 0; for (int i = 0; i < ar.Length; i++) { sum += int.Parse(ar[i]); Console.WriteLine(ar[i]); } Console.WriteLine("Average: " + sum / ar.Length); } }

5

MS.NET -

Object Oriented Concepts Overview

Class: A class is a template / skeleton / blueprint for creating an object. Object: An Object is an entity that has properties for validations, methods for functionality and events for depicting the change of state. Every object has the data and behavior with which they are differed. Data associated at any given instance of time is the state of an object. Component: A ready to use third party object can be called as a Component. It can be replaced without any changes in the application. A component is generally used by a programmer as an object. An application can be called as a collection of related objects exchanging messages with each other. Loosely coupled objects are better than tightly coupled objects i.e. the lesser the information given to other objects the better it is as the objects are loosely coupled the dependencies are less and stronger security. Every object oriented language should have three features • Encapsulation • Inheritance • Polymorphism Encapsulation: Binding of data and behavior i.e. functionality of an object within a secured and controlled environment is encapsulation. Inheritance: The Process of acquiring the existing functionality of the parent and with new added features and functionality by a child object is called inheritance. The advantages of inheritance are Generalization, Extensibility and Reusability. For example: A calculator is a generalized form of mathematical operations where as a Scientific calculator is an Extended and Specific form. Polymorphism: An object in different forms and in each form it exhibits the same functionality but implemented in different ways. For example: A man who knows more than one language can speak any language he knows. Here the functionality is speech and person is the object. A faculty can take a form of Java Faculty or MSNET faculty and in both the forms he teaches, but what he teaches differs. Here functionality is teach and faculty is the object. Object Creation and Instantiation In MS.NET when an object is created there is no way to get the address of an object. Only the reference to the object is given through which we can access the members of the class for a given object. When an object is created all the variables (value/ reference types) are allocated the memory in heap as a single unit and default values are set to them based on their data types.

Working with Classes & Objects Syntax in VB: Dim as = New Syntax in C#: ; = new ( );

or

or

Dim As New

= new ( );

Account Example 1. 2.

Create a new project (File -> New Project). Give the name of project as AccountApplication. In Solution Explorer, Right Click and add to the project a new class and name it as Account

Code in VB:

Code in C#:

1

MS.NET -

Object Oriented Concepts

Public Class Account Public Id As Integer Public Name As String Public Balance As Decimal Public Sub New() MsgBox("Object created") End Sub Protected Overrides Sub Finalize() MsgBox("Object Destroyed") End Sub End Class

class Account { public int Id; public String Name; public Decimal Balance; public Account() { MessageBox.Show(“Object Created”); } ~Account() { MessageBox.Show(“Object Destroyed”); } }

In VB: Dim a As Account In C#: Account a; “a” is a refrence variable of type Account with default value set to Nothing(VB) or null(CS). Note: “a” is not an object of type Account. In VB: a = New Account() In C#: a = new Account() • ‘Creates an object of type Account (allocating memory on heap to every member of the Account class) and its reference is assigned to ‘a’. • Every member allocated memory is set to its default value based on the datatype. • The value of the reference variable is reference to an object. In the AccountApplication, Change the name of the Form, “Form1” to “AccountForm” a.Id = 1 The above statement can be read as: “Id” menber of an object of type Account referenced by “a” is set to 1. Note: If a reference variable is not intialized i.e referring to either “Nothing” or null, then trying to access any member using it will throw a runtime exception i.e. “NullReferenceException”. Dim a1 as Account a1 = a //Copies the value of a (reference to the object) into a1 and thus both “a1” and “a” refers to the same object. Note: One Object can have many references but one reference variable cannot refer to many objects. Account Form Code in VB: Account Form Code in C#: Public Class AccountForm public partial class AccountForm: Form Dim a As Account { Private Sub btnCreate_Click(. . .) Handles btnCreate.Click Account a; a = New Account() private void btnCreate_Click(...) End Sub { a = new Account(); Private Sub btnGet_Click(...) Handles btnGet.Click } txtId.Text = a.Id.ToString private void btnGet_Click(...) txtName.Text = a.Name { txtBalance.Text = a.Balance.ToString txtId.Text = a.Id.ToString; End Sub txtName.Text = a.Name; txtBalance.Text = a.Balance.ToString; Private Sub btnClear_Click(...) Handles btnClear.Click } txtId.Text = "" private void btnClear_Click(...) txtName.Text = "" { txtBalance.Text = "" txtId.Text = ""; End Sub txtName.Text = "";

2

MS.NET -

Object Oriented Concepts txtBalance.Text = ""; } private void btnSet_Click(...) { a.Id = int.Parse(txtId.Text); a.Name = txtName.Text; a.Balance = double.Parse(txtBalance.Text); } private void btnDestroy_Click(...) { a = null; } private void btnGC_Click(...) { GC.Collect(); } private void btntemp_Click(...) { Account a1 = new Account(); a = a1; } private void btnGetGeneration_Click(...) { MessageBox.Show(GC.GetGeneration(a).ToString()); }

Private Sub btnSet_Click(...) Handles btnSet.Click a.Id = Integer.Parse(txtId.Text) a.Name = txtName.Text a.Balance = Decimal.Parse(txtBalance.Text) End Sub Private Sub btnDestroy_Click(...) Handles btnDestroy.Click a = Nothing End Sub Private Sub btnGC_Click(...) Handles btnGC.Click GC.Collect() ‘Forces the activation of GC End Sub Private Sub btnTemp_Click(...) Handles btnTemp.Click Dim a1 = New Account() a = a1 End Sub Private Sub btnGetGeneration_Click(...) Handles btnGC.Click MsgBox(GC.GetGeneration(a)) End Sub End Class }

Working with Methods The methods of the object are used to describe the functionality / behavior. Recommendation: A method name should start with uppercase and parameters should use camel notation. Syntax in VB: Public Sub/Function (ByVal/ByRef parameter1 as , . . .) as End Sub/Function Syntax in C#: public ( paramerter1,….) {} Note: • An instance method is always invoked on the current object. • While writing a method in a class, do not set to it any data as parameter which is already the data member in the same class. • If parameter/local variable and datamember of a class have same name, the local variable takes the precedence over datamember and if datamember has to accessed in such same “Me” (VB) or “this” (CS) can be used.



In a method “Me” or “this” is reference to the current object on which the method is invoked.

In the Account Class add the following Code Code in VB: Public Sub Deposit(ByVal Amount As Decimal) Me.Balance += Amount End Sub Public Sub Withdraw(ByVal Amount As Decimal) If (Me.Balance a); } static unsafe void ShowArray(int *ar,int len) { for(int i=0; i operators, and the = operators should also be overloaded in pairs. The complete list of operators that can be overloaded is: • •

Unary operators: +, -, !, ~, ++, --, true, false Binary operators: +, -, *, /, %, &, |, ^, , ==, !=, >, =, Add References -> System.Configuration.dll Private Sub btn_Click(…) MsgBox(System.Configuration.ConfigurationManager.AppSetting(“k1”)) End Sub When the project is compiled using VS.NET the content of App.Config file is copied into another file by name .exe.config (or) .dll.config and its also placed in the same folder where the .exe is generated. Important Notes: • Parent of all configuration files on the machine is Machine.Config. The Configuration settings present in Machine.Config are global to all .net applications running on that machine. Its Present in the folder: \config\Machine.config. • Individual applications app.config file if required can override the settings in the machine.config.

3

Deccansoft Software Services – MS.NET

Unsafe Code, Operator Overloading, Reflection,Attributes & Config file

Location of Framework Folder: C:\Windows\Microsoft.Net\Framework\V2.0.X.X\

4

Deccansoft Software Services – MS.NET

Unsafe Code, Operator Overloading, Reflection,Attributes & Config file

DON’T XEROX THIS PAGE Custom Attributes: Custom attributes are user-defined attributes that provide additional information about program elements.. _ Public Class AuthorAttribute Inherits System.Attribute Public ReadOnly Name As String Public Location As String Public Sub New(ByVal name As String, Optional ByVal location As String = "") Me.Name = name Me.Location = location End Sub End Class Syntax for attaching an Attribute to a class or any of its member. Class Account ….. End Class or Class Account ….. End Class or Class Account ….. End Class In Form Dim tp As Type = GetType(Account) Dim ob ( ) As Object ob = tp.GetCustomAttributes (true) If (TypeOf(ob(0) is AuthorAttribute) Dim aa as AuthorAttribute = DirectCast(ob(0), AuthorAttribute) MsgBox(aa.Name & “ “ & aa.Location) End If

Partial Classes It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled. There are several situations when splitting a class definition is desirable: •

When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously. • When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when creating Windows Forms, Web Service wrapper code, and so on. You can create code that uses these classes without having to edit the file created by Visual Studio. To split a class definition, use the partial keyword modifier.

5

Deccansoft Software Services – MS.NET 1.

2.

Working with Assemblies and GAC

Create a new Class Library 1. Click File menu and select Project from New. 2. From New Project select Visual Basic-Windows from Project Types. From Templates select Class Library and check the Checkbox of Create directory for solution. Write the ClassLibrary1 in the Name and write the project location in Location i.e. D:\DemoSolution. Write the Solution Name is AssembliesWalkthrough.Click OK. 3. Write the code in the Class of Class1.vb. Public Class Class1 Public Function SayHello(ByVal name As String) As String Return "Hello" & " " & name & " " & "1.0" End Function End Class 4. Build the ClassLibrary1 ->Select Build Solution from Build menu. Adding a new Windows Application to the ClassLibrary 1. 2. 3. 4.

Go to Solution Explorer, right click on that and Select New Project from Add. Select Windows from Project Types and select Windows Application from Templates and click OK. Right click on WindowsApplication1 and select the Add Reference. We get Add Reference dialogBox click on Projects and select Class Library1 from Project Name. Click OK. Note: The Projects Tab is used for adding reference to other projects in the same Solution. 5. Click View menu and click on Tool Box. 6. You will get a Tool Box on Left hand side of the form. Double Click on Button from Common Controls. Imports ClassLibrary1 Public Class Form1 Private Sub Button1_Click(……) Handles Button1.Click ‘Create an object of ClassLibrary Dim c As new Class1 ‘calling the function of ClassLibrary1. MsgBox(c.SayHello("Version")) End Sub End Class 7. Right Click on Windows Application1 and select Set as StartUp Project option. 8. Now run the project with Ctrl+F5. We get Form1 with Button1.

4.

**We can see the included classlibrary1.dll file in Windows Application1 through D drive in this way D:\DemoSolution\AssembliesWalkthrough\WindowsApplication1\bin\Debug path and see the dll of the Class Library. Providing Strong Name to the Class Library 1. Select Solution Explorer from View menu. 2. Right Click on ClassLibrary1 and Select the Properties. 3. Click on Signing and Check the Sign the assembly Checkbox. Select for creating a strong name key file and Click on it. 4. You get one dialogbox with the name of Create a strong Name Key. If you want to provide the password check the Checkbox of Protect my key file with a password. Other wise do uncheck. Enter the Strong Name Key in key file name. Click OK. Note: VS.NET uses a tool called as SN.EXE for generating the strong name key file. 5. xyz.snk will be added in the ClassLibrary1 project. Providing Version to the Class Library (Objservation)

5 (A)

1. Click on Application Tab and Click on Assembly Information button. 2. Assembly Information dialogbox will open. Default Version for Assembly Version will be 1 0 0 0, keep as it is and ensure None is selected in Neutral Language. Click OK. Deploying the assembly in GAC through Visual Studio 2005 Command Prompt 1. Open Visual Studio 2005 Command Prompt from Visual Studio

3.

2. Goto the Debug folder of the Project and run the following command

5 (B)

GacUtil -i ClassLibrary1.dll. **We can also uninstall an Assembly by typing GacUtil –u ClassLibrary1 **We can list the existing list by typing GacUtil –l Another way to add into the Cache 1. Click on Start ===> Select Control panel from Settings Î Click-Administrative Tools===>Click-Microsoft .NET

1

Deccansoft Software Services – MS.NET

Working with Assemblies and GAC

Framework 2.0 Configuration. 2. In the new Window Click Assembly Cache from My Computer and click on Add an Assembly to the Assembly Cache. 3. You will get Add an Assembly dialogbox. In that select our ClassLibrary1.dll from ClassLibrary1 folder and click Open. Then the assembly will be added to the GAC. 6 . •

Goto References of WindowsApplication1 Æ Select ClassLibrary1 Æ Properties Æ LocalCopy= False The same signing key file can be used for signing of all the assemblies developed by a given developer or organization. Walkthrough for Assemblies (Case -2) Continue of Case -1 (For Side- by- Side Versioning) 1. Copy the dll of ClassLibrary1 from the bin folder of our project and go to C:\Program Files\Common Files\CompanyName\ClassLibrary1\Ver 1.0\ and paste the dll and from here add the dll into the GAC. 2. Modify the implementation in Class1 of ClassLibrary1 project. Public Class Class1 Public Function SayHello(ByVal name As String) As String Return "Hello " & name & " - 2.0" End Function End Class 3. Follow the steps of Providing Version to the Class Library from Case Study-1:Change the Assembly Version and the File Version to 2.0.0.0 instead of 1.0.0.0 4. Rebuild the ClassLibrary1 and copy the dll of ClassLibrary1 from the bin folder of our project to C:\Program Files\Common Files\CompanyName\ClassLibrary1\Ver 2.0\ and paste the dll and from here add the dll into the GAC. Note: at this time we have two versions of the same ClassLibrary present in GAC. 5. In WindowsApplication1 remove the old reference of ClassLibrary1 and add the new reference of ClassLibrary1 – Version 1.0.0.0 (select the Dll present in “C:\Program Files\Common Files\CompanyName\ClassLibrary\Ver 1.0”) folder Note: Run the WindowsApplication1.exe and make sure that it’s using Version 1 of the DLL because it is build (compiled) using Version 1 of the ClassLibrary. 6. Add to the existing solution, a new windows application (WindowsApplication2) and add reference to ClassLibrary1 Version 2.0.0.0 (select the Dll present in “C:\Program Files\Common Files\CompanyName\ClassLibrary\Ver 2.0”) folder. Note: Confirm that in both the Windows Applications ClassLibrary1 reference property Local Copy is set to false. 7. Add button1 to the Form and write the click event handler for button1 in WindowsApplication2. Imports ClassLibrary1 Public Class Form1 Private Sub Button1_Click(……) Handles Button2.Click ‘Create an object of ClassLibrary Dim c As new Class1 ‘calling the function of ClassLibrary1. MsgBox(c.SayHello("Version")) End Sub End Class 8. Right Click on WindowsApplication1 and select Set as StartUp Project option. 9. Now run the project with Ctrl+F5. We get Form1 with Button1. 10. Right Click on WindowsApplication2 and select Set as StartUp Project option and run the project with Ctrl+F5.

2

Deccansoft Software Services – MS.NET

Working with Assemblies and GAC

This is called Side-by-Side Versioning and is not supported in COM. Walkthrough for Assemblies (Case Study-3) Continue of Case Study-2 (For Upgrading the Versions) 1. 1. Click on Start from the Desktop ==>Go to Settings => Control panel => Administrative Tools =>Microsoft .Net FrameWork 2.0 Configuration ===>Click on My Computer => Configured Assemblies 2. Click on Configure an Assembly. You will get Configure an Assembly dialogbox. 3. Click on Choose Assembly button. Choose the Library which you want to upgrade i.e ClassLibrary1 with Version 1.0.0.0. 4. After that click on Finish button. 5. You will get a dialogbox of ClassLibrary1 Properties. Click on Binding Policy button in that write the Requested Version 1.0.0.0 which we want to replace to New Version 2.0.0.0. Click on Apply button and then OK button. Note: Here you can run the WindowsApplication1.exe by directly going its bin folder and verify that its using ClassLibrary1.DLL – Version 2.0.0.0 and not Version 1.0.0.0 using which it originally build / compiled Explanation: 6. Go to this path through C drive C:\WINNT\Microsoft.NET\Framework\v2.0.50727\CONFIG and click on machine.config file and open it. 7. Copy this code from machine.config file and paste it where we want the new version in this way. Note: Because the above xml is generated in machine.config, all the applications build using Version 1.0.0.0 of ClassLibrary1.DLL at runtime use Version 2.0.0.0. In case only if one application has to use Version 2.0.0.0, the above xml must be placed in that applications config file and not in machine.config. 8. Right Click on WindowsApplication1 and select New Item form Add. We get Add New Item dialog box will be display.from that select Application Configuration File and click on Add. 9. Paste the content copied from “machine.config” file here in the “app.config” file of windows Application1 in between tag. 10. Right Click on Windows Application1 and select Set as StartUp Project option. 11. Now run the project with Ctrl+F5..

In this way the version will be upgraded from old version to new version. When we run the WindowsApplication1 in which had Classlibrary1.dll is there with Version 1.0.0.0 this one will be upgraded with new Version 2.0.0.0 and shows the information of Version 2.0.0.0.

Notes • • • • • •

A ClassLibrary is a Dll file whose code can be reused in many other application. The code in Exe file cannot be reused. A namespace is a logical collection of classes and other types with unique names. In a given namespace all the types have unique names and thus it is used to resolve the ambiguity in case of name conflict of different type. Any type when used outside the namespace, it must be qualified by its namespace, but when used by another type with in the same namespace then it need not be qualified by the namespace. In VB.Net project properties we can mention a root namespace and that becomes the default Namespace for all classes & other types in the project. Where as in C#, in project properties we can mention the default namespace but in code we have to explicitly mention the namespace. The editor auto generates the code using default namespace. Namespace can never be used as a boundary for an access modifier / specifiers. A public method of a public class cannot have either as parameter or return any datatype which is not public.

3

Deccansoft Software Services – MS.NET • • • • • •

• •

Working with Assemblies and GAC

In we can use Imports (VB) / using (CS) Namespace on top of the file so that we don’t have to qualify all the types of that namespace in that file. In VB.NET we can do project level Imports but in CS we don’t have that facility. A Public Class is accessible within and outside the assembly. Where as an internal (C#) / Friend (VB) Class can be access only by other types with in the assembly. This is the default access modifier for the class. Top level class can be declared as either public or internal (C#) / Friend (VB) but nested class (a class within class) can have any access modifier. An internal (C#) / Friend (VB) member of a class is accessible to all other type with in the assembly and is not accessible out side the assembly. A member declared as “protected internal” (CS) or “Protected Friend” (VB) is accessible to all the class with in the assembly and only to the derived classes out side the assembly. A class which is accessible outside assembly but can’t be instantiated from outside the assembly is called “Public Not Creatable “.To write such a class we have to make the constructor of the class as “internal” or friend. In the example below class1 is Public Not Creatable. public class Class1 { internal Class1() {} } public class Class2 { public Class1 GetClass1Object() { return new Class1(); } } Unlike COM component .Net Component need not be register in Win Registry. A top class cannot have any access modifier other than public or internal where as inner class can have any access modifier.

Types Of Assemblies • Private Assemblies: An assembly whose local copy is maintained by each & every application referencing to it. • Shared Assembly: An assembly whose single copy deployed in Global Assembly Cache (GAC) and used / shared by many applications running on that machine. Such assemblies must have Strong name. StrongName = Assembly Name +Version + Public / Private Key + Culture • Satellite Assembly: A resource only assembly for a given culture is called as satellite assembly. They don’t have any code but they have only resources like string tables and images. Notes about Shared Assemblies: • The referring application includes the strong name of the referred assembly (library) in its manifest which is auto generated by the language compiler. • When the application requires the library, using this strong name information the referred library is loaded. First it searches the library in the local directory of the application but if not found it is loaded from GAC. • A shared assembly must be first placed in any directory and from there it must be installed in GAC and from the same location we can add the reference to the assembly in the application. We cannot add reference to the assembly directly from GAC. • C:\WINNT\assembly\GAC_MSIL\ClassLibrary1\1.0.0.0__9e435e4509ac3422> is the location where ClassLibrary1.DLL will be present.

4

Deccansoft Software Services – MS.NET

ADO.NET

Structured Query Language = DDL + DML + DCL + DTL Data Defination Language = Create, Alter, Drop Data Manipulation Language = Insert, Delete, Update, Select Data Contro Language = Grank, Revoke Data Transaction Language = Commit, Rollback, SavePoint Client Process Application Managed Provider

DataSet

DataAdapter Command

Connection

Data Reader

DB Server Managed Provider It is a .Net component implementing certain standard set of interfaces provided by Microsoft, for a specific type of backend. Following are the four managed providers which are build in along with MS.NET Framework. 1. System.Data.SqlClient Manage Provider for SqlServer 2. System.Data.OracleClient- Manage Provider for Oracle 3. System.Data.Oledb -Manage Provider- Can be used for any database which has Oledb provider 4. System.Data.Odbc - Manage Provider for Odbc drivers – This can be used for all databases but it would be slow compared to a managed provider specific to a given database. Imporatant Objects in Managed Provider Connection: Connection object encapsulates the functionaly of establishing a communication path over the sockets. In .Net ,Connections are ‘Pooled’. We can make by default 100 simultaneous connections without closing but obviously we have to close every connection Opened only then it can be reused from Pool i.e keeps the connection with the database open for the short period of time. The Connection Pooling can be customized by setting appropriate parameters in ConnectionString of Connection Object and this cannot be done for Oledb and ODBC managed providers. Command: Command Object can be used for execution of any type of Sql Statement. DataReader: When “Select” or similar type of sql statement is executed a new cursor (memory are in backend) is created on the back end. This Cursor contains primary key or indexed key of the table on which the statement is executed for the records which have qualified the condition in the where clause of the select statement. It also has a pointer, which is by default positioned at BOF. The cursor and pointers functionality is encapsulated by the “DataReader” object created in the front end. Using this object, we can move the pointer in the forward direction getting one record from backend into the front-end at the time. The cursor managed by Data Reader is read-only and forward-only Goto ServerExplorer Æ Right Click on Data Connections Æ Create New Sql Server Database Æ Server Name as .\SqlExpress Æ New Database name as MSNET Create the following table in that database. Emp (EmpId, EmpName, EmpSalary) table in backend. EmpId – Int, PrimaryKey and also set Identity = True in Property of EmpId field EmpName – Varchar(50) - AllowNull = False(Uncheck) EmpSalary – Money Right Click on EMP table and select Show Table Data Æ Enter some default data. • Note: On top of file mention Imports System.Data.SqlClient To Execute Insert / Delete / Update Statements Private Sub btnInsert_Click(. . .) Handles btninsert.Click

1

Deccansoft Software Services – MS.NET

ADO.NET

Dim con As New SqlConnection con.ConnectionString = "Data Source=.\sqlexpress;Initial Catalog=MSNET;Integrated Security=True" ‘con.ConnectionString = "Data Source=.\sqlexpress;Database=MSNET;User id=sa;Password=dss" ‘con.ConnectionString = "Server=.\sqlexpress;Database=MSNET;uid=sa;pwd=dss" Dim cmd As New SqlCommand cmd.CommandText = "insert into Emp(EmpName,EmpSalary) values('" & txtName.Text.Replace("'", "''") & "'," & txtSalary.Text & ")" Note: In and SQL Statement the value of every Varchar field must be enclosed in single quotes. But if the value itself has single quote then it should be replaced with two single quotes. 'cmd.CommandText = "Delete from Emp where empid=" & txtId.Text 'cmd.CommandText = "Update Emp Set EmpName = ‘” & txtName.Text.Replace("'", "''") & “’, EmpSalary=” & txtSalary.Text & “where EmpId=" & txtId.Text cmd.CommandType = CommandType.Text cmd.Connection = con Try con.Open() MsgBox(cmd.ExecuteNonQuery()) ‘Used for execution of those Statements which do not return any data. cmd.CommandText = "Select @@Identity" ‘Used for fetching the last set Identity column value on the current con. MsgBox(“Last Inserted EmpId as set by backend “ + cmd.ExecuteScalar) Finally If (con.State = ConnectionState.Open) Then con.Close() End Try End Sub Private Sub btnSelect_Click(. . .) Handles btnSelect.Click Dim con As New SqlConnection con.ConnectionString = "Data Source=.\sqlexpress;Initial Catalog=MSNET1;Integrated Security=TRUE" Dim cmd As New SqlCommand 'cmd.CommandText = "select empname from emp where empid=1" cmd.CommandText = "select max(empid) from emp" cmd.CommandType = CommandType.Text cmd.Connection = con con.Open() MsgBox(cmd.ExecuteScalar) ‘Used for execution of statements which return only one value. con.Close() End Sub Private Sub btnGetEmp_Click(. . .) Handles btnGetemp.Click Dim dr As SqlDataReader dr = GetEmployees() Dim str As String = "" While (dr.Read()) 'Read return false if EOF is reached. str &= dr("EmpId") & vbTab str &= dr(1) & vbTab Dim ind As Integer ind = dr.GetOrdinal("EmpSalary") 'Return the Index of the column EmpSalary If (dr.IsDBNull(ind)) Then str &= "--" & vbCrLf Else str &= dr.GetDecimal(ind) & vbCrLf End If End While MsgBox(str) dr.Close() 'Here is the connection is Closed 'con.Close() 'This is not required if CommandBehavior.CloseConnection is mentioned when the statement is executed. End Sub Private Function GetEmployees() As SqlDataReader Dim con As New SqlConnection() con.ConnectionString = "Data Source=.\sqlexpress;Initial Catalog=MSNETDemoDb;Integrated Security=TRUE" Dim cmd As New SqlCommand cmd.CommandText = "select EmpId,EmpName,EmpSalary from Emp" cmd.CommandType = CommandType.Text cmd.Connection = con

2

Deccansoft Software Services – MS.NET

ADO.NET

Dim dr As SqlDataReader con.Open() dr = cmd.ExecuteReader(CommandBehavior.CloseConnection Or CommandBehavior.SingleRow) 'If the CommandBehavior.CloseConnection is mentioned the Connection is automatically closed when the data reader is closed. Return dr End Function

MARS By Default we can have only one data reader opened at a time on one connection object. If MultipleActiveResultSets=True is added to the connection string then more than one data reader can be opened at the same time on the single connection object. It’s a new feature in Ado.net 2.0 Note: The result of one select statement should not overlap with the result of another statement. Department(DeptId,DeptName) Employee(EmpId,EmpName,EmpSalary,DeptId); Note: One Department can have more than one Employee. Private Sub btnGetDeptEmp_Click(. . .) Handles btnDeptGetEmp.Click Dim con As New SqlConnection con.ConnectionString = "Data Source=.\sqlexpress;Initial Catalog=MSNETDemoDb;Integrated Security=TRUE; MultipleActiveResultSets=True" Dim cmdDept As New SqlCommand cmdDept.CommandText = "select * from Department" cmdDept.CommandType = CommandType.Text cmdDept.Connection = con Dim drDept As SqlDataReader con.Open() drDept = cmdDept.ExecuteReader() Dim str As String = "" While (drDept.Read()) Dim cmdEmp As New SqlCommand cmdEmp.CommandText = "select * from Employee where Deptid=" & drDept("DeptId") cmdEmp.CommandType = CommandType.Text cmdEmp.Connection = con Dim drEmp As SqlDataReader drEmp = cmdEmp.ExecuteReader() While (drEmp.Read()) str &= drDept("DeptName") & vbTab str &= drEmp("EmpId") & vbTab str &= drEmp(1) & vbTab str &= drEmp.GetDecimal(2) & vbCrLf End While drEmp.Close() End While drDept.Close() MsgBox(str) con.Close() End Sub Prepared Statement : An sql Statement on its first execution is compiled, optimized and an execution plan is created for it, If the statement is marked as prepared then for further usage this execution plan is catched by the backend so that the same plan can be reused for the subsequent request for the same statement but different values for parameters. Note: The prepared statement must be framed using the paramenters. Note: In Sql Server the parameters must begin with @, In Oracle just the name is sufficient but for OleDb and Odbc Providers we need to use “?” as place holder for all the parameters and while adding the parameters a proper order must be maintained. Private Sub btnInsParam_Click(. . .) Handles btnInsParam.Click Dim con As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=MSNETDemoDb;Integrated Security=TRUE") Dim cmd As New SqlCommand cmd.CommandText = "Insert into emp(EmpName,EmpSalary) values(@EmpName,@EmpSalary)" cmd.CommandType = CommandType.Text cmd.Connection = con

3

Deccansoft Software Services – MS.NET

ADO.NET

'For every place holder in the sql statement a parameter object must be created and added to the parameters collection. Dim parEmpName As New SqlParameter("@EmpName", SqlDbType.VarChar, 50) Dim parEmpSalary As SqlParameter parEmpSalary = cmd.CreateParameter() parEmpSalary.ParameterName = "@EmpSalary" parEmpSalary.SqlDbType = SqlDbType.Money cmd.Parameters.Add(parEmpName) cmd.Parameters.Add(parEmpSalary) Dim dic As New Dictionary(Of String, Decimal) dic.Add("DE1", 10000) dic.Add("DE2", 2000) dic.Add("DE3", 30000) dic.Add("DE4", 40000) 'Set the value for the parameters. con.Open() cmd.Prepare() 'Prepares the execution plan for the sql statement. For Each kv As KeyValuePair(Of String, Decimal) In dic parEmpName.Value = kv.Key 'Get Name parEmpSalary.Value = kv.Value ' Get Salary cmd.ExecuteNonQuery() Next con.Close() End Sub Note: If the SQL Statement has to be executed only once, don’t mark is Prepared because the backend takes extra time for preparation of execution plan and this would become overhead the plan is not reused. Stored Procedures It is a precompiled set of sql statement which are compiled in native form and stored in the backend. They are very fast on their first execution also. Advantages: 1. They are very fast in execution because they are precompiled and stored in backend in native form of that backend. 2. Reduces network trafic because they are executed in backend the data used by them is also in backend. 3. Its easy to update logic/code in them because its stored only at one place i.e in database. Note: As far as possible always try to execute all the sql statements using stored procedures. Every Input Parameter must have a value before the command is executed. If required we can set the to DbNull.Value. In SQL-Server every out parameter is also input. Sample Stored Procedure Create Procedure GetSalary(@Id int,@Sal money out) AS Begin Select @Sal=EmpSalary from Emp where EmpId=@Id End --------------------------------------------------------------------------------------Private Sub btnSPDemo_Click(. . .) Handles btnSPDemo.Click Dim con As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=MSNetDemoDb;Integrated Security=TRUE") Dim cmd As New SqlCommand cmd.CommandText = "GetSalary" cmd.CommandType = CommandType.StoredProcedure cmd.Connection = con Dim parId As New SqlParameter("@Id", SqlDbType.Int) Dim parSal As New SqlParameter("@Sal", SqlDbType.Money) parSal.Direction = ParameterDirection.Output parSal.Value = DBNull.Value cmd.Parameters.Add(parId) cmd.Parameters.Add(parSal) con.Open() parId.Value = txtId.Text cmd.ExecuteNonQuery() MsgBox(parSal.Value)

4

Deccansoft Software Services – MS.NET

ADO.NET

con.Close() End Sub Create Procedure GetEmployees AS Begin Select Count(*) from Emp Select EmpId, EmpName, EmpSalary from Emp End Private Sub btnGetEmployeesStoredProcedure_Click(. . .) Handles btnInsParam.Click Dim con As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=MSDemoDb;Integrated Security=TRUE") Dim cmd As New SqlCommand cmd.CommandText = "GetEmployees" cmd.CommandType = CommandType.StoredProcedure cmd.Connection = con con.Open() dr = cmd.ExecuteReader() dr.Read() ' Moves to the only record in the first cursor created by execution of the stored procedure. MsgBox(dr(0)) ' Shows the total number of records in the Emp table.- i.e result of “Select Count(*) from Emp” dr.NextResult() ' Moves the Pointer to the second cursor. i.e “Select EmpId,EmpName,EmpSalary from Emp” Dim str As String = "" While (dr.Read()) str &= dr("EmpId") & vbTab str &= dr(1) & vbTab Dim ind As Integer ind = dr.GetOrdinal("EmpSalary") ‘Return the Index of the column EmpSalary If (dr.IsDBNull(ind)) Then str &= "--" & vbCrLf Else str &= dr.GetDecimal(ind) & vbCrLf End If End While MsgBox(str) dr.Close() con.Close() End Sub Note: If required cmd.CommandText can have more than one sql statement separated by “;”. This feature may or may not be supported by a give database. Using Factory class for writing Provider Independent code. (only in 2.0) Dim con As IDbConnection Dim fac As System.Data.Common.DbProviderFactory fac = System.Data.Common.DbProviderFactories.GetFactory( “System.Data.SqlClient") con = fac.CreateConnection() con.ConnectionString = "" Dim cmd As IDbCommand cmd = con.CreateCommand() Dim par As IDataParameter par = cmd.CreateParameter() Dim dr As IDataReader dr = cmd.ExecuteReader Transaction: Its a group of Sql Statements to de executed as one unit to modify the state of database. ACID (Atomacity, Consistancy, Isolation and Durability) Private Sub btnTransaction_Click(. . .) Handles btnTransaction.Click Dim con As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=MSNetDemoDb;Integrated Security=TRUE") Dim cmd1, cmd2 As SqlCommand cmd1 = New SqlCommand() cmd2 = New SqlCommand() cmd1.Connection = con

5

Deccansoft Software Services – MS.NET

ADO.NET

cmd2.Connection = con cmd1.CommandText = "Insert into Emp(EmpName,EmpSalary) Values(‘A1’,10000)" cmd2.CommandText = "Update Emp set EmpSalary = EmpSalary = 1000" con.Open() Dim trans As SqlTransaction trans = con.BeginTransaction() 'Starts a new transaction over the connection cmd1.Transaction = trans 'All the commands belonging to the transaction must have their Transaction property set. cmd2.Transaction = trans Try cmd1.ExecuteNonQuery() cmd2.ExecuteNonQuery() 'This will fail trans.Commit() ' If no exception is thrown the transaction is commited. Catch ex As Exception MsgBox(ex.Message) trans.Rollback() 'If exception is thrown the transaction is rolledback. End Try con.Close() End Sub While Practising: On Execution of above code by default we will get an error and the transaction is rolledback and then Execute the above code replacing “=” with “+” in the update statement and see that transaction is now commited and a record is inserted in Emp table. Note: Once a transaction has begin over a connection, a command without its transaction property set cannot be executed on that connection unless either the transaction is committed or rolledback. How Generic code can be written – Example for execution of Stored Procedure. Class DBUtil Public Shared Function ExecuteSPNonQuery(ByVal connectionString As String, ByVal spName As String, ByVal ParamArray params() As SqlParameter) As Integer Dim con As New SqlConnection(connectionString) Dim cmd As New SqlCommand(spName, con) cmd.CommandType = CommandType.StoredProcedure For Each p As SqlParameter In params cmd.Parameters.Add(p) Next Try con.Open() Return cmd.ExecuteNonQuery() Finally con.Close() End Try End Function End Class Private Sub btnExecuteSP_Click(. . .) Handles btnExecuteSP.Click Dim cs As String = "server=.\sqlexpress;database=msnet;integrated security=true" Dim spName As String = "GetSalary" Dim pId As SqlParameter = New SqlParameter("@Id", SqlDbType.Int) pId.Direction = ParameterDirection.Input Dim pSalary As SqlParameter = New SqlParameter("@sal", SqlDbType.Money) pSalary.Direction = ParameterDirection.Output pId.Value = CInt(txtId.Text) DBUtil.ExecuteSPNonQuery(cs, spName, pId, pSalary) If (Not IsDBNull(pSalary.Value)) Then txtSalary.Text = pSalary.Value End Sub Async Execution of Command Dim dr As SqlDataReader Dim cmd As New SqlCommand Dim ar As IAsyncResult = cmd.BeginExecuteReader() ‘Begins the Asynchronous call MessageBox.Show(“Continuee….”) If (ar.IsCompleted) Then ‘Checks if the return value is available. dr = cmd.EndExecuteReader(ar) ‘Ends the Asynchronous call and provides the return value. End If End Sub

6

Deccansoft Software Services – MS.NET

ADO.NET – Dataset

DataSet: • Its a DISCONNECTED object model for working with the data fetched from database. • It is completely independent of the database i.e we can fetch the data from different database into the same same dataset instance. • Because of it is a disconnected model it reduces the number of trips to the server and thus it reduces the load on server. This increases server’s scalability. (Scalability is the measure of server capability to handle increasing number of clients) • Because the data is available locally, client doesn’t have a make a round trip to the server for every requirement, This reduces network traffic and also client applications performance is improved. • Because it is disconnected, it can be used for exchanging of data between distributed objects. • Because it can easily interoperate with XML it can be used for communication between objects even if they are seperated by firewall. DataSet DataTable DataColumn DataRow Constraint DataRelation DataAdapter has following four Command Properties: SelectCommand / InsertCommand / UpdateCommand / DeleteCommand da.Fill(ds, “Emp”) 1. Opens the connection of SelectCommand of DataAdapter referenced by “da” (only if the connection is not already open) 2. Executes the SelectCommand over that connection. 3. Fetches all the data at one time into frontend and creates a DataTable by name “Emp” (provided its not already exiting) and new DataTable is added to Tables collection of DataSet referenced by “ds”. 4. For every record fetched from backend it creates a DataRow object and this row is either Added or Merged in the DataTable Rows Collection. 5. Closes the connection (provided it has opened it). da.Update(ds, “Emp”) • Based on the state of each DataRow in the mentioned DataTable, the appropriate command of the DataAdapter referenced by “da” is executed. • If the state of the Row is “Deleted” then DeleteCommand is executed. If the state of the Row is “Modified” then the “UpdateCommand” is executed and if the state of the row is “New” then the “InsertCommand” is executed. • Based on the row being executed and the SourceColumn and SourceVersion property values of Parameter, the value for the parameters of the command in execution are set. SourceColumn property of SqlParameter: It is the name of DataColumn in DataTable to which a Parameter is binded to i.e., while executing the command the value of the parameter is taken from the mentioned column of the DataRow for which the command is being executed. SourceVersion property of SqlParameter: It decides which version (Current or Original) value of the column for a given row should be assigned to the parameter. Dealing with Concurrency:When the changes made to the dataset by one user are updated in the database, the data in the dataset of the other users becomes Dirty and such data should not be updated unless the dataset is refeshed and latest data is modified and updated because if change are made to the dirty data and updated in database, it may override the change made by other users with out looking it those changes. Solution: The UpdateCommand and DeleteCommand CommantText must be modified to inlcude all the columns so that the Original Values of Column are compared with the values in the database fields. Ex: Update Emp Set EmpName=@EName, EmpSalay=@ESal where EmpId=@OrgEId and EmpName=@OrgEName and EmpSalary=@OrgESalary When DataAdapter#Update is executed and if it executes ethier UpdateCommand or DeleteCommand and finds the number of records effected by execution of this command is zero then it throws “DBConcurrencyException”.

1

Deccansoft Software Services – MS.NET

ADO.NET – Dataset

Dim con As New SqlConnection("server=localhost\sqlexpress;user id=sa;password=dss;database=MSNET") Dim dt As DataTable Dim WithEvents daEmp As SqlDataAdapter Dim ds As DataSet Dim dr As DataRow Private Sub DataSetForm_Load(. . .) Handles MyBase.Load daEmp = New SqlDataAdapter("Select EmpId, EmpName, EmpSalary from Emp", con) MsgBox(daEmp.SelectCommand.CommandText) ds = New DataSet() RefreshEmpIdDropDown() gvEmp.DataSource = ds.Tables(0) ''''''Insert Command''''''' Dim cmdInsert As SqlCommand Dim p(2) As SqlParameter cmdInsert = New SqlCommand("insert into Emp(EmpName,EmpSalary) values (@ename,@esalary)", con) p(0) = cmdInsert.Parameters.Add("@ename", SqlDbType.VarChar, 20) p(0).SourceColumn = "EmpName" p(0).SourceVersion = DataRowVersion.Current p(1) = cmdInsert.Parameters.Add("@esalary", SqlDbType.Float) p(1).SourceColumn = "Empsalary" p(1).SourceVersion = DataRowVersion.Current daEmp.InsertCommand = cmdInsert ''''''''Delete Command'''''''' Dim cmdDelete As SqlCommand cmdDelete = New SqlCommand("Delete from emp where empid=@orgeid", con) Dim par As SqlParameter par = cmdDelete.Parameters.Add("@orgeid", SqlDbType.Int) par.SourceColumn = "Empid" par.SourceVersion = DataRowVersion.Original daEmp.DeleteCommand = cmdDelete '''''''Update Command''''''''' Dim cmdUpdate As SqlCommand cmdUpdate = New SqlCommand("Update Emp set empname=@ename, empsalary=@esalary where empid=@orgeid", con) p(0) = cmdUpdate.Parameters.Add("@orgeid", SqlDbType.Int) p(0).SourceColumn = "Empid" p(0).SourceVersion = DataRowVersion.Original p(1) = cmdUpdate.Parameters.Add("@ename", SqlDbType.VarChar, 20) p(1).SourceColumn = "EmpName" p(1).SourceVersion = DataRowVersion.Current p(2) = cmdUpdate.Parameters.Add("@esalary", SqlDbType.Float) p(2).SourceColumn = "EmpSalary" p(2).SourceVersion = DataRowVersion.Current daEmp.UpdateCommand = cmdUpdate 'Dim sb As New SqlCommandBuilder(daEmp) 'sb.ConflictOption = ConflictOption.CompareAllSearchableValues ‘ or OverwriteChanges ‘The above statement automatically frames the InsertCommand, UpdateCommand and DeleteCommand properties of the ‘mentioned DataAdapter (daEmp) and it does so based on the columns mentioned in the SelectCommand Properties of the ‘DataAdapter. Also for this to work the database table mentioned in the Select statement of SelectCommand must have the ‘PrimaryKey defined in the backend (database).

2

Deccansoft Software Services – MS.NET

ADO.NET – Dataset

'MsgBox(sb.GetInsertCommand().CommandText) 'MsgBox(sb.GetUpdateCommand().CommandText) 'MsgBox(sb.GetDeleteCommand().CommandText) 'For Handling events of DataAdapter in C# do the following here….. 'daEmp.RowUpdated += new SqlRowUpdatedEventHandler(da_RowUpdated); 'daEmp.RowUpdating += new SqlRowUpdatingEventHandler(da_RowUpdating); End Sub Private Sub RefreshEmpIdDropDown() ds.Clear() daEmp.Fill(ds, "Emp") dt = ds.Tables("Emp") cmbId.Items.Clear() For Each dr As DataRow In dt.Rows cmbId.Items.Add(dr("EmpId")) Next cmbId.SelectedIndex = 0 End Sub Private Sub cmbId_SelectedIndexChanged(. . .) Handles cmbId.SelectedIndexChanged Dim drs() As DataRow drs = dt.Select("empid=" & cmbId.Text) ‘This method return the array of datarow based on the condition given as the first parameter. dr = drs(0) ‘Because we are filtering based on the EmpId which is PrimaryKey we will have only 1 record. ‘dt.PrimaryKey = New DataColumn(){dt.Columns(“EmpId”)} 'dr = dt.Rows.Find(cmbId.Text) ‘Can be used only if the EmpId is maked as PrimaryKey in DataTable txtName.Text = dr("EmpName").ToString() If (dr.IsNull("EmpSalary")) Then txtSalary.Text = "" Else txtSalary.Text = dr("EmpSalary").ToString() End If End Sub Private Sub btnNew_Click(. . .) Handles btnAdd.Click Dim dr As DataRow dr = dt.NewRow() ‘dr = New DataRow() 'Is invalid because the constructor of the class is Protected dr("Empname") = txtName.Text ‘EmpId is AutoIncrement thus it need not be set. dr("EmpSalary") = CSng(txtSalary.Text) dt.Rows.Add(dr) End Sub Private Sub btnModify_Click(. . .) Handles btnEdit.Click Dim dr As DataRow Dim drs() As DataRow drs = dt.Select("empid=" & cmbId.Text) dr = drs(0) dr("Empname") = txtName.Text dr("EmpSalary") = CSng(txtSalary.Text) End Sub Private Sub btnDelete_Click(. . .) Handles btnDelete.Click Dim drs() As DataRow drs = dt.Select("empid=" & cmbId.Text) dr = drs(0) Dim res As DialogResult res = MessageBox.Show("Do you really want to delete the Row", "Delete", MessageBoxButtons.YesNo) If (res = Windows.Forms.DialogResult.Yes) Then MessageBox.Show("Before Delete: " & dt.Rows.Count) dr.Delete() 'This only marks the row as deleted but the row is still there in Rows collection of DataTable MessageBox.Show("After Delete: " & dt.Rows.Count) cmbId.Items.RemoveAt(cmbId.SelectedIndex) If (cmbId.Items.Count 0) Then cmbId.SelectedIndex = 0 End Sub Private Sub btnUpdateDatabase_Click(. . .) Handles btnUpdateDatabase.Click Try

3

Deccansoft Software Services – MS.NET

ADO.NET – Dataset

daEmp.Update(ds, "Emp") 'This method executes the Insert, Update or Delete Commands of the dataadapter using the data from a given DataRow and the command executed depends upon the RowState property of the datarow. RefreshEmpIdDropDown() Catch exp As DBConcurrencyException ‘Please refer to the notes at the beginning of this handout. MsgBox(exp.Message) dt.Clear() daEmp.Fill(ds, "Emp") RefreshEmpIdDropDown() End Try End Sub ‘Event Handler of DataAdapter. Private Sub daEmp_RowUpdated(ByVal sender As Object, ByVal e As SqlRowUpdatedEventArgs) Handles daEmp.RowUpdated If (e.StatementType = StatementType.Insert) Then Dim con As SqlConnection con = e.Command.Connection ‘As the connection is already open it is not required to reopen the connection. Dim cmd As New SqlCommand("Select @@Identity", con) e.Row("EmpId") = cmd.ExecuteScalar() – EmpId of the record inserted is fetched and assigned to the current rows EmpId field. Dim index As Integer index = cmbId.Items.Add(e.Row("EmpId")) cmbId.SelectedIndex = index End If End Sub

Private Sub daEmp_RowUpdating(ByVal sender As Object, ByVal e As SqlRowUpdatingEventArgs) Handles daEmp.RowUpdating If e.StatementType == StatementType.Update Then If e.Row("EmpSalary") > 50000 Then MsgBox("Salary Cannot Be more than 50000") e.Status = UpdateStatus.SkipCurrentRow e.Row.RejectChanges() End If End If End Sub Table Mapping : Used for giving DataTable and Column Names which can be different from backend table and field names. Note: The backend column names are Case Sensitive. Private Sub btnTableMapping_Click(. . .) Handles btnTableMapping.Click Dim dtmEmp As New Data.Common.DataTableMapping("Emp", "Employee") daEmp.TableMappings.Add(dtmEmp) Dim dcm As New Data.Common.DataColumnMapping("EmpId", "ID") dtmEmp.ColumnMappings.Add(dcm) dtmEmp.ColumnMappings.Add("EmpName", "Name") dtmEmp.ColumnMappings.Add("EmpSalary", "Salary") dt.Clear() daEmp.Fill(ds, "Emp") gvEmp.DataSource = ds.Tables("Employee") End Sub DataRelation: Dim con As SqlConnection Dim ds As New DataSet() con = New SqlConnection("server=localhost\sqlexpress;user id=sa;password=dss;database=MSNET") Dim daDept As New SqlDataAdapter("select * from Dept", con) Dim daEmp As New SqlDataAdapter("select * from Emp", con) daDept.Fill(ds, "Dept") daEmp.Fill(ds, "Emp") Dim dr As DataRelation dr = New DataRelation("Dept_Emp", --Relationship Name ds.Tables("Dept").Columns("DeptId"), // -- Parent Table column reference ds.Tables("Emp").Columns("DeptId"),// - Child Table column refenrece True) //– if true it also creates a Foreign Key Constraint in Child Table. ds.Relations.Add(dr)

4

Deccansoft Software Services – MS.NET

ADO.NET – Dataset

Dim drDept As DataRow drDept = ds.Tables("Dept").Select("DeptId=1")(0) ‘Gets the reference to the Dept with DeptId=1 Dim drsEmps As DataRow() drsEmps = drDept.GetChildRows("Dept_Emp") ‘Dept_Emp is the DataRelation name Dim drEmp As DataRow Dim str As String = "" For Each drEmp In drsEmps str &= drEmp(0) & vbTab & drEmp(1) & vbCrLf Next MsgBox(str) MsgBox(ds.Tables("Emp").Rows(0).GetParentRow("Dept_Emp")("DeptName")) – Gets the name of the Department of the first emp in the Emp DataTable Employee. DataView: One DataTable can have multiple DataViews and each DataView can be Sorted and Filtered independently. Dim dt As DataTable dt = ds.Tables("Emp") Dim dvEmp As DataView dvEmp = dt.DefaultView ‘ or dv = New DataView(dt) dvEmp.RowFilter = "EmpSalary > 2000" Dim str As String = "" Dim drv As DataRowView For Each drv in dvEmp str &= drv(0) & " " & drv("EmpSalary") & vbCrLf Next MsgBox(str) dvEmp.Sort = "EmpId" MsgBox(dvEmp.Find(2)) 'Index of the row with EmpId=2 dvEmp.Sort = "EmpName,EmpSalary" ‘Sorted first using EmpName and if name is same sorts using EmpSalary MsgBox(dvEmp.Find(New Object() {"E1", 1000}))‘Gets index of row with EmpName=’E1” & EmpSalary=1000 dvEmp.Sort = "EmpName" Dim drvs() As DataRowView = dvEmp.FindRows("E1") ‘Gets the DataRowView of the row having EmpName=’E1’ Note: One DataView cannot be using multiple DataTables. Between DataTable and DataView its One to Many relationship. Creating DataSet Programmatically Dim ds As New DataSet Dim dt As New DataTable("Table") Dim dcNumber As New DataColumn("Number", GetType(Integer)) Dim dcStar As New DataColumn("*", GetType(String)) dcStar.DefaultValue = "*" Dim dcCounter As New DataColumn("Counter", GetType(String)) dcCounter.AutoIncrement = True Dim dcEquals As New DataColumn("=", GetType(String)) dcEquals.DefaultValue = "=" Dim dcResult As New DataColumn("Result", GetType(String)) dcResult.Expression = "Number * Counter" ds.Tables.Add(dt) dt.Columns.Add(dcNumber) dt.Columns.Add(dcStar) dt.Columns.Add(dcCounter) dt.Columns.Add(dcEquals) dt.Columns.Add(dcResult) For i As Integer = 1 To 10 Dim dr As DataRow dr = dt.NewRow() dr("Number") = Integer.Parse(txtNumber.Text) dt.Rows.Add(dr) Next gvTable.DataSource = ds.Tables(0) Set Primary Key for a DataTable Programmatically ds.Tables("Emp").PrimaryKey = New DataColumn(){ ds.Tables(“Emp”).Columns(“EmpId”) } The datatype of PrimaryKey is DataColumn array because in some cases it might be composite key(multiple cols)

5

Deccansoft Software Services – MS.NET

ADO.NET – Dataset

Adding ForeignKey Programmatically Dim fk As ForeignKeyConstraint fk = New ForeignKeyConstraint(ds.Tables("Dept").Columns("DeptID"), -- Primary Key ds.Tables("Emp").Columns("DeptID")) – Foreign Key fk.DeleteRule = Rule.SetNull – if Dept is deleted then all the emps in Emp table DeptId is set to Null. fk.UpdateRule = Rule.Cascade –‘If DeptId is modified in the Dept table it automatically changes in Emp table. ds.Tables("Emp").Constraints.Add(fk) Note: Any kind schema changes make to the dataset or datatable connot be reflected in backend. To Compute second last max salary Dim maxSalary As Decimal maxSalary = ds.Tables("Emp").Compute("max(empsalary)", Nothing) MsgBox(ds.Tables("Emp").Compute("max(empsalary)", "EmpSalary
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF