Monday, July 30, 2012

History and navigation with MVC and Ext 4.1 (Sencha)


I struggled for awhile with how to present the 'Are you sure you want to exit?' message when a user has unsaved data and attempts to close the browser or navigate elsewhere.  I also wanted pages in my application to be URL accessible so that a user could bookmark a URL to show a specific record or email a URL to another user.  I am using  Ext 4.1 and MVC.  

I decided on a two pronged approach.   First, I hooked directly into the window.beforeunload event for handling the user attempting to close the browser window or page away when they have unsaved data.  It was easy to setup a handler for the beforeunload.  The difficulty I ran into was finding the scope of my MVC application.

Secondly I used Ext.history to handle page navigation.



Here is an excerpt from my main MVC controller.

//-------------------------------------------------------
// function to handle the token that is passed in the URL for the page.
//-------------------------------------------------------
   dispatch: function (token) {

        if (token == "") {    // no parameters passed, go to home page.
            Ext.History.add("Main");
        }
        else if (token) {
            parts = token.split(':');

            if (parts[0] == "editCustomer") {  // Edit a specified customer
                this.editCustomer(parts[1]);
            } else if (parts[0] == "Main") {
                this.goHome();
            } else if (parts[0] == "tabpanel") {  // open a tab on main page
                this.goHome();
                var tab = this.getMainSearch().query('#tabs')[0];    //tabs
                tab.setActiveTab(parts[1]);  // set the main tab control to 'home'
            } else {
                this.goHome();
            }
        } else
            this.goHome();


    },
//-------------------------------------------------------
// Check if we need to ask if user needs to save.
//-------------------------------------------------------
    processHistoryToken: function (token, opt) {

        if (this.changesMade()) {  // if any dirty data that is not saved.
            this.token = token;
            Ext.Msg.show({
                title: 'Warning.',
                msg: "Save changes before exiting page?"  ,
                buttons: Ext.Msg.YESNO,
                fn: function (btn) {
                    if (btn == 'yes') {
// User has said yes so explicitly save the data to server.
                        if (this.changesMadeEvent())  // changes for my 'event' form
                            this.saveEvent(false);
                        if (this.changesMadeTicket())  // changes for my 'ticket' form
                            this.saveTicket(false);
                        }
// reset the forms so they are no longer dirty
                    this.getEventDetail().query('#EventDetailform')[0].getForm().reset();
                    this.getChangeDetail().query('#ChangeDetailform')[0].getForm().reset();
// proceed with doing the action
                    this.dispatch(this.token);
                },
                animEl: 'elId',
                icon: Ext.MessageBox.QUESTION,
                scope: this
            })
        } else {
            this.dispatch(token);
        }
    },
//-------------------------------------------------------
// Handler for the window.onbeforeonload.
//-------------------------------------------------------
 confirmExit: function () {

         // Using the previously save scope, call the 'changesMade' function to see if
        // any unsaved form data.
        if (this.MYscope.getController('AM.controller.smMain').changesMade())
            return "You will lose your changes if you leave this page !";
    },


//-------------------------------------------------------
// init function for my main MVC controller
//-------------------------------------------------------

   init: function () {
        // -------------------------------------------------
        // History management and navigation 'dispatcher' which handles some of the user navigation.
        // ----------------------------------------------------
        Ext.History.init();
        Ext.History.hasHistory = false;  // default to no history saved to prevent 'back' button completely out of the app.

        Ext.History.on('change', function (token, opt) {
            Ext.History.hasHistory = true;   // we have some history now so 'back' button is ok.
            this.processHistoryToken(token);
        }, this, this);


        //  Store our context as a property of the window.  I'm sure there are better ways to do this, but this works!
        window.MYscope = this;
        window.onbeforeunload = this.confirmExit;
......

// Support for URL.   Set the 'page' in the application based on the URL.
var token = document.location.hash.replace("#", "");
this.processHistoryToken(token);

...

Thursday, September 1, 2011

HoverButton

I found a nice hoverbutton extension at :


It extends the button class so that a mouseover will cause the menu to expand. I updated for Extjs 4.0. I also found that the expand would only work when mousing over the down-arrow icon so I modified it to use 'mouseover' and 'mouseout' events. This now allows the menu to expand when the mouse is anywhere over the button.

/**
* Add autoShow on mouseover option to buttons with menus
* @copyright LustForge.com 2011
* @author J.Lust
* @version ExtJs 3.3.4
*/
Ext.define('Ext.HoverButton', {
    extend: 'Ext.Button',
    alias: 'widget.hoverButton',


    // hide task properties and helpers
    hideTask: null,
    hideTaskMs: 250, // timeout in ms
    hideTaskFn: function () {
        if (this.hideTask !== null) {
            this.hideTask.cancel();
        }
        this.hideTask = new Ext.util.DelayedTask(this.hideMenu, this);
        this.hideTask.delay(this.hideTaskMs);
    },


    // extend init props
    initComponent: function () {


        // add hide/show, if this is a button with menu
        var config = {}, menuConfig = {};
        if (Ext.isDefined(this.initialConfig.menu)) {
            config = {
                listeners: {
                    //    menutriggerover: {
                    mouseover: {
                        fn: function (b) {
                            // console.log('menutriggerOver');
                            b.showMenu();
                        },
                        scope: this
                    },
                    mouseout: {
                        // menutriggerout: {
                        fn: function (b) {
                            //  console.log('menutriggerOut');
                            this.hideTaskFn();
                        },
                        scope: this
                    }
                }
            };
            // add listeners to see if user is over extended menu list
            menuConfig = {
                listeners: {
                    // if mousing over menu list, disable timeout
                    mouseover: {
                        fn: function (b) {
                            // cancel hide if they went away and came back
                            if (this.hideTask !== null) {
                                //       console.log('menu mouseOver');
                                this.hideTask.cancel();
                                this.hideTask = null;
                            }
                        },
                        scope: this
                    },
                    // on mousing out of menu list, resume timeout
                    mouseout: {
                        fn: function (b) {
                            //    console.log('menu mouseOut');
                            this.hideTaskFn();
                        },
                        scope: this
                    }
                }
            };


            Ext.apply(this.menu, menuConfig);
        }


        // apply config
        Ext.apply(this, Ext.apply(this.initialConfig, config));
        // call parent
        Ext.HoverButton.superclass.initComponent.apply(this, arguments);
    }
});

I use it as a 'more' dropdown box in my toolbar as follows:

, {
text: 'More',
xtype: 'hoverButton',
menu: {
     xtype: 'menu',
items: {
xtype: 'buttongroup',
columns: 1,
defaults: {
xtype: 'button',
scale: 'large',
iconAlign: 'left'
},
items: [
{
text: 'option1',
cls: 'x-btn-text-icon',
etc......

Buttongroup menu hiding

One unique behaviour of a buttongroup in a menu is that it will not 'hide' or collapse until the user clicks elsewhere. So how do you hide the buttongroup? Easy once you know how. Just do this call:

Ext.menu.Manager.hideAll();


This will hide all open menus.

Thursday, August 20, 2009

WPF binding to a typed dataset

I having been learning WPF and came across a problem trying to use typed datasets and the Visual Studio wizard for generating the xsd file. Once I created the dataset (xsd file) I couldn't find a way to actually bind it to anything or get the data. After some trial and error, the following seems to work well. I am populating an Xceed datagrid but the code is generic. I want to provide a 'blank' row for adding new records as well.


public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{

// Customers table (dataset is 'dsCustomers' as found in the ...Designer.cs file)
m_customer = new dsCustomers.TblCustomers();
//Create data adapter and fill from the source table
(new dsCustomersTableAdapters.TblCustomersTableAdapter()).Fill(m_customer );

m_customer.Rows.Add(m_customer.NewRow()); // Add a blank row

// Likewise for Address table (more verbose)

m_Addresses= new dsCustomers.TblAddresses();
dsCustomersTableAdapters.TblAddressesTableAdapter tblAdap = new dsCustomersTableAdapters.TblAddressesTableAdapter();

tblAdap.Fill(m_Addresses);
DataRow dr = m_Addresses.NewRow(); // generate a new row
m_Addresses.Rows.Add(dr); // append back to the table

base.OnStartup(e);
}

private dsCustomers.TblCustomers m_customer ;

public dsCustomers.TblCustomers Customers
{
get
{
return m_customer ;
}
}
private dsCustomers.TblAddresses m_Addresses;

public dsCustomers.TblAddresses Addresses
{
get
{
return m_Addresses;
}
}
}





Meanwhile the xaml is ..

< Grid.Resources>

< xcdg:DataGridCollectionViewSource
x:Key="Tblmycustomers"
Source="{Binding Source={x:Static Application.Current},
Path= Customers}"/ >

< xcdg:DataGridCollectionViewSource
x:Key="TblLocations"
AutoCreateForeignKeyDescriptions="true"
Source="{Binding Source={x:Static Application.Current},
Path= Addresses}"/ >
< /Grid.Resources >

Saturday, January 17, 2009

Cookies and the problems they cause

I often use the Ext state manager to automatically manage cookies for Ext widgets. This allows the application to 'remember' user settings such as window size, location etc. The only code required is :

Ext.state.Manager.setProvider(new Ext.state.CookieProvider());


This is very powerful and simple to add to an application BUT it can cause a mountain of problems. I've been bitten twice. What sometimes happens is the cookies can end up being applied to the incorrect objects. It seems that when Ext creates DOM objects, if there is no explicit dom id, an id is created. This id is used by the cookie 'manager' to reference the objects that are monitored. This is fine, except when items are added or removed from the application. The auto generated id numbers are changed and the cookies are now referencing different objects. This problem occurs during the development process or when new application versions are released (widgets are added and removed).

How do we avoid this? Its quite simple. Just assign explicit id properties to ALL items you create. Just do this as a 'best practice'. By doing this, there are no auto generated ids and no danger of the manager referencing the wrong objects.

Using Ext.extend to extend user classes.

While learning javascript, I've fallen into the copy/paste trap of code creation. Rather than using OO constructs, I often copy a block of code, paste it and modify it slightly. This is bad bad bad so I thought I would figure out how to use Ext.Extend to take my own base class and use inheritance to extend the base functionality. There is no rocket science here but I can use this now as a template for inheriting. Code ...

// ----------- Base class (extending 'object' )  ------------------
genericBase = Ext.extend(Object, {
basevar1: 1,
constructor: function(args) {
this.basevar1 = 2;
},

baseFunc1: function(testArg) {
alert("test Arg is " + testArg + " basevar = " + this.basevar1);
}
});

// ----------- Derived class (extending 'genericBase'class ) -------
genericDerived = Ext.extend(genericBase, {
derVar: 444, // class property
constructor: function(args) {
// Call the base constructor
genericDerived.superclass.constructor.call(this, args);
},

derivedFunc1: function(testArg) {
alert("derivedFunc1 called " + testArg );
},
getBaseval: function() {
return this.basevar1;
}

});


// -------- Code to instantiate and test the classes

// First, create the object
var myobj = new genericDerived({prop1: '123', prop2: 'abc' });

// displays basevar with a get method
alert("Derived class, method call ==>" + myobj.getBaseval());

// also displays basevar, but with direct property reference
alert("explicit reference to property basevar1 ==> " + myobj.basevar1);

myobj.baseFunc1('Calling base method');
myobj.derivedFunc1('Calling derived class method');


Tuesday, December 2, 2008

How to modify Ext tooltips dynamically

I have a requirement to dynamically change tool-tips as content gets refreshed and modified. There were a couple of suggestions in the forums, but the following works great for me:
var mydom = Ext.get('mydomelement');       // get element
var tip = Ext.getCmp(mydom.dom.id + '_tip'); //get element's tooltip

if ( tip ) {// tool tip already exists, so modify

tip.title = 'new title';
tip.html = 'new text';
}

else { // tip does not exist. Create it with unique id.

new Ext.ToolTip({
target: mydom.dom.id,
id: mydom.dom.id + '_tip',
title: 'title here', html: 'original text'
});
}
I am giving every tooltip a unique id, based on the id of the dom element it decorates.

Wednesday, November 26, 2008

Creating Charts and Graphs

Microsoft has released a chart control with .net framework 3.5. I believe it is licensed from Dundas and certainly has the Dundas look and feel. The functionality looks good but in my travels there are two graphing systems I have used, one for the client side and one for the server side.

On the server side I usually pre-generate graphs so that if there is lots of user traffic, database access is minimized. The client does not get one of those pesky 'loading data' messages. The server side graphic files are recreated on a periodic basis, with the web page referencing the image file (PNG, GIF etc). The package I have used is ZedGraph. It is open source however there doesn't seem to have been any project activity in over a year. It is easy to use and I had the samples up and running in about 5 minutes.

On the client side interactivity rules. There are a few open source packages around ( flot, plotkit ) but they are fairly basic. I paid the few dollars for Emprise Charts and have been very happy. The interactive features are great, especially the zoom and mouse-over features. I believe there is a free version that gives limited use and a watermark on graph backgrounds. I highly recommend Emprise Charts. I've combined Ext, .Net web services and Emprise in a complete solution that is quite slick. I basically loop through an Ext datastore and load up the graph points.

Deciding on whether to render on server or on client really depends on what your users will be looking at. If your db queries are expensive in terms of time to get the data, server side is best however if you can do it, client side rendering with Ajax will give your users a better interactive experience.

Wednesday, September 17, 2008

Using Intellisense with Visual Web Dev Express

I use Visual Web Developer Express - 2008 for all my development now, although most of my projects are still .NET 2.0.

Recently I discovered how to use javascript intellisense which helps a ton. You need to have SP1 of Visual Web Developer :
http://www.microsoft.com/downloads/details.aspx?FamilyId=7B0B0339-613A-46E6-AB4D-080D4D4A8C4E&displaylang=en

Once you have SP1, just add the following to the top of each JS file:

/// < reference path="lib/ext/adapter/ext/ext-base.js">
/// < reference path="lib/ext/ext-all-debug.js">
/// < reference path="myotherfile.js">


Not only do I get Ext intellisense, but also for objects from my own javascript files. Works great!

Tuesday, April 15, 2008

Minimizing server requests : multiple tables per request

The following example shows how to return multiple tables in one ajax request. Of course, minimizing server traffic allows for a snappy client experience. My requirement was to retrieve two data tables in a single server call. The Web service makes two distinct SQL calls, merges the datasets on the server and returns an XML document.

The client establishes a single data connection and then reads the results into two separate data stores using MemoryProxy data stores. The net effect is exactly the same result as making two (expensive) server requests.


Server Side

 [WebMethod]
public XmlDocument getPlannerDetail(String plannerid)
{
// SQL Query #1
String str = " select * from TblPlanners where plannerid = '" + plannerid + "'";
Filldt("plannerDetail", (int)Servers.nweb1, str);

DataSet localds = new DataSet();
localds.Merge(dt);

// SQL Query #2
str = "select plannerid_Owner, plannerid_Changer from TblPlanners_permission where plannerid_Owner = '" + plannerid + "'";
Filldt("Permits", (int)Servers.nweb1, str);

localds.Merge(dt);

XmlDocument doc = new XmlDocument();
xmlDoc.LoadXml(localds.GetXml());
return xmlDoc;

}

Client Side

var getdata = new Ext.data.Connection();

getdata.request({
url: "Service.asmx/getPlannerDetail",
params: {
plannerid: '123'
},
method: 'POST',
scope: this,

callback: function(options, success, response){

if (success) {
var xml = response.responseXML;

dsDetails = new Ext.data.Store({
proxy: new Ext.data.MemoryProxy(xml),
reader: new Ext.data.XmlReader({
record: 'plannerDetail',id: 'plannerid'
}, ['plannerid', 'centerid', 'LongName', 'DefaultViewRange'])
});

dsPermits = new Ext.data.Store({
proxy: new Ext.data.MemoryProxy(xml),
reader: new Ext.data.XmlReader({
record: 'Permits',
id: 'plannerid_Owner'
}, ['plannerid_Owner', 'plannerid_Changer'])
});

dsDetails.load();
dsPermits.load();
}
}
});

Friday, November 16, 2007

How To : Send Ext datastore to .Net dataset with XML

There are many examples of using the Ext xmlreader to get data xml data into a datastore on the client, however I wanted to do the reverse and allow my CRUD application to update the modified datastore back to the server, updated with user changes.

On the client I created a 'serialize' function to convert the datastore to XML, and then did an Ext.data.Connection to post the data to the server.

SaveDStoServer :function(ds) {

var prog = Ext.MessageBox.wait("Saving data to server");

var ds_serialized= myscope.SerializeDS(ds);

var serv= new Ext.data.Connection();
serv.request({
url: "Service.asmx/Savedata",
params: {myID: 123, datastore:ds_serialized},
method: 'POST',
scope: this,
callback: function(options, success, response){
prog.hide();
if (success){
var xml = response.responseXML;
}
else {
if( response.status == -1 )
Ext.MessageBox.alert('Error on save','Server timeout')
else
Ext.MessageBox.alert('Error on save',response.responseText)
}
}
});
},



SerializeDS : function (ds) {

var columns = ds.fields.keys; // get columns from data store
var retdata ="&ltNewDataSet>";

ds.each ( function (rec) {
retdata +="&lt/datarow>";
for (var i=0; i< columns.length; ++ i)
retdata += "<" + columns[i] + ">" + rec.data[columns[i]]
+ "&lt/" + columns[i] + ">"
retdata += "&lt/datarow>";
});

retdata += "&lt/NewDataSet>";

return ""+retdata;
},
},


On the server side web service method, I create an XML document, create a reader and then read into the dataset. I tried using 'XMLdatadocument' but if did not seem able to create a schema and had an empty dataset. This may not be the most efficient way but it seems to work well. As always, be aware of web service parameter verification to prevent SQL injection.

[WebMethod]
public String Savedata (String SchID, String datastore)
{

DataSet ds = new DataSet();
XmlDocument doc = new XmlDocument();

// Load the xml into an XmlDocument
doc.LoadXml(datastore);
StringReader sreader = new StringReader(doc.DocumentElement.OuterXml);

ds.ReadXml(sreader);

foreach (DataRow row in dsCraft.Tables[0].Rows)
{
System.Diagnostics.Debug.WriteLine(row[0] + " " + row[1]);
}

return "success";
}

Monday, September 3, 2007

.Net Web Service with Ext data store

After using Ajaxpro with a couple of applications, I thought I should look into a more standardized approach for Ext/.Net integration. Specifically, how to bind SQL data on the server to a Ext data store. Ajaxpro's future seems uncertain.

First the Web Service:

[WebMethod]
public XmlDocument getSites(String Site, String Type, String Disc, String Manu, String query, String limit, String start, String callback)
{

XmlDocument xmlDoc = new XmlDocument();
DataSet ds = new DataSet();
String sql = " Select SITE as col1 from mytable where site = " + Site;

// create a connection
SqlDataAdapter oda = new SqlDataAdapter(sql, connStringSQL);
oda.Fill(ds);
xmlDoc.LoadXml(ds.GetXml());
return xmlDoc;
}
And the Ext code, with the .Net xml doc having 'Table' as record:

// parameters that get passed
var inparms ={query: '', start: '', limit: '', callback: '', Site: '', Type: '', Disc: '', Manu: ''};

var xmlread = new Ext.data.XmlReader({ record: 'Table' }, [
// set up the fields mapping into the xml doc
{name: 'col1'} ]);

// create the Data Store
var dsSites = new Ext.data.Store({
// load using HTTP
proxy: new Ext.data.HttpProxy({method:'POST',url: 'Service.asmx/getSites'}),
reader: xmlread, params: inparms });
.
.
.
dsSites.load( { params : inparms});
or
dsSites.load( {params : {query: '', start: '', limit: '', callback: '', Site: 'London', Type: '', Disc: '', Manu: ''});

Tuesday, August 14, 2007

Ext Combobox example... the very basics

I created a fairly sophisticated Ext application with editable grids and layouts several months ago. I now have a requirement for a new application. I thought I would start anew, resisting the temptation to just copy my old code and start modifying. I wanted to start with a clean slate but I was surprised how difficult it was to get started.

After some frustration with documentation and examples trying to get a simple combobox created, I distilled one of the examples down to the essentials. You should be able to install Ext, copy/paste the code below and you should be good to go. There are just two files you are creating, a HTML and ext_main.js...

HTML:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>my combo</title>
<link rel="stylesheet" type="text/css" href="lib/ext/resources/css/ext-all.css" />

<!-- GC --> <!-- LIBS -->
<script type="text/javascript" src="lib/ext/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="lib/ext/ext-all.js"></script>

<script type="text/javascript" src="ext_main.js"></script>

</head>
<body>
<h1>Simple Combo</h1>

<input type="text" id="local-states" size="20"/>

</body>
</html>

Code in ext_main.js:

/*
* Ext JS Library 1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/

// some data used in the examples
Ext.namespace('Ext.exampledata');

Ext.exampledata.states = [
['AL', 'Alabama'],
['AK', 'Alaska'],
['AZ', 'Arizona'],
['AR', 'Arkansas'],
['CA', 'California'],
['CO', 'Colorado'],
['CN', 'Connecticut'],
['DE', 'Delaware'],
['DC', 'District of Columbia'] ];

var combos = {
init : function(){


// simple array store
var store = new Ext.data.SimpleStore({
fields: ['abbr', 'state'],
data : Ext.exampledata.states
});
var cbsite = new Ext.form.ComboBox({
store: store,
displayField:'state',
typeAhead: true,
mode: 'local',
triggerAction: 'all',
emptyText:'Select a state...',
selectOnFocus:true
});

cbsite.applyTo('local-states');

}};
Ext.onReady(combos.init, combos);


Saturday, June 9, 2007

Teched 2007

Some thoughts on the Teched conference:
  • Very little or no negative discussion of Microsoft technologies. The talk about Microsoft Live did not once mention 'google'. I only once heard someone mention a non-Microsoft Ajax framework, when someone in a Q&A mentioned Dojo. When a presenter is so one sided in their presentation or so narrowly focused, it makes question what is being resented. For example, how can someone go on and on about how great the 'Web Developer Toolbar' is and not once mention Firebug?
  • A subtle implication that the 'buzz' around Ajax is in fact all about Microsoft's ASP.Net Ajax. Microsoft's framework is supposedly unique in that it uses OO concepts and 'prototype' in the javascript.
  • Alot of the developer hype was around Silverlight and how it allows developers to write C# code on the web client. This seems to be Microsofts latest effort for world domination. There is no way to make money writing javascript libraries, so with Silverlight, the plugin will relegate the browser to the role of a window frame. If successful, microsoft will then have all web development in C#, selling more copies of Visual Studio... and more $ for Micro$soft. Scary.
  • Office seems to be morphing into system for users to create and share rich browser based applications and documents, using Sharepoint.
  • I find it ironic that while microsoft is talking about the great capabilities of its Ajax toolkit, their Teched website is terrible. It is full of postbacks, arcane menuing and is not Firefox friendly. Even the ASP.Net/Ajax site has missed obvious opportunities for Ajax use in its interface.
  • There were some excellent presentations however. A couple of these were around security, with real-world examples of how systems have been breached and the implications.

Thursday, May 31, 2007

Browser bookmarks

Afraid you'll lose your bookmarks if your disk crashes, or when you jump to another computer? Some solutions I have found:

  • http://www.quickbookmarks.com This is basically an online repository for your bookmarks. Wherever you are in the world, you can log in and find that obscure bookmark you saved. The only downside I seen is you have to explicitly define each bookmark with no bulk import feature.
  • http://www.mybookmarks.com This page DOES allow importing of bookmarks but I'm not a big fan of the clunky interface. You just need to export you bookmarks to html (see below) and then import.
  • Firefox has a neat bookmark export feature that exports your bookmarks to an html page! Just go to Bookmarks/Organize and then File/Export and save to an HTML file for backup or stick it on your web page.

Wednesday, May 23, 2007

Using AjaxPro with Ext data store

As I posted on Ext forum I use the following modified code to use AjaxPro with Ext. It helps avoid emedding URLs in the proxy call.

ds = new Ext.data.Store({
proxy: new Ext.data.AjaxProxy(myAsp, "GetMovies"),
reader:reader,
remoteSort: true
});


And AjaxProProxy.js, modified from Rodiniz:

Ext.data.AjaxProxy = function(ajaxProObject, method) {
Ext.data.AjaxProxy.superclass.constructor.call(this);
this.ajaxProObject = ajaxProObject;
this.method = method;
};
Ext.extend(Ext.data.AjaxProxy, Ext.data.DataProxy, {

// Harley's load function
load: function(params, reader, callback, scope, arg) {
if(this.fireEvent("beforeload", this, params) !== false) {
var s = [];
for (var x in params) {
s[s.length] = "params[\"" + x + "\"]";
}
s = s.join(",");
var o = {
params: params || {},
request: {
callback : callback,
scope : scope,
arg : arg
},
reader: reader,
callback: this.loadResponse,
scope: this
};

eval("this.ajaxProObject[this.method](" + s + ", this.loadResponse, o)");

} else {
callback.call(scope||this, null, arg, false);
}
},


// Rodiniz's response handler

loadResponse: function(response, request) {

var o = response.context;

var result;
try {
result = o.reader.read(response.json);

}catch(e){
this.fireEvent("loadexception", this, o, response, e);
o.request.callback.call(o.request.scope, null, o.request.arg, false);
return;
}
o.request.callback.call(o.request.scope, result, o.request.arg, true);
},


slight mod in Rodiniz's reader....
read : function(response){

var r= new Object(); //to handle errors
var obj=response + "*/";
var doc = eval(obj);
if(r.error){
throw r.error;
}
return this.readRecords(doc);
},

Tuesday, May 15, 2007

Ext Combobox - Typeahead and mode local

The Ext combobox has a 'mode' property that can be either 'remote' or 'local'. These terms are somewhat misleading. They should really be called something like 'manual load' and 'auto load'. A 'remote' mode combobox gets its data store's load method called behind the scenes. A 'local' mode combo requires an explicit data store 'load' call to get the store and combobox loaded up with data.

Meanwhile, it seems that the only way to get 'typeahead' to work in a combobox is if mode:local. I'd also recommend Trigger:all and I'm not sure why anyone would not want to Trigger:all. This causes the entire combobox dropdown to be listed when the user clicks the down arrow.

var cb = new fm.ComboBox({
typeAhead: true,
mode:'local',
store: dsdevice,
forceSelection: true,
triggerAction: 'all',
displayField: 'fld1',
valueField: 'fld2',
lazyRender:true,
editable:true
});

Friday, May 11, 2007

dataset on the server....grow your own sql

I have spent some time trying to get the Ext datastore translated to a .Net dataset for updating but I've come to the conclusion that its just not worth the effort. I've heard others say that its not worth working with datasets except for simple out of the box applications and now I believe that too.

The dataset that gets sent to the server side routine needs to have its row's 'setmodified' or 'setadded' method set and then the dataset needs to be 'merged'. Then, it is just a black box in terms of what happens and it is difficult to get the underlying SQL when there are problems. I have done the following on the server side for the updates. I have a handler for the Ext data store 'update' event so that every field change on the grid will cause this code to fire. I added a timestamp column to the table to handle optimistic concurrency.

Code:

conn = new OleDbConnection(ads.ConnectionString);
conn.Open();

foreach (DataRow row in ds.Tables[0].Rows) // should always be one row
{

sqlcmd = "UPDATE TblOperations SET ";
sqlcmd += " Device = '" + row["Device"].ToString() + "', ";
sqlcmd += " Station = '" + row["Station"].ToString() + "' ";
sqlcmd += " where ID_key = " + row["ID_key"].ToString();
if (! row["timest"].ToString().Equals("") )
sqlcmd += " and timest = '" + row["timest"].ToString() + "' ";

cmd = new OleDbCommand(sqlcmd, conn);
affected += cmd.ExecuteNonQuery();
}

if ( affected == 1 )
return "";
else
return "error"



Now I need to get 'adds' and 'deletes' handled.

Dataset on the server.... ugh

I wrote the following to send the ext.datastore to the server, in response to a 'save button' click.

Code:
var editedds = myextdatastore.getModifiedRecords();

var ds4 = new Ajax.Web.DataSet();
var dt4 = new Ajax.Web.DataTable();

for(var i = 0, len = myextdatastore.fields.keys.length; i < i =" 0," len =" editedds.length;">


My C# routine correctly reads the dataset on the server but I'm disappointed that now I have to create all the insert/update/delete logic by creating 'insertcommand','updatecommand' etc. I thought the whole point of using ADO datasets was that it would handle all this logic. It seems like there is no way to get around having to code this on the server.

Below is my c# code. It returns no errors but it doesn't update either.....

Code:public static String SaveAll(System.Data.DataSet ds )
{
OleDbDataAdapter oda = getAccessAdapter();

OleDbCommandBuilder bld = new OleDbCommandBuilder(oda);
bld.GetInsertCommand(true);
OleDbCommand command;

command = new OleDbCommand(
"INSERT INTO TblOperations (Device,Operation) " +
"VALUES ( ?,?)");

command.Parameters.Add("@Device", OleDbType.VarChar, 40, "Device");
command.Parameters.Add("@Operation", OleDbType.VarChar, 40, "Operation");

oda.InsertCommand = command;

command = new OleDbCommand("UPDATE TblOperations SET Device=?, Operation=? WHERE ID_key=?");
command.Parameters.Add(new OleDbParameter("Device", OleDbType.VarChar , 50));
command.Parameters.Add(new OleDbParameter("Operation", OleDbType.VarChar, 50));
command.Parameters.Add(new OleDbParameter("ID_key", OleDbType.Numeric, 0));

oda.UpdateCommand=command;

oda.Update(ds, "Table1");

return " hello world " + oda.UpdateCommand.CommandText;

}

Ext - .Net dataset updating with grid

I am enjoying my Ext/ajaxpro grid and it seems to work great for viewing .net datasets. My next goal is to allow inline editing and updates to the dataset and of course return the modified dataset to the server for processing