crp_spaeth
15 May 2009, 1:35 AM
After evant and shibubh already released two Solutions for ExtDirect <-> .net Comunication
I just proud to release mine.
After both Routers have nice Ideas I just took the best stuff from both and combine it into an Opensource Project i just released ExtDirect4DotNet.
http://code.google.com/p/extdirect4dotnet
So Whats the deal with this Router/Proxy?
You will not need to write your own Handler (but you still can).
All you need to get it running is
Include the JSON.NET dll into your Project,
Include the extdirect4dotnet dll and configure two handlers in your web.config
<add verb="*" path="directProxy.rfc" type="ExtDirect4DotNet.DirectProxy,ExtDirect4DotNet"/>
<add verb="*" path="directRouter.rfc" type="ExtDirect4DotNet.DirectRouter,ExtDirect4DotNet"/>
At this Point you are ready to go.
If you want to make a Method Call able from Extjs
just add an Attribute to its class by write the Line infront of your class
[DirectAction]
and add [DirectMethod] before the Method you want to share.
In the Example attached to the release at GoogleCode you will find the CRUDSampleMethods Class:
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ExtDirect4DotNet;
using System.Collections.Generic;
using ExtDirect4DotNet.helper;
namespace ExtDirect4DotNetSample
{
public class Person
{
public string id
{
get;
set;
}
public string email
{
get;
set;
}
public string first
{
get;
set;
}
public string last
{
get;
set;
}
}
/// <summary>
/// A sample Ext.Direct - Action - Class
///
/// Class is markt as DirectAction via the Direct Action attribute [DirectAction]
///
/// The Class extends ActionWithSessionState wich makes the curren SessionState in this Action
/// availible via the Session member.
/// </summary>
[DirectAction]
public class CRUDSampleMethods : ActionWithSessionState
{
/// <summary>
/// Just a small Id generator jusing the Session to store the highest id
/// </summary>
/// <returns>the Id</returns>
private string generateId()
{
Session["lastId"] = ((int)Session["lastId"]) + 1;
return Session["lastId"].ToString();
}
/// <summary>
/// Returns a (cached) List of Persons from the Session
/// </summary>
/// <returns>The List of Persons</returns>
private List<Person> getData()
{
return getData(false);
}
/// <summary>
/// Returns a (cached) List of Persons from the Session
/// </summary>
/// <param name="fresh">true to clear the Cache</param>
/// <returns>The List of Persons</returns>
private List<Person> getData(Boolean fresh)
{
List<Person> personList = (List<Person>)Session["CRUDMethodsData"];
if (personList == null || !fresh)
{
personList = new List<Person>();
Person p1 = new Person() { first = "Martin", last = "Späth", email = "email1@extjs.com", id = "1" };
personList.Add(p1);
Person p2 = new Person() { first = "Heinz", last = "Erhart", email = "email2@extjs.com", id = "2" };
personList.Add(p2);
Person p3 = new Person() { first = "Albert", last = "Einstein", email = "email1@extjs.com", id = "3" };
personList.Add(p3);
Session["CRUDMethodsData"] = personList;
Session["lastId"] = 3;
}
return personList;
}
/// <summary>
/// The C in Crud
/// Represents a properitary Logic for creating a Person Object
/// Adds it to the List in the Session and after that it returns back the Person
///
/// This Methode has bin marked as a DirectMethod via the DirectMethod Attribute [DirectMethod]
/// You can configure Different Options for this Methods by setting Properties in the Attribute.
/// While this Method will get Used in a CRUD Process and some of those Methodes need special Handling
/// the MethodeType is set To Create.
///
/// See the MethodType Doc for more information
/// </summary>
/// <param name="personToCreate">The Person that should get added to the List in the Session (represents a Record in Extjs)</param>
/// <returns>The Person that was created</returns>
[DirectMethod(MethodType = DirectMethodType.Create)]
public Person create(Person personToCreate)
{
personToCreate.id = generateId();
getData().Add(personToCreate);
return personToCreate;
}
/// <summary>
/// The R in cRud
/// Represents a properitary Logic for Reading.
/// Will return a List Of Persons Wrapped by a LoadResponse Class
///
/// This Methode is marked as a DirectMethod via the DirectMethod Attribute [DirectMethod]
/// You can configure Different Options for this Methods by setting Properties in the Attribute.
///
/// Special thing here is the ParameterHandling.
/// Which is set to AutoResolve her. This means that you can call the Function form the Javascript Side
/// like this:
///
/// CRUDSampleMethods.read({sort: 'email', dir:'ASC'})
///
/// and the DirectMethod Class will try to mapp those Parameters to the Parameters of the .Net Function
///
/// So this Function will get call as you would call it in .Net the following way.
///
/// read("email","ASC")
/// </summary>
/// <param name="sort">the property to Sort the List of Persons by</param>
/// <param name="dir">The Direction or "ASC"/"DESC"</param>
/// <returns>A LoadRespone Object that wraps the Persons</returns>
[DirectMethod(MethodType = DirectMethodType.Read, ParameterHandling = ParameterHandling.AutoResolve)]
public LoadResponse read(string sort, string dir)
{
List<Person> rows = getData();
switch (sort)
{
case "email":
rows.Sort(delegate(Person p1, Person p2)
{
return p1.email.CompareTo(p2.email);
});
break;
case "first":
rows.Sort(delegate(Person p1, Person p2)
{
return p1.first.CompareTo(p2.first);
});
break;
case "last":
default:
rows.Sort(delegate(Person p1, Person p2)
{
return p1.last.CompareTo(p2.last);
});
break;
}
if (dir != "ASC")
{
rows.Reverse();
}
return new LoadResponse() { Results = rows.Count, Rows = rows };
}
/// <summary>
/// The U in crUd
/// Represents a properitary Logic for Updating an existing Person in the List.
///
/// This Methode is marked as a DirectMethod via the DirectMethod Attribute [DirectMethod]
/// You can configure Different Options for this Methods by setting Properties in the Attribute.
///
/// The MethodType is Set to Uptdate here.
/// This means a Special Parameterhandling as well.
/// The Method will get Called from Extjs in the following Way:
///
/// update(1,{RECORD});
///
/// DirectMethodType.Update
///
/// Will Pass that into your Function
/// </summary>
/// <param name="sort">the property to Sort the List of Persons by</param>
/// <param name="dir">The Direction or "ASC"/"DESC"</param>
/// <returns>A LoadRespone Object that wraps the Persons</returns>
[DirectMethod(MethodType = DirectMethodType.Update)]
public Person update(string id, Person personWithUpdatedValues)
{
List<Person> persons = getData();
Person person = persons.Find(t => t.id == id);
// update logic
if (personWithUpdatedValues.last != null)
{
person.last = personWithUpdatedValues.last;
}
if (personWithUpdatedValues.first != null)
{
person.first = personWithUpdatedValues.first;
}
if (personWithUpdatedValues.email != null)
{
person.email = personWithUpdatedValues.email;
}
return person;
}
/// <summary>
/// The D in cruD
/// Represents a properitary Logic for Deleting an existing Person in the List.
///
/// This Methode is marked as a DirectMethod via the DirectMethod Attribute [DirectMethod]
/// You can configure Different Options for this Methods by setting Properties in the Attribute.
///
/// The MethodType is Set to Delete here.
///
/// An nother Special thing here is the OutputHandling Parameter
/// This ensures that the Followin Proccess Logic will not rerender the result of this methods
///
/// Make Sure that the ToString Function of this Function returns Clean JSON if you want to use this Method!
/// </summary>
/// <param name="id">Id Of the Person which should get deleted</param>
/// <returns>just retunrs Success to tell the store that the record was deleted on the Server.</returns>
[DirectMethod(MethodType = DirectMethodType.Delete, OutputHandling=OutputHandling.JSON)]
public string destroy(string id)
{
List<Person> persons = getData();
Person person = persons.Find(t => t.id == id);
persons.Remove(person);
return "{\"success\": true}";
}
/// <summary>
/// just a small function that resets the content of the Session Object
/// </summary>
[DirectMethod]
public void reset()
{
getData(true);
}
}
}
As you can see in the Example you got many Options to configure your methods by setting the properties of the Attributes:
For more Details just take a look at the Attribute Class itself.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExtDirect4DotNet
{
public enum DirectMethodType
{
/// <summary>
/// Contains a single Parameter with the Record to save.
/// If the method has only One Paramter the Parametr gets deserialzed with the typ of that parameter.
/// </summary>
Create,
/// <summary>
/// Since The parameter will come as a Hash e.g.: {sort: 'name', sortDir: 'DESC'}
/// the Hash will get mapted via Autoresolve.
///
/// The Function should have at least those two Parameters: (string sort, string sortDir).
/// </summary>
Read,
/// <summary>
/// Len gets set to 2 since the Update function gets called with two parameters
/// First is the Id of the Record, Second is the record with the updated data.
/// If The DirectMethod it self has two parametrs, the Seconde Parameter in the Request
/// Gets Serialized with the same type than the Function.
/// </summary>
Update,
/// <summary>
/// The Function will have only one Parameter the Id.
/// </summary>
Delete,
/// <summary>
/// Simple Function...
/// </summary>
Normal,
/// <summary>
/// Function with Form Specifix Handling (len gets set to 1 and the parameter will read out of the httpContext.Form)
/// </summary>
Form,
/// <summary>
/// This Method gets Handled as a normal Method but the Proxy will generate another Method with the posfix "_form"
/// where len gets set to 1 and the Parameterhandling for this gets done as a Form Method
/// </summary>
Hybrid
}
public enum ParameterHandling
{
/// <summary>
/// No Special Handling will be done
/// The Parameter mapping been done by parameter Position
/// </summary>
PassThrough,
/// <summary>
/// Set this to true to set len propertie to for normal Methodes (No CRUD Methods special handling) to 1 and try to resolve the parameter.
/// This makse it possible to submit paramers independend from their order same technic as in exct used
/// minimize paramter to one containing all the properties {name: 'Martin', lastname: 'Spaeth'} will execute
/// the following sample method
///
/// [DirectMethod(ResolveParameterNames=true)]
/// public string sample(string name, string lastname){
/// return "{name:"+name+",lastname:"+lastname"}";
/// }
///
/// will return an API definition like that:
///
/// "ActionName":[{"name":"sample","len":1,"formHandler":false}
///
/// And can get called from Ext like that:
///
/// ActionName.sample({lastname:'spaeth',name:'martin'});
///
/// </summary>
AutoResolve
}
public enum OutputHandling
{
/// <summary>
/// Used when the Method returns a Normal Object and this should get Serialized before it gets send to the Browser
/// </summary>
Normal,
/// <summary>
/// Signalize the router logic not do Serialisation after execution the method (Defaults to false )
///
/// If you return a json-string and do not set this to true you may end up with this:
/// "... data[{\"propertiename\":\"propertyValue\"}] ..." instead of
/// "... date[{"propertiename":"propertieValue"}"] ...
/// </summary>
JSON
}
/// <summary>
/// This attribute should be added to methods that will be Ext.direct methods.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class DirectMethodAttribute : Attribute
{
/// <summary>
/// Set this Option for Specific output Handling
/// </summary>
public OutputHandling OutputHandling = OutputHandling.Normal;
/// <summary>
/// Set this Option for specific parameter-mapping handling
/// This may influnce the len propertie of the Function
/// </summary>
public ParameterHandling ParameterHandling = ParameterHandling.PassThrough;
/// <summary>
/// Set this Option to specifie this Method for the CRUD Actions
/// </summary>
public DirectMethodType MethodType = DirectMethodType.Normal;
/// <summary>
/// Set this to true to let ExtDirect4DotNet try to SerializeParameter Types for you.
///
/// This Option makes is Usefull when you want to Call a method with a Date for Example
/// The Router will use the Newtonsofts deserialize Function and trys to deserialize the Json string into
/// The needed parameter
/// </summary>
public bool SerializeParameterTypes = false;
}
}
Just to summarize:
You can set the following Properties
MethodType
Create
Contains a single Parameter with the Record to save.
If the method has only One Paramter the Parametr gets deserialzed with the typ of that parameter.
Read
Since The parameter will come as a Hash e.g.: {sort: 'name', sortDir: 'DESC'}
the Hash will get mapted via Autoresolve.
The Function should have at least those two Parameters: (string sort, string sortDir).
Update
The Function will have only one Parameter the Id.
Delete
len = 1
Normal
Default. ParameterCount will get set to the number of Parameters the Function has
Form
Function with Form Specifix Handling (len gets set to 1 and the parameter will read out of the httpContext.Form)
Hybrid
This Method gets Handled as a normal Method but the Proxy will generate another Method with the posfix "_Form"
where len gets set to 1 and the Parameterhandling for this gets done as a Form Method
ParameterHandling
PassThrough
No Special Handling will be done
The Parameter mapping been done by parameter Position
AutoResolve
Set this to set len propertie to for normal Methodes (No CRUD Methods special handling) to 1 and try to resolve the parameter.
This makse it possible to submit paramers independend from their order same technic as in exct used
minimize paramter to one containing all the properties {name: 'Martin', lastname: 'Spaeth'} will execute
the following sample method
[DirectMethod(ResolveParameterNames=true)]
public string sample(string name, string lastname){
return "{name:"+name+",lastname:"+lastname"}";ParameterHandling
}
will return an API definition like that:
"ActionName":[{"name":"sample","len":1,"formHandler":false}
And can get called from Ext like that:
ActionName.sample({lastname:'spaeth',name:'martin'});
OutputHandling
Normal
Used when the Method returns a Normal Object and this should get Serialized before it gets send to the Browser
Signalize the router logic not do Serialisation after execution the method (Defaults to false )
JSON
If you return a json-string and do not set this to true you may end up with this:
"... data[{\"propertiename\":\"propertyValue\"}] ..." instead of
"... date[{"propertiename":"propertieValue"}"] ...
Another great Feature of ExtDirect4DotNet is:
Automatic Parameter Deserialization
This makes it Possible to have every Kind of Class as a Parameter for your .net Classes
as long as they are deserializable by JSON.NET:
Example
You can define Class named Person
public class Person
{
public string id
{
get;
set;
}
public string email
{
get;
set;
}
public string first
{
get;
set;
}
public string last
{
get;
set;
}
}
now you can use this class as Parameter for a Function.
// function within an DirectAction marked Class called DirectAction:
[DirectMethod]
public string getName(Person person)
{
return person.first + " " + person.last;
}
you can now call this class by
DirectAction.getName({last: 'spaeth', first:'martin'}, function(res){alert(res)});
If the Deserilization fails it will return an Exception.
Use Session State in your Methods
As you can see in the CRUD-Sample
You can implement IActionWithSessionState or just extend from ActionWithSessionState
to Have Access to the current Session via the now available Session property.
If you like to give this a try just download:
http://extdirect4dotnet.googlecode.com/files/extdirect4dotnet.zip
This Zip includes two Full documented Samples and Testscenarios
Btw. If someone would like to join the Project feel free to send me an PM.
I just proud to release mine.
After both Routers have nice Ideas I just took the best stuff from both and combine it into an Opensource Project i just released ExtDirect4DotNet.
http://code.google.com/p/extdirect4dotnet
So Whats the deal with this Router/Proxy?
You will not need to write your own Handler (but you still can).
All you need to get it running is
Include the JSON.NET dll into your Project,
Include the extdirect4dotnet dll and configure two handlers in your web.config
<add verb="*" path="directProxy.rfc" type="ExtDirect4DotNet.DirectProxy,ExtDirect4DotNet"/>
<add verb="*" path="directRouter.rfc" type="ExtDirect4DotNet.DirectRouter,ExtDirect4DotNet"/>
At this Point you are ready to go.
If you want to make a Method Call able from Extjs
just add an Attribute to its class by write the Line infront of your class
[DirectAction]
and add [DirectMethod] before the Method you want to share.
In the Example attached to the release at GoogleCode you will find the CRUDSampleMethods Class:
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ExtDirect4DotNet;
using System.Collections.Generic;
using ExtDirect4DotNet.helper;
namespace ExtDirect4DotNetSample
{
public class Person
{
public string id
{
get;
set;
}
public string email
{
get;
set;
}
public string first
{
get;
set;
}
public string last
{
get;
set;
}
}
/// <summary>
/// A sample Ext.Direct - Action - Class
///
/// Class is markt as DirectAction via the Direct Action attribute [DirectAction]
///
/// The Class extends ActionWithSessionState wich makes the curren SessionState in this Action
/// availible via the Session member.
/// </summary>
[DirectAction]
public class CRUDSampleMethods : ActionWithSessionState
{
/// <summary>
/// Just a small Id generator jusing the Session to store the highest id
/// </summary>
/// <returns>the Id</returns>
private string generateId()
{
Session["lastId"] = ((int)Session["lastId"]) + 1;
return Session["lastId"].ToString();
}
/// <summary>
/// Returns a (cached) List of Persons from the Session
/// </summary>
/// <returns>The List of Persons</returns>
private List<Person> getData()
{
return getData(false);
}
/// <summary>
/// Returns a (cached) List of Persons from the Session
/// </summary>
/// <param name="fresh">true to clear the Cache</param>
/// <returns>The List of Persons</returns>
private List<Person> getData(Boolean fresh)
{
List<Person> personList = (List<Person>)Session["CRUDMethodsData"];
if (personList == null || !fresh)
{
personList = new List<Person>();
Person p1 = new Person() { first = "Martin", last = "Späth", email = "email1@extjs.com", id = "1" };
personList.Add(p1);
Person p2 = new Person() { first = "Heinz", last = "Erhart", email = "email2@extjs.com", id = "2" };
personList.Add(p2);
Person p3 = new Person() { first = "Albert", last = "Einstein", email = "email1@extjs.com", id = "3" };
personList.Add(p3);
Session["CRUDMethodsData"] = personList;
Session["lastId"] = 3;
}
return personList;
}
/// <summary>
/// The C in Crud
/// Represents a properitary Logic for creating a Person Object
/// Adds it to the List in the Session and after that it returns back the Person
///
/// This Methode has bin marked as a DirectMethod via the DirectMethod Attribute [DirectMethod]
/// You can configure Different Options for this Methods by setting Properties in the Attribute.
/// While this Method will get Used in a CRUD Process and some of those Methodes need special Handling
/// the MethodeType is set To Create.
///
/// See the MethodType Doc for more information
/// </summary>
/// <param name="personToCreate">The Person that should get added to the List in the Session (represents a Record in Extjs)</param>
/// <returns>The Person that was created</returns>
[DirectMethod(MethodType = DirectMethodType.Create)]
public Person create(Person personToCreate)
{
personToCreate.id = generateId();
getData().Add(personToCreate);
return personToCreate;
}
/// <summary>
/// The R in cRud
/// Represents a properitary Logic for Reading.
/// Will return a List Of Persons Wrapped by a LoadResponse Class
///
/// This Methode is marked as a DirectMethod via the DirectMethod Attribute [DirectMethod]
/// You can configure Different Options for this Methods by setting Properties in the Attribute.
///
/// Special thing here is the ParameterHandling.
/// Which is set to AutoResolve her. This means that you can call the Function form the Javascript Side
/// like this:
///
/// CRUDSampleMethods.read({sort: 'email', dir:'ASC'})
///
/// and the DirectMethod Class will try to mapp those Parameters to the Parameters of the .Net Function
///
/// So this Function will get call as you would call it in .Net the following way.
///
/// read("email","ASC")
/// </summary>
/// <param name="sort">the property to Sort the List of Persons by</param>
/// <param name="dir">The Direction or "ASC"/"DESC"</param>
/// <returns>A LoadRespone Object that wraps the Persons</returns>
[DirectMethod(MethodType = DirectMethodType.Read, ParameterHandling = ParameterHandling.AutoResolve)]
public LoadResponse read(string sort, string dir)
{
List<Person> rows = getData();
switch (sort)
{
case "email":
rows.Sort(delegate(Person p1, Person p2)
{
return p1.email.CompareTo(p2.email);
});
break;
case "first":
rows.Sort(delegate(Person p1, Person p2)
{
return p1.first.CompareTo(p2.first);
});
break;
case "last":
default:
rows.Sort(delegate(Person p1, Person p2)
{
return p1.last.CompareTo(p2.last);
});
break;
}
if (dir != "ASC")
{
rows.Reverse();
}
return new LoadResponse() { Results = rows.Count, Rows = rows };
}
/// <summary>
/// The U in crUd
/// Represents a properitary Logic for Updating an existing Person in the List.
///
/// This Methode is marked as a DirectMethod via the DirectMethod Attribute [DirectMethod]
/// You can configure Different Options for this Methods by setting Properties in the Attribute.
///
/// The MethodType is Set to Uptdate here.
/// This means a Special Parameterhandling as well.
/// The Method will get Called from Extjs in the following Way:
///
/// update(1,{RECORD});
///
/// DirectMethodType.Update
///
/// Will Pass that into your Function
/// </summary>
/// <param name="sort">the property to Sort the List of Persons by</param>
/// <param name="dir">The Direction or "ASC"/"DESC"</param>
/// <returns>A LoadRespone Object that wraps the Persons</returns>
[DirectMethod(MethodType = DirectMethodType.Update)]
public Person update(string id, Person personWithUpdatedValues)
{
List<Person> persons = getData();
Person person = persons.Find(t => t.id == id);
// update logic
if (personWithUpdatedValues.last != null)
{
person.last = personWithUpdatedValues.last;
}
if (personWithUpdatedValues.first != null)
{
person.first = personWithUpdatedValues.first;
}
if (personWithUpdatedValues.email != null)
{
person.email = personWithUpdatedValues.email;
}
return person;
}
/// <summary>
/// The D in cruD
/// Represents a properitary Logic for Deleting an existing Person in the List.
///
/// This Methode is marked as a DirectMethod via the DirectMethod Attribute [DirectMethod]
/// You can configure Different Options for this Methods by setting Properties in the Attribute.
///
/// The MethodType is Set to Delete here.
///
/// An nother Special thing here is the OutputHandling Parameter
/// This ensures that the Followin Proccess Logic will not rerender the result of this methods
///
/// Make Sure that the ToString Function of this Function returns Clean JSON if you want to use this Method!
/// </summary>
/// <param name="id">Id Of the Person which should get deleted</param>
/// <returns>just retunrs Success to tell the store that the record was deleted on the Server.</returns>
[DirectMethod(MethodType = DirectMethodType.Delete, OutputHandling=OutputHandling.JSON)]
public string destroy(string id)
{
List<Person> persons = getData();
Person person = persons.Find(t => t.id == id);
persons.Remove(person);
return "{\"success\": true}";
}
/// <summary>
/// just a small function that resets the content of the Session Object
/// </summary>
[DirectMethod]
public void reset()
{
getData(true);
}
}
}
As you can see in the Example you got many Options to configure your methods by setting the properties of the Attributes:
For more Details just take a look at the Attribute Class itself.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExtDirect4DotNet
{
public enum DirectMethodType
{
/// <summary>
/// Contains a single Parameter with the Record to save.
/// If the method has only One Paramter the Parametr gets deserialzed with the typ of that parameter.
/// </summary>
Create,
/// <summary>
/// Since The parameter will come as a Hash e.g.: {sort: 'name', sortDir: 'DESC'}
/// the Hash will get mapted via Autoresolve.
///
/// The Function should have at least those two Parameters: (string sort, string sortDir).
/// </summary>
Read,
/// <summary>
/// Len gets set to 2 since the Update function gets called with two parameters
/// First is the Id of the Record, Second is the record with the updated data.
/// If The DirectMethod it self has two parametrs, the Seconde Parameter in the Request
/// Gets Serialized with the same type than the Function.
/// </summary>
Update,
/// <summary>
/// The Function will have only one Parameter the Id.
/// </summary>
Delete,
/// <summary>
/// Simple Function...
/// </summary>
Normal,
/// <summary>
/// Function with Form Specifix Handling (len gets set to 1 and the parameter will read out of the httpContext.Form)
/// </summary>
Form,
/// <summary>
/// This Method gets Handled as a normal Method but the Proxy will generate another Method with the posfix "_form"
/// where len gets set to 1 and the Parameterhandling for this gets done as a Form Method
/// </summary>
Hybrid
}
public enum ParameterHandling
{
/// <summary>
/// No Special Handling will be done
/// The Parameter mapping been done by parameter Position
/// </summary>
PassThrough,
/// <summary>
/// Set this to true to set len propertie to for normal Methodes (No CRUD Methods special handling) to 1 and try to resolve the parameter.
/// This makse it possible to submit paramers independend from their order same technic as in exct used
/// minimize paramter to one containing all the properties {name: 'Martin', lastname: 'Spaeth'} will execute
/// the following sample method
///
/// [DirectMethod(ResolveParameterNames=true)]
/// public string sample(string name, string lastname){
/// return "{name:"+name+",lastname:"+lastname"}";
/// }
///
/// will return an API definition like that:
///
/// "ActionName":[{"name":"sample","len":1,"formHandler":false}
///
/// And can get called from Ext like that:
///
/// ActionName.sample({lastname:'spaeth',name:'martin'});
///
/// </summary>
AutoResolve
}
public enum OutputHandling
{
/// <summary>
/// Used when the Method returns a Normal Object and this should get Serialized before it gets send to the Browser
/// </summary>
Normal,
/// <summary>
/// Signalize the router logic not do Serialisation after execution the method (Defaults to false )
///
/// If you return a json-string and do not set this to true you may end up with this:
/// "... data[{\"propertiename\":\"propertyValue\"}] ..." instead of
/// "... date[{"propertiename":"propertieValue"}"] ...
/// </summary>
JSON
}
/// <summary>
/// This attribute should be added to methods that will be Ext.direct methods.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class DirectMethodAttribute : Attribute
{
/// <summary>
/// Set this Option for Specific output Handling
/// </summary>
public OutputHandling OutputHandling = OutputHandling.Normal;
/// <summary>
/// Set this Option for specific parameter-mapping handling
/// This may influnce the len propertie of the Function
/// </summary>
public ParameterHandling ParameterHandling = ParameterHandling.PassThrough;
/// <summary>
/// Set this Option to specifie this Method for the CRUD Actions
/// </summary>
public DirectMethodType MethodType = DirectMethodType.Normal;
/// <summary>
/// Set this to true to let ExtDirect4DotNet try to SerializeParameter Types for you.
///
/// This Option makes is Usefull when you want to Call a method with a Date for Example
/// The Router will use the Newtonsofts deserialize Function and trys to deserialize the Json string into
/// The needed parameter
/// </summary>
public bool SerializeParameterTypes = false;
}
}
Just to summarize:
You can set the following Properties
MethodType
Create
Contains a single Parameter with the Record to save.
If the method has only One Paramter the Parametr gets deserialzed with the typ of that parameter.
Read
Since The parameter will come as a Hash e.g.: {sort: 'name', sortDir: 'DESC'}
the Hash will get mapted via Autoresolve.
The Function should have at least those two Parameters: (string sort, string sortDir).
Update
The Function will have only one Parameter the Id.
Delete
len = 1
Normal
Default. ParameterCount will get set to the number of Parameters the Function has
Form
Function with Form Specifix Handling (len gets set to 1 and the parameter will read out of the httpContext.Form)
Hybrid
This Method gets Handled as a normal Method but the Proxy will generate another Method with the posfix "_Form"
where len gets set to 1 and the Parameterhandling for this gets done as a Form Method
ParameterHandling
PassThrough
No Special Handling will be done
The Parameter mapping been done by parameter Position
AutoResolve
Set this to set len propertie to for normal Methodes (No CRUD Methods special handling) to 1 and try to resolve the parameter.
This makse it possible to submit paramers independend from their order same technic as in exct used
minimize paramter to one containing all the properties {name: 'Martin', lastname: 'Spaeth'} will execute
the following sample method
[DirectMethod(ResolveParameterNames=true)]
public string sample(string name, string lastname){
return "{name:"+name+",lastname:"+lastname"}";ParameterHandling
}
will return an API definition like that:
"ActionName":[{"name":"sample","len":1,"formHandler":false}
And can get called from Ext like that:
ActionName.sample({lastname:'spaeth',name:'martin'});
OutputHandling
Normal
Used when the Method returns a Normal Object and this should get Serialized before it gets send to the Browser
Signalize the router logic not do Serialisation after execution the method (Defaults to false )
JSON
If you return a json-string and do not set this to true you may end up with this:
"... data[{\"propertiename\":\"propertyValue\"}] ..." instead of
"... date[{"propertiename":"propertieValue"}"] ...
Another great Feature of ExtDirect4DotNet is:
Automatic Parameter Deserialization
This makes it Possible to have every Kind of Class as a Parameter for your .net Classes
as long as they are deserializable by JSON.NET:
Example
You can define Class named Person
public class Person
{
public string id
{
get;
set;
}
public string email
{
get;
set;
}
public string first
{
get;
set;
}
public string last
{
get;
set;
}
}
now you can use this class as Parameter for a Function.
// function within an DirectAction marked Class called DirectAction:
[DirectMethod]
public string getName(Person person)
{
return person.first + " " + person.last;
}
you can now call this class by
DirectAction.getName({last: 'spaeth', first:'martin'}, function(res){alert(res)});
If the Deserilization fails it will return an Exception.
Use Session State in your Methods
As you can see in the CRUD-Sample
You can implement IActionWithSessionState or just extend from ActionWithSessionState
to Have Access to the current Session via the now available Session property.
If you like to give this a try just download:
http://extdirect4dotnet.googlecode.com/files/extdirect4dotnet.zip
This Zip includes two Full documented Samples and Testscenarios
Btw. If someone would like to join the Project feel free to send me an PM.