1 / 49

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

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.

vashon
Download Presentation

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

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Overview • C# • Basics • Syntax • Classes • ASP.NET

  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.

  4. What Can you do with C#? • You can write: • Console applications • Windows Application • ASP.NET projects • Web Controls • Web Services

  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

  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

  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

  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

  9. Hello World using System; //the same as import class Hello { static void Main() { Console.WriteLine("Hello world"); } } Hello.cs

  10. 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. Writing and compiling

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

  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.

  13. Primitive types

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

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

  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.

  17. foreach Statement • Iterates over arrays or any class that implements the IEnumerable interface • Iteration of arrays • Iteration of user-defined collections public static void Main(string[] args) { foreach (string s in args) Console.WriteLine(s); } foreach (Customer c in customers.OrderBy("name")) { if (c.Orders.Count != 0) { ... } }

  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.

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

  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.

  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.

  22. Inheritance • C# like Java has no Multiple Inheritance. • C# like Java allows multiple implementations via interfaces. • C# has different access modifiers:

  23. 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;

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

  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 …

  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.

  27. ASP.NET in the Context of .NET Framework VB C++ C# JScript J# Visual Studio.NET Common Language Specification ASP.NET Web Forms Web Services Windows Forms ADO.NET and XML Base Class Library Common Language Runtime Operating System We will start with Web Forms

  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. Server http request html page PC running UA – IE http response html page

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

  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.

  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.

  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

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

  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.

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

  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.

  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.

  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

  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

  40. Output The output after inserting www to the first field and pressing the button.

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

  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>

  43. The Code-Behind Example Output After onclick event

  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 …

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

  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 • Log onto the Web server using an administrator account. • From the Start menu, open the Administrative Tools Control Panel. 3. In the Administrative Tools window, double-click Internet Information Services.

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

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

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

More Related