Thursday, August 16, 2012

WCF : http vs https configuration

http vs https configuration

HTTP Web.config settings.

<system.serviceModel>
    <services>
      <service name="MyService.ServiceImplementation.MyServiceCall" behaviorConfiguration="MyService.ServiceImplementation.MyServiceCall_Behavior">
        <!-- Service Endpoints -->
          <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpBindingConfig" contract="MyService.ServiceContract.IMyService" bindingNamespace="http://www.MyService.com/">
          <!--
          <endpoint address="" binding="basicHttpBinding" contract="MyService.ServiceContract.IMyService" bindingNamespace="http://www.MyService.com/">
              Upon deployment, the following identity element should be removed or replaced to reflect the
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity
              automatically.
          -->
                    <identity>
                        <dns value="localhost"/>
                    </identity>
                </endpoint>
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
            </service>
        </services>
        <bindings>
        <wsHttpBinding>
            <binding name="wsHttpBinding" closeTimeout="00:20:00" openTimeout="00:20:00" receiveTimeout="00:20:00" sendTimeout="00:20:00" messageEncoding="Mtom">
                <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
                <!--<httpTransport maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" authenticationScheme="Anonymous" maxBufferSize="2147483647" transferMode="Buffered"/>-->
            </binding>
           
        </wsHttpBinding>
            <basicHttpBinding>
                <binding name="basicHttpBindingConfig" closeTimeout="00:20:00" openTimeout="00:20:00" receiveTimeout="00:20:00" sendTimeout="00:20:00" transferMode="StreamedResponse" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" >
                    <readerQuotas  maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
                    <!--<httpTransport maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"  maxBufferSize="2147483647" transferMode="StreamedResponse"/>-->
                </binding>
            </basicHttpBinding>
        </bindings>
     
        <behaviors>
            <serviceBehaviors>
                <behavior name="MyService.ServiceImplementation.MyServiceCall_Behavior">
                    <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
                    <serviceMetadata httpGetEnabled="true"/>
                    <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                    <serviceDebug includeExceptionDetailInFaults="true"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
    </system.serviceModel>


HTTPS Web.config settings.


 <system.serviceModel>
    <!-- We have multiple host headers on our server -->
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true">
    </serviceHostingEnvironment>
  
<bindings>
      <basicHttpBinding>
        <binding name="SecureTransport" >
          <security mode="Transport">
            <transport clientCredentialType="None"/>
          </security>
        </binding>

   
    <binding name="basicHttpBindingConfigMTOM" closeTimeout="00:20:00" openTimeout="00:20:00" receiveTimeout="00:20:00" sendTimeout="00:20:00" messageEncoding="Mtom" >
<security mode="Transport">
            <transport clientCredentialType="None"/>
          </security>

        <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
    </binding>
    <binding name="basicHttpBindingConfigTEXT" closeTimeout="00:20:00" openTimeout="00:20:00" receiveTimeout="00:20:00" sendTimeout="00:20:00" messageEncoding="Text" transferMode="StreamedResponse">
<security mode="Transport">
            <transport clientCredentialType="None"/>
          </security>
        <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>               
    </binding>
      </basicHttpBinding>
    </bindings>


    <services>
      <service name="MyService.ServiceImplementation.MyServiceCall" behaviorConfiguration="MyService.ServiceImplementation.MyServiceCall_Behavior">
        <!-- Service Endpoints -->

        <endpoint address="" bindingConfiguration="basicHttpBindingConfigMTOM" binding="basicHttpBinding" contract="MyService.ServiceContract.IMyService" bindingNamespace="http://www.MyService.com" >

          <!--<endpoint address="Reporting/MyService.svc" binding="basicHttpBinding" contract="MyService.ServiceContract.IMyService">
Make the endpoint relative
                -->

          <!--
              Upon deployment, the following identity element should be removed or replaced to reflect the
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity
              automatically.
          -->
          <identity>

            <dns value="test.MyService.com" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>


    <behaviors>
      <serviceBehaviors>
        <behavior name="MyService.ServiceImplementation.MyServiceCall_Behavior">
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="false" httpsGetEnabled="True" httpsGetUrl=""/>
          <!-- To receive exception  details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

  </system.serviceModel>

Monday, May 14, 2012

SQL SERVER: DB backup Script

--EXEC BackupDBUtility @Path = 'D:\DBBackup\My\', @dbName = 'Test1'

Create proc BackupDBUtility(@Path VARCHAR(100), @DBName VARCHAR(20))
AS
begin
SET NOCOUNT ON

DECLARE @Now CHAR(14) -- current date in the form of yyyymmddhhmmss
DECLARE @Result INT -- stores the result of the dir DOS command
DECLARE @RowCnt INT -- stores @@ROWCOUNT
DECLARE @filename VARCHAR(200) -- stores the path and file name of the BAK file
DECLARE @cmd SYSNAME -- stores the dynamically created DOS command
declare @Sql varchar(4000)

-- Get the current date using style 120, remove all dashes, spaces, and colons
 SELECT @Now = REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(50), GETDATE(), 120), '-', ''), ' ', ''), ':', '')

 -- Build the .BAK path and file name
 SELECT @filename = @Path + @DBName + '\' + @DBName + '_' + @Now + '.BAK'
 -- Build the dir command that will check to see if the directory exists
 SELECT @Path =  @Path + @DBName

 --create the folder Path
 DECLARE @Dir TABLE (subdirectory nvarchar(255), depth INT)
 INSERT INTO @Dir(subdirectory, depth)
 EXEC master.sys.xp_dirtree @Path

 IF NOT EXISTS (SELECT 1 FROM @Dir WHERE subdirectory = @Path)
 EXEC master.dbo.xp_create_subdir @Path
 --Take backup
BACKUP DATABASE @DBName TO DISK = @filename

end

SQL SERVER : Enable xp_cmdshell

sp_configure 'xp_cmdshell', '1' 
reconfigure
GO

sp_configure 'xp_cmdshell'
GO

ASP.NET : Locking Objects

These limit the number of threads that can perform some activity or execute a section of code at a time. Exclusive locking constructs are most common — these allow just one thread in at a time, and allow competing threads to access common data without interfering with each other. The standard exclusive locking constructs are lock (Monitor.Enter/Monitor.Exit), Mutex, and SpinLock. The nonexclusive locking constructs are Semaphore, SemaphoreSlim, and the reader/writer locks.

lock(obj)
  • is a CLR construct that for (intra-object?) thread synchronization. Ensures that only one thread can take ownership of the object's lock & enter the locked block of code. Other threads must wait till the current owner relinquishes the lock by exiting the block of code. Also it is recommended that you lock on a private member object of your class.
Monitors
  • lock(obj) is implemented internally using a Monitor. You should prefer lock(obj) because it prevents you from goofing up like forgetting the cleanup procedure. It 'idiot-proof's the Monitor construct if you will.
    Using Monitor is generally preferred over mutexes, because monitors were designed specifically for the .NET Framework and therefore make better use of resources.
Using a lock or monitor is useful for preventing the simultaneous execution of thread-sensitive blocks of code, but these constructs do not allow one thread to communicate an event to another. This requires synchronization events, which are objects that have one of two states, signaled and un-signaled, that can be used to activate and suspend threads. Mutex, Semaphores are OS-level concepts. e.g with a named mutex you could synchronize across multiple (managed) exes (ensuring that only one instance of your application is running on the machine.)

Mutex:
  • Unlike monitors, however, a mutex can be used to synchronize threads across processes. When used for inter-process synchronization, a mutex is called a named mutex because it is to be used in another application, and therefore it cannot be shared by means of a global or static variable. It must be given a name so that both applications can access the same mutex object. In contrast, the Mutex class is a wrapper to a Win32 construct. While it is more powerful than a monitor, a mutex requires interop transitions that are more computationally expensive than those required by the Monitor class.
  • Use the Semaphore class to control access to a pool of resources. Threads enter the semaphore by calling the WaitOne method, which is inherited from the WaitHandle class, and release the semaphore by calling the Release method. The count on a semaphore is decremented each time a thread enters the semaphore, and incremented when a thread releases the semaphore. When the count is zero, subsequent requests block until other threads release the semaphore. When all threads have released the semaphore, the count is at the maximum value specified when the semaphore was created. A thread can enter the semaphore multiple times..The Semaphore class does not enforce thread identity on WaitOne or Release.. programmers responsibility to not muck up. Semaphores are of two types: local semaphores and named system semaphores. If you create a Semaphore object using a constructor that accepts a name, it is associated with an operating-system semaphore of that name. Named system semaphores are visible throughout the operating system, and can be used to synchronize the activities of processes. A local semaphore exists only within your process. It can be used by any thread in your process that has a reference to the local Semaphore object. Each Semaphore object is a separate local semaphore.
 Reference:
 

Thursday, May 10, 2012

UnitTest : Moq

What?

Moq (pronounced "Mock-you" or just "Mock") is the only mocking library for .NET developed from scratch to take full advantage of .NET 3.5 (i.e. Linq expression trees) and C# 3.0 features (i.e. lambda expressions) that make it the most productive, type-safe and refactoring-friendly mocking library available. And it supports mocking interfaces as well as classes. Its API is extremely simple and straightforward, and doesn't require any prior knowledge or experience with mocking concepts.

 Checkout the QuickStart for more examples!

 

Features at a glance

Moq offers the following features:
  • Strong-typed: no strings for expectations, no object-typed return values or constraints
  • Unsurpassed VS intellisense integration: everything supports full VS intellisense, from setting expectations, to specifying method call arguments, return values, etc.
  • No Record/Replay idioms to learn. Just construct your mock, set it up, use it and optionally verify calls to it (you may not verify mocks when they act as stubs only, or when you are doing more classic state-based testing by checking returned values from the object under test)
  • VERY low learning curve as a consequence of the previous three points. For the most part, you don't even need to ever read the documentation.
  • Granular control over mock behavior with a simple MockBehavior enumeration (no need to learn what's the theoretical difference between a mock, a stub, a fake, a dynamic mock, etc.)
  • Mock both interfaces and classes
  • Override expectations: can set default expectations in a fixture setup, and override as needed on tests
  • Pass constructor arguments for mocked classes
  • Intercept and raise events on mocks
  • Intuitive support for out/ref arguments 

Installing and Setting Up Moq

Moq is maintained as a Google Code project. You can download the Moq binaries and API documentation here:
http://code.google.com/p/moq/
After you download the Moq binaries from Google Code, make sure that you unblock the archive by right-clicking the file, selecting Properties, and pushing the Unblock button (see Figure 1). If you forget to do this, you run into confusing security issues when you try to use Moq within Visual Studio.
clip_image002
The archive includes an assembly named Moq.dll. You need to add this assembly to your test project in Visual Studio. You also need to add the Moq namespace to your test classes.

What Can Be Mocked?

You can use Moq to create mocks from both interfaces and existing classes. There are some requirements on the classes. The class can’t be sealed. Furthermore, the method being mocked must be marked as virtual. You cannot mock static methods (use the adaptor pattern to mock a static method).
These limitations are the same as the limitations you face when working with Rhino Mocks. Both Moq and Rhino Mocks use proxy classes under the covers. Indeed, both frameworks derive from the same Castle DynamicProxy code base.

Mocking Methods and Properties

Imagine that you are building a database-driven web application. Imagine, for example, that you are creating an online store. You want to concentrate on writing all of the business logic for your store before doing anything else. In particular, you don’t want to devote any time to writing your data access components before writing your business components.
This is a good situation to take advantage of a Mock Object Framework. In this situation, you can create an interface that describes how you want your data access component to look. Then, you can simply mock the interface and take advantage of the mock while testing your business logic. The mock enables you to avoid writing code until you are really ready to do it.

UnitTest : Mock Framework

One way of thinking about an object-oriented program is that each object is an entity that interacts with other objects (which we will call 'collaborators') in order to do its work. This is illustrated in the following diagram:
MockObjects1
The idea behind Mock Objects is this: when unit testing an object, you replace its collaborators with 'Mock' collaborators. This is illustrated below:
MockObjects2
So how is this different from stubs? Well, whilst there are some similarities, there are also two important distinctions:
  1. Mock Objects test themselves - ie, they check that they have been called in the right manner at the right time by the object being tested. Stubs generally just return stubbed data, which can be configured to change depending on how they are called.
  2. Mock Objects are generally extremely lightweight. There are often totally different instances of them set up for every test. Stubs, on the otherhand, are relatively heavyweight and are often reused between tests.

Design Implications

It's important to realise that, depending on the degree to which you use them, Mock Objects have two major implications for your software design. These are:

Everything by Interfaces

Most inter-object interaction must be done via interfaces. This is so that either real or mock implementations can be passed to objects being tested. Another way of thinking about this is that you essentially have to introduce an extra layer of indirection between an object and any collaborator that you want to mock. This extra indirection can make the code difficult to follow at first.

Dependency Injection

Generally, the collaborators of an object should be given to the object - the object should not get the collaborators itself. This is an existing design strategy known as 'dependency injection', or 'inversion of control' - perhaps it's most well-known use is in the Spring framework. I won't go into this pattern in too much detail - Martin Fowler has written a useful article about it. I found that whilst its usage could generally lead to better design, when used for testing at a very low level it can have quite major and disturbing implications on your code. I will discuss this further in the section Experiences with Mock Objects.

When Are Mock Objects Useful?

Perhaps the main benefit of using Mock Objects is that because you are replacing the collaborators of an object, you don't have to set up all of the complex state that may be required to run those collaborators.
For example, I was recently working on some business logic that took data from an XML file, processed it, and inserted it in a database. When it came to testing the intricacies of the business logic, I didn't want to have to write an automated test to painstakingly set up XML files, trigger the business logic and then carefully check the contents of the database tables. All I cared about was the the business logic interacted correctly with the XML Parser and the database layer - ie, that it made the right calls with the right parameters at the right time. So I carefully defined my interfaces with the XML parser and the database, and then plugged 'Mock' implementations of these interfaces into the business logic when I was testing it.
An important thing to emphasis about Mock Objects is that they are really just a tool that helps you to test details of an object that would have otherwise been inaccessible or impractical to test.
For example, by mocking up a JDBC driver used by a Data Access Object, you can easily simulate the driver throwing SQLExceptions, and thus test how your DAO deals with them. Simulating such conditions with a real JDBC driver in an automated test would be much more difficult. And whilst mocking up parts of a JDBC driver can seem like pain, I believe that in the long run it's less painful than trying to set up a database to induce a particular behaviour that you are trying to test.
Overall I found that when developing with Mock Objects, I spent most of my time writing lots of small, focused tests, instead of spending lots of time thinking about how I could contrive a single big test that would exercise a deeply embedded piece of functionality.
The flipside of this is that using Mock Objects does not test the integration of your units. As you would know, sometimes defects can occur during the integration of components - there can be mismatches between what collaborators expect from one another.
For example, at some stage it would be a good idea to try your unit with a real JDBC driver just in case the query that you're passing to it is garbage. Consequently, higher-level tests of your unit are still a good idea. It's just that if it gets to a point where you're spending more time writing code that is 'non-core' to the test - ie, code for setting up or tearing down the particular state required - it might be worth using Mock Objects instead.

There are many Framework available for the same.
 
 This is just a quicky, doesn't mean much, but allows a look at how each framework's syntax allows to setup a expectation & return value for a method:
  • NMock:
    IMock mock = new DynamicMock(typeof(IRequest));
    IRequest request = (IRequest)mock.MockInstance;
    mock.ExpectAndReturn("Username","Ayende");
    testedObject.HandleRequest(request);
    mock.Verify();
    EasyMock.Net:
    MockControl control = MockControl.CreateControl(typeof(IRequest));
    IRequest request = (IRequest)control.GetMock();
    control.ExpectAndReturn(request.Username,"Ayende");
    control.Replay();
    testedObject.HandleRequest(mock);
    control.Verify();
    TypeMock.Net: [Update: This is the correct syntax]
    Mock requestMock = MockManager.Mock(typeof(ConcreteRequest));
    requestMock.ExpectAndReturn("Username","Ayende");
    //TypeMock.Net should take care of intercepting the calls for Username
    testedObject.HandleRequest(new ConcreteRequest());
    MockManager.Verify();
    Rhino Mocks Version 1.0:
    MockControl mockRequest = MockControl.CreateControl(typeof(IRequest));
    IRequest request = (IRequest)mockRequest.MockInstance;
    mockRequest.ExpectAndReturn(request.Username,"Ayende");
    mockRequest.Replay();
    testedObject.HandleRequest(request);
    mockRequest.Verify();
    NMock2:
    using(Mockery mocks = new Mockery())
    {
    IRequest request = (IRequest)mocks.NewMock(typeof(IRequest),"IRequest");
    Expect.Once.On(request).GetProperty("Username").Will(Return.Value("Ayende"));
    testedObject.HandleRequest(request);
    }
    Rhino Mocks Version 2.0:
    using(MockRepository mocks = new MocksRepository)
    {
    IRequest request = (IRequest)mocks.CreateMock(typeof(IRequest));
    Expect.On(request).Call(request.Username).Return("Ayende");
    mocks.ReplayAll();
    testedObject.HandleRequest(request);
    }
     

Monday, May 7, 2012

WCF : DataContract Vs MessageContract

1. Comparison

Data Contracts

WCF data contracts provide a mapping function between .NET CLR types that are defined in code and XML Schemas Definitions defined by the W3C organization (www.w3c.org/) that are used for communication outside the service.
you can say “Data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged”. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) to be exchanged.

Message Contracts

Message contracts describe the structure of SOAP messages sent to and from a service and enable you to inspect and control most of the details in the SOAP header and body. Whereas data contracts enable interoperability through the XML Schema Definition (XSD) standard, message contracts enable you to interoperate with any system that communicates through SOAP.
Using message contracts gives you complete control over the SOAP message sent to and from a service by providing access to the SOAP headers and bodies directly. This allows use of simple or complex types to define the exact content of the SOAP parts.

2. Why use MessageContract when DataContract is there?

Data contracts are used to define the data structure. Messages that are simply a .NET type, lets say in form of POCO (plain old CLR object), and generate the XML for the data you want to pass.
Message contracts are preferred only when there is a need to “control” the layout of your message(the SOAP message); for instance, adding specific headers/footer/etc to a message.
Sometimes complete control over the structure of a SOAP message is just as important as control over its contents. This is especially true when interoperability is important or to specifically control security issues at the level of the message or message part. In these cases, you can create a message contract that enables you to use a type for a parameter or return value that serializes directly into the precise SOAP message that you need.

3. Why we use MessageContract to pass SOAP headers ?

Passing information in SOAP headers is useful if you want to communicate information “out of band” from the operation signature.
For instance, session or correlation information can be passed in headers, rather than adding additional parameters to operations or adding this information as fields in the data itself.
Another example is security, where you may want to implement a custom security protocol (bypassing WS-Security) and pass credentials or tokens in custom SOAP headers.
A third example, again with security, is signing and encrypting SOAP headers, where you may want to sign and/or encrypt some or all header information. All these cases can be handled with message contracts. The downside with this technique is that the client and service must manually add and retrieve the information from the SOAP header, rather than having the serialization classes associated with data and operation contracts do it for you.

When we use MessageContract ?



A very simple answer to the question is, when you need a higher level of control over the message, such as sending custom SOAP header, you then use MessageContract instead of DataContract. But in my opinion, most of the messaging needs can be catered by DataContracts.
This is the extract from MSDN : Sometimes complete control over the structure of a SOAP message is just as important as control over its contents. This is especially true when interoperability is important or to specifically control security issues at the level of the message or message part. In these cases, you can create a message contract that enables you to use a type for a parameter or return value that serializes directly into the precise SOAP message that you need.
To elborate on the above mentioned MSDN extract, a message contract allows you to specifically control which elements will be in the SOAP header, and which will be in the SOAP body and this isn't possible using the DataContract. As DataContracts represent types. Messages are not used as types but rather the payload a method operates on and they are specific to the operation they are passed to and from.
This situation arises when you have a communication partner which requires a very specific format and you have to tweak your SOAP messages to match that given layout exactly. In my view, always use DataContracts unless you have to use MessageContract for a very good reason.
One of the hypothetical situation could be your communication partner would like to have a custom security header with username and hashed password. So you could have a message contract something similar to the below

01[MessageContract]
02public class BankingTransaction
03{
04  [MessageHeader] public string UserName;
05  [MessageHeader] public string Password;
06  [MessageBodyMember] private Account sourceAccount;
07  [MessageBodyMember] private Account targetAccount;
08  [MessageBodyMember] public int amount;
09 
10}
Notice on the above contract the UserName and Password are decorated with MessageHeader attribute. The generated SOAP message with WCF basicHttpBinding will look like following:
02  <s:Header>
03    <Action s:mustUnderstand="1"
06</Action>
07    <h:Password xmlns:h="http://tempuri.org/">HashPassword</h:Password>
08    <h:UserName xmlns:h="http://tempuri.org/">TestUser</h:UserName>
09  </s:Header>
10  <s:Body>
11    <BankingTransaction xmlns="http://tempuri.org/">
12      <amount>10</amount>
13      <sourceAccount>1234</sourceAccount>
14      <targetAccount>5678</targetAccount>
15    </BankingTransaction>
16  </s:Body>
17</s:Envelope>

Notice the SOAP the password and username members are serialized as SOAP header and the remaining members were serialized as SOAP body.

4. Can’t mix datacontracts and messagecontracts.

Because message-based programming and parameter-based programming cannot be mixed, so you cannot specify a DataContract as an input argument to an operation and have it return a MessageContract, or specify a MessageContract as the input argument to an operation and have it return a DataContract. You can mix typed and untyped messages, but not messageContracts and DataContracts. Mixing message and data contracts will cause a runtime error when you generate WSDL from the service.