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

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

Date post:29-Dec-2015
Category:
View:216 times
Download:1 times
Share this document with a friend
Transcript:
  • C# for JAVA programmers

    ASP.NET

    Rina Zviel-GirshinLecture 1

  • OverviewC#BasicsSyntaxClassesASP.NET

  • IntroductionC# 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 productsAuthors: Hejlsberg, Wiltamuth and Golde.Modern object oriented language.Internet-centric the goal of C# and .NET is to integrate the web into desktop.

  • What Can you do with C#?You can write:Console applicationsWindows ApplicationASP.NET projectsWeb ControlsWeb Services

  • KeywordsC# has 77 keywords.C++ has 63.Java has 48.35 are shared.13 in Java are omitted:boolean,extends,final, implementsimport,instanceof, native,package,strictfp,super, synchronized, throws, transient

  • List of keywordsabstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit externfalse 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 stringstruct switch this throw true try typeof uint ulong unchecked unsafe ushort using volatile void while

  • C# Program StructureNamespacesContain types and other namespacesType declarationsClasses, structs, interfaces, enums and delegatesMembersConstants, fields, methods, properties, events, operators, constructors, destructors

  • SyntaxCase-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

  • Hello Worldusing System; //the same as import

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

  • Writing and compilingUse 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 codeCLR is independent and is provided as part of the .NET Framework.

  • Type SystemValue typesPrimitives int i;Enumsenum State { Off, On }Structsstruct Point { int x, y; }Reference typesClassesclass Foo: Bar, IFoo {...}Interfaces interface IFoo: IBar {...}Arraysstring[] a = new string[10];Delegatesdelegate void Empty();

  • Data TypesValue types (primitive types and enumerated values and structures)byte, sbyte, char, bool, int, uint, float, double, long (int64)..stringor reference types (objects and array).

    Casting is allowed.Identifiers name as in Java.

  • Primitive types

  • ArraysZero based, type bound.Built on .NET System.Array class.Declared with type and shape, but no boundsint [ ] one; int [ , ] two; int [ ][ ] three;Created using new or initializersone = 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 objectsone.LengthSystem.Array.Sort(one);

  • DataAll data types derived from System.ObjectDeclarations:datatype varname;datatype varname = initvalue;C# does not automatically initialize local variables (but will warn you)!

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

  • foreach StatementIterates over arrays or any class that implements the IEnumerable interfaceIteration of arrays

    Iteration of user-defined collectionsforeach (Customer c in customers.OrderBy("name")) { if (c.Orders.Count != 0) { ... }}public static void Main(string[] args) { foreach (string s in args) Console.WriteLine(s);}

  • ClassesAll code and data enclosed in a class.Class membersConstants, fields, methods, properties, events, operators, constructors, destructorsStatic and instance membersNested typesC# 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.

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

  • More about classFile name the same as class name.The same name as class.Exists a default constructor.Overloading is allowed.this keyword can be used.

  • Passing parameters by referencePassing 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.

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

    Sheet1

    abstractabstractas

    booleanboolasbase

    breakbreakbasebool

    bytebyteboolchecked

    casecasebreakdecimal

    catchcatchbytedelegate

    charcharcaseenum

    classclasscatchevent

    constconstcharexplicit

    continuecontinuecheckedextern

    defaultdefaultclassfalse

    dodoconstfixed

    doubledoublecontinueforeach

    elseelsedecimalimplicit

    extends:defaultin

    finalsealeddelegateinternal

    finallyfinallydois

    floatfloatdoublelock

    forforelsenamespace

    gotogotoenumnull

    ififeventobject

    implementsimplementsexplicitoperator

    importusingexternout

    instanceofisfalseoverride

    intintfinallyparams

    interfaceinterfacefixedreadonly

    longlongfloatref

    nativeexternforsbyte

    newnewforeachsealed

    packagenamespacegotosizeof

    privateprivateifstackalloc

    protectedprotectedimplicitstring

    publicpublicinstruct

    returnreturnint

    shortshortinterfacetypeof

    staticstaticinternaluint

    strictfpN/Aisulong

    superbaselockunchecked

    switchswitchlongunsafe

    synchronizedlocknamespaceushort

    thisthisnewusing

    throwthrownullvirtual

    throwsN/Aobject

    transientN/Aoperator

    trytryout

    voidvoidoverride

    volatilevolatileparams

    whilewhileprivate

    protected

    public

    readonly

    ref

    return

    sbyte

    sealed

    short

    sizeof

    stackalloc

    static

    string

    struct

    switch

    this

    throw

    try

    typeof

    uint

    ulong

    unchecked

    unsafe

    ushort

    using

    virtual

    void

    volatile

    while

    Sheet2

    C# access modifierJava access modifier

    privateprivate

    publicpublic

    internalprotected

    protectedN/A

    internal protectedN/A

    Sheet3

  • EnumerationsDefine a type with a fixed set of possible valuesenum Color { Red, Green, Blue }Color background = Color.Blue;Integer casting must be explicitColor background = (Color)2;int oldColor = (int)background;

  • DelegatesObject oriented function pointersMultiple receiversEach delegate has an invocation listThread-safe + and - operationsFoundation for eventsdelegate double Func(double x);

    Func func = new Func(Math.Sin);double x = func(1.0);

  • 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

  • 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 moreASP.NET pages work in all browsers including Netscape, Opera, AOL, and Internet Explorer.

  • ASP.NET in the Context of .NET FrameworkOperating SystemCommon Language RuntimeBase Class LibraryADO.NET and XMLASP.NETWeb Forms Web ServicesWindowsFormsCommon Language SpecificationVBC++C#JScriptJ#Visual Studio.NETWe will start with Web Forms

  • HTML pageUser 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 IEServerhttp request html pagehttp response html page

  • ASP.NET page modus operandUsually 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.NETIf 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.

  • Adding Server CodeYou can add some code for execution simply by adding syntactically corr

Click here to load reader

Embed Size (px)
Recommended