load a tree : ExtJs - Jayrock - extjs

im trying to build a treepanel (or just a simple tree i just need it to work) and load it with data from database
here is my code to build the tree
var objHandler = new Interact();
var treestore = new Ext.data.TreeStore ( {
root:{
id:'root_node',
nodeType:'async',
text:'Root'
},
proxy:{
type:'ajax',
url:'myUrl'
}
});
function ReadTree() {
try {
objHandler.ReadAssets(function (serverResponse) {
if (serverResponse.error == null) {
var result = serverResponse.result;
if (result.length > 2) {
treestore.load(Ext.decode(result));//TreeStore does not inherit from Ext.data.Store and thus does not have a loadData method. Both TreeStore and Store inherit from Ext.data.AbstractStore which defines a load method only. Therefore TreeStore has a load method
}
}
else {
alert(serverResponse.error.message);
}
}); //eo serverResponse
} //eo try
catch (e) {
alert(e.message);
}
}
var AssetTree = Ext.create('Ext.tree.Panel', {
title: 'Asset Tree',
width: 200,
height: 150,
store: treestore,
// loader: new Ext.tree.TreeLoader({ url: 'myurl' }),
columns: [
{ xtype: 'treecolumn',text : 'First Name', dataIndex :'Title'}/*,
{text : 'Last', dataIndex :'Adress'},
{text : 'Hired Month', dataIndex :'Description'}*/
],
autoscroll : true
});
ReadTree();
im using jayrock : http://code.google.com/p/jayrock/
Interact.ashx.cs :
public class Interact : JsonRpcHandler
{
[JsonRpcMethod()]
public string ReadAssets()
{
// Make calls to DB or your custom assembly in project and return the result in JSON format. //This part is making custom assembly calls.
clsDBInteract objDBInteract = new clsDBInteract();
string result;
try
{
result = objDBInteract.FetchAssetsJSON();
}
catch (Exception ex)
{
throw ex;
}
return result;
}
clsDBInteract.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using Extensions;
namespace WebBrowser
{
public class clsDBInteract
{
SqlConnection dbConn = new SqlConnection("server=***********; user id = *****; password = ******; Database=*******");
/////// data to fill assets grid
public DataSet FetchAssetsDS()
{
DataSet ds = new DataSet();
try
{
SqlCommand sqlCommand = new SqlCommand("select Title, adress, Description from table");
sqlCommand.Connection = dbConn;
sqlCommand.CommandType = CommandType.Text;
SqlDataAdapter sda = new SqlDataAdapter(sqlCommand);
dbConn.Open();
sda.Fill(ds);
if (sqlCommand.Connection.State == ConnectionState.Open)
{
dbConn.Close();
}
//ds = sqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
return ds;
}//eo FetchAssetsDS
public string FetchAssetsJSON()
{
string result = string.Empty;
try
{
DataSet ds = FetchAssetsDS();
result = ds.ToJSONString(); // This method will convert the contents on Dataset to JSON format;
}
catch (Exception ex)
{
throw ex;
}
return result;
}//eo FetchAssetsJSON
}//eo clsDBInteract
}
I dont have any error, but the panel is empty, i tested and i can read the data in the readtree function..so i guess the problem would be in the store maybe or the loading
its been more than two weeks that im trying to pull this off
any help would be appreciated
P.S: im using ExtJs4 with c# .net
thanks

You havent given a url for the store to get the data from
proxy: {
url:'myurl',
type: 'memory',
reader: {
type: 'json',
root: 'users'
}
}
I would recommend looking at the response in firebug to see if the data structure being returned is valid JSON
EDIT
This is how I would build the create the Tree assuming the JSON is valid for a tree (not just valid JSON)
Ext.create('Ext.tree.Panel', {
rootVisible:false,
store:Ext.create('Ext.data.TreeStore', {
root:{
id:'root_node',
nodeType:'async',
text:'Root'
},
proxy:{
type:'ajax',
url:'yourUrl'
}
})
});

i solved this by creating my own type (no jayrock)
my tree model and store:
Ext.define('TreeModel', {
extend: 'Ext.data.Model',
fields: [
{ name: 'text' },
{ name: 'id' },
{ name: 'descr' }
]
});
window.TreeStore = Ext.create('Ext.data.TreeStore', {
model: 'TreeModel',
root: Ext.decode(obj.TreeToJson()),
proxy: {
type: 'ajax'
},
sorters: [{
property: 'leaf',
direction: 'ASC'
}, {
property: 'text',
direction: 'ASC'
}]
});
my class:
public class TreeItem
{
public string text { get; set; }
public int id { get; set; }
public string descr { get; set; }
public string expanded { get; set; }
public string leaf { get; set; }
public List<TreeItem> children { get; set; }
}
then i get my data and fill my tree like this
public string TreeToJson()
{
List<TreeItem> child = new List<TreeItem>();
for (int i = 0; i < n; i++)
{
child.Add(new TreeItem() { text = t.AssetTree()[i].Item1, id = t.AssetTree()[i].Item2, ip = t.AssetTree()[i].Item3, descr = t.AssetTree()[i].Item4, expanded = "false", leaf = "true" });
}
TreeItem tree = new TreeItem() { text = "my root", id = 0, expanded = "true", leaf = "false", children = child };
}
hope it helps someone

Related

To show icons in dropdown in EPiServer CMS edit mode

I have requirement to show icons as well in dropdown in CMS edit mode as shown below. I'm using EPiServer version 11.15.1.0
In case, if you have any better suggestion/approach , Please advise.
I'm pasting answer here in case if anyone need in future:
define([
"dojo/_base/declare",
"dojo/_base/array",
"dojox/html/entities",
"epi-cms/contentediting/editors/SelectionEditor"
],
function (
declare,
array,
entities,
SelectionEditor
) {
return declare("alloy/editors/SelectionEditorHTML", [SelectionEditor], {
_setSelectionsAttr: function (newSelections) {
this.set("options", array.map(newSelections, function (item) {
let svghtml="<div class='svg_icon'><svg style='width:1.5rem;height:1.5rem'> <use xlink:href='/build/spritemap/demo.spritemap.svg#"+item.value +"'></use></svg></div>";
let html = entities.decode( "<div class='_drpmain'><div class='drptxt'>"+ item.text + "</div>") + entities.decode(svghtml)+"</div>";
return {
label: html,
value: item.value,
selected: item.value === this.value || !item.value && !this.value
};
}, this));
}
});
});
and
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SelectOneWithIconAttribute : Attribute, IMetadataAware
{
public virtual Type SelectionFactoryType { get; set; }
public void OnMetadataCreated(ModelMetadata metadata)
{
if (metadata is ExtendedMetadata extendedMetadata)
{
extendedMetadata.ClientEditingClass = "alloy/editors/SelectionEditorHTML";
extendedMetadata.SelectionFactoryType = SelectionFactoryType;
}
}
}
Once done, simply use attribute
[SelectOneWithIcon(SelectionFactoryType = typeof(IconSelectionFactory))]
[CultureSpecific]
public virtual string Icon1 { get; set; }

Posting JavaScript objects with Ajax and ASP.NET MVC

How can I post a list from view to controller using ajax? I have this code in client side:
$(".js-save").click(function (e) {
e.preventDefault();
var button = $(this);
var lstERegistroVenta = [];
var ERegistroVenta = new Object();
ERegistroVenta.IdProducto = 1;
ERegistroVenta.IdInventario = 2;
ERegistroVenta.MontoProducto = 12.5;
ERegistroVenta.CantidadProducto = 1;
ERegistroVenta.MontoTotalSinIGV = 20.5
ERegistroVenta.MontoTotal = 23.5
lstERegistroVenta.push(ERegistroVenta);
$.ajax({
dataType: 'json',
type: 'POST',
url: "/API/Inventario/Venta/1",
data: JSON.stringify({ lstERegistroVenta: lstERegistroVenta }),
success: function () {
toastr.success("Correcto");
},
error: function () {
toastr.error("Error");
}
});
});
When I try to pass the data I receive only empty list. In server side I have this API
[HttpPost]
[Route("API/Inventario/{Venta}/{IdProducto}")]
public IHttpActionResult AsignarProducto(int IdProducto,List<ERegistroVenta> lstERegistroVenta)
{
return Ok();
}
public class ERegistroVenta
{
public int IdProducto { get; set; }
public int IdInventario { get; set; }
public double MontoProducto { get; set; }
public int CantidadProducto { get; set; }
public double MontoTotalSinIGV { get; set; }
public double MontoTotal { get; set; }
}
First of all, I wouldn't suggest calling an API method directly from a View. Instead, call a controller method which should internally call the API method. The code for this would look something like below.
$.ajax({
dataType: 'json',
type: 'POST',
url: "/TestController/TestMethod",
data: { "IdProducto" : "1", "lstERegistroVenta": lstERegistroVenta },
success: function () {
toastr.success("Correcto");
},
error: function () {
toastr.error("Error");
}
});
[HttpPost]
public void TestMethod(int IdProducto,List<ERegistroVenta> lstERegistroVenta)
{
// Your Logic Here
}
I found a solution. Maybe my mistake was that I didn't send an anonymous list of objects.
Take a look to this:https://kwilson.io/blog/post-an-array-of-objects-to-webapi-using-jquery/
My solution below:
$(".js-save").click(function (e) {
e.preventDefault();
var button = $(this);
var lstERegistroVenta = [];
var ERegistroVenta = new Object();
ERegistroVenta.IdProducto = 1;
ERegistroVenta.IdInventario = 2;
ERegistroVenta.MontoProducto = 12.5;
ERegistroVenta.CantidadProducto = 1;
ERegistroVenta.MontoTotalSinIGV = 20.5
ERegistroVenta.MontoTotal = 23.5
lstERegistroVenta.push(ERegistroVenta);
$.ajax({
dataType: 'json',
method: 'POST',
url: "/API/Inventario/Venta/1",
data: { '': lstERegistroVenta },
success: function () {
toastr.success("Correcto");
},
error: function () {
toastr.error("Error");
}
});
});
And in server side:
[HttpPost]
[Route("API/Inventario/{Venta}/{IdProducto}")]
public IHttpActionResult AsignarProducto(int IdProducto,List<ERegistroVenta> lstERegistroVenta)
{
// Logic Here
}
Hope this helps to another user.

angularjs $http post object always null

I'm trying to send an object to the backend with an $http post, but one of the parameters is always null. I'm formatting the dto in the same way when saving a new object and that works fine, but when I try to call the update function it's not working. What am I missing?
This is my controller code:
vm.postUpdateITSM = function (itsm) {
$http({
method: "POST",
url: "api/sources/" + itsm.Id,
data: {
id: itsm.Id,
dto: {
ConnectorType: itsm.Type,
SourceName: itsm.ServerName,
DisplayName: itsm.DisplayName,
Credentials: JSON.stringify(itsm.UserName,
itsm.Password),
Url: itsm.URL,
Settings: JSON.stringify(itsm.ResolveAlerts ? itsm.ResolveAlerts : false,
itsm.AcknowledgeAlerts ? itsm.AcknowledgeAlerts : false,
itsm.SyncInterval,
itsm.IncidentInterval,
itsm.Status ? itsm.Status : "")
}
}
});
}
And on the back end: The dto is always null when called.
public async Task<IHttpActionResult> Update(int id, [FromBody] SourceDto dto)
{
var source = Mapper.Map<Source>(dto);
source.SourceID = id;
source.ServerCount = "";
var res = await SystemActors.SourceManager.Ask(new UpdateSource(source));
var failure = res as Status.Failure;
if (failure != null)
{
return InternalServerError();
}
var success = ((SqlResult<object>) res).Success;
if (!success)
{
return Content(HttpStatusCode.BadRequest, "Failed to update source.");
}
return Ok(new ResponsePackage {Success = true});
}
And this is the SourceDto class:
public class SourceDto
{
public string ConnectorType { get; set; }
public string SourceName { get; set; }
public string DisplayName { get; set; }
public string Credentials { get; set; }
public string Url { get; set; }
public string Settings { get; set; }
}
Your frontend data is formatted a bit wrong - the data parameter should just be the one object your ASP.NET controller is expecting in the [FromBody], your SourceDto model - and the id should be a query string:
method: "POST",
url: "api/sources/" + itsm.Id,
data: {
ConnectorType: itsm.Type,
SourceName: itsm.ServerName,
DisplayName: itsm.DisplayName,
Credentials: JSON.stringify(itsm.UserName,
itsm.Password),
Url: itsm.URL,
Settings: JSON.stringify(itsm.ResolveAlerts ? itsm.ResolveAlerts : false,
itsm.AcknowledgeAlerts ? itsm.AcknowledgeAlerts : false,
itsm.SyncInterval,
itsm.IncidentInterval,
itsm.Status ? itsm.Status : "")
}
});
ASP.NET will apply the request body to the expected model - if it doesn't match, you'll get null

NancyFX Post - Bind to Object with List Parameter

I am using Nancy and I have created a basic model with a List property on it. When I use the below GET method I get the expected JSON output. However when I try to POST back the same JSON I end up with an object with and empty list of strings. I created two properties just to verify that my issue wasn't because of instantiating the DataPoints parameter to a new List in the constructor. Does anyone have any ideas on why this isn't returning properly?
JSON Object Returned from Initial Get
{
"dataPoints": [
"0",
"1",
"2",
"3",
"4"
],
"dataPoints2": [
"0",
"1",
"2",
"3",
"4"
]
}
JSON Object Returned from Post:
{
"dataPoints": [],
"dataPoints2": []
}
Class:
public class BasicModel
{
private List<string> _dataPoints;
public List<string> DataPoints
{
get
{
if (_dataPoints == null)
{
_dataPoints = new List<string>();
}
return _dataPoints;
}
set
{
_dataPoints = value;
}
}
public List<string> DataPoints2 { get; set; }
public BasicModel()
{
DataPoints2 = new List<string>();
}
public BasicModel(int idx)
{
DataPoints2 = new List<string>();
for (int i = 0; i < idx; i++)
{
DataPoints.Add(i.ToString());
DataPoints2.Add(i.ToString());
}
}
}
Get Method:
Get["/basicModel/{idx}"] = parameters =>
{
int idx = Convert.ToInt32(parameters["idx"].ToString());
BasicModel m = new BasicModel(idx);
return Negotiate
.WithStatusCode(HttpStatusCode.OK)
.WithModel(m)
.WithView("default");
};
Post Method:
Post["/basicmodel"] = parameters =>
{
BasicModel m = new BasicModel();
this.BindTo(m);
return Negotiate
.WithStatusCode(HttpStatusCode.OK)
.WithModel(m)
.WithView("default");
};
You may be running into a know issue with BindTo create a new instance even though you give one.
You should be able use Bind instead of BindTo though and have bind return a new object:
Post["/basicmodel"] = parameters =>
{
BasicModel m = this.Bind();
return Negotiate
.WithStatusCode(HttpStatusCode.OK)
.WithModel(m)
.WithView("default");
};

Build and load a tree with data from database with ExtJs

I'm trying to build a treepanel (or just a simple tree I just need it to work) and load it with data from database
I've been trying and trying and trying ..but cant do it.
Can someone show me how can I do this please?
My JSON:
{
{Title:'yahoo Website',adress:'www.yahoo.com',Description:'Serveur yahoo'},
{Title:'skype',adress:'skype.com',Description:'skype.com'},
{Title:'bing',adress:'www.bing.com',Description:'microsoft bing'},
{Title:'facebook',adress:'www.facebook.com',Description:'social network'},
{Title:'Google',adress:'Google.com',Description:'Google';},
{Title:'\' or 1=1--',adress:'\' or 1=1--',Description:'\' or 1=1--'}
]
My C# code:
public class Interact : JsonRpcHandler {
[JsonRpcMethod()]
public string ReadAssets() {
clsDBInteract objDBInteract = new clsDBInteract();
string result;
try {
result = objDBInteract.FetchAssetsJSON();
} catch (Exception ex) {
throw ex;
}
return result;
}
firstly look at this simple example. This tree have a store wich can read infromation from url by json scructure. You can write there http://youdomain.com/yourscript.php. At yourscript.php you have to read information from database, encode it to JSON and run echo your_json;
That's all.
P.S. json example
i solved this by creating my own type (no jayrock)
my tree model and store:
Ext.define('TreeModel', {
extend: 'Ext.data.Model',
fields: [
{ name: 'text' },
{ name: 'id' },
{ name: 'descr' }
]
});
window.TreeStore = Ext.create('Ext.data.TreeStore', {
model: 'TreeModel',
root: Ext.decode(obj.TreeToJson()),
proxy: {
type: 'ajax'
},
sorters: [{
property: 'leaf',
direction: 'ASC'
}, {
property: 'text',
direction: 'ASC'
}]
});
my class:
public class TreeItem
{
public string text { get; set; }
public int id { get; set; }
public string descr { get; set; }
public string expanded { get; set; }
public string leaf { get; set; }
public List<TreeItem> children { get; set; }
}
then i get my data and fill my tree like this
public string TreeToJson()
{
List<TreeItem> child = new List<TreeItem>();
for (int i = 0; i < n; i++)
{
child.Add(new TreeItem() { text = t.AssetTree()[i].Item1, id = t.AssetTree()[i].Item2, ip = t.AssetTree()[i].Item3, descr = t.AssetTree()[i].Item4, expanded = "false", leaf = "true" });
}
TreeItem tree = new TreeItem() { text = "my root", id = 0, expanded = "true", leaf = "false", children = child };
}
hope it helps someone

Resources