Flex xml in tree - actionscript-3

The following xml values is getting from php file
<result>
<list>
<node>air</node>
<node>flex</node>
<node>android</node>
</list>
</result>
i am calling this xml using httpservice
<mx:HTTPService
id="project"
url="http://localhost/eshpm/AIR/newproject.php"
method="POST" result="onResult_projectname(event)" resultFormat="e4x">
<mx:request xmlns="">
<name>yes</name>
</mx:request>
</mx:HTTPService>
The result is obtained using the function
private function onResult_projectname(evt:ResultEvent):void
{
xmldata = new XML(evt.result);
xmlList_user = new XMLListCollection(xmldata.list);
tree.dataProvider = xmlList_user.children();
}
The problem is that i am able to display the values in Tree.......but it is repeating
ie, "air" is comming in tree twice....
plz help.............thanks

Try using <mx:Tree dataProvider="{project.lastResult.result}" labelField="node"/>. By invoking project.send() databinding works and populates your Tree.

Related

How to pass Arrays from backing bean to JavaScript to draw a chart using Chart.js in an Ajax call

I am using prime faces backing bean and Chart.js to draw a chart
I am selecting a row in the data table . On selection of row updating the Canvas which has the Chart in it. I am getting the values on Selection method and building two arrays one for X axis and another for y-axis. How can i pass these arrays to JavaScript to render the chart . I tried Prime faces JSON array to pass to JavaScript. I could not get the values in JavaScrip.
Here is my sample code .xhtml code
<p:dataTable id="myTbl" var="cars" value="#{bean.value}" rowKey="#{bean.carId}" selection="#{bean.selectedCar}" selectionMode="single" reflow="true" >
<p:ajax event="rowSelect" listener="#{bean.onRowSelect}" update=":chartForm" oncomplete="drawChart();" />
</p:dataTable>
<div class= "chart-container" >
<h:outputText id="outputid" value="#{bean.carId}" />
<canvas id="myChart" ></canvas>
</div>
function drawChart(){
var carId = '#{bean.carId}';
alert (carId)
I am selecting a row from the above table. On selection I want to capture the id of the line , get data and display the chart.js chart on same page
here is my bean class
In Bean Class
private String carId;
setter and getter methods
public void onRowSelect(SelectEvent event) {
Cars car= (Cars) event.getObject();
this.carId = car.Id ;
}
I got values into Primefaces JSON Array and passing into JavaScript .In JavaScript I am doing JSON.parse . Initially I got serialization error , so changed the bean to request scoped
The problem is I am not getting any values into JavaScript
I removed JSON Array and and just passing a String
I can get the bean.property on xhtml page as mentioned in my code but not able to get into JavaScript
Am i missing something
you can try to use jsf expression language in javascript code
For example:
//<![CDATA[
var jsVar = #{managedBean.property}
//]]>
Well, if you are concerned with the calling (and passing values) of JS function from bean, then you can call execute of RequestContext.getCurrentInstance() to directly invoke your scripting method from the bean, as following:
RequestContext.getCurrentInstance().execute("yourJSFunction('" + param1 + "');");
However, I think you will still be missing a trick of converting your JSONArray back to JSON object in JS, which you can do as following:
When passed from bean:
function yourJSFunction(coordinatesArray) {
coordinatesArray = JSON.parse(coordinatesArray);
}
Or when using as a bean property:
var coordinatesArr = JSON.parse('#{yourBean.strProperty}');

How do you access the Package Variables Collection in biml?

I'm just getting started with biml and bimlscript. I can see the power it holds, but so far digging through the language and API reference has been frustrating. I can't seem to find any reference online to access the package's variable collection.
I'm trying to set up this script so I can add more variables into my Variables section, and then automatically add those variables to a script task later in the process.
Here is the minimal code for my problem:
<Biml xmlns="http://schemas.varigence.com/biml.xsd" >
<Packages>
<Package Name="Load">
<Variables>
<Variable Name="ETLProcessStepID" DataType="Int32">0</Variable>
<Variable Name="TenantID" DataType="Int32">1</Variable>
</Variables>
<!-- more stuff going on in the biml -->
<# var package = RootNode.Packages.Where(loadPackage => loadPackage.Name.Contains("Load"));
foreach (var variable in package.Variables) { #>
<ReadWriteVariables VariableName="<#=variable.Name#>" />
<# }#>
</Package>
</Packages>
</Biml>
This seems to be the closest I've gotten. Unfortunately It results in:
Error 0 'System.Collections.Generic.IEnumerable<Varigence.Languages.Biml.Task.AstPackageNode>' does not contain a definition for 'Variables' and no extension method 'Variables' accepting a first argument of type 'System.Collections.Generic.IEnumerable<Varigence.Languages.Biml.Task.AstPackageNode>' could be found (are you missing a using directive or an assembly reference?).
If I'm reading the documentation right, there is a Variables collection in the Packages node. https://varigence.com/Documentation/Api/Type/AstPackageNode
If I'm not reading the documentation right, can anyone direct me to a reference on how I could access the package variables collection?
The first error you're running into is that your C# variable called package is going to return a collection from that Linq call. Since there should only be one element that matches it, we'll use First to just give us one of these things
var package = RootNode.Packages.Where(loadPackage => loadPackage.Name.Contains("Load")).First();
Now the tricky part and I'll actually have to check with some bigger guns on this, but I don't think you'd be able to access the current package's variable collection like that because it's not built yet. Well, at least using BIDS Helper/BimlExpress. The Biml first needs to get compiled into objects because, assuming a single select, you won't have anything in the RootNode.Packages collection. You certainly wouldn't have "Load" because you're compiling it right now.
In Mist, the paid for solution which is soon to be rebranded as BimlStudio, you could use a Transformer to accomplish this. You'd build out the Load package first and then a transformer fires off just prior to emission as a dtsx package and does whatever correction you were trying.
Consider the following test harness. It creates a simple package and then has some bimlscript immediately after it wherein I enumerate though all the packages and then for each package, I enumerate the root level Variables collection. You'll only see the "Test" message rendered. The inner calls won't fire because nothing exists yet.
<Biml xmlns="http://schemas.varigence.com/biml.xsd">
<Packages>
<Package Name="so_38908470" >
<Variables>
<Variable Name="ETLProcessStepID" DataType="Int32">0</Variable>
<Variable Name="TenantID" DataType="Int32">1</Variable>
</Variables>
<#
string message = "<!-- {0} -->";
WriteLine(message, "test");
foreach (var package in RootNode.Packages)
{
WriteLine(message, package.Name);
foreach(var variable in package.Variables)
{
WriteLine(message, variable.Name);
}
}
#>
</Package>
</Packages>
</Biml>
The more I think about this, Tiering might be able to accomplish this with BIDS Helper/BimlExpress. Since it looks like you're trying to use the Variables defined within a package as inputs to a Script Task or Component, as long as you're using ScriptProjects type things which are parallel to a Packages collection, this might work.
Eureka
Add two Biml files to your project: Load.biml and Script.Biml. Use the following code in each. Select both and right click to generate SSIS package.
Load.biml
This is going to be your package. It is the package you started up above with a Script Task in there that is going to dump the name and value of all the user variables declared at the root of the package. But as you see, there isn't anything in the ScriptTask tag that specifies what variables or what the code is going to do.
<Biml xmlns="http://schemas.varigence.com/biml.xsd" >
<Packages>
<Package Name="Load">
<Variables>
<Variable Name="ETLProcessStepID" DataType="Int32">0</Variable>
<Variable Name="TenantID" DataType="Int32">1</Variable>
</Variables>
<Tasks>
<Script ProjectCoreName="ST_EchoBack" Name="SCR Echo Back">
<ScriptTaskProjectReference ScriptTaskProjectName="ST_EchoBack" />
</Script>
</Tasks>
</Package>
</Packages>
</Biml>
Script.biml
This biml looks like a lot but it's the same concepts as I was working with above where I enumerate though the packages collection and then work with the Variables collection. I use the biml nuggets to control the emission of the Namespace, Name and DataType properties.
<## template language="C#" tier="1" #>
<Biml xmlns="http://schemas.varigence.com/biml.xsd" >
<ScriptProjects>
<ScriptTaskProject ProjectCoreName="ST_EchoBack" Name="ST_EchoBack" VstaMajorVersion="0">
<ReadOnlyVariables>
<!-- List all the variables you are interested in tracking -->
<#
string message = "<!-- {0} -->";
WriteLine(message, "test");
// ValidationReporter.Report(Severity.Error, "test");
foreach (var package in RootNode.Packages.Where(x=> x.Name == "Load"))
{
WriteLine(message, package.Name);
// ValidationReporter.Report(Severity.Error, package.Name);
foreach(var variable in package.Variables)
{
WriteLine(message, variable.Name);
// ValidationReporter.Report(Severity.Error, variable.Name);
#>
<Variable Namespace="<#=variable.Namespace#>" VariableName="<#=variable.Name#>" DataType="<#=variable.DataType#>" />
<#
}
}
#>
</ReadOnlyVariables>
<Files>
<File Path="ScriptMain.cs" BuildAction="Compile">using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
namespace ST_EchoBack
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public void Main()
{
bool fireAgain = false;
string message = "{0}::{1} : {2}";
foreach (var item in Dts.Variables)
{
Dts.Events.FireInformation(0, "SCR Echo Back", string.Format(message, item.Namespace, item.Name, item.Value), string.Empty, 0, ref fireAgain);
}
Dts.TaskResult = (int)ScriptResults.Success;
}
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
}
} </File>
<File Path="Properties\AssemblyInfo.cs" BuildAction="Compile">
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyVersion("1.0.*")]
</File>
</Files>
<AssemblyReferences>
<AssemblyReference AssemblyPath="System" />
<AssemblyReference AssemblyPath="System.Data" />
<AssemblyReference AssemblyPath="System.Windows.Forms" />
<AssemblyReference AssemblyPath="System.Xml" />
<AssemblyReference AssemblyPath="Microsoft.SqlServer.ManagedDTS.dll" />
<AssemblyReference AssemblyPath="Microsoft.SqlServer.ScriptTask.dll" />
</AssemblyReferences>
</ScriptTaskProject>
</ScriptProjects>
</Biml>
I thought I could simplify call GetBiml() the variable variable but that is going to emit the exact biml it was defined with
<Variable Name="ETLProcessStepID" DataType="Int32">0</Variable>
<Variable Name="TenantID" DataType="Int32">1</Variable>
and if that didn't have the actual value in there, it'd be legit syntax for the ReadOnly/ReadWrite variables collection. Que lástima.
Biml Script Component Source
Biml Test for echo aka Script Task

How to support JSONP with Spring MVC and multiple response types

I have a method in a controller that will return HTML or JSON depending on which was asked for. Here's a stripped-down example of such a method, modeled after information on how to do this that I found in this question:
#RequestMapping(value="callback")
public ModelAndView callback(#RequestParam("c") String c) {
Map response = new HashMap<String, String>();
response.put("foo", "bar");
return new ModelAndView("fake", "data", new JSONPObject(c, response));
}
I put the JSONPObject into the model because I have to in order to be able to reach it from the view that renders if HTML was requested. But this poses a problem when I'm rendering JSON with a callback:
curl 'http://localhost:8080/notes/callback.json?c=call'
{"data"call(:{"foo":"bar"})}
As you can see, because I put my data in the "data" slot in the model, when the model is rendered as JSON there's that extra wrapping. What I'm looking for is the rendered JSON (technically JSONP) to look like this:
call({"data":{"foo":"bar"}})
Can anyone see a way to get where I'm trying to go without breaking the ability to return a view that accesses the JSONPObject during rendering?
This is how I'm using JSONP with Spring MVC, just modify it according to your needs:
on Server Side:
#RequestMapping(value="/notes/callback.json", method=RequestMethod.GET)
public void jsonpCallback(#RequestParam("callback") String callback, HttpServletResponse response) {
response.setContentType("text/javascript; charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(callback + "(" + jsonDataString + ")");
}
On client side:
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
function yourfunction() {
jQuery.getJSON("http://localhost:8080/notes/callback.json?callback=?",
function(data) {
alert(data.someParam);
});
}
</script>
I figured this out. When rendering JSON, Spring is using a MappingJacksonJsonView per my configuration. That view has a property that tells it to find the single item in the map and extract it before rendering. After setting that property, this now works.
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" >
<property name="extractValueFromSingleKeyModel" value="true" />
</bean>
</list>
</property>

Struts2 JSON Plugin with Hibernate

So I'm trying to create a JSON object from a List of AcaClasses.
Action Class:
public class StudentJSONAction extends ActionSupport{
//Your result List
private List<AcaClass> gridModel;
public String getJSON() {
return execute();
}
public String execute() {
//Get the first student from the Factory and get their AcaClasses
gridModel = StudentFactory.getAll().get(0).getAcaClasses();
return SUCCESS;
}
//Getters and Setters
The StudentFactory is my interface to the hibernate database.
Struts.xml
<action name="getJSON" class="StudentJSONAction">
<result type="json">
<param name="enableSMD">true</param>
<param name="ignoreInterfaces">false</param>
</result>
</action>
When I call the getJSON action, all I get is:
{"methods":[],"objectName":null,"serviceType":"JSON-RPC","serviceUrl":"\/FlowridersSP\/getJSON","version":".1"}
This problem is very similar to mine but I would like to see if there is a solution using the Struts2 JSON Plugin
Question: Why am I not getting back a list of AcaClasses in JSON form?
My end goal is to plug in this JSON in the JQuery Grid Plugin
I am not familiar with JSON plugin, but are you correctly configuring the plugin to serialize the gridModel? A quick look at the plugin documentation suggests that you might want to set the root parameter also:
<action name="getJSON" class="StudentJSONAction">
<result type="json">
<param name="enableSMD">true</param>
<param name="ignoreInterfaces">false</param>
<param name="root">gridModel</param>
</result>
</action>
Also, try to identify if the problem is with StudentFactory or with the JSON serialization. You can set up gridModel with a list of dummy AcaClass objects and see if the serialization works correctly. Also, as suggested by #Quaternion, you can log the list of AcaClass objects loaded by StudentFactory and verify that it is loading the expected instances.

How to export XML using a SQL Server query?

Let's say I have a table Employee like this
EmpID, EmpName
1 , hatem
and I write a query: select * from Employee for xml auto
so the output will be in XML format.
I want to know how can I export the result to a XML file to be saved on my computer's drive as I need to read the XML files from this folder and deserialize them in my .net application.
If you only need to store the XML and not do anything else to it, this is probably the easiest way to accomplish this - using straight simple ADO.NET:
string query = "SELECT EmployeeID, LastName, FirstName, Title, BirthDate, HireDate FROM dbo.Employees FOR XML AUTO";
using(SqlConnection _con = new SqlConnection("server=(local);database=Northwind;integrated security=SSPI;"))
using (SqlCommand _cmd = new SqlCommand(query, _con))
{
_con.Open();
string result = _cmd.ExecuteScalar().ToString();
_con.Close();
File.WriteAllText(#"D:\test.xml", result);
}
This will create a file D:\test.xml (or change that to match your system) and will put those XML tags into that file.
The SqlCommand object also has a .ExecuteXmlReader() method which would return an XmlReader object to scan and manipulate the XML - not just return a string. Use whatever makes the most sense to you!
PS: also, the output of FOR XML AUTO is a bit .... let's say ... suboptimal. It uses the dbo.Employee as it's main XML tag and so forth... with SQL Server 2008, I would strongly recommend you look into using FOR XML PATH instead - it allows you to tweak and customize the layout of the XML output.
Compare your original XML output with FOR XML AUTO
<dbo.Employees _x0040_ID="1" LastName="Davolio" FirstName="Nancy" Title="Sales Representative" BirthDate="1948-12-08T00:00:00" HireDate="1992-05-01T00:00:00" />
<dbo.Employees _x0040_ID="2" LastName="Fuller" FirstName="Andrew" Title="Vice President, Sales" BirthDate="1952-02-19T00:00:00" HireDate="1992-08-14T00:00:00" />
against this query - just to see the difference:
SELECT
[EmployeeID] AS '#ID',
[LastName], [FirstName],
[Title],
[BirthDate], [HireDate]
FROM
[dbo].[Employees]
FOR XML PATH('Employee'), ROOT('Employees')
Output is:
<Employees>
<Employee ID="1">
<LastName>Davolio</LastName>
<FirstName>Nancy</FirstName>
<Title>Sales Representative</Title>
<BirthDate>1948-12-08T00:00:00</BirthDate>
<HireDate>1992-05-01T00:00:00</HireDate>
</Employee>
<Employee ID="2">
<LastName>Fuller</LastName>
<FirstName>Andrew</FirstName>
<Title>Vice President, Sales</Title>
<BirthDate>1952-02-19T00:00:00</BirthDate>
<HireDate>1992-08-14T00:00:00</HireDate>
</Employee>
I've had the same problem and I've created a .NET CLR that exports XML to a file:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Text;
using System.Xml;
using System.IO;
public sealed class StringWriterWithEncoding : StringWriter
{
private readonly Encoding encoding;
public StringWriterWithEncoding(Encoding encoding)
{
this.encoding = encoding;
}
public override Encoding Encoding
{
get { return encoding; }
}
}
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void XMLExport (SqlXml InputXml, SqlString OutputFile)
{
try
{
if (!InputXml.IsNull && !OutputFile.IsNull)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(InputXml.Value);
StringWriterWithEncoding sw = new StringWriterWithEncoding(System.Text.Encoding.UTF8);
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
NewLineChars = "\r\n",
NewLineHandling = NewLineHandling.Replace,
Encoding = System.Text.Encoding.UTF8
};
using (XmlWriter writer = XmlWriter.Create(sw, settings))
{
doc.Save(writer);
}
System.IO.File.WriteAllText(OutputFile.ToString(), sw.ToString(), System.Text.Encoding.UTF8);
}
else
{
throw new Exception("Parameters must be set");
}
}
catch
{
throw;
}
}
}
Here's an example how to use it:
DECLARE #x xml
SET #x = '<Test><Something>1</Something><AnotherOne>2</AnotherOne></Test>'
EXEC dbo.XmlExport #x, 'c:\test.xml'
And the output is a nicely formatted XML file:
<?xml version="1.0" encoding="utf-8"?>
<Test>
<Something>1</Something>
<AnotherOne>2</AnotherOne>
</Test>