Thursday, July 30, 2009

WCF : Key set does not exist



Recently i was working on installation of certificates for creating the a development environment for WCF using SSL. After creating the certificate and installing i came across the error like

"Key set does not exist"

Root Cause : The ASPNET and Network Services does not have access to the folder where the certificates are stored.

Resolution : Give access to ASPNET and Network Services accounts to the "MachineKeys" folder in "Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA" of the root drive.




This would resolve the issue . Happy Coding :)

Friday, July 24, 2009

SQL Date Formats



Here is the list of the Date formats available in SQL Server

Thursday, July 23, 2009

List to List conversion using LINQ




One of my requirment was to get the List object from a source and change it to another list with removing some of the properties. Here is how i have achived it

Project class
public class Project
{
public string ProjectCode { get; set; }
public string ProjectName { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string ManagerId { get; set; }
public string ClientId { get; set; }
}

Setting values to ProjectClass

List lstProject = new List
{ new Project { ProjectCode = "1" ,ProjectName ="CIS1", StartDate = "1/1/2000" ,EndDate = "2/2/2000" ,ManagerId ="MG1" ,ClientId="CL1"},
new Project { ProjectCode = "2" ,ProjectName ="CIS2", StartDate = "1/1/2000" ,EndDate = "2/2/2000" ,ManagerId ="MG2" ,ClientId="CL2"},
new Project { ProjectCode = "3" ,ProjectName ="CIS3", StartDate = "1/1/2000" ,EndDate = "2/2/2000" ,ManagerId ="MG3" ,ClientId="CL3"},
new Project { ProjectCode = "4" ,ProjectName ="CIS4", StartDate = "1/1/2000" ,EndDate = "2/2/2000" ,ManagerId ="MG4" ,ClientId="CL4"},
new Project { ProjectCode = "5" ,ProjectName ="CIS5", StartDate = "1/1/2000" ,EndDate = "2/2/2000" ,ManagerId ="MG5" ,ClientId="CL5"}
};

Converting the List to another List with some filters

List lstOutputProjects1 = (from projectlist in lstProject
select new Project
{
ProjectName = projectlist.ProjectName,
StartDate = projectlist.StartDate,
EndDate = projectlist.EndDate,
ManagerId = projectlist.ManagerId,
ClientId = projectlist.ClientId
}).ToList();

Hope this Helps :)

Tuesday, July 21, 2009

Avoiding the SSL Security Information pop-up message




On the administration consoles, some users get the SSL security information pop-up message with each page turn. How can we prevent this?
Users may see a security message like the one below when working with a site that uses a secure socket layer (SSL):
Security Information This message contains both secure and nonsecure items. Do you wish to display the non secure items? Message Information: Downloading non-secure content from a secure Web site. The Web site you are viewing is a secure site. It uses a security protocol such as SSL (Secure Sockets Layer) or PCT (Private Communications Technology) to secure the information you send and receive. When sites use a security protocol, information that you provide, such as your name or credit-card number, is encrypted so that it can’t be read by other people. However, this Web page also contains items that do not use this secure protocol. Given what you know about this Web site and your computer, you must decide whether to continue working with this site. If you do not feel confident about working with this site, click No.


Root Cause

This message will typically display in the following situations:
A site utilizes SSL, but some items referenced on the site, such as images hosted on other servers, are not SSL protected. In this case, the message is indicating that not all callouts are SSL protected.
The user moves from a site that uses Secure Socket Layer (SSL) to one that does not. If SSL is used, the URL begins with https instead of http. The additional "s" in the URL indicates the SSL. Therefore, the message lets the user know that they are leaving an SSL-protected site.


Temporary solution to Block the Popup

Users may not get the security message if they have previously clicked an option that states "Don't warn me again..." or "Always trust..." In addition, users can configure their browsers to not display these alerts. For example, in the case of mixed content messages, users can turn off the pop-up message through the path: Internet Explorer > Tools > Internet Options > Security > Custom Level > Miscellaneous > Display Mixed Content and disable the setting.
As a result, if the user sees the “Don’t warn me again”-type of option, checking this box is the easiest way to avoid multiple warning messages. If your secure site includes a redirect, you may want to verify that the redirect goes to an SSL-protected site that has a URL beginning with https.
If you suspect non-secured images or links are include on your RightNow pages, you should check the files below for any links or references to non-secure items:
home_top.phph
home_bottom.phph
top.phph
bottom.phph
head.phph
Removing the links to non-secure items will prevent the message from displaying.

Reference : http://crm.rightnow.com/app/answers/detail/a_id/2009

Retrieving Username in WCF server Side in wsHttpBinding




While using custom validation in WCF using "UserNamePasswordValidator" every time we make a call to the service user will be authenticated with the Validate (.....) Method. But after authentication how do we retrive the username . Write the below code to retrive the UserName while you use wsHttpBinding.


OperationContext objOpeContext = OperationContext.Current;
ServiceSecurityContext objSSContext = objOpeContext.ServiceSecurityContext;
string strUserName = objSSContext.PrimaryIdentity.Name;


The strUserName will provide you the userName who is making the call.

More info available @ http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/0c69f2d3-3346-4cad-90f5-87ff34aca9cf/

Monday, July 20, 2009

Hosting a WCF Service Library in IIS



STEP 1
Create your service library project and code up your service. I am assuming that you know how to do this. For my example I am simply going to use what comes out of the box when you create a new service library project in Visual Studio 2008. To follow along create a new service library project in Visual Studio 2008 and name it HostingServiceLibraryIIS.

Step 2
create an svc file (use text file as the type) in the project named whatever you like. I will name mine “sample.svc”.

Add this single line to the top of the file:
<% ServiceHost Service=”HostingServiceLibraryIIS.Service1” %>
where your class that holds your service implementation is listed in place of "HostingServiceLibraryIIS.Service1".


Step 3
Add a configuration file to your project and name it web.config. Paste the contents of the "system.serviceModel" section from the App.config file that was included by default in the library project into the web.config file between the opening and closing "configuration" tags.

Step 4
Create a new application in IIS and point it at the folder that contains your project files. Make sure that your project is building to the bin folder and not bin/Debug or bin/Release.

That’s it! You should now be able to browse to your svc file in IIS and see your service in action.

WCF : A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider



While working on WCF using secured connection i came across the following error

"A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider"

Here is my application scnerio
1. WCF services libraries hosted in IIS
2. Client is ASP.Net Client

Got it resolved by following the below steps

Step 1
Creating an SSL Certificate
To create a self-signed certificate to install in IIS as the SSL certificate, you can issue the following makecert.exe command from the Visual Studio 2005 command line:

makecert -r -pe -n "CN=localhost" -ss my -sr LocalMachine -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 c:\localhost.cer

The subject name “localhost” makes it possible to browse without errors to http://localhost or any path relative to it. The subject name of the SSL certificate must match the domain or machine name used in the path to access the site. If you used your machine name to browse to Web sites on your machine, for example
http://xyz/, you’d create the certificate with the subject name “CN=xyz”.

Step 2
Creating a Secure Messaging Certificate
To create a certificate for use in Web service message exchanges, you can give the certificate any relevant name. I tend to use the following names for various samples I create:
SubjectKey (for client applications)
RPKey (for target service applications)
IPKey (for identity provider services such as a security token service [STS])

You can use subject names that are meaningful to your applications. The syntax would be essentially the same for makecert.exe, with the exception of the subject name and certificate output filename:

makecert.exe -r -pe -n "CN=RPKey" -ss my -sr LocalMachine -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 c:\rpkey.cer


Step 3
Exporting the Certificate
The goal is to export a .pfx file (the key pair) and a .cer file (the public certificate) for later use. The .cer file is generated in the directory you specified in the makecert.exe command. The .pfx file can be exported from the Certificates snap-in tool as follows:
Because the certificate is generated to enable exporting the private key, you can export it using the Certificates console. Open the Certificates snap-in, expand the CurrentUser Personal store (assuming it was created in currentuser), and select All Tasks Export
Follow the steps in the wizard and be sure to select “Yes, export the private key”, and “Delete the private key if the export is successful”. Provide a password to protect the key upon export to the .pfx file.
Now you have a .pfx and .cer file ready to use for SSL or secure messaging.

Step 4
During development you may need to test applications that require SSL. If you create a certificate using makecert.exe, you can use the resulting key pair as the SSL certificate. Here are the steps to accomplish this:
1) Import the localhost.pfx certificate to the Local Machine Personal store. You can do this from the Certificates snap-in by right-clicking on the Personal store and selecting Import. You’ll be asked to provide the key pair password you used when exporting earlier.
2) Next, open the console for Internet Information Services (IIS) from Control Panel Administrative Tools.
3) Open the Properties dialog for the default Web site and select Server Certificate from the Directory Security tab.
4) Choose Assign an existing certificate. You’ll be presented with keys from the Local Machine Personal store; the localhost certificate should be listed. Select it.

(Please doble click on the IIS certificate to see whether the certificate is valid or not. if not valid you will find the error message there itself.

Before you start opening ASP.NET Web sites with SSL enabled, it’s a good idea to test the SSL certificate to verify the trust chain. You can use the IIS Diagnostic Toolkit to do this. Download and install the toolkit from http://www.microsoft.com/downloads/details.aspx?familyid=9BFA49BC-376B-4A54-95AA-73C9156706E7&displaylang=en. Then, from the Start menu find the program group for SSL Diagnostics and launch the SSL Diagnostics tool. You should be able to see the result in the grid itself

A test certificate will fail this test with the error: “A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider.” That’s because the certificate was not issued by a provider installed in the Trusted Root Certification Authorities store. This problem will be solved if you import the localhost.cer file into Local Machine Trusted Root Certification Authorities.


Step 5
App.config file changes










Since the services are hosted in IIS replicate the above changes to web.config file also.


Step 6
Create a class inherating from "UserNamePasswordValidator ". Please note to add the below libraries

using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.ServiceModel;


public class ServiceValidator:UserNamePasswordValidator
{
public override void Validate(string strUserName, string strPassword)
{
if (string.IsNullOrEmpty(strUserName))
throw new ArgumentNullException("Invalid UserName");
if (string.IsNullOrEmpty(strPassword))
throw new ArgumentNullException("Invalid Password");
if (!ValidateUser(strUserName, strPassword))
throw new SecurityTokenException("Invalid userName or Password");
}
private bool ValidateUser(string strUserName, string strPassword)
{
if (strUserName == "Test1" && strPassword == "1Test")
return true;
else
return false;
}
}

After the changes in the web.config file and the code changes, every service request will validate the user against the credentials passed from the slient.

Step 7
Now pass the UserName and Password from the client along with the client proxy, while making a call to the service

//Here localhost.ProjectServicesClient is the proxy Name
localhost.ProjectServicesClient objProj = new
localhost.ProjectServicesClient();
objProj.ClientCredentials.UserName.UserName = "Test1";
objProj.ClientCredentials.UserName.Password = "1Test
";

Now with Every call to the service these credentials will be validated.

Saturday, July 18, 2009

Cannot find the X.509 certificate



Recently while working on the WCF services i came across the error "Cannot find the X.509 certificate". I searched a bit but none of the answers were matching my scenario. Here is my application details.

1. Service is WCF service Library
2. Services are hosted in IIS 6.0
3. Client is ASP.Net calling these services.

I have installed the cerficates and changed the configurations in app.config file. The most important thing is when you are hosting it IIS you also need to change the Web.config File accordingly. Please replicate the same to web.config file.

Though of putting it here so that someone should not waste 1 or 2 hour finding why is it not working as I did :)

Thursday, July 16, 2009

makecert.exe error: Can't create the key of the subject WCF



Recetly I struggeld to use the makecert tool since it was showing the below error.
This was happening even after the Network Services has full access to the "C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys" folder.
Some how i found it out some where how to fix this
Can't create the key of the subject ('')

Each time I tried, the GUID would change or the Name will change.

I'm not sure why it is happening, but I did find a workaround. The directions I was following were to create the certificate in the "LocalMachine" certificate store using the following command:

makecert.exe -sr LocalMachine -ss MY -a sha1 -n CN=Client -sky exchange -pe

After some trial and error I discovered I was able to create the certificate in the current user store instead using the following command:

makecert.exe -sr CurrentUser -ss MY -a sha1 -n CN=Client -sky exchange -pe

I thought I would post this message to hopefully save others the effort.
Note to the makecert developers: Please provide more useful error messages.

UPDATE:
I discovered the source of the problem! For some reason, I did not have the appropriate permissions to the directory where the certificates are stored. If you are getting the same error that I was getting, try granting your account (or the admin group, etc.) full control permission to the following directory:

Please try this link for complete solution

http://dotnetclr.blogspot.com/2009/07/wcf-certificate-chain-processed-but.html