lecture1 - FTP Directory Listing
Download
Report
Transcript lecture1 - FTP Directory Listing
C# for JAVA
programmers
ASP.NET
Rina Zviel-Girshin
Lecture 1
1
Overview
C#
Basics
Syntax
Classes
ASP.NET
2
Introduction
C# is derived from C ++, Java, Delphi, Modula-2,
Smalltalk.
Designed to be the main development medium for
future Microsoft products
Similar to Java syntax.
Some claim - C# is more like C++ than Java.
Authors: Hejlsberg, Wiltamuth and Golde.
Modern object oriented language.
Internet-centric
the goal of C# and .NET is to integrate the web into
desktop.
3
What Can you do with C#?
You can write:
Console applications
Windows Application
ASP.NET projects
Web Controls
Web Services
4
Keywords
C# has 77 keywords.
C++ has 63.
Java has 48.
35 are shared.
13 in Java are omitted:
boolean,extends,final, implements
import,instanceof, native,package,strictfp,
super, synchronized, throws, transient
5
List of keywords
abstract as base bool break byte
case catch char checked class const continue
decimal default delegate do double
else enum event explicit extern
false fixed float for foreach goto
if implicit int interface internal
lock long namespace new null
object out override private protected public readonly ref return
sbyte sealed short sizeof stackalloc static string
struct switch this throw true try typeof
uint ulong unchecked unsafe ushort using
volatile void while
6
C# Program Structure
Namespaces
Type declarations
Contain types and other namespaces
Classes, structs, interfaces, enums and delegates
Members
Constants, fields, methods, properties, events,
operators, constructors, destructors
7
Syntax
Case-sensitive.
White space means nothing.
Semicolons (;) to terminate statements.
Code blocks use curly braces ({}).
C++/Java style comments
// or /* */
Also adds /// for automatic XML
documentation
8
Hello World
using System; //the same as import
Hello.cs
class Hello
{
static void Main()
{
Console.WriteLine("Hello world");
}
}
9
Writing and compiling
Use any text editor or
STUDIO.NET to write your
programs.
File .cs.
Compile using csc (C# Compiler)
or “Compile” option of Studio.
Compilation into MSIL
(Microsoft Intermediate
Language) (as ByteCode in Java).
The MSIL is then compiled
into native CPU instructions
MSIL is a complete language more
or less similar to Assembly language
by using JIT (Just in Time)
compiler at the time of the
program execution.
CLR (Common Language
Runtime) provides a
universal execution engine
for developers code
CLR is independent and is
provided as part of the .NET
Framework.
10
Type System
Value types
Primitives
Enums
Structs
int i;
enum State { Off, On }
struct Point { int x, y; }
Reference types
Classes
Interfaces
Arrays
Delegates
class Foo: Bar, IFoo {...}
interface IFoo: IBar {...}
string[] a = new string[10];
delegate void Empty();
11
Data Types
Value types (primitive types and enumerated
values and structures)
byte, sbyte, char, bool, int, uint, float, double, long
(int64)..
string
or reference types (objects and array).
Casting is allowed.
Identifier’s name as in Java.
12
Primitive types
Type
bool
sbyte
byte
short
ushort
int
uint
Size
1
1
1
2
2
4
4
Type
long
ulong
char
float
double
decimal
string
Size
8
8
2
4
8
16
20+
13
Arrays
Zero based, type bound.
Built on .NET System.Array class.
Declared with type and shape, but no bounds
Created using new or initializers
int [ ] one;
int [ , ] two;
int [ ][ ] three;
one = new int[20];
two = new int[,]{{1,2,3},{4,5,6}};
three = new int[1][ ];
three[0] = new int[ ]{1,2,3};
Arrays are objects
one.Length
System.Array.Sort(one);
14
Data
All data types derived from
Declarations:
System.Object
datatype varname;
datatype varname = initvalue;
C# does not automatically initialize local
variables (but will warn you)!
15
Statements
Conditional statements have the same syntax
as in Java.
if else, switch case,
for, while, do .. while,
&& , || , ! and a bitwise & and |
Function calls as in Java.
16
foreach Statement
Iterates over arrays or any class that implements the
IEnumerable interface
Iteration of arrays
public static void Main(string[] args) {
foreach (string s in args) Console.WriteLine(s);
}
Iteration of user-defined collections
foreach (Customer c in customers.OrderBy("name")) {
if (c.Orders.Count != 0) {
...
}
}
17
Classes
All code and data enclosed in a class.
Class members
Constants, fields, methods, properties, events, operators,
constructors, destructors
Static and instance members
Nested types
C# supports single inheritance.
class B: A, IFoo {...}
All classes derive from a base class called Object.
You can group your classes into a collection of
classes called namespace.
18
Example
using System;
namespace ConsoleTest
{
public class Name
{
public string FirstName = "Rina";
public string LastName = "ZG";
public string GetWholeName()
{
return FirstName + " " + LastName;
}
static void Main(string[] args)
{
Name myClassInstance = new Name();
Console.WriteLine("Name: " + myClassInstance.GetWholeName());
Console.ReadLine();
}
}
}
19
More about class
File name the same as class name.
The same name as class.
Exists a default constructor.
Overloading is allowed.
this keyword can be used.
20
Passing parameters by reference
Passing parameters – by value value types and by
reference reference type.
Adding ref or out keyword before value type
arguments in function call results into by reference
function call.
Example:
void Swap(ref int a , ref int b)
function call – Swap(ref x, ref y);
The difference b/t ref and out – out values can be
uninitilized.
21
Inheritance
C# like Java has no Multiple Inheritance.
C# like Java allows multiple implementations
via interfaces.
C# has different access modifiers:
C# access
modifier
private
public
internal
protected
internal protected
Java access
modifier
private
public
protected
N/A
N/A
22
Enumerations
Define a type with a fixed set of possible values
enum Color
{
Red, Green, Blue
}
…
Color background = Color.Blue;
Integer casting must be explicit
Color background = (Color)2;
int oldColor = (int)background;
23
Delegates
Object oriented function pointers
Multiple receivers
Each delegate has an invocation list
Thread-safe + and - operations
Foundation for events
delegate double Func(double x);
Func func = new Func(Math.Sin);
double x = func(1.0);
24
ASP .Net and C#
Easily combined and ready to be used in
WebPages.
Powerful.
Fast.
Most of the works are done without getting
stuck in low level programming and driver
fixing and …
25
Why ASP.NET?
ASP.NET makes building real world Web
applications relatively easy.
Displaying data, validating user input and uploading
files are all very easy.
ASP.NET uses predefined .NET Framework classes:
Just use correct classes/objects.
over 4500 classes that encapsulate rich functionality like
XML, data access, file upload, image generation,
performance monitoring and logging, transactions,
message queuing, SMTP mail and more
ASP.NET pages work in all browsers
including Netscape, Opera, AOL, and Internet Explorer.
26
ASP.NET in the Context of .NET
Framework
VB
C++
C#
JScript
J#
Common Language Specification
Web Forms Web Services
Windows
Forms
ADO.NET and XML
Base Class Library
Common Language Runtime
Operating System
Visual Studio.NET
ASP.NET
We will start with
Web Forms
27
HTML page
User Agent asks HTML
page by sending HTTP
request to the web-server.
Web-server sends a
response which includes
the required page
including additional data
objects.
Server
PC running
UA – IE
28
ASP.NET page modus operand
Usually ASP.NET page constructed from regular HTML
instructions and server instructions.
Server instructions are a sequence of instructions that should
be performed on server.
An ASP .NET page has the extension .aspx.
ASP+ = ASP.NET
If UA requests an ASP .NET page the server processes any
executable code in the page (the code can be written in
current page or can be written in additional file).
The result is sent back to the UA.
29
Adding Server Code
You can add some code for execution simply by adding
syntactically correct code inside <% %> block.
Inside <% %> block you write instruction that should be
implemented on server machine.
Example:
<html>
<body bgcolor=“silver"> <center>
<p> <%Response.Write(now())%> </p>
</center> </body> </html>
Where now() returns the date on the server computer and adds it to the resulting
html page.
Response is a Response object and it has a write method that outputs it’s
argument to the resulted text.
30
Dynamic Pages
ASP.NET pages are dynamic.
Different users get different information.
In addition to using <% %> code blocks to add
dynamic content ASP.NET page developer can
use ASP.NET server controls.
Server controls are tags that can be understood
by the server and executed on the server.
31
Types of Server Controls
There are three types of server controls:
HTML Server Controls – regular HTML tags with
additional attribute id and runat=“server”directive:
Web Server Controls - new ASP.NET tags that have the
following syntax:
<input id="field1" runat="server">
<asp:button id="button1" Text="Click me!" runat="server"
OnClick="submit"/>
Validation Server Controls – those controls are used for
input validation:
More about
server controls
in the future
<asp:RangeValidator ControlToValidate=“gradesBox"
MinimumValue="1" MaximumValue="100" Type="Integer"
Text="The grade must be from 1 to 100!" runat="server" />
32
How to run ASPX file?
To run ASPX file on your computer you need to install IIS,
.NET SDK, IE6 and Service Pack 2.
Now you can write asp.net pages using any text editor even Notepad!
Exists many other tools Visual Studio.NET or Web-Matrix.
Place your code to the disk:\Inetpub\wwwroot directory (or
you can change this default directory).
Now open your browser and request the following page:
http://127.0.0.1/mypage.aspx
or http://localhost/mypage.aspx
It is a loopback call. Your PC now plays 2 roles: a client and a server.
33
Loopback call
Using your UA you type a request for a specific
page.
The actual request is sent to your computer’s IIS.
Now your computer is a server that receives a
request and runs it at server.
The resulting code – the response - is sent back to
your computer.
Your computer’s UA displays the response
message.
The loopback is completed.
34
ASP.NET Execution Model
Client
Server
public class Hello{
protected void Page_Load(
Object sender, EventArgs e)
{…}
}
Hello.aspx.cs
First request
Postback
Output Cache
35
Language Support
The Microsoft .NET Platform currently offers built-in
support for three languages:
C#,
Visual Basic and
Jscript (Microsoft JavaScript)
You have to specify language using one of the following
directive
<script language="VB" runat="server">
or
<%@Page Language=“C#” %>
The last directive defines the scripting language for the
entire page.
36
What’s in a name? Web Forms
All server controls must appear within a <form> tag.
The <form> tag must contain the runat="server"
attribute.
The runat="server" attribute indicates that the form
should be processed on the server.
An .aspx page can contain only ONE <form
runat="server"> control.
That is why .aspx page is also called a web form.
37
Web Forms creation
ASP.NET supports two methods of creation
dynamic pages:
a spaghetti code - the server code is written within
the .aspx file.
a code-behind method - separates the server code
from the HTML content. 2 files – .cs and .aspx
38
Spaghetti code - Copy.aspx
<%@ Page Language="C#" %>
<script runat=server>
void Button_Click(Object sender, EventArgs e)
{
field2.Value = field1.Value;
}
</script>
<html><body>
<form Runat="Server">
Field 1:<input id="field1" size="30" Runat="Server"><br>
Field 2: <input id="field2" size="30" Runat="Server"><br>
<input type="submit" Value=“Submit Query”
OnServerClick="Button_Click" Runat="Server">
</form>
</body></html>
A server code
is written
within the .aspx file
39
Output
The output
after
inserting
www to the
first field
and
pressing
the button.
40
Code-behind– myCodeBehind.cs file
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
public class myCodeBehind: Page {
protected Label lblMessage;
protected void Button_Click(Object sender , EventArgs e)
{ lblMessage.Text="Code-behind example"; }
}
41
Presentation.aspx file
<%@ Page src="myCodeBehind.cs" Inherits="myCodeBehind" %>
<html><body>
<form runat="Server">
<asp:Button id="Button1" onclick="Button_Click"
Runat="Server" Text="Click Here!"></asp:Button>
<br/>
<asp:Label id="lblMessage" Runat="Server"></asp:Label>
</form>
</body></html>
42
The Code-Behind Example Output
After onclick
event
43
IIS - Installation
If exists: MY Computer ->(rc=right click, manage)
Computer Management -> Services and Applications
-> IIS- Internet Information Service (5.0 or 5.1).
Or: C:\WINDOWS\system32\inetsrv\inetmgr.exe
Install: Start -> Control Panel -> Add or Remove
Programs -> Add/Remove Windows Components ->
IIS -> next …
44
IIS – Ins’ Problems
Trying to open a project (VS):
“visual studio .net has detected that the specified web server is
not running ASP.NET
version 1.1 you will be unable to run ASP.NET web
applications or services”
Solution: in command prompt
c:\windows\microsoft.net\framework\v1.1.4322 -> run:
aspnet_regiis –I
45
IIS – Ins’ Problems
1.
2.
3.
Trying to run\debug in VS:
“Error while trying to run project…Debugging failed
because integrated windows authentication is not
enabled…”
Solution:
To enable integrated Windows authentication
Log onto the Web server using an administrator account.
From the Start menu, open the Administrative Tools Control
Panel.
In the Administrative Tools window, double-click Internet
Information Services.
46
IIS – Ins’ Problems
4. In the Internet Information Services window, use the tree control to open the
node named for the Web server.
A Web Sites folder appears beneath the server name.
5. You can configure authentication for all Web sites or for individual Web sites.
To configure authentication for all Web sites, right-click the Web Sites folder
and choose Properties from the shortcut menu. To configure authentication for
an individual Web site, open the Web Sites folder, right-click the individual
Web site, and choose Properties from the shortcut menu
6. In the Properties dialog box, select the Directory Security tab.
7. In the Anonymous access and authentication section, click the Edit button.
8. In the Authentication Methods dialog box, under Authenticated access, select
Integrated Windows authentication.
9. Click OK to close the Authentication Methods dialog box.
10. Click OK to close the Properties dialog box.
11. Close the Internet Information Services window.
47
Start Programming
Default Home Directory is in C:\Inetpub\wwwroot\ but you can work in
any directory you choose using Virtual directory.
Virtual directory: Web Sites -> Default Web Site -> (rc, New ) -> Virtual
Directory.. -> next -> Alias -> Path…
Run your .aspx: after compilation you can run in the visual studio
environment or calling the .aspx through the I-Explorer with the following
link http://localhost/’Alias’/’filename’.aspx
http://127.0.0.1/’Alias’/’filename’.aspx .
To prevent script from running, ,not to allowed to execute the code , Alias
-> (rc, Properties) Execute Permissions – none.
48
Start Programming
The Html – page (only html) is different from the
aspx - page (html, asp.net, script) it was making
from.
Always give reasonable names to: Project, functions,
variables, files, windows…!!!
Always document (explain) the code!!!
The two paragraph above are matter of life!!! (grades
will be taken regardless the correctness of the code
when not documented\named !!!)
49