Friday, August 15, 2008

Wednesday, March 5, 2008

MWT LAB MANUAL

IT 05 409 MIDDLE WARE TECHNOLOGIES

LAB MANUAL

III-B.Tech.II-Semester (IT)



PREPARED BY
Mrs. Ch. Rajya Lakshmi, Asst. Prof.
Mr. M.S.R. Lakshmi Reddy Asst. Prof.



DEPARTMENT OF INFORMATION TECHNOLOGY

CMR INSTITUTE OF TECHNOLOGY
(Affiliated to JNTU: Kukatpally:: Hyderabad)
(Recognized by A.I.C.T.E.)
KANDLAKOYA :: HYDERABAD- 501401.




INTRODUCTION

Course Objectives :

The Middle Ware Technologies Lab for engineers is a 3 hour training lab course spread at about 39 hours. The Lab co-ordinates two sections of one is RMI programming for 5 no. and other is of C#.NET Programming of 15 no. self- explanative simple practical concepts include training on RMI & .NET frame work architecture and its programming attitudes which includes C#, ASP, VB in .NET technologies along with its collaboration with XML, Java Beans, Servelets, Java Applets technologies like and Introduction to CORBA is also an extension to the university prescribed work for the lab. In developing web concepts, MVC and/or .NET architectures is/are strictly followed on the basis of all SDLC part in Software Engineering especially Domain Engg. and Web Engg., whenever and wherever it is mandatory in corporate training way.
Course goals:
The specific goals of this course are:
To understand and be able to articulate the issues involved in designing, implementing Middle ware Technology supported programming languages.
To appreciate the strengths and tradeoffs between different C/S programming paradigms, such as static or dynamic ones.
To develop a working knowledge of middle ware technologies provided by Java and /or .NET Tech. frameworks.
Required Work
There will be homework assignments of about 20 programmatic/project scripts/memos, most of which will involve programming. Assignments are due at the beginning of its theoretic class on the date specified. Late assignments will receive 75% of full credit if they are handed in within one week of the specified due date. After one week, no credit will be given or else losing of credits is made in practice. There is no specific attendance policy for the course, although it is expected that absences will leave the student unprepared for tests and assignments. Tests will not be rescheduled except in extreme circumstances. However, the lowest quiz grade will be dropped. Grades will be determined as follows:
Day – to- Day evaluation Marks
15 marks
Internal practical Examination
10 marks
Final Exam (University / External End Exam)
50 marks

At the minimum, traditional grading cutoffs will apply. That is, 90% is guaranteed an A, 87% is guaranteed a B+, etc. Depending on class performance, some shifting of grades (in an upward direction only) may occur as final letter grades are assigned.



LIST OF CONCEPTS UNDER TAKEN IN THE MIDDLE WARE TECHNOLOGIES LAB


Sl. No.
Name of the Program / Project concept
Record Code
Lab Code

.NET Programming


1
How to work with windows applications using C#
MWT-.NET-08
MT-.NET
2
Steps to testing and debugging a windows forms application - how to a project
MWT-.NET-09
MT-.NET
3
Working with delegates in C#
MWT-.NET-10
MT-.NET
4
Creating windows service with C#
MWT-.NET-11
MT-.NET
5
Demonstrate read and write images into sql server database with C#
MWT-.NET-12
MT-.NET
6
To create and install a simple windows screensaver
MWT-.NET-13
MT-.NET
7
Partitioning an application into multiple assemblies with C#
MWT-.NET-14
MT-.NET
8
Example of sample data stored in an xml file using c#
MWT-.NET-15
MT-.NET
9
Example of select, insert, change, and delete rows in a database in ado.net using C#
MWT-.NET-16
MT-.NET
10
A Sample web form Sending Mail through SMTP MAIL and C#.
MWT-.NET-17
MT-.NET
11
Performing string manulation with string builder and string classes and C#
MWT-.NET-18
MT-.NET
12
Error Handling and Files
MWT-.NET-19
MT-.NET
13
Web servies security with c#
MWT-.NET-20
MT-.NET
14
Reading and writing xml documents with xml text reader and xml textwriter class and c#
MWT-.NET-21
MT-.NET









.NET PROGRAMMING

INTRODUCTION


WHAT IS .NET?
An open languageplatform for enterprise and web development, a frame work, is not a language.It is platform independent.

Net main objectives:
1. .NET is introduced to support platform independent concepts
2. Language interoperability
3. It supports pure OOP’S concepts
4. It suppotrs network concepts.

.Net supports 10+1 languages as of now but microsoft is planning to introduce more than 23 languages in the frame work
1. C#.net 2. VB.net
3. J#.net 4. COBOL.net
5. VBS.net 6. JScript.net
7. PHP.net 8. JSP.net
9. VC++.net 10. C++.net 11. Perl.net
As .NET application logic can be developed by using any .net frame work compatible language, hence .net is called as language independent.
.NET frame work:


What is CLR?
CLR is standard run time execution engine for managed code
CLR is software which is available in many versions like windows versions, Linux versions,etc.
CLR will be installed in C:\WIN_NT\SYSTEM32 folder
The main file name of CLR is MSCOREE.DLL file



How To Work with Windows Applications USING C#
If you have worked with Visual Basic 6.0 or Visual C++ 6.0, you may be aware of the various Graphical User Interface (GUI) elements with which you worked. These elements include buttons, text boxes, check boxes, radio buttons and many more. In fact there are dozens of other controls which are used, along with various Windows-based applications. Windows-based applications are called WinForms for short. With WinForms, you can develop standalone applications. This means that you can run those applications only under a Windows platform and with the .NET Framework. The end user should either install .NET Framework or .NET redistributable framework in order to work with Windows-based applications. If you want to develop ASP.NET applications, you should use WebForm controls.
The System.Windows.Forms namespace provides all necessary classes and methods for developing powerful GUI applications. It is this namespace which provides access to WinForm controls and their associated methods and properties. If you are using a plain text editor instead of Visual Studio .NET, you have to know about the various properties and their corresponding values. But if you have Visual Studio .NET, the properties for each of the controls can be modified from the properties window, and the appropriate coding will be automatically done in the background. The compilation and execution stages are same as any other C# application. The only difference is that the output can be viewed through a Form. The source code will become lengthy as you develop complex application with WinForms. The .NET Framework supplies more than 60 controls for developing Windows applications. Even though all these controls are not used in a single project, they can be suitably used for various purposes. For example, if you are developing a data entry project, you can make use of TextBoxes and Validation Controls. If you are working on a billing project, you can use Buttons, DataGrid and CheckBoxes. The usage of these controls depends upon each project's requirements.
If you have Visual Studio .NET, you can view the names of all these controls from the ToolBox. Just place your mouse pointer over the ToolBox section on the left hand side and the Visual Studio .NET automatically displays all the controls. As you can see, these controls are divided into tabs. For instance, the controls used for developing database applications are located in a tab titled "Data." In the same way, reusable and user created controls are placed in a tab titled "Components." The different types of controls used for building a WinForm application is given in Figure
The explanation of the important controls shown above is here in this article / upcoming articles. You can learn about rest of the controls which are not discussed in this series with the help of the MSDN library or the documentation which came with the .NET Framework SDK.
Working with Windows Applications - My first WinForm application
In this section, you will learn how to develop a classic "HelloWorld" Windows application. Enter the code given in listing 6.1 using Notepad:
Listing 6.1
HelloWorldWin1.cs
001: // HelloWorldWin1.cs
002: // -----------------
003: using System;
004: using System.Windows.Forms;
005:
006: public class HelloWorldWin1:Form
007: {
008:
009: public HelloWorldWin1()
010: {
011: // Add your additional code(s) here
012: }
013:
014: public static void Main()
015: {
016: Application.Run(new HelloWorldWin1());
017: }
018: }
Save the file with the name HelloWorldWin1.cs and compile the program as shown below.
Compilation
csc HelloWorldWin1.cs
Execution
HelloWorldWin1
Output

2. STEPS TO Testing and Debugging a Windows Forms Application run a project IN C# run a project by clicking the Start Debugging button in the Standard toolbar, selecting the Start Debugging command from the Debug menu, or pressing the F5 key. This builds the project if it hasn’t been built already and causes the project’s form to be displayed.When you close this form, the application ends. Then, you’re returned to Visual Studio where you can continue working on your program.
You can also build a project without running it as described in this figure. In most cases, though, you’ll run the project so you can test and debug it.
If build errors are detected when you run a project, the errors are displayed in the Error List window, and you can use this window to identify and correct the errors. If it isn’t already displayed, you can display this window by clicking on the Error List tab that’s usually displayed at the bottom of the window. When you do that, you should realize that the errors will still be listed in the Error List window and highlighted in the Code Editor even after you’ve corrected them. The errors aren’t cleared until you build the project again.
Description
To run a project, click the Start Debugging button in the Standard toolbar, select the Debug->Start Debugging menu command, or press the F5 key. This causes Visual Studio to build the project and create an assembly. Then, assuming that there are no build errors, the assembly is run so the project’s form is displayed as shown above.
If syntax errors are detected when a project is built, they’re listed in the Error List window and the project does not run.
To locate the statement that contains the error, you can double-click on the error description in the Error List window. After you’ve corrected all the errors, run the project again to rebuild it and clear the errors.
You can build a project without running it by selecting the Build->Build Solution command.
When you build a project for the first time, all of the components of the project are built. After that, only the components that have changed are rebuilt. To rebuild all components whether or not they’ve changed, use the Build->Rebuild Solution command.

How to test a project When you test a project, you run it and make sure the application works correctly. As you test your project, you should try every possible combination of input data and user actions to be certain that the project works correctly in every case.
To start, you should test the user interface. Make sure that each control is sized and positioned properly, that there are no spelling errors in any of the controls or in the form’s title bar, and that the navigation features such as the tab order and access keys work properly.
Next, subject your application to a carefully thought-out sequence of valid test data. Make sure you test every combination of data that the project will handle. If, for example, the project calculates the discount at different values based on the value of the subtotal, use subtotals that fall within each range.
Finally, test the program to make sure that it properly handles invalid data entered by users. For example, type text information into text boxes that expect numeric data. Leave fields blank. Use negative numbers where they shouldn’t be allowed. Remember that the goal of testing is to find all of the problems.
As you test your projects, you’ll eventually encounter runtime errors. These errors, also known as exceptions, occur when C# encounters a problem that prevents a statement from being executed. If, for example, a user enters “ABC” into the Subtotal text box on the Invoice Total form, a runtime error will occur when the program tries to assign that value to a decimal variable.
When a runtime error occurs, Visual Studio breaks into the debugger and displays an Exception Assistant window like the one in this figure. Then, you can use the debugging tools that you’ll be introduced to in the next figure to debug the error.
Runtime errors, though, should only occur when you’re testing a program. Before an application is put into production, it should be coded and tested so all runtime errors are caught by the application and appropriate messages are displayed to the user.
How to test a project
Test the user interface. Visually check all the controls to make sure they are displayed properly with the correct text. Use the Tab key to make sure the tab order is set correctly, verify that the access keys work right, and make sure that the Enter and Esc keys work properly.
Test valid input data. For example, enter data that you would expect a user to enter.
Test invalid data or unexpected user actions. For example, leave required fields blank, enter text data into numeric input fields, and use negative numbers where they are not appropriate. Try everything you can think of to make the program fail.
Description
To test a project, you run the project to make sure it works properly no matter what combinations of valid or invalid data you enter or what sequence of controls you use.
If a statement in your application can’t be executed, a runtime error, or exception, occurs. Then, if the exception isn’t handled by your application, the statement that caused the exception is highlighted and an Exception Assistant window like the one above is displayed. At that point, you need to debug the application as explained in the next figure.
How to debug runtime errors When a runtime error occurs, Visual Studio enters break mode. In that mode, Visual Studio displays the Code Editor and highlights the statement that couldn’t be executed, displays the Debug toolbar, and displays an Exception Assistant dialog box like the one shown in figure 3-15. This is designed to help you find the cause of the exception (the bug), and to debug the application by preventing the exception from occurring again or by handling the exception. For example, you can often handle an exception by displaying an appropriate message to the user. This message may give the user one or more options for dealing with the exception.
Often, you can figure out what caused the problem just by knowing what statement couldn’t be executed, by reading the message displayed by the Exception Assistant, or by reading the troubleshooting tips displayed by the Exception Assistant. But sometimes, it helps to find out what the current values in some of the variables or properties in the program are. To do that, you can place the mouse pointer over a variable or property in the code so a data tip is displayed. This tip displays the current value of the variable or property.
For example, if the current value of the Text property of the txtSubtotal control is “ABC”, the data tip will clearly show that the Text property does not contain numeric data. However, the variable named subtotal requires numeric data. As a result, you know that the highlighted statement can’t be executed because the user didn’t enter numeric data in the Subtotal text box.
Once you find the cause of a bug, you can correct it. But first, you must exit from break mode. To do that, you can click the Stop Debugging button in the Debug toolbar. Then, you can correct the problem in the Code Editor and test the application again.
For now, don’t worry if you don’t know how to correct the problem in this example. Instead, you can assume that the user will enter valid data. In chapter 7, though, you’ll learn how to catch exceptions and validate all user entries for an application because that’s what a professional application has to do.
Description
When an application encounters a runtime error, you need to fix the error. This is commonly referred to as debugging, and the error is commonly referred to as a bug.
When an application encounters a runtime error, it enters break mode. In break mode, the Debug toolbar is displayed along with other windows that provide debugging features.
When an application displays the Exception Assistant window, you can read a description of the error. This should give you an idea of what the error might be. You can also click on the links in the Troubleshooting Tips list to display more information in a Help window. You’ll learn more about debugging and the Exception Assistant window in chapter 11.
To display a data tip for a property or variable, move the mouse pointer over it in the C# code. Then, its value is displayed in the data tip.
To exit break mode and end the application, click the Stop Debugging button in the Debug toolbar or press Shift+F5. Then, you can attempt to fix the error, and you can run the application again when you’re done fixing the error.
Copy and open the Invoice Total application
Use the Windows Explorer to copy the Invoice Total project that you created for chapter 2 from the C:\C# 2005\Chapter 02 directory to the C:\C# 2005\Chapter 03 directory.
Open the Invoice Total solution (InvoiceTotal.sln) that’s now in the C:\C# 2005\Chapter 03\InvoiceTotal directory. Add code to the form and correct syntax errors
Display the Invoice Total form in the Form Designer, and double-click on the Calculate button to open the Code Editor and generate the method declaration for the Click event of this object. Then, enter the code for this method as shown in figure 3-5. As you enter the code, be sure to take advantage of all of the Visual Studio features for coding including snippets.
Return to the Form Designer, and double-click the Exit button to generate the method declaration for the Click event of this object. Enter the statement shown in figure 3-5 for this event handler.
Open the Error List window as described in figure 3-6. If any syntax errors are listed in this window, double-click on each error to move to the error in the Code Editor. Then, correct the error. Test the application
Press F5 to build and run the project. If you corrected all the syntax errors in step 5, the build should succeed and the Invoice Total form should appear. If not, you’ll need to correct the errors and press F5 again.
Enter a valid numeric value in the first text box and click the Calculate button or press the Enter key to activate this button. Assuming that the calculation works, click the Exit button or press the Esc key to end the application. If either of these methods doesn’t work right, of course, you need to debug the problems and test the application again. Enter invalid data and display data tips in break mode
Start the application again. This time, enter “xx” for the subtotal. Then, click the Calculate button. This will cause Visual Studio to enter break mode and display the Exception Assistant as shown in figure 3-15.
Note the highlighted statement and read the message that’s displayed in the Exception Assistant. Then, move the mouse pointer over the variable and property in this statement to display their data tips. This shows that the code for this application needs to be enhanced so it checks for invalid data. You’ll learn how to do that in chapter 7. For now, though, click the Stop Debugging button in the Debug toolbar to end the application. Create a syntax error and see how it affects the IDE
When you return to the Code Editor, hide the Error List window by clicking on its Auto Hide button. Next, change the name of the Subtotal text box from txtSubtotal to txtSubTotal. This creates an error since the capitalization doesn’t match the capitalization used by the Name property of the text box.
Try to run the application, and click No when Visual Studio tells you the build had errors and asks whether you want to continue with the last successful build. Then, double-click on the error in the Error List, correct the error, and run the application again to make sure the problem is fixed. Use refactoring
Change the name of the subtotal variable from subtotal to invoiceSubtotal. When you do a bar will appear under the last letter of the variable. Point at this bar to display a drop-down arrow. Then, click on this arrow and select the Rename command. This should rename the subtotal variable throughout the form, but run the form to make sure it’s working correctly. Generate and delete an event handler
Display the Form Designer for the Invoice Total form and double-click a blank area on the form. This should generate an event handler for the Load event of the form.
Delete the event handler for the Load event of the form. Then, run the application. When you do, you’ll get a build error that indicates that the form does not contain a definition for this event handler.
Double-click on the error. This opens the Designer.cs file for the form and jumps to the statement that wires the event handler. Delete this statement to correct the error.
If you’re curious, review the generated code that’s stored in the Designer.cs file for this simple form. Then, click the minus sign to the left of the region named “Windows Form Designer generated code” to collapse this region.
Run the form to make sure it’s working correctly. When you return to the Code Editor, close the Designer.cs file for the form. Experiment with the Help feature
To see how context-sensitive help works, place the insertion point in the Focus method in the last statement of the first event handler and press F1. This should open a Help window that tells you more about this method.
In the left pane, select the Index tab to display the Index window. Type “focus” into the Look For box in this window to see the entries that are listed under this topic. Next, if Visual C# (or Visual C# Express Edition) isn’t selected in the Filter By drop-down list, select it to show just the topics for C#. Then, click on one or more topics to display them.
Continue experimenting with the Index, Contents, Help Favorites, and Search features to see how they work, and try using some of the buttons in the Web toolbar to see how they work. Then, close the Help window. Exit from Visual Studio
Click the Close button for the Visual Studio window to exit from this application. If you did everything and got your application to work right, you’ve come a long way!










3. WORKING WITH Delegates in C#
Introduction:
This article will deal with Event and delegates in C#. C# Open a new door by including the feature of Event Driven programming such as Events and Delegates. This article is part of the series that helps in understanding Events and Delegates.Events are the means by which Windows Application receive notification. In a Windows application a lot of Events are occurring at a particular instant for e.g. Mouse Move, Mouse out, Mouse Click etc. Delegates are pointer to the function and are type-safe. This Article will cover the Single delegate, Multi-cast delegates and Event Driven programming using C#. The first part of this article will focus delegates and its types and the remaining part is on Events.
Delegates:
Another very interesting feature in C# is delegates. Delegates are best complemented as new type of Object in C#. They are also represented as pointer to functions. Technically delegate is a reference type used to encapsulate a method with a specific signature and return type. Since in this article delegate discussion is event centric. If we consider a real world scenario then delegates can be understood as any delegate representing a country a group of people representing a company etc. This same definition can be mapped to C# as delegate act as an intermediary between event source and destination. The DotNetFrameWork has a Name Space System.Delagate. We have two flavors of delegate in C#.
 Single Delegate
 Multi-cast Delegate
Single Delegates:
A delegate is called a single delegate that derives from the System.Delegate class contains an invocation list with one method. Now we will look at how the single-cast delegates are declared. In single-cast delegates, the delegate can point to both static and non-static method if both have the same signature as the delegate. Look at the code below how to declare a single-cast delegate.
public delegate void Myfunction(string,System.Int32)
The above code shows a simple delegate which will point to a method with no return type and taking two arguments as parameters. Now we see delegate that return a value.
public delegate bool MyFunctionOne();
Consider a simple example
using System;
namespace ConsoleApplication
{
///
/// Summary description for Name.
///

public class Name
{
public Name()
{
//
// TODO: Add constructor logic here
//
}

public string Compare(string NameOne, string NameTwo)
{
System.Int32 result=NameOne.CompareTo(NameTwo);

if(result==0)
{
return NameOne;
}
else
{
Console.WriteLine(NameTwo +""+ NameTwo);
return NameTwo+" "+NameOne;
}
}
}
}


Description of the Above Code:
The above example doesn't show the true usage of delegates but I think we are getting the idea what we want to understand. Above is a simple program which compares two strings. If the strings are equal then only one name is returned otherwise both the names are returned if the condition executes to false. Now first the main method is invoked which is situated in DelegateExample Class. In this class we have also declared our delegate.
public delegate string CompareNames(string NameOne,string NameTwo);
It accepts two arguments of type string and also returns a string. In the main method we create the instance of Name class and then we create the instance of our delegate passing the name of our method in it as its argument so that it points to compare method now. Then we just call our delegates by passing the arguments. Which in return call the Compare method and return the string.



Multi-cast Delegates:
A delegate is called Multi-cast Delegate that derives from the System.MulticastDelegate contains an invocation list with multiple methods. At times it is desirable to call two methods through a single delegate. This can be achieved through Single-cast Delegate but it is different from having a collection, each of which invokes a single method.In Multi-casting you create a single delegate that will invoke multiple encapsulated methods. The return type of all the delegates should be same. Now the question why are we using Multi-cast delegates when Single-cast delegates are enough. Well the answer to this question is what if you want to call three methods when a button is clicked. The Multi-cast delegates are used with events where multiple call to different methods are required. System.MulticastDelegate contains two methods Combine and Remove. The Combine is a static method of class System.MulticastDelegate and is used to Combine the delegates and the remove method is used to remove the delegate from the list. For user convenience we have += operator overloaded for delegate Combine method and -= operator overloaded for Remove method Multi-cast delegates are similar to Single-cast delegates for e.g.
public delegate void MulticastDelegate();
Multi-cast delegate can have arguments and can return value as well. All the Methods pointed by delegates should return the similar value as the delegate return type.
public delegate string MultiCastOne(string Name);

Consider a simple example:
using System;

namespace Multi_castDelegate
{
///
/// Summary description for Class1.
///

class MyClassDelegate
{
///
/// The main entry point for the application.
///


public delegate string StringDelegate(string s);
}
}




Below is the class that defines the static methods having same signature as delegate.
using System;

namespace Multi_castDelegate
{
///
/// Summary description for MyImplementingClass.
///

public class MyClass
{
public MyClass()
{

}

public static string WriteString(string s)
{
Console.WriteLine("Writing string");
return "null";
}

public static string logString(string s)
{
Console.WriteLine("loging string");
return "null";
}

public static string TransmitString(string s)
{
Console.WriteLine("Transmitting string");
return "null";
}
}
}
The Main class:
using System;
using System.Threading;
namespace Multi_castDelegate
{
///
/// Summary description for Test.
///

public class Test
{
public static void Main()
{
MyClassDelegate.StringDelegate
Writer,Logger,Transmitter;
MyClassDelegate.StringDelegate myDelegate;
Writer=new MyClassDelegate.StringDelegate(MyClass.WriteString);

/// calling Writer
Writer("hello i am Writer just acting like Single cast");
Logger=new MyClassDelegate.StringDelegate(MyClass.logString);

///calling Logger
Logger("hello i am Logger just acting like Single-cast");
Transmitter=new MyClassDelegate.StringDelegate(MyClass.TransmitString);
///calling Transmitter
Transmitter("hello i am Transmitter just acting like Single-cast");
///here mydelegate used the Combine method of System.MulticastDelegate
///and the delegates combine
myDelegate=(MyClassDelegate.StringDelegate)
System.Delegate.Combine(Writer,Logger);
myDelegate("used Combine");
///here Transmitter is also added using the overloaded form of Combine
myDelegate+=Transmitter;
myDelegate("Using Overloaded Form");
///now using the Remove method
myDelegate=(MyClassDelegate.StringDelegate)
System.Delegate.Remove(myDelegate,Writer);
myDelegate("Without Writer");
///overloaded Remove
myDelegate-=Transmitter;
myDelegate("Without Transmitter");
System.Threading.Thread.Sleep(2300);
}
}
}

Description of the Above Code:
The above program contains three classes, MyClassDelegate contains the delegate.
public delegate string StringDelegate(string s);
The class MyClass Contains the static methods that contains the static methods that have a similar signature as the delegate StringDelegate. The third class is the Test Class which shows how to combine the delegates and how to remove the delegate
4. Creating windows service with c#
Introduction
As a matter of fact Microsoft Windows services, formerly known as NT services enable you to create long-running executable applications that run in its own Windows session, which then has the ability to start automatically when the computer boots and also can be manually paused, stopped or even restarted.
This makes services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer. You can also run services in the security context of a specific user account that is different from the logged-on user or the default computer account.
Windows services don’t have any interface to the user, so it can not be debugged like any regular application, but it’s debugged as a process. .NET has a very nice tool that enables processes debugging while it’s in the run status, by easily pressing Ctrl + Alt + P shortcut.
Background
I’ve searched well so many sites about a code that I can with the help of it, build a simple Windows service, but I found a lot of code on how to manage the current Windows services of the system and that’s through the ServiceController class.
After searching the MSDN, I’ve found some nice code that helped me to create this simple Windows service. Hope it can help as a basic architecture for and usage of such a Windows service.
Using the code
At first you should simply open VS.NET and then at the File menu click on New, Project. From the New Project Dialog Box, choose the Windows service template project and name it MyNewService like shown below:

The project template automatically adds a component class that is called Service1 by default and inherits from System.ServiceProcess.ServiceBase.
Click the designer. Then, in the Properties window, set the ServiceName property for Service1 to MyNewService.
Set the Name property to MyNewService. Set the AutoLog property to true.
In the code editor, edit the Main method to create an instance of MyNewService. When you renamed the service in step 3, the class name was not modified in the Main method. To access the Main method in VC#, expand the Component Designer generated code region.static void Main(){ System.ServiceProcess.ServiceBase[] ServicesToRun; //Change the following line to match. ServicesToRun = new System.ServiceProcess.ServiceBase[] { new MyNewService() }; System.ServiceProcess.ServiceBase.Run(ServicesToRun); }
In the next section, you will add a custom event log to your Windows service. Event logs are not associated in any way with Windows services. Here the EventLog component is used as an example of the type of components you could add to a Windows service.
To add custom event log functionality to your service:
In the Solution Explorer, right-click Service1.vb or Service1.cs and select View Designer.
From the Components tab of the Toolbox, drag an EventLog component to the designer.
In the Solution Explorer, right-click Service1.vb or Service1.cs and select View Code.
Edit the constructor to define a custom event log.
To access the constructor in Visual C#, expand the Component Designer generated code region.public MyNewService(){ InitializeComponent() if(!System.Diagnostics.EventLog.SourceExists("DoDyLogSourse")) System.Diagnostics.EventLog.CreateEventSource("DoDyLogSourse", "DoDyLog"); eventLog1.Source = "DoDyLogSourse"; // the event log source by which //the application is registered on the computer eventLog1.Log = "DoDyLog";}
To define what happens when the service starts, in the code editor, locate the OnStart method that was automatically overridden when you created the project, and write code to determine what occurs when the service begins running:protected override void OnStart(string[] args){ eventLog1.WriteEntry("my service started"); }
The OnStart method must return to the operating system once the service's operation has begun. It must not loop forever or block. To set up a simple polling mechanism, you can use the System.Timers.Timer component. In the OnStart method, you would set parameters on the component, and then you would set the Timer.Enabled property to true. The timer would then raise events in your code periodically, at which time your service could do its monitoring.
To define what happens when the service is stopped, in the code editor, locate the OnStop procedure that was automatically overridden when you created the project, and write code to determine what occurs when the service is stopped:protected override void OnStop(){ eventLog1.WriteEntry("my service stoped");}
You can also override the OnPause, OnContinue, and OnShutdown methods to define further processing for your component. For the method you want to handle, override the appropriate method and define what you want to occur. The following code shows what it looks like if you override the OnContinue method:protected override void OnContinue(){ eventLog1.WriteEntry("my service is continuing in working");}
Some custom actions need to occur when installing a Windows service, which can be done by the Installer class. Visual Studio can create these installers specifically for a Windows service and add them to your project. To create the installers for your service.
Return to design view for Service1.
Click the background of the designer to select the service itself, rather than any of its contents.
In the Properties window, click the Add Installer link in the gray area beneath the list of properties. By default, a component class containing two installers is added to your project. The component is named ProjectInstaller, and the installers it contains are the installer for your service and the installer for the service's associated process.
Access design view for ProjectInstaller, and click ServiceInstaller1.
In the Properties window, set the ServiceName property to MyNewService.
Set the StartType property to Automatic.
Tip
To avoid being asked about the system username and password you must change the Account for the serviceProcessInstaller to LocalSystem. This is done by opening the ProjectInstaller design and then selecting the serviceProcessInstaller, press F4 and then change the Account property to LocalSystem. Or you can manually do that by creating a class that inherits from System.Configuration.Install.Installer like this:
Collapse[RunInstaller(true)]public class ProjectInstaller : System.Configuration.Install.Installer private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;private System.ServiceProcess.ServiceInstaller serviceInstaller1; /// /// Required designer variable. /// private System.ComponentModel.Container components = null;public ProjectInstaller() // This call is required by the Designer. InitializeComponent(); // TODO: Add any initialization after the InitComponent call } private void InitializeComponent() { this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); // serviceProcessInstaller1 this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem; this.serviceProcessInstaller1.Password = null; this.serviceProcessInstaller1.Username = null; // serviceInstaller1 this.serviceInstaller1.ServiceName = "MyNewService"; this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic; // // ProjectInstaller // this.Installers.AddRange (new System.Configuration.Install.Installer[] { this.serviceInstaller1, this.serviceInstaller1}); }}
To build your service project
In Solution Explorer, right-click your project and select Properties from the shortcut menu. The project's Property Pages dialog box appears.
In the left pane, select the General tab in the Common Properties folder.
From the Startup object list, choose MyNewService. Click OK.
Press Ctrl+Shift+B to build the project.
Now that the project is built, it can be deployed. A setup project will install the compiled project files and run the installers needed to run the Windows service. To create a complete setup project, you will need to add the project output, MyNewService.exe, to the setup project and then add a custom action to have MyNewService.exe installed.
To create a setup project for your service
On the File menu, point to Add Project, and then choose New Project.
In the Project Types pane, select the Setup and Deployment Projects folder.
In the Templates pane, select Setup Project. Name the project MyServiceSetup.
A setup project is added to the solution. Next you will add the output from the Windows service project, MyNewService.exe, to the setup.
To add MyNewService.exe to the setup project
In Solution Explorer, right-click MyServiceSetup, point to Add, then choose Project Output. The Add Project Output Group dialog box appears.
MyNewService is selected in the Project box.
From the list box, select Primary Output, and click OK.
A project item for the primary output of MyNewService is added to the setup project. Now add a custom action to install the MyNewService.exe file.
To add a custom action to the setup project
In Solution Explorer, right-click the setup project, point to View, then choose Custom Actions. The Custom Actions editor appears.
In the Custom Actions editor, right-click the Custom Actions node and choose Add Custom Action. The Select Item in Project dialog box appears.
Double-click the application folder in the list box to open it, select primary output from MyNewService (Active), and click OK. The primary output is added to all four nodes of the custom actions — Install, Commit, Rollback, and Uninstall.
Build the setup project.
To install the Windows Service
Browse to the directory where the setup project was saved, and run the .msi file to install MyNewService.exe.
To start and stop your service
Open the Services Control Manager by doing one of the following:
In Windows 2000 Professional, right-click My Computer on the desktop, then click Manage. In the Computer Management console, expand the Services and Applications node.
- Or -
In Windows 2000 Server, click Start, point to Programs, click Administrative Tools, and then click Services.
Note: In Windows NT version 4.0, you can open this dialog box from Control Panel.
You should now see MyNewService listed in the Services section of the window.
Select your service in the list, right-click it, and then click Start.
Right-click the service, and then click Stop.
To verify the event log output of your service
Open Server Explorer and access the Event Logs node. For more information, see Working with Event Logs in Server Explorer.
Note: The Servers node of Server Explorer is not available in the Standard Edition of Visual Basic and Visual C# .NET.
To uninstall your service
On the Start menu, open Control Panel and click Add/Remove Programs, and then locate your service and click Uninstall.
You can also uninstall the program by right-clicking the program icon for the .msi file and selecting Uninstall.
5. DEMONSTRATE READ AND WRITE IMAGES INTO SQL SERVERDATABASE
WITH C#
General:
The following code will help you to create a table called "emp" in oracle database with three fields namely id, name, photo. The field photo is a blob field for which you are going to insert an image as the value using the code. The image size may be anything even in GB as the blob field in oracle can store upto 4GB of size.
Code to create a table in oracle database:
public void oracleconnection()
{
try
{
//use your own userid,password and datasorce
connstr="User Id="userid ";Password="password" ;Data Source="datasource ";";
conn=new OracleConnection(connstr);
conn.Open();
OracleCommand cmnd=conn.CreateCommand();
cmnd.CommandText="CREATE TABLE emp(id INTEGER,name VARCHAR2(50),photo BLOB)";
cmnd.ExecuteNonQuery();
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}
Working of the code:
Using the fileopendialog() you can give the path of the .jpg file in your system. This file is then converted as a bitmap image and stored in a picture box as its image. To insert an image into the blob field, you have to use a filestream object. Using filestream you have to read() the imagefile and store it as byte[] array as in C#.Net. Then you have to insert the byte array to the blob field as an Oracle parameter which is of parameter type Blob and its value as the byte[] array specified above, using normal sql query used for insertion.
The same you have to do while retrieving the image. You have to specify the name to store the retrieved image as "image.jpg" (which is stored in the bin folder of your project). For this you have to select all the rows in the table and select the column of teh image ie. The blob field with the datarow and the datacolumn properties where the image is stored as blob in the database. Using the same filestream object write() the entire file upto its length and retrieve the same image in the picture box control.
USING THE CODE:
(1) For inserting the data into the blob field of the database
Note: This should be done after creating the table in oracle database as specified above in this article.
Open a project in C# and name it as oracleblob. Now click add reference and in .Net category select "System.data.Oracleclient.dll". Then in your project add before the namespace using system.data.oracleclient.
Now in the form1 add two textboxes, two labels, three buttons and a picturebox and name them as follows:
textbox:txtid,txtname
label:lblid,lblempname
buttons:btnbrowse,btnsave,btnclose
picturebox:pctimg
Declare these variables as global:
OracleConnection conn;
string connstr;
When the user gives the id and name in the textboxes and update the picturebox's image by specifying the path of image using Browse button, the picture is loaded in the picturebox. When he clicks the save button then these details are inserted as a row in the table. After inserting he can close the application using close button.(see picture of the form form1.jpg).
The code for the browse button is as follows:
This will open a dialogbox wherein you can select the image file's path.
private void btnbrowse_Click(object sender, System.EventArgs e)
{
try
{
FileDialog fldlg=new OpenFileDialog();
//specify your own initial directory
fldlg.InitialDirectory=@":D\";
//this will allow onlt those file extensions to be added
fldlg.Filter="Image File (*.jpg;*.bmp;*.gif)*.jpg;*.bmp;*.gif";
if(fldlg.ShowDialog()==DialogResult.OK)
{
imagename=fldlg.FileName;
Bitmap newimg=new Bitmap(imagename);
pctimg.SizeMode=PictureBoxSizeMode.StretchImage;
pctimg.Image=(Image)newimg;
}
fldlg=null;
}
catch(System.ArgumentException ae)
{
imagename=" ";
MessageBox.Show(ae.Message.ToString());
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
The code for save button is as follows:This code will add the details specified in textboxes namely the id, name and the image in picturebox to a row in the table created inoracle database. This code uses the function Updatedata() which is explained as follows:
private void updatedata()
{
//use filestream object to read the image.
//read to the full length of image to a byte array.
//add this byte as an oracle parameter and insert it into database.
try
{
//proceed only when the image has a valid path
if(imagename!="")
{
FileStream fls;
fls=new FileStream(@imagename,FileMode.Open,FileAccess.Read);
//a byte array to read the image
byte[] blob=new byte[fls.Length];
fls.Read(blob,0,System.Convert.ToInt32(fls.Length));
fls.Close();
//open the database using odp.net and insert the data
connstr="User Id="userid";Password="password";Data Source="datasource";";
conn=new OracleConnection(connstr);
conn.Open();
OracleCommand cmnd;
string query;
query="insert into emp(id,name,photo) values(" + txtid.Text + "," + "'" + txtname.Text + "'," + " :BlobParameter )";
//insert the byte as oracle parameter of type blob
OracleParameter blobParameter = new OracleParameter();
blobParameter.OracleType = OracleType.Blob;
blobParameter.ParameterName = "BlobParameter";
blobParameter.Value = blob;
cmnd=new OracleCommand(query,conn);
cmnd.Parameters.Add(blobParameter);
cmnd.ExecuteNonQuery();
MessageBox.Show("added to blob field");
cmnd.Dispose();
conn.Close();
conn.Dispose();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Code in the save button:
private void btnclose_Click(object sender, System.EventArgs e){this.Close();}
Note: Add a few rows in the table using the above mentioned procedure so that it will be helpful in retreiving the blob field.
(2) For retreiving the image from the blob field of the oracle database
Open a form to the same project and name it as frmread.cs. Then in your project add using system.data.oracleclient.Now in the form1 add one combobox, one label, two buttons and a picturebox and Name them as follows:
combobox:cmbempname (*make its dropdown property as dropdownlist)
label:lblname
buttons:btnshow,btnclose
picturebox:pctimg
When the form loads the name is added in the combobox, the user has to select a name, and when he clicks the show button, the corresponding image in the blob field is retreived and added to the picturebox. See the form in the picture frmread.jpg.
Declare these variables as global in the form:
OracleConnection conn;
OracleDataAdapter empadap;
DataSet dset;
string connstr;
Code for the Show button:
There is a function named connection() which performs the work of adding all the names ito combobox after getting them from the database using oracledataadapter(). This should be used in the form's Load event,so that it helps user to select one of the names which is in the table added using the previous form.
private void Frmread_Load(object sender, System.EventArgs e)
{
Connection();
}
private void Connection()
{
//connect to the database and table
//selecting all the columns
//adding the name column alone to the combobox
try
{
connstr="User Id=scott;Password=tiger;Data Source=star;";
conn=new OracleConnection(connstr);
conn.Open();
empadap=new OracleDataAdapter();
empadap.SelectCommand=new OracleCommand("SELECT * FROM emp",conn);
dset=new DataSet("dset");
empadap.Fill(dset);
DataTable dtable;
dtable=dset.Tables[0];
cmbempname.Items.Clear();
foreach(DataRow drow in dtable.Rows)
{
cmbempname.Items.Add(drow[1].ToString());
cmbempname.SelectedIndex=0;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Now the code inside the show button is as follows:
private void btnshow_Click(object sender, System.EventArgs e)
{
DataTable dataTable = dset.Tables[0];
//if there is an already an image in picturebox, then delete it
if(pctimg.Image != null)
{
pctimg.Image.Dispose();
}
//using filestream object write the column as bytes and store it as an image
FileStream FS = new FileStream("image.jpg", FileMode.Create);
foreach(DataRow dataRow in dataTable.Rows)
{
if(dataRow[1].ToString() == cmbempname.SelectedItem.ToString())
{
byte[] blob = (byte[])dataRow[2];
FS.Write(blob,0,blob.Length);
FS.Close();
FS = null;
pctimg.Image = Image.FromFile("image.jpg");
pctimg.SizeMode = PictureBoxSizeMode.StretchImage;
pctimg.Refresh();
}
}
}
Code in the close button:
private void btnclose_Click(object sender, System.EventArgs e)
{
conn.Close();
this.Close();
}
Note: The image is retreived from the blob field and added to the picturebox control and also is stored as "image.jpg" in the bin folder of your application.

6. TO CREATE AND INSTALL A SIMPLE WINDOWS SCREENSAVER
To create and install a simple windows screensaver, similar to the Marquee screensaver; witch is installed on your system with Microsoft Windows. Screensavers are actually executable files, only difference is that they have a scr extension instead of exe. Before we begin, there are a few things to know about Windows screensavers. Screensavers are located in the [SystemFolder]\system32. After a specified period of time the computer is idle (time witch is set trough the Display Properties -> Screen Saver), Windows is making a call to the current screesnsaver, telling him to start. When this happens, the specified screensaver starts executing, until the user presses/moves the mouse and/or types a keyboard key.
Most screensavers have also a configuration dialog, where you can set different options for the screensaver. These options can be saved either in the registry or in a configuration file.
The part where windows start the screensaver looks pretty easy, the hard part is where we must know when the user pressed the Settings button, so that we can display the settings dialog. Here is how it works. When the user presses the settings button, Windows is calling the current screensaver with the parameter ?/c? followed by some numbers.

To start the screensaver, the current screensaver is called, along with the ?/s? parameter.
Let's now start designing our screensaver. As I told you earlier, we will do something simple, similar to the Marquee windows screensaver.
This article is accompanied by a demo screensaver along with the source code, to help you get started! In the following, I will present the parts that are important in the process of creating your own customisable screensaver.
First of all, you will need to have a options dialog, in witch you allow your user to change certain settings for the screensaver. In my example, I allow the changeing of the speed that the text rolls, the background color, the foreground color and the text that is displayed. Here it is:

I keep the settings in an xml file, on the hard drive.Also, you can keep yours in the windows registry, but i recommend the file, because messing with the registry can cause problems.
After you've created the settings dialog, you sould start working on the main form, the screensaver itself. The main form should have the following:
FrameBorderStyle property to None
WindowState property to Maximized
MaximizeBox to False
MinimizeBox to False
TopMost to True
Also, you may need a Timer object to do some redrawing at a specified interval, although it is not necessarely reqiured. Another thing you may need to do is use the SetStyle property to make the form react better when you do extensive drawing on it (like I did in the example code). One other thing that is of major importance. You must give the user a way to close the screensaver, otherwhise it will get stuck looking at it and not be able to do anything. So you must close the program whenever the user presses a key on the keyboard, or clicks/moves the mouse.
Let's take a quick look at my Main method, so you can understand better how to put it all together.
if (args.Length>0)
{
//display the options...
if (args[0].ToLower().Trim().Substring(0, 2) == "/c")
{
frmOptions op = new frmOptions();
op.ShowDialog();
Application.Exit();
}
if (args[0].ToLower().Equals("/s"))
{
Application.Run( new Form1());
}
}
else
Application.Run( new Form1());
If we don't get a parameter when starting the application, we simply run it. But if we'll get one, we check to see what they are. If we have something that starts with '/c', then we will need to display the options. If we get the '/s' parameter, we will need to start the screensaver.
To install the screensaver, you will need do go to the bin/Debug folder of your applications and replace the exe extension with scr. Now copy the application to your windows/system32 folder. You will see that you can select it from the display properties and set it as a screensaver; also you can view the settings and change them.














7. Partitioning an application into multiple assemblies with c#:

Assembly is a collection of classes developing different languages and packed as dll to achieve a task
All dll filees collected as assemblies
Assemblies supports code reusability.It supports language Interoperability
It is a collection of namespaces.Name space is a collection of classes and sub name spaces
It is mainly three types
1.private assemblies 2.shared assemblies 3.public assemblies
Example on assemblies:
//EXAMPLE ON PRIVATE AND PUBLIC ASSEMBLIES//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PA;
using PA.SA;

namespace patest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

}

private void button1_Click(object sender, EventArgs e)
{
PAclass p = new PAclass();
MessageBox.Show(p.p1());
SAclass s = new SAclass();
MessageBox.Show(s.Print());
}
}
}

// EXAMPLE ON SHARED ASSEMBLIES//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace SA
{
public class Test
{
public static DataTable GetData(String tn)
{
String q="select * from "+tn;
SqlConnection cn=new SqlConnection("user id=sa;database=northwnd;server=winserver");

SqlDataAdapter da=new SqlDataAdapter(q,cn);
DataSet ds = new DataSet();
da.Fill(ds,"e");
return ds.Tables["e"];
}

}
}



















8. EXAMPLE OF SAMPLE DATA STORED IN AN XML FILE USING C#
One of the great features introduced by microsoft in the .net technology is the dataset . The dataset is the object corresponding the the traditional ADO recordset . However the dataset has many significant differences
1)The dataSet can hold the results of many SQL queries .
2)You can use the dataset while the connection is closed .
3)You can create a dataset from an XML file .
4)You can write XML directly from a dataset .
While some may say that the recordset can offer some of these features, but sure will not be flexible and powerful as ADO.NET datasets .We will discuss now very nice feature in the dataset to save your database server resources . Most people use the dataset for returning a query result from the database . We will use the dataset now to return multiple result sets that is very helpful when you are filling drop down controls with some thing from lookup tables . Assuming that we have a connection ready to SQL server , using the pubs sample database , you can create a sql dataadapter like that :
sqlDataAdapter1.SelectCommand.CommandText="SELECT * FROM titles;SELECT * FROM authors" ;
you can see that we separate the SQL statment that returns each result set with a semi colon , a space would work but this is more readable .We can then fill a dataset with this code
DataSet ds= new DataSet();
sqlDataAdapter1.Fill( ds ) ;
now we have a dataset with 2 tables if you bind the dataset to a grid you will have the 2 tables availiable to choose from You may want to use the data of each table to bind a user control you can say
listBox1.DisplayMember="title" ;
listBox1.ValueMember="title_id" ;
listBox1.DataSource=ds.Tables[0] ;
as you see the tables collection contain a table for each returned result set , so there is no limit on the number of result sets that you can return from the database just a final note this code will not work with MySQL databases , it doesnt support returning multiple databsets As for oracle , you will have to use reference Cursors to achieve the same functionality .
But what if we do not wish to use a database to keep our data in an application . is there a way for us to load from files ? Yes you can create XML files containing the data you need . DataSets even provide a very easy method for wrting XML files containing the data . if you call
ds.write( filename ) ;
you can save an entire dataset to an XML file . It has 8 overloads , the simplest one just takes a file name to save to . If you then want to read this data again into a dataset you just create a dataset and use the ReadXml method on the file name you wish and its all done . You have a woking dataset that you can bind to controls or use how ever you wish .
9. Example Of select, insert, change, and delete rows in a database IN
ADO.NET Using C#
With the introduction of .NET technology came a new concept in database connectivity called ADO.NET. While similar to traditional Activex Data Objects (or ADO), it is very different mainly because of the underlying architecture. Most programmers and developers entering into the .NET world assume that since they are well-versed in ADO 2.x that ADO.NET is just another flavor of it. Once they get deep into the code of a C# forms-based application they suddenly realize that they need to learn a few new concepts with ADO.NET.
The main difference between ADO.NET and prior versions of ADO is that ADO.NET is a "disconnected" technology when it comes to dealing with databases. What do we mean by a disconnected technology? Basically, all database access operations involve first retrieving the data from the database into the computer's cache and disconnecting from the database. This is automatic with ADO.NET and seamless to the developer. Data is manipulated, viewed, and deleted within the local computer's cache and not while connected to the physical database. When the data in the cache is ready for updating, the connection to the database is reestablished and the data is transmitted and applied.
Why would we want to work in a disconnected technology? It's easy. We don't have to stay connected to the database to work with data in our local memory and this is a tremendous resource saver. Fewer active connections in the database help the database perform better.
In this article, we will go through a small tutorial that addresses the basic operations we would want to do in any forms-based C# applications. We would want to add, delete, view, and change records within a table. Our example uses a Microsoft Access database but can be easily adapted to a MS SQL or Oracle database using the OLE (Object Linking and Embedding) database drivers.
The Example Program
For this tutorial, we will use as an example a basic forms application which accesses one table with two fields. This example uses a Microsoft Access 2000 database however it can be easily adapted to an SQL Server or Oracle environment by merely changing the connection string. Figure 1 shows our graphical user interface (GUI) for the sample application.
Figure 1
The listbox in the middle of the GUI will display existing records in the table PhoneNumbers. The "New" button is used to insert a new record into the table, the "Change" button is used to update a record, and the "Delete" button will delete a row in the table. The "Exit" button will do just that -- quit the application.
Getting Started - The Connection String and the OleDbConnection Object
In any ADO.NET or ADO application, the connection string is what describes the specific connect parameters we need to successfully connect to a database. When an application is developed to run in multiple relational database environments, you typically change the connectionstring.
public static string connectionString = "provider=Microsoft.JET.OLEDB.4.0; + "data source = " + Application.StartupPath + "\\ADONETTutorialDb.mdb";
The database, ADONETTutorialDb.mdb, should be placed in the same directory as this application's .exe file is located in.The OleDataAdapter Object
An object we will discuss in sections to follow is the "DataSet" object which is merely the data table in cache memory -- the results of the query stored in cache. The OleDataAdapter object creates the bridge between the dataset in cache and the actual database table in the database. You basically feed it the connection string which we discussed earlier and the command string that contains the SQL statement to apply. In the next code fragment, we will define the SQL statement to apply when we declare a new OleDbDataAdapter instance:
string commandstring = "select * from PhoneNumbers";dataAdapter = new OleDbDataAdapter(commandstring, connectionString);
The BuildCommands Method
This concept in ADO.NET seems a little tricky at first however you will see the advantages later on. In ADO.NET, a DataAdapter object can have four explicit SQL commands. They are the SelectCommand, InsertCommand, UpdateCommand, and DeleteCommand. This method actually builds the syntax for each command that we will use for operating on the data. However, in addition to the syntax, we can actually define the parameters or variable arguments that will be passed to the commands. This adds a dynamic feature to ADO.NET SQL commands. Remember in ADO, we had to actually build the SQL statement with whatever values of current variables. These were strung together along with the SQL syntax. We no longer have to do this with ADO.NET as now we can define "reusable" SQL commands that are part of the current DataAdapter object.

Here is how the InsertCommand will be setup:
// Declare a reusable insert command with parametersdataAdapter.InsertCommand = connection.CreateCommand();dataAdapter.InsertCommand.CommandText ="insert into PhoneNumbers " +"(Phonenum, Subscriber) " +"values " +"(?, ?)";
dataAdapter.InsertCommand.Parameters.Add("Phonenum", OleDbType.Char, 0, "Phonenum");dataAdapter.InsertCommand.Parameters.Add("Subscriber", OleDbType.Char, 0, "Subscriber");
Notice that we will use the CreateCommand method on the current connection object and assign the text of the SQL insert command. For our tutorial, the PhoneNumbers table only has two columns: Phonenum and Subscriber. When we get to the part where the values go, we simply put "?,?" as a substitution for both column values. Now, how is the value of the column in memory linked to the column in the SQL command? The answer is through the Parameters.Add method that will tell the InsertCommand object that the first parameter will come from the columns "Phonenum" and "Subscriber" in the DataTable (we will discuss the DataTable further).
And now for the Update and Delete commands:
The same concept applies here as well. We are using the Parameters.Add method to create the link between the table in memory and the physical database table. Here is the code for the Update and Delete commands below:
// Declare a reusable update command with parametersdataAdapter.UpdateCommand = connection.CreateCommand();dataAdapter.UpdateCommand.CommandText = "update PhoneNumbers " +"set Subscriber = ? " +"where Phonenum = ? ";dataAdapter.UpdateCommand.Parameters.Add("Subscriber", OleDbType.Char, 0, "Subscriber");dataAdapter.UpdateCommand.Parameters.Add("Phonenum", OleDbType.Char, 0, "Phonenum");
// Declare a reusable delete command with parametersdataAdapter.DeleteCommand = connection.CreateCommand();dataAdapter.DeleteCommand.CommandText ="delete from PhoneNumbers where Phonenum = ?";dataAdapter.DeleteCommand.Parameters.Add("Phonenum", OleDbType.Char, 0, "Phonenum");
The DataSet Class
With ADO.NET, we have a new structure known as the DataSet. The DataSet class can be thought of as an in-cache memory database table filled with data from the physical database and the current select statement. We use the Fill method of the OleDbDataAdapter object to refresh the data in the DataSet. Invoking the Fill method will synchronize the data in the DataSet to match what is in the ADO recordset (database). The next code fragment will fill the data set with the current contents of the PhoneNumbers table in a new DataSet instance named dataSet. Once filled, the Fill_lb method is called to display the current dataset in cache memory in the listbox on the main form.
dataSet = new DataSet();dataSet.CaseSensitive = true;dataAdapter.Fill(dataSet,"PhoneNumbers");Fill_lb();
The Fill_lb Method
The Fill_lb method in the tutorial program will first declare an instance of a DataTable which is one table of relational data residing in memory and is usually used in conjunction with the DataSet object. In our example, we are associating the DataTable object with the dataSet.tables[0] pointer or, in other words, the first table in the dataSet object. Now we have DataTable methods accessible to us. The first step is to open up something like a cursor (but not really a cursor) on the dataTable and read each row and post to the listbox. To do this, we will use a foreach construct to fill each row in the listbox:
dataTable = dataSet.Tables[0];listBox1.Items.Clear();foreach (DataRow dataRow in dataTable.Rows){ LoadBuffers(dataRow); listBox1.Items.Add( Phonenum + "\t\t" + Subscriber);}
Note the LoadBuffers method. Here we pass an individual DataRow object to this method and its purpose is to extract data from the columns in the row and store in the global variable strings Phonenum and Subscriber.
Ready to Process
Once the Fill_lb method is invoked, we are ready to process. You will see a screen as follows:
Figure 2
At this point, the program is ready to handle data-altering events. We will discuss the following events generated by clicking the buttons on this form.
The "New" Event
If you fill in the Phone number and name fields in the form and click the "New" button, a new row will get added. Beware that Phone# is a unique key so don't try to add one already there. What happens is that we add a new row to the DataSet object. However before this, we must build the new row via the DataRow object which we named newrow for this instance. The dataAdapter is the link between the in-cache table and the physical database table therefore the Update method will send the transaction and the AcceptChanges method will actually commit it. Note that for Oracle databases, we found that trailing spaces had to be trimmed from the end of field. It does not seem to be a problem in other database platforms but does not hurt anything if the Trim method is left in.
The "Change" Event
Changing data in the dataset is a little more complex than with inserting and deleting. First, we have to select the row in the listbox and then move that information into an object of DataRow type which in our example is named selectedRow. We apply the changes by invoking the BeginEdit method on the target row. The BeginEdit method marks the beginning of a transaction to apply changes to the row. Once the new values are applied, we issue the EndEdit method on the target row.
// get the selected rowDataRow selectedRow = dataTable.Rows[listBox1.SelectedIndex];
// inform the userApplication.DoEvents();
// Begin an edit transaction on the row.selectedRow.BeginEdit();selectedRow["Subscriber"] = txtSubscriber.Text.Trim();selectedRow.EndEdit();
The next step is to create a new DataSet (dsChanges) that will contain each row that changed in the original DataSet object. Then, with this new DataSet, we will check the HasErrors property to see if there were any changes that produced an error. The remaining code will determine which row has the error and display the key (Phonenum) to the user.
// retrieve each row that changedDataSet dsChanges = dataSet.GetChanges(DataRowState.Modified);
// check for any changed rows with errorsbool okayFlag = true;if (dsChanges.HasErrors) {...}
If all is okay, then we will call the Update method in the dataAdapter object and pass to it the dsChanges object that contains our changes. This will stage the changes for updating to the physical database. The actual update will take place when we invoke the AcceptChanges method on the DataSet object. And of course, we will call the RejectChanges method on the DataSet object if there are errors.
// No errors -- all okayif (okayFlag){ // apply updates to the database dataAdapter.Update(dsChanges,"PhoneNumbers"); // tell the user MessageBox.Show("Updated " + selectedRow["Phonenum"]); Application.DoEvents(); // apply changes and refresh the listbox dataSet.AcceptChanges(); Fill_lb();}else // if any errors then throw out the changes dataSet.RejectChanges();
So let's summarize the steps involved in changing a database row:
1. Apply the changes to the row: BeginEdit -> apply changes -> EndEdit2. Create a new DataSet object with changes via the GetChanges method on the edited DataSet object.3. Check the new dataset with changes for errors -- inform the user of the bad row.4. If everything is okay, then call the Update method on the DataAdapter object and pass the dataset with changes (dsChanges).5. Invoke the DataSet.AcceptChanges method to post the updates to the database. If there are errors, invoke the RejectChanges method to discard any updates.
The "Delete" Event
The very last event we will discuss has to do with the process of deleting a row from the database table. The first step in deleting is to get the selected row from the listbox and place it into a new object of type DataRow (selectedRow in our example). You then will call the Delete method on the selectedRow object to mark the row for deletion. Note that we have only marked the row and not followed through with the actual delete. This does not happen until you apply the dataAdapter.Update method and the dataSet.AcceptChanges method. Of course, if we have any exceptions or errors then the dataSet.RejectChanges method is applied to back out from the delete. The next code fragment shows our delete logic:


// fetch the selected row in the listboxDataRow selectedRow = dataTable.Rows[listBox1.SelectedIndex];string msg = selectedRow["Phonenum"] + " deleted.";
// delete the selected rowselectedRow.Delete();
// apply delete to the databasetry{ dataAdapter.Update(dataSet,"PhoneNumbers"); dataSet.AcceptChanges(); // refresh the listbox after the delete Fill_lb(); // inform the user MessageBox.Show(msg); Application.DoEvents();}catch (OleDbException ex){ dataSet.RejectChanges(); MessageBox.Show(ex.Message);}

Conclusion
The combination of this tutorial document and the sample program should give you enough foundation to create most C# forms applications with an ADO.NET interface. In fact, you can probably take the example tutorial application and expand it to fit your more complex applications. All the basics are in it: select, insert, change, and delete rows in a database. ADO.NET is very different from classic ADO because of the type of technology it uses. It uses a "disconnected" technology in which we connect to the database to retrieve rows based on our select query, disconnect from the database and work with our data. We only connect back to the database when there are modifications, inserts, or deletes to apply to a specific table.








10. A sample webform Sending Mail through SMTP MAIL and C#

Using System.Web.Mail;
//(code for timer1_elapsed event//
{
int hh=DateTime.Now.Hour;
int mm=DateTime.Now.Miniute;
if(hh==20&&mm==40)
{
mailmessage m=new mailmessage();
m.To=teja@yahhoo.com;
m.subject=”just for test”;
m.BodyFormat=MailFormat.html;
m.body=”

cmrit


dear friend

”;
m.Form=”ravi@ptpl”;
SmtpMail.send(m);
}
Open Service1.cs{design)->right click->add installer
ServiceProcessinstaller->properties->account=localsystem
Goto serviceinstaller->properties->servicename=A2
Build the project(build->build solution)
























11. PERFORMING STRING MANIPULATION WITH STRING BUILDER
AND STRING CLASSES AND C#

In the C# classes and how to create a class in C#. We will also discuss Class Members like fields, constants and static members; I will also discuss the Access Modifiers available in C#.
A class is the core of any modern Object Oriented Programming language such as C#; most of the time, you will be writing classes. If you have a background in C or C++, many class aspects are similar, but some are different. For example, C# doesn't permit functions to exist outside the class declaration like C++; also, C# use the .NET Framework Class Library, so you have access to thousands more functions than the class libraries available to C++.
But the concept of data encapsulation is the same in all the modern OOP languages, so a class in C# contains data (fields for example) and operations that manipulate the data (methods). For example, a class that describes an employee would include fields like firstName, lastName, dateOfBirth, basicSalary and department, and methods that operate on the data, such as CalculateSalary() which calculates the employee's basic salary plus the overtime, for example, and another method like RaiseBasicSalary() that raises the basic salary of the employee.
To create a class, you simply use the keyword "class" followed by the class name:
class Employee {

}
You can precede the class keyword with an access modifier keyword (which we will discuss later in the article):
public class Employee {

}
All of the class members must exist between the curly braces, so you don't have global functions like C++. You can create more than one class definition in one physical file, but it's not a good programming practice; it's better to create each class in one file with the extension .cs
Note that all classes in C# directly or indirectly inherit from one base class, System.Object, and you don't have to explicitly define the inheritance, because the C# compiler enforces it. So the following class:
public class Employee { }
is the same as:
public class Employee : System.Object { }
You can add a class to your project using Visual Studio.NET; simply right click the project icon in Solution Explorer window (you can view the Solution Explorer windows using CTRL+ALT+L), then click on Add --> Add Class, and the Add New Item windows will be shown:
Note that you can add a class, Windows Form, Control, Component and many other variations; this is one feature of the Visual Studio.NET tool. For example, when you add Windows Form, VS.NET will create the Form (it's a class too) and generate code that the Form requires.
Modify the name of the class to Employee.cs and click Open. VS.NET will create the file, and generate basic class declaration code:
using System; namespace Company { /// /// Summary description for Employee. /// public class Employee { public Employee() { // // TODO: Add constructor logic here // } } }
VS.NET declares the class as public, and creates an empty default constructor along with some comments. These are special kinds of comments that are used for generating documentation -- another feature of VS.NET. For now, delete the documentation and the default constructor, so you will show the Employee class as:
using System; namespace Company { public class Employee { } }
Before we discuss class members you should know that every member must have an access modifier, and if you didn't supply one, C# will consider this member a private member. It's better, however, that you explicitly define it private with the keyword "private." As you can see, there's no semicolon needed after the class declaration, although you can put it there if you're used to doing so. There are no more #include files, because the C# compiler automatically resolves project dependencies. In C# the operators -> and :: (unlike C++) don't exist, so if you want to access class members, use the dot operator ( . )
C# classes are reference types, so they are never allocated on the Stack; they are allocated on the Managed Heap. The Managed Heap is an area of memory that is managed by the Common Language Runtime, which has the ability to free unused memory blocks (objects) in a process known as Garbage Collection. When you have a variable that's not attached to an object:
Employee Michael;
You will not be able to access the object's members, and the variable Michael will reference to a block of memory which contains nothing, so we say of this variable that "it has a null reference" which means we can't use it. You must instantiate an object in order to use it:
Employee Michael = new Employee();
As we have said before, the new operator creates the object on the Managed Heap and returns the reference, which will be stored in the variable Michael.
The this keyword
The "this" keyword gets you an access to an instance of the class, and you can use it with instance methods, instance constructors and instance properties. You can't use it with any static members; this makes sense because a static member works on the class itself, not on an instance of it. Use the "this" keyword followed by the (.) operator to get access to the class members on an instance object. Take a look at the following class:
using System; namespace Company { public class Employee { public string FirstName; public string LastName; //the default constructor public Employee() { this.FirstName = "Michael"; this.LastName = "Youssef"; } } }
In the Employee class's default constructor I used the "this" keyword to initialize the public fields FirstName and LastName, so this keyword pretends that you already have an instance of the Employee class.
Class members
Inside a C# class you have defined: fields, properties, methods, constructors, destructor, indexers, constants, events, delegates and operators. We will discuss Fields, Constants and Static Types in this article; we will have separate articles for each of the other Class members.
Fields
A field is a class level variable, or you can call it a member variable. If you declare a field of a value type, it stores the data itself, but if you declare a field of a reference type, it stores a reference to where the actual data is allocated. You must be careful when you define member variables. Let's take an example:
using System; namespace MyCompany { public class Employee { public decimal Salary; } public class EmployeeTest { static void Main(string[] args) { // this is client code that can modify the value of the Employee's salary Employee Michael = new Employee(); Michael.Salary = 10000; Console.WriteLine("Michael's salary = {0:C}",Michael.Salary); Michael.Salary = 0; Console.WriteLine("Michael's salary = {0:C}",Michael.Salary); Console.ReadLine(); } }
The class Employee has only one public field (Salary) which represents the employee's salary. The EmployeeTest class' Main method creates the instance Michael of type Employee, and the next statement sets the salary to $10,000. As you can see, the client code assigns the value to the public field Salary, and you don't have any kind of security over the process. Again, the Main method assigns 0 to the salary and writes it to the Console Window. You will get the following result:
Good Object oriented practice states that you must declare your fields as private, and provide provide public properties to access the fields (we will discuss properties later in the series, too, so don't worry). Let's look at the MSIL code for Employee class. Open the ILDASM tool and load the application, then navigate to the Employee class and double click on the Salary field:
The MSIL is just telling us that it's a public field of type System.Decimal, and it's called Salary. This means that when you instantiate the Employee class, the created object will have a block of memory for the Salary field; that is worth remembering.
With other programming languages we had a very common problem, which C# has vanquished. Suppose that you need a field to be initialized at runtime and never change after that. If you know the value at design time, you can use constants (as we will discuss shortly). You can declare your field with the keyword "readonly" to have this behavior, and once it has been initialized at runtime it will never change. You have only one place to initialize the "readonly" field, which is the class constructor. Turning back to our Employee class, we need a "readonly" field to hold the SSN that will dynamically return from a method; this method maybe will connect to a database server to get the SSN of the employee, so the SSN is not available at design time.
using System; namespace MyCompany { public class Employee { public decimal Salary; public readonly double SSN; // class constructor public Employee() { SSN = this.GetSSN(); } private double GetSSN() { //we will assume that we have connected to a database return 987654321; } } public class EmployeeTest { static void Main(string[] args) { // this is client code that can modify the value of the Employee's salary Employee Michael = new Employee(); Console.WriteLine(Michael.SSN); Console.ReadLine(); } } }
Constants
Sometimes you know the value that you want to assign to your fields, and you need these values to remain unchanged. For example, in the employee class you may have a field for the maximum overtime hours per week, which will never change, and this information is available at design time. What you do? Use the "const" keyword to declare the field as constant, which means that its value will not change; it must be available at design time.
public class Employee { public decimal Salary; public const int MaxOverTimeHours = 10; }
Note that the value of the constant field must be literal, so you can't get the value as a return value from a method call. Load the ILDASM Tool, navigate to the Employee class, and double click the MaxOverTimeHours field.
This is the MSIL declaration for the constant field MaxOverTimeHours, and as you can see, it has been assigned the value (0xA) 10. Now let's try to use this field.
public class EmployeeTest { static void Main(string[] args) { Console.WriteLine(Employee.MaxOverTimeHours); Console.ReadLine(); } }
From the above constant field declaration, you can see that it's a static field, which means that you can't access the field with an object reference. You have to use the class name in order to access the static members. Think about it for a minute: why do we need an instance variable for a field whose value will never change? It will create a lot of unnecessary memory spaces, so C# defines it as static, because it will never change. Load the EmployeeTest class with the ILDASM tool and get to the main method:
The highlighted MSIL Instruction pushes the value 10 onto the stack, and the next Instruction calls the Console::WriteLine(Int32) method to print this value. As you can see, we don't have the MaxOverTimeHours constant field here; instead, the C# compiler replaces the field with the value.
Static members
A Static member is a member that has a class-level access, unlike instance members which must be called on an instance of the class. To call a Static member, simply use the class name followed by the (.) operator without creating an object from the class. Static members are useful for many scenarios.
Take the Console class as an example; to write a line to the console you use the static method WriteLine() of the Console class. In this scenario, it doesn't make sense to create an instance of the Console class and call WriteLine(), because all of the objects would write a line to the Console Window.
You can use static members to provide functionality that is not bound to an instance of the object; a class like Console can't be instantiated, and all its members are static. This is the perfect scenario, where we have some functionality and code that doesn't fit in the Object Oriented Programming Objects and Classes world, such as the Console class.
If you have a class that contains a static field and another instance field, note that each time you create an instance of the class, the CLR will allocate a memory location for the instance field, but, as for the static field, it will create only one memory location no matter how many objects you have. Think of the static members as class level members, and the instance members as per object data fields. Also remember that a static method can only manipulate static fields; we will discuss this issue in the methods article.

Turning back to our Employee class example, suppose that we need some way to track how many employee objects we have. Look at the following code:
using System; namespace MyCompany { public class Employee { public decimal Salary; public const int MaxOverTimeHours = 10; public static double EmployeeCounter; public Employee() { EmployeeCounter++; } } public class EmployeeTest { static void Main(string[] args) { Employee Michael = new Employee(); Employee Youssef = new Employee(); Employee David = new Employee(); Console.WriteLine(Employee.EmployeeCounter); Console.ReadLine(); } } }
The result of this code is 3. In the Employee class we added a public static field called EmployeeCounter, and in the default constructor of the Employee class (for now think of a constructor as a special type of methods that is called every time you create an instance of your class), we increase the EmployeeCounter by 1 for each new employee instance. In the EmployeeTest class we created 3 objects of type Employee, and printed the value of the EmployeeCounter field. Note that we used the class name in order to access the static field.







14. WEB SERVIES SECURITY WITH C#
Authentication and Authorization in ASP.NET

Abstract Authentication is the process of identification and validation of a user's credentials. After the identity is authenticated, a process called authorization determines whether that identity has access to a particular resource. This article discusses both these concepts in detail

Authentication
Authentication is the process of determining the authenticity of a user based on the user’s credentials. Whenever a user logs on to an application, the user is first authenticated and then authorized. The application’s web.config file contains all of the configuration settings for an ASP.NET application. It is the job of the authentication provider to verify the credentials of the user and decide whether a particular request should be considered authenticated or not. An authentication provider is used to prove the identity of the users in a system.

Authorization
Authorization is the process of determining the accessibility to a resource for a previously authenticated user. Note that authorization can only work with authenticated users, hence ensuring that no un-authenticated user can access the application. The default authentication mode is anonymous authentication.
Authentication
Authorization
Authentication is a process in which the user’s credentials are used to verify the user’s identity. In short, this is the process of determining the identity of the request entity.
Authorization is a process in which the authenticated user is allowed (authorized) access to resources.
In short, whenever a user logs on to an application, the authentication process is first carried followed by the authorization user. Certain applications do not have any restriction/validation on the logged in user. Even such applications authenticate the user as anonymous.
ASP.NET and IISBelow, is the sequence of events involved in the authentication process (jointly done by IIS and ASP.NET):
The incoming request is first checked by IIS. If the IP address from where the request is sought is not allowed access to the domain, IIS denies the request.
By default, IIS allows anonymous access and hence requests are automatically authenticated. However, this can be overridden for each application within IIS. Next in the sequence, IIS performs this authentication, if it has been configured to do so.
As a next step, the authenticated user request is passed to ASP.NET.
ASP.NET now checks whether Impersonation is enabled or not. By default impersonation is not enabled in ASP.NET. Generally, some applications require impersonation for ASP compatibility and Windows server authentication.
If impersonation is enabled, ASP.NET executes with the identity of the entity on behalf of which it is performing the executing task.
If impersonation is disabled, the application runs with the privileges of ASP.NET.
Finally, the identity that has been authenticated and checked for in the previous steps is used to request resources from the OS. ASP.NET relies on NTFS file permissions for granting access.
If access is granted (successful authorization), ASP.NET returns the user’s request through IIS.
The above sequence of steps is pictorially depicted in Illustration 1.
Illustration 1
Authentication Providers :
ASP.NET provides three types of authentication, namely windows authentication, forms authentication and passport authentication. It is the job of the authentication provider to verify the credentials of the user and decide whether a particular request should be considered authenticated or not.
Windows Authentication ProviderWindows authentication provider is the default provider for ASP.NET. It lets us/application authenticate users based on the users’ Windows accounts. IIS performs authentication for this provider and the authenticated identity is then passed on to the code.
Passport Authentication ProviderThis provider uses the passport services provided by Microsoft.
Forms Authentication ProviderThe forms authentication provider uses custom HTML forms to collect authentication information and lets us use our logic to authenticate users. The user’s credentials are stored in a cookie for use during the session. If the application authenticates the request, the system issues a form that contains the credentials or a key for reacquiring the identity. Subsequent requests are issued with the form in the request headers; they are authenticated and authorized by an ASP.NET handler using whatever validation method we have specified in our code.
To select an authentication provider, an entry indicating the same has to be made in the web.config file.
//For Windows authentication //For Passport authentication //For Forms authentication
ASP.NET also supports custom authentication providers. Setting the authentication mode for the application to “none” and then writing our own code to perform authentication can achieve this.
//For Custom authentication
ASAPI Filters
For example, we might install an ISAPI* filter** in IIS that compares incoming requests’ IP address with a list of source IP addresses and considers the request to be authenticated only if the IP address is found in the source list. In this example, we can set the authentication mode to “none” in the web.config file. This will prevent any of the default authentication providers from being triggered.
We just had a brief look at the authentication providers of ASP.NET. Let us now go into detail and explore the authentication modes in detail.
Windows Authentication and IIS

IIS provides Windows Authentication and hence, this should be configured within IIS. There are four different kinds of Windows authentication available: Anonymous, Basic, Digest and Integrated Windows Authentication.
Anonymous Authentication: IIS doesn’t perform any authentication checks. IIS allows any user to access the ASP.NET application.
Basic Authentication: For this kind of authentication, the Windows user name and password have to be provided to connect. However, this information is sent over the network in plain text, and, hence, this is an insecure method of authentication.
Digest Authentication: It is the same as basic authentication except for the fact that the password is hashed before it is sent across the network. However, to be using Digest Authentication, we must use Internet Explorer 5.0 or above.
Integrated Windows Authentication: In this kind of authentication technique, passwords are not sent across the network. The application here uses either the kerberos or challenge/response protocols to authenticate users. Kerberos, a network authentication protocol, is designed to provide strong authentication for client-server applications. It provides the tools of authentication and strong cryptography over the network to help secure information in systems across an entire enterprise.
Passport Authentication: Passport authentication is a centralized authentication service. This uses Microsoft’s Passport service to authenticate the users of an application. If the authentication mode of an application is configured as “Passport”, and if the users have signed up with Passport, then the authentication formalities are pushed over to Passport servers.Passport uses an encrypted cookie mechanism to identify and indicate authenticated users. If the users have already been signed into Passport when they visit the application page, ASP.NET will consider them as authenticated; otherwise, the users will be redirected to Passport servers to login. Upon successful login, they’ll be redirected back to the application page.




Forms Authentication: With forms authentication, custom logic can be built into an ASP.NET application. The following happens when forms authentication is used in an ASP.NET application:
When a user requests a page for the application, ASP.NET checks for the presence of a special session cookie.
If the cookie is present, ASP.NET assumes the user is authenticated and processes the request.
If the cookie isn’t present, ASP.NET redirects the user to a web form where the custom logic has been built into the code. The authentication checks can be incorporated into the web form, and when the user is authenticated ASP.NET needs to be informed of the same by setting a property. Once this is done, ASP.NET creates the special cookie to handle any subsequent requests.
Configuring Authorization
Impersonation is a technique that allows the ASP.NET process to act as the authenticated user, or as an arbitrary specified user. ASP.NET impersonation is controlled by entries in the application’s web.config file. By default, impersonation is disabled. Including the following code in the file can explicitly turn impersonation off:

ASP.NET does not perform impersonation if the above piece of code is found in the file. This means that ASP.NET will run with its own privileges. After the user has been authenticated, ASP.NET uses it own identity to request access to resources.By default, ASP.NET runs as an unprivileged account. By changing the userName attribute of the processModel section in the machine.config file, the account can be changed from a low-privileged one to a high-privileged one. When this modification is made, it applies to all sites on the server. If the userName attribute of the processModel is changed to SYSTEM, the user account becomes a high privileged account. However, this is a security risk as it elevates the privileges of the ASP.NET process and the OS may be at risk.To enable impersonation, the following code should be included:

In this case, ASP.NET takes on the identity IIS passes to it. If anonymous access is allowed in IIS, ASP.NET will impersonate the IUSR_ComputerName account that IIS uses. If anonymous access is not allowed, ASP.NET will take on the credentials of the authenticated user and makes requests for resources taking on that identity. A further important feature of any ASP.NET application is that a particular identity can also be used for all authenticated requests. To accomplish this, the following line of code needs to be included:

In this case, all authenticated users will be taking on the identity and using this identity ASP.NET makes all requests for resources. The drawback to this technique is that the password must be coded in plain text in the web.config file. Though ASP.NET does not allow for this file to be downloaded, it is still a security risk.Best PracticesBelow is a list of some best practices to help you in choosing an authentication mode and configuring authorization:
If there is no sensitive data in the application, no anonymous authentication is the best authentication mode. This allows all users, who have access to the host, to access the application.
If authentication of users needs to be performed, there are several choices. Windows Authentication in ASP.NET is the best authentication mode to use if all user accounts exist on the network in which the application is running. If not all users have accounts on the network, then forms authorization can be used.
If different users, having different sets of privileges, need to access the application then impersonation in the ASP.NET configuration file should be turned on.
*ISAPI: Internet Server Application Program Interface - is a programming interface on IIS, Microsoft's web server. It allows third parties (and Microsoft) to add functionality to web servers running Microsoft IIS. **ISAPI Filter: A DLL that uses the ISAPI to register for web server events and edit the data stream going to and coming from the Microsoft IIS web server.
Windows-based Authentication
When you use ASP.NET Windows authentication, ASP.NET attaches a WindowsPrincipal object to the current request. This object is used by URL authorization. The application can also use it programatically to determine whether a requesting identity is in a given role.

function doClick(index, numTabs, id) {
document.all("tab" + id, index).className = "tab";
for (var i=1; i if(User.IsInRole("Administrators")) { DisplayPrivilegedContent();}

The WindowsPrincipal class determines roles by NT group membership. Applications that want to determine their own roles can do so by handling the WindowsAuthentication_OnAuthenticate event in their Global.asax file and attaching their own class that implements System.Security.Principal.IPrincipal to the request, as shown in the following example:
// Create a class that implements IPrincipalpublic class MyPrincipal : IPrincipal { // implement application-defined role mappings} // In a Global.asax file:public void WindowsAuthentication_OnAuthenticate(Object Source, WindowsAuthenticationEventArgs e) { // Attach a new application-defined class that implements IPrincipal to // the request. // Note that since IIS has already performed authentication, the provided // identity is used. e.User = new MyPrincipal(e.Identity);} ' Create a class that implements IPrincipalPublic Class MyPrincipal : Inherits IPrincipal ' Implement application-defined role mappingsEnd Class ' In a Global.asax filePublic Sub WindowsAuthentication_OnAuthenticate(Source As Object, e As WindowsAuthenticationEventArgs) ' Attach a new application-defined class that implements IPrincipal to ' the request. ' Note that since IIS has already performed authentication, the provided ' identity is used. e.User = New MyPrincipal(e.Identity)End Sub // Create a class that implements IPrincipal.public class MyPrincipal implements IPrincipal { // Implement application-defined role mappings.} // In a Global.asax filepublic function WindowsAuthentication_OnAuthenticate(Source:Object, e:WindowsAuthenticationEventArgs) : void { // Attach a new application-defined class that implements IPrincipal to // the request. // Note that since IIS has already performed authentication, the provided // identity is used. e.User = new MyPrincipal(e.Identity);}If User.IsInRole("Administrators") Then DisplayPrivilegedContent()End If if(User.IsInRole("Administrators")) { DisplayPrivilegedContent();
}
OUTPUT OF Windows Authentication













15. READING AND WRITING XML DOCUMENTS WITH XML TEXTREADER AND XML TEXTWRITER CLASS AND C#

.NET is built using Xml by .net development team in many places .The Xml that is provided to access the Xml data.Finally System.Xml is the namespace that is added with all .net related Xml classes.In this two classes that provide the stream model of access for xml data these two classes are 1.XmlTextReader 2.XmlTextWriter
1.XmlTextReader:
It Reads the Xml file content in noncached manner and produces the ReadStatus everytime using it’s properties and methods.TextReader allows sequential processing of data where user can read step by step in a forward only manner
To read a file using this syntax:
XmlTextReader obj;
2.XmlTextWriter:
It is used to generate on-fly Xml documents taking input from user or from any other
Prepared source
It has many methods and properties that generates the Xml tags.
To write a file using this syntax:
XmlTextWriter obj;


//EXAMPLE ON XMLTEXTREADER AND XMLTEXTWRITER//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace WindowsApplication3
{
public partial class Form1 : Form
{
public Form1()
{ InitializeComponent(); }

private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { }

private void Form1_Load(object sender, EventArgs e)
{
XmlTextReader Xmlrdr;
}


private void button1_Click(object sender, EventArgs e)
{
Xmlrdr = new XmlTextReader("E:\\authors.Xml");
while (Xmlrdr.Read())
{
if (Xmlrdr.Name == "au_fname")
{
Xmlrdr.Read();
listBox1.Items.Add(Xmlrdr.Value);
}
}
Xmlrdr.Close();

}
}
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace WindowsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
XmlTextWriter XmlW;
XmlW = new XmlTextWriter("C:\\status.Xml", null);
XmlW.Formatting = Formatting.Indented;
XmlW.WriteStartDocument();
XmlW.WriteStartElement("ROOTD.S");
}



private void button1_Click(object sender, EventArgs e)
{
XmlW.WriteStartElement("TASKS");
XmlW.WriteElementString("PROGRAMERID", textBox1.Text);
XmlWhitespace.WriteElementString("TASKS", textBox2.Text);
if (checkBox1.Checked)
XmlWhitespace.WriteElementString("STATUS", "COMPLETED");
else
XmlW.WriteElemenetString("STATUS", "INCOMPLETE");
XmlW.Flush();
MessageBox.Show("RECORD ADDED");
}
}
}