Wednesday, May 30, 2012

WCF Service Creation With C#


Basic WCF Service Creation in C#.Net => Part1



Hello All, this is the start up guide to create WCF service. This article is a pictorial step by step help to create WCF application.

WCF (Windows Communication Foundation) is a part of .Net 3.0. So you need to install Visual Studio 2008 to use WCF.
It is platform for SOA. WCF provides a way to create loosely coupled application.
WCF is intended to provide services that are distributed and interoperable.
It unifies ASMX and .NET Remoting, MSMQ and can be easily extended to support new protocol.

When we create a Service, to expose the functionality to the world, it needs to be hosted into Host Process. Service Host will be used to expose the end point of the service to other Service or Clients.

Let’s start with the steps...

We will start with VS 2008. Create a File -> New Project -> WCF ->WCFClassLibrary project as shown below



Select WCF in left panel and WCF Service Library in the right panel.

Give appropriate name in the Name Box. Click Ok.


The Project will contain a sample Service1.cs & IService.cs files. Delete it. So that we can add our own service and understand the things in better way.

Right click on MathsLibrary -> Add -> New Item -> Select Class1.cs. 
Rename it to MathsOperations.cs
This will create a simple class file. Open the file. Make the class public.
Similary add one more class IMathsOperations.cs, which will be an interface, which will provide a list of what all operations a WCF service will perform.
Open IMathsOperations.cs and change it to public interface IMathsOperations
And add the below code to it..

To make IMathsOperations as WCF Service Contract, add an attribute [ServiceContract] to it.
Also what all operation you want to make visible to client should be decorated with [OperationContract].
[ServiceContract] and [OperationContract] are included in System.ServiceModel namespace.


Now once decided with the contract, we can implement this interface into our srevice as below

Build the project once you are done up to this.

Let us add app.config to Host solution.
App.config contains endpoint details, which includes ABC (Address, Binding and Contract)
Address is the Address WHERE the service can be found.
Binding the HOW to access the service
Contract is WHAT the service contains.

Now let’s modify App.config. Right click on App.config, click on Edit WCF Configuration




Below popup should appear

Select the Service1 from left panel, following window should show up



Click on ellipses button and go the path where the MathsLibrary.dll exists.
Click on it, it will give you the name of the service it contains.


Similarly go to Endpoints, and select proper contract with same steps as above. 




Also we can change the binding to be used as below…






Select Host on left hand side and it will show you base address, edit the base address to whatever you want..

Once this is done. Build the project.
VS 2008 provides you the way to host the service. We can also host it in console application or Windows Service or IIS.
We will learn those in next parts. Here we will use the host provided by VS 2008.
Now let’s create a client application. Add console application (Or any other project type) project in same solution or different solution.
Add service reference to the MathsService that we have created. It will automatically load all necessary dlls. 

Then with the below code we can give a call to the service..

















This will give you below output


In the next sub-sections we will see how to host this service in IIS, Windows services, Console applications etc.

Tuesday, May 29, 2012

What Firefox Users Want

Firefox was 1st choice of all techy guys before chrome and still it have a large user base and people love it. Still there are few things which users demands in Firefox from other browsers. 
 
Here is the list what Firefox users wants
  • This extension and separate/concurrent private browsing tabs and/or windows (Opera has private browsing tabs, which in my opinion are really useful). - by morally_bankrupt77
  • In Chrome you can have both private and normal session together but in Firefox starting private session suspend normal session and vice varsa. Dont know why private browsing is not implemented that way. - by dvgaba
  • Auto-add of search engines and accessing them using tab in the awesome bar.
    When I visit amazon.com in chrome and search for something, and then the next time I open up a tab and start typing amazon.com, there is this option to hit tab and then search within amazon, without having to go to the page first. That is by far one of the things I miss the MOST from chrome - by c0d3M0nk3y
  • Multi-process architecture, so one tab does not lock or crashes the others. I really don't know why this is not on their top priority list. I'm willing to bet that this will fix all of the complains about Firefox being slow or hanging. All the MemShrink progress is great but Firefox still feels bloated and slower than Chrome. -_rs
  • The sandbox. And this is not something only from Chrome, at this moment, Firefox is the only big browser without one, even Internet Explorer has it. by -_rs
  • hoverzoom image-viewer by Kylde
  • In-chrome settings but that's already planned. Also, Australis Theme and better built-in personalization tools like Stratiform. by samingue   
Here is what is listed in Firefox Bugzilla

Sunday, May 27, 2012

Firefox and great add-ons

Firefox is a great browser to have as your default browser. Great speed, security and always one step ahead in innovation. And Mozilla itself takes a deep interest in users privacy and usability. Feature like "Do Not Track" and BrowserId are created for users. 
Chrome is a decent browser but its a wrapper on webkit only where Firefox is true innovation and real product. Google created Chrome/Android keeping there ads business in mind. In terms of speed Firefox and Chrome are very close to each other but in terms of add-ons Firefox knockout Chrome. Install Firefox is you want innovation in browsers and you dont want to be tracked by Big "G". 

And IE dont have anything to be compared with Firefox/Chrome as its a dead browsers and MS even dont roll new versions to Old versions for there own Old Windows OS. 

  • Noscript - Best Add-on to have in your kitty. Want to know why then better try it today. Feel little annoying in starting but trust me it worth the headache. 
  • Adblock Plus - Name itself tells what it do. 
  •  Firebug - Best friend of all web developers.
Download Aurora
Download NoScript
Download Adblock
Download Firebug

Friday, May 25, 2012

Getting Started With ForkJoinPool - Map & Reduce of Java



ForkJoinPool ::FJP is a executor service for Fork-Join Taks or tasks which can computed using divide and conqor or we can say FJP is inbuild Map & Reduce framework in Java.
               FJP implements work-steal so all threads try to find and execute task submitted by other tasks in FJP or external program. FJP try to maintain active threads as per number of processor available.
  FJP provides below methods to submit task ::==>

Call Type External Task Clients i.e. main method Inner Task Divide and Conquer Calls
Call from non-fork/join clients  Call from within fork/join computations
Arrange async execution  execute(ForkJoinTask)  ForkJoinTask.fork()
Await and obtain result  invoke(ForkJoinTask)  ForkJoinTask.invoke()
Arrange exec and obtain Future  submit(ForkJoinTask)  ForkJoinTask.fork() (ForkJoinTasks are Futures)




Pre-requiste :: FJP is in-builted in Java 7. You can download and install the same from Oracle.
You can either configure Java in your system path and also set JAVA_HOME to home directory of JDK installation.
Or you can use Eclipse and configure JRE in eclipse.

You can also use FJP with Java 6 but you need to do some configuration to make it work.
1st you need to download JSR166 from here.
Add JSR166 in your classpath in eclipse or using -cp when compling 
And when running your program you need to pass VM Arguments as -Xbootclasspath/p:jsr166.jar in eclipse or using Java command line utility.

Getting Started ::
Classes which we use in our example
ForkJoinPool :: ForkJoinPool is used to create a pool of threads. You can pass number of processers as arguments.
RecursiveTask<V> :: RecursiveTask implements ForkJoinTask and its compute method computes the result and return a result of type V.
RecursiveAction  :: Similar to RecursiveTask but its compute method doesn't return anything means void.
ForkJoinTask     :: Superclass of RecursiveAction and RecursiveTaks. Provides methods like fork, join, invokeAll to create subtaks from current task and submit to Pool.

Creating ForkJoinPool

You can create ForkJoinPool as
ForkJoinPool fjp = new ForkJoinPool(); // Use all available processors
or
ForkJoinPool fjp = new ForkJoinPool(numperOfProcessors); // Use number of processors passed

Creating RecursiveTask<V>
In RecursiveTask compute method is similar to run method of Thread/Runnable and call method of Callable interface.
So we will not call compute method ourselves. But all logic to divide big task into smaller task will be in compute method.
You need to create a subclass of RecursiveTask<V> to start get going. Also we need to pass data to newly created class.
So best way is to create parameterized constuctor. And Store the data at instance level. So compute method can access the data and work on it.

Code With Comments 

package com.thekarna.fjp; import java.util.Random; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.Future; import java.util.concurrent.RecursiveTask; /** * This class glues all code required for FJP Demo. * In many cases given implementation can perform worse then single threaded max finder * So don't use this to benchmark, * this is only a Hello World Kind of program to get started with FJP * @author DVG * */ public class MaxFinderFJP { /** * This class extends RecursiveTask class * RecursiveTask class is quite similar to Thread/Runnable/Callable in context to ExecutorService * And compute method of this class is similar to run/call method of Runnable/Callable * compute method is the place where you will write your problem solution and also logic to divide & conquer * You can also extend RecursiveAction but that return void * @author DVG * * @param <T> */ @SuppressWarnings("all") private static class MaxFinderTask<T> extends RecursiveTask<T> { private static final int THRESHOLD = 10000; private T targetArray[] = null; private int low; private int high; /** * Parameterized so the callee can pass data * @param arr */ public MaxFinderTask(T arr[]) { targetArray = arr; low = 0; high = targetArray.length; } private MaxFinderTask(T arr[], int low, int high) { targetArray = arr; this.low = low; this.high = high; } /** * Bread & Butter for ForkJoinPool * All Logic Go Below * @return */ @Override protected T compute() { /* If Task is small then compute it normally as diving more then required will result in negative way */ if (high - low <=MaxFinderTask.THRESHOLD) { return this.computeNormal(); } int mid = (high - low) / 2; T result = null; T result2 = null; //Divide The Big Task in Smaller Task So All Processor Can Get There Share MaxFinderTask<T> leftTask = new MaxFinderTask<>(this.targetArray, low, low+mid); MaxFinderTask<T> rightTask = new MaxFinderTask<>(this.targetArray, low+mid, high); //Fork 1st Task, Fork is a non-blocking call so current thread will move ahead. leftTask.fork(); //Call compute directly which will result in again divide & conquer result2 = rightTask.compute(); //Calling Join Result in blocking call but Divide & conquer will go ahead in newly created leftTask result = leftTask.join(); //Merge Results and Return return ((Comparable) result).compareTo(((Comparable) result2)) > -1 ? result : result2; } /** * This Method Found Max in Normal Way * @return */ protected T computeNormal() { if (this.targetArray.length == 1) { return this.targetArray[0]; } Comparable cMax = (Comparable)this.targetArray[0]; for(int i=low; i<high; i++) { Comparable obj = (Comparable)this.targetArray[i]; if(obj.compareTo(cMax) > 0) { cMax = obj; } } return (T)cMax; } } /** * This is where all things get going on * @param args */ public static void main(String[] args) { //Create a array of millions/billion entries Integer d[] = new Integer[100_000_0]; //Fill it with random data for (int i = 0; i < d.length; i++) { Random r = new Random(System.nanoTime()); d[i] = r.nextInt(); } final long startTime = System.currentTimeMillis(); //Create a ForkJoinPool final ForkJoinPool forkJoinPool = new ForkJoinPool(); //Create Object of MaxFinderTask and Call Invoke which is a blocking call //You can also use submit method and can use submit which returns Future //final Future<Integer> futureResult = forkJoinPool.submit(new MaxFinderTask<Integer>(d)); final Integer result = forkJoinPool.invoke(new MaxFinderTask<Integer>(d)); //final Future<Integer> futureResult = forkJoinPool.submit(new MaxFinderTask<Integer>(d)); forkJoinPool.shutdown(); System.out.println("Max == " + result); System.out.println("Time Taken FJP == " + (System.currentTimeMillis() - startTime)); } }

Tuesday, May 22, 2012

My 1st Haskell Program

From past few days I was thinking to do something in Haskell. Gone though few blogs and also tried my hands on tryhaskell only Haskell interactive tutorial. It was way different then my bread & butter Java. So wasn't able to understand much. And now was feeling to write a factorial program in Haskell. My first experiment with Haskell. 


Downloaded Haskell from here
Now Install Haskell similar the way you installed millions of software.
Haskell itself update %PATH% variable so you are not ready to rock and roll in Haskell.


Haskell comes with ghci, ghc and runhaskell utilities to interpret, compile or run haskell programs.



  • ghci provide haskell prompt where you can execute haskell statements on the fly.
  • ghc is haskell compiler which compile haskell program and produce an exe on successful compilation.
  • runhaskell utility run haskell program on the fly.
Below is mine 1st real haskell program



  1. Line 1 Prototype of factorial function.
  2. Line 2 Body of factorial program, used recursion
  3. Line 4 Here we need to execute multiple statements in main so we are using do syntax here
  4. Line 5 Give a message to user
  5. Line 6 It takes value from IO and store it in numS variable and you cant use = instead of <- As using = will give IO operation another name rather then reading value from IO
  6. Line 7 read function convert String to Integer and then give the result to factorial function and factorial function computes the result and print function display the result.

This is my 1st real haskell program, I am not fully aware of haskell or haskell terminology so there may be many mistakes.


Code
1
2
3
4
5
6
7
factorial :: Integer -> Integer
factorial n = if n > 0 then n * factorial (n-1) else 1

main = do
    print "Enter a Number" 
    numS <- getLine
    print (factorial (read numS))


After detailed review of above program by fellow reddit haskellers I come to know that there is lots of improvement needed in this program and that also helped me to dig deeper in haskell.

Instead of IF ELSE + Recursion now factorial method uses Pattern Matching. 
Pattern Matching is similar to Switch Statements of High Level Languages. When you call a method haskell run time scan the program from top to down order and go to the 1st match same to switch statement.
And if you reverse the order of factorial function declaration like below compiler will always go to 1st statement.


factorial n = n * factorial (n-1)

factorial 0 = 1


Print function is used for displaying non-string type as String on I/O so using print to display "Enter a Number" message results in extra double quotes in message so I changed it to putStrLn as suggested by dave4420 on reddit.


And instead of using parentheses I changed last line to haskell way which is much clear and haskelly. 


Updated Code


1
2
3
4
5
6
7
8
factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n-1)

main = do
	   putStrLn "Enter a Number"	
	   numS <- getLine
	   print $ factorial $ read numS

Monday, May 21, 2012

Starting with HTML5 Forms

HTML5 forms add a lot of power to html forms which result in reduced development time. And HTML5 are improved for developer as well as users using them.


HTML5 specification added lots of feature in forms but all browsers are at different states. Check www.html5test.com for current support to HTML5 form elements.

Below is the list of newly added input type in HTML5. 



Input Type Purpose
tel For entering a telephone number.
search To prompt users to enter text that they want to search for.
url For entering a single URL.
email For entering either a single email address or a list of email addresses.
datetime For entering a date and time with the time zone set to UTC.
date For entering a date with no time zone.
month For entering a date with a year and a month, but no time zone.
week For entering a date that consists of a week-year number and a week number, but no time zone.
time For entering a time value with hour, minute, seconds, and fractional seconds, but no time zone.
datetime-local For entering a date and time with no time zone.
number For numerical input.
range For numerical input, but unlike number, the actual is not important.
color For choosing color through a color well control.


Example of HTML form input elements. And if you need any custom type then you can use pattern attribute to achieve it. And from below example it is very clear that new input elements saves a lot of javascript validation code. Code for example form is provided below.











<form oninput='fullName.value = "Mr. " + firstName.value + " " + lastName.value' onsubmit="return alter('Saved')";>
<output id="fullName" name="fullName"></output><br/>
<input type="text" id="firstName" name="firstName" placeholder="Enter First Name" required="required" autofocus="autofocus"/><br/>  
<input type="text" id="lastName" name="lastName" placeholder="Enter Last Name" required="required"/><br/>
<input type="email" id="email" name="email" placeholder="example@demo.com" required="required"/><br/>
<input type="email" id="emailConfirm" name="emailConfirm" placeholder="Confirm Email Address" required="required" oninput="verifyEmail(this)"/><br/>
<input type="tel" id="telNo" name="telNo" placeholder="Enter Your Phonenumber"/><br/>
<input type="url" id="webAddress" name="webAddress" placeholder="Enter Your Website"/><br/>
<input type="number" id="age" name="age" min="18" max="100" required="required" placeholder="Enter Your Age"/><br/>
<input type="submit" value="Save Info" /> <br/>
</form>
<script>
function verifyEmail(input) {
  if (input.value != document.getElementById('email').value) {
    input.setCustomValidity('The two email addresses must match.');
  } else {
    // input is valid -- reset the error message
    input.setCustomValidity('');
  }
}
</script>

Sunday, May 20, 2012

Hello Vertx Javascript

Everyone is talking about node.js but another new kid in town is vert.x which is similar in nature to node (talking in terms of javascript server side programming). So today we will write Hello World in vertx.   


Steps :: 

  • Click here to download vertx or go to vertx home page here
  • Create environment variable VERTX_HOME with value as extracted vertx directory
  • Add %VERTX_HOME%\bin to %PATH%

Now you are ready to code.
Here is the code

load('vertx.js')


//Configure Vertx server to listen on port 8080 for incoming http requests
vertx.createHttpServer().requestHandler(function(req) {
  req.response.end("<html><body><h1>Hello from vert.x!</h1></body></html>");
}).listen(8080, 'localhost');

stdout.println("Server is running on " + "http://127.0.0.1:8080");


Save above code as server-helloworld.js


Start node server as
>vertx  run server-helloworld.js
Server is running on http://127.0.0.1:8080
Now go to http://127.0.0.1:8080/ and see the magic

Lots of valuable tutorial for various vertx utilities are located in %VERTX_HOME%\examples\javascript

For above code check in %VERTX_HOME%\examples\javascript\http directory.

Starting With Node on Windows - Part2

In last post  we start with node on windows and create a simple console based "Hello World" program in node.
But node is designed to serve on HTTP protocol so today we will write our 1st server side node program.


Here is the code
//Load http module required for http protocol communications
var http = require('http');
//Configure http server to respond all request with Hello World From Node Server
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World From Node Server\n");
});
// Listen on port 8080, IP defaults to 127.0.0.1
server.listen(8080);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8080/");


Save above code as server-helloworld.js


Start node server as
>node server-helloworld.js
Server running at http://127.0.0.1:8080/
Now go to http://127.0.0.1:8080/ and see the magic