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
Related
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; }
I am trying to get a specific value from a Bson document using an IQueryable object. I have a method that is reading a json structure as shown below.
"SimulatedData": [
{
"value": 1819.00923045901,
"units": "hp",
"tag": "comp/totalIhp",
"name": "Compressor - Total IHP"
},
{
"value": 789.294125,
"units": "RPM",
"tag": "comp/averageSpeed",
"name": "Compressor - Speed"
},
{
"value": 2064.74658240481,
"units": "hp",
"tag": "comp/totalBhp",
"name": "Compressor - Total BHP"
}
]
I am reading this JSON, getting the 'tag' key value and then looking for this tag value in a collection in MongoDB.
try
{
string jsonFromFile;
using (var reader = new StreamReader(path))
{
jsonFromFile = reader.ReadToEnd();
}
var simulatedData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(jsonFromFile);
foreach (var channel in simulatedData.SimulatedData)
{
var tag = channel.tag;
var master = DBConnect.CosmosClient.GetCollection<MasterVariables>("MasterVariables");
var channelId = master.AsQueryable().Where(x => x.Tag == $"{tag}");
foreach(var c in channelId)
{
string id = c.ChannelID;
Console.WriteLine(id);
}
}
}
The value of the 'tag' key will be used to search in MasterVariables for a match. The document in MasterVariables that matches the value of the 'tag' key will result in a JSON/bson as below.I have a class that take in these values and sets them to class attributes
{
"Tag" : "comp/idealTotalSucCapacity",
"Group" : "{ id : \"comp\", parent : \"#\", text : \"Compressor\" }",
"Series" : "Compressor",
"Enabled" : true,
"ChannelID" : "C8",
"productType" : "Spotlight_Comp",
"database" : "compdata"
}
MasterVariables class (below)
public class MasterVariables
{
public string Tag { get; set; }
public string Group { get; set; }
public string Series { get; set; }
public bool Enabled { get; set; }
public string ChannelID { get; set; }
public string productType { get; set; }
public string database { get; set; }
}
My main issue is that I am not able to get the "ChannelID" value using c.ChannelID . My code compiles and doesn't give me any errors. But I am very confused as to why I am not able to get the channelID value using an Iqueryable object. I know the below foreach isn't correct since I will only be receiving 1 Bson document that matches the 'tag' value. But I haven't found anything helpful about a different way to get the ChannelId. Any thoughts on what I am doing wrong here? Or is there a different approach?
foreach(var c in channelId)
{
string id = c.ChannelID;
Console.WriteLine(id);
}
here is my codes.
json_model
var mix = {
MixName: $("#mixname").val(),
MixDesc: tinyMCE.activeEditor.getContent(),
Price: $("#price").val(),
DiseaseMixs: [],
MixProducts: []
}
Add items to DiseaseMixs and MixProducts
$("#DiseaseList").find("tbody tr").each(function (index) {
mix.DiseaseMixs.push({
MixID: parseInt(MixID),
DiseaseID: parseInt($(".diseaseid").eq(index).html()),
ImpactDegree: parseInt($(".derece option:selected").eq(index).html()),
Description: $(".diseaseMixDesc input").eq(index).val()
});
})
$("#productList").find("tbody tr").each(function (index) {
mix.MixProducts.push({
MixID: parseInt(MixID),
ProductID: parseInt($(".productid").eq(index).html()),
MeasureTypeID: parseInt($(".birim option:selected").eq(index).val()),
MeasureAmount: $(".measureAmount input").eq(index).val()
});
})
and end of this process, here is a sample json object that is post.
{
"MixName": "asdasddas",
"MixDesc": "<p>sadasd</p>",
"Price": "123",
"DiseaseMixs": [{
"MixID": 1,
"DiseaseID": 2,
"ImpactDegree": 5,
"Description": "asads"
}, {
"MixID": 1,
"DiseaseID": 3,
"ImpactDegree": 4,
"Description": "aqqq"
}],
"MixProducts": [{
"MixID": 1,
"ProductID": 2,
"MeasureTypeID": 3,
"MeasureAmount": "3"
}, {
"MixID": 1,
"ProductID": 3,
"MeasureTypeID": 2,
"MeasureAmount": "45"
}]
}
ajax post
$.ajax({
url: 'SaveMix',
type: 'POST',
data: JSON.stringify(mix),
contentType: 'application/json; charset=utf-8',
success: function (result) {
console.log(result);
},
error: function (xhr, status) {
alert(status);
console.log(xhr);
}
})
and MVC Model and JSONResult function
Model
public class MixModel
{
public string MixName { get; set; }
public string MixDesc { get; set; }
public float Price { get; set; }
DiseaseMix[] DiseaseMixs { get; set; } //DiseaseMix EntityFramework entity
MixProduct[] MixProducts { get; set; } //MixProduct EF
}
function
[HttpPost]
public JsonResult SaveMix(MixModel mix)
{
bool result = false;
//do something
return Json(new { result = result }, JsonRequestBehavior.AllowGet);
}
and here is the result I get is.
No matter how I tried, I could not bind the model.
What am I doing wrong? Please give me some help.
Thanks in advance.
Model binding is failing because those 2 properties are currently private(which is the default when you don't specify anything explicitly).
Change the 2 properties to public so that model binder can set the values of those.
public class MixModel
{
public string MixName { get; set; }
public string MixDesc { get; set; }
public float Price { get; set; }
public DiseaseMix[] DiseaseMixs { get; set; } //DiseaseMix EntityFramework entity
public MixProduct[] MixProducts { get; set; } //MixProduct EF
}
I also suggests to not mix your view models with entities generated by your ORM. That creates a tightly coupled solution.
Client code:
var basket = {
products: [],
user: { name: "schugh" }
};
$("#basket table tr").each(function (index, item) {
var product = $(item).data('product');
if (product) {
basket.products.push(product);
}
});
$.ajax({
url: "http://localhost:12116/basketrequest/1",
async: true,
cache: false,
type: 'POST',
data: JSON.stringify(basket),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
alert(result);
},
error: function (jqXHR, exception) {
alert(exception);
}
});
Server code:
Post["/basketrequest/{id}"] = parameters =>
{
var basketRequest = this.Bind(); //basketrequest is null
return Response.AsJson(basketRequest , HttpStatusCode.OK);
};
Other model classes:
[Serializable]
public class BasketRequest
{
public User User;
public List<Product> Products;
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
public ProductStatus ProductStatus { get; set; }
}
public enum ProductStatus
{
Created,
CheckedBy,
Published
}
public class User
{
public string Name { get; set; }
}
The code in the Nancy Module this.Bind(); returns null. If I change the Complex object to just List<Product>, i.e. with no wrapper BasketRequest, the object is fine...
Any pointers?
EDIT: JSON posted:
{
"User": {
"Name": "SChugh"
},
"Products": [{
"Id": 1,
"Name": "Tomato Soup",
"Category": "Groceries",
"Price": 1
}, {
"Id": 2,
"Name": "Yo-yo",
"Category": "Toys",
"Price": 3.75
}]
}
Your BasketRequest object should implement properties instead of fields. So
public class BasketRequest
{
public User User { get; set; }
public List<Product> Products { get; set; }
}
also you should probably use the generic method too
this.Bind<BasketRequest>();
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