November 13, 2003 Week 2
November 13, 2003 Week 2
NET Fundamentals
Week Topics
1 Introduction to .NET Framework, C#
2 C#, Windows Forms Programming, Exceptions
3 Introduction to Framework Class Library
Types in .NET
Objects and Object Construction
Boxing and Unboxing
Interfaces
Week Topics
4 ADO.NET (managed data access)
- Connections
- Adapters
- Data Sets
- Grid Control
5 Bootstrapping the Common Language Resource (CLR)
Modules and Assemblies
.Net Packaging
Public and Private Keys
Shared Assemblies
The Global Assemble Cache (GAC)
Strong Names
Week Topics
6 ASP.NET
Introduction to Web Services
Web Security
Advanced Concepts:
- Serialization
- Reflection
Web Services Class Project
7 Web Services Class Project (continued)
8 Web Services Class Project (continued)
C#
Data Types
A word on types
• All types in .NET derive from System.Object
• They all provide implementations of ToString()
and GetType()
• To get a string with the type of any variable, you
can call <var>.GetType()
• Whenever you call Console.WriteLine(obj) the
ToString() method on obj is implicitly called. The
default ToString implementation for classes
simply returns the name of the class.
Primitive Types
C# Type .NET Framework type
bool System.Boolean
byte System.Byte
sbyte System.Sbyte
char System.Char
decimal System.Decimal
double System.Double
float System.Single
Primitive Types (continued)
C# Type .NET Framework type
int System.Int32
uint System.UInt32
long System.Int64
ulong System.UInt64
object System.Object
short System.Int16
ushort System.UInt16
string System.String
Boolean
bool bTmp;
bTmp = True;
bool bTmp = False;
double dTmp;
dTmp = 12.625;
double dTmp = 12.625;
double aDbl;
aDbl.ToString("..."); << insert formating
Sample Double Formatting Code
strTmp = Console.ReadLine();
string strTmp2;
strTmp2 = strTmp;
strTmp2 “time will tell”
Concatenating Strings
string strCity = “Calais”;
string strState = “ME”;
string strZip = “04270”;
string strLoc;
strLoc = strCity + “, ” + strState + “ ” + strZip;
strLoc “Calais, ME 04270”
String Functions
string strTmp;
strTmp.Trim(); – removes leading and trailing spaces
strTmp.ToUpper(); – converts string to all upper case
strTmp.ToLower(); – converts string to all lower case
strTmp.Length; – returns string length as an integer
strTmp.SubString() – extracts a substring
String Function Examples
string strTmp = “ Hello World ”;
strTmp.Trim();
strTmp “Hello World”
Additionally, you can use the read/write Capacity property to set the maximum
length of your object. The following example uses the Capacity property to define
the maximum object length.
MyStringBuilder.Capacity = 5;
The EnsureCapacity method can be used to check the capacity of the current
StringBuilder. If the capacity is greater than the passed value, no change is made;
however, if the capacity is smaller than the passed value, the current capacity is
changed to match the passed value.
The Length property can also be viewed or set. If you set the Length property to a
value that is greater than the Capacity property, the Capacity property is
automatically changed to the same value as the Length property. Setting the Length
property to a value that is less than the length of the string within the current
StringBuilder shortens the string.
StringBuilder.methods
Method name Use
Appends information to the end of
StringBuilder.Append
the current StringBuilder.
Replaces a format specifier passed in
StringBuilder.AppendFormat
a string with formatted text.
Inserts a string or object into the
StringBuilder.Insert specified index of the current
StringBuilder.
Removes a specified number of
StringBuilder.Remove characters from the current
StringBuilder.
Replaces a specified character at a
StringBuilder.Replace
specified index.
Append
•The Append method can be used to add text or a string
representation of an object to the end of a string represented
by the current StringBuilder. The following example
initializes a StringBuilder to "Hello World" and then
appends some text to the end of the object. Space is
allocated automatically as needed.
StringBuilder MyStringBuilder = new StringBuilder("Hello World!");
MyStringBuilder.Append(" What a beautiful day.");
Console.WriteLine(MyStringBuilder);
This example displays Hello World! What a beautiful day to
the console.
AppendFormat
• The AppendFormat method adds text to the end of the
StringBuilder, but also implements the IFormattable interface and
therefore accepts the standard format strings described in the
formatting section. You can use this method to customize the format
of variables and append those values to a StringBuilder. The
following example uses the AppendFormat method to place an
integer value formatted as a currency value at the end of a
StringBuilder.
int MyInt = 25;
StringBuilder MyStringBuilder = New StringBuilder("Your total is ");
MyStringBuilder.AppendFormat("{0:C} ", MyInt);
Console.WriteLine(MyStringBuilder);
namespace HelloCall {
class HelloClass {
static void Main(string[] args) {
Console.WriteLine("In Hello Main");
HelloClass foo = new HelloClass();
foo.OtherCall();
}
void OtherCall() {
Console.WriteLine("In OtherCall");
}
}
}
methods
methods
• Provide the ability to transfer control within a
program.
• Simplify code sharing, providing an excellent way
to eliminate redundant code.
• methods maybe called with one or more
arguments or with no arguments at all
• methods maybe called with a return type or a
return type of void to indicate no return type.
methods
Defining
private void aMethod()
{
insert code here;
}
Calling
aMethod();
methods with Arguments
private void aMethod(string strTmp)
{ … }
aMethod(“hi there”);
To set a BackColor:
this.BackColor = Color.Red;
Label1.ForeColor = Color.White;
Abort - The return value is Abort (usually sent from a button labeled Abort).
Cancel - The return value is Cancel (usually sent from a button labeled Cancel).
Ignore - The return value is Ignore (usually sent from a button labeled Ignore).
No - The return value is No (usually sent from a button labeled No).
None - Nothing is returned from the dialog box. This means that the modal dialog
continues running.
OK - The return value is OK (usually sent from a button labeled OK).
Retry - The return value is Retry (usually sent from a button labeled Retry).
Yes - The return value is Yes (usually sent from a button labeled Yes).
MessageBox Sample Code
string strMessage = "No server name. Cancel operation?“;
string strCaption = "No Server Name Specified“;
int iBttns = MessageBoxButtons.YesNo;
int iIcon = MessageBoxIcon.Question;
DialogResult Result;
'Displays a MessageBox using the Question icon and specifying the No
button as the default.
Result = MessageBox.Show(strMessage, strCaption, iBttns , iIcon);
' Gets the result of the MessageBox display.
if (Result = DialogResult.Yes)
{
this.Close(); ' Closes the parent form.
}
Exceptions
Exceptions in .NET
• .NET relies heavily on exception handling.
• In fact all error notification/handling by the
framework is in the form of exceptions.
• Returning error values by your custom code is still
possible, but not encouraged.
• The move from error codes to exceptions will
have an impact on how your code is structured and
designed.
• Since exceptions are part of the framework, they
are consistent across all languages.
Benefits of exception handling
• Cleanup code is kept in a localized spot, and we can be assured that
the code will run.
– This implies your logic isn’t scattered with a ton of cleanup code,
nor do you have to jump to cleanup blocks. (On error goto…)
• Similarly, all code to handle exceptional situations in kept in a
central place.
– Once this is done, you write the rest of your code as if the errors
can never occur.
– Examples of exceptional situations are arithmetic overflows, out-
of-memory conditions, attempts to access resources after they
have been closed, etc.
• When exceptions do occur, the availability of information that will
help us locate and fix the error.
– You typically get call stack information when unhandled
exceptions occur.
Evolution of exception handling
• With Win32, you used error codes and GetLastError
HANDLE h = CreateFile(………);
if (h == INVALID_FILE_HANDLE)
{
DWORD d = GetLastError();
FormatMessage(…d, …);
}
• With COM, you used HRESULTS
HRESULT hr = MyCOMObject.DoSomething();
if (FAILED(hr))
{
// handle error
}
The problem with error codes
• What you get back is a 32 bit number, with no
additional information.
• FormatMessage normally gave you very generic
error descriptions. (“Invalid parameter”), with no
indication of where the problem took place.
• In order to make sense of error codes, you had to
usually include header files. (So what do you do
for other languages ?).
• In the case of “smart” error codes like
HRESULTS, you were provided with macros that
could be used to decipher the code.
Error codes (contd.)
• Defining your own error codes was a very loose process.
– Pick a set of values and put them in a header file.
– Take care that the codes do not conflict with other codes. Usually
achieved by starting your codes at some offset from the well-known set
of codes.
– Provide some mechanism for callers to translate your codes into
meaningful messages.
• After doing all this, you could still do the following:
CreateFile(………); // ignore all errors
OR
MyCOMObject.DoSomething(); //ignore HRESULT
Exceptions
• The last example shows how error codes allow you to opt-in
– you can opt to handle the error, but you ignore it by
default.
• Exceptions change this to the opt-out model – you can
explicitly choose to ignore the exception, but you must
handle it by default.
– If you don’t handle it, your caller gets handed the
exception, and so on up the chain.
• When exception handling was added to C++, it had a
reputation for being slow. Part of the reason was that a fairly
large burden was placed on the compiler to make sure
cleanup (destruction) code was put in place whenever an
exception could be thrown.
Exceptions
• In .NET, since all languages are built on the runtime,
the runtime implements exception handling.
• Unlike error codes, exceptions are objects that
represent exceptional conditions, and can carry a lot
of information.
• In C#, the following keywords are used with
exceptions.
– try
– catch
– finally
– throw
The try block
• The try block is where you put sections of code
that may potentially throw exceptions.
• It also contains code that requires common
cleanup or exception recovery operations.
object o2 = new object();
try
{
//other code you may have …
int i2 = (int) o2; // Error
}
• A try-block by itself is no good – it must be
associated with at least one catch or finally block.
The catch block
• A catch block contains code to execute in response to an
exception.
• A try block can have zero or more catch blocks associated
with it.
}
A common mistake
• Folks commonly put this catch block in
their code:
catch (Exception e1)
{
// Do stuff
}
Homework
Due
November 20, 2003