visual programming it0309 semester number 051).pdf · visual programming_it0309 semester...

68
VISUAL PROGRAMMING_IT0309 Semester Number05 G.Sujatha & R.Vijayalakshmi Assistant professor(O.G) SRM University, Kattankulathur 12/26/2012 School of Computing, 1

Upload: vutram

Post on 26-Jun-2018

228 views

Category:

Documents


0 download

TRANSCRIPT

VISUAL PROGRAMMING_IT0309Semester Number‐05 

G.Sujatha & R.VijayalakshmiAssistant professor(O.G)

SRM University, Kattankulathur

12/26/2012School of Computing,  1

UNIT  1

12/26/2012School of Computing, Department of  2

Disclaimer

The contents of the slides are solely for thepurpose of teaching students at SRMUniversity. All copyrights and Trademarks oforganizations/persons apply even if notspecified explicitly.

12/26/2012School of Computing, Department of  3

CONTENTS

• Introduction to .NET and C#: Overview of the .NET Framework 

• Common Language Runtime • Framework Class Library ‐ Understanding the C# Compiler. 

• Basics of C#: Working with Variables ‐Making Decisions.

• Classes and Objects: • Methods – Properties • Interface‐ Partialclass• Null and Casting as. Handling Exceptions.

12/26/2012School of Computing, Department of  4

Introduction to .NET and C#

• NET PlatformWeb‐based applications can bedistributed to a variety of devicesand desktops 

• C#developed specifically for .NET 

• .NET initiative– Introduced by Microsoft (June 2000)

• Vision for embracing the Internet in software development

12/26/2012School of Computing, Department of  5

Introduction to .NET and C#

– Independence from specific language or platform

• Applications developed in any .NET‐compatible language

– Visual Basic.NET, Visual C++.NET, C# and more

• Supports portability and interoperability

– Architecture capable of existing on multiple platforms

• Supports portability

12/26/2012School of Computing, Department of  6

Introduction to .NET and C#

• Key components of .NET– Web services

• Applications used over the Internet– Software reusability

• Web services provide solutions for variety of companies– Cheaper than one‐time solutions that can’t be reused– Single applications perform all operations for a company via various Web services

» Manage taxes, bills, investments and more

• Pre‐packaged components using Visual Programming• (buttons, text boxes, scroll bars)

– Make application development quicker and easier

12/26/2012School of Computing, Department of  7

Overview of the .NET Framework

• The .NET Framework is an integral Windows component that supports building and running the next generation of applications and XML Web services. The .NET Framework is designed to fulfill the following objectives: 

• To provide a consistent object‐oriented programming environment whether object code is stored and executed locally, executed locally but Internet‐distributed, or executed remotely.

12/26/2012School of Computing, Department of  8

Overview of the .NET Framework

• To provide a code‐execution environment that minimizes software deployment and versioning conflicts.

• To provide a code‐execution environment that promotes safe execution of code, including code created by an unknown or semi‐trusted third party.

• To provide a code‐execution environment that eliminates the performance problems of scripted or interpreted environments.

12/26/2012School of Computing, Department of  9

Overview of the .NET Framework

• To make the developer experience consistent across widely varying types of applications, such as Windows‐based applications and Web‐based applications.

• To build all communication on industry standards to ensure that code based on the .NET Framework can integrate with any other code.

12/26/2012School of Computing, Department of  10

Common Language Runtime 

• Central part of framework– Executes programs

• Compilation process– Two compilations take place

• Programs compiled to Microsoft Intermediate Language (MSIL)

– Defines instructions for CLR

• MSIL code translated into machine code– Platform‐specific machine language

12/26/2012School of Computing, Department of  11

Common Language Runtime 

• Why two compilations?– Platform independence

• .NET Framework can be installed on different platforms• Execute .NET programs without any modifications to code• .NET compliant program translated into platform independent MSIL

– Language independence• MSIL form of .NET programs not tied to particular language• Programs may consist of several .NET‐compliant languages• Old and new components can be integrated• MSIL translated into platform‐specific code

• Other advantages of CLR– Execution‐management features

• Manages memory, security and other features– Relieves programmer of many responsibilities– More concentration on program logic

12/26/2012School of Computing, Department of  12

Framework Class Library

• Importance of the Base Class Library• • Software developer use a personalized set of tools in terms of classes

• and components.• • The more complete this set of tools is, the faster is the development

• process of a new application.• – No common base class library under C++! Many different string

• classes.

12/26/2012School of Computing, Department of  13

Framework Class Library

• • The .NET class library adds some modern aspects:

• – XML• – Cryptography• – Reflection• – Windows Forms• • The .NET class library provides a common interface between all the

• different .NET programming languages.

12/26/2012School of Computing, Department of  14

Framework Class Library

12/26/2012School of Computing, Department of  15

Framework Class Library

12/26/2012School of Computing, Department of  16

Understanding the C# Compiler

Overview of C# compilation

• Compilation consists of producing assembly files (executable or library files) from C# source files previously generated, through the production of a makefile file.

• Compilation is run either directly on a component or on a C# makefile work product created on a component.

12/26/2012School of Computing, Department of  17

Understanding the C# Compiler

• Compilation can be run: 

• from the context menu available on C# makefile work products on components 

• from the toolbar, by selecting a component and clicking on the  Compile" icon. 

• For a component, the generated makefile recursively compiles all the referenced package's files.

12/26/2012School of Computing, Department of  18

Understanding the C# Compiler

• The Mono C# compiler is considered feature complete for C# 1.0, C# 2.0 and C# 3.0 (ECMA). A preview of C# 4.0 is distributed with Mono 2.6, and a complete C# 4.0 implementation is available with Mono 2.8 or when building Mono from our trunk source code release. 

• Starting with Mono 2.2 it supports a Compiler Service that applications can consume. 

.

12/26/2012School of Computing, Department of  19

Understanding the C# Compiler

• You have to pick one of: • mcs: compiler to target 1.1 runtime (to be deprecated with Mono 2.8). 

• gmcs: compiler to target the 2.0 runtime. • smcs: compiler to target the 2.1 runtime, to build Moonlight applications. 

• dmcs: Starting with Mono 2.6 this command is the C# 4.0 compiler, and references the 4.0 runtime. 

12/26/2012School of Computing, Department of  20

Understanding the C# Compiler

• The compiler is able to compile itself and many more C# programs (there is a test suite included that you can use). The compiler is routinely used to compile Mono, roughly four million lines of C# code and a few other projects. 

• The compiler is also fairly fast. On a IBM ThinkPad t40 it compiles 18,000 lines of C# code per second. 

12/26/2012School of Computing, Department of  21

Understanding the C# Compiler

Compiler Service 

• The compiler can be used as a service by using the Mono.CSharp.Evaluator class in the Mono.Sharp.dll assembly. 

• Both a console and GUI read‐eval‐print shells are distributed as part of Mono 2.2 and are both built on top of the above service. 

12/26/2012School of Computing, Department of  22

Understanding the C# Compiler

State of the Compiler 

• Starting with Mono version 2.6 a new compiler dmcs is available as a preview of C# 4.0 (a preview since Mono 2.6 will ship before C# 4.0 is finalized). 

• The default compiler (mcs) now defaults to the 3.x language specification, starting with Mono 2.8 it will default to 4.0: 

12/26/2012School of Computing, Department of  23

BASICS OF C#

• Variables, Loops, Decision Statements, etcData Types• Float , double ,decimal,long,ulong,string

Variables Declarations• byte ‐ 0 to 255• char ‐ 2 bytes• bool• sbyte ‐ ‐128 to 127• short ‐ 2 byte int

12/26/2012School of Computing, Department of  24

BASICS OF C#

• ushort ‐ 0 to 65,535• int ‐ 4 bytes• uint ‐ 4 bytes positiveUsing Variables • C# is Strongly Typed

float x = 10.9f;double y = 15.3;y = x; // okayx = (float) y; // conversion required

12/26/2012School of Computing, Department of  25

BASICS OF C#

• Variables must have Value before being used.– Hence declarations usually include initialization

• Simple Arraysint[] myArray1 = new int[5];int[] myArray2 = {1, 2, 3, 4, 5};for (int i=0;i<10; i++)Console.Write ("{0} ",myarray[i]);

Console.WriteLine();

12/26/2012School of Computing, Department of  26

BASICS OF C#

• Looping Statements• Same as C++

– while (count > 0) process_list (count--);

– do process_list( ++count );

while (count < 10);

– for (int i=1; i<=10; i++)Different from C++while (count)// illegal C# unless count is bool

12/26/2012School of Computing, Department of  27

BASICS OF C#

• Decision StatementsAlmost Just Like C++

12/26/2012School of Computing, Department of  28

if (count >= 10){ dostuff();domorestuff();

}else...

switch (choice){case 'Y': //must be emptycase 'y': do_yes_stuff();

break;default:

...

BASICS OF C#

12/26/2012School of Computing, Department of  29

Simple Console OutputSystem.Console.WriteLineSystem.Console.Write

System.Consolue.WriteLine ("count = {0} and sum = {1}",

count, sum);

BASICS OF C#

• Simple Console Inputstring inputline;char charvalue;int intvalue;Console.Write ("Enter a string: ");inputline = Console.ReadLine();Console.WriteLine("You just entered \"{0}\"",inputline);

Console.Write ("Enter a character: ");

12/26/2012School of Computing, Department of  30

BASICS OF C#

charvalue = (char) Console.Read();Console.WriteLine("You just entered \"{0}\"", charvalue);

Console.ReadLine();

Console.Write ("Enter an integer: ");inputline = Console.ReadLine();intvalue = Convert.ToInt32(inputline);Console.WriteLine("You just entered \"{0}\"", intvalue);

12/26/2012School of Computing, Department of  31

Classes and Objects

• C# is a a language with C++‐based syntax much like Java is derived from C++.  To define a class you use the class keyword, your classes name, and base class.

• C# supports namespaces.  Every type in the Framework Class Library exists in a namespace.  You should give your reusable types a namespace as well, however it is less necessary for your application classes to be in a namespace.

12/26/2012School of Computing, Department of  32

Classes and Objects

12/26/2012School of Computing, Department of  33

class Name:BaseType{// Members

}Namespace NameName{

class Name:BaseType{}

}class MyType{

public static String someTypeState;public Int32 x;public Int32 y;

}

Classes and Objects

• This above example in class MyType shows a class that does not explicitly declare a base class, so it is implicitly derived from Object, and it also shows the definition of a couple of fields in the type.

Accessibility• In C#, private is the default accessibility• Accessibilities options

– public – Accessible to all

12/26/2012School of Computing, Department of  34

Classes and Objects

– private – Accessible to containing class– protected – Accessible to containing or derived classes– internal – Accessible to code in same assembly– protected internal – means protected or internal

• Classes can be marked as public or internal– By default they are private– Accessible only to code in the same source module

12/26/2012School of Computing, Department of  35

Classes and Objects

• Type Members in C#• Fields

– The state of an object or type• Methods

– Constructors– Functions– Properties (smart fields)

• Members come in two basic forms– Instance – per object data and methods

• Default– Static – per type data and methods

• Use the static keyword

12/26/2012School of Computing, Department of  36

Classes and Objects

• Object• The object type is an alias for Object in the .NET Framework. In the unified type system of C#, all types, predefined and user‐defined, reference types and value types, inherit directly or indirectly from Object. You can assign values of any type to variables of type object. When a variable of a value type is converted to object, it is said to be boxed. When a variable of type object is converted to a value type, it is said to be unboxed. For more information, see Boxing and Unboxing.

12/26/2012School of Computing, Department of  37

Classes and Objects

• The following sample shows how variables of type object can accept values of any data type and how variables of type object can use methods on Object from the .NET Framework.

class ObjectTest

{

public int i = 10; 

}

12/26/2012School of Computing, Department of  38

Classes and Objects

class MainClass2 {static void Main(){object a; a = 1; // an example of boxing Console.WriteLine(a); Console.WriteLine(a.GetType()); Console.WriteLine(a.ToString()); a = new ObjectTest(); ObjectTest classRef; classRef = (ObjectTest)a; Console.WriteLine(classRef.i); }} 

12/26/2012School of Computing, Department of  39

Classes and Objects

/* Output 

1

System.Int32 

* 10 */ 

12/26/2012School of Computing, Department of  40

Methods – Properties 

12/26/2012School of Computing, Department of  41

Methods – Properties 

• The various types of methods will be discussed in detail.

• Methods are blocks of code that perform some kind of action, or carry out functions such as printing, opening a dialog box, and so forth. There are two kinds of methods in C#, as there are in Java. They are:

• Instance Method• Static Method

12/26/2012School of Computing, Department of  42

Methods – Properties 

• Let's discuss each of these in detail. Instance Methods are methods declared outside the main method and can be accessed only by creating an object of the corresponding class, as shown 

• using System;class Instmethod{ //Method declared outside the main. 

12/26/2012School of Computing, Department of  43

Methods – Properties 

void show() { int x = 100; int y = 200;  

Console.WriteLine(x); Console.WriteLine(y); }public static void Main(){ //Object created Instmethod a = new Instmethod ();//Instance method called a.show(); }} 

12/26/2012School of Computing, Department of  44

Methods – Properties 

• Class methods also are declared outside the main method but can be accessed without creating an object of the class. They should be declared with the keyword static and can be accessed using the classname.methodnamesyntax. This is illustrated in Listing 5. Similarly, you also can create class variables.

12/26/2012School of Computing, Department of  45

Methods – Properties

PropertiesProperties provide added functionality to the .NET Framework. Normally, we use accessor methods to modify and retrieve values in C++ and Visual Basic. If you have programmed using Visual Basic's ActiveX technology, this concept is not new to you. Visual Basic extensively uses accessor methods such as getXXX() and setXXX() to create user‐defined properties.

• A C# property consists of:

• Field declaration

• Accessor Methods (getter and setter methods)

12/26/2012School of Computing, Department of  46

Methods – Properties

• Getter methods are used to retrieve the field's value and setter methods are used to modify the field's value. C# uses a special Value keyword to achieve this. Below example declares a single field named zipcode and shows how to apply the field in a property.

12/26/2012School of Computing, Department of  47

Methods – Properties

class Propertiesexample

using System;

{

//Field "idValue" declared

public string idValue;

//Property declared

public string IdValue

{

get

{

return idValue;

}

12/26/2012School of Computing, Department of  48

Methods – Properties

set

{

idValue = value;

}

}

public static void Main(string[] args)

{

Propertiesexample pe = new Propertiesexample();

pe.IdValue = "009878";

string p = pe.IdValue;

Console.WriteLine("The Value is {0}",p);

}

}

12/26/2012School of Computing, Department of  49

Interface‐ Partialclass

Partial Class Definitions • 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.

12/26/2012School of Computing, Department of  50

Interface‐ Partialclass

• 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, as shown below:

12/26/2012School of Computing, Department of  51

Interface‐ Partialclass

public partial class Employee

{

public void DoWork()

{

}

}

public partial class Employee

{

public void GoToLunch()

{

}

}

12/26/2012School of Computing, Department of  52

Interface‐ Partialclass

• An interface contains only the signatures of methods, delegates or events. The implementation of the methods is done in the class that implements the interface, as shown in the following example:

interface ISampleInterface{void SampleMethod();

}

class ImplementationClass : ISampleInterface{

12/26/2012School of Computing, Department of  53

Interface‐ Partialclass

// Explicit interface member implementation: 

void ISampleInterface.SampleMethod()

{

// Method implementation.

}

static void Main()

{

// Declare an interface instance.

ISampleInterface obj = new ImplementationClass();

// Call the member.

obj.SampleMethod();

}

}

12/26/2012School of Computing, Department of  54

Interface‐ Partialclass

• An interface can be a member of a namespace or a class and can contain signatures of the following members: 

• Methods

• Properties

• Indexers

• Events

• An interface can inherit from one or more base interfaces.

• When a base type list contains a base class and interfaces, the base class must come first in the list.

12/26/2012School of Computing, Department of  55

Interface‐ Partialclass

• A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface

12/26/2012School of Computing, Department of  56

Null and Casting as

• C# As Cast Example

• Dot Net PerlsYou need to perform a cast of a variable to a more derived type, or have the cast fail if the type is incompatible. While the C# language provides a multitude of casting mechanisms, the as operator cast is often the most efficient and also least prone to error. In this example, we look at the as cast construct in the C# programming language.

12/26/2012School of Computing, Department of  57

Null and Casting as

• For reference types, the as‐cast is recommended for its combination of performance and safety. You can test the casted variable against null and then use it, eliminating extra casts.

• Program that uses as casts  using System;using System.Text;

class Program{

12/26/2012School of Computing, Department of  58

Null and Casting as

static void Main()

{

// Create a string variable and cast it to an object.

string variable1 = "carrot";

object variable2 = variable1;

// Try to cast it to a string.

string variable3 = variable2 as string;

if (variable3 != null)

{

Console.WriteLine("have string variable");

}

12/26/2012School of Computing, Department of  59

Null and Casting as

// Try to cast it to a StringBuilder.

StringBuilder variable4 = variable2 as StringBuilder;

if (variable4 != null)

{

Console.WriteLine("have StringBuilder variable");

}

}

}

Output

have string variable

12/26/2012School of Computing, Department of  60

Handling Exceptions

• Exceptions and Exception Handling• The C# language's exception handling features help you deal with any unexpected or exceptional 

situations that occur when a program is running. Exception handling uses the try, catch, and finally keywords to try actions that may not succeed, to handle failures when you decide that it is reasonable to do so, and to clean up resources afterward. Exceptions can be generated by the common language runtime (CLR), by the .NET Framework or any third‐party libraries, or by application code. Exceptions are created by using the throw keyword.

• In many cases, an exception may be thrown not by a method that your code has called directly, but by another method further down in the call stack. When this happens, the CLR will unwind the stack, looking for a method with a catch block for the specific exception type, and it will execute the first such catch block that if finds. If it finds no appropriate catch block anywhere in the call stack, it will terminate the process and display a message to the user.

• In this example, a method tests for division by zero and catches the error. Without the exception handling, this program would terminate with a DivideByZeroException was unhandled error.

12/26/2012School of Computing, Department of  61

Handling Exceptions

class ExceptionTest

{

static double SafeDivision(double x, double y)

{

if (y == 0)

throw new System.DivideByZeroException();

return x / y;

}

static void Main()

{

// Input for test purposes. Change the values to see

// exception handling behavior.

double a = 98, b = 0;

double result = 0;

12/26/2012School of Computing, Department of  62

Handling Exceptions

try

{

result = SafeDivision(a, b);

Console.WriteLine("{0} divided by {1} = {2}", a, b, result);

}

catch (DivideByZeroException e)

{

Console.WriteLine("Attempted divide by zero.");

}

}

}

12/26/2012School of Computing, Department of  63

Handling Exceptions

• Exceptions have the following properties:

• Exceptions are types that all ultimately derive from System.Exception.

• Use a try block around the statements that might throw exceptions.

• Once an exception occurs in the try block, the flow of control jumps to the first associated exception handler that is present anywhere in the call stack. In C#, the catch keyword is used to define an exception handler.

• If no exception handler for a given exception is present, the program stops executing with an error message.

• Do not catch an exception unless you can handle it and leave the application in a known state. If you catch System.Exception, rethrow it using the throw keyword at the end of the catch block.

• If a catch block defines an exception variable, you can use it to obtain more information about the type of exception that occurred.

• Exceptions can be explicitly generated by a program by using the throw keyword.

• Exception objects contain detailed information about the error, such as the state of the call stack and a text description of the error.

12/26/2012School of Computing, Department of  64

Handling Exceptions

• Code in a finally block is executed even if an exception is thrown. Use a finally block to release resources, for example to close any streams or files that were opened in the try block. 

• Managed exceptions in the .NET Framework are implemented on top of the Win32 structured exception handling mechanism. For more information, see Structured Exception Handling (C++) and A Crash Course on the Depths of Win32 Structured Exception Handling

12/26/2012School of Computing, Department of  65

bibliography

• http://csharp.net‐tutorials.com

• 1. Stephen C. Perry, Core C# and .NET, Prentice Hall, New Jersey, 2005 (Chapters 1, 16 ‐18)

• 2. Peter Wright, Beginning Visual C# 2005 Express Edition: From Novice to Professional,Apress, 2006 (Chapters 3 – 6, 8‐13)

12/26/2012School of Computing, Department of  66

Review questions

• Write the objectives of .Net framework

• Compare kernel and compact profile

• List the advantages of metadata

• Write the output for the following program

Static void Main()

{int? a= null;

Console.WriteLine(a);

}

• Justify the statement “It is possible to create and use code library. Explain it.

• Find out the error in the following program

12/26/2012School of Computing, Department of  67

Review questions

Static int main()

{

byte a=259;

int b= null;

Console.WriteLine(a+ “ “+b)

}

• Write the purpose of properties

• Define metadata

• Write the output for the following program

Static void Main()

{string[] fruits ={“apple”,”orange”,”banana”};

foreach(string a in fruits)

{

Console.WriteLine(a)

}

}

12/26/2012School of Computing, Department of  68