mvvmcross keep program settings using file plugin and json serialize/deserialize - json

I'm trying to use the fileplugin and json serializer to do this.
I have the following DcsSetup class, in the core project.
For now I'm working with droid. I can't seem to save the file. The json serialize is ok. The WriteFile seems ok, but next time I try to read the file using TryReadTextFile it fails.
I can't find the file on the device, so I think the WriteFile stuff is wrong.
What is the correct way to save and read my Settings class on Android?
public class DcsSetup
{
public class Settings
{
//Server
public string Server;
public int Port;
public int Device;
public string EncodingFromClient;
public string EncodingToClient;
public int FontCorrectionPixelsWidth; //Pixels to add or subtract i Y dimension to get the right font size
public int FontCorrectionPixelsHeight; //Pixels to add or subtract i Y dimension to get the right font size
public float XPct;//Pct to add to vertical placement of textBox and Buttons.
public float YPct;//Pct to add to horisontal placement of textBox and Buttons.
public float SizePct;//Pct to add to horisontal size of textBox and Buttons.
public bool FullScreen;
public bool DontSleep;
//Diverse
public bool AutoSendEnter;
}
public Settings Setting;
public DcsSetup()
{
var setupFound=true;
var fileService = Mvx.Resolve<IMvxFileStore>();
var jsonConvert = Mvx.Resolve<IMvxJsonConverter>();
var path = fileService.PathCombine("Setting", "Settings.txt");
Setting = new Settings();
try {
string settingFile;
if (fileService.TryReadTextFile(path, out settingFile)){
Setting = jsonConvert.DeserializeObject<Settings>(settingFile);
} else{
setupFound = false;
}
}
catch(Exception e) {
AppTrace.Error("Failed to read settings: {0}", e.Message);
setupFound=false;
}
if(setupFound==false){
Setting.Server = "192.168.1.100";
Setting.Port = 1650;
Setting.Device = 1;
Setting.EncodingFromClient = "CP1252";
Setting.EncodingToClient = "CP1252";
Setting.FontCorrectionPixelsWidth = 0;
Setting.FontCorrectionPixelsHeight = 0;
Setting.XPct = 97.0f;
Setting.YPct = 100.0f;
Setting.SizePct = 98.0f;
Setting.FullScreen = false;
Setting.DontSleep = true;
Setting.AutoSendEnter = true;
try {
//json
var json = jsonConvert.SerializeObject(Setting);
fileService.EnsureFolderExists("Setting");
fileService.WriteFile(path, json);
}
catch (Exception e) {
AppTrace.Error("Failed to save settings: {0}", e.Message);
}
}
}
}
}

I just created a project in VS2012 using the 3.1.1-beta2 packages for MvvmCross
I then added the File and Json plugin packages
I changed the core FirstViewModel to:
public class FirstViewModel
: MvxViewModel
{
private readonly IMvxFileStore _fileStore;
private readonly IMvxJsonConverter _jsonConverter;
private readonly string _filePath;
public class ToStore
{
public string Foo { get; set; }
}
public ICommand SaveCommand
{
get
{
return new MvxCommand(() =>
{
var toStore = new ToStore() {Foo = Hello};
var json = _jsonConverter.SerializeObject(toStore);
_fileStore.WriteFile(_filePath, json);
});
}
}
public ICommand LoadCommand
{
get
{
return new MvxCommand(() =>
{
string txt;
if (_fileStore.TryReadTextFile(_filePath, out txt))
{
Mvx.Trace("Loaded {0}", txt);
var stored = _jsonConverter.DeserializeObject<ToStore>(txt);
Hello = stored.Foo;
}
});
}
}
private string _hello = "Hello MvvmCross";
public FirstViewModel(IMvxFileStore fileStore, IMvxJsonConverter jsonConverter)
{
_fileStore = fileStore;
_jsonConverter = jsonConverter;
_filePath = _fileStore.PathCombine("SubDir", "MyFile.txt");
_fileStore.EnsureFolderExists("SubDir");
}
public string Hello
{
get { return _hello; }
set { _hello = value; RaisePropertyChanged(() => Hello); }
}
}
I called this from a test Android UI:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="40dp"
local:MvxBind="Text Hello"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="40dp"
local:MvxBind="Text Hello"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="40dp"
android:text="Load"
local:MvxBind="Click LoadCommand"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="40dp"
android:text="Save"
local:MvxBind="Click SaveCommand"
/>
</LinearLayout>
This seemed to work OK - it saved and loaded the JSON fine within and between test runs.
Based on this, my only guess is whether you are redeploying the app between runs - if you do this and you don't have MonoDroid's Preserve application data/cache on device between deploys checked, then you won't see the settings preserved.

Related

primefaces org.primefaces.component.diagram override

I have a problem with org.primefaces.component.diagram, i want to add an action when click on any overlay or connector, i make this using jquery, but the problem is that there is no identifier for the connection, after search i was able to get the ids of the 2 end points of the connection but if there is many connection between the same points then i cannot distinguish between them, i tried to override the diagram and add "connectionId" attribute on the connection but i got an exception in the front end :
Uncaught ReferenceError: connectionId590236 is not defined at eval (eval at (jquery.js.xhtml?ln=primefaces&v=5.2:14), :1:1488)
screenshot
The closet solution would be is to use setId on Element in the DefaultDiagramModel creation.
An example would be as the following:
Element elementA = new Element("A", "20em", "6em");
elementA.setId("element-a");
Element elementB = new Element("B", "10em", "18em");
elementB.setId("element-b");
Element elementC = new Element("C", "40em", "18em");
elementC.setId("element-c");
...
Since PrimeFaces doesn't provide the control you are searching for, and the original component comes from jsPlumb, you may rely on that to achieve what you are looking for.
First make sure that the <p:diagram> has a widgetVar value, es. diagramWV
An example would be the following:
$(document).ready(function () {
//timeout makes sure the component is initialized
setTimeout(function () {
for (var key in PF('diagramWV').canvas.getAllConnections()) {
if (PF('diagramWV').canvas.getAllConnections().hasOwnProperty(key)) {
//Elemenets Events
// on source just once
$(PF('diagramWV').canvas.getAllConnections()[key].source).off('click').on('click', function () {
console.log($(this).attr('id'))
});
// on target just once
$(PF('diagramWV').canvas.getAllConnections()[key].target).off('click').on('click', function () {
console.log($(this).attr('id'))
});
//Connection Event
PF('diagramWV').canvas.getAllConnections()[key].bind("click", function (conn) {
console.log("source " + conn.sourceId);
console.log("target " + conn.targetId);
});
}
}
}, 500);
});
Note: The canvas property of the widgetVar is the current instance of jsPlumbInstance
Here's an online demo, and a small working example on github.
finally i found an acceptable solution :
-> add an label overlay on the connection and set the identifier on it.
org.primefaces.model.diagram.Connection conn = new org.primefaces.model.diagram.Connection(
EndPointA, EndPointB);
LabelOverlay labelOverlay = new LabelOverlay(connection.getId(), "labelOverlayClass", 0.3);
conn.getOverlays().add(labelOverlay);
-> then add JS function to handle on dbclick action on the connection and get the id from its related overlay using the classes "._jsPlumb_overlay" and "._jsPlumb_hover"
<p:remoteCommand name="connectionClicked"
actionListener="#{yourBean.onConnectionDoubleClick}" />
<script type="text/javascript">
var connectionId;
$('._jsPlumb_connector').on('dblclick', function(e) {
$('._jsPlumb_overlay._jsPlumb_hover').each(function() {
connectionId = $(this).text();
});
connectionClicked([ { name : 'connectionId', value : connectionId } ]);
});
});
</script>
-> finally in the bean you extract the id and do whatever you want
public void onConnectionDoubleClick() {
Map<String, String> params = FacesContext.getCurrentInstance()
.getExternalContext().getRequestParameterMap();
String connectionId = params.get("connectionId");
if(StringUtils.isBlank(connectionId))
return;
.........
I was able to add a click event to Overlay by extending the primefaces Overlay class. If you make a change to the toJS() class (taking heavy inspiration from the Primefaces LabelOverLay) then you can write your own overlay with the jsplumb overlay constructor. Here's my implementation of a ClickableLabelOverlay.
public class ClickableLabelOverlay implements Overlay {
private String label;
private String styleClass;
private double location = 0.5;
private String onClick;
public ClickableLabelOverlay() {
}
public ClickableLabelOverlay(String label) {
this.label = label;
}
public ClickableLabelOverlay(String label, String styleClass, double location, String onClick) {
this(label);
this.styleClass = styleClass;
this.location = location;
this.onClick = onClick;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getStyleClass() {
return styleClass;
}
public void setStyleClass(String styleClass) {
this.styleClass = styleClass;
}
public double getLocation() {
return location;
}
public void setLocation(double location) {
this.location = location;
}
public String getOnClick() {
return onClick;
}
public void setOnClick(String onClick) {
this.onClick = onClick;
}
public String getType() {
return "Label";
}
public String toJS(StringBuilder sb) {
sb.append("['Label',{label:'").append(label).append("'");
if(styleClass != null) sb.append(",cssClass:'").append(styleClass).append("'");
if(location != 0.5) sb.append(",location:").append(location);
if(onClick != null) sb.append(",events:{click:function(labelOverlay, originalEvent){").append(onClick).append("}}");
sb.append("}]");
return sb.toString();
}
}
Put any javascript you want to execute inside of the onClick variable and it'll run when you click on the overlay. For convenience I added it to the set of default overlays for my diagram.
diagram.getDefaultConnectionOverlays().add(new ClickableLabelOverlay(...)

MvxAutoCompleteTextView does not show dropdown list

When I enter "aa" in MvxAutoCompleteTextView. No dropdown list shown.
Anyone knows how to use MvxAutoCompleteTextView? No example in Mvvmcross NPlus1Days and Tutorials.Thanks
Layout
<MvxAutoCompleteTextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
local:MvxBind="Text SearchKey; ItemsSource ListAddresses; PartialText LabelTitle; SelectedObject Address" />
ViewModel
private string _SearchKey;
public string SearchKey
{
get { return _SearchKey; }
set { _SearchKey = value; RaisePropertyChanged(() => SearchKey); }
}
private List<string> _ListAddresses = new List<string>(){ "aa", "bb", "cc" };
public List<string> ListAddresses
{
get { return _ListAddresses; }
set { _ListAddresses = value; RaisePropertyChanged(() => ListAddresses); }
}
private string _LabelTitle;
public string LabelTitle
{
get { return _LabelTitle; }
set { _LabelTitle = value; RaisePropertyChanged(() => LabelTitle); }
}
private string _Address;
public string Address
{
get { return _Address; }
set { _Address = value; RaisePropertyChanged(() => Address); }
}
Here is an example that works:
https://github.com/JimWilcox3/MvxAutoCompleteTest
I had trouble with this control as well and Jim's example helped a lot. This answer warns against binding Text and I think that has some merit purely because for me the control was half working. When binding to Text the list view would appear but I could never bind SelectedObject or PartialText. I noticed I was receiving the following bind error:
Error - autoComplete is null in MvxAutoCompleteTextViewPartialTextTargetBinding
The simple fix for me was to change
<MvxAutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
... />
To
<Mvx.MvxAutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
... />

Passing binded item to MvxCommand

Considering the following code:
<Mvx.MvxListView
android:id="#+id/items_list"
style="#style/ListNoDividers"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_above="#+id/footer_panel"
android:layout_below="#+id/intro_text"
local:MvxBind="ItemsSource Items;ItemClick DoItCommand"
local:MvxItemTemplate="#layout/item_template" />
I know that when I tap in item in the list, the DoItCommand will be invoked and the binded item will be past as a command parameter.
How can I use the same in a non MvxListView, like on this code snippet:
<LinearLayout
android:id="#+id/item1"
style="#style/ItemStyle"
local:MvxBind="Click DoItCommand, CommandParameter=PropertyInViewModel"
android:layout_marginBottom="#dimen/HalfDefaultInnerMargin" />
<LinearLayout
android:id="#+id/item1"
style="#style/ItemStyle"
local:MvxBind="Click DoItCommand, CommandParameter=OtherPropertyInViewModel"
android:layout_marginBottom="#dimen/HalfDefaultInnerMargin" />
Bottom line is that I need to pass a property value to DoItCommand using the command parameter.
As pointed out in the comments, using a similar approach to this, solves the issue!
public class MyLinearLayout : LinearLayout
{
public HhLinearLayout(Context context, IAttributeSet attrs)
: base(context, attrs)
{
Click += LinearLayoutClick;
}
public ICommand Command { get; set; }
public object CommandParameter { get; set; }
private void LinearLayoutClick(object sender, EventArgs e)
{
var command = Command;
var commandParameter = CommandParameter;
if (command == null || !command.CanExecute(commandParameter))
{
return;
}
command.Execute(commandParameter);
}
}

Including static html file from ~/Content into ASP.NET MVC view

I've got master page in my project, which contains some information about site copyright and some contact info in it. I'd like to take it out of master page and place it in a static files (for some reason, these files must be placed in ~/Content folder). Is there a way that I can tell in my view something like
<% Html.Include("~/Content/snippet.html") %> // not a real code
?
You are better off using a partial view (even if it only contains static text) and include it with the Html.Partial helper. But if you insist:
<%= File.ReadAllText(Server.MapPath("~/Content/snippet.html")) %>
If you are in .Net MVC 5 and want to include a HTML file a partial file without having Razor that render it:
#Html.Raw(File.ReadAllText(Server.MapPath("~/Views/Shared/ICanHaz.html")))
Use your own view engine
using
#Html.Partial("_CommonHtmlHead")
as
/Views/Shared/_CommonHtmlHead.html
or
/Views/MyArea/Shared/_CommonHtmlHead.htm
is the best for me.
Creating your own view engine for this by using the System.Web.Mvc.VirtualPathProviderViewEngine ascending class seems to be relatively easy:
/// <summary>
/// Simple render engine to load static HTML files, supposing that view files has the html/htm extension, supporting replacing tilda paths (~/MyRelativePath) in the content
/// </summary>
public class HtmlStaticViewEngine : VirtualPathProviderViewEngine
{
private static readonly ILog _log = LogManager.GetLogger(typeof (HtmlStaticViewEngine));
protected readonly DateTime? AbsoluteTimeout;
protected readonly TimeSpan? SlidingTimeout;
protected readonly CacheItemPriority? Priority;
private readonly bool _useCache;
public HtmlStaticViewEngine(TimeSpan? slidingTimeout = null, DateTime? absoluteTimeout = null, CacheItemPriority? priority = null)
{
_useCache = absoluteTimeout.HasValue || slidingTimeout.HasValue || priority.HasValue;
SlidingTimeout = slidingTimeout;
AbsoluteTimeout = absoluteTimeout;
Priority = priority;
AreaViewLocationFormats = new[]
{
"~/Areas/{2}/Views/{1}/{0}.html",
"~/Areas/{2}/Views/{1}/{0}.htm",
"~/Areas/{2}/Views/Shared/{0}.html",
"~/Areas/{2}/Views/Shared/{0}.htm"
};
AreaMasterLocationFormats = new[]
{
"~/Areas/{2}/Views/{1}/{0}.html",
"~/Areas/{2}/Views/{1}/{0}.htm",
"~/Areas/{2}/Views/Shared/{0}.html",
"~/Areas/{2}/Views/Shared/{0}.htm"
};
AreaPartialViewLocationFormats = new[]
{
"~/Areas/{2}/Views/{1}/{0}.html",
"~/Areas/{2}/Views/{1}/{0}.htm",
"~/Areas/{2}/Views/Shared/{0}.html",
"~/Areas/{2}/Views/Shared/{0}.htm"
};
ViewLocationFormats = new[]
{
"~/Views/{1}/{0}.html",
"~/Views/{1}/{0}.htm",
"~/Views/Shared/{0}.html",
"~/Views/Shared/{0}.htm"
};
MasterLocationFormats = new[]
{
"~/Views/{1}/{0}.html",
"~/Views/{1}/{0}.htm",
"~/Views/Shared/{0}.html",
"~/Views/Shared/{0}.htm"
};
PartialViewLocationFormats = new[]
{
"~/Views/{1}/{0}.html",
"~/Views/{1}/{0}.htm",
"~/Views/Shared/{0}.html",
"~/Views/Shared/{0}.htm"
};
FileExtensions = new[]
{
"html",
"htm",
};
}
protected virtual string GetContent(string viewFilePath)
{
string result = null;
if (!string.IsNullOrWhiteSpace(viewFilePath))
{
if (_useCache)
{
result = TryCache(viewFilePath);
}
if (result == null)
{
using (StreamReader streamReader = File.OpenText(viewFilePath))
{
result = streamReader.ReadToEnd();
}
result = ParseContent(result);
if (_useCache)
{
CacheIt(viewFilePath, result);
}
}
}
return result;
}
static readonly Regex TildaRegularExpression = new Regex(#"~/", RegexOptions.Compiled);
/// <summary>
/// Finds all tilda paths in the content and replace it for current path
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
protected virtual string ParseContent(string content)
{
if (String.IsNullOrWhiteSpace(content))
{
return content;
}
string absolutePath = VirtualPathUtility.ToAbsolute("~/");
string result = TildaRegularExpression.Replace(content, absolutePath);
return result;
}
protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
{
HttpContextBase httpContextBase = controllerContext.RequestContext.HttpContext;
string filePath = httpContextBase.Server.MapPath(partialPath);
string content = GetContent(filePath);
return new StaticView(content);
}
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
HttpContextBase httpContextBase = controllerContext.RequestContext.HttpContext;
string result = null;
if (!string.IsNullOrWhiteSpace(masterPath))
{
string filePath = httpContextBase.Server.MapPath(masterPath);
result = GetContent(filePath);
}
string physicalViewPath = httpContextBase.Server.MapPath(viewPath);
result += GetContent(physicalViewPath);
return new StaticView(result);
}
protected virtual string TryCache(string filePath)
{
HttpContext httpContext = HttpContext.Current;
if (httpContext != null && httpContext.Cache != null)
{
string cacheKey = CacheKey(filePath);
return (string)httpContext.Cache[cacheKey];
}
return null;
}
protected virtual bool CacheIt(string filePath, string content)
{
HttpContext httpContext = HttpContext.Current;
if (httpContext != null && httpContext.Cache != null)
{
string cacheKey = CacheKey(filePath);
httpContext.Cache.Add(cacheKey, content, new CacheDependency(filePath), AbsoluteTimeout.GetValueOrDefault(Cache.NoAbsoluteExpiration), SlidingTimeout.GetValueOrDefault(Cache.NoSlidingExpiration), Priority.GetValueOrDefault(CacheItemPriority.AboveNormal), CacheItemRemovedCallback);
return true;
}
return false;
}
protected virtual string CacheKey(string serverPath)
{
return serverPath;
}
protected virtual void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason)
{
_log.InfoFormat("CacheItemRemovedCallback(string key='{0}', object value = ..., {1} reason={2})", key, reason.GetType().Name, reason);
}
}
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ViewEngines.Engines.Add(new HtmlStaticViewEngine(new TimeSpan(12,0,0,0)));
}
}
public class StaticView : IView
{
private readonly string _text;
public StaticView(string text)
{
_text = text;
}
public void Render(ViewContext viewContext, TextWriter writer)
{
if (! string.IsNullOrEmpty(_text))
{
writer.Write(_text);
}
}
}
NOTE:
This code is tested only with simple usage for rendering
partial views
Is there a reason you are holding the content in an HTML file rather than a partial view?
If you create a file called snippet.ascx in your Views/Shared folder you can import the content of that snippet.ascx file into any view by using <% Html.RenderPartial("snippet"); %>
To include static html file into a MVC View goes like this:
<!-- #include virtual="~\Content\snippet.htm" -->
For ASP .NET Core 3.1 Razor page you can do it like this:
#Html.Raw(System.IO.File.ReadAllText("wwwroot/Content/snippet.html"));
See documentation regarding static files here:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1

How to provide JSON data to Dojo tree using Struts2 framework

I'm currently developing a web application using Struts2 framework. This application requires to dynamically update the objects on the screen based on data received from another application.
At the moment, I would like to implement a dynamic tree view which nodes are updated periodically with data provided by an Action class. I’m trying to do so using the dojo.dijit.tree object from the dojo toolkit. I’m aware that I can do so using the dojo tags which are part of the struts framework, however, it lacks much of the functionality that I need (persistence, open and close branches dynamically, etc) therefore, I have opted for using the dojo toolkit instead.
My problem with the dojo.dijit.tree is that I don’t know how to provide its data using a JSON result type. I have already created a class which returns a JSON result type with the same structure needed by the dojo tree component. I have tested the generation of a dojo tree using a file “test.txt” which was generated by the class and it works as expected. However, I would like to pass the JSON data directly to the dojo.dijit.tree component without saving a file on disk. When I execute the application I get a “save as” window to save the returned JSON result.
This is my struts.xml file:
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="devResult" class="gui.JsonAction">
<result name="success">/start1.jsp</result>
</action>
</package>
<package name="example" namespace="/" extends="json-default">
<result-types>
<result-type name="json" class="org.apache.struts2.json.JSONResult"></result-type>
</result-types>
<action name="getJSONResult" class="gui.JsonAction">
<result type="json"/>
</action>
</package>
This is the jsp file which displays the tree:
<head>
<title>Testing Tree</title>
<style type="text/css">
#import "js/dojo/dojo/resources/dojo.css";
#import "js/dojo/dijit/themes/nihilo/nihilo.css";
</style>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js"
djConfig="isDebug: true,parseOnLoad: true">
</script>
<script type="text/javascript">
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.Tree");
dojo.require("dojo.parser");
</script>
<body class="nihilo">
The Tree:<br><br>
<s:url id="devResult" action="jsonAction.action"></s:url>
<div dojoType="dojo.data.ItemFileReadStore" href="%{devResult}" jsid="popStore" />
<div dojoType="dijit.Tree" store="popStore" labelAttr="sname" label="Tree" />
</body>
This is the Action class which produces the JSON result:
public class JsonAction extends ActionSupport {
private static final long serialVersionUID = 7392602552908646926L;
private String label = "name";
private String identifier = "name";
private List<ChildrenClass> items = new ArrayList<ChildrenClass>();
public JsonAction() {
ChildrenClass item1 = new ChildrenClass("name1", "cat");
ChildrenClass item2 = new ChildrenClass("name2", "cat");
ChildrenClass item3 = new ChildrenClass("name3", "cat");
ChildrenClass item4 = new ChildrenClass("name4", "cat");
items.add(item1);
items.add(item2);
items.add(item3);
items.add(item4);
}
public String execute() {
return SUCCESS;
}
public void setLabel(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getIdentifier() {
return identifier;
}
public void setItems(List<ChildrenClass> lists) {
this.items = lists;
}
public List<ChildrenClass> getItems() {
return items;
}
}
This is the ChildrenClass which is used in the class above:
public class ChildrenClass {
private String name;
private String type;
private ChildrenClass[] children;
public ChildrenClass() {
name = "DefaultName";
type = "DefaultType";
}
public ChildrenClass(String aName, String aType) {
name = aName;
type = aType;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setChildren(ChildrenClass[] children) {
this.children = children;
}
public ChildrenClass[] getChildren() {
return children;
}
}
I would like to ask to the stackoverflow reader to please indicate me how to do to read the JSON data in the jsp file in order to populate the dojo tree. In addition, I would like to ask how can I refresh the content of it periodically.
PS: If somebody has a better method to implement something similar to this, I would be glad to receive your comments.
Thanks in advance.
I have found out a way to pass data directly from a JSON result to a dojo.dijit.tree component. Setting the "url" parameter to the action name which returns the json result type.
This is my new body of the .jsp file:
Simple Tree:<br><br>
<div dojoType="dojo.data.ItemFileReadStore" url=getJSONResult handleAs="json" jsid="popStore" />
<div dojoType="dijit.Tree" store="popStore" labelAttr="sname" label="PID 512" />