Monday, May 31, 2010
Can I Use Generics in Web Services?
for example:
public class MyWebService
{
[WebMethod]
public List<system.string> GetCities()
{
List<system.string> cities = new List<system.string>();
cities.Add("New York");
cities.Add("San Francisco");
cities.Add("London");
return cities;
}
}
Call WCF using transport layer security and SSL configured
<system.serviceModel>
<services>
<service behaviorConfiguration="returnFaults" name="TestService.Service">
<endpoint binding="wsHttpBinding" bindingConfiguration=
"TransportSecurity" contract="TestService.IService"/>
<endpoint address="mex" binding="mexHttpsBinding"
name="MetadataBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="returnFaults">
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceMetadata httpsGetEnabled="true"/>
<serviceTimeouts/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<wsHttpBinding>
<binding name="TransportSecurity">
<security mode="Transport">
<transport clientCredentialType="None"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<diagnostics>
<messageLogging logEntireMessage="true"
maxMessagesToLog="300" logMessagesAtServiceLevel="true"
logMalformedMessages="true" logMessagesAtTransportLevel="true"/>
</diagnostics>
</system.serviceModel>
//Contract Description
[ServiceContract]
interface IService
{
[OperationContract]
string TestCall();
}
//Implementation
public class Service:IService
{
public string TestCall()
{
return "You just called a WCF webservice On SSL
(Transport Layer Security)";
}
}
//Tracing and message logging
In the above ServiceModel configuration, there are two end points:
1. One with contract TestService.IService: In this, binding is configured to have transport layer security , see inside the
2. One with contract IMetadataExchange: this is also configured to an HTTPS call. If you see the binding it is mexHttpsBinding, and in the service behaviors section, httpsGetEnabled is used, here I tried to even secure the metadata publishing through WSDL.
To configure this Web.config file you can use SvcConfigEditor.exe which is located in
C:\program files\microsoft sdks\windows\v6.0\bin\svcconfigeditor.exe
If you try to run the code from Visual Studio then you get an exception as shown below:
"Could not find a base address that matches scheme HTTPS for the endpoint with binding WSHttpBinding. Registered base address schemes are [HTTP]."
So first configure the website on SSL. To get an idea on how to configure SSL, you can go through this. Make sure that when you configure the SSL, the certificate CN value should be exactly the same as the URL of the website. For example, if your webservice address is http:\\www.example.com, then issue a certificate on the name : CN = http:\\www.example.com.
Don't forget to host an entry in the hosts file c:\windows\system32\drivers\etc\hosts. If you want to put this on localhost then just enter the following in the host file 127.0.0.1 www.example.com.
Configure www.example.com as the header value in the website properties on port 80. Once you are done with SSL, you will access the webservice through the web browser as https://www.example.com/service.svc. On this page you will have the HTTPS URL for WSDL .
I have even enabled tracing and message logging on the webservice. To view the service log just use svctraceviewer.exe by loading service.log file in this. See the
Note that I have not put any certificates to run this sample. So if you want to run this sample, then generate a certificate, install it on IIS as per the instructions above and run it though the browser.
Call a Web Service Using SSL from ASP.NET
This article includes the following steps:
* Step 1. Install Server Certificates on the Web Server
* Step 2. Create a Simple Web Service
* Step 3. Configure the Web Service Virtual Directory to Require SSL
* Step 4. Test the Web Service Using a Browser
* Step 5. Install the Certificate Authority's Certificate on the Client Computer
* Step 6. Develop a Web Application to Call the Serviced Component
Step 1. Install Server Certificates on the Web Server
For information about installing Web server certificates on a Web server
Step 2. Create a Simple Web Service
To create a simple Web service on the Web service host computer
- Start Visual Studio .NET and create a new C# ASP.NET Web Service application called SecureMath.
- Rename service1.asmx as math.asmx.
- Open math.asmx.cs and rename the Service1 class as math.
- Add the following Web method to the math class.
[WebMethod]
public long Add(long operand1, long operand2)
{
return (operand1 + operand2);
} - To create the Web service, click BuildSolution on the Build menu.
Step 3. Configure the Web Service Virtual Directory to Require SSL
Your Web service runs on Internet Information Services (IIS) and relies on IIS to provide SSL support.
This procedure assumes that you have a valid server certificate installed on your Web server. For more information about installing Web server certificates
To use IIS to configure your Web service's virtual directory for SSL
- On the Web service host computer, start IIS.
- Navigate to the SecureMath virtual directory.
- Right-click SecureMath, and then click Properties.
- Click the Directory Security tab.
- Under Secure communications, click Edit.
If Edit is unavailable, it is likely that a Web server certificate is not installed.
- Select the Require secure channel (SSL) check box.
- Click OK, and then OK again.
- In the Inheritance Overrides dialog box, click Select All, and then click OK to close the SecureMath properties dialog box.
This applies the new security settings to all subdirectories in the virtual directory root.
Step 4. Test the Web Service Using a Browser
This procedure ensures that the Web server certificate is valid and has been issued by a Certification Authority (CA) that is trusted by the client computer.
To call the Web service using SSL from Internet Explorer
- Start Internet Explorer on the client computer and browse (using HTTPS) to the Web service. For example:
https://WebServer/securemath/math.asmx
The Web service test page should be displayed by the browser.
- If the Web service test page is displayed successfully, close Internet Explorer and go to Procedure 5, "Develop a Web Application to Call the Serviced Component."
- If the Security Alert dialog box, as illustrated in Figure 1, is displayed, click View Certificate to see the identity of the issuing CA for the Web server certificate. You must install the CA's certificate on the client computer. This is described in Procedure 4, "Install the Certificate Authority's Certificate on the Client Computer.
Step 5. Install the Certificate Authority's Certificate on the Client Computer
This procedure installs the issuing CA's certificate on the client computer as a trusted root certificate authority. The client computer must trust the issuing CA in order to accept the server certificate without displaying the Security Alert dialog box.
If you use Microsoft Certificate Services as a CA within your Windows domain
Perform this procedure only if your Web server certificate was issued by a Microsoft Certificate Services CA. Otherwise, if you have the CA's .cer file, go to Step 8.
- Start Internet Explorer and browse to http:// hostname/certsrv, where hostname is the name of the computer where Microsoft Certificate Services that issued the server certificate is located.
- Click Retrieve the CA certificate or certificate revocation list, and then click Next.
- Click Install this CA certification path.
- In the Root Certificate Store dialog box, click Yes.
- Browse to Web service using HTTPS. For example:
https://WebServer/securemath/math.asmx
The Web service test page should now be correctly displayed by the browser, without a Security Alert dialog box.
You have now installed the CA's certificate in your personal trusted root certificate store. To be able to call the Web service successfully from an ASP.NET page, you must add the CA's certificate to the computer's trusted root store.
- Repeat Steps 1 and 2, click Download CA certificate, and then save it to a file on your local computer.
- Now perform the remaining steps, if you have the CA's .cer certificate file.
- On the taskbar, click Start, and then click Run.
- Type mmc, and then click OK.
- On the Console menu, click Add/Remove Snap-in.
- Click Add.
- Select Certificates, and then click Add.
- Select Computer account, and then click Next.
- Select LocalComputer: (the computer this console is running on), and then click Finish.
- Click Close, and then OK.
- Expand Certificates (Local Computer) in the left pane of the MMC snap-in.
- Expand Trusted Root Certification Authorities.
- Right-click Certificates, point to All Tasks, and then click Import.
- Click Next to move past the Welcome dialog box of the Certificate Import Wizard.
- Enter the path and filename of the CA's .cer file.
- Click Next.
- Select Place all certificates in the following store, and then click Browse.
- Select Show physical stores.
- Expand Trusted Root Certification Authorities within the list, and then select Local Computer.
- Click OK, click Next, and then click Finish.
- Click OK to close the confirmation message box.
- Refresh the view of the Certificates folder within the MMC snap-in and confirm that the CA's certificate is listed.
- Close the MMC snap-in.
Step 6. Develop a Web Application to Call the Web Service
This procedure creates a simple ASP.NET Web application. You will use this ASP.NET Web application as the client application to call the Web service.
To create a simple ASP.NET Web application
- On the Web service client computer, create a new C# ASP.NET Web application called SecureMathClient.
- Add a Web reference (by using HTTPS) to the Web service.
- Right-click the References node within Solution Explorer, and then click Add Web Reference.
- In the Add Web Reference dialog box, enter the URL of your Web service. Make sure you use an HTTPS URL.
Note If you have already set a Web reference to a Web service without using HTTPS, you can manually edit the generated proxy class file and change the line of code that sets the Url property from an HTTP URL to an HTTPS URL. - Click Add Reference.
- Open WebForm1.aspx.cs and add the following using statement beneath the existing using statements.
using SecureMathClient.WebReference1;
- View WebForm1.aspx in Designer mode and create a form like the one illustrated in Figure 2 using the following IDs:
- operand1
- operand2
- result
- add

Figure 2. WebForm1.aspx form
- Double-click the Add button to create a button-click event hander.
- Add the following code to the event handler.
private void add_Click(object sender, System.EventArgs e)
{
math mathService = new math();
int addResult = (int) mathService.Add( Int32.Parse(operand1.Text),
Int32.Parse(operand2.Text));
result.Text = addResult.ToString();
} - On the Build menu, click BuildSolution.
- Run the application. Enter two numbers to add, and then click the Add button.
The Web application will call the Web service using SSL.
Tuesday, May 25, 2010
C# 3.0 Features
Object Initializers
using System;
class MyClass {
public int Count;
public string Str;
}
class ObjInitDemo {
static void Main() {
// Construct a MyClass object by using object initializers.
MyClass obj = new MyClass { Count = 100, Str = "Testing" };
Console.WriteLine(obj.Count + " " + obj.Str);
}
}
Collection Initializers
List<Customer> listOfCustomers =Automatic Properties
new List<Customer> {
{ Id = 1, Name="Dave", City="Sarasota" },
{ Id = 2, Name="John", City="Tampa" },
{ Id = 3, Name="Abe", City="Miami" }
};
public class Customer {Query Expression Translation
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
This is just a bit of syntatic sugar, because the query expression gets translated using Query Expression Translation into extension methods that are invoked behind the scenes. The .Where and .Select Methods are extension methods of IEnumerable
var query = listOfCustomers .Where(c => c.City.Equals("Sarasota")) .Select(c => new {c.Name, c.City});
Lambda Expressions
Lambda Expressions are shown above to ease the pain of typing the very verbose anonymous delegates:
c => c.City.Equals("Sarasota")
avoids
delegate(Customer c) { return c.City.Equals("Sarasota"); }
Extension Methods
static class StringExtensions
{
public static string AppendMyNameToString(this string value)
{
return value + " Marlon";
}
}
Now I can do the following code:
Console.WriteLine("Hello".AppendMyNameToString());
LINQ
I will not go into much detail on this topic because it's quite a large subject. Basically LINQ is a declarative way to query data. So instead of being imperative and using loops andif statements, you can tell C# what you want and LINQ will go ahead and build that data for you. Let's take for example, you have a list of strings and you want to get all strings that start with the letter "s".
string[] list = new string[] { "test", "marlon", "ema" };C# 2.0
ListC# 3.0
IEnumerableThe above code is equivalent to this:
IEnumerable
Anonymous Types
anonymous types allow you to create a type on-the-fly at compile time. The newly created type has public properties and backing fields defined for the members you initialize during construction. For example, consider the following line of code: var obj=new{ID=1,FirstName="Thiru",LastName="Thangarathinam"};
What is LINQ
LINQ adds to C# the ability to generate queries for any LINQ-compatible data source.
Furthermore, the syntax used for the query is the same, no matter what data source is used.
This means that the syntax used to query data in a relational database is the same as that used to query data stored in an array
Object Initializers in C# 3.0
class MyClass {
public int Count;
public string Str;
}
class ObjInitDemo {
static void Main() {
// Construct a MyClass object by using object initializers.
MyClass obj = new MyClass { Count = 100, Str = "Testing" };
Console.WriteLine(obj.Count + " " + obj.Str);
}
}
This produces the following output:
100 Testing
As the output shows, the value of obj.Count has been initialized to 100 and the value of
obj.Str has been initialized to “Testing”. Notice, however, that MyClass does not define any
explicit constructors, and that the normal constructor syntax has not been used. Rather, obj
is created using the following line:
MyClass obj = new MyClass { Count = 100, Str = "Testing" };
ADO.NET Entity Framework
while allowing the Entity Framework to provide the data access plumbing code that would otherwise need to be written and maintained.
TOP NEW FEATURES
Custom Code-Gen: Use Visual Studio T4 templates to fully customize the generation of POCO or Entity Classes.
POCO: Support for Plain Old CLR Objects, or POCO types that do not need to:
o Inherit from a required base class
o Implement a required interface
o Include metadata or mapping attributes on type members
Model-First: Create your Entity Data Model and rom that model generate DDL to create the database.
Deep Support for Established Patterns and Practices:
The Entity Framework enables customers to develop using a range of established patterns and practices from Data Driven approaches to Domain Driven or Test Driven design patterns.
Simplicity
The Entity Framework is a core part of the .NET Framework making it simple to create data driven applications that “just work”, whether developing with WPF, Silverlight, ASP.NET, etc.
Entity Framework Designer
Use the Entity Designer in Visual Studio to generate an Entity Data Model from a Database and setup the mapping between application specific objects and database objects. Create your Entity Data Model using the Entity Designer and from that model generate DDL to create the database.
ASP.NET
Use ASP.NET Dynamic Data or MVC with the Entity Data Source Control and the Entity Framework to quickly create data driven web applications.
Silverlight
Use Silverlight with the Entity Framework and ADO.NET Data Services to quickly create data driven Rich Internet Applications (RIA).
Rich Programming Model
The Entity Framework offers a rich,extensible programming model to facilitate building data driven applications. Persistence Ignorance The Entity Framework provides full support for developers to choose how they handle persistence. This includes persistence ignorance, prescribed code and custom generated code to match any developers approach and methodology.
First Class LINQ Support
LINQ to Entities provides flexible, strongly typed queries against the Entity Framework in order to return qury results as strongly typed CLR data objects. Simplify coding by taking advantage of Visual Studio’s IntelliSense support in strongly typed classes.
Foreign Keys
Use Foreign Keys and Independent Associations to relate your entities to one another.

Map Tables to Entities
Map tables in a database to application-specific objects using the mapping capabilities of the ADO.NET Entity Framework. Map multiple related tables to a single entity and reduce code complexity.
Simplify modeling and mapping
Use the Entity Designer to generate models, create& edit models, validate models and mappings, and generate a database from your model
Friday, May 21, 2010
Important Urls for .NET
-----------------
http://msdn.microsoft.com/en-us/library/aa480210.aspx
http://www.codeproject.com/KB/aspnet/WCF.aspx
http://www.dotnetfunda.com/interview/ShowCatQuestion.aspx?category=74
OOPS
----------
http://www.codeproject.com/KB/architecture/OOP_Concepts_and_manymore.aspx
http://www.objectmentor.com/omSolutions/oops_what.html
C#
---------------
http://blogs.msdn.com/csharpfaq/
http://www.dotnetfunda.com/interview/ShowCatQuestion.aspx?category=34
http://blogs.crsw.com/mark/articles/252.aspx
ASP.net
------------------------------------
http://blogs.crsw.com/mark/articles/254.aspx
http://www.careerride.com/ASPNet-Questions.aspx
http://www.codeproject.com/KB/aspnet/ASPNETFAQs26-50.aspx
SQL SERVER
-------------------------------------------
http://blog.sqlauthority.com/2007/04/21/sql-server-interview-questions-and-answers-complete-list-download/
http://www.techbaba.com/faqs/sql+server+question+answers.aspx
DESIGN PATTERNS
---------------------------------------
http://www.dotnetuncle.com/Design-Patterns/dot-net-design-pattern-interview-questions.aspx
http://www.dotnetspark.com/kb/171-design-pattern-interview-questions-part.aspx
http://www.dotnetfunda.com/interview/showcatquestion.aspx?category=44
Thursday, May 20, 2010
Interface vs Abstract Class
- A class can implement any number of interfaces but a subclass can at most use only one abstract class.
- An abstract class can have non-abstract Methods(concrete methods) while in case of Interface all the methods has to be abstract.
- An abstract class can declare or use any variables while an interface is not allowed to do so.
Design Patterns (Gang of Four)
Abstract Factory - Creates an instance of several families of classes
Builder - Separates object construction from its representation
Factory - Method Creates an instance of several derived classes
Prototype - A fully initialized instance to be copied or cloned
Singleton - A class of which only a single instance can exist
Structural Patterns
Adapter - Match interfaces of different classes
Bridge - Separates an object’s interface from its implementation
Composite - A tree structure of simple and composite objects
Decorator - Add responsibilities to objects dynamically
Facade - A single class that represents an entire subsystem
Flyweight - A fine-grained instance used for efficient sharing
Proxy - An object representing another object
Behavioral Patterns
Chain of Resp. - A way of passing a request between a chain of objects
Command - Encapsulate a command request as an object
Interpreter - A way to include language elements in a program
Iterator - Sequentially access the elements of a collection
Mediator - Defines simplified communication between classes
Memento - Capture and restore an object's internal state
Observer - A way of notifying change to a number of classes
State - Alter an object's behavior when its state changes
Strategy - Encapsulates an algorithm inside a class
Template - Method Defer the exact steps of an algorithm to a subclass
Visitor - Defines a new operation to a class without change
Tuesday, May 18, 2010
c# 4.0 Features
- Dynamic Typed Objects
- Optional and Named Parameters
- Improved COM Interoperability
- Co- and Contra-Variance
Dynamic lookup
Dynamic lookup allows you to write method, operator and indexer calls, property and field accesses, and even object invocations which bypass the C# static type checking and instead gets resolved at runtime.
object calc = GetCalculator();
Type type = calc.GetType();
object result = type.InvokeMember(
"Add",
BindingFlags.InvokeMethod,
null,
new object[] { 10, 20 });
int sum = Convert.ToInt32(result);
With the C# 4.0 we would simply write the following code:
dynamic calc = GetCalculator();
int sum = calc.Add(10, 20);
In the above example we are declaring a variable, calc, whose static type is dynamic. We’ll then be using dynamic method invocation to call the Add method and then dynamic conversion to convert the result of the dynamic invocation to a statically typed integer.
Named and optional parameters
Parameters in C# can now be specified as optional by providing a default value for them in a member declaration. When the member is invoked, optional arguments can be omitted. Furthermore, any argument can be passed by parameter name instead of position.
public StreamReader OpenTextFile(
string path,
Encoding encoding = null,
bool detectEncoding = false,
int bufferSize = 1024) { }
COM specific interop features
Dynamic lookup as well as named and optional parameters both help making programming against COM less painful than today. On top of that, however, we are adding a number of other small features that further improve the interop experience.
When you work with COM interop methods, you had to pass a reference to Missing.Value for unneeded parameters, like the following:
object filename = "test.docx";
object missing = System.Reflection.Missing.Value;
doc.SaveAs(ref filename,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);
Now, in C# 4.0 you can only write:
doc.SaveAs(filename);
Variance
It used to be that an IEnumerable
Generics with C# 4.0 now support safe co-variance and contra-variance through the use of the in (contra-variant) and out (co-variant) contextual keywords. Let’s take a look at how this changes the definition of the IEnumerable
public interface IEnumerable<out T>
{
IEnumerator
}
public interface IEnumerator<out T>
{
T Current { get; }
bool MoveNext();
}
Given that an IEnumerable collection is read only, there is no ability specified within the interface to insert new elements, it is safe to treat a more derived element as something less derived. With the out contextual keyword we are contractually affirming that IEnumerable
IEnumerable<string> strings = GetStrings();
IEnumerable<object> objects = strings;
Using the in contextual keyword we can achieve safe contra-variance, that is treating something less derived as something more derived.
public interface IComparer<in T>
{
int Compare(T x, T y);
}
Given that IComparer
IComparer<object> objectComparer = GetComparer();
IComparer<string> stringComparer = objectComparer;
It is important to notice that co-variance in IEnumerable refers to the fact that its Current property can return a string instead of an object as output, while contra-variance in IComparer