Monday, 23 March 2015

Getting Started with C#







Getting Started with C#


This lesson will get you started with C# by introducing a few very simple programs. Here are the objectives of this lesson:

¯ Understand the basic structure of a C# program.
¯ Obtain a basic familiarization of what a "Namespace" is.
¯ Obtain a basic understanding of what a Class is.
¯ Learn what a Main method does.
¯ Learn how to obtain command-line input.
¯ Learn about console input/output (I/O).

A Simple C# Program

There are basic elements that all C# executable programs have and that's what we'll concentrate on for this first lesson, starting off with a simple C# program. After reviewing the code in Listing 1-1, I'll explain the basic concepts that will follow for all C# programs we will write throughout this tutorial. Please see Listing 1-1 to view this first program

.

Warning: C# is case-sensitive.

Listing 1-1. A Simple Welcome Program: Welcome.cs

// Namespace Declaration
using System;

// Program start class
class WelcomeCSS
{
    // Main begins program execution.
    static void Main()
    {
        // Write to console
        Console.WriteLine("Welcome to the C# Station Tutorial!");
    }
}
The program in Listing 1-1 has 4 primary elements, a namespace declaration, a class, a Main method, and a program statement. It can be compiled with the following command line:

 csc.exe Welcome.cs
This produces a file named Welcome.exe, which can then be executed. Other programs can be compiled similarly by substituting their file name instead of Welcome.cs. For more help about command line options, type "csc -help" on the command line. The file name and the class name can be totally different.

Note for VS.NET Users: The screen will run and close quickly when launching this program from Visual Studio .NET. To prevent this, add the following code as the last line in the Main method:

// keep screen from going away
// when run from VS.NET
Console.ReadLine();

Note: The command-line is a window that allows you to run commands and programs by typing the text in manually. It is often refered to as the DOS prompt, which was the operating system people used years ago, before Windows. The .NET Framework SDK, which is free, uses mostly command line tools. Therefore, I wrote this tutorial so that anyone would be able to use it. Do a search through Windows Explorer for "csc.exe", which is the C# compiler. When you know its location, add that location to your Windows path. Then open the command window by going to the Windows Start menu, selecting Run, and typing cmd.exe. This blog post might be helpful: How to set the path in Windows 7.

The first thing you should be aware of is that C# is case-sensitive. The word "Main" is not the same as its lower case spelling, "main". They are different identifiers. If you are coming from a language that is not case sensitive, this will trip you up several times until you become accustomed to it.

The namespace declaration, using System;, indicates that you are referencing the System namespace. Namespaces contain groups of code that can be called upon by C# programs. With the using System; declaration, you are telling your program that it can reference the code in the System namespace without pre-pending the word System to every reference. I'll discuss this in more detail in Lesson 06: Namespaces, which is dedicated specifically to namespaces.

The class declaration, class Welcome CSS, contains the data and method definitions that your program uses to execute. A class is one of a few different types of elements your program can use to describe objects, such as structs, interfaces , delegates, and enums, which will be discussed in more detail in Lesson 12: Structs, Lesson 13: Interfaces, Lesson 14: Delegates, and Lesson 17: Enums, respectively. This particular class has no data, but it does have one method. This method defines the behavior of this class (or what it is capable of doing). I'll discuss classes more in Lesson 07: Introduction to Classes. We'll be covering a lot of information about classes throughout this tutorial.

The one method within the WelcomeCSS class tells what this class will do when executed. The method name, Main, is reserved for the starting point of a program. Main is often called the "entry point" and if you ever receive a compiler error message saying that it can't find the entry point, it means that you tried to compile an executable program without a Main method.

A static modifier precedes the word Main, meaning that this method works in this specific class only, rather than an instance of the class. This is necessary, because when a program begins, no object instances exist. I'll tell you more about classes, objects, and instances in Lesson 07: Introduction to Classes.

Every method must have a return type. In this case it is void, which means that Main does not return a value. Every method also has a parameter list following its name with zero or more parameters between parenthesis. For simplicity, we did not add parameters to Main. Later in this lesson you'll see what type of parameter the Main method can have. You'll learn more about methods in Lesson 05: Methods.

The Main method specifies its behavior with the Console.WriteLine(...) statement. Console is a class in the System namespace. WriteLine(...) is a method in the Console class. We use the ".", dot, operator to separate subordinate program elements. Note that we could also write this statement as System.Console.WriteLine(...). This follows the pattern "namespace.class.method" as a fully qualified statement. Had we left out the using System declaration at the top of the program, it would have been mandatory for us to use the fully qualified form System.Console.WriteLine(...). This statement is what causes the string, "Welcome to the C# Station Tutorial!" to print on the console screen.

Observe that comments are marked with "//". These are single line comments, meaning that they are valid until the end-of-line. If you wish to span multiple lines with a comment, begin with "/*" and end with "*/". Everything in between is part of the comment. Comments are ignored when your program compiles. They are there to document what your program does in plain English (or the native language you speak with every day).

All statements end with a ";", semi-colon. Classes and methods begin with "{", left curly brace, and end with a "}", right curly brace. Any statements within and including "{" and "}" define a block. Blocks define scope (or lifetime and visibility) of program elements.

Accepting Command-Line Input

In the previous example, you simply ran the program and it produced output. However, many programs are written to accept command-line input. This makes it easier to write automated scripts that can invoke your program and pass information to it. If you look at many of the programs, including Windows OS utilities, that you use everyday; most of them have some type of command-line interface. For example, if you type Notepad.exe MyFile.txt (assuming the file exists), then the Notepad program will open your MyFile.txt file so you can begin editing it. You can make your programs accept command-line input also, as shown in Listing 1-2, which shows a program that accepts a name from the command line and writes it to the console.
Danger! Regardless of the fact that I documented the proper use of command-line arguments before and after Listing 1-2, some people still send me email to complain that they get an error or tell me there's a bug in my program. In fact, I get more email on this one subject than any other in the whole tutorial. Please read the instructions to include the command-line argument. <Smile />

Note: When running the NamedWelcome.exe application in Listing 1-2, you must supply a command-line argument. For example, type the name of the program, followed by your name: NamedWelcome YourName. This is the purpose of Listing 1-2 - to show you how to handle command-line input. Therefore, you must provide an argument on the command-line for the program to work. If you are running Visual Studio, right-click on the project in Solution Explorer, select Properties, click the Debug tab, locate Start Options, and type YourName into Command line arguments. If you forget to to enter YourName on the command-line or enter it into the project properties, as I just explained, you will receive an exception that says "Index was outside the bounds of the array." To keep the program simple and concentrate only on the subject of handling command-line input, I didn't add exception handling. Besides, I haven't taught you how to add exception handling to your program yet - but I will. In Lesson 15: Introduction to Exception Handling, you'll learn more about exceptions and how to handle them properly.

Listing 1-2. Getting Command-Line Input: NamedWelcome.cs

// Namespace Declaration
using System;

// Program start class
class NamedWelcome
{
    // Main begins program execution.
    static void Main(string[] args)
    {
        // Write to console
        Console.WriteLine("Hello, {0}!", args[0]);
        Console.WriteLine("Welcome to the C# Station Tutorial!");
    }
}

Tip: Remember to add your name to the command-line, i.e. "NamedWelcome Joe". If you don't, your program will crash. I'll show you in Lesson 15: Introduction to Exception Handling how to detect and avoid such error conditions.

If you are using an IDE, like Visual Studio, see your IDE's help documentation on how to set the command-line option via project properties. i.e. in Visual Studio 2010, double-click the Properties folder in your solution project, click the Debug tab, and add your name to Command Line Arguments. The actual step can/will differ between IDE's and versions, so please consult your IDE documentation for more information.

In Listing 1-2, you'll notice an entry in the Main method's parameter list. The parameter name is args, which you'll use to refer to the parameter later in your program. The string[] expression defines the type of parameter that args is. The string type holds characters. These characters could form a single word, or multiple words. The "[]", square brackets denote an Array, which is like a list. Therefore, the type of the args parameter, is a list of words from the command-line. Anytime you add string[] args to the parameter list of the Main method, the C# compiler emits code that parses command-line arguments and loads the command-line arguments into args. By reading args, you have access to all arguments, minus the application name, that were typed on the command-line.

You'll also notice an additional Console.WriteLine(...) statement within the Main method. The argument list within this statement is different than before. It has a formatted string with a "{0}" parameter embedded in it. The first parameter in a formatted string begins at number 0, the second is 1, and so on. The "{0}" parameter means that the next argument following the end quote will determine what goes in that position. Hold that thought, and now we'll look at the next argument following the end quote.

The args[0] argument refers to the first string in the args array. The first element of an Array is number 0, the second is number 1, and so on. For example, if I typed NamedWelcome Joe on the command-line, the value of args[0] would be "Joe". This is a little tricky because you know that you typed NamedWelcome.exe on the command-line, but C# doesn't include the executable application name in the args list - only the first parameter after the executable application.

Returning to the embedded "{0}" parameter in the formatted string: Since args[0] is the first argument, after the formatted string, of the Console.WriteLine() statement, its value will be placed into the first embedded parameter of the formatted string. When this command is executed, the value of args[0], which is "Joe" will replace "{0}" in the formatted string. Upon execution of the command-line with "NamedWelcome Joe", the output will be as follows:

Hello, Joe!
Welcome to the C# Station Tutorial!
Interacting via the Command-Line

Besides command-line input, another way to provide input to a program is via the Console. Typically, it works like this: You prompt the user for some input, they type something in and press the Enter key, and you read their input and take some action. Listing 1-3 shows how to obtain interactive input from the user.

Listing 1-3. Getting Interactive Input: InteractiveWelcome.cs

// Namespace Declaration
using System;

// Program start class
class InteractiveWelcome
{
    // Main begins program execution.
    public static void Main()
    {
        // Write to console/get input
        Console.Write("What is your name?: ");
        Console.Write("Hello, {0}! ", Console.ReadLine());
        Console.WriteLine("Welcome to the C# Station Tutorial!");
    }
}
In Listing 1-3, the Main method doesn't have any parameters -- mostly because it isn't necessary this time. Notice also that I prefixed the Main method declaration with the public keyword. The public keyword means that any class outside of this one can access that class member. For Main, it doesn't matter because your code would never call Main, but as you go through this tutorial, you'll see how you can create classes with members that must be public so they can be used. The default access is private, which means that only members inside of the same class can access it. Keywords such as public and private are referred to as access modifiers. Lesson 19: Encapsulation discusses access modifiers in more depth.

There are three statements inside of Main and the first two are different from the third. They are Console.Write(...) instead of Console.WriteLine(...). The difference is that the Console.Write(...) statement writes to the console and stops on the same line, but the Console.WriteLine(...) goes to the next line after writing to the console.

The first statement simply writes "What is your name?: " to the console.

The second statement doesn't write anything until its arguments are properly evaluated. The first argument after the formatted string is Console.ReadLine(). This causes the program to wait for user input at the console. After the user types input, their name in this case, they must press the Enter key. The return value from this method replaces the "{0}" parameter of the formatted string and is written to the console. This line could have also been written like this:

string name = Console.ReadLine();
Console.Write("Hello, {0}! ", name);

The last statement writes to the console as described earlier. Upon execution of the command-line with "InteractiveWelcome", the output will be as follows:

>What is your Name?  <type your name here> [Enter Key]
>Hello, <your name here>!  Welcome to the C# Station Tutorial!

Summary


Now you know the basic structure of a C# program. using statements let you reference a namespace and allow code to have shorter and more readable notation. The Main method is the entry point to start a C# program. You can capture command-line input when an application is run by reading items from a string[] (string array) parameter to your Main method. Interactive I/O can be performed with the ReadLine, Write and WriteLine methods of the Console class.

Wednesday, 11 March 2015

Structure of C Program
The basic Structure of C Program is as follow:
Document Section
Links Section (File)
Definition Section
Global variable declaration Section
voidmain ()
{
    Variable declaration section
    Function declaration section
    executable statements;
}
voidmain (): Used to start of actual C program. It includes two parts as declaration part and executable part.
Variable declaration section: Used to declare private variable.
Function declaration section: Used to declare functions of program from which we get required output.
Then, executable statements are placed for execution.
Function definition section: Used to define functions which are to be called from main().

C Basic Program
#include<stdio.h>
#include<conio.h>
void main()
{
 printf("Welcome to SOLMEYVN…");

}
Difference between Compiler and Interpreter
The main difference between Compiler and Interpreter is:
Compiler translates the program statements(Source Code) into Machine Code in one go i.e. all lines of program simultaneously. That's why all compiler based languages shows all the errors together.

While interpreter translates the source code into machine code one statement at a time. That's why program execution cannot proceed to next statement until the previous error is corrected/rectified.
Different parts of C program
1.       Pre-processor   
2.       Function
3.       Variables
4.       expression
5.       Comment

Pre-processor: #include < file name>
The first word of any C program. It is also known as pre-processor. The main work of pre-processor is to initialize the environment of program, i.e to link the program with the header file.
Example : #include<stdio.h>
#include- Inclusion Directive
<  > è  Search file only local  file system 
Std- standard
Ièinput
Oèoutput

Main function: main() function is a function that must be used in every C program. A function is a sequence of statement required to perform a specific task. main() function starts the execution of C program. In the above example, int in front of main() function is the return type of main() function. we will discuss about it in detail later. The curly braces { } just after the main() function encloses the body of main() function.

Input output function:
scanf() and printf() functions





C Program Execution Process

Q.)   WHAT IS C?
C Language is a general purpose and structured programming language developed by 'Dennis Ritchie' at AT&T's Bell Laboratories in the 1972s in USA.
It is also called as 'Procedure oriented programming language.'
C is not specially designed for specific applications areas like COBOL (Common Business-Oriented Language) or FORTRAN (Formula Translation). It is well suited for business and scientific applications. It has some various features like control structures, looping statements, arrays, macros required for these applications.
The C language has following numerous features as:
·         Portability
·         Flexibility
·         Effectiveness and efficiency
·         Reliability
·         Interactivity

C program executes in following 4 (four steps).
1.       Creating a Program :
An editor like notepad or wordpad is used to create a C program. This file contains a source code which consists of executable code. The file should be saved as '*.c' extension only.
2.       Compiling the Program :
The next step is to compile the program. The code is compiled by using compiler. Compiler converts executable code to binary code i.e. object code.
3.       Linking a Program to Library :
The object code of a program is linked with libraries that are needed for execution of a program. The linker is used to link the program with libraries. It creates a file with '*.exe' extension.
4.       Execution of Program :
The final executable file is then run by dos command prompt or by any other software.
History of C:
Year of Establishment
Language Name
Developed By
1960
ALGOL-60
Cambridge University
1963
CPL (Combined Programming Language)
Cambridge University
1967
BCPL (Basic Combined Programming Language)
Martin Richard at Cambridge University
1970
B
Ken Thompson at AT& T's Bell Laboratories.
1972
C
Dennis Ritchie at AT& T' Bell Laboratory.

The development of C was a cause of evolution of programming languages like Algol 60,
CPL (Combined Programming Language), BCPL (Basic Combined Programming Language) and B.

Algol-60 : (1963) :ALGOL is an acronym for Algorithmic Language. It was the first structured procedural programming language, developed in the late 1950s and once widely used in Europe. But it was too abstract and too general structured language.

·         CPL : (1963) :
CPL is an acronym for Combined Programming Language. It was developed at Cambridge University.
·         BCPL : (1967) :
BCPL is an acronym for Basic Combined Programming Language. It was developed by Martin Richards at Cambridge University in 1967. BCPL was not so powerful. So, it was failed.
·         B : (1970) :
B language was developed by Ken Thompson at AT& T Bell Laboratories in 1970. It was machine dependent. So, it leads to specific problems.
·         C : (1972) :
'C' Programming Language was developed by Dennis Ritchie at AT& T Bell Laboratories in 1972. This is general purpose, compiled, structured programming language. Dennis Ritchie studied the BCPL, then improved and named it as 'C' which is the second letter of BCPL

Basic of C Programming 

Software:  The term Software refers to the set of computer programs, procedures and associated documents that describe the program and how they are to be used. It is sequences the simple operations that the hardware rapidly and tirelessly repeats, their by making it a very useful tool.
OR
Software: Software is a collection of application program.
 Application Program: Application is collection of large size program.

Program: Program is a set of instructions which are execute in a sequence manner.

Types of Software

1.       System Software
2.       Application Software

System Software: System Software refers to all the programs, languages and documentation supplied by the manufacturer with the computer. These programs allow the users to communicate with the computer and to write or develop his own programs. It is also known as a system package. The system package supports the running of the other software communication with peripheral devices (printer, card readers, disk and tape devices, etc). The system software makes the operation of the computer system more effective and efficient.

System Software is further sub classified as:
         i.            Operating System Software
       ii.            Language Software
Operating System Software:
It contains instructions for carrying out certain task such as:
·          Arithmetic: Add, Subtract, multiply, divide numeric values.
·         Text Processing : Copying, compare, extract,  insert, join textual items
·         Transfer of data between memories, registers, terminals etc.
·         Sequencing: Follow instructions sequentially, select among alternatives set of instructions, repeat instructions.
·         Control: Activate, deactivate, test, synchronize devices, cause data to read from and written in various devices.

Language Software:
                A computer can understand and carry out only such instructions as are coded in machine language. Instructions coded in binary format are extremely tedious to write. Hence instruction in the first instance, are written in English which are the converted by the computer itself into machine language with the help of language software. Language software covers Assembler, Compilers, and Interpreters.
·         Assembler: It translates instructions written in symbolic language into binary form understood by computer hardware.
·         Compiler:

C Overview
C is a structured programming language developed by Dennis Ritchie in 1973 at Bell Laboratories. It is one of the most popular computer languages today because of its structure, high-level abstraction, machine independent feature. C language was developed with UNIX operating system, so it is strongly associated with UNIX, which is one of the most popular network operating system in use today and heart of internet data superhighway.

The root of all modern languages is ALGOL, introduced in 1960s. It was the first computer language to use block structure.
In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming Language) mainly for writing system software.

In the year 1970, using the concepts of BCPL, Ken Thompson developed a language called B. It was used to create earlier versions of UNIX operating System at Bell Laboratories.
·         Both B and BCPL were type less system programming languages
·         C was evolved from ALGOL, BCPL and B by Dennis Ritchie at the Bell Laboratories in 1972.

·         C added the concept of data types
·         Since C was developed along with the UNIX operating system, it is strongly associated with UNIX.
·         The language became more popular after the publication of the book “The C Programming Language” by Brian Kernighan and Dennis Ritchie in 1978. The book was so popular that the language came to be known as”K & R C”.
·         Later on it was made an American Standard (ANSI C) and then International (ISO).
·         C99 is a standardized version of C which was done in 1999; so the name C99.

History of C Language

C language has evolved from three different structured language ALGOL, BCPL and B by Dennis Ritchie. It uses many concepts from these languages and introduced many new concepts such as data types, struct, and pointer. In 1988, the language was formalized by American National Standard Institute(ANSI). In 1990, a version of C language was approved by the International Standard Organization(ISO) and that version of C is also referred to as C89. 





ASP.NET Page Life Cycle Events
PreInit
Init
PreLoad
Load
Control Events
PreRender
SaveViewState
Render

Unload 
PreInit()
This is the first event which raised  in asp.net page lifecycle
Check for Request is for Post Back or not.
All dynamic control need to be created
Theme Change, Master Page Set at runtime
Init()
Raised after all controls have been initialized
Build up a tree of controls from the ASPX file
Turn on view state monitoring – any changes in control will be tracked by View State for future.
PreLoad()
Load view state data for page and controls
Load Postback data if needed
We can process any kind operation that need to perform before page load
Load()
OnLoad methods control called for each and every control
We can create the connection initialization for any kind of external source like database connection
We can also set the control properties
Control Events
If this is an postback request , Corresponding events will triggered. Like, if the post back is happing for button click, then Button_Click Event will fired.
PreRender
Each control of the page has a PreRender event which is being invoked.
EnsureChildControls is also being called during this events
DataBind method for all control has also been called
If we want to change any thing to any control this is the last event where we can do because after the pageRender starts 
SaveViewState
ViewState Monitoring is turned off as here all the ViewState Data need to be saved.
View State data saved in hidden filed called _VIEWSTATE
Render
Pages calls the Render method for each and every control.
Text writer that writes the output to the as output stream
Output steam set to the page's Response property.
Unload
This is the last event of asp.net page life cycle
This ensure the Request and Response has been set to null.
This is called only after the content of the page fully rendered and response sent to client