Introduction to the Microsoft. Net framework



Yüklə 130 Kb.
tarix07.11.2018
ölçüsü130 Kb.
#78922

Introduction to the Microsoft .NET Framework

The Web has changed computing, and will change it more. In 1992 it seemed like a dream that you could connect to a computer in Sweden, click on a link and be connected to a computer in Japan. Now it seems normal.


Today it seems like a dream that you could use a program on your computer and it would call on other programs running on computers in Sweden and Japan, performing tasks for you. Of course, to some extent that is now achieved through a Web browser, using server-side programming. For example, if I want to know the cheapest source of two tons of 16-gauge copper wire, I might be able to find it.

However, today I can find a supplier in the United Kingdom and one in East Orange, New Jersey, using Google, so obviously more change is still to come. This kind of thing is called “business to business” Web services (B2B).
The existence and ubiquity (if you need it there’s a dictionary at www.m-w.com) of bad guys in the world makes it difficult for people to allow other people to run programs on their computer. We need technical means to allow programs to run while ensuring that they can’t do damage. Moreover, the different computers in the world run different operating systems and have different underlying hardware, so it’s difficult to write programs on one computer that will run on many other computers.
Java offers one approach to these problems; .NET offers another. One could say that .NET is Microsoft’s answer to Java. The basic plan in both cases involves “byte code”. This is a kind of “universal assembly language”. It is a language intermediate between a high-level language and machine code for a particular machine. It is not meant to be written by humans, but produced by compilers. But it still needs one last translation stage to produce machine code. That last translation takes place at run-time.
Traditionally code was either compiled or interpreted. (I am assuming you know the difference.) Java and .NET use “just-in-time compilation” (JIT). That means that the byte code is used at run time to produce machine code, which should then execute at the same speed as if the program had been compiled. (Interpreted code often runs an order of magnitude slower.)

But the JIT compiler produces machine code specific for the target machine, so the byte-code file can run on any machine that has a JIT compiler.

There is another advantage to the byte-code approach—you can start with different source languages and produce compatible byte-code. So you could produce some components of your program in Visual Basic, some in C++, etc., and they should work together.
Both Java and .NET also offer features to “manage” the code in two important respects: they provide garbage collection for memory management, and security features to ensure that a program written by someone else (whom you may not trust very much) is safe to run on your computer.
In the case of .NET, this byte-code language is called Microsoft Intermediate Language (MSIL). The system that runs MSIL code (by using just-in-time compilation) is called the Common Language Runtime (CLR). It’s called that because it doesn’t matter by that time what language was used to produce the MSIL.
To aid in producing code that can be managed as described above, Microsoft developed the C# programming language, which is quite a bit like Java. It seems that the original plan was to use Java for that purpose, but for technical and legal reasons, that didn’t work out.
Microsoft also wrote the Framework Class Library (FCL) that provides thousands of classes and methods that make it possible to write .NET programs.
That still doesn’t quite complete the picture, because we haven’t provided a way for programs to call other programs over the Internet. For that we need a protocol for passing function calls and data over a network. Microsoft’s answer to this need is called SOAP: Simple Object Access Protocol. This protocol specifies how to formulate such data in XML (Extended Hypertext Markup Language) and send it over the web via the HTTP protocol that is already used for web pages.
Review of the parts of .NET and various acronyms:
CLR Common Language Runtime. The system that runs bytecodes, by compiling it “just in time” to executable code.
FCL Framework Class Library. A collection of classes to use in writing .NET programs. The CLR and the FCL are the two main components of the .NET framework.
MSIL Microsoft Intermediate Language. The bytecode produced by .NET compilers.
C# Programming language similar to Java used to produce CLR code (but other languages can also be used to produce CLR code)
HTML Hypertext Markup Language—used for web pages.
XML Extended (hypertext) markup language; XML “document type definitions” can be used to specify how to encode certain kinds of data in HTML.
SOAP Simplified Object Access Protocol. Enables programs to call each other over the Internet by passing data in XML form.
JIT Just In Time. A JIT compiler is needed on the target machine to convert CLR code to machine language at run time.

Web Service. (For some reason no acronym is used! Are we slipping, people? Why did we miss the chance to use WS?) This is a program meant to be used over the Internet by other programs. Example: Google provides a web service so that your program can access Google’s search facilities. That’s the way the Google toolbar (that you can add to your browser) works.



An Example of XML


For those with no prior knowledge of XML, let’s make the matter a little more concrete (I took this example from an article by Charles Wiltgen)




Charles

Wiltgen


This might be used by a web service that would return an author when sent an ISBN number (an ISBN number is a unique number assigned to a book).

Future Vision

These technologies are designed to underpin a world in which some people (or companies, more likely) provide web services that are used (“consumed”) by other people (or companies). As first examples, a company might have internal web services for sales data or billing. Microsoft has an internal web service for travel reimbursement.


Business to business web services should provide a lucrative market. There is, Microsoft hopes, a potential to change the way companies conduct business with their customers and with their suppliers, making every aspect of the economy more efficient. Some of you students may be smart enough to figure out how to ride this wave to riches.

The Framework Class Library (FCL)

The FCL offers another way to produce Windows programs, besides the MFC approach that we have used so far in this course. You still have messages, and you still write handlers for those messages. But now, you call the messages “events” instead, and you write the handlers in C#. Students whose C++ background is weak and whose Java background is strong may find this easier.


One should understand, however, that FCL is not just a different “wrapper” of the Win32 API. It is not a replacement for MFC in that sense. The FCL produces MSIL code and these programs will run on any platform that supports .NET, which includes Linux and FreeBSD. (However, I haven’t tried this—it may be true only in theory.)
Visual Studio offers a single environment in which one can mix components built in different languages. One can, for example, implement a component in Visual Basic that defines a class X, and then implement another component in C# that defines a class Y derived from X. Before .NET, one could make DLLs or ActiveX controls, but the CLR offers a closer integration of different languages, and is simpler to use.
Summary
Here’s Jeff Richter’s list of features of .NET, from his book Applied Microsoft .NET Programming:


  • consistent programming model. (Replaces DLLS and COM)

  • simplified programming model (Goodbye to IDL and the registry)

  • Run once, run always (Goodbye to “DLL Hell”). [Yes, but this implies keeping many versions of the FCL on your machine.]

  • Simplified deployment [Goodbye to the registry for installation and uninstallation]

  • Wide platform reach [You can run on any machine that can run CLR]

  • Programming language integration

  • Simplified code re-use (a market in components)

  • garbage collection

  • type-safe verification

  • rich debugging support

  • consistent method failure paradigm (exception throwing)

  • code access security

  • interoperability with pre-existing code



Building Applications with FCL and Visual Studio
We can build the following types of applications:


  • Windows Forms. Windows applications similar to what we can do with MFC.

  • Web Forms. Essentially these are Active Server Pages. This is the subject of a course in Server Side Web Programming, and will not be covered in this course.

  • XML Web Services. This is the main point of .NET.

  • Console applications. Applications without a graphical user interface.

  • Windows services. Not covered in this course.

  • Components. These modules define classes that expose methods for use in applications of the above types.

In this course, we will build a Windows Form application, a web service, and a component.



An Example Program
Let’s start with a console application so we can realize that .NET does not necessarily involve a graphical user interface. This will be your

first C# program. You can do this without Visual Studio. Just put the following code in file hello.cs:


public class Startup

{

public static void Main()



{

System.Console.WriteLine(”Hello World!”);

}

}
You can, in principle, compile this code from the command line with the command


c:\> csc /t:exe hello.cs
but first you must set the path so that the compiler csc will be found. In practice, it’s easier to use Visual Studio. Choose

New| Project| C# Application | Console Application.
Replace (all of ) the sample code it gives you with the code above. (Or, choose Empty Project instead of Console Application and then Project |Insert Existing Item to add hello.cs).
When you run this within Visual Studio, as with any console application, if you want to see the output for more than a fraction of a second you need to put a break point on the closing brace. (Use F9 to set a breakpoint.)
The program illustrates that C# has namespaces like Java; System is such a namespace, and the method called is provided by the FCL.

A Windows Form Application
Now let’s create a program that does have a graphical user interface. We’ll build a simple Calculator application. (A calculator is a very standard example of a Windows program, so this is not an original example by any means. I have seen it done in MFC by Dr. Pearce years ago and I first saw it done in C# by Joe Hummel.)
Create a new project, choose C# as the language and choose Windows Application as the project type.

This application seems to be essentially the same as what you get when you choose MFC Application | Dialog-based application. That is, the main window is a dialog onto which you can drag and drop controls (edit boxes, list boxes, etc.) from the Toolbox, and when you build and run the program, you see your dialog but you don’t have a menu.

Drag two edit boxes and a button onto your form:


The button text is set in the property sheet of the button:



I also changed the Name property to AddButton.
Now we need to add a message handler for the command message that is generated when the Add button is pressed. Visual Studio makes this even easier than it was for MFC applications: just double-click the button on your form. That will open a text editor on the relevant code:


Make the code look like this:


private void AddButton_Click(object sender,

System.EventArgs e)

{

int i,j,k;



i = System.Convert.ToInt32( this.textBox1.Text);

j = System.Convert.ToInt32( this.textBox2.Text);

k = i+j;

System.Windows.Forms.MessageBox.Show("Sum = "+k);

}
Build and run your program. Enter two numbers and press Add. It should work correctly. Now enter some text that is not a number and press Add. What happens? An exception is thrown, and not caught. We will learn later how to handle an exception.
For now, notice the following things about the code:


  • The sender parameter is an object representing the Add button.

  • The terminology is event rather than message. In MFC we had messages, except that ActiveX controls fired events. In .NET we no longer have this distinction between different kinds of components.

  • You are using some FCL functions in the System namespace for data conversion and for display of the sum.

  • The second parameter, of type EventArgs, carries the kind of information that would be in wParam and lParam in the Win32 API, or would be in the extra parameters of your message handler in MFC. For example, mouse coordinates if the event were a mouse event.



Code Behind
This is a slogan that emphasizes the idea that controls are objects, and the there is code written to handle the events those objects fire. One thinks of the code as “behind” the object. Double-clicking on the object takes you to the code “behind” the object. Here of course “behind” is used in the metaphorical sense of “what makes it work”.

Form Events
Open the property sheet of your form. You’ll see the familiar lightning bolt for Events as well as an icon for Properties. Under Events there is a long list of events associated with the form:

You can add code for handling these events. To do so you double-click the event name. (This is annoyingly different from what we did with MFC and ActiveX.)
private void Form1_Load(object sender, System.EventArgs e)

{ System.Diagnostics.Debug.WriteLine("Form1 loading...");

this.textBox1.Text = "";

this.textBox2.Clear(); // another way to do it

}

As in MFC, there are classes in FCL corresponding to each kind of control:


System.Windows.Forms.Label

System.Windows.Forms.TextBox

System.Windows.Forms.Button

etc.
Code for creating instances of these classes, corresponding to the controls you have dropped on your form in the form editor, is autogenerated by Visual Studio.


Naming Conventions
.NET programmers are encouraged to use prefixes when setting the name property of a control:
cmdOK for a button labeled OK

lstNames for a list box to hold names



txtFirstName for a text box (edit box) holding a first name
Note: what was a static text box in MFC is now a label. What was an edit box in MFC is now a text box.
Yüklə 130 Kb.

Dostları ilə paylaş:




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©genderi.org 2024
rəhbərliyinə müraciət

    Ana səhifə