anandj123′s Blog

April 24, 2009

How to do WCF UserName token authentication with dynamic proxy for test driven development (TDD)

Filed under: Uncategorized — anandj123 @ 2:52 pm

Problem definition:

Previously I have linked to a website which describes in detail how to enable your WCF applications for username tokens authentication. That article went thru the setup of username token authentication using configuration files and client proxies. That is alright if you want to generate client proxies and use in your client application.

For testability reasons (which I will describe) we need to be able to use dynamic proxies for WCF services. I had to search a few places to gather all the required information to do this. Here I will describe how it can be done from a test driven development (TDD) methodology standpoint.

Approach/Solution:

In the example I have used a classical MVC pattern with service implementation for retrieving the model. At a high level the complete data flow is represented as:

 

I am just going to explain about the Web-server layer where the MVC pattern and WCF dynamic proxy resides. Maybe later I can go explain the other tiers and some of their nice features.

I created a View like the following:

public interface ISearchUserView
{
string SystemTextBox {get; set;}
string HostTextBox { get; set; }
string BankTextBox { get; set; }
string PathTextBox { get; set; }
ArrayList DataFormatDropDownList { get; set; }
ArrayList TradingMethodDropDownList { get; set; }
GenericCollection<UserData> UserGridView { set; }
}

 The implementation of the view is not important for this article, so I will leave that as well for now.

Then I created a controller which holds the view.

public class SearchUserController
{
 
private IDataService _service = null;
private Views.ISearchUserView _view = null;
public Views.ISearchUserView View
{
get { return _view; }
set { _view = value; }
}

 

Now the relevant parts are the following code:


public SearchUserController(Views.ISearchUserView view)
{
View = view;
 

WSHttpBinding binding = new WSHttpBinding(“WSHttpBinding_IDataService”);
EndpointAddress address = new EndpointAddress (new Uri(“http://localhost:8731/Web.Service/DataService/”),
new DnsEndpointIdentity(“MyServerCert”));

ChannelFactory<IDataService> service = 
new ChannelFactory<IDataService>(binding, address);
 
// Add the user name token to the request, these should come from the config file

// where we should encrypt them

service.Credentials.UserName.UserName = “test”;
service.Credentials.UserName.Password = “test”;
 
// Custom SSL validation of the server certificate,

// this we don’t need in production.

// in dev the cert is really not valid so to bypass the certificate validation

// we need custom validation here.

service.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom;
service.Credentials.ServiceCertificate.Authentication.CustomCertificateValidator = new MyX509Validator();
 
_service = service.CreateChannel();
}
 
// Dependency injection
public SearchUserController(IDataService service, Views.ISearchUserView view)
{
_service = service;
_view = view;
}

 Let me go thru each line of the code.

public SearchUserController(Views.ISearchUserView view)

This is a constructor that I am overriding which accepts a view, nothing special.

WSHttpBinding binding = new
WSHttpBinding(“WSHttpBinding_IDataService”);

Now we need to define the binding properties in the client side to connect to the server. The server is an implementation of the following ServiceContract.

[ServiceContract]
public interface IDataService
{
[OperationContract]
GenericCollection<UserData> GetUsers(string bankName);
}

 The binding is defined in the web.config file of the web-project as:

<!– WCF binding configurations –>
    <system.serviceModel>
        <bindings>
            <wsHttpBinding>
                <binding name=WSHttpBinding_IDataServicecloseTimeout=00:01:00
openTimeout=00:01:00receiveTimeout=00:10:00sendTimeout=00:01:00
bypassProxyOnLocal=falsetransactionFlow=falsehostNameComparisonMode=StrongWildcard
maxBufferPoolSize=524288maxReceivedMessageSize=65536
messageEncoding=TexttextEncoding=utf-8useDefaultWebProxy=true
allowCookies=false>
                    <readerQuotas maxDepth=32maxStringContentLength=8192maxArrayLength=16384
maxBytesPerRead=4096maxNameTableCharCount=16384 />
                    <reliableSession ordered=trueinactivityTimeout=00:10:00
enabled=false />
                    <security mode=Message>
                        <transport clientCredentialType=BasicproxyCredentialType=Nonerealm=“” />
                        <message clientCredentialType=UserNamenegotiateServiceCredential=truealgorithmSuite=DefaultestablishSecurityContext=true />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
    </system.serviceModel>

 Most of the configuration entries are not important at this point. Only thing that is worth pointing out is the security settings.

                    <security mode=Message>

                        <transport clientCredentialType=BasicproxyCredentialType=Nonerealm=“” />

                        <message clientCredentialType=UserName“  negotiateServiceCredential=truealgorithmSuite=DefaultestablishSecurityContext=true />

                    </security>

 Basically we are stating that we will use message level security with credential type UserName. To use this setting we need to have SSL connection between client and server. That is a necessary requirement because we will be sending the username and password across the wire in clear text.

EndpointAddress address = new
EndpointAddress(new Uri(“http://localhost:8731/Web.Service/DataService/”),

 The above code is just setting the server host address, nothing special here.


ChannelFactory<IDataService> service = new ChannelFactory<IDataService>(binding, address);

 Here I am creating the ChannelFactory for the particular service implementation.

service.Credentials.UserName.UserName = “test”;

service.Credentials.UserName.Password = “test”;

 The above 2 statements is where we need to set the user name and password for the UserName token authentication. Generally these values should be stored in a configuration file or something, but for demonstration purpose I hard-coded them.

service.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom;

service.Credentials.ServiceCertificate.Authentication.CustomCertificateValidator = new MyX509Validator();

 _service = service.CreateChannel();

Now the above 2 lines are not terribly important. In a production environment the server will have a valid X509 certificate from a certificate authority such as GeoTrust® but for development environment I did not have a certificate so I created a dummy certificate using the following command

makecert.exe -sr LocalMachine -ss My -a sha1 -n CN=MyServerCert -sky exchange –pe

That means it’s not a valid certificate. So if you want to bypass the actual server certificate validation (for SSL communication) then you can use the above logic to short circuit the validation.

The code for MyX509Validator is pretty straightforward for demonstration purpose:

public class MyX509Validator : X509CertificateValidator
{
public override void Validate(X509Certificate2 certificate)
{
// validate argument
if (certificate == null)
throw new ArgumentNullException(“certificate”);
 

// check if the name of the certifcate matches
if (certificate.SubjectName.Name != “CN=MyServerCert”)
throw new SecurityTokenValidationException(“Certificated was not issued by thrusted issuer”);
}
}

 That is all you need to create a dynamic proxy with full SSL/UserName token validation. You may ask, why do I need this? I can achieve the same result using configuration files as well? Well as I mentioned this is important for TDD. Here is the testability code:

Dependency Injection:

// Dependency injection

public SearchUserController(IDataService service, Views.ISearchUserView view)

{

_service = service;

_view = view;

}

The visual Studio Test code is as follows:

[TestMethod]

public void TestPortalUserDataControllerIscallingTheServiceAndSettngValueIntoTheView()
{
MockObjects.MockISearchUserView view = new MockObjects.MockISearchUserView();
MockObjects.MockIDataService service = new MockObjects.MockIDataService();
SearchUserController controller = new
SearchUserController(service, view);
 
controller.SearchButton_Click();

Assert.AreEqual(“Test Bank”, view._data[0].Bank);
}

 Pretty straight forward. We need to create 2 mock objects 1 for the view and another for the WCF service. Inject them to the Controller and voila. Here are the mock objects (I did not bother to use any mock framework here, but you can use one).


public class MockISearchUserView : ISearchUserView
{
public string BankTextBox
{
get
{
return “Test”;
}
set
{
throw new NotImplementedException();
}
}
}

 And

public class MockIDataService : IDataService
{
#region IPortalDataService Members
 

public GenericCollection<UserData> GetUsers(string bankName)
{
GenericCollection<UserData> users = new GenericCollection<UserData>();
 
UserData user = new
UserData();
user.Bank = “Test Bank”;
users.Add(user);
 
return users;
}
 
#endregion
}

 Maybe in a future post I can go into detail about the testing things.

Conclusion:

Here I wanted to demonstrate how you can use the WCF authentication mechanism without generating client proxies. You can use the dynamic proxy functionality provided in WCF to achieve the same results. This is important for the testability reasons as I demonstrated. TDD is a way of coding, if you like it there is no greater thing that happened to software development that this. If you don’t like it, you will hate it for all the complexity that it brings in. I am in the former camp.

April 8, 2009

What is the use of spirituality and why should I follow the path of spirituality?

Filed under: Uncategorized — anandj123 @ 3:26 pm

Background:

For the first 30 years of my life I did not find any answers to this first fundamental question and blissfully ignored the second part. I never considered myself an atheist, because deep down I somehow knew there is some force governing the whole thing. I could never accept the answer that the sun and moon follow exact same path every day just on their own or by chance.

My parents gave me name Anand, the literal meaning of the word is bliss. People around me tell me that I do some justice to the name. I have been successful in studies and job and never had to struggle much in life. Kind of cruising thru it all if you can say that. So, I asked myself many times if there is nothing that is bothering me then why should I even consider doing religious activity like going to temple, offering Prasad and doing all other stuff.

One evening I and one of my friends were having a nice chat about general stuff (movies, sports etc.). He had many years of meditation experience under his belt. He casually asked me if I do any meditation. Instead of answering him I put up a reverse question “I am generally happy, people who are sad generally do spiritual stuff, why should I consider meditation etc”. He said, if you enjoy your life then you should consider doing it even so more, because people who do meditation enjoy life even more. Not a strong reply which can convince a lot people but it convinced me. So a potential thought came to me, let’s give it a try, what’s the harm.

After many years of practice:

Now I am 37 and I can say for sure is spirituality definitely the way to go. I learned many things over these years. I am a technical person with a graduate degree in Engineering. My mind works in a structured way, so I will try to analyze the fundamental question in a scientific way and see I can put my experiences/learning in words.

Q: Why do we need spirituality?

A: Well because there is pain. If you are suffering from a disease you need to take medicine. Plain and simple.

Q: How can I say that?

A: I have felt it in me and most of the people I see around (except for few realized saints). Here are a few examples that I have seen myself.

  1. Consider holding a good paying job (even in this economy), watching a good movie with popcorn, going out golfing every Saturday and enjoying the goodies of life. Where is the pain here? That’s a tough one right? Wrong, the pain is in the background. That means, even while enjoying the stuff there is always an underlying fear that this will end. Once it ends there is withdrawal symptoms (e.g. why did that good movie end, why can’t I play another 18 holes of golf etc.) and sometimes depression (If I lose my job and house etc.).
  2. I have everything that I want (health, wealth, family, job etc.). Life looks good, but it’s just a struggle to get up and go to work every day. I am not satisfied and things look boring at best. Life seems such a drag. I think it’s not pain just annoyance right? Wrong again, look around, things are vibrant full of life. Even the deadest things (like a stapler in my desk) are more alive than your mind can comprehend. If you know bit of Particle Physics the scientist will validate to this statement. There are some books which can attest to my statement. Read and you will be surprised.
  3. Ok, I accept there is pain. Common examples, Boss is a pain in the rear end, lost the job, lost a family member etc. You get the picture.

In next post I will try to document extended range of pains written in Hindu and Buddhist scriptures (sorry don’t know much about other scriptures).

Q: Well if god is there then why he cannot remove all the pain and we all become happy? He seems to be a cruel guy right?

A: I don’t think so. Pain is the background for “OUR” happiness.

Q: How can that be?

A: Imagine you have a black pen and you need to write something. What do you need? A white piece of paper. Why a white piece, why not a black piece of paper? You must be thinking I am becoming lunatic. No, for to see something we need to have duality (basic building block for analyzing the problem). If the pen is black we need white background, if the pen is white we need a black background. So when we ask god for happiness, the “poor guy” has to create an opposite background so that we can see the happiness against it. Otherwise, why would option b. in the previous question be labeled as pain? Because the background is missing against which all this could be considered world of happiness.

Q: OK, why god can’t create happiness where no background of pain is required?

A: Actually that is the definition of god (sat-chit-ananda). He is all that happiness without duality. This concept cannot be understood by usual methods of learning. Because all concepts reside in mind. And mind works in duality. I will try to document some of the general problems with understanding of this concept clarify my own understanding.

Q: Well if he is all that, why is he keeping all the fun to himself, why he cannot share that with me?

A: Wrong QUESTIONER, look at the guy who is asking the question. That guy who is asking the question is defined in the scriptures as ego. That is the source of all pain.

Q: Well if ego is the source of pain, why not get rid of him. Why so much complicated procedures etc.

A: Well, once again look at the structure of the question. The guy who wants to get rid of ego is actually the ego. It’s rather like a spider web. You can keep asking these types of questions and keep on discovering that everything is ego.

Q: If everything is ego, then who am I?

A: That is the right question. This question needs to be asked (again and again for many lives sometimes) to get to the core of things. Who ever found the answer they say that they are not different from god. Very sweeping statement, very hard to believe.

Spirituality is trying to answer that question (Who am I). I will try to write about my own journey (I am still at the foothills of the summit). Sometimes, it’s just funny to look at the answers that ego provides (or try to survive the onslaught), other times it is very painful (when ego gets hurt or felt diminished and you the real “I” deny the reconstruction effort).

Disclaimer:

I am not an expert on the subject. You should consider me like a blind person and this journey is like climbing Mount Everest. Would you want a blind person to be your guide, I wouldn’t.

I have the blessings and infinite grace of my guru Pujya Baba Kalyandasji Maharaj. He is guiding me and helping me from falling-off of cliffs. So you should never follow anything that is written here. Consider them as fun reading.

 

 

 

April 1, 2009

Curse of knowledge

Filed under: Uncategorized — anandj123 @ 2:20 pm

Richard Feynman, Albert Einstein and others have repeatedly said that:

“You do not really understand something unless you can explain it to your grandmother.”

When I was working at Thoughtworks, there was a challenge given to each new hires.

“Explain dependency injection pattern to the office mailman”.

That’s quite a challenge considering I did not know what the pattern was all about at that time. One of the reason I have started writing a blog is to see if I can explain some of the ideas in simple sentences. I have felt many times that I have been a patient of “Curse of knowledge” syndrome. You can read more about it here, here . Hope my effort at writing alleviates the symptoms a little bit.

Maybe in the next post I will try to explain the “Dependency injection pattern” to my wife (definitely not to grandma).

Here are few useful tools that might be helpful to me in my monumental effort. Especially “Principle 6: Stories”

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.