0% found this document useful (0 votes)
59 views146 pages

Awp

Uploaded by

muzammil04786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
59 views146 pages

Awp

Uploaded by

muzammil04786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 146
TY. B.Sc. (IT): Sem. V Advanced Web Programming Notes CONTENTS fe Topic fal . Syllabus @ Introducing .NET, The C# Language & Types, Objects and Namespace 1 1.1 | Introducing .NET 2 1.2. | The C# Language 5 1.3. | Types, Objects and Namespace 16 Web Form Fundamentals & Form Controls 47 / | 2.1. | Web Form Fundamentals 48 | 2.2. | Form Controls 60 ya Topi = Error Handling, Logging, and Tracing, State Management a & Styles, Themes, and Master Pages tn | 3.1 | Error Handling, Logging, and Tracing 81 | 3.2 | State Management 85 3.3 | Styles, Themes, and Master Pages 100 ‘ADO.NET Fundamentals, Data Binding & Th, The Data Controls m 4.1_| ADO.NET Fundamentals 108 42 | Data Binding 115 4.3 | The Data Controls 118 XML, Security Fundamentals & ASP.NET AJAX 125 ¥ 5.1 | XML 126 5.2 | Security Fundamentals 132 5.3 | ASP.NET AJAX 136 Advanced Web Programming TY. BSc. (IT): Sem. V ES EVALUATION SYSTEM Duration | Marks Theory Examination 2%Hrs. | 75 Internal - 25 Practical Examination 2% Hrs. 50 SYLLABUS Unit! Introducing .NET: The .NET Framework, C#, VB, and the .NET Languages, The Common Language Runtime, The .NET Class Library. The C# Language:-G#-tanglage Basics, Variables and Data Types, Variable Opefations, Object-Based Manipulation, Conditional Logic, Loops, Methods. Types, Objects, and Namespaces: The Basics About Classes, Building a Basic Class, Value Types and Reference Types, Understanding Namespaces and Assemblies, Advanced ClassiProgramming, Unit Il Web Form Fundamentals: Writing Code, Using the Gode-Behindl Class, Adding Event Handlers, Understanding the Anatomy .of an ASP.NET Application, Introducing Server Controls, Using theyPage Class, Using Application Events, Configuringlan ASP.NET Application. Form Controls: Stepping Up to Web Controls, Web Control Classes, List Contidls/ Table Controls, Web ControliEVents and AutoPostBack, Validation, Understanding ValidationyeUsing the Validation Controls, Rich Controls, The Calendar, The AdRotator, Pages with Multiple Views, User Controls and Graphics, User Controls, Dynamic Graphics, The Chart Control, Website Navigation: Site Maps, URL“Mapping and Routing, The SiteMapPath Control, The TreeView Controly- The. Menu Control. Unit Ill Error Handling, Logging, and Tracing : Avoiding Common” Errors, Understanding Exception Handling, Handling Exceptions, Throwing Your Own Exceptions, Using Page Tracing State Management : Understanding the Problem of State, Using View State, Transferring Information Between Pages, Using Cookies, Managing Session State, Configuring Session State, Using Application State, Comparing State Management Options. Styles, Themes, and Master Pages : Styles, Themes, Master Page Basics, Advanced Master Pages. o Unit IV ADO.NET Fundamentals: Understanding Databases, Configuring Your Unit V Database, Understanding SQL Basics, Understanding the Data Provider Model, Using Direct Data Access, Using Disconnected Data Access. Data Binding : Introducing Data Binding, Using Single-Value Data Binding, Using Repeated-Value Data Binding, Working with Data Source Controls, The Data Controls : The GridView, Formatting the GridView, Selecting a GridView Row, Editing with the GridView, Sorting and Paging the GridView, Using GridView Templates, The DetailsView and FormView. XML : XML Explained, The XML Classes, XML Validation, XML Display and Transforms. Security Fundamentals: Understanding Security. Requirements;"Authentication and Authorization, Forms.Authentication, Windows Authentication. ASP.NET AJAX: Understanding Ajax,-Using Partial Refreshes,. Using Progress Notification, Implementing Timed Refreshes, Working with the ASP.NET AJAX Control Toolkit @oog0 w Introducing .Net, The C# Language & Types, Objects and Namespaces Weightage :.15.Marks: Introducing..NET The“NET Framework, C#,)VB, and the .NET Languages, The Common Language Runtime, The .NET Class Library. The C#t Language C# Language Basics, Variables afid Data Types))Variable Operations, ObjectBased Manipulation, Conditional Logic; Loops, Methods. Types, Objects, and Namespaces ‘The Basics About Classes, Building aBasie Cldss, Value Types.and/Reference Types, Understanding Namespacesvand Assemblies, Advanced Class Programming. Topics : 1.4, Introducing .NET 1.2 \ The C# Language 1.3 ‘Types; Objects, and Namespaces Help Line : For any query WhatsApp to 704 501 85 39 & get it Solved 21 Vidyalankar : T.Y. B.Sc. (IT) - AWP 1 Qt Ans.: INTRODUCING .NET Explain .Net FrameWork. OR What is .NET Framework? Explain its architecture in brief. [0-18] The .Net framework is a software development platform developed by Microsoft. This framework is meant to create applications, which would run on the Windows Platform. The first version of the .Net framework was released in the year 2002.The version was called .Net framework 1.0. The .Net framework can be used to create both - Form-based and Web-based applications. Web services can also be developed using the .Net framework. Net Framework Architecture The basic architecture of the .Net framework is as shown below + WinForms, Language + ASP.Net + ADO.Net brary an Fig. 1 = net frameworkarthitecture diagram NET Components : ANet/framework Consists of following key components : 1. Languages : Net supports variety of languages like Visual C++, VB, C# etc. Using these following types of applications can be built. The .Net framework Applications are classified bbroadly into the following categories : * Windows Applications : This is used for developing Forms-based applications, which wouldsrun-on arcend user machine. These applications do:not. support remote server processing. * Web Applications = The™NET-Framework includes a powerful system for generating Web content dynamically, enabling personalization,.security, etc. This system is called ASP.NET (Active Server Pages .NET), and one can use C# to create ASP.NET applications using Web Forms. * Web Services : Using Web services one can exchange virtually any data over the Internet, using the same simple syntax regardless of the language used to create a Web service or the system on which it resides. * ADO.Net : Any of the above types of Application may also require some form of database access, which can be achieved using the ADO.NET (This technology is used to develop applications to interact with Databases such as Oracle or Microsoft SQL Server) 2. Base Class Library (BCL) : The .NET Framework class library is a library of classes, interfaces, and value types that provide access to system functionality. It is the foundation on which .NET Framework applications, Unit | : Introducing .NET, The C# Language & Types, Objects and Namespace |3. Q2 Ans.: a3 Ans.: components, and controls are built. Following are different types of applications that can make use of .net class library. (i) Windows Application (i) Console Application (iii) Web Application {iv) XML Web Services (v) Windows Services Developers just need to import the BCL in their language code and use its predefined methods and properties to implement common and complex functions like reading and writing to file, graphic rendering, database interaction, and XML document manipulation. 3. Common Language Runtime : The Common Language Runtime (CLR), the virtual machine component of Microsoft's NET framework, manages the execution of .NET programs. A process known as just-in-time compiler that converts the compiled code into machine instructions which the computer's CPU then executes. The CLR provides additional. services including memory management, type....safetyrexception handling, garbage collection, .seeurity-and'thread management. All programs written for the NET framework, irrespective of programming language, are executed by the CLR, Explain Components of the CLR. Following are the components of CLR. * Common Type Systemi(CTS) : CTSidescribes d set of types thatycan be used in different .Net languages: in common. That is, the Common Type System (CTS) ensure that objects written’in different .Net/languages can interactawith each other. For Communicatingsbetween! programs written in ‘any .NET complaint language, the types haye to be compatible on the basic level, These types can/be Value Types or Reference Types. * CLS: It is’@ subset of CTS, All instruction is in CLS i.e. instruction of CTS is written in CLS. | MSIL sit i8 language independentiéode. When you compile code that uses the NET Framework library, you don't immediately create operating system - specific native code. Instead, you compile your code into Microsoft Intermediate Language (MSIL), code, The MSIL code is not specific to any operating system or to any'language. CLR provides following features’: © Interlanguage Operability «Extensible types provided by a class library. * Support for threads that allows creation of multithreaded, scalable applications. * Support for structured exception handling. * Garbage collection * Use of delegates instead of function pointers for increased type safety and security, Explain CIL and JIT. Common Intermediate Language (CIL), formerly called Microsoft Intermediate Language (MSIL), is the lowest-level human-readable programming language defined by the Common Language Infrastructure (CLI) specification and is used by the NET Framework. 4l Vidyalankar : T.Y. B.Sc. (IT) - AWP a4 Ans.: as Ans.: During compilation of CLI programming languages, the source code is translated into CIL code rather than into platform- or processor-specific code. CIL is a CPU- and platform-independent instruction set that can be executed in any environment supporting the Common Language Infrastructure, such as the .NET runtime on Windows. CIL code is verified for safety during runtime, providing better security and reliability The execution process looks like this: 1. Source code is converted to CIL i.e. Common Intermediate Language. 2. CIL is then assembled into a form of so-called Microsoft Intermediate language [MSIL] and a CLI assembly is created. 8. Upon execution of a CLI assembly, its code is passed through the runtime's JIT compiler to generate native code. Ahead-of-time compilation may also be used, which eliminates this step, but at the cost of executable- file portability. 4, The computer's processorexecutesthé Tiative code. Just-in-time compilation (JIT) JIT involves ‘turning thé MSIL code ‘into code immediately execulable by the native machine. The conversion is performed gradually during the program's execution. JIT compilation providesiy © environment-specific optimization * runtime type safety, + assembly,verification To accomplish these tasks, theWIT compiler examines the assembly metadata for any illegal aeg@ss@s andihandies violations appropriately. JIT compiler do pot convert the complete MSIL ode 16 native machine code in one go, instead conversion is donevonly when needed, Write a steps in creating Web Application. 1. Application code is written using a .NET-compatible language. 2. That code is compiled into:CIL, which is\stored in an assembly. 3. "Wherthis:code.is executed it must first be compiled into native code using a JIT compiler 4, The native code is executed in the context of the manageéd'CLR® Explained C# code is managed code. The role of the CLR doesn't end once the source code is converted to CIL and a JIT compiler compiles the CIL to native code. The CLR looks after the applications by managing memory, handling security, allowing cross-language debugging, and so on, hence code written using the .NET Framework is managed when it is executed. By contrast, applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C+ can be used to write such applications. In C# one can write only code that runs in a managed environment. .Net can use the managed features of the CLR and allow itself to handle any interaction with the operating system. Unit | : Introducing .NET, The C# Language & Types, Objects and Namespace | 5. a6 Ans.: 1.2 Qa Ans.: Explain Garbage Collection in .Net. In the common language runtime (CLR), the garbage collector serves as an automatic memory manager. It provides the following benefits : * Enables one to develop an application without having to free memory. * Allocate objects on the managed heap efficiently. + Reclaims objects that are no longer being used, clears their memory, and keeps the memory available for future allocations. Managed objects automatically get clean content to start with, so their constructors do not have to initialize every data field. * Provides memory safety by making sure that an object cannot use the content of another object. Conditions for a garbage collection : Garbage collection occurs when one of the following conditions:is true’: «The system has low physicalmemory-tf¢an be detected by either thelow memory Notification from the OS or low memory indicated by the host. + The_memory. that” is» used) by, allocated objects onthe managed. heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs. * The GC.Collect() methods Galled t6lexplicitly perfotm garbage collgetion. In almost all cases, theré is no neéd to callithis method, because the garbage collector runs continuously. This method is primarily Greater than 3 > -1, evaluates to true < Less than [5113 evaluates to false >= __|Greater than or equal to 4 >= 4 evaluates to true <= [Less than or equalito 5 <= 3 evaluates to false. I= Not equal to. 10 evaluates to true: Explain Logical Operators in C#. Logical operators are Used to perform logical operation such asand, or. Logical ‘operators operates on Boolean expressions (true and false) and returns Boolean values. Logical, operators aré uséd in decision making and loops. Operand 1] Operand2 | POR(|) | AND(&&) true’ true’ true: true ‘rue false ‘true false false true ‘true false false false false false Explain Unary Operatorsiin-C#. The unary operators operates on a single operanid: Operator Operator Name Description + [Unary Plus Leaves the sign of operand as it is = ___|Unary Minus Inverts the sign of operand ++ __ [increment Increment value by 1 [Decrement [Decrement value by 1 Logical Negation (Not) Inverts the value of a Boolean Explain Ternary Operator/Conditional Operator in C#. The ternary operator ? : operates on three operands. It is a shorthand for if- then-else statement. Ternary operator can be used as follows: variable = Condition? Expression1 : Expression2; 8] Vidyalankar : T.Y. B.Sc. (IT) - AWP a9 Ans.: Q.10 Ans.: The ternary operator works as follows: * If the expression stated by Condition is true, the result of Expression is assigned to variable. If itis false, the result of Expression? is assigned to variable. Example: using System; namespace conditionaloperatort { class Program € static void Main(stringl] ar) { int a, b, ed, max; Console. WriteLine("enter 4 integer values"); a = int.Parse(Console.ReadLine()); b = Convert:Toint32(Console.ReadLine()); c = int,Parse(Console.ReadLine()); d = int.Parse(Console ReadLine()): max = ((a > b) 2a: b) > (c>d?c:d)? ((a > b) ? a: b) : (c>d?e:d); Console. Writekina(" lafgest value Console. ReadLine(); "+ max); Bitwise and bil shift operators.ate Used to perform bit manipulation operations. [Operator JOperator Name ~/ © |Bitwise Complement &__ |Bitwise AND [__[Bitwise OR a |[Bitwise Exclusive OR << [Bitwise Lett'Shitt >> [Bitwise Right Shift Explain Compound Assignment Operators in C#. Following are the various forms of Compound Assignment Operators : Operator Operator Name Example | Equivalent To ‘Addition Assignment X=x+5) ‘Subtraction Assignment x=x-5 Multiplication Assignment X=x"5 Division Assignment x=x/5 Modulo Assignment X=x%5 = _[Bitwise AND Assignment x=x&5 [= _[Bitwise OR Assignment x=x|5 ‘= |Bitwise XOR Assignment x=xA5 <<=_|Left Shift Assignment x=x<<5 Unit | : Introducing .NET, The C# Language & Types, Objects and Namespace | 9 Qt Ans.: Q.12 Right Shift Assignment K>s=5 k=xo55 Lambda Operator k=> xx [Returns x*x Explain Type Conversion in C#. Itis a process of converting value of one type into another type. Itis also known as type casting. Itis of two types 1. Implicit type conversion: — Itis automatically done by C+ in type safe manner. = Conversion of lower type to higher type is done implicitly. — No casting required. — No loss of precision. Example : int x float y ; implicit 2... Explicittype casting: — Here the cast operatoriconversion function is explicitly required to performcasting, Conversion of higher type to lower type is done explicitly. — There is loss of precision Example: doublesp=12.6; int x=(int)p; # provides many conversion function... They are ToBoolean — Convertsia.type to'a Boolean wherespossible. ToByte... Converts type to a byte. ToChar ~ Converts/aitype'to a Single unicode character, where possible. ‘ToDatetime — Converts a type (integer't0 string) to date-time structure. ‘ToDecimal — Converts\floating point or integer type to decimal. ‘ToDouble ~ Converts a type to a double type. Tolnt16 — Converts a type to 16-bit integer. Tolnt32 ~ Converts a type t6°32-bit integer. ‘TéIAt64=Converts.a type to 64 bit integer. 10. ToSbyte - Converts a type to signédbyte-type.. 41. ToSingle - Converts a type to small floating point number. 12. ToString - Converts a type of String 13. ToType - Converts a type of specified type. 14. ToUInt16 — Converts a type to unsigned int type. 15. ToUInt2 - Converts a type to unsigned long type. 16. ToUInté4 — Converts a type to an unsigned big int. Note : These methods are static and called using class “Convert” SON SEE SW =o Explain Boxing and Unboxing. Operator Operator Name Example | Equivalent To Addition Assignment X=xX+5 ‘Subtraction Assignment K=x-5 Multiplication Assignment x=x* 5 10| _Vidyalankar : T.Y. B.Sc. (IT) - AWP. Division Assignment k=x/5 Modulo Assignment x=x%5 Bitwise AND Assignment x=x85 |= _[Bitwise OR Assignment x=x|5 ‘= ___[Bitwise XOR Assignment x=x45 Left Shift Assignment x<<5 Right Shift Assignment X>>5 Lambda Operator x=>x'x__[Retums xx Ans.: Boxing : In C# every class is subclass of class System.Object. * So every type in C# can be converted to type System.Object. * These process of conversion of value type to object type or subtype to basetype is known as Boxing. * Itdoes not require explicit casting. * Boxing process helps to implement CTS in .net. Unboxing: * It is process of /Gonversion of, object, typé to) value type or basetype to Subtype. * Unboxing in not done implicitly. + Itneeds casting to be doney Example: using System; namespace boxin { class Pfégram { static'void Main(stringi] args) f intx float y = 20.5f; object 01 = x//boxing object 02 = y;//boxing Console: WriteLine(" Console. WriteLine(" o: int a = (int)o1;//unboxing- float b = (float)o2://unboxing Console. WriteLine(" a=" + a); Console. WriteLine(" b=" + b); Console.ReadLine(); 0% "+ 01); “£02): } Output: WY fles//C:/Usere/acer/Documents/Vieua Studio 2010/Projects/szpghst/bosir/bexin/bn/Debug/berin EXE Unit | : Introducing .NET, The C# Language & Types, Objects and Namespace | 11 Q.13__ Explain command line argument with example. Ans.: These are the arguments passed to program from command line. * These arguments are stored in array in form of String. * [tis one mechanism to pass input to the program, * To pass commandline argument in visual studio. Project > Properties > Debug >» Command Line Arguments. Example: using System; namespace emdlinet {class Program as static void Main(stringl] ar) { int x, yi Console.Writetine(“arg are"); for(inti=0;i) { case : break; case : : break; default: |= break; + Fallthrough in’Swich caselin Ci: In G++) C, java if for case code is specified and break is not specified and that case,is ¢xecuted then the control alsorfalls through the next cases until break is found of switch is terminated: This is known as falithrough in.switch case, In.C# the fallthrough is not supported i.e. the-Control will not fall from one case to another. Hence’every:case:including “default” must and with break; Example: using System; namespace fallthrought {class Program { static void Main(stringl] args) { int n; Console. WriteLine( "enter n"); n=int.Parse(Console.ReadL ine()); switch (n) { case 1: Console. WriteLine("one"); break: case 2: Console.WriteLine("two"); breal 14] Vidyalankar : T.Y. B.Sc. (IT) - AWP. case 3: Console.WriteLine("three case 4: Console.WriteLine(“four" default: Console. WriteLine("default"); break; } Console.ReadLine(); shat fltiough flthrcughtbin/ Oebug/altrough EXE Q.16 Explain flow control, explain.whatis'break and continue statement. Ans.: Thesstatements inside your source files are generally executed from top) to bottom, in the order that they appear. Control flow.statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. break statement : The break statement tefminates the’ execution, control from a loop ofa switch statement to the next statement after the loop or switch statement. Example: using System; using Systém,Collections.Geneticy using System.Lingy using System.Text; namespace breakdemo { class: Program { static void Main(stringl] args) { inti for (i= 11 <= 5; i++) { Console.WriteLine("hello"); it (i>= 3) break ; Console. WriteLine("hi"); } Console.ReadLine(); Unit I : Introducing .NET, The C# Language & Types, Objects and Namespace | 15, w/acer/DecumentsVieua Sto 2010/Prejectezpghat’bresksemo breakers bin/Debugbreskdemo.EXE continue statement : The continue statement causes early iteration of a loop. It skips the remaining statements after the continue statement and moves the execution control to the next iteration of the loop. using System; using System.Collections.Generic; using System.Ling; using System.Text; namespace continuedemo { class Program { static void Main(string[] args) { int i; for (i=; <= 5; is) { Gonsole-Writevine ("hello"); if (>= 8) continues Console. WriteLine("hi"); } Console.ReadLing(); ” } } Output: ‘ie //ev eee eer document eu uso 2010/Prjecs/eominuedero/ contin ontinvedero EXE 16] Vidyalankar : T.Y. B.Sc. (IT) - AWP 1.3 Qt Ans.: Q2 Ans.: TYPES, OBJECTS AND NAMESPACES Explain Call by value with C#. In Call By Value the actual argument are the values that gets copied into formal argument. Here actual argument and formal argument refers to different memory locations, hence changes made in formal argument is not reflected in actual argument. Example: using System; namespace callbyvalue {class Program { static void Main(string[] args) { int xy; InitializeKaro( out x,out y); Console WriteLine(“after calling InitializeKaro function"); Console-WriteLine(" x= " +x +and y=""+y); Console.ReadKey(): } static void InitializéKaro(out int a,outlint b) { a= 10; b= 20; } } ghatealyraue/caloyvelie bi Debug/calyrale EXE Difference between a Value Type and a Reference Type. The Types in NET Framework are either treated by Value Type or by Reference Type. A Value Type holds the data within its own memory allocation and a Reference Type contains a pointer to another memory location that holds the real data. Reference Type variables are stored in the heap while Value Type variables are stored in the stack. Stack Heap Pointers to the Reference Unit | : Introducing .NET, The C# Language & Types, Objects and Namespace | 17 Q3 Ans.: Value Type: A Value Type stores its contents in memory allocated on the stack. When you cteated a Value Type, a single space in memory is allocated to store the value and that variable directly holds a value. If you assign it to another variable, the value is copied directly and both variables work independently. Predefined data types, structures, enums are also value types, and work in the same way. Value types can be created at compile time and Stored in stack memory, because of this, Garbage collector can't access the stack. eg. intx=10; Here the value 10 is stored in an area of memory called the stack. Reference Type: Reference Types are used by a reference which holds an address of the object but not the object itself. Because reference types represent the address of the variable rather than the data itself, assigning a_reference=variable”to~another doesn't copy the data. Insteadsitycreatesa second copy of the reference, which refers-torthe”same location of the heap as the original value. Reference Type variables are stored in’a.different,area.of memory called the heap. This means that when a reference type. variable is no longer used, it can be marked for garbage collection. Examples of reference types are Classes, Objects, Arrays, Indexers, Interfaces etc. e.g. _ intl] a= new int{20}/ In the above code the space required for the 20 integers that makevuplthe array is allocated on the heap. Explain calbby reference.in Ci. In call by reference thie actual argument.is the address referred by reference of formal argument .Here /actual/ and formal argument refers to same memory. Hence’ changes’ made by formal argumentiisifefiected in actual argument. The reference of a Variable can be,pass\using ‘ref’ Keyword. Example: using System; using System. Collections. Geniétic; using'System.Ling; using System. Text; namespace call_by_ref { class Program { static void Main(string[] args) { int x=10, y=20; Console.WriteLine("befor calling swap function"); Console.WriteLine(" x= "+x +" and y= "+ y); swap(ref x,ref y); Console.WriteLine(‘after calling swap function"); Console.WriteLine(" x= "+x +" and y= "+ y); Console.ReadKey(); } static void swap( ref int x,ref int y) 18] a4 Ans.: Vidyalankar : T.Y. B.Sc. (IT) - AWP { int t; t=x; x=y; y=t Vial Studi 2010 reject espa eal by eal fbn Debug call by ref EXE rtrd Pare Note :.‘ref'-keyword'catl pass the reference of variable if and only if the variable has assigned the value, If a value is not assigned to a variable and we need to pass reference of a variable we can do so using ‘out keyword. Example: using System ; namespace call by valule { Glass Program { static void Main(String [/] atgs) { int: ff (out x)p Console, WriteLine (“after call x =” + x); Console.ReadLine ( ); static void f1 (out int xy t x= 10; Console.WriteLine(“In f1 x =" +x); } Explain Property in C#. Itis block of code in a class used to assign and retrieve values of data members of class. General form : Property returntype propertyname { set {code Unit I: Introducing .NET, The C# Language & Types, Objects and Namespace | 19 } get {return t Properties are accessed using object : * When values is assigned to property, it invokes set block. * When property name is used in expression or in output system than it invokes get blocks. * Set block assigns value to data members. * Get blocks retums value. * Types: (i) Readonly — (ii) Writeonly * Readonly property will only have get block. ysiem; ‘ namespace openydemoreeGoWO \\)) (/) class A public int x; property int AP, { t = | public sta _ “Gince 1960 ine ("x=" +a Aprop); * Write only property will only have set block. Example: using System ; namespace PropertyDemoWriteOnly { class A public int x; property int AProp {set 20| _Vidyalankar : T.Y. B.Sc. (IT) - AWP { xevalue; } } class example { public static void Main(String [ ] args) { Aat =new A(); a1.AProp = 10; Console.WriteLine ("x=" +a1.x); } * Example of Property with set and get block: using System ; namespace PropertyDemo { class A { int x; property int APFop {set { xevalue; } get 4 return x; J } class example { public static void Main(String [ ] args) { Aat =newiA(); ai.AProp = 10; Console WriteLine-(‘x="-+a1,Aprop); } Note : Property if needs to be accessed outside class must be public. If property contains both get and set, then data member may not be public. If property contains either of get or set then data members must be public. @5 Explain Operator Overloading in C#. Ans.: Operator Overloading: Itis a process of assigning new meaning to already existing operator. When an operator is an expression with user defined objects (operands),the environment is not aware of action to be taken and user has to specify the action in method: Unit | : Introducing .NET, The C# Language & Types, Objects and Namespace | 21 Qs Ans.: public static classname operator op(arg.list) { } where op = operator to overload The operator op ()method is called automatically when the operator is used with objects. Note: The object name specifies address of the object. The operator function must be public and static. Binary Operator Overloading : General form : [2 operands] OP1 OP OP2; where OP1 and OP2 are operands [objects] OP = Operator Interpreted’as operator OP (OP1, OP2); i.e. OP1 and OP2 willbe passed Unary Operator Overloading General form ‘[1 operand] OP1 OP; on OP OPI eg: | Ctt or ++C; Interpreted as :operator OP (OP1 The only available operand will be passed. Create a class.complex with data member as teal and imaginary. Overload binary ‘pli's’ operator to add 2 complex no. using System; namespace operatoroverloadt public class Complex { doublex.¥ public Complex() {} public Complex(double a, double b) public void display() { Console.WriteLine(x+ "+i "+y); } public. static Complex operators (Complex c1 Complex c2) { Complex c3=new Complex(); 03.x=C1.x+2.x; cBy=ct y+e2.y; 22| _Vidyalankar : T.Y. B.Sc. (IT) - AWP return 03; } class Program { public static void Main(stringl] args) { Complex c1 = new Complex(12.3,13.2); Complex c2 = new Complex(13.6,15.8); Complex c3 =new Complex (); 3 = ct + c2;//treated as operator+(ct,c2) Console.WriteLine(" The entered complex numbers are : "); ct.display(); c2.display(); Console, WriteLine(*\n-The-addition of two complex numbers are"); e8-display(); Console ReadKey();, J Q7 Explain variable sized array with suitable’example. OR Explain jagged array with example. [0-18] Ans,: Jagged array is also called Array of Array or variable sized array. In a jagged array, each row may have different-number of columns. It is equivalent to an array of Variable-sized. one-dimensional arrays. The Length property is used to gét'the"length-of.each one-dimensional array. A jagged array can be declared and initialized as follows datatype[][] arrayname=new datatypefrowsize][]; arrayname[0]=new datatypel|{valt,val2,val3, arrayname(1}=new datatypell(valt ,val2,val3, arraynamef2}=new datatypel]{(valt ,val2,val3, ...}; Example : class numadd { public static void Main() { int{]Q] x=new int{4]f}; x{0]=new int{2]{5, 13}; as Ans.: ag Ans.: Unit | : Introducing .NET, The C# Language & Types, Objects and Namespace | 23 x[1]snew int{3](7,8,11}; x{2}=new int[4}{2,3,4,5}; x{3]=new int{1}{9}; forint i=O;i<4ji+-4) { for(int { } Console. Write("\n") x{i].Length;j++) Console.Write(x(iJi+"\t"); } Is Multiple Main () allowed in C#? Justify We can use more than on Main Method in_C#.programButonly one.Main Method which will act.as.entry;point'for the program. using’System; class A { static void Main(string[] args) { Console.WriteLine(“irom Class A’ Console.ReadLine(); } } class 8 { static Void Main(stting[) args) it Console. WriteLine("ClassiB%); Console. ReadLine(): t Try to execute Program a8 gWeI' below: csc filename.cs /main:classname As in given program there are two classes A and B in which each containing A Main Method. We may write as. csc filename.cs /main:A [ for Class A Main Execution ] or, esc filename.cs /main:B [ for Class B Main Execution ] Explain various Types of Constructors in C#. [0-18] Constructors are of following type : Default : When constructor does not accept any parameter then it is referred as default constructor or zero parameterized, Parameterized : When constructor accepts the parameter then it is referred as parametrized constructor. 24| _Vidyalankar : T.Y. B.Sc. (IT) - AWP Constructor Overloading: It is scenario where a class contains more than one constructor. Example: using System; namespace constructoroverloading class A int x, ys public A()//default constructor { } public A(int i for with one argument —-Be sure with t public A(int p, int q)/ constructor with two argumegis { class Program . Since 1960 in(stringl] arg: is) al =new A();//invokes default con: A.a2=new A(10); invokes parameterized constructor with one argument A.a3 = new A(20, 30); Jiinvokes parameterized constructor with two arguments at.display(); a2.display(); a3.display(); Console.ReadLine(); Unit | : Introducing .NET, The C# Language & Types, Objects and Namespace | 25 Q.10 Ans.: Qn Ans.: Output: Explain Private Constructor. Private Constructor : * Private constructors are used to restrict the instantiation of object using ‘new operator outside the scope of the class. * Aprivate constructor is a special instance constructor. It is commonly used in classes that contain static members only. * This type of constructors is mainly used for creating singleton object. * Ifyou don't want the class to be inherited.we'declaré'its Constructor private. + We can'tinitialize*the class outside the class or the instance of class can't|be created outside ifjts constructor is declared private. #=Weehavestotake help of riested-class| (Inner Class)-orestatic=method to initialize a class having private constructor. Example : using System; class test { Private test() { ConsolélWriteLine(Iprivate constrictor "); public test(int x) { } } class testmaint { Console. WriteLine("non private constructor’ x); public static void Main() { test t = new test(); JIEtror'test.test()' is inaccessible due to its protection level test t2 = new test(10); Console.ReadLine(); } Explain static constructor. Static Constructor * There can be only one static constructor in the class. * Its invoked automatically as soon as the class is loaded for execution. * The static constructor should be without parameters. 261 Vidyalankar : T.Y. B.Sc. (IT) - AWP. Q42 Ans.: * Itcan only access the static members of the class. * There should be no access modifier in static constructor definition. Example: using System; namespace staticconstructor {class A { public static int x; static A() { x=10; } } class Program stati Vold Main(string[] args) ConsoleWriteL inet" +A); Console.ReadLine(); Explain Polymorphism in'G# + Itmeans ‘ability to take multiple forms’. * C# supports polymorphism ‘==Depending on the when the polymorphism is resolved it's of two types : (i) Compile time (ii) Run time (i) Compile time polymorphism : Here the ambiguity or polymorphism is resolved at compile time. — Method overloading is an example of compile time polymorphism. - Here a class has multiple function with same name and different prototype. [numbers and types of argument] — Here binding of function call to function code is done at compile time itself based on number and types of argument passed in function call. It is also known as early binding or static binding. Example: using System; namespace methodoverloading Unit | : Introducing .NET, The C# Language & Types, Objects and Namespace | 27 {class Program {void area(int |, int b) { Console. WriteLine("area of rectangle= " + (I* b)); } void area(float |) { Console.WriteLine(‘area of circle= * + (3.14*I*|)); } Void area(int I, int b,int h) { Console.WriteLine(‘volume of rectangle=" + (| * b*h)); } static void Main(string[] args) {Program p = new Program(); p.area(12,,4)j//unetion’call p.area(7.4f); parea(5, 6, 7); ‘Console.ReadLine(); } (ii), Runtime polymorphism: — When method of base class is overridden in derived class and we use base class reference to call the method then always base class version of the function is called because’ the compiler only see the type of Teference-and.not the content. To solve this problem, the base-class. version of function is declared as “virtual” and the methods are overridden using “override” keyword. — Now depending on object assigned to base class reference, respective version of function is called. — Hence the polymorphism is resolved at runtime, hence known as runtime. Polymorphism also known as late binding/ dynamic binding. using System; namespace inheritance1 { class A { public virtual void display() { Console.WriteLine(‘class A display 28| _Vidyalankar : T.Y. B.Sc. (IT) - AWP } } class B: A public override void display() Console. WriteLine("class B display"); ) } class C: A public override void display() { class Program { static void Main (String [] args) { A al=newA(); Bb1=newB(); © ct=newC(); Af; Ifreterence of A real; 1: display (); r=b1; Unit | : Introducing .NET, The C# Language & Types, Objects and Namespace | 29 display ( ); rect; r: display (); CARL (); } } } Output: file/ Cer acer/Documerte ew Project sph vituaoveie/vitualovenidebieDebugNituloverie EXE Q.13 Explain.abstract'method. Ans,» Abstract method™of a class which does not have definition but only ‘declaration: © Aclass if contains atleast one abstract method it is declared as abstract. * An abstract class cannot beiinstantiated. * When a class inherit-abstract class, it)must override it's abstract methods else itself become abstract. Example’ Using System; namespace abstractdemo { abstract Class shape { } class-circle.;. shape { public abstraét void displayarea(); double r; public circle(double r1) { } public override void displayarea() { } rent; Console.WriteLine(‘area of circle=" + (3.14 * r* 1); } class triangle : shape double b, h; public triangle(double b1,double h1) 30| _Vidyalankar : T.Y. B.Sc. (IT) - AWP. { } public override void displayarea() { Console.Writel ine(‘area of triangle=" + (0.5 * b * h)); } } class Program { static void Main(string[] args) { circle c = new circle(7); triangle t = new triangle(8,9); c.displayarea(); t.displayarea(); Console.ReadLine(); i } acer Document vial jefe -eghat abet ene sstraetlernbin Cebu sbetreadere EXE Explain enum type with example. The enum) keyword is used.to declare’an enumeration. + /Itig a(distincttype that consist of set of named/Constant called as enumerator list. * | By default the 1° enumerator has value ‘0’ and value of subsequent is previous value + 7 * Every member however can be explicitly assigned values. Examples using System; namespace enum1 {enum color : int (Ted, blue, green, cyan _, magenta, yellow, black } class Program { public static void Main(string[] args) { color c = color.magenta; Console.WriteLine("String equivalent of c = "+ c); Console.Write("Int equivalent of c= "+ (int)c); Console.ReadKey(); } : Introducing .NET, The C# Language & Types, Objects and Namespace | 31 Q15 Ans.: Q16 Ans.: acer/Documents/Visual Studio 2010/Projects/aspghat/enumt/enum /bin/Debug/enurn1.EXE Write a short note on Assembly. * An assembly is a fundamental building block of any .NET framework application. It contains the code that is executed by common language runtime. For example, when we build a simple C# application, Visual Studio creates an assembly in the form of a single portable executable (PE) file, specifically an EXE or DLL. * Every assembly has a file called ‘manifest’ file that stores all information about that assembly. This information's are known as metadata. * The manifest file contains all the metadataneeded to specify the assembly's version.requirements, Security identity, and all metadata needed to define the ‘scope of the assembly and resolve references torresources and classes Components of Assembly : * Manifest It describes the assembly The manifé8bfile contain§ all the metadatatieeded to specify the assembly's version’ requifements, security identity, and all metadata needed’ to define the scope of the assembly and resolve referenc@é to resources and classes. * Type Metadata It contains, metadata, which deScribes’each and every type (class, structure, enumeration, ete), ° MSIL It contains Intermediatellanguage code. * Resources It contains bitmaps, icons-audios andjottier types of resources Explain Functions of Assembly» An assembly performs the following functions: * It contains code that the common language runtime executes. Microsoft intermediate language (MSIL) code in a portable executable (PE) file will not be executed if it does not have an associated assembly manifest. + It forms a security boundary. An assembly is the unit at which permissions are requested and granted + It forms a type boundary. Every type's identity includes the name of the assembly in which it resides. * It forms a reference scope boundary. The assembly's manifest contains assembly metadata that is used for resolving types and satisfying resource requests. The manifest also enumerates other assemblies on which it depends. * Itforms a version boundary. The assembly is the smallest versionable unit in the common language runtime; all types and resources in the same assembly are versioned as a unit 32] Vidyalankar : T.Y. B.Sc. (IT) - AWP. Q17 Ans.: Q18 Ans.: * It forms a deployment unit. When an application starts, only the assemblies that the application initially calls must be present. + Itis the unit at which side-by-side execution is supported. Explain the Benefits of Assembly. Following are the benefits of Assembly : * Assemblies are designed to simplify application deployment and to solve versioning problems that can occur with component-based applications. * End users and developers are familiar with versioning and deployment issues that arise from today's component-based systems. Some end users have experienced the frustration of installing a new application on their computer, only to find that an existing application has suddenly stopped working. This problem can be solved using Assembly. * Many deployment problems have been solved by the use of assemblies in the .NET Framework. Because they are.self-deseribing components, that have_no_dependencies*on"tegistry entries, assemblies enable zero-impact pplication installation. They also simplify uninstalling and replicating applications. What are sealed classes? Why are they used? The methods declared with.a'Sealed keyword in its heater are known as'sealed methods. Such method provides a complet@,implementation to its basé class virtual method using the override keyword. Characteristios : s<@9A method cannot be defined as Sealed!Unless that methodiis an override of a methodiin its base class. A sealed méthod cannot be. overridden further. Sealed methods are /uséful to avoid problems caused by overriding the existing functionality. « Itprevents the user from changing the internal functionality of a class. Example: using. System; class A { public virtual void F4() { Console. WriteLine("A.F1"); } public virtual void G1() { } Console.WriteLine("A.G1"); class B: A { sealed override public void F1() { Console. WriteLine("B.F1"); Unit | : Introducing .NET, The C# Language & Types, Objects and Namespace | 33 Q1g Ans.: } override public void G1() { } Console.WriteLine("B.G1"); class C:B { override public void G1() { } Console.WriteLine("C.G1"); } The class B provides two override methods: an F1 method that has.the sealed modifier and a G1 method that does not,.B's.use-of the'séaléd modifier prevents C from further.overriding’Pt Explain-Sealed:Classes. Why are'they used? * Generally if we create classes we can inherit the properties of that created class in any class without having.any restrictions. * In some situation wesWill get requirement like) we don't want ito give permission for the users to derive’ the classes from it or don't allow users to inherit the properties from particular class + _ For thatipurpose we have keyword called “sealéd” in] OOPS, When we defined class with keyword “Sealed” then we don't have a chance to derive that particularclass and we don't have permission to inherit the properties from that particular lass. + Asealediclass.¢anmot be inherited. * | Itis anjertor to use a sealed.class/aS a base class. + Use the sealed modifier in a class declaration to prevent inheritance of the class. * Itis not permitted to use the abstract modifier with a sealed class. Example: using System; sealed class A { public int x; public int y; t class MainClass { public static void Main() { Aal =new A(); a1.x=110; al. 50; Console. WriteLine(*x = {0}, y= {1}", a1.x, at.y); 34] Vidyalankar : T.Y. B.Sc. (IT) - AWP. Q.20 Ans.: Q.21 Ans.: Explain the similarities and differences between Interfaces and Abstract classes. Similarities: * Both abstract classes and interfaces may contain members that can be inherited by a derived class. * Neither interfaces nor abstract classes may be directly instantiated, but we can declare variables of these types. In such case, we can use polymorphism to assign objects that inherit from these types to variables of these types. * In both cases, we can then use the members of these types through these variables, although we don't have direct access to the other members of the derived object Differences: * Derived classes may only inherit from a single base class, which means that only a single abstract class can be inherited-direetly "(although it is possible for a chain.of.inheritance"to Include multiple abstract classes). Conversely, ‘clases can use as many interfaces as they want. *==Absiract=classes May possess”both ‘abstratt/ members»and=non-absiract members (these possess a code body, and can’be virtual so that they may be overridden in the derived class). Interface members conversely, must be implemented on the class'that uses’ the interface they do not possess code bodies. * Moreover, interface members are by definition publicsbiit members of abstractyclasses /may also be private (as long as they, aren’t abstract), protected, intemal, or protected interfall (where protected internal members are accéssible only fram éode within the application or from a derived class) In addition;“interfaces can't containyfields, constructors, destructors, static Tmembers, or Constants. Explain concept of virtual keyword in C#, If a class in C# is inherited by more than one classes and the derived classes overrides the methods of base. class. If base class reference is used to invoke the overridden method, irrespective of the object assigned to base class reference always"base-class. version of the method is called. To overcome this, the base class version of the function i8 defined»preceded with virtual keyword, now depending on the object assigned to the reference respective version of the function is called. This is case of polymorphism, and is resolved at runtime depending on object assigned to the reference at the time of call hence it is example of Runtime Polymorphism (Dynamic Method Dispatch). Example: using System; namespace inheritancet { class A { public virtual void display() { Console.WriteLine("class A display");

You might also like