Getting Started with LINQ – Part 2

Hi Friends,

In this section, we’ll proceed further and look different projection strategies. So, the 1st case which i am using here is the Object Initializers. With C# Object Initializers, we can project the same into more complex types. For example, suppose, as a first step in a query, we want to strip vowels from a list of names while still keeping the original versions alongside, for the benefit of subsequent queries. Therefore, we can write as shown below

6th

However, Anonymous Types allow you to structure your intermediate results without writing special classes. So, here we can remove TempProjectionItem as shown below in the example.

7th8th

The let keyword introduces a new variable alongside the range variable. With let, we can write a query extracting strings whose length, excluding vowels, exceeds two characters, as follows:

8th

The compiler resolves a let clause by projecting into a temporary anonymous type that contains both the range variable and the new expression variable. Thanks for joining me. In the next section, we’ll delve further and check other pieces as well. Till then stay tuned and happy coding

Thanks,
Rahul Sahay
Happy Coding

1,401 total views, 1 views today

Pragmatic WCF is Free to download

Hi Friends,

It gives me immense pleasure to announce that, I have made Pragmatic WCF free for 5 days, ending on 26th June. I really, like you guys to go ahead and utilize this opportunity to download the same, read it and provide your feedback. Looking ahead for your feedback.

wcf

Download Link:- http://bit.ly/pragmaticWCF-kindle

Also, from many folks I have been hearing don’t know how to use Kindle. It’s very simple. Once, you buy the book. Amazon, will send you kindle link on your mail as well. This will enable you to install kindle on your machine or on phone. This will help you reading book offline. Otherwise, if you want to read the same online, that also you will instantly.

Thanks,
Rahul Sahay
Happy Coding

3,427 total views, 2 views today

Pragmatic WCF

wcf

Hi Friends,

This is the glimpse of my WCF book. Here, I have again solved the Movie Review case study. But, in this case applied all the latest concepts from WCF umbrella. Here, you will learn how to write SOA application right from the scratch. I hope you will like this.

Copyright © 2015 Rahul Sahay
All rights reserved.
ISBN: 1514261251
ISBN-13: 978-1514261255

CONTENTS

Chapter 1: Getting started
INTRODUCTION,13
WHAT IS SOA,13
WHAT IS SERVICE,14
SERVICE ORIENTED ARCHITECTURE,14
SERVICE ORIENTED APPLICATION,15
SERVICE ORIENTED TECHNOLOGIES,16
ALTERNATIVE TECHNOLOGIES, 16
WINDOWS COMMUNICATION FOUNDATION, 17
WCF ARCHITECTURE,18
WCF VS WEB API,19
COMPONENTS,19
WHEN TO CONSIDER,20
SUMMARY,20

CHAPTER 2: CONTRACTS & SERVICES
INTRODUCTION,21
WHAT ARE CONTRACTS,21
DATA CONTRACTS,22
WRITING FIRST DATA CONTRACT,23
SERVICE CONTRACT,26
WRITING FIRST SERVICE CONTRACT,27
SERVICES,28
WRITING THE SERVICE,28
UNIT TESTING, 32
SUMMARY, 38

CHAPTER 3: HOSTING
INTRODUCTION,39
SELF-HOSTING,39
CONSOLE HOSTING,40
SERVICE CONFIGURATION,42
WEB HOSTING,48
WAS,56
CONFIG-LESS HOSTING,60
WINDOWS-PROJECT SETUP,61
SUMMARY,68

CHAPTER 4: CREATING PROXY & CLIENT CONFIGURATION
INTRODUCTION,68
PROXY SETUP,69
PROXY CREATION,70
CLIENT CONFIGURATION,71
INSPECTING CLIENT APP,73
ADDING ANOTHER ENDPOINT,80
MODIFYING PROXY,82
SETTING-UP PROXY,87
NO-CONFIG CODING,89
CONTRACT EQUIVALENCE,90
CREATING ANOTHER SERVICE,91
PROXY CHANGES,96
SERVICE HOST CONFIGURATION,98
CLIENT CONFIGURATION,101
CHANNEL FACTORY,103
CONTRACT MISMATCH,108
VERSION TOLERANCE,112
SUMMARY,113

CHAPTER 5: THREADING
INTRODUCTION,114
IN-PROCESS THREADING,114
IMPLEMENTING IN-PROCESS,115
THREADS,120
SERVICE BEHAVIOR,120
MARSHALLING UP,123
SERVICE INTEGRATION,127
SUMMARY,130

CHAPTER 6: BINDINGS & SERVICE BEHAVIOR
INTRODUCTION,131
WHEN TO CHOOSE WHAT,132
TRANSPORT,133
BINDING CONFIGURATIONS,134
SEND TIMEOUT,135
MAX RECEIVED MESSAGE,139
SLIDING TIMEOUT,140
BEHAVIOR CONFIGURATION,143
THROTTLING,149
SUMMARY,150

CHAPTER 7: METADATA
INTRODUCTION,151
WHAT IS METADATA,151
METADATA EXPOSURE,152
ADDING BEHAVIOR,152
ADDING SERVICE REFERENCE,153
ADDING CLIENT CODE,159
ADDING MEX ENDPOINT,160
ADDING MEX PROGRAMMATICALLY,162
SUMMARY,164

CHAPTER 8: INSTANCING & CONCURRENCY
INTRODUCTION,167
PER CALL,167
PER SESSION,167
SINGLE SESSION,168
PER CALL DEMO,168
PER SESSION DEMO,176
SINGLETON DEMO,178
SESSION MODE,179
BINDING ENFORCEMENT,180
CONCURRENCY,182
SINGLE CONCURRENCY,182
MULTIPLE CONCURRENCY,183
RE-ENTRANT CONCURRENCY,184
CLIENT CODE SETUP,184
PER CALL TEST,190
PER SESSION TEST,192
SINGLETON TEST,194
PER CALL MULTIPLE TEST,196
PER SESSION MULTIPLE TEST,198
SINGLETON MULTIPLE TEST,200
TASK TEST,202
SUMMARY,203

CHAPTER 9: FAULTS AND EXCEPTIONS
INTRODUCTION,204
SOAP FAULTS,204
SCENARIO 1,205
SCENARIO 2,205
UNHANDLED EXCEPTION,206
UNHANDLED EXCEPTION – 2ND,209
UNHANDLED EXCEPTION – 3RD,211
HANDLE FAULT EXCEPTION,214
HANDLE FAULT EXCEPTION OF T,216
HANDLE WITH CUSTOM CONTRACT,220
SUMMARY,225

CHAPTER 10: OPERATION MANAGEMENT
INTRODUCTION,226
REQUEST-RESPONSE,226
ONE-WAY OPERATION,227
ONE-WAY CODING,227
CHANGING BINDING,233
CALLBACK OPERATIONS,234
CALLBACK IMPLEMENTATION,235
CLEARING DEADLOCK,240
REPLACING MESSAGE-BOX,246
USING THREAD,250
CHANGING THREAD TO TASK,252
SUMMARY,253

CHAPTER 11: SECURITY
INTRODUCTION,254
SECURITY SCENARIOS,255
AUTHENTICATION,256
AUTHORIZATION,256
RUNNING WITH NO SECURITY,256
RUNNING WITH SECURITY,263
PROTECTION LEVELS,266
ALTERNATE CREDENTIALS,268
ROLE-BASED,270
INTRANET WEB APP,274
INTERNET WEB APP,285
SECURITY MODE,286
SETTING BEHAVIOR,289
CERTIFICATE CREATION,291
CONFIGURING CERTIFICATE,293
CLIENT CONFIGURATION,295
ASP.NET PROVIDERS,309
SUMMARY,329

PREFACE
Hello and welcome to Pragmatic WCF. My entire career has been about learning new technologies and applying the same. It is like taking on new challenges and implementing the same efficiently. I enjoy learning new stuffs, and I like to share things that I have learned through blogging and book writing. I also like to help others by cascading the knowledge related to different technologies. I always wanted to write a book where I can highlight some of the enterprise level coding practice in the field of distributed technology. I also wanted to show something that solved the kinds of problems that architects and developers face on daily basis while writing enterprise level solution. After years of research and hard work, I finally put all the topics with complete demo in place.
There are many reasons why WCF came to my mind. Undoubtedly my focus on web services and interoperability. Given that WCF has deep support for web service standards (WS*) and supports high degree of extensibility. Another quality about WCF that impresses me is that it embraces pure SOA platform, which means decoupling the development of services from downstream business components. In short, WCF unifies earlier technology stacks, namely .NET Remoting, Enterprise Services, ASP.NET web services (ASMX), and Web Services Enhancements (WSE).
I am strong believer of the fact that anyone developing enterprise systems today should be using WCF. Because the kind of tooling support provided by WCF is simply awesome. Another feature about WCF, which I like most, is its explicitness. WCF is an enabler of robust system design, which confirms security, reliability, and scalability.
I wrote this book to demonstrate developers the power of WCF with complete end-to-end illustrations.

WHO THIS BOOK IS FOR
The primary target audience for this book is anyone who would like to explore the world of SOA implementation using WCF. This book starts with basic understanding then moving to advanced section. Any .NET developer novice or expert can use this book as reference. In addition, anyone who is interested in learning how to design decoupled system right from the scratch, I think he/she is at best place.
HOW THIS BOOK IS STRUCTURED

Chapter 1, Getting Started
Starts by explaining what WCF is, and then describes essential WCF concepts and building blocks of it. The chapter starts with a discussion of the SOA application, which is really the kingpin of all that is enabled in the subsequent chapters. This chapter starts with scratch with basic definitions and comparison with other cousin technologies.
Chapter 2, Contracts & Services
In this chapter, I discussed Contracts and Services in detail. Contracts and Services are the heart of any WCF application. Here, you will start with basic understanding. Then, you will see demos around it with deep understanding around designing contracts and service.
Chapter 3, Hosting
Hosting is the key ingredient to give life to your service. Here, you will learn variety of techniques to host the services. Here, you will also learn how to host the services in different scenarios with different protocols.
Chapter 4, Creating Proxy & Client Configuration
This section is entirely dedicated to proxy creation and consuming service. Here, you will learn while doing so, what are underline factors involved like how channel plays an important role around proxy. Then, you will also learn things like communication establishment, security establishment, message exchange etc…
Chapter 5, Threading
In this chapter, you will learn how to handle threading issues in real time environment. Here, you will also learn how to keep the UI responsive while operation is executing in the background thread. Major thing is how to delegate the job to different threads while keeping the UI thread free for accepting multiple requests.

Chapter 6, Bindings & Service Behavior
In this chapter, you will learn complete suite of different bindings available with WCF. Binding is one of the key elements for building any WCF application. Here, you will do deep dive with different Transport Mechanisms available for the WCF application.
Chapter 7, Metadata
Metadata is the Shape and Characteristics of service. In short it is pretty much everything about service. All these bits are part of metadata and this is exposed in the form of WSDL. Here, you will learn Metadata Exchange in detail.
Chapter 8, Instancing & Concurrency
Instancing means instance of service whereas concurrency determines how the service will handle locking during multiple concurrent calls. In this Chapter, you will learn two major things Instancing and Concurrency. In the first section, you will learn Instancing and then concurrency.
Chapter 9, Faults & Exceptions
Faults & Exceptions one of the most important pieces of WCF. I have seen that people do not take this section seriously. However, in case of WCF, this is important as we are talking cross boundary here. Therefore, it is important to understand how and when SOAP exceptions occur and how to handle them.
Chapter 10, Operation Management
Demystifies WCF by making operation calls differently. This is one of the unique features of WCF. Unlike Web API, which is again a great technology but it does the operation handling only one-way. Nevertheless, here you will learn different ways.
Chapter 11, Security
Security is one of the most important areas of any application. More secure you will make your application, more reliable it will be. In this chapter, you will learn different kinds of security implications and their solution. Here, you will also learn how to implement different techniques in intranet and internet scenario.

WHAT IS NOT COVERED
This book is the first part of WCF series where in I have covered major things what developers’ need on day-to-day basis. However, there are certain things, which I have not covered in this book like Transaction Handling, Queuing, Routing, Service Bus and many other things. I always feel Transactions go hand in hand with other advanced topic, hence moved this out for next edition.
ACKNOWLEDGEMENTS
Again, this book would not have been possible without the loving support of my wife Nivi, who had to take over much of the household responsibility apart from her teaching activities. Appreciation also goes out to my Mom and Dad for believing in me and always keeps on encouraging me to complete the book in a best possible way. In addition, in the end, you know how it is, you pick a book and flip to Acknowledgement’s page and find that author has once again dedicated the book someone close to him, not to you. Not this time. I would like to thank all the readers whole-heartedly for choosing the book. Finally, I would like to thank readers of my blog (http://myview.rahulnivi.net). Many of you have contributed by asking questions, providing feedback, and inspiring and encouraging me in everything, I do.
CHAPTER 1: GETTING STARTED

WHAT DO you find in this CHAPTER?

• Introduction
• What is SOA
• What is Service
• Service Oriented Architecture
• Service Oriented Application
• Service Oriented Technologies
• Alternative Technologies
• Windows Communication Foundation
• WCF Architecture
• WCF Vs Web API
• Components
• When to consider
• Summary
INTRODUCTION:-
Hello and welcome to Pragmatic WCF. In this section, we will begin with the simple definition and meaning of WCF, and then we will gradually see individual items as explained in the definition. We will also see the different components involved in SOA application and technology behind the scene. Then, we will also compare WCF and Web API and its capabilities. Last but not the least we will also see when to consider WCF. So, without wasting time let us get started.

WHAT IS SOA:-
SOA stands for “Service Oriented Application”. As per Wikipedia SOA means “A service-oriented architecture (SOA) is a design pattern in which application components provide services to other components via a communications protocol, typically over a network. The principles of service-orientation are independent of any vendor, product or technology”. Now, let us understand the same in plain English; it is writing a system in such a way that you are exposing everything behind the firewall via some API and client has limited functionality access and it accomplishes its job via Service Calls. Therefore, it is a way of organizing your system where the client has little intelligence about it and makes the call to access the functionality.
One point to note here in the world of SOA, application’s business layer orchestrated by a set of loosely coupled services. Loosely coupled services mean services, which communicate with the client or with each other via set of industry-accepted protocols, in this case SOAP (Simple Object Access Protocol).

WHAT IS SERVICE:-
A Service is a collection of Units of Responsibilities. In WCF, we use the term Operations to define responsibilities. These units of responsibilities are rock solid in handling designated responsibility means anything, which needs orchestrated by making down level calls to other components, is handled by service operation. Let us say if security is necessary then it will handle by service, if some kind of operation mode or concurrency issue or behaviors etc. will be taken care by service itself. Hence, in this case client does not need to worry about these down-level things. Client only need to make a call and that is it. A service itself is a point of entry for the client and sits on the top of this architecture, which we will see soon. Services are also manager of all the down level layers. These down level layers could be business repository or database repository or combination of both. Moreover, because of these reasons, services are secure, keep system healthy, consistent, and thread safe and many other things, which we will discuss in different modules.

SERVICE ORIENTED ARCHITECTURE:-
Everything I described illustrated below in the diagram. As you can see that we have database and data access layer, we have the business layer and we have the UI (Presentation) layer. These are the three basic components of any application, which are required at minimum. Now, when we expose things as services to make our application service oriented, we are hiding away all the calls to the data access layers and business access layer. We are hiding the same using Firewall and this Firewall in this diagram is termed as Service Layer. Because, Service Layer exposed using industry accepted protocol, there is lot of low-level communication need to happen. Here, in this case we are talking between machines means going from one machine to another. Therefore, in order to access services from the client side we use Service Proxies. This layer abstracts all low-level communication and setup the connection between client and service. Therefore, all kind of handshaking happens at this layer. In addition, client has no knowledge of all these handshakings.

1st

SERVICE ORIENTED APPLICATION:-
An application, which follow above rules, referred as Service Oriented Application. All the SOA applications are whose sensitive areas wrapped inside service call. This is known as operation. However, client not exposed to any of these inner implementations. This hides away anything which client should not have access. It also prevents client from unwanted intrusion into other parts of the system. It also removes potentially dangerous configurations from client machine like connection string. Connection strings could be dangerous thing if not encrypted. Therefore, with SOA applications, clients do not need to bother of these issues; they just need make a service call and all heavy lifting done by service itself.

In Service Oriented Applications, it is all about the call.
• Client makes a call with required data for processing
• Service receives data, performs job and returns response
• Details of processing completely hidden from the client.
SERVICE ORIENTED TECHNOLOGIES:-
To write Service Oriented Application, we need technologies that enforces certain way of doing things. It also needs to abstract a lot of low level tasks means a lot of work is required for low level tasks. Like different ways of handling
• Communication,
• State Management,
• Transaction,
• Security Implications
Now, this technology also needs to provide necessary tooling both on the server side and on client side. Since, we are using SOAP here; SOAP requires tooling that is the number one difference between Rest services and SOAP based services. Because of this tooling requirement, WCF comes into picture.

ALTERNATIVE TECHNOLOGIES:-
There are variety of alternative technologies, which we have already used prior to WCF like

• .Net Remoting: – Some of the features of .Net Remoting like TCP-Compatible. Fast but bad part is .Net-to-.Net communication only. It also had many cryptic configurations, which makes developers tough to use.

• Web Services: – This was one of the most widely used technology for communication. Still widely used. Limiting factor with Web Services are they are only HTTP based. Also for advanced features, it requires WS* stack implementations which is again little cryptic to handle.

• Enterprise Services: – This provided advances services to components including things like Security, Transactions etc. However, again it is little difficult to work with this technology as it needed bunch of configurations.

• MSMQ: – Another great technology which heavily relies on queuing. This technology is still around. It is widely used for reliable messaging and disconnected use. Nevertheless, in order to implement the same, you need to learn another API implementation.

• Sockets: – And then we had Sockets. Good for Point-to-Point communication. However, this is again very much configuration driven and needs a lot of low-level plumbing before launching the same. It relies on things like Packet-Size, port no etc.

WINDOWS COMMUNICATION FOUNDATION:-
One thing, which is common with all these legacy technologies, is that proof of the technology and the communication found in the code, which you write. Therefore, Sockets code is different from what you write for MSMQ. Similarly, Enterprise Library code is different for .Net Remoting or Web Services. Then comes Windows Communication Foundation. This provides Unified Programming Model for several technologies. This means you can focus on writing your service and how the service is communicated or exposed is done via configuration. WCF is SOAP based but it is REST Capable. WCF also abstracts the details of communication, which means you do not need to know how these down level calls are happening. Hence, you can just focus on your requirement writing business logic in you service code. WCF also gives flexibility in terms of transportation means you write your service code once and you can use any transport medium like TCP, HTTP, and Pipe etc…. Last but not the least WCF provides cool service characteristics which can be handled either declaratively or via program. Below is the list of few Features.

• Security
• State
• Transactions
• Reliability
• etc

WCF ARCHITECTURE:-
Let me give brief snapshot of WCF Architecture. WCF sometimes also referred as interception architecture or pipeline architecture. A pipeline or interception architecture is based on Gang of Four Chain of Responsibility principle. Here, it means it should have two endpoints client and service and whole bunch of stuffs should happen in between. Client packages a message and send the same to a service by a proxy call. Now, between this client and service call there are variety of things being done and checked. Some of them are done on the client side of the wire; some of them done on the server side of the wire. We will look all these minute details in the coming sections. Below, is the simple diagram for the same.

2nd

3rd

WCF VS WEB API:-
We talked a lot about WCF. Now, let us get rid of that and do comparison between these two.

• WCF is configuration driven and feature rich.
• WEB API is more interoperable.
• WCF based on SOAP protocol.
• WEB API based on REST architecture.
• WCF requires Tooling.
• WEB API requires HTTP request.
• WCF binding makes it faster in Firewall like TCP.
• WEB API is not replacement of WCF.

COMPONENTS:-
In the coming chapters, we will drill down heavily into WCF components. So, let us look briefly, what these components are. WCF is very explicit means you need to know ahead of time what you are going to expose and based on that you need to design. In short, WCF is contract based. WCF uses variety of components besides these contracts such as

• Proxies
• Services
• Configuration
• Hosting
• Etc.

WHEN TO CONSIDER-
Most systems today have many client components like Desktop app, Browser, Mobile App, and Mobile Browser. Some of these apps sit inside the Firewall, some out. For example, desktop application sits inside the Firewall app, even the sites hosted on IIS sits inside the firewall. However, mobile apps are different things they are like native apps to the different phone environments like IOS, Windows or Android. Therefore, they sit outside the firewall. However, Mobile browsers are more like mobile simple desktop browsers only difference is these are optimized one, but they still sit inside the firewall. Therefore, the idea is if your application is going to sit inside the Firewall, WCF is definitely a great choice as it certainly offer tons of feature around that.

SUMMARY:-
In this section, we have seen the basics of WCF like the one we started with simple introduction and then looked at the SOA terminology and characteristics of SOA. Then, we have also seen technologies involved behind the implementation of SOA. We also talked in brief about WCF architecture and its role in building SOA. We have also done little comparison with WEB API and in the end; we discussed when to consider WCF for writing your APP.

CHAPTER 2: CONTRACTS & SERVICES

WHAT DO you find in this CHAPTER?

• Introduction
• What are Contracts
• Data Contracts
• Writing First Data Contract
• Service Contract
• Writing First Service Contract
• Services
• Writing the Service
• Unit Testing
• Summary

INTRODUCTION:-
In this section, we are going to look at Contracts and Services in detail. Contracts and Services are the main essence of WCF as these are basic stuffs, which is going to define your API. Now, in order to do the same I am going to use one case study. My usual Movie Review. Here, in this case I am going to design the API around the same App. In this course, you will see that how I use to fetch movies, directors and many more using WCF implementation.

WHAT ARE CONTRACTS:-
Contracts are parts of WCF explicitness, which means it provides definition and you know in advance, what the things are going to participate when communication happens. Here, in this context, we will be discussing two types of Contracts:-

• Data Contracts: – Data contracts define the data. They are simple plain classes used to be known as message classes when we used to write web service. These classes have the data, which goes to the service, and response data, which comes out from the service.

• Service Contracts: – Service Contracts define the API. They are the list of operations logically grouped operations exposed to client. This is the only piece, which both client and server share.
DATA CONTRACTS:-
A client makes a call to the service by grouping a bunch of data sending it to the service for further processing and then receiving response. The shape of both the data means incoming and outgoing data defined by data contracts. Incoming data or the request data can be Data Contract or can be argument for example couple of strings or integer packaged together and send in single data contract or that can be sent individually.
However, return data has to be Data Contract, when there is more than one type. Briefly, Data-Contracts are simple classes with just properties in it. Properties we use generally here are auto-implemented property, which I will demo soon. Serializer we use here is Data-Contract Serializer. This is also very much explicit. This is why these are often termed as opt-in serializer. In addition, the attributes, which we will be using here, are
• Data Contract
• Data Member
Before jumping to write my first DataContract let me go ahead and explain the project layout. Below, I have pasted the screen shot of my MovieLib solution.

4th

Now, as you can see that it comprise of seven projects. Out of which two sits inside the Hosting Project. Do not worry about that I will explain each individual bits separately. What I am not going to explain here is Core and Data project as both of these projects are part of my framework, which I already talked in my earlier book http://amzn.to/1w9sIlt. Here, Data project includes data access layer. Data Access Layer uses DbContext to talk to dB, which is nothing but Entity Framework Code First. Now, if you see the below screen shot my entities sit inside the Entities folder which is mapped to the database behind the scenes.

5th

Here, I also have Repositories folder where in my Movie Repository sits. You will see me coding there when I make some calls via repository. In addition, for writing testable software each repository is extracted out from its interfaces. However, I do suggest downloading the code from github (https://github.com/rahulsahay19/MovieLib-WCF ), if you want to code along on the same case study; else, you can make use of WCF concepts directly in your project. This book does not mandate to use my code to code along. You can definitely have your code but you can apply WCF principles from here. The contracts project where I am going to put my data and service contracts. In Services project, I am going to put my services. You need to have services decoupled from contracts; that way you can share the contracts if you are doing referencing. Unit Test project is all about testing WCF Services.

WRITING FIRST DATA CONTRACT:-
In this section, I am going to write my first data contract. This data contract I am going to write in Contracts project as shown below.

6th

7th

Now, before writing my contract let me explain my entity here. In data project under entities folder I already have Movie class as shown below.

using System.Collections.Generic;
using MovieLib.Core;

namespace MovieLib.Data.Entities
{
    public class Movie : IIdentityEntity
    {
        public int Id { get; set; }
        public string MovieName { get; set; }
        public string DirectorName { get; set; }
        public string ReleaseYear { get; set; }
        public virtual ICollection<MoviesReview> Reviews { get; set; }

        public int EntityId
        {
            get { return Id; }
            set { Id = value; }
        }
    }
}

Now, I may choose to share every information what I have in my entity with my client. However, because of my own reason, I choose to give specific things to client and hence I am putting my contracts in a different folder with subset of above properties. Therefore, as you can see below in the snippet I have taken only three properties, which I am willing to send across the client. One more point to note here is naming convention. In the world of WCF, we usually keep DataContract classes end with the name Data; that is why I kept MovieData.

using System.Runtime.Serialization;

namespace MovieLib.Contracts
{
    [DataContract]
    public class MovieData
    {
        [DataMember]
        public string MovieName { get; set; }
        [DataMember]
        public string DirectorName { get; set; }
        [DataMember]
        public string ReleaseYear { get; set; }
    }
}

Now, in order to make it a Data Contract I have annotated the same with the name [DataContract]. This comes from the namespace System.Runtime.Serialization. If you see the references of this project, you will see two important references and that is

8th

One more point to note here, that everything in WCF world come from the name space System.ServiceModel. You might also notice that I have also decorated individual properties with [DataMember] attribute and the reason for this is simple. As I said in WCF, we use opt-in serializer, which means until we decorate explicitly, this property will not participate during serialization. However, Microsoft folks in .NET 4.0 change the DataContract serializer where in if you leave out [DataContract] attribute from the class, every public member becomes automatically serializable. Nevertheless, I like the idea of explicitness.

SERVICE CONTRACT:-
Service Contracts are nothing but logically grouped operations. A service contract defines the operation of service. It means service contract will be having C# Interfaces, which needs to be implemented in service class. In-fact, a service contract is nothing but an interface with method members only no properties. Like the DataContract, we have attributes here as well. These attributes are-

• Service Contract
• Operation Contract
These attributes defined in System.ServiceModel namespace assembly.

WRITING FIRST SERVICE CONTRACT:-
The first service contract I am going to write is IMovieService. This contract I will write in my Contracts project as shown below. As I said, Service Contracts are nothing but C# Interface.

9th

using System;
using System.Collections.Generic;
using System.ServiceModel;

namespace MovieLib.Contracts
{
    [ServiceContract]
    public interface IMovieService
    {
        [OperationContract]
        IEnumerable<string> GetDirectorNames();
    }
}

Here, in the above snippet I have annotated the interface with [ServiceContract] and individual methods as [OperationContract]. Again, these annotations are part of WCF explicitness, so that it can participate in WCF Serialization.

SERVICES:-
Services are simple classes. Services are the implementation of Service Contract for the server side of the wire. Now, a service is the first line of contact or the entry point for the client and it manages all the down level calls. These calls can be anything like simply making a Data-Access layer call and fetching data or making some Business API call for further processing; means could be anything.

WRITING THE SERVICE:-
I am going to write my service in services project and going to name the same MovieManager. As I said earlier, services manages all the down level calls, hence I usually prefer ending my service class name with Manager.

10th

In addition, not to forget my service project is referencing my all dependent assemblies as shown below in the screen shot.

11th

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using MovieLib.Contracts;
using MovieLib.Data.Entities;
using MovieLib.Data.Repositories;
using MovieLib.Data.Repository_Interfaces;

namespace MovieLib.Services
{
   public class MovieManager :IMovieService
    {
        public IEnumerable<string> GetDirectorNames()
        {
            List<string> movieData = new List<string>();
            IMovieRepository movieRepository = new MovieRepository();

           IEnumerable<Movie> movies = movieRepository.GetMovies();

            if (movies != null)
            {
                foreach (Movie movie in movies)
                {
                    movieData.Add(movie.DirectorName);
                }
            }
            
            return movieData;
        }
    }
}

Now, it is worth time investing seeing from where GetMovies() is coming. This is coming from Data project. As I said, Data and Core are prewritten part of framework. Hence, I will not be discussing the same in detail. However, let us have a glimpse of that. First it looks for movie repository where in finds the implementation of dbcontext there.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using MovieLib.Core;
using MovieLib.Data.Entities;
using MovieLib.Data.Repository_Interfaces;


namespace MovieLib.Data.Repositories
{
    public class MovieRepository : DataRepositoryBase<Movie, MovieReviewDbContext>, IMovieRepository
    {
        protected override DbSet<Movie> DbSet(MovieReviewDbContext entityContext)
        {
            return entityContext.Movies;
        }

        protected override Expression<Func<Movie, bool>> IdentifierPredicate(MovieReviewDbContext entityContext, int id)
        {
            return (e => e.Id == id);
        }


        public IEnumerable<Movie> GetMovies()
        {
            using (MovieReviewDbContext entityContext = new MovieReviewDbContext())
            {
                return entityContext.Movies.ToList();

            }
        }
    }
}

Now, GetMovies() is the method defined in the interface IMovieRepository as shown below in the snippet.

using System.Collections.Generic;
using MovieLib.Core;
using MovieLib.Data.Entities;

namespace MovieLib.Data.Repository_Interfaces
{
    public interface IMovieRepository :IDataRepository<Movie>
    {
        IEnumerable<Movie> GetMovies();
    }
}

Also, below is the snapshot of the project structure of data project.

12th

UNIT TESTING:-
In order to do Unit Test, I need to make service class unit testable. One basic rule of testing is do not instantiate dependency. However, in the current scenario, we will end up instantiating dependency and getting live data for testing which is a bad thing. Now, in order to fix this we need to have a way to inject our repositories. This is where Dependency Injection comes into picture. We can use any of DI container available like Ninject, StructureMap, Unity, etc…But in this case, we will simply achieve DI without any container product. I think this will be good during development for testing the product. Then while finishing the project, we can use any container to achieve the same.

Now, to achieve the same I need additional constructors. For Unit Test, we can leverage overloaded constructors and put in our own implementation there. Therefore, this means I am going to widen the scope via class wide repository variables and I will only instantiate when this variable is null. So, if Service class used by WCF, then this variable will be NULL, however if the same is called from Unit Test, then it will have the constructor overloads and send mocks. If you are new to mocking I would suggest, please have some basic idea before jumping to write Unit Test. However, in this case I am going to brief about the same. Below, is the snippet of Unit Testable class with additional constructors.

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using MovieLib.Contracts;
using MovieLib.Data.Entities;
using MovieLib.Data.Repositories;
using MovieLib.Data.Repository_Interfaces;

namespace MovieLib.Services
{
   public class MovieManager :IMovieService
    {
       private IMovieRepository _iMovieRepository;
       public MovieManager()
       {
            
       }

       public MovieManager(IMovieRepository iMovieRepository)
       {
           _iMovieRepository = iMovieRepository;
       }
        public IEnumerable<string> GetDirectorNames()
        {
            List<string> movieData = new List<string>();
            IMovieRepository movieRepository = _iMovieRepository ?? new MovieRepository();

           IEnumerable<Movie> movies = movieRepository.GetMovies();

            if (movies != null)
            {
                foreach (Movie movie in movies)
                {
                    movieData.Add(movie.DirectorName);
                }
            }
            
            return movieData;
        }
    }
}

Now, I am going to create a new Unit Test in Test Project as shown below.

13th

Once the same is created, then I will put the below snippet in my test file

using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using MovieLib.Contracts;
using MovieLib.Data.Entities;
using MovieLib.Data.Repository_Interfaces;
using MovieLib.Services;

namespace MovieLib.Tests
{
    [TestClass]
    public class MovieTests
    {
        [TestMethod]
        public void MovieTest()
        {
            Mock<IMovieRepository> mockMovieRepository = new Mock<IMovieRepository>();

            //Mock return as GetMovies returns the same, so we are not going to hit db
            //we are going to return mocked up entity
            IEnumerable<Movie> movie = new Movie[]
            {
                new Movie()
                {
                    MovieName = "Avatar",
                    DirectorName = "James Cameron",
                    ReleaseYear = "2009"
                },
                new Movie()
                {
                    MovieName = "Titanic",
                    DirectorName = "James Cameron",
                    ReleaseYear = "1997"
                }
            };

            //so, now i am going to setup the mock, Hence below i am telling that when you are encountering
            //following member of mockMovieRepository that receives the following information of GetMovies
            //obj is the implementation of mockMovieRepository. see, mock is creating the test class behind 
            //the scene.
            mockMovieRepository.Setup(obj => obj.GetMovies()).Returns(movie);

            IMovieService movieService = new MovieManager(mockMovieRepository.Object);

            IEnumerable<string> data = movieService.GetDirectorNames();

            Assert.IsTrue(data.ElementAt(0).Contains("James Cameron"));
        }
    }
}

Let me go ahead and explain the code here. Here, I have used moq-testing framework for mocking dependency. You can download and install the same via nuget. Once installed successfully, it will show below shown assembly in the references folder.

14th

If you see the MovieManager code closely, you will find MovieManager is dependent on MovieRepository. Therefore, we will mock MovieRepository here. Rather than using MovieRepository which is designed to hit the database, we need to create a test class or test implementation of IMovie Repository that has its own GetMovies() member and that is instructed to return Movie entity. Then foreach operation will be used to build Movie Entity data.

So, rather than writing explicit test class, I will use Mocking framework which will give me the same test class. In addition, this movie Repository returns me Movie Entity data after hitting the database. Nevertheless, for mocked up version, need to create the mocked up data. Once, mock data is ready, next thing I have done is setup the mock. Here, obj is the implementation of mock MovieRepository as shown below in the screen shot.

15th

Now, my unit test needs to instantiate the manager class. Once, the instance of the movie manager class is ready I need to call GetDirectorNames() which will return the mocked up version of data as constructed above. Once, I build the project and run the test, it will produce me the below result.

16th

SUMMARY:-
In this section we have get started with Data Contracts and Service Contracts. We have also seen why this explicitness is required in WCF. Then, we have implemented the service contract in the service class. In the first session, we just implemented for the sake of implementation. In the second session, we have used class wide variable to make sure that service is testable. In short, we have injected our dependencies as per call. We have also seen moq framework in action.

Buy Here:- http://bit.ly/pragmaticWCF

Kindle Edition:- http://bit.ly/pragmaticWCF-kindle

Code Download Link:- https://github.com/rahulsahay19/MovieLib-WCF

Thanks,
Rahul Sahay
Happy Coding

1,896 total views, 2 views today

Getting Started with LINQ

Hi Friends,

In today’s discussion, we’ll look into LINQ operations. LINQ or Language Integrated Query is a set of language and framework features for constructing type safe queries over local collections or remote data sources. It was introduced in C# 3.0 and framework 3.5.

The basic units of data in LINQ are sequence of elements which actually implements IEnumerable. In the below example,
employees is sequence and “John”,”Dave”,”Black”,”Jack” are elements.

string[] employees = {"John","Dave","Black","Jack"};

A query operator is the one which transforms the sequence. A typical query operator accepts a sequence and emits a transformed output sequence. For, IEnumerable case, we have around 40 query operators. They are also known standard operators.

Let us get started with few simple queries.

Note:- I am using LINQPAD to run these queries. Hence, final statement dump is specific to it. It’s basically used to show the output.

string[] employees = {"John","Dave","Black","Jack","Rahul"};

IEnumerable<string> filtered_emp = employees.Where(n=>n.Length>4);

filtered_emp.Dump("Simple usage of Query");

1st

Since, standard query operators are implemented as static methods, we can directly call Where on employees. Most query operators accept lambda expressions as an argument like here we have n=>n.Length>4.

Now, Let’s look at complex query

string[] employees = {"John","Dave","Black","Jack","Rahul"};

IEnumerable<string> query = employees.Where(n=>n.Contains("a"))
							.OrderBy(n=>n.Length)
							.Select(n=>n.ToLower());

query.Dump("Simple usage of Query");

2nd

here, what it is doing; taking the input, extracts all the strings containing letter a then sorts them by length and then converts the same in lower case. Here, the variable n is privately scoped to each lambda expressions. Here, OrderBy and Select are standard query Operators.

Now, let’s look at Range Variable. The Identifier immediately following the from keyword syntax is called the Range variable. For instance, in below example

from n in new[] { "John","Dave","Black","Jack","Rahul" }
where n.Contains ("a")
select n

3rd

Chaining of query operator is very efficient in many cases like shown below.

string[] names = { "John","Dave","Black","Jack","Rahul" };

IEnumerable<string> query = names
	.Where   (n => n.Contains ("a"))
	.OrderBy (n => n.Length)
	.Select  (n => n.ToUpper());
	
query.Dump();

// same query rewritten progressively:

IEnumerable<string> filtered   = names.Where      (n => n.Contains ("a"));
IEnumerable<string> sorted     = filtered.OrderBy (n => n.Length);
IEnumerable<string> finalone = sorted.Select    (n => n.ToUpper());

filtered.Dump   ("Filtered");
sorted.Dump     ("Sorted");
finalone.Dump ("FinalQuery");

4th

So, as you can see in the above example same final query is achieved in the first expression and again same thing achieved differently by writing the same progressively. Similarly, sometimes we need to keep the natural ordering of numbers as it is.

int[] numbers  = { 10, 9, 8, 7, 6 };

numbers.Take (3)  .Dump ("Take(3) returns the first three numbers in the sequence");
numbers.Skip (3)  .Dump ("Skip(3) returns all but the first three numbers in the sequence");
numbers.Reverse() .Dump ("Reverse does exactly as it says");

5th

Now, in the end there are other important operators which are equally important.

int[] numbers = { 10, 9, 8, 7, 6 };

// Element operators:

numbers.First().Dump ("First");
numbers.Last().Dump ("Last");

numbers.ElementAt (1).Dump ("Second number");
numbers.OrderBy (n => n).First().Dump ("Lowest number");
numbers.OrderBy (n => n).Skip(1).First().Dump ("Second lowest number");

// Aggregation operators:

numbers.Count().Dump ("Count");
numbers.Min().Dump ("Min");

// Quantifiers:

numbers.Contains (9).Dump ("Contains (9)");
numbers.Any().Dump ("Any");
numbers.Any (n => n % 2 != 0).Dump ("Has an odd numbered element");

// Set based operators:

int[] seq1 = { 1, 2, 3 };
int[] seq2 = { 3, 4, 5 };
seq1.Concat (seq2).Dump ("Concat");
seq1.Union (seq2).Dump ("Union");

6th

7th

Thanks for Joining me.

Thanks,
Rahul Sahay
Happy Coding

2,125 total views, 1 views today

Writing Unit Tests against actual legacy data

Hi Friends,

In today’s discussion, we will talk about writing Unit Tests, but it is not about how to get started with Unit Tests. Rather it is about, if you have a scenario where in you need to construct data set which is very primitive and it needs lot of work to construct even mock data. So, the best thing which i find is you can collect the actual data either from SOAP tool, if it is some kind service response and have the same in xml. And then you can write Unit Tests against that like shown below.

For one of the scenarios. Below, I have collected and constructed my XML.

<?xml version="1.0" encoding="utf-8" ?>
<CustomerResponseDTO>
  <ContractList>
    <Contract>
      <ContractNumber>530000000112</ContractNumber>
      <ContractIdPK>713343129248515901</ContractIdPK>
      <CurrencyType>1000001</CurrencyType>
      <CurrencyValue>USD</CurrencyValue>
      <FrequencyModeValue>B</FrequencyModeValue>
      <BillingValue>10 Days Inv</BillingValue>
      <ServiceProvId>1</ServiceProvId>
      <CompanyNumber>19</CompanyNumber>
      <IssueLocation>US</IssueLocation>
      <ContractLastUpdateDate>2015-05-10 16:14:45.158</ContractLastUpdateDate>
      <ContractLastUpdateUser>mdmadmin</ContractLastUpdateUser>
      <ContractLastUpdateTxId>626143129248478201</ContractLastUpdateTxId>
      <AgreementName>MaxWell</AgreementName>
      <ComponentID>1000944</ComponentID>
      <ContractExtension>
        <CreditLimit>222</CreditLimit>
        <ShippingChargeFlag>Y</ShippingChargeFlag>
        <TaxableFlag>Y</TaxableFlag>
        <CustomerClass>SA</CustomerClass>
        <CreatedBy>DSA</CreatedBy>
        <LinkNumDesc>Test</LinkNumDesc>
        <SalesPerson/>
        <ModifyBy>XMODIFY_BY</ModifyBy>
      </ContractExtension>
      <AdminNativeKey>
        <AdminNativeKey>
          <adminNativeKeyIdPK>712243</adminNativeKeyIdPK>
          <adminContractId>530000</adminContractId>
          <adminFieldNameType>CustomerAccountNumber</adminFieldNameType>
          <adminFieldNameValue>123456</adminFieldNameValue>
          <contractId>7133431</contractId>
          <nativeKeyLastUpdateDate>2015-05-10 16:14:45.266</nativeKeyLastUpdateDate>
          <nativeKeyLastUpdateUser>mdmadmin</nativeKeyLastUpdateUser>
          <nativeKeyLastUpdateTxId>6261431</nativeKeyLastUpdateTxId>
        </AdminNativeKey>
      </AdminNativeKey>
    </Contract>
  </ContractList>
</CustomerResponseDTO>

Then, you can write test case like shown below:-

[TestMethod]
        [DeploymentItem(CILXMLFile)]
        public void Should_Have_Customer_Number()
        {
            var actual = GetSampleData();
            //Assert
            Assert.AreEqual(530000, actual.CustomerNumber);
        }

        [TestMethod]
        [DeploymentItem(CILXMLFile)]
        public void Should_Have_Company_Name()
        {
            var actual = GetSampleData();
            //Assert
            Assert.AreEqual("MaxWell", actual.CompanyName);
        }

Then, you can get the GetSampleData() like shown below.

const string XMLFile = @"TestData/TestData.xml";
        private static T DeserializeTestData<T>(string xmlPath) where T : class
        {
            var serializer = new XmlSerializer(typeof(T));

            using (var reader = new StreamReader(xmlPath))
            {
                return (T)serializer.Deserialize(reader);
            }
        }

        private Adapers.Customer GetSampleData()
        {
            //Arrange
            
            var customerResponseDto = DeserializeTestData<CustomerResponseDTO>("TestData.xml");

            Mock<ICustomerSearchServiceWrapper> mock = new Mock<ICustomerSearchServiceWrapper>();



            mock.Setup(
                      obj =>
                          obj.GetCustomer(It.IsAny<GetCustomerRequestDTO>(), It.IsAny<PagingInput>(),
                              It.IsAny<ClientApplicationInfo>()))
                  .Returns(customerResponseDto);

            var objectUnderTest = new TestSearchServiceAdapter(mock.Object,new Mock<IConfigurableSettings>().Object);
            //Act

            var actual = objectUnderTest.GetAddressDetails("1234567890", "US", "BLG");
            return actual;
        }

With the above changes in place, when i run the same, it will produce the below result.

5th

Thanks for joining me.

Thanks,
Rahul Sahay
Happy Coding

1,370 total views, 2 views today

Fluent Assertions

Hi Friends,

Today, i will talk about one of the patterns which i usually use while writing unit tests. Apart from MOQ library, i also use Fluent Assertions(http://www.fluentassertions.com/). You can search for the same in nuget package manager and install it in the test project. Out of the box, fluent assertions give tons of extensions method which help to easily write assertions on the actual like shown below. In the below example, i am just running the test against one sample string of my name.

1st

Now, when i complete this test, it will look like

 [TestMethod]
        public void CheckStringValue()
        {
            string actual = "Rahul Sahay";
            actual.Should().StartWith("Ra").And.EndWith("ay");
        }

When, i run the same it will produce the below result.

2nd

Similarly, To verify that a collection contains a specified number of elements and that all elements match a predicate, you can test like shown below.

 [TestMethod]
        public void CheckCollection()
        {
            IEnumerable collection = new[] { 1, 2, 3,4,5 };
            collection.Should().HaveCount(6, "because I thought I put 5 items in the collection");
        }

Now, when i run the above test, it will fail. And this will fail for a valid reason. But, look at the error message returned by the same.

3rd

Let, me show the same against one of the infrastructure code where i am using the same.

[TestMethod]
        public void MovieNameTest()
        {
            IEnumerable<Movie> movie;
            var mockMovieRepository = MovieRepository(out movie);

            mockMovieRepository.Setup(obj => obj.GetMovies()).Returns(movie);

            IMovieService movieService = new MovieManager(mockMovieRepository.Object);

            IEnumerable<MovieData> data = movieService.GetDirectorNames();

            data.Should().HaveCount(4, "because we put these many values only");


        }

Now, it has one dependency on MovieRepository(out movie). Basically, this is my arrange.

  private static Mock<IMovieRepository> MovieRepository(out IEnumerable<Movie> movie)
        {
            Mock<IMovieRepository> mockMovieRepository = new Mock<IMovieRepository>();

            //Mock return as GetMovies returns the same, so we are not going to hit db
            //we are going to return mocked up entity
            movie = new Movie[]
            {
                new Movie()
                {
                    MovieName = "Avatar",
                    DirectorName = "James Cameron",
                    ReleaseYear = "2009"
                },
                new Movie()
                {
                    MovieName = "Titanic",
                    DirectorName = "James Cameron",
                    ReleaseYear = "1997"
                }
            };
            return mockMovieRepository;
        }

When, i run the above test, it will again throw similar error because count is 2 and i am checking for 4.

4th

Thanks for joining me. I hope you like it.

Rahul Sahay,
Happy Coding

2,087 total views, 3 views today