c# for java programmers asp.net rina zviel-girshin lecture 1

49
1 C# for JAVA C# for JAVA programmers programmers ASP.NET ASP.NET Rina Zviel-Girshin Lecture 1

Upload: vashon

Post on 21-Mar-2016

65 views

Category:

Documents


1 download

DESCRIPTION

C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1. Overview. C# Basics Syntax Classes ASP.NET. Introduction. C# is derived from C ++, Java, Delphi, Modula-2, Smalltalk. Similar to Java syntax. Some claim - C# is more like C++ than Java. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

1

C# for JAVA C# for JAVA programmersprogrammers

ASP.NETASP.NET

Rina Zviel-GirshinLecture 1

Page 2: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

2

Overview C#

Basics Syntax Classes

ASP.NET

Page 3: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

3

Introduction C# is derived from C ++, Java, Delphi, Modula-2,

Smalltalk. Similar to Java syntax. Some claim - C# is more like C++ than Java.

Designed to be the main development medium for future Microsoft products Authors: Hejlsberg, Wiltamuth and Golde.

Modern object oriented language. Internet-centric

the goal of C# and .NET is to integrate the web into desktop.

Page 4: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

4

What Can you do with C#? You can write:

Console applications Windows Application ASP.NET projects Web Controls Web Services

Page 5: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

5

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

Page 6: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

6

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

Page 7: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

7

C# Program Structure Namespaces

Contain types and other namespaces Type declarations

Classes, structs, interfaces, enums and delegates Members

Constants, fields, methods, properties, events, operators, constructors, destructors

Page 8: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

8

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

Page 9: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

9

Hello Worldusing System; using System; //the same as import//the same as import

class Helloclass Hello{{ static void Main() static void Main() {{ Console.WriteLine("Hello world");Console.WriteLine("Hello world"); }}}}

Hello.cs

Page 10: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

10

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).

MSIL is a complete language more or less similar to Assembly language

The MSIL is then compiled into native CPU instructions

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.

Page 11: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

11

Type System Value types

Primitives int i; Enums enum State { Off, On } Structs struct Point { int x, y; }

Reference types Classes class Foo: Bar, IFoo {...} Interfaces interface IFoo: IBar {...} Arrays string[] a = new string[10]; Delegates delegate void Empty();

Page 12: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

12

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.

Page 13: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

13

Primitive typesType Sizebool 1sbyte 1byte 1short 2ushort 2int 4uint 4

Type Sizelong 8ulong 8char 2float 4double 8decimal 16string 20+

Page 14: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

14

Arrays Zero based, type bound. Built on .NET System.Array class. Declared with type and shape, but no bounds

int [ ] one; int [ , ] two; int [ ][ ] three;

Created using new or initializers 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);

Page 15: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

15

Data All data types derived from

System.Object Declarations:

datatype varname;datatype varname = initvalue;

C# does not automatically initialize local variables (but will warn you)!

Page 16: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

16

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.

Page 17: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

17

foreach Statement Iterates over arrays or any class that implements the

IEnumerable interface Iteration of arrays

Iteration of user-defined collections

foreach (Customer c in customers.OrderBy("name")) {foreach (Customer c in customers.OrderBy("name")) { if (c.Orders.Count != 0) {if (c.Orders.Count != 0) { ...... }}}}

public static void Main(string[] args) {public static void Main(string[] args) { foreach (string s in args) Console.WriteLine(s);foreach (string s in args) Console.WriteLine(s);}}

Page 18: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

18

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.

Page 19: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

19

Exampleusing 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(); } }}

Page 20: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

20

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.

Page 21: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

21

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.

Page 22: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

22

Inheritance C# like Java has no Multiple Inheritance. C# like Java allows multiple implementations

via interfaces. C# has different access modifiers:

C# access modifier

Java access modifier

private privatepublic publicinternal protectedprotected N/Ainternal protected N/A

Page 23: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

23

Enumerations Define a type with a fixed set of possible valuesenum Color

{Red, Green, Blue

}…Color background = Color.Blue; Integer casting must be explicit

Color background = (Color)2;int oldColor = (int)background;

Page 24: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

24

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);

Page 25: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

25

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 …

Page 26: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

26

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.  Just use correct classes/objects.

ASP.NET uses predefined .NET Framework classes: 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.

Page 27: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

27

ASP.NET in the Context of .NET Framework

Operating SystemOperating System

Common Language RuntimeCommon Language Runtime

Base Class LibraryBase Class Library

ADO.NET and XMLADO.NET and XML

ASP.NETASP.NETWeb Forms Web ServicesWeb Forms Web Services

WindowsWindowsFormsForms

Common Language SpecificationCommon Language Specification

VBVB C++C++ C#C# JScriptJScript J#J#Visual Studio.N

ETVisual Studio.N

ET

We will start with Web Forms

Page 28: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

28

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.

PC runningUA – IE

Serverhttp request html pagehttp response html page

Page 29: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

29

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.NETASP+ = 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.

Page 30: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

30

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.

Page 31: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

31

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.

Page 32: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

32

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:

<input id="field1" runat="server"> Web Server Controls - new ASP.NET tags that have the

following syntax: <asp:button id="button1" Text="Click me!"

runat="server" OnClick="submit"/> Validation Server Controls – those controls are used for

input validation: <asp:RangeValidator ControlToValidate=“gradesBox"

MinimumValue="1" MaximumValue="100" Type="Integer" Text="The grade must be from 1 to 100!" runat="server" />

More about server controls in the future

Page 33: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

33

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.aspxIt is a loopback call. Your PC now plays 2 roles: a client and a server.

Page 34: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

34

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.

Page 35: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

35

ASP.NET Execution ModelClient Server

public class Hello{protected void Page_Load(Object sender, EventArgs e){…}}Hello.aspx.cs

First requestPostback Output Cache

Page 36: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

36

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.

Page 37: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

37

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.

Page 38: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

38

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

Page 39: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

39

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

Page 40: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

40

Output

The output after

inserting www to the first field

and pressing

the button.

Page 41: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

41

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"; }

}

Page 42: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

42

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>

Page 43: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

43

The Code-Behind Example Output

After onclick event

Page 44: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

44

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 …

Page 45: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

45

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 promptc:\windows\microsoft.net\framework\v1.1.4322 -> run: aspnet_regiis –I

Page 46: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

46

IIS – Ins’ Problems 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

1. Log onto the Web server using an administrator account. 2. From the Start menu, open the Administrative Tools

Control Panel. 3. In the Administrative Tools window, double-click Internet

Information Services.

Page 47: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

47

IIS – Ins’ Problems4. 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.

Page 48: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

48

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’.aspxhttp://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.

Page 49: C# for JAVA programmers ASP.NET Rina Zviel-Girshin Lecture 1

49

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 !!!)