A Place for C Sharpers/.Netters

I Will do coding till last moment of life-Kiran Patil

Archive for December, 2007

Web service Software factory Quickstart or Security with Web Service Software Factory Using Direct Using Direct Authentication

Posted by kiranpatils on December 10, 2007

Target Audience:

if you want to make one demo application in Windows Service factory and also want to see security features of WCF than this is for you…so good to go….if not than go….

prerquisities:

Web Service Software Factory–July 2006

Visual studio 2005

get it from here:http://msdn2.microsoft.com/en-us/library/aa480534.aspx

You can use the WCF Security Guidance Package to configure and test security settings used by Windows Communication Foundation (WCF) services. The guidance package contains recipes that are used to configure authentication protocols. In addition, a recipe is also included that can be used to validate the configuration and perform code analysis using FxCop. The authentication recipes represent an automated process that makes it very easy to configure security.

You can also use the Service Configuration Editor included in the Microsoft Windows Software Development Kit (SDK) for .NET Framework 3.0 to manually configure WCF security settings. The guidance package is easier to use than the service configuration editor, but there may be cases when you have to modify security settings on a computer that does not have the guidance package installed. As a result, this topic discusses both automated configuration using the guidance package and manual configuration using the configuration editor.

Employee Service

1. Create A project By File->new->Project

WCF SERVICE 01

WCF SERVICE 02WCF SERVICE 03

It will generate the solution structure as shown above.

How to: Implement EmployeeService

EmployeeService.DataContracts

To create your data contract using the Create Data Contract recipe

WCF SERVICE 04

This will bring up the recipe wizard

WCF SERVICE 06

Click Next

WCF SERVICE 07

When Table is validated at that time only the Finish Button is going to be enable

It will generate following file:

using System;

using System.Collections.Generic;

using System.Runtime.Serialization;

namespace EmpService.DataContracts

{

/// <summary>

/// Data Contract Class – Employee

/// </summary>

[DataContract(Namespace = "http://EmpService.DataContracts/2007/12", Name = "Employee")]

public partial class Employee

{

private System.Int32 EmployeeIDField;

[DataMember(IsRequired = true, Name = "EmployeeID", Order = 0)]

public System.Int32 EmployeeID

{

get { return EmployeeIDField; }

set { EmployeeIDField = value; }

}

private System.String FirstNameField;

[DataMember(IsRequired = false, Name = "FirstName", Order = 1)]

public System.String FirstName

{

get { return FirstNameField; }

set { FirstNameField = value; }

}

private System.String LastNameField;

[DataMember(IsRequired = true, Name = "LastName", Order = 2)]

public System.String LastName

{

get { return LastNameField; }

set { LastNameField = value; }

}

private System.String NoteField;

[DataMember(IsRequired = false, Name = "Note", Order = 3)]

public System.String Note

{

get { return NoteField; }

set { NoteField = value; }

}

}

}

EmployeeService.ServiceContracts

To create your service contract using the Create Service Contract recipe

WCF SERVICE 08

This will show up a Service Contract Recipe

WCF SERVICE 09

WCF SERVICE 10

Service Contract Example[Fill values in above table like shown as below Table. if value is not in belows table you can keep it as it is.]

Name

Request

Response

FindEmployeeByLastName

System.String

 

EmployeeService.DataContracts.Employe

WCF SERVICE 11

For this example, you do not generate the service contract implementation

Just Build the Solution.

 

EmployeeService.ServiceImplementation

To implement the service contract

WCF SERVICE 12

WCF SERVICE 14

it will generate following code:

public EmpService.DataContracts.Employee FindEmployeeByLastName(string request)

{

EmpService.DataContracts.Employee emp = new EmpService.DataContracts.Employee();

System.Security.Principal.IPrincipal principal = System.Threading.Thread.CurrentPrincipal;

emp.EmployeeID = (request.Length > 0) ? request[0].GetHashCode() : 0;

emp.FirstName = principal.Identity.Name;

emp.LastName = request;

emp.Note = “AuthType = “ + principal.Identity.AuthenticationType;

return emp;

}

This is test code that returns the Employee data contract with the FirstName property equal to the current authenticated user name, the LastName property equal to the request, and the Note property initialized with the authentication type used by the WCF service

How to: Expose and Test the Service

Services are exposed and tested through the provided sample host. This host is a file system–based Web application that uses the built-in Web server included in ASP.NET 2.0 for developing and testing purposes. To enable the host, use the Expose Service recipe.

WCF SERVICE 17

WCF SERVICE 19

To test the host

1. In Solution Explorer, right-click EmployeeManager.svc (it was added in the previous step), point to Service Factory (WCF), and then click View in Browser or Debug Host. This opens a browser window.

2. In the browser window that opens, you can examine the WSDL and learn how to use Svcutil.exe to generate client code used to access the service. Svcutil.exe is a service model metadata utility tool included in the Microsoft Windows Software Development Kit (SDK) for .NET Framework 3.0.

WCF SERVICE 20

How to: Implement the Test Client

Services are tested through the provided sample client application. The client application included with the WCF Service template is a Windows Forms application that includes a grid to view the results.

WCF SERVICE 21

WCF SERVICE 22

Copy this URL

WCF SERVICE 23

WCF SERVICE 24

WCF SERVICE 25

To test the service clientTabClick

 

Press Enter And TAB it will generate the code shown as below:

//TODO: Call proxy method

using( proxy = new ())

{

[] dts = proxy.FindBy(this.SearchText.Text);

ResultsGrid grid = new ResultsGrid(dts);

grid.ShowDialog(this);

}

Now fill it like this:

private void ExecuteButton_Click(object sender, EventArgs e)
{
//TODO: Call proxy method
using(EmployeeManager.EmployeeManagerClient proxy = new EmployeeManager.EmployeeManagerClient ())
{
EmployeeManager.Employee dts = proxy.FindEmployeeByLastName(this.SearchText.Text);

ResultsGrid grid = new ResultsGrid(dts);

grid.ShowDialog(this);
}
}

This implies that you have implemented a FindEmployeeByLastName method in the EmployeeManager class. This is your business logic.

WCF SERVICE 35

WCF 29

WCF 30

It looks Good…..na so much work gives you so nice result…isn’t it?????

WCF SECURITY

To use the security package, you have to enable it using the Guidance Package Manager. After it is enabled, you have to modify security settings for the solution before you use any of the other security recipes. For information about how to enable the security package and configure the solution, see the following subtopics:

How to: Enable the WCF Security Guidance Package

WCF 31

WCF 34

click on enable/Disable Packages..

WCF 37

Select Web Service software factory security->OK->Close.

 

In short Steps:

To enable the WCF Security Guidance Package

1. On the Tools menu, click Guidance Package Manager.

2. Click Enable / Disable Packages.

3. Select the Web Service Software Factory – Security (WCF) check box.

4. Click OK.

5. Click Close

How to: Modify Your Security Settings

 

Using the Modify Security Settings recipe, you can constrain the security settings for the solution. It is intended to be used by an architect or lead developer who wants to pre-configure security settings for services within the solution.

To modify your security settings

1. In Solution Explorer, right-click the solution, point to Service Factory (WCF Security), and then click Modify security settings.

WCF 36

 

2. On the Security Settings page, you can set the security settings that are available for the solution. The following options are available:

· Kerberos

· X.509 Certificates

· Direct Authentication (using UsernameToken) with Windows accounts

· Direct Authentication (using UsernameToken) with ADAM provider

· Direct Authentication (using UsernameToken) with SQL Server provider

· Anonymous

WCF 38

 

3. On the Message Protection Settings page, you can set the protection levels that are available for the solution. The following options are available:

· None

· Sign

· Sign and Encrypt (XML signatures are also encrypted)

WCF 39

Press FINISH.

It will save the settings in solution means now whenever you click on Security Settings it will show you the settings which you have modified.

 

The following is optional [I have also copied and pasted from MSDN :-) ]

TO DO IT MANUALLY

How to: Use the Service Configuration Editor

The Microsoft Windows Software Development Kit (SDK) for .NET Framework 3.0 provides a tool named Service Configuration Editor that can be used to create and modify security settings in a configuration file. There are several options that can be used to open a configuration file using the configuration editor; this topic describes two options. The first option is to launch the editor and open the configuration file using editor menus. The second option is to add the service configuration file to the list of programs that can be used in the Open With dialog box in Visual Studio.

To launch the configuration editor and open a file

1. On the Start menu, point to All Programs, point to Microsoft Windows SDK, point to Tools, and then click Service Configuration Editor.

2. On the File menu of the configuration editor, point to Open, and then click Config file.

3. In the Open dialog box, navigate to the configuration file you want to open, select the file, and then click Open.

Alternatively, you can create a new configuration file using the configuration editor. To do this, click New Config on the File menu.

To open a file and add the Service Configuration Editor to the Visual Studio Open With dialog box

1. In the Visual Studio Solution Explorer, select the configuration file you want to open.

2. Right-click the configuration file, and then click Open With.

3. Click Add, and then type the following in the Program Name box: C:\Program Files\Microsoft SDKs\Windows\v6.0\Bin\SvcConfigEditor.exe. In the Friendly Name box, type Service Configuration Editor, and then click OK.

4. In the Open With dialog box, click Service Configuration Editor (it was added in step 3), and then click OK.

Figure 1 illustrates the Service Configuration Editor with an open Web.config file.

WCF 41

Service Configuration Editor

In the Service Configuration Editor, the tree view in the left pane is used to navigate through different elements in the configuration file. Many of the folders shown in the tree view represent XML elements under the <system.serviceModel> element in a configuration file. The main pane on the right is used to configure different attributes for the element selected in the left pane. Examining all the different configuration settings is beyond the scope of this discussion; however, this subtopic reviews settings that are used to control security.

ms-help://MS.VSCC.v80/MS.VSIPCC.v80/ms.wssf.2006Dec/WSSF/local/note.gifNote:

Many folders in the service configuration tree view represent XML elements in a configuration file. The main pane in the Service Configuration Editor is used to set attributes of the element that is selected in the tree view.

As shown in Figure 1, there are five top-level folders: Services, Client, Bindings, Diagnostics, and Advanced.

The Services folder represents the services configuration element, which contains one or more service configurations. Under each service element is an endpoints element that contains one or more endpoint configurations. An endpoint for a service identifies the contract that defines the service interface. With the example illustrated in Figure 1, the service contract is defined as EmployeeService.ServiceContracts.IEmployeeManager.

Each endpoint element must contain binding information that indicates how a client application connects to the service. The endpoint can also identify a behavior that can be used to extend the default behavior of a WCF service.

The Client folder represents a client configuration element. The client element contains an endpoint element used to define the address of the WCF service accessed by the client application. Similar to the service endpoint, the client endpoint also contains binding and behavior information.

The Bindings folder represents the bindings configuration element, which contains one or more binding configurations. Bindings specify communication details used to connect to a WCF endpoint, such as transport protocols, security requirements, and encoding requirements. Security requirements for a binding include authentication protocols with related encryption and signing requirements.

The Diagnostics folder represents a diagnostics element that contains different configuration elements used to enable actions such as tracing and message logging.

The Advanced folder does not represent a configuration element; however, some child folders, such as Endpoint Behaviors and Service Behaviors, represent elements in the configuration file. Endpoint Behaviors represents an element named endpointBehaviors that can contain one or more behavior configurations that can be used by an endpoint. The Service Behaviors folder represents an element named serviceBehaviors that contains one or more behavior elements that can be used by a service. Several behaviors are included in the .NET Framework 3.0 runtime that can be used to perform operations such as authorization.

The following is a summary of elements that control security:

  • · A service element contains information used to specify how client applications connect to and interact with the service. For example:
  • Endpoints in a service identify a service contract and binding type.
  • Service behaviors can be used to perform authorization and supply credentials for a service.
  • A binding element specifies transport protocols, security requirements, and encoding requirements used to connect to a service

When using X.509 certificates, direct authentication, or anonymous authentication, you have to install X.509 certificates in a certificate store located on your server or client workstation. For information about how to request and install these certificates, see the following subtopic:

How to: Install X.509 Certificates in the Local Certificate Store

There are two types of certificates you will need to install and use when configuring and testing WCF security using the Web Service Software Factory - Security (WCF) guidance package. The first one is a computer certificate that will be installed in the Local Computer certificate store. The second one is a client certificate that will be installed in the Current User certificate store. These tasks will be accomplished using a Microsoft Management Console (MMC) snap-in, which is described in How to: Use the X.509 Certificate Management Tools of Web Service Security: Scenarios, Patterns, and Implementation Guidance for Web Services Enhancements (WSE) 3.0.

To initialize the MMC snap-in for certificates

WCF 43

WCF 44

WCF 45

WCF 46

WCF 48

WCF 49

WCF 51

WCF 51

WCF 54

It will save the file:

WCF56

In short Steps are:

To initialize the MMC snap-in for certificates

1. On the taskbar, click Start, and then click Run.

2. In the Run box, type mmc, and then click OK.

3. On the File menu, click Add/Remove Snap-in, and then click Add.

4. Under Snap-in, double-click Certificates.

5. Click My user account, and then click Finish.

This allows you to manage certificates for the current user. Certificates – Current User appears on the list of selected snap-ins.

6. Under Snap-in, double-click Certificates.

7. Click Computer account, click Next, click Local Computer, and then click Finish.

This allows you to manage local computer certificates.

8. Click Close, and then click OK.

9. To save the console, click Save on the File menu.

10. In the File name box, type Certificates.msc, and then click Save.

This will add a new menu item named Certificates.msc to the Administrator menu. The Certificates.msc menu item can be used to open the certificates snap-in.

After the certificates snap-in has been initialized, the next step is to request a computer certificate that will be used for the WCF services you are configuring.

To obtain an X.509 computer certificate

1. Open the Certificates.msc Microsoft Management Console (MMC) snap-in.
WCF56

Expand Certificates (Local Computer), expand Personal, and then select Certificates.

3. Right-click Certificates, point to All Tasks, and then click Request New Certificate.

4. Create a computer certificate by following the wizard steps:

a. Click Next.

b. In the Certificate types list, click Computer, and then click Next.

c. In the Friendly name box, type a name.

d. (Optional) In the Description box, type a description.

e. Click Next.

f. Click Finish.

How to: Secure Your WCF Service Using Direct Authentication

Direct authentication is a process where a user’s ID and proof-of-possession are used by a service to authenticate the user. Proof-of-possession could be a password or smart card. The combination of user ID and proof-of-possession represent a user’s credentials. The credentials are sent as part of the message to a service, which validates the credentials and sends a response.

WCF 57

As illustrated in Figure 1, the following steps describe the direct authentication process:

1. The client sends a request to the Web service. Credentials are attached to the request message.

2. The Web service validates the credentials against an identity store and makes authorization decisions about the client.

3. (Optional) The Web service returns a response to the client.

In Chapter 1 of Web Service Security: Scenarios, Patterns, and Implementation Guidance for Web Services Enhancements (WSE) 3.0, the architecture pattern section named “Direct Authentication” describes the following forces that would justify using direct authentication:

· The credentials that the client presents to the Web service are based on shared secrets such as passwords. Frequently, authentication of individual users is performed with passwords. Computers and applications often use higher quality secrets that are more secure than passwords. The client and the Web service must securely exchange the shared secrets before interaction is possible. The exchange of shared secrets must occur through an out-of-band mechanism.

· The Web service can validate credentials from the client against an identity store. The Web service must have direct access to the identity store, including appropriate permissions for accessing identity information.

· The Web service is relatively simple, and does not require support for capabilities such as singlesign-on or support for non-repudiation. In these circumstances, an effective, low cost solution that does not use an authentication broker may be possible.

· The client and the Web service trust one another to manage credentials securely. In this situation, both parties should consider the credentials as equal in value to the information and services they protect. If either the Web service or the client manage the credentials in an insecure manner, neither party can be sure that the mishandled credentials prove the identity of the user or application.

The WCF Security guidance package contains three recipes for direct authentication that support different identity stores:

ADAM. Active Directory Application Mode (ADAM) is a lightweight directory service that is accessed using a Lightweight Directory Access Protocol (LDAP).
SQL Server. User credentials are stored in a database and accessed using membership and role provider classes that are available in the .NET Framework.
Windows accounts. Credentials are used to authenticate users stored in Active Directory.

To secure your WCF service using direct authentication:

1. In Solution Explorer, right-click the Web service Host project, point to Service Factory (WCF Security), and then click Secure a Service Using Direct Authentication with [Provider].

WCF58

2. Specify your service properties, including service name, endpoint, binding name, and behavior name.

WCF59

WCF60

3. Select the X.509 certificate you want to use from a certificate store. The X.509 certificate in this step is used to provide data origin authentication.

WCF61

4. Select your message protection requirements The configuration options for message protection requirements and algorithm suite will be dependant on the options that you specified in How to: Modify Your Security Settings. In addition, enable signature confirmation, establish secure conversation, or negotiate service credential configuration settings may be available based on the type of direct authentication being configured.

WCF62

5. Configure the identity provider.

WCF62

That’s done.

I can understand after doing this much long exercise you will fill tired..so go at home….or not than keep reading i will make u…..

Thanks

Source code is Here: Click on Me

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

 

 

 

 

 

 

 

 

 

 

 

 

 

Posted in Windows service Factory3.0 | Tagged: , , | 1 Comment »

Differences between visual basic .net and Visual c# .net

Posted by kiranpatils on December 7, 2007

Syntactically, Visual Basic .NET and Visual C# .NET are two different languages, just as Visual Basic, Visual C, and Visual C++ are different languages. Visual C# .NET looks more familiar to Visual C, Visual C++, and Java programmers, and Visual Basic .NET looks more familiar to Visual Basic developers. The biggest differences between the languages fall into the following categories:

  • Case sensitivity
  • Variable declaration and assignment
  • Data types
  • Statement termination
  • Statement blocks
  • Use of () vs. []
  • Operators
  • Conditional statements
  • Error handling
  • Overflow checking
  • Parameter passing
  • Late binding
  • Handling unmanaged code
  • Keywords

Case Sensitivity

Identifier names in Visual Basic .NET are not case-sensitive, but identifier names in Visual C# .NET are. This primarily presents a problem when you write code, and is not an issue in debugging a program that already compiles.

Variable Declaration and Assignment

Variables in Visual Basic .NET are declared with the variable before the data type. In Visual C# .NET, the data type precedes the variables.

Visual Basic .NET Visual C# .NET
Dim i, j As Integer int i, j;
Dim i As Integer = 7 int i = 7;
Dim i(6) As Integeror

Dim i() As Integer = New Integer(6) {}

int[] i = new int[6];
Dim con As SqlConnection SqlConnection con;
Dim x As New Y(“ABC”)or

Dim x As Y = New Y(“ABC”)

Y x = new Y(“ABC”);

Data Types

Simple data types have different names in Visual Basic .NET and Visual C# .NET. For example, Integer in Visual Basic .NET is int in Visual C# .NET. However, System.Int32, the .NET Framework base type for which Integer and int are aliases, can be used in both languages. Visual C# .NET also supports the signed byte, unsigned short, unsigned int, and unsigned long data types, which are not available in Visual Basic .NET.

The following table lists the different data type names in each language and the base types for which they are aliases.

Visual Basic .NET Visual C# .NET .NET Framework
Boolean bool System.Boolean
Byte byte System.Byte
Short short System.Int16
Integer int System.Int32
Long long System.Int64
Single float System.Single
Double double System.Double
Decimal decimal System.Decimal
Date System.DateTime System.DateTime
String string System.String
Char char System.Char
Object object System.Object
n/a sbyte System.Sbyte
n/a ushort System.UInt16
n/a uint System.UInt32
n/a ulong System.UInt64

Statement Termination

Statements in Visual Basic .NET are terminated by the end of the line. You can use the colon (:) to put multiple statements in a line, and you can use the line continuation (_) character to make a statement span several lines.

Statements in Visual C# .NET are terminated by the semicolon (;). You can use multiple statements per line, and statements can span multiple lines.

Visual Basic .NET Visual C# .NET
A = 5B = 7 : C = 8

MySub (Arg1, _

Arg2, _

Arg3)

A = 5;B = 7; C = 8;

MySub (Arg1,

Arg2,

Arg3);

Statement Blocks

Visual Basic .NET does not use arbitrary statement blocks. Instead, certain keywords that have a specialized terminating statement are used instead of the statement blocks.

In Visual C# .NET, braces ({}) are used to delimit a statement block; otherwise, a single statement is assumed.

Visual Basic .NET Visual C# .NET
If A = 5 ThenDoSomething()

DoSomethingAgain()

End If

If (a == 5){

DoSomething();

DoSomethingAgain();

}

or

if (a == 5)

DoSomething();

DoSomethingAgain(); //This is not part of

//the if statement.

Use of () vs. [ ]

Visual Basic .NET uses parentheses () to delimit array elements, function arguments, and property indexes.

Visual C# .NET uses parentheses () to delimit function arguments, and brackets ([]) to delimit array elements and property indexes.

Purpose Visual Basic .NET Visual C# .NET
Declare an array Dim a() As LongDim a(3, 5) as Integer int[] x = new int[5];
Initialize an array Dim a() As Long = {3, 4, 5} int[] x = new int[5] {1, 2, 3, 4, 5};
Reallocate array Redim n/a
Functions Arguments X= A(5)MySub (A, B, C) MySub(A, B, C);
Property Indexes Y = MyDataSet.Tables_ (“Author”).Rows(5)._Columns(“AuthorID”) Y = MyDataSet.Tables["Author"].Rows[5].Columns["AuthorID"]

Operators

The operators that are used in Visual Basic .NET and Visual C# .NET are quite different. The following table lists the main operators. This information can also be found in the Microsoft® Visual Studio .NETTM documentation.

  Operator Visual Basic .NET Visual C# .NET   Additive    
  Addition + +
  Subtraction - -
  Multiplicative    
  Multiplication * *
  Division / /
  Integer division \ / (depending on the operands)
  Modulus (division returning only the remainder) Mod %
  Exponentiation ^ n/a
  Assignment    
  Assignment =+= -= *= /* =+= -= *= /*
Integer division \= /= (depending on the operands)  
Concatenate &= +=  
Modulus n/a %=  
Left shift n/a <<=  
Right shift n/a >>=  
Bitwise AND n/a &=  
XOR n/a ^=  
OR n/a |=  
Relational and equality      
Less than < <  
Less than or equal to <= <=  
Greater than > >  
Greater than or equal to >= >=  
Equal = ==  
Not equal <> !=  
Compare two object reference variables Is ==  
Compare object reference type TypeOf x Is Class1 x is Class1  
Compare strings = == or String.Equals()  
Concatenate strings & +  
Shortcircuited Boolean AND AndAlso &&  
Shortcircuited Boolean OR OrElse ||  
Shift      
Left shift n/a <<  
Right shift n/a >>  
Scope resolution      
Scope resolution . ., base  
Postfix      
Type cast Cint, CDbl, …, CType (type)  
Member selection . .  
Postfix increment n/a ++  
Postfix decrement n/a  
Unary      
Indirection n/a * (unsafe mode only)  
Address of AddressOf & (unsafe mode only)  
Logical NOT Not !  
One’s complement Not ~  
Prefix increment n/a ++  
Prefix decrement n/a  
Size of type n/a sizeof  
Bitwise      
Bitwise NOT Not ~  
Bitwise AND And &  
Bitwise XOR Xor ^  
Bitwise OR Or |  
Logical      
Logical AND, OR And &&  
Logical OR Or ||  
Conditional      
Conditional IIf ?:  
Pointer to member      
Pointer to member n/a . (Unsafe mode only)  

Conditional Statements

The following table lists the differences in the conditional statements that Visual Basic .NET and Visual C# .NET use.

Conditional Statement Visual Basic .NET Visual C# .NET
Decision structure (selection) Select Case …, Case, Case Else, End Select switch, case, default,
Decision structure (if … then) If … Then, ElseIf … Then, Else, End If if, else
Loop structure (conditional) While… End While, Do [While, Until] …, Loop [While, Until] do, while, continue
Loop structure (iteration) For …, [Exit For,] NextFor Each …, [Exit For,] Next for, foreach
Control flow statement Exit, GoTo, Stop, End, Return, break, continue, goto, return,throw

Error Handling

Unstructured error handling is for backward compatibility. Visual Basic .NET supports both structured and unstructured error handling, but Visual C# .NET supports only structured error handling.

Purpose Visual Basic .NET Visual C# .NET
Structured error handling Try…
Catch

Finally

End Try

try, catch, finally,
throw
Unstructured error handling On Error GoTo …On Error Resume Next n/a

Overflow Checking

Visual Basic .NET has a project level setting to check for overflow. However, the checking can only be turned on and off at the project level, instead of at the level of an expression or a block of code. To turn overflow checking on and off, follow these steps:

1. On the Project menu, click Properties.

2. Under Configuration Properties, select Optimizations, and then select or clear Remove integer overflow checks.

Visual C# .NET statements can run in either a checked or an unchecked context. In a checked context, arithmetic overflow raises an exception error. In an unchecked context, arithmetic overflow is ignored and the result is truncated. This can be used on an expression or a block of code.

Parameter Passing

Visual Basic .NET uses ByVal for passing parameters by value, and uses ByRef for passing parameters by reference. Visual Basic .NET can also force parameters to be passed by value, regardless of how they are declared, by enclosing the parameters in extra parentheses. Visual Basic .NET also supports optional parameters, which are not available in Visual C# .NET.

Visual C# .NET does not have a way to pass reference types (objects) strictly by value. You can either pass the reference (basically a pointer) or a reference to the reference (a pointer to a pointer). Unmanaged Visual C# .NET methods can take pointers just like Visual C++ methods. To pass a parameter by reference, Visual C# .NET uses the ref keyword. To use a ref parameter, the argument must explicitly be passed to the method as a ref argument. The value of a ref argument is passed to the ref parameter.

Purpose Visual Basic .NET Visual C# .NET
Pass by value Public Sub ABC (ByVal y As Long)…

End Sub

ABC(x)

ABC((x))

void ABC(int x){

}

ABC(i);

Pass by reference Public Sub ABC(ByRef y As Long)…

End Sub

ABC(x)

void ABC(ref int x){

}

ABC(ref i);

Optional parameter Supported n/a

Late Binding

Both Visual Basic .NET and Visual C# .NET can implement implicit late binding through reflection. However, implementing late binding in Visual Basic .NET is much easier than in Visual C# .NET.

In Visual Basic .NET, as in Visual Basic 6.0, the Visual Basic compiler calls a helper method behind the scenes that uses reflection to obtain the object type. The arguments that are passed to the helper method cause the appropriate method to be invoked at run time. These arguments are the object on which to invoke the method, the name of the invoked method that is a string, and the arguments that are passed to the invoked method that is an array of objects. Additionally, you can implement late binding explicitly in code through reflection.

Imports System

Module Hello

Sub Main()

‘ Set up variable.

Dim helloObj As Object

‘ Create the object.

helloObj = new HelloWorld()

‘ Invoke the print method as if it was early bound

‘ even though it is really late bound.

helloObj.PrintHello(“Visual Basic Late Bound”)

End Sub

End Module

In Visual C# .NET, implementing late binding is more difficult than in Visual Basic .NET. Instead of having the compiler implement late binding, you must explicitly implement late binding in code by using reflection.

Handing Unmanaged Code

Visual C# .NET permits you to write unmanaged code. In unmanaged code, you can do things such as declare and operate on pointers, perform conversions between pointers and integral types, and take the address of variables. In a sense, writing unmanaged code is much like writing Visual C code in a Visual C# .NET program.

Because code that is written by using an unmanaged context cannot be verified to be safe, it is run only when the code is fully trusted. Do not use unmanaged context to try to write Visual C code in Visual C# .NET. Unmanaged code must be clearly marked with the modifier unsafe so that developers cannot use unmanaged features accidentally, and the execution engine works to make sure that unmanaged code cannot be run in a non-trusted environment. The scope of the unmanaged context extends from the parameter list to the end of the function, so pointers can also be used in the parameter list.

In Visual Basic .NET, you cannot write unmanaged code.

Keywords

The following table lists the keywords that Visual Basic .NET and Visual C# .NET use in several categories. This information can also be found in the Visual Studio .NET online documentation.

  Purpose Visual Basic .NET Visual C# .NET     Object Oriented Programming      
  Indicates a class constructor Public Class Class1Public Sub New(..)

MyBase.New

End Sub

End Class

Note: You have to call the base class constructor explicitly in Visual Basic .NET.

public class Class1{

public Class1(..)

{

}

….

}

Note: The call to the base class constructor (base()) is generated automatically by the compiler in Visual C# .NET if you do not include constructor initializers.

 
  Indicates a class destructorNote: The Destructor or Finalize method is called by garbage collection. Protected Overrides Sub Finalize()m_Gadget = Nothing

m_Gear = Nothing

MyBase.Finalize()

End Sub

public class Class1{

public ~Class1()

{

….

}

}

 
  Declares a class Class class  
  Indicates class inheritance Public Class AInherits B

End Class

public class A : B{

}

 
  Indicates that the class can only be inherited and cannot be instantiated MustInherit abstract  
  Indicates that the class cannot be inherited NotInheritable sealed  
  Calls your own implementation of the method instead of an overridden method in the derived class MyClass None  
  Refers to a base class from the derived class MyBase base  
  Declares a type-safe reference to a class method Delegate delegate  
  Indicates that the method or the property overrides the implementation in its base class Overrides override  
  Indicates that these methods have no implementation and must be implemented in derived classes MustOverride(in MustInherit

class)

abstract(in abstract

class)

 
  Indicates that the method or the property cannot be overridden in derived classes NotOverridableNote: By default, methods are not overridable. sealed  
  Indicates that the method or the property can be overridden in an inheriting class Overridable virtual  
  Overloads a procedure, a function, or a method Overloads None. Define functions with same name but different signatures.  
  Specifies that a variable can contain an object whose events you want to handle WithEvents No specific keyword  
  Specifies the events for which an event procedure will be called Handles (Event procedures can still be associated with a WithEvents variable by naming pattern.) n/a  
  Evaluates an object expression one time to access multiple members With objExpr<.member>

<.member>

End With

n/a  
  Refers to the current object Me This  
  Declares an enumerated type Enum…

End Enum

Enum  
  Declares an interface Interface interface  
  Implements an interface Implements class C1 : I1  
  Indicates an indexer Default Property public string this[int index]{

get {return List[index];}

set {List[index]=value;}

}

 
  Class Access Modifiers      
  Indicates that the modifier is accessible outside the project or the assembly Public public  
  Indicates that the modifier is accessible inside the assembly only Friend internal  
  Indicates that the modifier is accessible only in the project (for nested classes, in the enclosing class) Private private  
  Class Member Access Modifiers      
  Indicates that the modifier is accessible outside the class and the project Public public  
  Indicates that the modifier is accessible outside the class, but in the project Friend internal  
  Indicates that the modifier is only accessible in a class or a module Private private  
  Indicates that the modifier is accessible only to current and derived classes Protected protected  
  Indicates the union of Protected and Friend or Internal Protected Friend protected internal  
  Indicates that the members are shared across all instances Shared static  
  Miscellaneous Lifetime      
  Preserves the local variables for the procedure Static n/a  
  Other      
Calls the Windows API Declare statement use Platform Invoke  
Indicates a comment ‘, Rem //, /* */ for miltine comments,/// for XML comments  
Indicates a constant Const Const, readonly  
  Creates a new object New, CreateObject new
  Declares a function or a method with no return value Sub void
  Declares that an object can be modified asynchronously n/a volatile
  Declares a variable Private, Public, Friend, Protected, Static, Shared, Dim declarators (keywords include user-defined types and built-in types)
  Declares a variable explicitly Option Explicit None (All variables must be declared before use)
  Declares and raises an event Event, RaiseEvent event
  Declares a structure Structure…

End Structure

struct
  Defines a default property Default by using indexers
  Declares a null object Nothing null
  Declares a namespace Namespace…

End Namespace

Namespace{

}

  Indicates namespace usage Imports using
  Retrieves a character from a string GetChar Function [ ]
  Returns the address of a function AddressOf (For class members, this operator returns a reference to a function in the form of a delegate instance) delegate
  Tests for a null object Obj Is Nothing obj == null
  Tests for a database null expression IsDbNull n/a
  Threads primitives SyncLock lock

Conclusion

Based on your personal preference and past experience, you can use either Visual Basic .NET or Visual C# .NET to build solutions. Although differences do exist between the two languages, both languages use the .NET Framework common language runtime and are equally powerful. This document only briefly discusses the differences in syntax between Visual Basic .NET and Visual C# .NET. For more detailed information about these differences and other differences that exist between the two programming languages, see the Visual Studio .NET online help.

Posted in .NET | 1 Comment »

Keyboard Problems In Microsoft Virtual PC 2007

Posted by kiranpatils on December 4, 2007

HI All,

Today i have installed Microsft Virtual PC 2007. which is nice.

But in login screen i got stuck because when i have pressed CTRL+ALT+DELETE it shows my Windows XP os’s [Host OS] Task manager [What is this].

After sometime i got the entry. you have to press right ALT(means the ALT Key which is right side of your spacebar) and Delete means ALT+DELETE. that’s it I got the entry in it. But you are thinking why this stupid ALT+DELETE only i want esc+DELETE can i do that? yes you can..just go to Microsoft Virtual PC Console and from File->Options->keyboard and go to current host key textbox and press new key..magic this is now your Current Host key instead of Right ALT.

This is not end of keyboard problems other also When i am going to logging in my username was ABC#. but when i click shift+# it becomes epsilon in username textbox for login….as my habit i have searched in MS-VPC 2007’s documentation but it doesn’t have solution..than i gone to my other habit which is googling that also failed….At last my colleague found it’s solution actually the Regional settings are for English(U.K.) that’s why # sign .so solution is that if you want to type # in UK Regional Keyboard settings Type just press “|” key which is before your backspace key..that’s It…cool na??

Posted in Keyboard Problems In Microsoft Virtual PC 2007 | 2 Comments »