Unit I Evolution of .Net Framework First Introduced in early 2000’s and has gone through several versions and updates. Year 2002 2003 2005 2006 2007 2010 .NET CLR Visual Version Version Studio 1.0 1.1 2.0 3.0 3.5 4.0 1.0 Visual Studio .NET 2002 1.1 Visual Studio .NET 2003 2.0 2.0 Visual Studio 2005 Visual Studio 2005 2.0 Visual Studio 2008 4.0 Visual Studio 2010 Features and Enhancements Aimed to simplify application development and improves security It included a runtime environment called the Common Language Runtime and a class Library that provide a wide range of pre built functionality. Added support for ADO.NET classes for Oracle database and ODBC database connectivity. Introduce Significant improvements, including the Generic feature, which allowed developers to create more efficient and type safe code. Brought enhancement to Web development, ASP.net and ADO.net Although It didn’t introduce a new version of the CLR, this release added new libraries and APIs for Windows Presentation Foundation, (WPF), Windows Communication Foundation (WCF), Windows Workflow Foundation (WWF) and more. These technologies aimed to simplify building windows desktop applications, communication between services, and workflow based applications This version built upon previous release by adding features like Language Integrated Query (LINQ) and improvements to ASP.net, WCF and WPF. This release introduced major enhancements, including Task Parallel Library (TPL) for improved parallel programming, dynamic language runtime (DLR) Managed 1 2012 4.5 4.0 2013 4.5.1 4.0 2014 4.5.2 4.0 2015 4.6 4.0 2017 4.7 4.0 2019 4.8 4.0 2022 6 6.0 Visual Studio 2012 Visual Studio 2013 Visual Studio 2013 Visual Studio 2015 Visual Studio 2017 Visual Studio 2019 Visual Studio 2022 Extensibility Framework (MEF)nwere introduced in this release. Improvements to asynchronous programming with the introduction of the async and await keywords. Support for Windows Store, enhancements of WPF, WCF, WWF, MEF, and ASP.NET. Performance and debugging improvements. ASP.NET, APIs enhancements, New Workflow features and Debugging improvements features were added in this release. It focused on improving performance, security and adding various enhancements to existing features. New 64-bit JIT compiler, Assembly Loader improvements, enhancements to Garbage Collector. High DPI support for Windows Forms controls, Touch support for WPF in Windows 10, Enhanced cryptography support, performance, and reliability improvements. JIT improvements, Malware scanning for Assemblies and Accessibility Enhancements AI assisted development, Azure Cloud App Support, Integration with Git and GitHub Overview of the .Net Framework The .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The framework includes a variety of programming languages, such as C#, F#, and Visual Basic, and supports a range of application types, including desktop, web, mobile, and gaming applications. .NET Framework is designed to fulfill the following objectives: • Provide a consistent, object-oriented programming environment whether object code is stored and executed locally, or executed remotely. 2 • Provide a code-execution environment that: ✓ Minimizes software deployment and versioning conflicts. ✓ Promotes safe execution of code, including code created by an unknown or semi-trusted third party. ✓ Eliminates the performance problems of scripted or interpreted environments. • Make the developer experience consistent across widely varying types of apps, such as Windows-based apps and Web-based apps. • Build all communication on industry standards to ensure that code based on .NET Framework integrates with any other code. Advantage of .Net framework 1. It support for a variety of programming languages. 2. It support variety of application types. The framework includes libraries and tools for creating desktop, web, mobile, and gaming applications, which makes it a versatile choice for developers working on a wide range of projects. 3. The .NET Framework improves the security, reliability, and performance of applications. These include features such as code access security, automatic memory management, and just-in-time (JIT) compilation, which helps improve the speed of application execution. 4. The .NET Framework is also designed to integrate with other Microsoft technologies, such as Microsoft SQL Server, Microsoft SharePoint, and Microsoft Office, which can make it easier to build applications. 5. .NET Framework is a powerful and versatile development platform that provides a wide range of tools and libraries for building and running applications on Windows operating systems. 6. It is a virtual machine for compiling and executing programs written in different languages like C#, VB.Net, etc. 3 7. It is used to develop Form-based applications, Web-based applications, and Web services. 8. .NET Framework supports more than 60 programming languages of which 11 programming languages are designed and developed by Microsoft. The remaining Non-Microsoft Languages are supported by .NET Framework but not designed and developed by Microsoft. Disadvantages of .NET Framework: 1. Windows dependency: Although the .NET Framework can run on multiple operating systems, it was originally designed for use on Windows operating systems, which means that it may not be the best choice for cross-platform applications. 2. Large footprint: The .NET Framework has a large installation footprint, which can make it difficult to deploy applications on systems with limited storage or bandwidth. 3. Licensing: Some versions of the .NET Framework require a license, which can add to the cost of developing and deploying applications. 4. Performance: While the .NET Framework provides good performance for most applications, it may not be the best choice for high-performance applications that require low-level access to hardware or complex algorithms. 5. Learning curve: Although the .NET Framework is designed to be easy to use, it still has a learning curve, especially for developers who are new to the platform or to object-oriented programming in general. 4 Components of .NET Framework There following components of .NET Framework: 1. 2. 3. 4. 5. I. are CLR (Common Language Runtime) CTS (Common Type System) BCL (Base Class Library) CLS (Common Language Specification) FCL (Framework Class Library) CLR (common language runtime) .NET CLR is a runtime environment that manages and executes the code written in any .NET programming language. CLR is the virtual machine component of the .NET framework. That language's compiler compiles the source code of applications developed using .NET compliant languages into CLR's intermediate language called MSIL, i.e., Microsoft intermediate language code. This code is platformindependent. The main Component of CLR are o o o Class Loader - Used to load all classes at run time. MSIL to Native code - The Just In Time (JIT) compiler will convert MSIL code into native code. Code Manager - It manages the code at run time. 5 o o o Garbage Collector - It manages the memory. Collect all unused objects and deallocate them to reduce memory. Thread Support - It supports the multithreading of our application. Exception Handler - It handles exceptions at run time. .NET CLR Functions Following are the functions of the CLR. II. o It converts the program into native code. o Handles Exceptions o Provides type-safety o Memory management o Provides security o Improved performance o Language independent o Platform independent o Garbage collection o Provides language features such as inheritance, interfaces, and overloading for object-oriented programs. CTS (Common Type System) CTS purovides guidelines for declaring, using, and managing data types at runtime. It offers cross-language communication. For example, VB.NET has an integer data type, and C# has an int data type for managing integers. After compilation, Int32 is used by both data types. So, CTS provides the data types using managed code. A common type system helps in writing language-independent code. It provides two categories of Types. 1. Value Type: A value type stores the data in memory allocated on the stack or inline in a structure. This category of Type holds the data directory. If one variable's value is copied to another, both the variables store data independently. It can be of inbuilt-in types, user-defined, or enumerations 6 types. Built-in types are primitive data types like numeric, Boolean, char, and date. Users in the source code create user-defined types. An enumeration refers to a set of enumerated values represented by labels but stored as a numeric type. 2. Reference Type: A Reference type stores a reference to the value of a memory address and is allocated on the heap. Heap memory is used for dynamic memory allocation. Reference Type does not hold actual data directly but holds the address of data. Whenever a reference type object is made, it copies the address and not actual data. Therefore two variables will refer to the same data. If data of one Reference Type object is changed, the same is reflected for the other object. Reference types can be self-describing types, pointer types, or interference types. The self-describing types may be string, array, and class types that store metadata about themselves. III. BCL (Base Class Library) The base class library has a rich collection of libraries features and functions that help to implement many programming languages in the .NET Framework, such as C #, F #, Visual C ++, and more. Furthermore, BCL divides into two parts: ❖ User defined class library ✓ Assemblies - It is the collection of small parts of deployment an application's part. It contains either the DLL (Dynamic Link Library) or exe (Executable) file. ❖ Predefined class library ✓ Namespace - It is the collection of predefined class and method that present in .Net. In other languages such as, C we used header files, in java we used package similarly we used "using system" in .NET, where using is a keyword and system is a namespace. IV. CLS (Common language Specification) 7 It is a subset of common type system (CTS) that defines a set of rules and regulations which should be followed by every language that comes under the .net framework. In other words, a CLS language should be cross-language integration or interoperability. For example, in C# and VB.NET language, the C# language terminate each statement with semicolon, whereas in VB.NET it is not end with semicolon, and when these statements execute in .NET Framework, it provides a common platform to interact and share information with each other. V. FCL (Framework Class Library) It provides the various system functionality in the .NET Framework, that includes classes, interfaces and data types, etc. to create multiple functions and different types of application such as desktop, web, mobile application, etc. In other words, it can be defined as, it provides a base on which various applications, controls and components are built in .NET Framework. Key Components of FCL ✓ ✓ ✓ ✓ ✓ ✓ Object type Implementation of data structure Base data types Garbage collection Security and database connectivity Creating common platform for window and web-based application 8 Basic Definition WinForms Windows Forms is a smart client technology for the .NET Framework, a set of managed libraries that simplify common application tasks such as reading and writing to the file system. ASP.NET ASP.NET is a web framework designed and developed by Microsoft. It is used to develop websites, web applications, and web services. It provides a fantastic integration of HTML, CSS, and JavaScript. It was first released in January 2002. ADO.NET (ActiveX Data Objects) 9 ADO.NET is a module of .Net Framework, which is used to establish a connection between application and data sources. Data sources can be such as SQL Server and XML. ADO .NET consists of classes that can be used to connect, retrieve, insert, and delete data. WPF (Windows Presentation Foundation) Windows Presentation Foundation (WPF) is a graphical subsystem by Microsoft for rendering user interfaces in Windows-based applications. WPF, previously known as "Avalon", was initially released as part of .NET Framework 3.0 in 2006. WPF uses DirectX. WCF (Windows Communication Foundation) It is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. WF (Workflow Foundation) Windows Workflow Foundation (WF) is a Microsoft technology that provides an API, an in-process workflow engine, and a rehostable designer to implement longrunning processes as workflows within .NET applications. LINQ (Language Integrated Query) It is a query language, introduced in .NET 3.5 framework. It is used to make the query for data sources with C# or Visual Basics programming languages. Entity Framework It is an ORM based open source framework which is used to work with a database using .NET objects. It eliminates a lot of developers' effort to handle the database. It is Microsoft's recommended technology to deal with the database. Parallel LINQ Parallel LINQ or PLINQ is a parallel implementation of LINQ to objects. It combines the simplicity and readability of LINQ and provides the power of parallel programming. It can improve and provide fast speed to execute the LINQ query by using all available computer capabilities. 10 AJAX AJAX is a web development technique for creating interactive web applications. If you know JavaScript, HTML, CSS, and XML, then you need to spend just one hour to start with AJAX. Why to Learn Ajax? AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script. With the help of AJAX we can communicate with server without page reload. ● Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and JavaScript for dynamic content display. ● Conventional web applications transmit information to and from the sever using Synchronous requests. It means you fill out a form, hit submit, and get directed to a new page with new information from the server. ● With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the results, and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server. ● XML is commonly used as the format for receiving server data, although any format, including plain text, can be used. ● AJAX is a web browser technology independent of web server software. ● A user can continue to use the application while the client program requests information from the server in the background. Rich Internet Application Technology 11 AJAX is the most viable Rich Internet Application (RIA) technology so far. It is getting tremendous industry momentum and several tool kit and frameworks are emerging. But at the same time, AJAX has browser incompatibility and it is supported by JavaScript, which is hard to maintain and debug. AJAX is Based on Open Standards AJAX is based on the following open standards − ● Browser-based presentation using HTML and Cascading Style Sheets (CSS). ● Data is stored in XML format and fetched from the server. ● Behind-the-scenes data fetches using XMLHttpRequest objects in the browser. ● Java Script to make everything happen. Where it is used? There are too many web applications running on the web that are using ajax technology like gmail, facebook, twitter, google map, youtube etc. How AJAX Works 12 Example Program <!DOCTYPE html> <html> <body> <div id="demo"> <h2>Let AJAX change this text</h2> <button type="button" onclick="loadDoc()">Change Content</button> </div> </body> </html> function loadDoc() { const xhttp = new XMLHttpRequest(); xhttp.onload = function() { document.getElementById("demo").innerHTML = this.responseText; } xhttp.open("GET", "ajax_info.txt", true); xhttp.send(); } Windows Forms 13 Windows Forms is a UI framework for building Windows desktop apps. It provides one of the most productive ways to create desktop apps based on the visual designer provided in Visual Studio. Functionality such as drag-and-drop placement of visual controls makes it easy to build desktop apps. Let's start with creating a Window Forms Application by following the following steps in Microsoft Visual Studio - File → New Project → Windows Forms Applications Finally, select OK, Microsoft Visual Studio creates your project and displays following window Form with a name Form1. Visual Basic Form is the container for all the controls that make up the user interface. Every window you see in a running visual basic application is a form, thus the terms form and window describe the same entity. Visual Studio creates a default form for you when you create a Windows Forms Application. 14 Every form will have title bar on which the form's caption is displayed and there will be buttons to close, maximize and minimize the form shown below – If you click the icon on the top left corner, it opens the control menu, which contains the various commands to control the form like to move control from one place to another place, to maximize or minimize the form or to close the form. Form Properties Following table lists down various important properties related to a form. These properties can be set or read during application execution. 15 Properties Description BackColor Sets the form background color. BorderStyle The Border Style property determines the style of the form's border and the appearance of the form – ● None − Borderless window that can't be resized. ● Sizable − This is default value and will be used for resizable window that's used for displaying regular forms. ● Fixed3D − Window with a visible border, "raised" relative to the main area. In this case, windows can't be resized. ● FixedDialog − A fixed window, used to create dialog boxes. ● FixedSingle − A fixed window with a single line border. ● FixedToolWindow − A fixed window with a Close button only. It looks like the toolbar displayed by the drawing and imaging applications. ● SizableToolWindow − Same as the FixedToolWindow but resizable. In addition, its caption font is smaller than the usual. ControlBox By default, this property is True and you can set it to False to hide the icon and disable the Control menu. Enabled If True, allows the form to respond to mouse and keyboard 16 events; if False, disables form. Font This property specify font type, style, size Form Methods The following are some of the commonly used methods of the Form class. You can refer to Microsoft documentation for a complete list of methods associated with forms control − Method Name Description Activate - Activates the form and gives it focus. ActivateMdiChild - Activates the MDI child of a form. Close - Closes the form. Focus - Sets input focus to the control. Hide - Conceals the control from the user. Refresh - Forces the control to invalidate its client area and immediately redraw itself and any child controls. Show - Displays the control to the user. Form Events Following table lists down various important events related to a form. You can refer to Microsoft documentation for a complete list of events associated with forms control − Event Description Activated Occurs when the form is activated in code or by the user. Click Occurs when the form is clicked. Closed Occurs before the form is closed. Closing Occurs when the form is closing. 17 DoubleClick Occurs when the form control is double-clicked. DragDrop Occurs when a drag-and-drop operation is completed. GotFocus Occurs when the form control receives focus. KeyDown Occurs when a key is pressed while the form has focus. KeyPress Occurs when a key is pressed while the form has focus. KeyUp Occurs when a key is released while the form has focus. Load Occurs before a form is displayed for the first time. LostFocus Occurs when the form loses focus. MouseDown Occurs when the mouse pointer is over the form and a mouse button is pressed. MouseEnter Occurs when the mouse pointer enters the form. MouseHover Occurs when the mouse pointer rests on the form. MouseLeave Occurs when the mouse pointer leaves the form. MouseMove Occurs when the mouse pointer is moved over the form. MouseUp Occurs when the mouse pointer is over the form and a mouse button is released. The ASP Technology 18 ASP and ASP.NET are server side technologies. Both technologies enable computer code to be executed by an Internet server. When a browser requests an ASP or ASP.NET file, the ASP engine reads the file, executes any code in the file, and returns the result to the browser. ASP.NET ASP.NET is a web application framework developed and marketed by Microsoft to allow programmers to build dynamic web sites. It allows you to use a full featured programming language such as C# or VB.NET to build web applications easily. ASP.NET was released in 2002 as a successor to Classic ASP. ASP.NET pages have the extension .aspx and are normally written in C# (C sharp). ASP.NET 4.6 is the latest official version of ASP.NET. ASP.NET 5 was expected to be an important redesign of ASP.NET. However, the development of ASP.NET 5 was stopped in favor of ASP.NET Core. ASP.NET is a web development platform, which provides a programming model, a comprehensive software infrastructure and various services required to build up robust web applications for PC, as well as mobile devices. ASP.NET works on top of the HTTP protocol, and uses the HTTP commands and policies to set a browser-to-server bilateral communication and cooperation. ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiled codes, written using the extensible and reusable components or objects present in .Net framework. These codes can use the entire hierarchy of classes in .Net framework. 19 The ASP.NET application codes can be written in any of the following languages: ● C# ● Visual Basic.Net ● Jscript ● J# ASP.NET is used to produce interactive, data-driven web applications over the internet. It consists of a large number of controls such as text boxes, buttons, and labels for assembling, configuring, and manipulating code to create HTML pages. ASP.NET Web Forms Model ASP.NET web forms extend the event-driven model of interaction to the web applications. The browser submits a web form to the web server and the server returns a full markup page or HTML page in response. All client side user activities are forwarded to the server for stateful processing. The server processes the output of the client actions and triggers the reactions. Now, HTTP is a stateless protocol. ASP.NET framework helps in storing the information regarding the state of the application, which consists of: ● Page state ● Session state The page state is the state of the client, i.e., the content of various input fields in the web form. The session state is the collective information obtained from various pages the user visited and worked with, i.e., the overall session state. The ASP.NET Component Model The ASP.NET component model provides various building blocks of ASP.NET pages. Basically it is an object model, which describes: ● Server side counterparts of almost all HTML elements or tags, such as <form> and <input>. 20 ● Server controls, which help in developing complex user-interface. For example, the Calendar control or the Gridview control. ADO.NET ADO.NET provides a bridge between the front end controls and the back end database. The ADO.NET objects encapsulate all the data access operations and the controls interact with these objects to display data, thus hiding the details of movement of data. The following figure shows the ADO.NET objects at a glance: The DataSet Class 21 The dataset represents a subset of the database. It does not have a continuous connection to the database. To update the database a reconnection is required. The DataSet contains DataTable objects and DataRelation objects. The DataRelation objects represent the relationship between two tables. Following table shows some important properties of the DataSet class: Properties CaseSensitive Description Indicates whether string comparisons within the data tables are casesensitive. DataSetName Gets or sets the name of the current data set. Tables Returns the collection of DataTable objects. The following table shows some important methods of the DataSet class: Methods Copy BeginInit Clear Description Copies both structure and data. Begins the initialization of the DataSet. The initialization occurs at run time. Clears data. EndInit Ends the initialization of the data set. Equals(Object) Determines whether the specified Object is equal to the current Object. Finalize Free resources and perform other cleanups. Merge() Merges the data with data from another DataSet. This method has different overloaded forms. The DataTable Class 22 The DataTable class represents the tables in the database. It has the following important properties; most of these properties are read only properties except the Primary Key property: Properties Columns Description Returns the Columns collection. Constraints Returns the Constraints collection. DataSet Returns the parent DataSet. PrimaryKey Gets or sets an array of columns as the primary key for the table. Rows Returns the Rows collection. The following table shows some important methods of the DataTable class: Methods Description AcceptChanges Commits all changes since the last AcceptChanges. Clear Clears all data from the table. GetErrors Returns an array of rows with errors. LoadDataRow Finds and updates a specific row, or creates a new one, if not found any. Reset Resets the table to its original state. Merge Merges the table with another DataTable. NewRow Creates a new DataRow. The DataRow Class 23 The DataRow object represents a row in a table. It has the following important properties: Properties Description HasErrors Indicates if there are any errors. Items Gets or sets the data stored in a specific column. ItemArrays Gets or sets all the values for the row. Table Returns the parent table. The following table shows some important methods of the DataRow class: Methods Description BeginEdit Begins edit operation. CancelEdit Cancels edit operation. Delete Deletes the DataRow. EndEdit Ends the edit operation. The DataAdapter Object The DataAdapter object acts as a mediator between the DataSet object and the database. This helps the Dataset to contain data from multiple databases or other 24 data source. The DataReader Object The DataReader object is an alternative to the DataSet and DataAdapter combination. This object provides a connection oriented access to the data records in the database. These objects are suitable for read-only access, such as populating a list and then breaking the connection. DbCommand and DbConnection Objects The DbConnection object represents a connection to the data source. The connection could be shared among different command objects. The DbCommand object represents the command or a stored procedure sent to the database from retrieving or manipulating data. Then you execute the program, observe the following: ● The application first creates a data set and binds it with the grid view control using the DataBind() method of the GridView control. ● The Createdataset() method is a user defined function, which creates a new DataSet object and then calls another user defined method CreateStudentTable() to create the table and add it to the Tables collection of the data set. ● The CreateStudentTable() method calls the user defined methods AddNewColumn() and AddNewRow() to create the columns and rows of the table as well as to add data to the rows. 25 When the page is executed, it returns the rows of the table as shown: Features of .NET Framework / Benefits of .NET Framework ● OOPs Support: .NET provides a fully object oriented environment. The philosophy of .NET is – “Object is mother of all.” Languages like Visual Basic.NET now support many of the OO features that were lacking traditionally. Even primitive types like integers and characters can be treated as objects – something not available even in OO languages like C++. ● Support for Multiple Languages and Language Interoperability: The CLR executes binary code called MSIL (Microsoft intermediate language), and that code looks the same regardless of the original source language. Within the .NET Framework is a compiler called the Just-In-Time, or JIT, compiler. It compiles the MSIL down to machine specific code. All .NET –enabled languages use the same data types and the same interfacing conventions. This makes it possible for all .NET languages to interoperate transparently. 26 ● Cross-platform support: Any windows operating system that supports the Common Language Runtime (CLR) can execute a .NET application, i.e. .NET application enables interoperability between multiple windows system. ● Rich Functionality out of the box: .NET framework contains hundreds of classes that provide a variety of functionality ready to use in the application to perform many operations such as file IO, network communication and so on. ● Easy Deployment: Executable modules in .NET are self-describing. Once the Common Language Runtime (CLR) knows where a module resides, it can find out everything else it needs to know to run the module, such as the module’s object interface and security requirements, from the module itself. That means a module can just be copied to a new environment and immediately executed. ● Code Access Security: .NET supplies a standard security mechanism, available to all parts of the application and also gives automatic access to benefits such as garbage collection (which destroys objects and reclaims memory for you) and more. ● Debugging Tools: .NET provides integrated debugging tools. Any language that targets the .NET Framework can be debugged with that single debugger. ● Distributed Systems: Microsoft.NET supports developing globally distributed systems using which from servers to Wireless Palmtops, with everything in between, will share the same general platform, with versions of .NET available for all of them, and with each of them able to integrate transparently with the others. 27 ● Richer User Interface: There are commonly used controls, such as Labels and Text Boxes, in both, with similar sets of properties and method and hence development of the internet environment looks very much like development for other types of software. The built-in intelligence of Web Forms allows rich, browserindependent screens to be developed quickly, and to be easily integrated with compiled code. Microsoft has announced an initiative for the future called the Universal Canvas which builds upon the XML standards to transform the internet from a Read only environment into a read/write platform, enabling users to interactively create, browse, edit and analyze information. The universal canvas can bring together multiple sources of information anywhere in the world to enable seamless data access and use. ● Extendibility: The completely object based approach of .NET is designed to allow base functionality to be extended through inheritance (unlike COM) and the platform’s functionality is appropriately partitioned to allow various parts (such as the just-in-time compilers) to be replaced as new versions are needed. It is likely that, in the future, new ways of interfacing to the outside world will be added to the current trio of windows Form, Web Forms, and Web Services such as universal Canvas. ● Portability of compiled Applications: .NET allows the future possibility of moving software to other hardware and operating system platforms. The ultimate goal is that compiled code produced on one implementation of .NET (such as Windows) could be moved to another implementation of .NET on a different operating system merely by copying the compiled code over and running it. 28 ● Integrity with COM: .NET integrates very well with COM-based software. The .NETFramework wraps COM components and exposes an interface that .NET components canwork with. This is absolutely essential to the quick acceptance of .NET, because it makes.NET interoperable with a tremendous amount of older COM-based software. .NETprovides a possible solution to DLL Hell, and removes much of the complexity of dealingwith COM and the registry..NET allows you to run components locally without requiringthe calling application to go to the registry to find components. VB.NET Language VB.Net is a simple, modern, object-oriented computer programming language developed by Microsoft to combine the power of .NET Framework and the common language runtime with the productivity benefits that are the hallmark of Visual Basic. Like all other .NET languages, VB.NET has complete support for objectoriented concepts. Everything in VB.NET is an object, including all of the primitive types (Short, Integer, Long, String, Boolean, etc.) and user-defined types, events, and even assemblies. All objects inherit from the base class Object. VB.NET is implemented by Microsoft's .NET framework. Therefore, it has full access to all the libraries in the .Net Framework. It's also possible to run VB.NET programs on Mono, the open-source alternative to .NET, not only under Windows, but even Linux or Mac OSX. The following reasons make VB.Net a widely used professional language − 29 ● Modern, general purpose. ● Object oriented. ● Component oriented. ● Easy to learn. ● Structured language. ● It produces efficient programs. ● It can be compiled on a variety of computer platforms. ● Part of .Net Framework. Simple VB.Net Program A VB.Net program basically consists of the following parts: ● Namespace declaration ● A class or module ● One or more procedures ● Variables ● The Main procedure ● Statements & Expressions ● Comments The following program displays the message “Hello World” in the Console Window Imports System Module Module1 'This program will display Hello World 30 Sub Main() Console.WriteLine ("HelloWorld") Console.ReadKey() End Sub End Module VARIABLES Variable is a temporary storage location for data in your application. It can hold the result of a specific calculation, information received from user at runtime or piece of data that you want to display on a page Variable naming conventions ● Variable name can contain digits, alphabets and the underscore character ● First character should not be a digit ● Keywords should not be used as variable name. However it can be used if it is prefixed with the @ character ● Variable names are not case sensitive (i.e) variable names sum and Sum are treated as same in Vb.NET Variables can be declared in two ways ● Explicit Variable declaration ● Implicit Variable declaration Explicit Variable declaration Here we declare the variable explicitly by specifying variable name and type after the Dim statement. It is strongly recommended method for variable declaration. Syntax Dim VariableName as Type [ = Initial value] 31 Examples Dim m, n as Single Dim Fact as Integer = 1 Dim s as String Dim p as Point = new Point(12,15) Implicit Variable declaration We can declare the variable implicitly that is simply by using the variable without declaring it first. Implicit variable declaration is not allowed by default. We have to place Option Explicit Off at the top of the page to allow implicit variable declaration. Example Option Explicit Off Public class Form1 Private sub form1_load(...) s= “Hello” MsgBox(s) End sub End Class Another method is to use Option Infer Statement. If Option Infer is set to ON, VB.NET will deduce or infer the type of variable by examining the assignment you make. Example Dim a = 10 It is equivalent to Dim a as Integer=10 Implicit variable declaration is a risky method as it results in misspelled variable name and other errors. 32 CONSTANTS Constant is a meaningful name that takes place of a number or text string that does not change throughout the execution of a program. Constants are declared with “const” keyword as follow const PI as Double = 3.1415 Benefits of constants ● Increases the readability of code ● Makes global changes easier to accomplish ● Reduce programming mistakes BOXING AND UNBOXING Boxing and unboxing is an important concept in VB.NET's type system. With Boxing and Unboxing, one can link between value-types and reference-types by allowing any value-type to be converted to and from object type. Boxing is a mechanism in which value type is converted into reference type. It is implicit. Unboxing is a mechanism in which reference type is converted into value type. It is explicit conversion process. Program to show Boxing and Unboxing o=i Module Module1 Sub Main() Dim i As Integer = 10 33 Dim j As Integer Dim o As Object ' boxing'unboxing j = CInt(o) Console.WriteLine("Value of o object : " & o) Console.WriteLine("Value of j : " & j) Console.ReadLine() End Sub End Module This example shows both boxing and unboxing. When a variable of a value type needs to be converted to a reference type, an object box is allocated to hold the value, and the value is copied into the box. Unboxing is just the opposite. When an object box is cast back to its original value type, the value is copied out of the box and into the appropriate storage location. DATA TYPES Data types specify the size and type of values that can be stored. In Visual Basic, data types are classified according to whether a variable of a particular type stores its own data or a pointer to the data. If it stores its own data it is a value type; if it holds a pointer to data elsewhere in memory it is a reference type. ` Value Types 34 A data type is a value type if it holds the data within its own memory allocation. Value types are of fixed length and stored on the stack. Value types include the following: ● All primitive data types ✔ Integer Types –sbyte, byte, short ,ushort, int, uint, long, ulong ✔ Floating point types – float, double, decimal ✔ Char type ✔ Boolean type ● Structures ● Enumerations Integer Types The Integer type is used to represent a whole number. Integer data types include the following types. Data Type .Net Type Name Size Byte(unsigned) System.Byte 8 bits Short(signed) System.Int16 16 bits Integer(signed) System.Int32 32 bits Long(signed) System.Int64 64 bits SByte(signed) System.Sbyte 8 bits Short(unsigned) System.Uint16 16 bits UInteger(unsigned) System.Uint32 32 bits ULong(unsigned) System.Uint64 64 bits Floating point types It is used to represent fractional values. Floating point data types includes the 35 following types Data Type .Net Type Name Size Single System.Single 32 bits Double System.Double 64 bits Decimal System.Decimal 128 bits Single Type It is used to represent a fractional number with seven decimal digits of precision. Append F to treat numeric literal as Single. Double Type It is used to represent a fractional number with 15 decimal digits of precision. Append R to treat numeric literal as Double. Decimal Type It is more precise than single or double. It has 28 decimal digits of precision. Append D to treat numeric literal as Decimal. Char Type It is used to represent a single Unicode character. It is of 2 bytes in length. Append c when initializing a char Boolean Type Boolean type represents the Boolean value true or false. It is assigned 16 bits. Structure Type The structure data type is used to define a composite date type. Defining a Structure Public Structure Point Dim x as Integer Dim x as Integer End Structure Accessing a Structure 36 Dim p as Point p.x=100 p.y=200 Enum Type The Enum type is used to represent a set of named constants Example Enum Direction West East North South End Enum Reference Type A reference type contains a pointer to another memory location that holds the data. Reference types are of variable length and stored on the heap. Reference types include the following: ● Object ● String ● Class ● Interface ● Delegate ● Arrays Object Type The Object type is a predefined referenced type. It serves as the base class for all predefined and user defined classes. String Type The String type is also a predefined reference type. It is used for creating and manipulating strings. We can perform various operations on string, such as copying, comparing, searching, concatenating and so on. Classes Classes provide the best approach to group together the logically related items and functions that work on them 37 Interface Interfaces are a collection of members, such as methods, delegates, events and Properties which are to be implemented by classes Delegates Delegates are used to encapsulate a method with a specific signature. It is similar to function pointer in c++ Arrays Arrays are used to store a fixed size sequential collection of elements of same type. Value type Reference type Value type store real data Reference type store reference to the data. Value type are stored on stack of memory Reference type are stored on heap of memory When passed as value type, new copy is When passed as Reference type then created and passed. So changes to reference of that variable is passed. So variable does not getreflected back changes to variable does get reflected back Value types are faster in access Reference types are slower in access. Value type consists of primitive data types, structures, enumerations. Reference type consists of class, array, interface, delegates Value types derive from System.ValueType Reference types derive from System.Object Value types cannot contain the value null. Reference types can contain the value null. Example: Module DataTypes Sub Main() Dim b As Byte Dim n As Integer Dim si As Single 38 Dim d As Double Dim da As Date Dim c As Char Dim s As String Dim bl As Boolean b=1 n = 1234567 si = 0.12345678901234566 d = 0.12345678901234566 da = Today c = "U"c s = "Me" If ScriptEngine = "VB" Then bl = True Else bl = False End If If bl Then 'the oath taking Console.Write(c & " and," & s & vbCrLf) Console.WriteLine("declaring on the day of: {0}", da) Console.WriteLine("We will learn VB.Net seriously") Console.WriteLine("Lets see what happens to the floating point variables:") Console.WriteLine("The Single: {0}, The Double: {1}", si, d) End If Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − U and, Me declaring on the day of: 12/4/2012 12:00:00 PM We will learn VB.Net seriously Lets see what happens to the floating point variables: The Single:0.1234568, The Double: 0.123456789012346 39 OPERATORS An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. VB.Net is rich in built-in operators and provides following types of commonly used operators: ● Arithmetic Operators ● Comparison Operators ● Logical/Bitwise Operators ● Bit Shift Operators ● Assignment Operators ● Concatenation Operators Arithmetic Operators Arithmetic operators are used in mathematical expressions. The following table lists the arithmetic operators: Assume integer variable A holds 5 and variable B holds 2, then: Operator Description Example + Addition A + B will give 7 - Subtraction A - B will give 3 * Multiplication A * B will give 10 / Division A / B will give 2.5 \ Integer Division(Whole No Division) A \ B will give 2 Remainder Division A mod B will give 1 Exponentiation(Raising to a power) A ^ B will 25 Mod ^ Comparison Operators Following table shows all the comparison operators supported by VB.Net. Assume variable A holds 10 and variable B holds 20, then Operator = Description Equal to Example A = B will give false 40 <> Not Equal to A <> B will give true < Less than A < B will give true > Greater Than A > B will give false <= Less than equal to A <= B will give true >= Greater than equal to A >= B will give false Logical/Bitwise Operators Bitwise operator works on bits and performs bit-by-bit operation. Following table shows all the logical operators supported by VB.Net. Assume variable A holds Boolean value True and variable B holds Boolean value False, then Operator Description Example NOT Logical as well as bitwise negation operator NOT A will give false AND Logical as well as bitwise Conjunction operator A AND B will giveFalse OR Logical as well as bitwise disjunction operator A OR B will give true XOR Logical as well as bitwise exclusion operator A XOR B will givetrue AndAlso Short Circuiting Logical Conjunction operator A AndAlso B will give False OrElse Short Circuiting Logical Disjunction operator A OrElse B will give true Truth Table for logical operator A B Not A A and B 41 A Or B A Xor B False False True False False False False True True False True True True False False False True True True True False True True False AndAlso When the left hand side is false, the condition of right hand side is never Evaluated A B A AndAlso B False Never Evaluated False True False False True True True OrElse When the left hand side is true, the condition of right hand side is never Evaluated. A B A AndAlso B True Never Evaluated True False True True False False False 42 Bit Shift Operator There are two bit shift operators. They are, << - Bit Shift Left Operator >> - Bit Shift Left Operator Concatenation Operator Concatenation Operators are used to join multiple strings into a single string. There are two concatenation operator namely “+” and “&” Assignment Operator Operation Long form syntax Shortcut Syntax Addition x=x+6 x += 6 Subtraction x=x-6 x -= 6 Multiplication x=x*6 x *= 6 Division x=x/6 x /= 6 Integer Division x=x\6 x \= 6 Exponentiation x=x^6 x ^= 6 String Concatenation x = x & “abc” x &= “abc” Operator Precedence Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first Operator Precedence 43 () Parenthesis ^ Exponentiation - Unary negation *,/ / Integer division Mod +,<< , >> All comparison operators (=, <>, <, <=, >, >=) Not And, AndAlso Or, OrElse Highest Xor Lowest Controls in Windows Forms Control Class The control class is the ultimate base class for all Windows Forms controls. This class implements base functionalities, such as handling user input through keyboard and mouse and defining position and size of a control that displays information to the user. It is defined in the namespace System.Windows.Forms namespace. The Control class defines properties, methods, and events, which are common to all Windows Forms controls 44 Some Properties of Control class ● Font : Gets or sets the font of the text displayed by the control. ● BackColor : Gets or sets the background color for the control. ● ForeColor : Gets or sets the foreground color of the control ● Margin : Gets or sets the space between controls. ● Size : Gets or sets the height and width of the control. ● Dock : Gets or sets which control borders are docked to its parent control and determines how a control is resized with its parent. ● Text : Gets or sets the text associated with this control. ● Visible : Gets or sets a value indicating whether the control and all its child controls are displayed. ● Enabled : Gets or sets a value indicating whether the control can respond to user interaction. ● Parent : Gets or sets the parent container of the control Some methods of Control class ● Hide() : Conceals the control from the user ● Show() : Displays the control to the user. ● Focus() : Sets input focus to the control. ● Select() : Activates the control. Some Events of Control class ● Click : Occurs when the control is clicked. 45 ● DoubleClick : Occurs when the control is double-clicked. ● GotFocus : Occurs when the control receives focus. ● LostFocus : Occurs when the control loses focus. ● KeyDown : Occurs when a key is pressed down while the control has focus. ● KeyPress : Occurs when a key is pressed while the control has focus. ● KeyUp : Occurs when a key is released while the control has focus. Label Control The Label control is one of the most commonly used windows Form controls. Label controls are typically used to provide descriptive text for a control. For example, you can use a Label to add descriptive text for a TextBox control to inform the user about the type of data expected in the control. Label is a non selectable control. Unlike other controls, it is not meant to accept input from user. Instead it displays a text that user can view but not select or modify. Some Properties of Label ● BorderStyle : Gets or sets the border style for the control. ● Image : Gets or sets the image that is displayed on a Label. ● ImageAlign : Gets or sets the alignment of an image that is displayed in the control. ● Text : Gets or sets the text associated with this control. 46 ● TextAlign : Gets or sets the alignment of text in the label. TextBox Control TextBox control lets you enter text on a Windows form at runtime. Typically, itis used to display or accept a single line of text. You can use the Multiline andScrollBars properties to enable multiple lines of text to be displayed or entered.Set the AcceptsTab and AcceptsReturn properties to true to enable greater textmanipulation in a multiline TextBox control. It can also be used to acceptpasswords and other sensitive information. You can use the PasswordChar property to mask characters entered in the TextBox You can limit the amount of text entered into a TextBox control by setting the MaxLength property to a specific number of characters. Use the CharacterCasing property to enable the user to type only uppercase, only lowercase, or a combination of uppercase and lowercase characters into theTextBox control. Some Properties of TextBox ● Multiline : Gets or sets a value indicating whether this is a multiline TextBox control. ● AcceptsReturn : Gets or sets a value indicating whether pressing ENTER in a multiline TextBox control creates a new line of text in the control ● AcceptsTab : Gets or sets a value indicating whether pressing the TAB key in a multiline text box control types a TAB character in the control instead of moving the focus to the next control in the tab order ● PasswordChar : Gets or sets the character used to mask characters of a password in a single-line TextBox control ● Text : Gets or sets the current text in the TextBox. 47 ● SelectedText : Gets or sets a value indicating the currently selected text in the control ● CharacterCasing : Gets or sets whether the TextBox control modifies the case of characters as they are typed. The possible values are :Lower, Normal or Upper ● ReadOnly : Gets or sets a value indicating whether text in the text box is read-only Some Methods of TextBox ● Clear() - Clears all text from the text box control. ● Copy() - Copies the current selection in the text box to the Clipboard. ● Cut() - Moves the current selection in the text box to the Clipboard ● Paste() - Replaces the current selection in the text box with the contents of the Clipboard. ● SelectAll() - Selects all text in the text box. ● Undo() - Undoes the last edit operation in the text box ● Focus() - Sets input focus to the control Important Event of TextBox ● TextChanged : Occurs when the Text property value changes. Button Control Buton control lets you generate a Click event; by handling the click event of a button, you can make the user perform some action at the runtime. A Button can be clicked by using the mouse, ENTER key, or SPACEBAR if the button 48 has focus. Some Properties of Button ● Image : Gets or sets the image that is displayed on a button control. ● ImageAlign : Gets or sets the alignment of the image on the button Control ● Text : Gets or sets the text associated with this control. ● TextAlign : Gets or sets the alignment of the text on the button control. Important event of Button ● Click : Occurs when the 49