C#.net file

Embed Size (px)

Citation preview

  • 7/27/2019 C#.net file

    1/36

    The .Net Framework

    The .NET Framework (pronounced dot net) is a software framework developed by Microsoft thatruns primarily on Microsoft Windows. It includes a large library and provides languageinteroperability (each language can use code written in other languages) across several

    programming languages. Programs written for the .NET Framework execute in a softwareenvironment (as contrasted to hardware environment), known as the Common LanguageRuntime (CLR), an application virtual machine that provides important services such as security,

    memory management, and exception handling. The class library and the CLR together constitutethe .NET Framework.

    The .NET Framework's Base Class Library provides user interface, data access, databaseconnectivity, cryptography, web application development, numeric algorithms, and network communications. Programmers produce software by combining their own source code with the.NET Framework and other libraries. The .NET Framework is intended to be used by most newapplications created for the Windows platform. Microsoft also produces a popular integrateddevelopment environment largely for .NET software called Visual Studio.

  • 7/27/2019 C#.net file

    2/36

    Design Features

    1. Interoperability

    Because computer systems commonly require interaction between newer and older applications,the .NET Framework provides means to access functionality implemented in programs thatexecute outside the .NET environment. Access to COM components is provided in theSystem.Runtime.InteropServices and System.EnterpriseServices namespaces of the framework;

    access to other functionality is provided using the P/Invoke feature.

    2. Common Language Runtime Engine

    The Common Language Runtime (CLR) is the execution engine of the .NET Framework. All.NET programs execute under the supervision of the CLR, guaranteeing certain properties and

    behaviors in the areas of memory management, security, and exception handling.

    3. Language Independence

    The .NET Framework introduces a Common Type System, or CTS. The CTS specificationdefines all possible data types and programming constructs supported by the CLR and how theymay or may not interact with each other conforming to the Common Language Infrastructure(CLI) specification. Because of this feature, the .NET Framework supports the exchange of typesand object instances between libraries and applications written using any conforming .NETlanguage.

    4. Base Class Library

  • 7/27/2019 C#.net file

    3/36

    The Base Class Library (BCL), part of the Framework Class Library (FCL), is a library of functionality available to all languages using the .NET Framework. The BCL provides classesthat encapsulate a number of common functions, including file reading and writing, graphicrendering, database interaction, XML document manipulation, and so on.

    5. Simplified Deployment

    The .NET Framework includes design features and tools which help manage the installation of computer software to ensure it does not interfere with previously installed software, and itconforms to security requirements.

    6. Security

    The design is meant to address some of the vulnerabilities, such as buffer overflows, which have been exploited by malicious software. Additionally, .NET provides a common security model for all applications.

    7. Portability

    While Microsoft has never implemented the full framework on any system except MicrosoftWindows, the framework is engineered to be platform agnostic, and cross-platformimplementations are available for other operating systems. Microsoft submitted the

    specifications for the Common Language Infrastructure (which includes the core class libraries,Common Type System, and the Common Intermediate Language), the C# language and theC++/CLI language to both ECMA and the ISO, making them available as official standards. Thismakes it possible for third parties to create compatible implementations of the framework and itslanguages on other platforms.

    What Is C# ??

    C# (pronounced "C-sharp") is an object-oriented programming language from Microsoft thataims to combine the computing power of C++ with the programming ease of Visual Basic. C# is

    based on C++ and contains features similar to those of Java.

    C# is designed to work with Microsoft's .Net platform. Microsoft's aim is to facilitate theexchange of information and services over the Web, and to enable developers to build highly

  • 7/27/2019 C#.net file

    4/36

    portable applications. C# simplifies programming through its use of Extensible MarkupLanguage (XML) and Simple Object Access Protocol (SOAP) which allow access to a

    programming object or method without requiring the programmer to write additional code for each step. Because programmers can build on existing code, rather than repeatedly duplicating it,C# is expected to make it faster and less expensive to get new products and services to market.

    Microsoft is collaborating with ECMA, the international standards body, to create a standard for C#. International Standards Organization (ISO) recognition for C# would encourage other companies to develop their own versions of the language. Companies that are already using C#include Apex Software, Bunka Orient, Component Source, devSoft, Far Point Technologies,LEAD Technologies, ProtoView, and Seagate Software.

    Features of c#

    Some notable distinguishing features of C# are:

    1. There are no global variables or functions. All methods and members must be declared withinclasses. Static members of public classes can substitute for global variables and functions.

    2. Local variables cannot shadow variables of the enclosing block, unlike C and C++. Variableshadowing is often considered confusing by C++ texts.

    3. C# supports a strict Boolean data type, bool. Statements that take conditions, such as whileand if, require an expression of a type that implements the true operator, such as the Booleantype. While C++ also has a Boolean type, it can be freely converted to and from integers, andexpressions such as if (a) require only that a is convertible to bool, allowing a to be an int, or a

    pointer.

    4. Managed memory cannot be explicitly freed; instead, it is automatically garbage collected.Garbage collection addresses the problem of memory leaks by freeing the programmer of responsibility for releasing memory which is no longer needed.

  • 7/27/2019 C#.net file

    5/36

    5. Multiple inheritance is not supported, although a class can implement any number of interfaces. This was a design decision by the language's lead architect to avoid complication andsimplify architectural requirements throughout CLI.

    6. C# is more type safe than C++. The only implicit conversions by default are those which are

    considered safe, such as widening of integers. This is enforced at compile-time, during JIT, and,in some cases, at runtime. There are no implicit conversions between Booleans and integers, nor

    between enumeration members and integers.

    7. Enumeration members are placed in their own scope.

    8. C# provides properties as syntactic sugar for a common pattern in which a pair of methods,accessor (getter) and mutator (setter) encapsulate operations on a single attribute of a class.

    ADVANTAGESAdvantages over C and C++ :-

    1. It is compiled to an intermediate language (CIL) independently of the language it wasdeveloped or the target architecture and operating system.

    2. Automatic garbage collection

    3. Pointers no longer needed (but optional)

    4. Reflection capabilities5. Don't need to worry about header files ".h"

    6. Definition of classes and functions can be done in any order

    7. Declaration of functions and classes not needed

    Advantages over Java :-

    1. Usually it is much more efficient than java and runs faster

    2. CIL (Common (.NET) Intermediate Language) is a standard language, while java byte codesaren't

    3. It has more primitive types (value types), including unsigned numeric types

    4. Indexers let you access objects as if they were arrays

    5. Conditional compilation

  • 7/27/2019 C#.net file

    6/36

    6. Simplified multithreading

    SOME IMPORTANT DEFINITIONS:-

    COMMON LANGUAGE RUNTIME

    The Common Language Runtime (CLR) is the virtual machine component of Microsoft's .NETframework and is responsible for managing the execution of .NET programs. In a process knownas just-in-time (JIT) compilation, the CLR compiles the intermediate language code known asCommon Intermediate Language (CIL) into the machine instructions that in turn are executed bythe computer's CPU. The CLR provides additional services including memory management, typesafety and exception handling. All programs written for the .NET framework, regardless of

    programming language, are executed by the CLR. It provides exception handling, Garbagecollection and thread management.

    DYNAMIC LINK LIBRARY

    In a nut shell, a dynamic link library (DLL) is a collection of small programs, which can becalled upon when needed by the executable program (EXE) that is running. The DLL lets theexecutable communicate with a specific device such as a printer or may contain source code todo particular functions. An example would be if the program (exe) needs to get the free space of your hard drive. It can call the DLL file that contains the function with parameters and a callfunction. The DLL will then tell the executable the free space. This allows the executable to besmaller in size and not have to write the function that has already exists. This allows any

    program the information about the free space, without having to write all the source code and itsaves space on your hard drive as well. When a DLL is used in this fashion are also known asshared files.

    FRAME CLASS LIBRARY(FCL)

    The Framework Class Library (FCL) is a standard library and one of two core components of Microsoft .NET Framework. The FCL is a collection of reusable classes, interfaces and valuetypes. The Base Class Library is a part of FCL and provides the most fundamental functionality,which includes classes in namespaces System, System. Code Dom, System .Collections, System.

    Diagnostics, System. Globalization, System.IO, System. Resources and System. Text.

    ACTIVE X DATA OBJECT

    Microsoft's ActiveX Data Objects (ADO) is a set of Component Object Model (COM) objectsfor accessing data sources. A part of MDAC, it provides a middleware layer between

    programming languages and OLE DB (a means of accessing data stores, whether they be

  • 7/27/2019 C#.net file

    7/36

    databases or otherwise, in a uniform manner). ADO allows a developer to write programs thataccess data without knowing how the database is implemented. He must be aware of the databasefor connection only. No knowledge of SQL is required to access a database when using ADO,although one can use ADO to directly execute SQL commands. The disadvantage of the latter isthat it introduces a dependency upon the type of database used.

    CONNECTED ARCHITECTURE

    The architecture of ADO.net, in which connection must be opened to access the data retrieved

    from database is called as connected architecture. Connected architecture was built on the classesconnection, command, datareader and transaction.

    Connection : in connected architecture also the purpose of connection is to just establish aconnection to database and it self will not transfer any data.

  • 7/27/2019 C#.net file

    8/36

    DataReader : DataReader is used to store the data retrieved by command object and make itavailable for .net application. Data in DataReader is read only and within the DataReader youcan navigate only in forward direction and it also only one record at a time.

    To access one by one record from the DataReader, call Read() method of the DataReader whose

    return type is bool. When the next record was successfully read, the Read() method will returntrue and otherwise returns false.

    . DISCONNECTED ARCHITECTURE

    The architecture of ADO.net in which data retrieved from database can be accessed even whenconnection to database was closed is called as disconnected architecture. Disconnectedarchitecture of ADO.net was built on classes connection, dataadapter, commandbuilder anddataset and dataview.

    Disconnected architecture is a method of retrieving a record set from the database and storing itgiving you the ability to do many CRUD (Create, Read, Update and Delete) operations on the

    data in memory, then it can be re-synchronized with the database when reconnecting. A methodof using disconnected architecture is using a Dataset

    Connected Disconnected It is connection oriented. It is disconnection oriented. Data reader DataSet Connected methods give faster performance. Disconnected get low in speed and

    performance

  • 7/27/2019 C#.net file

    9/36

    connected can hold the data of single table disconnected can hold multiple tables of data Data Reader can't persist the data Data Set can persist the data It is Read only, we can't update the data. We can update data

    REMOTE DATA OBJECT

    Remote Data Objects - RDO is an application program interface API from Microsoft that lets programmers writing Windows applications get access to relational databases from bothMicrosoft and other database providers. In turn, RDO statements in a program use Microsoft'slower-layer Data Access Objects DAO for actual access to the database. Database providerswrite to the DAO interface. RDO has evolved into ActiveX Data Objects - ADO whichMicrosoft recommended as program interface for new programs.

  • 7/27/2019 C#.net file

    10/36

    EXTENSIBLE MARKUP LANGUAGE (XML)

    Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. It is definedin the XML 1.0 Specification produced by the W3C, and several other related specifications, all

    gratis open standards. The design goals of XML emphasize simplicity, generality, and usabilityover the Internet. It is a textual data format with strong support via Unicode for the languages of the world. Although the design of XML focuses on documents, it is widely used for therepresentation of arbitrary data structures.

    EXTENSIBLE APPLICATION MARKUP LANGUAGE(XAML)

    Extensible Application Markup Language (XAML, /zml/) is a dec larative XML-basedlanguage created by Microsoft and is used for initializing structured values and objects. It isavailable under Microsoft's Open Specification. XAML is used extensively in .NET Framework 3.0 & .NET Framework 4.0 technologies, particularly Windows Presentation Foundation (WPF),Silverlight, and Windows Workflow Foundation (WF). In WPF, XAML forms a user interfacemarkup language to define UI elements, data binding, eventing, and other features. In WF,workflows can be defined using XAML. XAML is also used in Visual Studio 11 for Windows 8metro applications.

    JUST IN TIME COMPILER(JIT)

    JIT compilers represent a hybrid approach, with translation occurring continuously, as withinterpreters, but with caching of translated code to minimize performance degradation. It alsooffers other advantages over statically compiled code at development time, such as handling of late-bound data types and the ability to enforce security guarantees. JIT builds upon two earlier ideas in run-time environments: byte code compilation and dynamic compilation. It convertscode at runtime prior to executing it natively, for example byte code into native machine code.

    JAVA VIRTUAL MACHINE(JVM)

    A Java virtual machine is software that is implemented on virtual and non-virtual hardware andon standard operating systems. A JVM provides an environment in which Java byte code can beexecuted, enabling such features as automated exception handling, which provides root-causedebugging information for every software error (exception), independent of the source code. AJVM is distributed along with a set of standard class libraries that implement the Java application

    programming interface (API). Appropriate APIs bundled together with JVM form the JavaRuntime Environment (JRE). JVMs are available for many hardware and software platforms.The use of the same byte code for all JVMs on all platforms allows Java to be described as awrite once, run anywhere programming language, versus write once, compile anywhere, which

  • 7/27/2019 C#.net file

    11/36

    describes cross-platform compiled languages. Thus, the JVM is a crucial component of the Java platform.

    OBJECT ORIENTED PROGRAMMING (OOPS)Object-oriented programming (OOP) is a programming paradigm using "objects" datastructures consisting of data fields and methods together with their interactions to designapplications and computer programs. Programming techniques may include features such as dataabstraction, encapsulation, messaging, modularity, polymorphism, and inheritance. Manymodern programming languages now support OOP, at least as an option.

    ABSTRACTION: - In computer science, it is the process by which data and programs aredefined with a representation similar in form to its meaning (semantics), while hiding away theimplementation details. Abstraction tries to reduce and factor out details so that the programmer can focus on a few concepts at a time. A system can have several abstraction layers wherebydifferent meanings and amounts of detail are exposed to the programmer.

    ENCAPSULATION:- In a programming language, it is used to refer to one of two related butdistinct notions, and sometimes to the combination thereof:

    A language mechanism for restricting access to some of the object's components. A languageconstruct that facilitates the bundling of data with the methods (or other functions) operating onthat data.

    The second definition is motivated by the fact that in many OOP languages hiding of components is not automatic or can be overridden; thus, information hiding is defined as aseparate notion by those who prefer the second definition.

    POLYMORPHISM:- It is an important feature of object oriented programming. It means onename and multiple forms. The concept can be implemented by using function overloading andoperator overloading. The overloaded member functions are selected for invoking by matchingarguments both type and number. This information is known to the compiler at the compile timeand therefore, compiler is able to select the appropriate function for a particular call at thecompile time itself. This is called as early binding or static binding.

    At run time, when it is known that what class objects are under considerations, the approximateversion of the function is invoked. Since the function is linked with the particular class muchlater after the compilation, this process is known as late binding. It is also known as dynamic

    binding because the selection of the function is done dynamically at run time.

    INHERITANCE:- Inheritance is the most important feature of object oriented programming. Itis the process of creating a new class called derived class from existing class called as base class.

  • 7/27/2019 C#.net file

    12/36

    Most important advantage of inheritance is reusability i.e. reusing existing code i.e. save timeand money. By reusability a programmer can use a class created by another person or companywithout modifying it derive another classes form it.

    Private members can be accessed only within the class in which they are defined but public

    members can be form outside the class. Protected members can be accessed within the class inwhich they are defined and they are accessible in derived class which is derived by its own class.

    OVERLOADING: - It refers to the specification of several function declaration for a singlefunction name in the same scope. It is the method for calling several functions having samename. These functions are different during the calling process by the number and type of arguments passed to these functions.

    Add();

    Add(int,int);

    Add(float,float);

    Add(int,float);

    All the functions will be called in the program using the same name. But the compiler willdifferentiate them by the arguments passed to them.

  • 7/27/2019 C#.net file

    13/36

    Loops

    1. FOR LOOP:-

    It's preferred when you know how many iterations you want, either because you know the exactamount of iterations, or because you have a variable containing the amount. Here is an example

    on the for loop.Using System;

    Namespace ConsoleApplication1

    {

    Class Program

    {

    Static void Main (string[] args){

    int number = 5;

    for (int i = 0; i < number; i++)

    Console.WriteLine(i);

    Console.ReadLine();

    }

    }

  • 7/27/2019 C#.net file

    14/36

    }

    It consists of 3 parts:-

    1. We initialize a variable for counting

    2. Set up a conditional statement to test it

    3. Increment the counter (++ means the same as "variable = variable + 1").

    The first part, where we define the i variable and set it to 0, is only executed once, before theloop starts. The last 2 parts are executed for each iteration of the loop. Each time, i is comparedto our number variable - if i is smaller than number, the loop runs one more time. After that, i isincreased by one. Try running the program, and afterwards, try changing the number variable tosomething bigger or smaller than 5. You will see the loop respond to the change.

    2. FOR EACH LOOP:-

    It operates on collections of items, for instance arrays or other built-in list types.

    Using System;

    Using System.Collections;

    Namespace ConsoleApplication1

    {

    Class Program

    {

    Static void Main (string [] args)

    {

    ArrayList list = new ArrayList();

    list.Add("John Doe");

    list.Add("Jane Doe");

    list.Add("Someone Else");

    foreach(string name in list)

  • 7/27/2019 C#.net file

    15/36

    Console.WriteLine(name);

    }

    Console.ReadLine();

    }

    }

    Okay, so we create an instance of an ArrayList, and then we add some string items to it. We usethe foreach loop to run through each item, setting the name variable to the item we have reachedeach time. That way, we have a named variable to output. As you can see, we declare the namevariable to be of the string type you always need to tell the foreach loop which data type youare expecting to pull out of the collection. In case you have a list of various types, you may usethe object class instead of a specific class, to pull out each item as an object. When working with

    collections, you are very likely to be using the foreach loop most of the time, mainly because itssimpler than any of the other loops for these kinds of operations.

    3. WHILE LOOP:-

    The while loop is probably the most simple one, so we will start with that. The while loop simplyexecutes a block of code as long as the condition you give it is true. A small example and thensome more explanation:

    Using System;

    Namespace ConsoleApplication1

    {

    Class Program

    {

    Static void Main (string[] args)

    {

    int number = 0;

    while (number < 5)

  • 7/27/2019 C#.net file

    16/36

    {

    Console.WriteLine(number);

    number = number + 1;

    }

    Console.ReadLine();

    }

    }

    }

    Try running the code. You will get a nice listing of numbers, from 0 to 4. The number is firstdefined as 0, and each time the code in the loop is executed, it's incremented by one. But whydoes it only get to 4, when the code says 5? For the condition to return true, the number has to beless than 5, which in this case means that the code which outputs the number is not reached oncethe number is equal to 5. This is because the condition of the while loop is evaluated before itenters the code block.

    4. DO LOOP:-

    The opposite is true for the do loop, which works like the while loop in other aspects through.

    The do loop evaluates the condition after the loop has executed, which makes sure that the code block is always executed at least once.

    do

    {

    Console.WriteLine(number);

    number = number + 1;

    } while(number < 5);

    The output is the same though - once the number is more than 5, the loop is exited.

    CONDITIONAL STATEMENTS

    In computer science, conditional statements, conditional expressions and conditional constructsare features of a programming language which perform different computations or actions

  • 7/27/2019 C#.net file

    17/36

    depending on whether a programmer-specified Boolean condition evaluates to true or false.Apart from the case of branch predication, this is always achieved by selectively altering thecontrol flow based on some condition.

    In imperative programming languages, the term "conditional statement" is usually used, whereas

    in functional programming, the terms "conditional expression" or "conditional construct" are preferred, because these terms all have distinct meanings.

    1. IF STATEMENT:-

    The if then construct (sometimes called if then else) is common across many programminglanguages. Although the syntax varies quite a bit from language to language, the basic structure(in pseudo code form) looks like this: (The example is actually perfectly valid Visual Basic or QuickBasic syntax.)

    IF (predicate)

    THEN

    (Consequent)

    ELSE

    (Alternative)

    END IF

    When an interpreter finds an If, it expects a Boolean condition for example, x > 0, whichmeans "the variable x contains a number that is greater than zero" and evaluates that condition.If the condition is true, the statements following the then are executed. Otherwise, the executioncontinues in the following branch either in the else block (which is usually optional), or if thereis no else branch, then after the end If.

    2. ELSE IF STATEMENT:-

    By using else if , it is possible to combine several conditions. Only the statements following the

    first condition that is found to be true will be executed. All other statements will be skipped. Thestatements of

    if condition then

    -- statements;

    elsif condition then

  • 7/27/2019 C#.net file

    18/36

    -- more statements

    elsif condition then

    -- more statements;

    ...

    else

    -- other statements

    End if

    In some other languages, such as C and Java, else if literally just means else followed by if, andsyntactic sugar is neither needed nor provided. This works because in these languages, an elsefollowed by one statement (in this case the if) does not need braces. This is not true in Perl,

    which provides the keyword else if to avoid the large number of braces that would be required bymultiple if and else statements. Similarly, Python uses the special keyword else if becausestructure is denoted by indentation rather than braces, so a repeated use of else and if wouldrequire increased indentation after every condition.

    3. SWITCH CASE:-

    The C# switch statement allows you to choose from many statements based on multipleselections by passing control to one of the case statements within its body. The switch statementexecutes the case corresponding to the value of the expression. The switch statement can includeany number of case instances.

    Switch (expression)

    {

    Case expression:

    //your code here

    jump-statement

    default:

    //your code here

    jump-statement

  • 7/27/2019 C#.net file

    19/36

    }

    ARRAYS

    An array is the collection of same type of data items which are referred by common name.

    Declaration of array:-

    Data-type array-name[size] ;

    Initialization of array:-

    Data-type array- name[size]= {value1,value2,value3, .};

  • 7/27/2019 C#.net file

    20/36

  • 7/27/2019 C#.net file

    21/36

    Generally in C++ the destructor is called when objects gets destroyed. And one can explicitly

    call the destructors in C++. And also the objects are destroyed in reverse order that they arecreated in. So in C++ you have control over the destructors.

    One may be thinking how C# treats the destructor. In C# you can never call them, the reason isone cannot destroy an object. So who has the control over the destructo r (in C#)? Its the .Netframeworks Garbage Collector (GC).

    Now few questions arise why GC should control destructors why not us?

    The answer is very simple GC can do better object release than we can. If we do manual memorymanagement one has to take care both allocation and de-allocation of memory. So there is

    always chance that one can forgot de-allocation. And also manual memory management is timeconsuming and complex process.

    NAMESPACES

    Namespaces allow you to create a system to organize your code. A good way to organize your namespaces is via a hierarchical system. You put the more general names at the top of the

    hierarchy and get more specific as you go down. This hierarchical system can be represented bynested namespaces.By placing code in different sub-namespaces, you can keep your codeorganized.

    Example:

    namespace arun.CSharp.Namespaces

    {

    public class Hello

    {

    public string GetMessage()

    {

    return "Hello, world";

  • 7/27/2019 C#.net file

    22/36

    }

    }

    }

    Namespaces are hierarchical, and the name arun.CSharp.Namespace is actually shorthand for defining a namespace named arun that contains a namespace named CSharp that itself contains anamespace named Namespaces, as in:

    namespace arun

    {

    namespace CSharp

    {

    namespace Namespaces

    {....}

    }

    }

    EXCEPTION HANDLING

    The C# language's exception handling features help you deal with any unexpected or exceptionalsituations that occur when a program is running. Exception handling uses the try, catch, andfinally keywords to try actions that may not succeed, to handle failures when you decide that it isreasonable to do so, and to clean up resources afterward. Exceptions can be generated by thecommon language runtime (CLR), by the .NET Framework or any third-party libraries, or byapplication 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 willexecute the first such catch block that if finds. If it finds no appropriate catch block anywhere inthe 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 exceptionhandling, this program would terminate with a DivideByZeroException was unhandled error.

    class ExceptionTest

  • 7/27/2019 C#.net file

    23/36

    {

    static double SafeDivision(double x, double y)

    {

    if (y == 0)

    throw new System.DivideByZeroException();

    return x / y;

    }

    static void Main()

    {

    double a = 98, b = 0;

    double result = 0;

    try

    {

    result = SafeDivision(a, b);

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

    }

    catch (DivideByZeroException e)

    {

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

    }

    }

    }

    FILE HANDLING

  • 7/27/2019 C#.net file

    24/36

    File handling is an unmanaged resource in your application system. It is outside your applicationdomain (unmanaged resource). It is not managed by CLR. Data is stored in two ways, persistentand non-persistent manner.When you open a file for reading or writing, it becomes stream.Stream: Stream is a sequence of bytes traveling from a source to a destination over acommunication path. The two basic streams are input and output streams. Input stream is used toread and output stream is used to write. The System.IO namespace includes various classes for file handling. The parent class of file processing is stream. Stream is an abstract class, which isused as the parent of the classes that actually implement the necessary operations. The primarysupport of a file as an object is provided by a .NET Framework class called File. This static classis equipped with various types of (static) methods to create, save, open, copy, move, delete, or check the existence of a file.

    The following table describes some commonly used classes in the System.IO namespace.

    Class Name Description

    Filestream It is used to read from and write to any location within a file BinaryReader It is used to read primitive data types from a binary stream Binarywriter It is used to read primitive data types from a binary stream Streamreader It is used to read characters from a byte Stream Streamwriter It is used to write characters to a stream.

    Reading and writing in the text file

    StreamWriter

    The StreamWriter class in inherited from the abstract class TextWriter. The TextWriter class represents a writer, which can write a series of characters.

    The following table describes some of the methods used by StreamWriter class.

    Methods Description Close Closes the current StreamWriter object and the underlying stream Flush Clears all buffers for the current writer and causes any buffered data to be

    written to the underlying stream Write Writes to the stream Writeline Writes data specified by the overloaded parameters, followed by end of

    line

  • 7/27/2019 C#.net file

    25/36

    StreamReader

    The StreamReader class is inherited from the abstract class TextReader. The TextReader class

    represents a reader, which can read series of characters. The following table describes some methods of the StreamReader class.

    Methods Description Close Closes the object of StreamReader class and the underlying stream, and

    release any system resources associated with the reader Peak Returns the next available character but doesn't consume it Read Reads the next character or the next set of characters from the stream Readline Reads a line of characters from the current stream and returns data as a

    string Seek Allows the read/write position to be moved to any position with the file

    Reading and writing in the binary file

    BinaryReader

    BinaryReader handles binary files. A binary file may have thousands of integers stored in it, or another simple data type. BinaryReader is mainly for convenience. It makes using binary dataeasier. If you do not have a binary file you are trying to open already, you can create one using

    the BinaryWriter type in the C# programming language. Please visit the BinaryWriter tutorial onDot Net Perls for instructions about creating a binary file.

    BinaryWriter

    BinaryWriter creates binary files. A binary file uses a specific data layout for its bytes. TheBinaryWriter type is ideal it provides a stream-based mechanism for imperatively writing datato a file location on the disk.

    WINDOWS FORMS

  • 7/27/2019 C#.net file

    26/36

    A Windows Forms application is an application that uses top level windows, known as forms,and common user interface controls, such as buttons and text boxes, in order to interact with theend user. That kind of application is known as desktop application (in contrast to webapplications which are HTML-based applications). .Net provides rich functionality to help increating desktop applications. Most of the classes and types used in creating desktop applicationsreside in the System.Windows.Forms namespace.

    IDE and tools : The MS Visual Studio IDE (Integrated Development Environment) is a RAD(Rapid Application Development) IDE and it provides a number of tools for building windows-

    based applications rapidly.

    Form Designer:- Provides a design surface where the user drops and arranges controls in order to build a form.

    Property Grid:- Displays the public properties of the currently selected control or controls,

    allowing the user to customize the appearance and behavior of that control. It also displays a listof the available events for the control. Double clicking on an event name, creates an empty eventhandler.

    Toolbox :- Displays lists of available controls and components. The user drags items from that box and drops them on the Form Designer.

    Code editor :- A state of the art text edit control for writing user code.

    Creating a Windows Forms application

    The MS Visual Studio provides a wizard for creating a new Windows Forms project. Thatwizard is accessible by right clicking the Solution in the Solution Explorer and then Add | NewProject | Visual C# | Windows | Windows Forms Application. The wizard creates a new projectwhich contains just a single Form. Additional Forms can be added by right clicking the project inthe Solution Explorer and then Add | Windows Form.

    Windows Forms built-in controls and components

  • 7/27/2019 C#.net file

    27/36

    BUTTONS

    There are three buttons: the Button, RadioButton and CheckBox. They all inherit from theSystem.Windows.Forms.ButtonBase class. The ButtonBase class provides a set of properties thataffect the visual aspect of the button such as the FlatStyle, FlatAppearance, ImageList and

    ImageIndex etc.

    Button

    A classic button control programmers use all the time as a command button.

    CheckBox

    A classic check box with three-state capability.

    RadioButton

    A classic radio button, also known as option button. Radio buttons work in groups. Allradio buttons on the same parent act as a group. When AutoCheck is true, clicking on aradio button selects that button and de-selects any other radio button on the same parent.

    TextBox

    TextBox is a classic text box. Can be either single-line or multi-line. When Multiline boolean property is set to true, then Environment.NewLine is considered as the new linemark. Some properties, such as ScrollBars and WordWrap work only when the text boxis a multi-line one. TextBox has a 64K character capacity limit.

    RichTextBox

    RichTextBox is a multi-line text box that can display and edit RTF text, that is formatted text

    with bold, italic, colors etc. The SelectionFont and the SelectionColor are the key properties. Theformatting is applied any selected text or to new text entered after the change. The RichTextBoxhas not any character capacity limit.

    LIST CONTROLS :

  • 7/27/2019 C#.net file

    28/36

    ComboBox

    ComboBox represents a drop-down list of choices. The list is a list of objects, so practically an

    item can be of any type. The key properties are the SelectedIndex and the SelectedItem. The Text property returns the text of the selected item, if any. Also the ComboBox provides auto-completion functionality through the AutoCompleteMode, AutoCompleteCustomSource andAutoCompleteSource properties.

    ListBox

    ListBox represents a list of choices. The list is a list of objects, so practically an item can be of any type. The key properties are the SelectedIndex and the SelectedItem. The Text propertyreturns the text of the selected item, if any. ListBox provides multi-selection functionalitythrough the SelectionMode, SelectedIndices and SelectedItems.

    CheckedListBox

    CheckedListBox is a ListBox where presents a check box in front of each item. CheckedIndicesand CheckedItems collection properties return the checked indices and the checked items.

    ProgressBar

    The ProgressBar is a classic progress bar. The Minimum and Maximum properties indicate therange of the bar while the Step property indicates the how many positins the bar moves wherePerformStep() is called. Another way is to call the Increment() method. The Value propertyindicates the current position of the bar.

    DateTimePicker

    The DateTimePicker control is actually a combo box which displays a calendar in place of thedrop down list. The key property is the Format property of type DateTimePickerFormat enum.The Format property determines the mode of the control. When Format is Long or Short thecontrol diplays a long or a short date accordingly, while when Format is Time it displays timevalues. Setting Format to Custom requires to set the CustomFormat string property too.CustomFormat accepts valid date time format strings, i.e. yyyy-MM-dd or hh:mm etc.

  • 7/27/2019 C#.net file

    29/36

    NumericUpDown

    The NumericUpDown control is a spin text box, a control that accepts and displays numeric

    values in a user defined range. ListView

    ListView is a Windows list view control which displays a list of items. Those items are displayedaccording to the setting of the View property of type View. The List View can have Columnswhen View is set to Details. The Columns property stores the settings for those columns. TheItems property is a collection of ListViewItem objects. When columns are used each item is acollection of sub-items equal to the number of columns. The ListViewItem provides the SubItems property.

    TreeView

    TreeView is a Windows tree view control which displays a list of labeled items. Each item is aTreeNode object. The tree itself and each TreeNode object provide the Nodes property which isthe collection of its nodes.

    PictureBox

    The PictureBox control is used to display bitmap, icon, metafile, JPEG, GIF and PNG files. The

    key is the Image property which is an instance of the Image class.

    Label and LinkLabel

    Both controls display read-only text to the user. The Linklabel displays hyperlinks. They both provide a Click event.

    Timer

    The Timer component is a simple timer. It provides the Tick event which is triggered on Interval periods, when Enabled is true.

    Notify Icon

  • 7/27/2019 C#.net file

    30/36

    The NotifyIcon displays an icon in the Windows task bar notification area. Key properties are the Text, the Icon and the ContexMenu or ContextMenuStrip. TheShowBalloonTip() method displays a balloon tip in the notification area for a specified

    period.

    THREADING

    A thread is an independent execution path, able to run simultaneously with other threads.Threading enables your C# program to perform concurrent processing so you can domore than one operation at a time. For example, you can use threading to monitor input from the

    user, perform background tasks, and handle simultaneous streams of input. TheSystem.Threading namespace provides classes and interfaces that support multithreaded

    programming and enable you to easily perform tasks such as creating and starting new threads,synchronizing multiple threads, suspending threads, and aborting threads. To incorporatethreading in your C# code, simply create a function to be executed outside the main thread and

    point a new Thread object at it. .

    using System;

    using System.Threading;

    Heres a simple example and its output:

    class ThreadTest

    {

    static void Main()

    {

    Thread t = new Thread (WriteY); // Kick off a new thread

    t.Start(); // running WriteY()

    for (int i = 0; i < 1000; i++)

    Console.Write ("x");

    }

  • 7/27/2019 C#.net file

    31/36

    static void WriteY()

    {

    for (int i = 0; i < 1000; i++)

    Console.Write ("y");

    }

    }

    JOIN AND SLEEP

    You can wait for another thread to end by calling its Join method. For example:

    static void Main()

    {

    Thread t = new Thread (Go);

    t.Start();

    t.Join();

    Console.WriteLine ("Thread t has ended!");

    }

    static void Go()

    {

    for (int i = 0; i < 1000; i++)

    Console.Write ("y");

    }

  • 7/27/2019 C#.net file

    32/36

  • 7/27/2019 C#.net file

    33/36

  • 7/27/2019 C#.net file

    34/36

    1.

    2.

    3. Then write , Server name - .\sqlexpress

  • 7/27/2019 C#.net file

    35/36

    Database name Any name you want to give , let say project .

    HOW TO CREATE TABLES ??.....

    1. Click on in front of database , in solution explorer.

    2. Right click on tables , select create new table .

    3. Tables to be created are :-

    Login

    Labs

    Complaints

    Components

    Systems

    Vendors

    Manufacturer

  • 7/27/2019 C#.net file

    36/36

    WINDOWS FORMS :-

    1. The next and the last part of project is window form designing and coding .

    2. Now lets have a look of all the forms one by one along with their coding.