0154 Introduction To Visual Studio and Csharp Tutorial
0154 Introduction To Visual Studio and Csharp Tutorial
Introduction to
Visual Studio and C#
HANS-PETTER HALVORSEN, 2012.08.17
Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01
Table of Contents
1 Introduction .................................................................................................................................... 5
1.2 C# ............................................................................................................................................. 6
3.1.2 WPF................................................................................................................................ 17
2
3 Table of Contents
4.2.4 Arrays............................................................................................................................. 22
5.2 Polymorphism........................................................................................................................ 35
5
6 Introduction
1.2 C#
C# is p o ou ed see sha p .
C# is an object-oriented programming language and part of the .NET family from Microsoft. The most
recent version is C# 4.0 and it is part of Visual Studio 2010.
The first step in OOP is to identify all the objects you want to manipulate and how they relate to each
other, an exercise often known as data modeling. Once you've identified an object, you generalize it
as a class of objects and define the kind of data it contains and any logic sequences that can
manipulate it. Each distinct logic sequence is known as a method. A real instance of a class is called
a o je t o a i sta e of a lass . The o je t o lass i sta e is hat ou u i the o pute .
Its methods provide computer instructions and the class object characteristics provide relevant data.
You communicate with objects - and they communicate with each other.
Simula was the first object-oriented programming language. Simula was developed in the 1960s by
Kristen Nygaard from Norway.
Java, Python, C++, Visual Basic .NET and C# are popular OOP languages today.
Since Simula-type objects are reimplemented in C++, Java and C# the influence of Simula is often
understated. The creator of C++ (1979), Bjarne Stroustrup (from Denmark), has acknowledged that
Simula was the greatest influence on him to develop C++.
There exist different versions of Visual Studio, such as Visual Studio Express (free), Visual Studio
Professional, Visual Studio Premium and Visual Studio Ultimate.
8
9 Visual Studio
In this window you will select an appropriate template based on what kind of application you want to
create, and a name and location for your project and solution.
Solutions and projects contain items that represent the references, data connections, folders, and
files that you need to create your application. A solution container can contain multiple projects and
a project container typically contains multiple items.
2.2.4 Toolbox
The Toolbox contains all the necessary controls, etc. you need to create your user interface. See
Figure below.
The Toolbox contains all the controls, etc. we can use in our
user interface.
In order to use them in our user interface, we just drag and
d op the to the Fo , as sho elo :
Code Editor:
Build menu:
Debug menu:
Windows Forms is the standard way of creating Windows applications and has existed in many years,
even before .NET 1.0 (2002) was introduced. WPF is a new approach from creating Windows
applications and was introduced with .NET Framework 3.0 (2006).
For example has the Visual Studio 2010 IDE been entirely rewritten using WPF.
Windows Forms Application and WPF Applications will be explained in more detail below.
16
17 Windows Programming
3.1.2 WPF
Developed by Microsoft, the Windows Presentation Foundation (or WPF) is a computer-software
graphical subsystem for rendering user interfaces in Windows-based applications.
The graphical user interface in WPF is designed using XAML (Extensible Application Markup
Language).
XAML:
Following the success of markup languages for web development, WPF introduces a new language
known as eXtensible Application Markup Language (XAML), which is based on XML. XAML is designed
as a more efficient method of developing application user interfaces
In this p oje t e use a si ple Te tBo te tBo 1 a d he e sta t the p og a the te t Hello
Wo ld is itte to the Te tBo .
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}
4.1 Introduction
In this chapter we will start with the basic all programming languages have:…
Namespaces
Classes
Data Fields
Methods
Properties
In the next chapter we will go more in depth of what Object-oriented programming is and introduce
the following important OOP topics:
Inheritance
Polymorphism
Encapsulation
Note! C# is case-sensitive.
20
21 Getting Started with C#
Boolean type
Numeric types: Integrals, Floating Point, Decimal
String type
Example:
int i=35;
long y=654654;
float x;
double y;
decimal z;
4.2.4 Arrays
Example:
The if Statement
The switch Statement
An if statement allows you to take different paths of logic, depending on a given condition. When the
condition evaluates to a boolean true, a block of code for that true condition will execute. You have
the option of a single if statement, multiple else if statements, and an optional else statement.
Example:
bool myTest;
myTest=false;
if (myTest==false)
MessageBox.Show("Hello");
If we have more than one line of code that that shall be executed, we need to use braces, e.g.:
bool myTest;
myTest=false;
if (myTest == false)
{
MessageBox.Show("Hello1");
MessageBox.Show("Hello2");
}
Example:
bool myTest;
myTest=true;
if (myTest == false)
{
MessageBox.Show("Hello1");
}
else
{
MessageBox.Show("Hello2");
}
Example:
int myTest;
myTest=2;
if (myTest == 1)
{
MessageBox.Show("Hello1");
}
else if (myTest == 2)
{
MessageBox.Show("Hello2");
}
else
{
MessageBox.Show("Hello3");
}
Example:
switch (myTest)
{
case 1:
MessageBox.Show("Hello1");
break;
case 2:
MessageBox.Show("Hello2");
break;
default:
MessageBox.Show("Hello3");
break;
}
4.4 Loops
In C# we have different kind of loops:
Example:
int myInt = 0;
Example:
int myInt = 0;
do
{
MessageBox.Show("Inside Loop: " + myInt.ToString());
myInt++;
} while (myInt < 10);
MessageBox.Show("Outside Loop: " + myInt.ToString());
Example:
Example:
4.5 Methods
Methods are extremely useful because they allow you to separate your logic into different units. You
can pass information to methods, have it perform one or more statements, and retrieve a return
value. The capability to pass parameters and return values is optional and depends on what you want
the method to do.
Methods are similar to functions, procedure or subroutine used in other programming languages.
The difference is that a method is always a part of a class.
Example:
Static Methods
Static Methods belongs to the whole class, while nonstatic Methods belong to each instance created
from the class.
class Car
{
//Nonstatic/Instance Method
public void SetColor(string color)
{
}
}
class Boat
{
//Static Method
public static void SetColor(string color)
{
}
}
Boat.SetColor("green");
i.e., e do ’t eed to eate a o je t/i sta tiati g the lass efo e e use the “tati Method.
4.6 Namespaces
Namespaces are C# program elements designed to help you organize your programs. They also
provide assistance in avoiding name clashes between two sets of code. Implementing Namespaces in
your own code is a good habit because it is likely to save you from problems later when you want to
reuse some of your code.
You specify the Namespaces you want to use in the top of your code.
Example:
When you create a new Windows Forms application, the following default namespaces will be
included.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
…
4.7 Classes
The first step in OOP is to identify all the objects you want to manipulate and how they relate to each
other, an exercise often known as data modeling. Once you've identified an object, you generalize it
as a class of objects and define the kind of data it contains and any logic sequences that can
manipulate it. Each distinct logic sequence is known as a method. A real instance of a class is called
a o je t o a i sta e of a lass . The o je t o lass i sta e is hat ou u i the o pute .
Its methods provide computer instructions and the class object characteristics provide relevant data.
You communicate with objects - and they communicate with each other.
Everything in C# is based on Classes. Classes are declared by using the keyword class followed by the
class name and a set of class members surrounded by curly braces.
Every class has a constructor, which is called automatically any time an instance of a class is created.
The purpose of constructors is to initialize class members when an instance of the class is created.
Constructors do not have return values and always have the same name as the class.
Example:
class Car
{
//Method
public void ShowCarColor()
{
}
}
4.7.1 Constructor
The purpose of constructors is to initialize class members when an instance of the class is created.
Example:
class Car
{
//Method
public void ShowCarColor()
{
}
}
Example:
class Car
{
//Method
public void ShowCarColor()
{
}
}
class Car
{
//Method
public void ShowCarColor()
{
}
}
4.8 Properties
Properties provide the opportunity to protect a field in a class by reading and writing to it through
the property. In other languages, this is often accomplished by programs implementing specialized
getter and setter methods. C# properties enable this type of protection while also letting you access
the property just like it was a field.
Example:
class Car
{
myCar.Name="Volvo";
myCar.Color="Blue";
myCar.ShowCarProperties();
So far, the only class members you've seen are Fields, Properties, Methods, and Constructors. Here is
a complete list of the types of members you can have in your classes:
Constructors
Destructors (opposite of Constructors)
Fields
Methods
Properties
Indexers
Delegates
Events
Nested Classes
Camel notation:
Examples:
string myCar;
int number;
string backColor;
→ In Camel casing the first letter of an identifier is lowercase and the first letter of each subsequent
concatenated word is capitalized.
Pascal notation:
Examples:
class Car
{
void ShowCarColor()
{
…
}
}
→ In Pascal casing the first letter in the identifier and the first letter of each subsequent
concatenated word are capitalized.
Examples:
System.Drawing
System.Collections.Generics
Controls:
For controls on your user interface we either use Pascal notation or Hu ga ia otatio , but stick
to one of them!
Examples:
Pas al otatio :
LoginName
LoginPassword
Hu ga ia otatio :
txtName
txtPassword
lblName
btnCancel
Where txt means it is a Text Control, lbl a Label Control, btn a Button Control, etc.
Acronyms:
Casing of acronyms depends on the length of the acronym. All acronyms are at least two characters
long. If an acronym is exactly two characters, it is considered a short acronym. An acronym of three
or more characters is a long acronym.
In general, you should not use abbreviations or acronyms. These make your names less readable.
Similarly, it is difficult to know when it is safe to assume that an acronym is widely recognized.
DBRate
A property named DBRate is an example of a short acronym (DB) used as the first word of a
Pascal-cased identifier.
ioChannel
A parameter named ioChannel is an example of a short acronym (IO) used as the first word of a
camel-cased identifier.
XmlWriter
A class named XmlWriter is an example of a long acronym used as the first word of a Pascal-cased
identifier.
htmlReader
A parameter named htmlReader is an example of a long acronym used as the first word of a
camel-cased identifier.
Inheritance
Polymorphism
Encapsulation
5.1 Inheritance
Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse
existing code. Through effective employment of reuse, you can save time in your programming.
Example:
class Car
{
}
}
Then we define a new class that inherits from the Base Class:
34
35 More Object-oriented Techniques
As ou a see e a use the “etColo () Method that has been defined in the Base Class.
5.2 Polymorphism
Another primary concept of object-oriented programming is Polymorphism. It allows you to invoke
derived class methods through a base class reference during run-time.
Example:
class Car
{
public virtual void CarType()
{
MessageBox.Show("I am a Car");
}
}
The virtual modifier indicates to derived classes that they can override this method.
Then we create 3 new Classes that derive from the Base Class:
These 3 classes inherit the Car class. Each class has a CarType() method and each CarType() method
has an override modifier. The override modifier allows a method to override the virtual method of its
base class at run-time.
… … …
→ This is Polymorphism.
5.3 Encapsulation
Encapsulation means that the internal representation of an object is generally hidden from view
outside of the object's definition. Typically, only the object's own methods can directly inspect or
manipulate its fields.
Exceptions are unforeseen errors that happen in your programs. Most of the time, you can, and
should, detect and handle program errors in your code. For example, validating user input, checking
for null objects, and verifying the values returned from methods are what you expect, are all
examples of good standard error handling that you should be doing all the time.
However, there are times when you don't know if an error will occur. For example, you can't predict
when you'll receive a file I/O error, run out of system memory, or encounter a database error. These
things are generally unlikely, but they could still happen and you want to be able to deal with them
when they do occur. This is where exception handling comes in.
When exceptions occur, they are said to be thrown . C# uses the keywords try, catch, throw and
finally. It works like this: A method will try to execute a piece of code. If the code detects a problem,
it will throw an error indication, which your code can catch, and no matter what happens, it finally
executes a special code block at the end.
MyMethod()
{
try
{
... //Do Something that can cause an Exception
}
catch
{
... //Handle Exceptions
}
finally
{
... //Clean Up
}
Example:
AOChannel myAOChannel;
try
{
37
38 Exception Handling
myAOChannel = analogOutTask.AOChannels.CreateVoltageChannel(
aoChannel,
"myAOChannel",
0,
5,
AOVoltageUnits.Volts
);
writer.WriteSingleSample(true, analogDataOut);
}
catch (Exception e)
{
string errorMessage;
errorMessage = e.Message.ToString();
finally
{
analogOutTask.Stop();
}
The purpose is to control the level in the water tank. In order to communicate with the physical
process we use a NI USB-6008 DAQ device:
We will not show all the details in the code, but focus on the structure.
39
40 Windows Forms Example
In the Solution E plo e e ha e defi ed a Classes folde he e e put all the lasses e eate:
In order to create new classes we right- li k i the “olutio E plo e a d sele t Add-Ne Ite … :
Classes:
We sta t ith the Da Class that o tai s logi fo eadi g a d iti g to the DAQ de i e:
//Constructor
public DaqData(...)
{
...
}
//Method
public double ReadDaqData()
{
...
}
//Method
public void WriteDaqData(...)
{
...
}
}
}
It is good practice to create a new file for each new class we define. Then we start by defining a
meaningful Namespace. Next we define our Class with necessary Fields, Properties and Methods.
We also need to include the necessary Namespace our Class will need. In this example we have
included some 3.party Assemblies from National Instruments:
using NationalInstruments;
using NationalInstruments.DAQmx;
These Assemblies contains the driver to the NI USB-6008 DAQ device we are using.
The Assemblies we use ust e added i the Refe e es folde i the “olutio Explorer:
Main Application:
using NationalInstruments;
using NationalInstruments.UI;
using NationalInstruments.UI.WindowsForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Tuc.Control;
namespace Control_Application
{
public partial class Form1 : Form
{
...
}
}
It is also a good idea to create different regions in order to structure your code better. This can be
done like this:
//Comment
# region
... //Your Code
# endregion
ASP.NET
AJAX/ ASP.NET AJAX
JavaScript
Silverlight
8.2 HTML
HTML, which stands for HyperText Markup Language, is the predominant markup language for web
pages. HTML is the basic building-blocks of webpages.
HTML is written in the form of HTML elements consisting of tags, enclosed in angle brackets (like
<html>), within the web page content. HTML tags normally come in pairs like <h1> and </h1>. The
first tag in a pair is the start tag, the second tag is the end tag (they are also called opening tags and
closing tags). In between these tags web designers can add text, tables, images, etc.
45
46 Web Programming
8.4 CSS
Web browsers can also refer to Cascading Style Sheets (CSS) to define the appearance and layout of
text and other material.
The W3C, maintainer of both the HTML and the CSS standards
8.5 JavaScript
JavaScript is an object-oriented scripting language basically used to create dynamic web pages.
JavaScript is primarily used in the form of client-side JavaScript, implemented as part of a web
browser in order to provide enhanced user interfaces and dynamic websites.
8.6 ASP.NET
ASP.NET is a web application framework developed by Microsoft to allow programmers to build
dynamic web sites, web applications and web services.
It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to
Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Runtime
(CLR), allowing programmers to write ASP.NET code using any supported .NET language, such as C#
and VB.NET.
ASP.NET web pages or webpage, known officially as Web Forms], are the main building block for
appli atio de elop e t. We fo s a e o tai ed i files ith a .asp extension.
ASP.NET AJAX is a set of extensions to ASP.NET developed by Microsoft for implementing AJAX
functionality.
8.8 Silverlight
Microsoft Silverlight is an application framework for writing and running browser plug-ins or other
rich internet applications, with features and purposes similar to those of Adobe Flash. The run-time
environment for Silverlight is available as a plug-in for most web browsers. Silverlight is also one of
the two application development platforms for Windows Phone 7/8.
Silverlight is based on WPF, so in Silverlight applications, user interfaces are declared in Extensible
Application Markup Language (XAML) and programmed using a subset of the .NET Framework.
In order to use databases in our applications we need to know Structured Query language (SQL). For
more information about SQL, see the following Tutorial:
In addition you need to know about database systems. We have different kind of database systems
and lots of different vendors. Since this Tutorial is about Visual Studio and C#, we will use Microsoft
SQL Server. For more information about database systems in general and specially SQL Server, see
the following Tutorial:
9.1 ADO.NET
ADO.NET (ActiveX Data Object for .NET) is a set of computer software components that programmers
can use to access data and data services. It is a part of the base class library that is included with the
Microsoft .NET Framework. It is commonly used by programmers to access and modify data stored in
relational database systems, though it can also access data in non-relational sources.
48
Telemark University College
Faculty of Technology
Kjølnes Ring 56
www.hit.no
Faculty of Technology
E-mail: hans.p.halvorsen@hit.no
Blog: http://home.hit.no/~hansha/