0

C# textbox with double value filter

Simply handle KeyPress event. Allow copy, paste, cut and backspace too.

private void txtSpadRef_KeyPress(object sender, KeyPressEventArgs e)
{
  Double isNumber = 0;
  String s = e.KeyChar.ToString();
  int[] allowedChar = new int[] {3,8,22,24 };
  foreach (int i in allowedChar) { 
    if(e.KeyChar.Equals(Convert.ToChar(i))){
      return;
    }
  }

  if (s == "." && txtSpadRef.Text.IndexOf(".") < 0)
  {
    s += "0";
  }
  e.Handled = !Double.TryParse(s, out isNumber);
}



0

Row Locking With MySQL

Source : http://www.xpertdeveloper.com/2011/11/row-locking-with-mysql/

Steps:
  1. Start tarnsaction
  2. Lock the desired row by using normal select statement and add FOR UPDATE or LOCK IN SHARE MODE in the back.
  3. Update the row(s)
  4. Commit (update) / Rollback (revert)
    For example :
        SELECT * FROM table_name WHERE id=10 FOR UPDATE;
        SELECT * FROM table_name WHERE id=10 LOCK IN SHARE MODE;

Any lock placed with LOCK IN SHARE MODE will allow other transaction to read the locked row but it will not allow other transaction to update or delete the row.

Any lock placed with the FOR UPDATE will not allow other transactions to read, update or delete the row. Other transaction can read this rows only once first transaction get commit or rollback. 
0

MySQL Cache

Source : http://www.techiecorner.com/45/turn-on-mysql-query-cache-to-speed-up-mysql-query-performance/

It's a very simple.
Simply add to my.ini and restart MySQL service.
query-cache-type = 1          [0 (disable / off), 1 (enable / on) and 2 (on demand)]
query-cache-size = 20M     [the cache size)]

It will boost the performance. For me almost 5x faster.

:)
0

GWT - Add touch support to canvas

I have worked in the image viewer with support GWT scroll and touch.
The audience images using canvas + SVG transformation is detected so that the image can be panned and zoomed.No problems with scrolls, but I have a problem when showing images on smart phones.I have tried several other methods to handle events on canvas in GWT but failed.

Finally, I found an example of event handling in native JS and give a try. Luckyly it works.
I lost the URL of the referring page, but I'll try to find and update this post later.

The example :
I put all the event declaration in a function.
private native void attachTouch(JavaScriptObject ele) /*-{
    var ref = this;
    ele.ontouchstart = function(evt) {
      evt.preventDefault();
      var x2=-100;
      var y2=-100;
      if(evt.touches.length > 1){
        x2=evt.touches[1].pageX;
        y2=evt.touches[1].pageY;
      }
      ref.@net.vcari.webipc.client.graphics.ImageViewerSvgPanel::setInitialTouch(IIII)(evt.touches[0].pageX, evt.touches[0].pageY,x2,y2);
    }
    ele.ontouchmove = function(evt) {
      evt.preventDefault();
      var x2=-100;
      var y2=-100;
      if(evt.touches.length > 1){
        x2=evt.touches[1].pageX;
        y2=evt.touches[1].pageY;
      }
      ref.@net.vcari.webipc.client.graphics.ImageViewerSvgPanel::onTouchMove(IIII)(evt.touches[0].pageX, evt.touches[0].pageY,x2,y2);
    }
    ele.ontouchend = function(evt) {
      evt.preventDefault();
      ref.@net.vcari.webipc.client.graphics.ImageViewerSvgPanel::onEndTouch(II)(evt.pageX, evt.pageY);
    }
  }-*/;

Add touch events to the canvas:
attachTouch(canvas.getElement());

Yayy.....
0

GWT Generic Event Bus

I was looking at GWT Event Bus implementation on MVP Design Pattern.I think it's good but I'm too lazy to write the event and eventhandler classes for each type of event.So I decided to wrote a helper to simplify the implementation.

May be someone is disagree with this solution.

EventBusGenericEventHandler.java
package net.vcari.webipc.client;

import com.google.gwt.event.shared.EventHandler;

public interface EventBusGenericEventHandler  extends EventHandler{
  void  onEventTrigger(EventBusGenericEvent event);
}

The event bus event handler.

EventBusGenericEvent.java
package net.vcari.webipc.client;

import java.util.List;

import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelData;
import com.google.gwt.event.shared.GwtEvent;

public class EventBusGenericEvent extends GwtEvent<EventBusGenericEventHandler>{
  public Type<EventBusGenericEventHandler> eventType;

  public ModelData dataModel;
  public List<ModelData> dataModelList;
  
  @Override
  public Type<EventBusGenericEventHandler> getAssociatedType() {
    return eventType;
  }

  @Override
  protected void dispatch(EventBusGenericEventHandler handler) {
    handler.onEventTrigger(this);    
  }

}

Event bus event. I use GXT modeldata in my application. I put extra variable for single data(ModelData) and List. I use 2 variable to avoid confusion between List and single ModelData (^&%@&YY(&@& - dirty solution. Hahahaha).


EventBusTypes.java
package net.vcari.webipc.client;

import com.google.gwt.event.shared.GwtEvent.Type;

public class EventBusTypes {
  
  /**
   * Set current location event type. Use to trigger data update for other location like in image viewer
   */
  public static Type<EventBusGenericEventHandler> setCurrentLocationEvent=new Type<EventBusGenericEventHandler>();
  
  /**
   * Set current location process updated event type
   */
  public static Type<EventBusGenericEventHandler> setCurrentLocationUpdatedEvent=new Type<EventBusGenericEventHandler>();
  
  /**
   * Set other location event type. Use to trigger data update for other location like in image viewer
   */
  public static Type<EventBusGenericEventHandler> setOtherLocationEvent=new Type<EventBusGenericEventHandler>();
  
  /**
   * Set other location process updated event type
   */
  public static Type<EventBusGenericEventHandler> setOtherLocationUpdatedEvent=new Type<EventBusGenericEventHandler>();
  
}
The registers of event types.

I  declare the event bus as static. It can be called from other class.
public static EventBus EVENT_BUS = GWT.create(SimpleEventBus.class);


To trigger the event:
EventBusGenericEvent event = new EventBusGenericEvent();
event.eventType=EventBusTypes.setCurrentLocationEvent;
event.dataModel=pagingGrid.getGrid().getSelectionModel().getSelectedItem();
Application.EVENT_BUS.fireEvent(event);
Declare the event, set the type, set the data and fire the event.

To handle the event:

I think it's easier to declare the HandlerRegistration variable in module/class scope as it can be accessed anywhere inside the module/class. This is because it's required to remove the event handler when the container (like form or panel) is closed. If not, the event handler will be handled even the container has ben closed.
HandlerRegistration onSetOtherLocationHandlerRegistration;

Put the handler (may be in onRender function).
onSetOtherLocationHandlerRegistration=Application.EVENT_BUS.addHandler(EventBusTypes.setOtherLocationUpdatedEvent, new EventBusGenericEventHandler() {

      @Override
      public void onEventTrigger(EventBusGenericEvent event) {
        onSetOtherLocationEvent(event);
      }
    });

Finally, remove the handler when the form is closed / unloaded.
@Override
  protected void onUnload() {
    super.onUnload();
    onSetOtherLocationHandlerRegistration.removeHandler();
  }

Voila !!!

0

GWT - nocache.js cached

I got a problem when my GWT site keep notifying there is no file found for deferred binding js file. After simple investigation, I realize the main nocache.js file is cached. I thought it will be cache automatically but I was wrong.

A simple solution is to make web server to send a header not to cache the nocache.js files.
I found the solution here :
http://www.askapache.com/htaccess/using-http-headers-with-htaccess.html
http://code.google.com/p/google-web-toolkit/issues/detail?id=4823

Simply modify the .htaccess file (I use this file for compression) and put the following configuration:

<filesMatch "\.(nocache.js)$">
FileETag None
<ifModule mod_headers.c>
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</ifModule>
</filesMatch>

or this one
<Files *.nocache.*>
  ExpiresActive on
  ExpiresDefault "now"
  Header merge Cache-Control "public, max-age=0, must-revalidate"
</Files>


Voila !!!. :)


 
 
0

Disable Canvas ContextMenu in GWT

This week I'm working with canvas and I got a problem to hide the context menu from being appeared. I had try several methods such as handling the mouse up event, click event , sink events but all of them are not working.

Finally, I found a solution from 
http://svenbuschbeck.net/wordpress/2011/02/disable-context-menu-in-gwt/

The solution is similar to mouse up event but this one is using DomHandler.

Canvas canvas = Canvas.createIfSupported();
if (canvas == null) {
    return;
}

canvas.addDomHandler(new ContextMenuHandler() {

    @Override
    public void onContextMenu(ContextMenuEvent event) {
        event.preventDefault();
        event.stopPropagation();
    }
},ContextMenuEvent.getType());

0

GWT - How to show the wait cursor for long tasks




  Source : http://ui-programming.blogspot.com/2010/01/gwt-how-to-show-wait-cursor-for-long.html

GWT - How to show the wait cursor for long tasks

In case you have a task that takes more than 2 seconds you need to signal to the user that he needs to wait a little longer than usual. This can be done in many ways, here, we are talking about the setting the cursor to a WAIT cursor.

For this reason we have wrote 2 static functions to set the cursor to wait and then to put it back when the long task is over.

public static void showWaitCursor() {
    DOM.setStyleAttribute(RootPanel.getBodyElement(), "cursor", "wait");
}

public static void showDefaultCursor() {
    DOM.setStyleAttribute(RootPanel.getBodyElement(), "cursor", "default");
}

Here are the possible types of the HTML cursors, which can be used in different cases:

 


Example of how to use the functions to change HTML cursor for long task:

/**
 * create the long task instance, which in our case extends:
 *   interface Function { execute(); } 
 */
final Task longTask = new Task();

/** shows the wait cursor */
showWaitCursor();

/** launch the long task in a separate thread */
DeferredCommand.addCommand (new Command() {
    @Override
    public void execute () {
        try {
            longTask.execute();
        } finally {
            /* when task finishes (successful, or with failure) set back the default cursor */
            showDefaultCursor();
        }
    }
});

That's pretty much all.

Cheers!
0

Using GWT Event Bus

Simple tutorial on GWT Event Bus.
Tested and it works.

Source : http://stackoverflow.com/questions/6030202/how-to-use-the-gwt-eventbus

When you divide the project into logical parts (for example with MVP) than several different parts sometime need to communicate. Typical communication is sending some status changes, e.g.:
  • user logged-in / loged-out.
  • user navigated directly via URL to page so menu needs to be updated.
Event bus is quite logical to use in this cases.
To use it you instantiate one EventBus per app which is then used by all other classes. To achieve this you use static field, factory or dependency injection (GIN in case of GWT).
Example with you own event types:
 
public class AppUtils{

    public static EventBus EVENT_BUS = GWT.create(SimpleEventBus.class);
}
 
Normally you'd also create your own event types and handlers:
 
public class AuthenticationEvent extends GwtEvent<AuthenticationEventHandler> {
public static Type<AuthenticationEventHandler> TYPE = new Type<AuthenticationEventHandler>();

  @Override
public Type<AuthenticationEventHandler> getAssociatedType() {
    return TYPE;
}
@Override
protected void dispatch(AuthenticationEventHandler handler) {
    handler.onAuthenticationChanged(this);
}
}

and the handler:
 
public interface AuthenticationEventHandler extends EventHandler {
    void onAuthenticationChanged(AuthenticationEvent authenticationEvent);
}

Then you use it like this:

AppUtils.EVENT_BUS.addHandler(AuthenticationEvent.TYPE, new AuthenticationEventHandler()     {
        @Override
        public void onAuthenticationChanged(AuthenticationEvent authenticationEvent) {
            // authentication changed - do something
        }
    });

and fire the event:

AppUtils.EVENT_BUS.fireEvent(new AuthenticationEvent());


0

Choosing the Logger iButton That's Right for You

Article from Maxim. Also for my reference.

http://www.maxim-ic.com/app-notes/index.mvp/id/5405
0

LFRD003: Water Meter Automatic Meter Reading (AMR) Reference Design

 This is for my reference.An article from Maxim.
 
http://www.maxim-ic.com/app-notes/index.mvp/id/5404
1

GXT set DateField value from string

Here is the code to set GXT datefield value from the date string.

String sdate="24-01-2012";  //24 Jan 2012
DateTimeFormat dformat = DateTimeFormat.getFormat("dd-MM-yyyy");
DateField date2 = new DateField();
date2.getPropertyEditor().setFormat(dtFormat);
Date dDate= dformat.parse(sdate);
date2.setValue(dDate);
0

GXT Grid Column Alignment

How to align GXT grid column?
Answer : it can be done at ColumnConfig.
Here is sample code :

List configs = new ArrayList();

ColumnConfig column = new ColumnConfig();
column.setId("name");
column.setHeader("Company");
column.setWidth(200);
configs.add(column);

column = new ColumnConfig();
column.setId("symbol");
column.setHeader("Symbol");
column.setWidth(100);
configs.add(column);

column = new ColumnConfig();
column.setId("last");
column.setHeader("Last");
column.setAlignment(HorizontalAlignment.RIGHT);
column.setWidth(75);
column.setRenderer(gridNumber);
configs.add(column);

column = new ColumnConfig("change", "Change", 100);
column.setAlignment(HorizontalAlignment.RIGHT);
column.setRenderer(change);
configs.add(column);

The full example can be found here :
http://www.java2s.com/Code/Java/GWT/SetcolumnalignmentnameandheightExtGWT.htm
0

GWT Anchor Image Link

In my project, I need to display image link in GXT grid with the cursor changed to pointer when the cursor hover on the image. When clicked, it will open a new window.

Here is the code :

Anchor anchor =new Anchor();
final Image image = new Image("../resources/images/pdf.png");

anchor.addMouseOverHandler(new MouseOverHandler() {
    
    @Override
    public void onMouseOver(MouseOverEvent event) {
        DOM.setStyleAttribute(image.getElement(), "cursor", "pointer");
    }
});
                
anchor.addMouseOutHandler(new MouseOutHandler() {
    
    @Override
    public void onMouseOut(MouseOutEvent event) {
        DOM.setStyleAttribute(image.getElement(), "cursor", "default");                        
    }
});
anchor.addClickHandler(new ClickHandler() {
    
    @Override
    public void onClick(ClickEvent event) {
        String url="upload/" + model.get(property).toString();
        Window.open(url, "_blank", "");
        Info.display("Hardware", "Show Datasheet");
    }
});                
anchor.getElement().appendChild(image.getElement());            
return anchor;

 
Copyright © peyotest