Thursday, March 8, 2012

Hook windows keyboard - Capture keypress without focus in C#

Here is a class which hooks windows keyboard to capture all keypress events even if your C# application is not focused.



/// 
    /// Capture any window key
    /// 
    public static class WinKeyCapture
    {
        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;
        private static LowLevelKeyboardProc _proc = HookCallback;

        public static void SetHook()
        {
            SetHook(_proc);
        }

        public static void UnHook()
        {
            UnhookWindowsHookEx(_hookID);
        }

        private static IntPtr SetHook(LowLevelKeyboardProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
            }
        }
        private static IntPtr _hookID = IntPtr.Zero;

        private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);

        private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
            {
                int vkCode = Marshal.ReadInt32(lParam);
                if (vkCode == 44)
                    ScreenCapture.Load();
            }
            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook,
            LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
            IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);
    }

Tuesday, March 6, 2012

Single Page Applications using ASP.NET



What is Single Page Application?
Single Page Application is an architecture for web applications. It combines the best of web and desktop, built with HTML5 and JavaScript.Single Page Applications are rich and responsive. You do not need any browser plug-ins needs to install for this architecture, it is a standard web technology that is going to work on any device, operating system and browser.
You can develop Single Page Applications using ASP.NET MVC\Web Forms technologies.
Benefits
1. Great user experience – It means speed, when it comes to changing of display of user interface and navigate around, we want an instance response from the application which you can get from this architecture.
2. Run on any device
3. Working off-line – It is an interesting benefit which is just becoming possible now.
4. App-store deployable - It is bit advanced programming but you can deploy your applications to windows market place or Apple app-store etc. This is now possible with Phone-gap third party tool for developing apps for mobiles.
The Architecture diagram looks as below
image

Typical Web architecture contains a server and client, where server contains an endpoint to server HTML/CSS and JS. The client side this being rendered as Visible UI and contains some javascript as well that is web technology.
What is different in Single Page Applications?
With single page web applications, you also tend to have an data end points on server and it is going to return JSON\XML to your application, You can use this data on client data access layer and render that data to UI.
We also want to have fast UI navigation, to done that we have Navigation API which allows you to book marking, navigate forth and back without talking to the server.
We can also make available all right hand side in the diagram offline. You can use local storage apis in HTML5 to work with the data offline.
Using the new Single Page Application project template and scaffolder
Create a new ASP.NET MVC application in Visual Studio, You can install MVC4 beta from here
image
It will prompt you to select the project template there you can select Single Page Application project template as shown below
image
It creates a MVC application but the difference is it creates additional javascript libraries to make it easier for you build single page applications. If you want to use scaffolding then you can use a model class named TodoItem which will be created for you in model folder
To build a sample Single Page application using scaffolding, Add a controller to your solution
image 
Choose the Single Page application template in controller dialogue box
image
Now run the application then you should be able to see the below output
image
What is different from other scaffolding applications is it follows single page application architecture and when you hit the browser  back and forward it would not talk to the server. It also follows the all principles that we discussed on top.
image
In my next post I am going to discuss about each component in detail and how you can replace them with your own and replacing the scaffolding as well.
image
Each component as shown in the diagram having a specific technology which I can write in next post.

Thursday, March 1, 2012

What’s new in Visual Studio 2011 and ASP.NET 4.5


This is continue bloging to my older post of  New HTML 5 input types in ASP.Net 4.5 Developer Preview.

This post discuss about features in upcoming version of ASP.NET and Visual Studio. Most of the features are around HTML5, CSS and JavaScript. It also discuss about tools and abilities that required to built the modern websites. I am summarizing the MadsKristensen presentation on What’s new in Visual Studio 2011 and ASP.NET 4.5.

HTML5/CSS3/JavaScript
Adding audio and video tags is really simple now!
image
image
image

Productivity features like color selector in CSS is just an example of how it improves the developer workflow. You will get an intellisense for color selector as shown below
image
You can set opacity in Visual Studio 11 editor which is a CSS3 feature
image
You can notice there is a outline feature in CSS editor and you can CTRL + K + C comment the lines in CSS editor.
All browser specific tags are now available in CSS editor Example Borderradius
image
The editor automatically tells what tags are required for all browsers when you type specific HTML element
image
We now have snippets in CSS3 editor. Outlining is available in Javascript as well.
Go to definition works in Javascript editor  and it also takes you to the external files when you referring a function example a Jquery one
image
Working with javascript files in VS 2011 is much easier than ever before.
Design Time Features in Source Editing
There are some cases you need a designer to add the control to your page. There are some cases which you could not do in source editor. If you want to add a button click event you could do by double clicking the control or hooking the event handler using property window.
Now you can create an event handler using source editor as below
image
Now smart tags are available in source editor and in future releases you can expect this for all html elements
image
You can generate a user control by selecting a html code and right click then say extract to user control
image
The outcome of above action would look like as below, it adds a register tag and tag prefix element for your user control. You can also drag and drop the user controls from solution explorer to source editor.
image
The Page Inspector
Assume you had a complex web site which contains several project files, layouts and master pages. You may be asked to change a picture or some text, question is where it is located in this complex web site?
Now you can find the answer using page inspector. right click on your project in solution explorer
image
It actually spins up browser instance and it hosts the application in IE9 and developer tools in solution explorer
image
The editor has a inspect mode and when you hover the mouse on particular element then it highlights the html code for that element. Page Inspector provides the live view of the page
image
You can see what styles are applied to the selected element and when you click then it takes you to the CSS file.
ASP.NET
Runtime Improvements
All the templates and script libraries are now available as NuGet packages. When you create a new ASP.NET MVC4 project in Visual Studio 11 it loads all scripts as NuGet packages in solution explorer. Now you can have all up to date templates and script libraries as NuGet packages.
image
When you run the MVC application then you will see the new template as below
image
you will see the same template web application and web site. This template is built on HTML5 and all are mobile ready
Web Optimization
Instead of referencing a JS file directly , assume this file is located in some folder, now you can reference the folder itself and framework takes all JavaScript files in the folder and creates one file out of it minifies it stripes the all white spaces, gzips and send it to the client. You have concept called bundles where you can bundle your javascript and css files.
Dynamic Bundles are folder based and Static Bundles are in your control where you can hook anything.
image
Async in web pages
assume you are making two web requests and when they complete on the background thread you want to return the response.
image
Universal Providers
Membership, Profile, Role, Session providers only work against certain versions of SQL Server. Universal Providers built on top of entity framework and  work against any database supported by EF. Now there is a support for Azure as NuGet package.
Request Validation
It is a security feature and it stops malicious attacks. Assume you have got a form and submitting some html to that form, Request Validation stops this in past!
image
Now you have granular request validation , you can keep it turned on at application level and turn off at control level as shown below
image
Miscellaneous
  • You now have 30% faster start-up time when you first send a request to your website.
  • Incremental File Upload support. Multiple file upload support
  • Allows uploads > 2GB
  • Anti-XSS encoders(URL and HTML encoding)
ASP.NET Web Forms
Supporting HTML5 attribute support for ASP.NET controls. example now you can have input type=date equivalent in asp.net
image
image
Strongly Typed Controls
Support modeltype to data bound controls to bind the data using expression with intellisense support. Notice you will also have methods for Insert, Update and Select
image
image
ASP.NET MVC 4
  • Supports Visual Studio 2010
  • Ships with Visual Studio 2011
  • Mobile Support and Mobile Template
  • Single page applications
  • WCF Web API
Web API can be read more about here

More info I will cover in my next post to this series.

ASP.NET Web API



ASP.NET Web API is Framework for building for building HTTP services on top of the .NET Framework. It ships with ASP.NET MVC 4. You can install the ASP.NET MVC 4 from here. ASP.NET Web API is a integrated Framework resulted in joint effort from WCF and ASP.NET teams. WCF REST is now replaced by ASP.NET Web API. You can read the post to migrate your existing WCF Web API to ASP.NET Web API. This post briefly discuss about why we need it and how we can use it in ASP.NET and other projects.

Why use ASP.NET Web API?
  • Reach More Clients – By creating HTTP services by using client appropriate formats you making your application broadly available. Your services not just consumed by browsers but also client applications, mobile applications and other devices. In this way you are having interoperability with other applications directly by consuming your services

  • ASP.NET Web API uses content negotiation which makes it easy to provide the right format for each client like XML, JSON or custom formats
  • Scale with the Cloud – by using fully asynchronous task based service framework which provide light-weight hosting options including windows azure web or worker roles.
  • Embrace HTTP HTTP is an application level protocol and is supported on clients. It really simplifies the communication with clients.
More about the ASP.NET Web API features can be read here
Create a new project in Visual Studio and select ASP.NET MVC 4 web application template
image
Web API is one of the new built-in project template which you can select as shown in the below dialogue
image
This creates a new controller named ValuesController in your ASP.NET MVC application which implements APIController has some simple methods for returning sample data like Get, Put , Post and Delete. These are mapped to HTTP standard verbs.
image
These are implemented using standard ASP.NET MVC routing behavior, You can find a route find a ASP.NET Web API
image
Run the application and see the output, you can not browse directly the output of Web API but you can see what it is doing by using developer tools
image
Using the IE developer tools capture the output by typing the URL as shown below
image
if you look at the body of the response it is returning the below output
image
the above output is directly maps to output of the Get method in ValuesController.
The self hosting capability of WCF is still possible with ASP.NET Web API, all the features that you see in ASP.NET MVC routing, action based controller are still work out side web application. You can see the same features in console application by self hosting the service
image
image
tell the application where to listen for the service then the above code is using full asp.net routing and working in self host console application.

You can check out the new updates in ASP.NET 4.5 here.

Find a cool free stuff everyday

Giveaway of the Day

Hiren Bharadwa's Posts

DotNetJalps