Wednesday, January 19, 2011
Visual studio resolve usings.
I know a lot of us are hardcore ReSharper users and can do all kinds of jedi-like moves in the Visual Studio 2008 IDE. However, get us without ReSharper at times and we just stare at the keyboard in bewilderment wondering why namespaces aren't resolving, usings are being optimized, and refactorings are not taking place at blinding speeds, etc.
It turns out, Visual Studio 2008 actually has good support for resolving namespaces and optmizing using statements that can get you the functionality if you are not using ReSharper.
Resolving Namespaces
When you are writing code and Visual Studio places a small red notification rectangle at the end of the class,
Pressing Ctrl + . will bring up a context-sensitive menu that allows you to add a using statement or optionally fully qualify the path to the class.
Clicking the Enter Key will automatically add using System.Collections.Generic; with the other using statements, requiring no touch of the mouse.
This also works with attributes as well. Adding an attribute that needs a using statement to qualify its namespace will cause the same red notification rectangle to appear:
and pressing Ctrl + . will allow you to add the using statement, etc.
Optimizing, Removing, and Sorting Unused Using Statements
The other nice thing that ReSharper does is remove unused using statements using Ctrl+Alt+O.
We can get that using Visual Studio 2008, because you may have noticed the cool context-sensitive Organize Usings Option:
Very, very cool, but this needs to have a shortcut because we will be using it often. I want to use the familar Ctrl+Alt+O shortcut that I get from ReSharper ( you can choose your own ) so I need to map the shortcut to the Edit.RemoveAndSort Command in the keyboard options:
Now when I type Ctrl+Alt+O in the code editor it will remove all unused using statements in the current file as well as sort those using statements that are being used.
Very cool! Hope this helps.
Monday, January 3, 2011
A simple distributed lock with memcached
When you have a cluster of web application servers, you often need to coordinate the activity of your servers to avoid the same expensive work being done at the same time when a condition triggers it.
Most people use memcached as a simple key/value store but it can also be used as a simple distributed lock manager: along with the put(key, value) operation, it also has an add(key, value) operation that succeeds only if the cache wasn't already holding a value for the key.
Locking then becomes easy:
if (cache.add("lock:xyz", "1", System.currentTimeMillis() + 60000)) { try { doSomeExpensiveStuff(); } finally { cache.delete("lock:xyz"); } } else {// someone else is doing the expensive stuff
}
The code above tries to get the lock by adding a dumb value for our lock's idenfitier, with an expiration of one minute. This is the lock lease time, and should be more than the estimated maximum time for the lengthy operation. This avoids the lock being held forever if ever things go really bad such as your server crashing.
Once the operation is completed, we delete the lock, et voilĂ .
If you want the system to be rock-solid, you should check that you still own the lock before deleting it (in case the lease time expired), but in most cases this simple approach works nicely.
And if the expensive operation resets in the database the condition that triggered it, the lock should be released once the transaction has been committed to prevent a race condition in the time interval between the end of the expensive operation and the actual commit that would allow other servers to restart the same work. Spring's transaction synchronization helps doing that.
Registering an Application to a URL protocol
Registering an Application to a URL Protocol
The About Asynchronous Pluggable Protocols article describes how to develop handlers for URL protocols. In some cases, it may be desirable to invoke another application to handle a custom protocol. To do so, register the existing application as a URL Protocol handler. Once the application has successfully launched, it can use command-line parameters to retrieve the URL that launched it. These settings apply to protocol handlers launched from within Windows Internet Explorer and from Windows Explorer using the Run... command (Windows logo key+R).
This topic contains the following sections:
- Registering the Application Handling the Custom Protocol
- Launching the Handler
- Security Issues
- Example Protocol Handler
- Related Topics
Registering the Application Handling the Custom Protocol
To register an application to handle a particular URL protocol, add a new key, along with the appropriate subkeys and values, to HKEY_CLASSES_ROOT. The root key must match the protocol scheme that is being added. For instance, to add an "alert:" protocol, add an alert key to HKEY_CLASSES_ROOT, as follows:
alert
URL Protocol = ""
Under this new key, the URL Protocol string value indicates that this key declares a custom protocol handler. Without this key, the handler application will not launch. The value should be an empty string.
Keys should also be added for DefaultIcon and shell. The Default string value of the DefaultIcon key must be the file name to use as an icon for this new URL protocol. The string takes the form "path, iconindex" with a maximum length of MAX_PATH. The name of the first key under the shell key should be an action verb, such as open. Under this key, a command key or aDDEEXEC key indicate how the handler should be invoked. The values under the command and DDEEXEC keys describe how to launch the application handling the new protocol.
Finally, the Default string value should contain the display name of the new protocol. The following example shows how to register an application, alert.exe in this case, to handle the alertprotocol.
alert
(Default) = "URL:Alert Protocol"
URL Protocol = ""
DefaultIcon
(Default) = "alert.exe,1"
shell
open
command
(Default) = "C:\Program Files\Alert\alert.exe" "%1"
When a user clicks a link registered to your custom URL protocol, Internet Explorer launches the registered URL protocol handler. If the specified open command specified in the registry contains a %1 parameter, Internet Explorer passes the URL to the registered protocol handler application.
Launching the Handler
By adding the above settings to the registry, navigating to URLs such as alert:Hello%20World would cause an attempt to launch alert.exe with the complete URL on the command line. Internet Explorer decodes the URL, but the Windows Run... command does not. If a URL contains spaces, it may be split across more than one argument on the command line.
For example, if the link above is followed through Internet Explorer, the command line would be:
If this link is followed through Windows Explorer, the Windows Run command, or some other application, the command line would be:
Because Internet Explorer will decode all percent-encoded octets in the URL before passing the URL to ShellExecute, URLs such as alert:%3F? will be given to the alert application protocol handler as alert:??. The handler won't know that the first question mark was percent-encoded. To avoid this issue, application protocol handlers and their associated URL scheme must not rely on encoding. If encoding is necessary, protocol handlers should use another type of encoding that is compatible with URL syntax, such as Base64 encoding. Double percent-encoding is not a perfect solution either; if the application protocol URL isn't processed by Internet Explorer, it will not be decoded.
When ShellExecute executes the application protocol handler with the URL on the command line, any non-encoded spaces, quotes, and slashes in the URL will be interpreted as part of the command line. This means that if you use C/C++'s argc and argv to determine the arguments passed to your application, the URL may be broken across multiple parameters. To mitigate this issue:
- Avoid spaces, quotes, or backslashes in your URL
- Quote the %1 in the registration ("%1" as written in the 'alert' example registration)
However, avoidance doesn't completely solve the problem of quotes in the URL or a backslash at the end of the URL.
Security Issues
As noted above, the URL that is passed to an application protocol handler might be broken across multiple parameters. Malicious parties could use additional quote or backslash characters to pass additional command line parameters. For this reason, application protocol handlers should assume that any parameters on the command line could come from malicious parties, and carefully validate them. Applications that could initiate dangerous actions based on external data must first confirm those actions with the user. In addition, handling applications should be tested with URLs that are overly long or contain unexpected (or undesirable) character sequences.
For more information, please see Writing Secure Code.
Example Protocol Handler
The following sample code contains a simple C# console application demonstrating one way to implement a protocol handler for the alert protocol.
using System; using System.Collections.Generic; using System.Text; namespace Alert { class Program { static string ProcessInput(string s) { // TODO Verify and validate the input // string as appropriate for your application. return s; } static void Main(string[] args) { Console.WriteLine("Alert.exe invoked with the following parameters.\r\n"); Console.WriteLine("Raw command-line: \n\t" + Environment.CommandLine); Console.WriteLine("\n\nArguments:\n"); foreach (string s in args) { Console.WriteLine("\t" + ProcessInput(s)); } Console.WriteLine("\nPress any key to continue..."); Console.ReadKey(); } } } When invoked with the URL alert:"Hello%20World" (note extra quotes) from Internet Explorer, the program responds with:
Wednesday, December 29, 2010
How to make your ASP.Net label multiline (how to wrap text in your label)
With that said, I want to offer a little tip to help with formatting your ASP.Net pages. Getting a label to be multiline within a set width. Now many of you know this trick, but I always have to re-remember the trick every time I need it, so this post can be a reference for you as well.
The trick is actually this - Don't use a label. Use a textbox instead. Since all the controls inherit from the same base class, the text box and the label are very similar anyway. But only the textbox has the multiline capability.
Once you have the textbox on your page the trick is to make it look like a label for the end user. To do this you need to set the following properties (This is the part I can never remember):
Wrap = true; (obviously)
rows = {some number greater than 0} (I use the rows property rather than the height property as it tends to be earier to get the formatting right)
ReadOnly = true (makes sense, right)
TextMode = multiline (or there no real reason to wrap the text...)
BorderStyle = None
BorderWidth = 0
Those last two are actually VERY important, and here is why. They get rid of that pesky border that you see around text boxes. That border is a common visual signal to the end user that says "ENTER INFO HERE!". If you leave the border up expect a lot of phone calls from folks saying "The web page is broken. It won't let me enter text."
So use this in good faith. More controls soon. Even my first 2.0 controls.
Tuesday, December 21, 2010
C# Caching
Friday, December 17, 2010
Hello World RPC Server
import com.google.gwt.user.client.rpc.RemoteService;
public interface HelloWorldService extends RemoteService
{
public String sayHello(String sender);
}
package org.mortbay.gwt.example.client;
import com.google.gwt.user.client.rpc.RemoteService;
public interface HelloWorldService extends RemoteService
{
public String sayHello(String sender);
}
package org.mortbay.gwt.example.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface HelloWorldServiceAsync
{
public void sayHello(String sender, AsyncCallback callback);
}
Using Continuations (RetryRequest) | jetty6
package org.mortbay.gwt.example.server;
import javax.servlet.http.HttpServletRequest;
import org.mortbay.gwt.AsyncRemoteServiceServlet;
import org.mortbay.gwt.example.client.HelloWorldService;
import org.mortbay.util.ajax.Continuation;
import org.mortbay.util.ajax.ContinuationSupport;
public class HelloWorldServiceImpl extends AsyncRemoteServiceServlet implements HelloWorldService
{
private static final long serialVersionUID = 1L;
public String sayHello(String sender)
{
HttpServletRequest request = getThreadLocalRequest();
Continuation continuation = ContinuationSupport.getContinuation(request, null);
if(continuation.isNew() || !continuation.isPending())
{
request.setAttribute("ts", Long.valueOf(System.currentTimeMillis()));
continuation.suspend(5000);
}
long elapsed = System.currentTimeMillis() - ((Long)request.getAttribute("ts")).longValue();
return "Hello world *" + sender + "* resumed after " + elapsed + " ms";
}
}
Using Servlet-3.0 suspend/resume api | jetty7
package org.mortbay.gwt.example.server;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mortbay.gwt.AsyncRemoteServiceServlet;
import org.mortbay.gwt.example.client.HelloWorldService;
public class HelloWorldServiceImpl extends AsyncRemoteServiceServlet implements HelloWorldService
{
private static final long serialVersionUID = 1L;
public String sayHello(String sender)
{
HttpServletRequest request = getThreadLocalRequest();
HttpServletResponse response = getThreadLocalResponse();
System.err.println("HANDLING: " + request + " | " + request.hashCode() + " | " + response.hashCode());
if(request.isInitial())
{
request.setAttribute("ts", Long.valueOf(System.currentTimeMillis()));
request.suspend(5000);
return null;
}
// timed-out or resumed
System.err.println("RESPONDING");
long elapsed = System.currentTimeMillis() - ((Long)request.getAttribute("ts")).longValue();
return "Hello world *" + sender + "* resumed after " + elapsed + " ms";
}
}
SetWindowsHookEx
Syntax
Copy
HHOOK WINAPI SetWindowsHookEx(
__in int idHook,
__in HOOKPROC lpfn,
__in HINSTANCE hMod,
__in DWORD dwThreadId
);
Parameters
idHook [in]
Type: int
The type of hook procedure to be installed. This parameter can be one of the following values.
Value Meaning
WH_CALLWNDPROC
4
Installs a hook procedure that monitors messages before the system sends them to the destination window procedure. For more information, see the CallWndProc hook procedure.
WH_CALLWNDPROCRET
12
Installs a hook procedure that monitors messages after they have been processed by the destination window procedure. For more information, see the CallWndRetProc hook procedure.
WH_CBT
5
Installs a hook procedure that receives notifications useful to a CBT application. For more information, see the CBTProc hook procedure.
WH_DEBUG
9
Installs a hook procedure useful for debugging other hook procedures. For more information, see the DebugProc hook procedure.
WH_FOREGROUNDIDLE
11
Installs a hook procedure that will be called when the application's foreground thread is about to become idle. This hook is useful for performing low priority tasks during idle time. For more information, see the ForegroundIdleProc hook procedure.
WH_GETMESSAGE
3
Installs a hook procedure that monitors messages posted to a message queue. For more information, see the GetMsgProc hook procedure.
WH_JOURNALPLAYBACK
1
Installs a hook procedure that posts messages previously recorded by a WH_JOURNALRECORD hook procedure. For more information, see the JournalPlaybackProc hook procedure.
WH_JOURNALRECORD
0
Installs a hook procedure that records input messages posted to the system message queue. This hook is useful for recording macros. For more information, see the JournalRecordProc hook procedure.
WH_KEYBOARD
2
Installs a hook procedure that monitors keystroke messages. For more information, see the KeyboardProc hook procedure.
WH_KEYBOARD_LL
13
Installs a hook procedure that monitors low-level keyboard input events. For more information, see the LowLevelKeyboardProc hook procedure.
WH_MOUSE
7
Installs a hook procedure that monitors mouse messages. For more information, see the MouseProc hook procedure.
WH_MOUSE_LL
14
Installs a hook procedure that monitors low-level mouse input events. For more information, see the LowLevelMouseProc hook procedure.
WH_MSGFILTER
-1
Installs a hook procedure that monitors messages generated as a result of an input event in a dialog box, message box, menu, or scroll bar. For more information, see the MessageProc hook procedure.
WH_SHELL
10
Installs a hook procedure that receives notifications useful to shell applications. For more information, see the ShellProc hook procedure.
WH_SYSMSGFILTER
6
Installs a hook procedure that monitors messages generated as a result of an input event in a dialog box, message box, menu, or scroll bar. The hook procedure monitors these messages for all applications in the same desktop as the calling thread. For more information, see the SysMsgProc hook procedure.
lpfn [in]
Type: HOOKPROC
A pointer to the hook procedure. If the dwThreadId parameter is zero or specifies the identifier of a thread created by a different process, the lpfn parameter must point to a hook procedure in a DLL. Otherwise, lpfn can point to a hook procedure in the code associated with the current process.
hMod [in]
Type: HINSTANCE
A handle to the DLL containing the hook procedure pointed to by the lpfn parameter. The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by the current process and if the hook procedure is within the code associated with the current process.
dwThreadId [in]
Type: DWORD
The identifier of the thread with which the hook procedure is to be associated. If this parameter is zero, the hook procedure is associated with all existing threads running in the same desktop as the calling thread.
Return Value
Type: HHOOK
If the function succeeds, the return value is the handle to the hook procedure.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
Remarks
SetWindowsHookEx can be used to inject a DLL into another process. A 32-bit DLL cannot be injected into a 64-bit process, and a 64-bit DLL cannot be injected into a 32-bit process. If an application requires the use of hooks in other processes, it is required that a 32-bit application call SetWindowsHookEx to inject a 32-bit DLL into 32-bit processes, and a 64-bit application call SetWindowsHookEx to inject a 64-bit DLL into 64-bit processes. The 32-bit and 64-bit DLLs must have different names.
An error may occur if the hMod parameter is NULL and the dwThreadId parameter is zero or specifies the identifier of a thread created by another process.
Calling the CallNextHookEx function to chain to the next hook procedure is optional, but it is highly recommended; otherwise, other applications that have installed hooks will not receive hook notifications and may behave incorrectly as a result. You should call CallNextHookEx unless you absolutely need to prevent the notification from being seen by other applications.
Before terminating, an application must call the UnhookWindowsHookEx function to free system resources associated with the hook.
The scope of a hook depends on the hook type. Some hooks can be set only with global scope; others can also be set for only a specific thread, as shown in the following table.
Hook Scope
WH_CALLWNDPROC Thread or global
WH_CALLWNDPROCRET Thread or global
WH_CBT Thread or global
WH_DEBUG Thread or global
WH_FOREGROUNDIDLE Thread or global
WH_GETMESSAGE Thread or global
WH_JOURNALPLAYBACK Global only
WH_JOURNALRECORD Global only
WH_KEYBOARD Thread or global
WH_KEYBOARD_LL Global only
WH_MOUSE Thread or global
WH_MOUSE_LL Global only
WH_MSGFILTER Thread or global
WH_SHELL Thread or global
WH_SYSMSGFILTER Global only
For a specified hook type, thread hooks are called first, then global hooks.
The global hooks are a shared resource, and installing one affects all applications in the same desktop as the calling thread. All global hook functions must be in libraries. Global hooks should be restricted to special-purpose applications or to use as a development aid during application debugging. Libraries that no longer need a hook should remove its hook procedure.
Examples
For an example, see Installing and Releasing Hook Procedures.
Requirements
Minimum supported client
Windows 2000 Professional
Minimum supported server
Windows 2000 Server
Header
Winuser.h (include Windows.h)
Library
User32.lib
DLL
User32.dll
Unicode and ANSI names
SetWindowsHookExW (Unicode) and SetWindowsHookExA (ANSI)
See Also
Reference
CallNextHookEx
CallWndProc
CallWndRetProc
CBTProc
DebugProc
ForegroundIdleProc
GetMsgProc
JournalPlaybackProc
JournalRecordProc
LowLevelKeyboardProc
LowLevelMouseProc
KeyboardProc
MouseProc
MessageProc
ShellProc
SysMsgProc
UnhookWindowsHookEx
Conceptual
Hooks
Send comments about this topic to Microsoft
Build date: 12/1/2010
CCR Introduction
Concurrency and Coordination Runtime (CCR) is a managed code library, a Dynamically Linked Library (DLL), accessible from any language targeting the .NET Common Language Runtime (CLR).
The CCR addresses the need of service-oriented applications to manage asynchronous operations, deal with concurrency, exploit parallel hardware and deal with partial failure. It enables the user to design applications so that the software modules or components can be loosely coupled; meaning they can be developed independently and make minimal assumptions about their runtime environment and other components. This approach changes how the user can think of programs from the start of the design process and deals with concurrency, failure and isolation in a consistent way.
Problem Areas
Asynchrony - When communicating between loosely coupled software components, like programs running across the network, or User Interface (UI) code communicating with the user input and the file I/O subsystem, asynchronous operations enable the code to scale better, be more responsive, and deal with failure across multiple operations. Asynchronous programming however, considerably reduces the readability of user code, since logic is often split between callbacks and the code that originates the operation. In addition, it is an almost impossible task to correctly handle failure across multiple outstanding operations.
Concurrency - Code that needs to better utilize multiple execution resources, must be split into independent logical segments, that can run in parallel, and communicate when necessary to produce results from the combined execution. Often, that logical segment is captured by the thread OS primitive, that is nothing more than a long lived iteration. Because of thread performance implications on thread startup, the thread stays active for long periods of time. This forces a particular pattern. Code is structured as long sequences that use blocking or synchronous calls, and only deals with one thing at a time. Further, threads assume that the primary communication between them is shared memory, forcing the programmer to use very explicit, error-prone methods to synchronize access to that shared memory.
Coordination and Failure Handling - Coordinating between components is where most of the complexity in large software programs lies. A mismatch of interaction patterns, such as calling methods on objects versus using OS signaling primitives versus using queues plus signaling, leads to unreadable code, where the runtime behavior changes drastically between coordination approaches. More importantly, the error handling approaches are ill-defined and again vary drastically.
Application Model
CCR is appropriate for an application model that separates components into pieces that can interact only through messages. Components in this model need means to coordinate between messages, deal with complex failure scenarios, and effectively deal with asynchronous programming. This application model is also very similar to how heterogeneous hardware is integrated and how network applications are built. Most software programs have the same needs, from traditional client PC programs to server applications, to applets running in the Web browser. The software needs to coordinate user input, storage input/output and UI presentation. Although disguised in layers of mostly synchronous application code interfaces, asynchrony is inevitable since the devices operate at different speeds, have large differences in resources available, and we in general know how to use queues to isolate them.
The following sections introduce the CCR programming model and its implementation that addresses the above areas in an efficient, robust and extensible way.
© 2010 Microsoft Corporation. All Rights Reserved.
Array of Tuples
A: Listed below is a sample code snippet to implement an array of tuples.
//Array of Tuples (i.e. EmpName, EmpIDNum)
Tuple[] EmpRecs =
{
Tuple.Create("Sam Nasr", 891),
Tuple.Create("Jim Smith", 358),
Tuple.Create("Lisa Jones", 962)
};
string FirstEmpName = EmpRecs[0].Item1;
string SecondEmpName = EmpRecs[1].Item1;
int SecondEmpIDNum = EmpRecs[1].Item2;
More information can be found at http://msdn.microsoft.com/en-us/library/dd413854(VS.95).aspx
NTLM Authentication for Java http clients
What I found out during this exercise is that if one is on the same AD domain as the server hosting the secure contents then JDK 1.5 and 1.6 does a transparent authentication at the backend, automatically transferring the login details from the http client to the server , however if the request is being made from a client outside the domain then the login details have to be provided using the username and password for the client accessing the protected resource, for that I found the Jave Authenticator class to be the best option, since you do not have to alter your existing code and just call the Authenticator before the http request and populate the authentication credentials in it. Worked really well for me.
References
Two exhaustive definitions of how ntlm works, and the interactions
http://www.innovation.ch/personal/ronald/ntlm.html
http://davenport.sourceforge.net/ntlm.html
Useful link to valid Java Implementation
http://oaklandsoftware.com/papers/ntlm.html
Ads by Google
Oh Yahoo!
Take yesterday as an example. They botch news about closing down products like Delicious. The Upcoming team is apparently wiped out, but an apparently timestamped blog post appeared on wednesday, after the team was gone, asking for feedback on a new design for the site. Except the blog post doesn’t have a link to the new design, and still doesn’t as of today. Probably because whoever wrote it is gone, along with the rest of the team.
And today Yahoo realized that people really care about sites like Delicious and put up a blog post saying that they’re going to sell it, not shut it down. Which is great except the Delicious blog is now offline and returns an error (we reprinted it here).
And finally, yesterday Yahoo announced internally that they would be shutting down an instant messaging product called MyM. Have you heard of it? Neither had we. Oh wait, we did – in 2008. It turns out is was an internal project that was never launched and formally shut down nearly three years ago. Apparently the executive team didn’t know that.
In May I spoke with CEO Carol Bartz on stage at TechCrunch Disrupt. The headline was the last few seconds of the talk. But that wasn’t really what was interesting about the interview. What really riled Yahoo up was when I asked if they were really even a technology company any more. I think it’s now clear to the world now that they aren’t. They’re just a nightmarish Dilbert-cartoon version of the old Yahoo, where employees fear for their jobs and stumble around the office trying to protect themselves, not build anything new and ambitious.
There is only one way a company recovers from this. They must have new leadership. And soon. Because at this point they are little more than a holding company for some lucrative Asian Internet assets. This can’t possibly be what the board of directors hoped for when they hired Bartz less than a year ago. So much has changed, so fast.
Tuesday, December 14, 2010
Zombie Farm
Apparently this is a winning combination, as the game hit 7.3 million downloads in November, up from 6 million in October and growing about 25% a month. Currently it boasts about 2 million monthly active users, a number which has been doubling every couple of months since the app’s launch this February. Users have spent 2.76 billion minutes playing the game, which have resulted in 61.5 million Zombie Farm invasions. And despite complaints about the most recent updates’ slowness in the iTunes reviews, the developers are obviously doing something right.
To the tune of millions of dollars. Playforge developer Vince McDonnell and his wife were in danger of losing their house when he built the app, and now not so much. While McDonnell will not reveal how much total revenue the app has made thus far (people pay for in-game currency like $0.99 brains and tombstones) in comparison, Doodle Jump, the #10 app on the top grossing list sold about 3 million units in five months at $0.99 each which would project to about ($) 7 million sold for the year. Zombie Farm was at number #6 on the list, which means McDonnell has made at least a few million thus far.
Monday, February 8, 2010
GWT games
I wanted to revisit this application and was trying to figure out what the best language/framework to use.
I decided that GWT (Google Web Toolkit) would be an excellent choice for this application.
To see the application go here: http://imageoverflow.appspot.com/puzzle.html?imageUrl=http://imageoverflow.appspot.com/get/3b20793dfc300d058ad04d411da152eb?f=t
Now to the code...
The code consists of the following main classes.
ImagePuzzleWidget
PuzzleGrid
ClickableImage
ImagePuzzleWidget
The ImagePuzzleWidget is the main widget that encapsulates the game. It takes no arguments and is added directly to the Root Panel in the GWT entry point.
public void onModuleLoad() {
RootPanel.get().add(new ImagePuzzleWidget());
}
PuzzleGrid
PuzzleGrid extends the Grid GWT component. Its constructor looks like this:
public PuzzleGrid(final String url,final int cols,final int rows)
This class takes the url of the image you want to scramble as well as how many rows and cols you want.
We add an onLoadHandler that will get executed after the image has been loaded:
image.addLoadHandler(new LoadHandler() {
public void onLoad(LoadEvent event) {
setWidth(image.getWidth() + "px");
setHeight(image.getHeight() + "px");
int blockWidth = image.getWidth() / cols;
int blockHeight = image.getHeight() / rows;
for (int col = 0; col <>
for (int row = 0; row <>
setWidget(row, col,
new ClickableImage(url, blockWidth * col, blockHeight * row, blockWidth, blockHeight, row, col));
}
}
shuffle();
setVisible(true);
}
});
It is this class that does most of the work by splitting the image into sub parts and making ClickableImages out of them.
The class then shuffles the images and sets it as visible.
So now we have an image displayed broken into sub parts and displayed in a grid fashion.
ClickableImage
ClickableImage class, as its name implies embodies a section of the image that can be clicked.
The class basically just extends Image and adds a ClickHandler. I add some extra convenience methods like select and unselect which I won't show for the sake of brevity.
public ClickableImage(String url, int left, int top, int width, int height, int row, int col) {
super(url, left, top, width, height);
this.row = row;
this.col = col;
this.addStyleName("unselected");
this.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
toggleSelected();
}
});
}
And that is really all there is to it. By using GWT we can focus on writing our OO style code and not worry about the browser.
Make sure you check out the app at: http://imageoverflow.appspot.com/puzzle.html?imageUrl=http://imageoverflow.appspot.com/get/3b20793dfc300d058ad04d411da152eb?f=t
This post was written hastily, if there is any interest or question leave a comment and I'll ake the time to expand.
HTH
Monday, October 5, 2009
Extend JSF Command Link
<h:commandlink value="Remove" actionlistener="#{MyBean.remove}">
I wanted to add a confirm dialog. So I added this.
<h:commandlink value="Remove" actionlistener="#{MyBean.remove}" onclick="javascript return confirm('Are you sure')">
But as I copied and pasted this through 5 or 6 different pages, I got to thinking, there has to be a better way.
So I created a custom jsf component by extending Command Link.
Step 1
First step was to create my new tag. It simply wraps the default command link.
package com.acme;
import com.sun.faces.taglib.html_basic.CommandLinkTag;
import javax.el.MethodExpression;
import javax.el.ValueExpression;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlCommandLink;
import javax.faces.event.MethodExpressionActionListener;
import javax.faces.webapp.UIComponentELTag;
/**
* @author cmcintosh
*/
public class RemoveCommandLinkTag extends UIComponentELTag { // Declare a bean property for the hellomsg attribute.
CommandLinkTag commandLink = new CommandLinkTag();
ValueExpression value;
MethodExpression actionListener;
// Associate the renderer and component type.
public String getComponentType() {
return commandLink.getComponentType();
}
public String getRendererType() {
return commandLink.getRendererType();
}
@Override
protected void setProperties(UIComponent component) {
super.setProperties(component);
component.setValueExpression("value", value);
((HtmlCommandLink)component).addActionListener(new MethodExpressionActionListener(actionListener));
((HtmlCommandLink)component).setOnclick("javascript:return confirm('Are you sure you want to remove?')");
}
@Override
public void release() {
super.release();
commandLink.release();
}
public void setValue(ValueExpression value) {
this.value = value;
}
public void setActionListener(MethodExpression actionListener) {
this.actionListener = actionListener;
}
}
Step 2
Next I needed to create a tld.
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee" xsi="http://www.w3.org/2001/XMLSchema-instance" schemalocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">
<tlib-version>1.0</tlib-version>
<short-name>datastore</short-name>
<uri>/WEB-INF/tlds/datastore</uri>
<tag>
<name>RemoveCommandLink</name>
<tag-class>com.acme.datastore.web.components.tags.RemoveCommandLinkTag</tag-class>
<attribute>
<name>value</name>
<deferred-value>
<type>java.lang.String</type>
</deferred-value>
</attribute>
<attribute>
<name>actionListener</name>
<required>false</required>
<deferred-method>
<method-signature>
actionListener(javax.faces.event.ActionEvent)
</method-signature>
</deferred-method>
<type>String</type>
</attribute>
</tag>
</taglib>
This was one of the hardest parts note the deferred-method and deferredvalue. I've never encountered those before.
Step 3
Add it to the web.xml:
<jsp-config>
<taglib>
<taglib-uri>http://datastore.acme.com/datastore</taglib-uri>
<taglib-location>/WEB-INF/tlds/datastore.tld</taglib-location>
</taglib>
</jsp-config>
Step 4
Finally to use it:
<%@taglib prefix="ds" uri="http://datastore.acme.com/datastore"%>
.
.
.
<ds:removecommandlink value="Remove" actionlistener="#{ViewModifyTable.removeColumn}">
<f:param name="applicationId" value="#{ViewModifyTable.applicationId}">
<f:param name="tableName" value="#{ViewModifyTable.tableName}">
</f:param></f:param></ds:removecommandlink></h:commandlink></h:commandlink>
Friday, September 18, 2009
Configure logging level
Logger.getLogger("org.hibernate").setLevel(Level.SEVERE);
Tuesday, August 18, 2009
Readling List
http://www.mysqlperformanceblog.com/2009/08/13/xtradb-the-top-10-enhancements/
Mysql performance blog
http://www.amazon.com/gp/product/0596101716?ie=UTF8&tag=perinc-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0596101716
Monday, August 17, 2009
Pro JSF and Ajax by Jonas Jacobi and John R. Fallows
Rating: 7 /10
Pros:
- I liked this summary of other applications and which component of MVC they target: Examples of frameworks are Struts (an open source controller framework);
TopLink and Hibernate (model frameworks); and Tiles, Tapestry, XUL, and ADF UIX (so-
called view frameworks).
- Can be hard to read
- Why do so many frameworks model navigation these days?
Comparing Web Frameworks: Struts, Spring MVC, Webwork, Tapestry & JSF
Rating: 2/10
Way outdated, by the time I got my hands on it. No fault of the authors it was made in 2005.
Pros:
- Concise
- Its just a bunch of slides
Beginning Spring 2 by Dave Minter
Rating: 8/10
Pros:
- Very good introduction to Spring
- Clear explanation of IoC and dependency injection
- Made a strong case for using Spring for all applications
- Would of liked more Spring annotation examples.
- The database example could of been expanded. In particular I wasn't sure what the purpose of the DAO's were.
- I would of liked a more detail on Spring MVC