Remote Datasource and Remote Views + MVVM - mvvm

I am trying to separate my Views and ViewModels in a Kendo Mobile app (ie. not MVC). I have a remote datasource in a ViewModel and cannot get it to work - I am sure it is something simple (I can't find a Kendo example that uses a Remote DataSource in a ViewModel - it is all inline. (http://demos.telerik.com/kendo-ui/web/mvvm/remote-binding.html, http://docs.telerik.com/kendo-ui/getting-started/framework/datasource/overview)
It just shows this "function (e){var n=this;return e===t?n._data:(n._data=this._observe(e),n._ranges=[],n._addRange(n._data),n._total=n._data.length,n._process(n._data),t)}" and not the actual data.
games.html View
<div id="tabstrip-home"
data-role="view"
data-title="Games"
data-model="app.gamesService.viewModel">
<ul class="games-list"
data-bind="source: gamesDataSource"
data-template="template">
</ul>
</div>
<script type="text/x-kendo-template" id="template">
<div class="product">
<h3>#:ProductName#</h3>
<p>#:kendo.toString(UnitPrice, "c")#</p>
</div>
</script>
games.js ViewModel
(function (global) {
    var GamesViewModel, app = global.app = global.app || {};
 
    GamesViewModel = kendo.data.ObservableObject.extend({
                                                            gamesDataSource: new kendo.data.DataSource({
                                                                                                           transport: {
                                                                    read: {
                                                                                                                   url: "http://demos.telerik.com/kendo-ui/service/Products",
                                                                                                                   dataType: "jsonp"
                                                                                                               }
                                                                }
                                                                                                       })
                                                             
                                                        });
    app.gamesService = {
        viewModel: new GamesViewModel()
    };
})(window);

I found an example and managed to get this working, although the javascript is a little different. I'll have to read up on
(function (global) {
var GamesViewModel,
app = global.app = global.app || {};
GamesViewModel = kendo.data.ObservableObject.extend({
gamesDataSource: null,
init: function () {
var that = this,
dataSource;
kendo.data.ObservableObject.fn.init.apply(that, []);
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "http://demos.telerik.com/kendo-ui/service/Products",
dataType: "jsonp"
//ProductID":1,"ProductName":"Chai","UnitPrice":18,"UnitsInStock":39,"Discontinued":false
}
}
});
that.set("gamesDataSource", dataSource);
}
});
app.gamesService = {
viewModel: new GamesViewModel()
};
})(window);

Related

Using Protractor: Switch to iframe using browser.switchTo().frame

So I have already written the testing script which:
1) Logs into the application framework, then
2) Clicks menu to launch the app which I am testing ("MyAwesomeApp.html" for this post)
And my main problem is: In navpanel-spec.js below, I want to target the https://server/apps/Default.aspx?r=1 URL, then click within the iframe where MyAwesomeApp is running.
**** ERROR Trying to switch to the iframe this way, but it does NOT work:
browser.switchTo().frame(element(by.id('1')).getWebElement());
Error in cmd prompt:
Started
[15:43:29] E/launcher - No element found using locator: By(css selector, *[id="\31 "])
...
sat-navpanel-spec.js:52:24)
So there are two URLs going on here:
1) https://server/apps/Default.aspx?r=1 (the main app framework with menu system in top nav).
2) https://server/apps/MyAwesomeApp.html (the web app which the test script launches within the <iframe> tag.
The html looks like this, where the application renders within the <iframe> :
<body>
<div id="top">
<!-- top nav menu systems rendered here -->
</div>
<div id="middle">
<div id="m1">
<div id="m2" class="hidden">
<div id="m3">
<div id="right" class="hidden">
<div>
<div id="frame_holder" style="height: 940px;">
<iframe style="width: 100%; height: 100%;" name="1" id="1" src="https://server/apps/MyAwesomeApp.html">
</iframe>
</div>
</div>
</div>
</div>
<div id="left" style="display: none;"></div>
</div>
</div>
</div>
</body>
In my Protractor.config.js file I have a few specs :
specs: [
'spec/login.js',
'spec/launch-awesome-app.js',
'spec/navpanel-spec.js',
'spec/another-spec.js',
'spec/yet-another-spec.js'
]
login.js and launch-awesome-app.js work fine. They log into the menu system, then click thru the menus in order to launch myAwesomeapp - no problem.
MY PROBLEM:
In navpanel-spec.js I want to target the https://server/apps/Default.aspx?r=1 URL, then click within the iframe where MyAwesomeApp is running.
However, it is NOT selecting any of my elements.
If I target https://server/apps/MyAwesomeApp.html in navpanel-spec.js, of course it launches a new browser window and runs the test just fine.
Here's my navpanel-spec.js test spec:
describe('Testing My Awesome App', function () {
var panelObj = new PanelObjects();
var urlDefault = 'https://server/apps/Default.aspx?r=1';
var urlApp = 'https://server/apps/MyAwesomeApp.html';
browser.get(urlApp); // Runs my AwesomeApp tests okay, HOWEVER it launches a new browser window.
browser.get(urlDefault); // Launches app framework with top nav menus and embedded <iframe>,
// HOWEVER I cannot select iframe and successfully run tests here.
beforeEach(function () {
browser.sleep(5000);
browser.waitForAngular();
});
// USE-CASE OBJECT !!
var items = browser.params.useCaseJsonFile["navigatePanels"];
browser.getAllWindowHandles().then(function (handles) {
handles.map(function (win, idx) {
browser.driver.getCurrentUrl().then(function (curr) {
if (curr.indexOf('Default.aspx') >= 0) {
browser.driver.switchTo().window(handles[idx]);
}
});
});
});
browser.switchTo().frame(element(by.id('1')).getWebElement());
var testId = element(by.id('middle'));
console.log(testId);
items.map(function (item) {
if (item.enableTest) {
var specItem = it(item.name, function () {
console.log('------------------------------');
console.log('---- ' + item.describe);
browser.waitForAngular();
// select panels, etc..
panelObj.panelClick(item.panelName).then(function () {
// ...
});
panelObj.getPanelText(item.panelName).then(function (title) {
expect(title).toContain(item.panelTitle);
});
});
}
});
});
UPDATE
var LoginObjects = require('../pageObjects/login-objects.js');
describe('Testing My Awesome App', function () {
var panelObj = new PanelObjects();
var loginObj = new LoginObjects();
//var urlDefault = 'https://server/apps/Default.aspx?r=1';
//browser.get(urlApp); // Runs my AwesomeApp tests okay, HOWEVER it launches a new browser window.
browser.ignoreSynchronization = true;
// LOGIN AND LAUNCH APP !!!
loginObj.Login();
loginObj.Launch();
beforeEach(function () {
browser.sleep(5000);
browser.waitForAngular();
});
// USE-CASE OBJECT !!
var items = browser.params.useCaseJsonFile["navigatePanels"];
// SWITCH TO iframe ELEMENT
loginObj.switchWindowAndFrame();
items.map(function (item) {
if (item.enableTest) {
var specItem = it(item.name, function () {
console.log('------------------------------');
console.log('---- ' + item.describe);
browser.waitForAngular();
// select panels, etc..
panelObj.panelClick(item.panelName).then(function () {
// ...
});
panelObj.getPanelText(item.panelName).then(function (title) {
expect(title).toContain(item.panelTitle);
});
});
}
});
});
and my page objects :
module.exports = function(){
this.Login = function(){
var url = browser.params.loginUrl;
browser.driver.get(url);
browser.sleep(200);
var userName = browser.params.credential.userId;
var password = browser.params.credential.password;
element(by.id('username')).clear().then(function(){
element(by.id('username')).sendKeys(userName);
element(by.id('password')).sendKeys(password);
});
browser.sleep(1000);
var that = this;
var submitElement = element(by.id('bthLogin'));
submitElement.click().then(function () {
browser.getAllWindowHandles().then(function (handles) {
// LOGIN MESSAGE WINDOW
browser.driver.getCurrentUrl().then(function(curr){
if (curr.indexOf('LoginMsg.aspx') >= 0){
// Do we really need to close the login successful browser ???
browser.driver.close();
}
});
browser.driver.switchTo().window(handles[1]);
});
});
},
this.Launch = function(){
var sel = '#TheMenu1 > ul > li:first-child';
var elem = element(by.css(sel));
elem.click().then(function(){
browser.sleep(1000);
var elem2 = element(by.cssContainingText('.rmLink', 'The First Menu Item'));
elem2.click();
// Select menu item; sleep before attempting to click().
var subElem = element(by.cssContainingText('.rmLink', 'My Awesome App'));
browser.sleep(1000);
subElem.click();
browser.waitForAngular();
});
},
this.switchWindowAndFrame = function(){
browser.getAllWindowHandles().then(function (handles) {
handles.map(function(win, idx){
browser.driver.getCurrentUrl().then(function(curr){
if (curr.indexOf('Default.aspx') >= 0){
browser.driver.switchTo().window(handles[idx]);
}
});
});
});
browser.switchTo().frame(element(by.css('[name="1"]')).getWebElement());
}
};
As mentioned in the comments above, protractor has a bug which prefixes '\3' to your id element with number.
The temporary way is to change you locator. :P

AngularJS ignores form submit

I'm using AngularJS v1.2.13 to create a page with a form which will download a user's file on click.
I'm using $sce to enable the injection of the file URL which works fine.
However, the loading of the resource disables the form submit. I'm sure it has to do with the resource load because when I remove the load and hardcode the url it works fine. I've also created a JSFiddle without it and have not been able to reproduce the problem there.
Any ideas on why this is happening and how it can be fixed?
HTML:
<div ng-controller="viewProfileController" data-ng-init="findOne();">
<form method="get" action="{{downloadFileURL}}">
<button type="submit" class="no-button comment-small" >
Download File
</button>
</form>
</div>
Controller:
'use strict';
angular.module('bop.viewProfile').controller('viewProfileController', [
'$scope', 'Users', '$sce', '$routeParams',
function($scope, Users, $sce, $routeParams) {
$scope.downloadFileURL = '';
// Find current user
$scope.findOne = function() {
Users.get({
userId: $routeParams.userId
}, function(user) {
$scope.user = user;
$scope.downloadFileURL = $sce.trustAsResourceUrl($scope.user.file.url);
});
};
}]);
Users Service:
var userServices = angular.module('bop.users', ['ngResource']);
userServices.factory('Users', ['$resource', function($resource) {
return $resource(
'users/:userId',
{ userId: '#_id' },
{ update: { method: 'PUT' } }
);
}]);

jsTree - cannot create new node - all other functions work well

Deselect and hover funcntions work fina but create/delete/rename don't.
What do is do wrong?
info.json contains 5 nodes marked from 1 to 5.
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<link rel="stylesheet" href="jstree\dist\themes\default\style.min.css" />
<script src="jstree\dist\jstree.js"></script>
<script>
$(function() {
$('#test_tree').jstree({
'core' : {
'data' : {
'url' : 'info.json',
'data' : function (node) {
return { 'id' : node.id };
}
}
}
});
});
</script>
</head>
<body>
<div id="container" >
<div id="nav_bar">
<button id="create" onclick = "demo_create()">Create</button>
</div>
<div id="test_tree"></div
</div>
<script>
function demo_create() {
$.jstree.reference('#test_tree').hover_node('ajson5');
$.jstree.reference('#test_tree').deselect_node('ajson1');
$.jstree.reference('#test_tree').create_node();
};
</script>
</body>
I used same example from official site but it doesn't work
Thanks for any help.
First, in order for changes to be made to the tree, checkcallback in core config need to be set to true.
$('#test_tree').jstree({
'core' : {
'data' : {
'url' : 'info.json',
'data' : function (node) {
return { 'id' : node.id };
},
check_callback : true
}
}
You need to at least pass the parent.id to the create_node function.
$.jstree.reference('#test_tree').create_node('ajson1');
You could check the API at the jstree website for the full parameter list.
Demo jsTreeView 3.2.1 version
$("#treeView").jstree({ 'core': {
'check_callback': true,
'themes': {
"variant": "large"
},
'data':
[{"id":"1","parent":"#","text":"Parent Node"}]
}
});
You are missing the single quotation mark for the check_callback, after using that it will work. e.g. 'check_callback': true.
Code to create new Node
var ref_treeview = $("#treeView").jstree(true);
sel = ref_treeview.get_selected();
if (!sel.length) {
return false;
}
sel = sel[0];
sel = ref_treeview.create_node(sel, "childNode", "last", CreateNode,true);
Here CreateNode is my Callback function name
you have to send the selected element.
use the following (this is basically the code of the create button in the demo page http://www.jstree.com/demo/):
var tree = $("#test_tree").jstree(true);
var sel = tree.get_selected();
if (!sel.length)
{
return false;
}
sel = sel[0];
sel = tree.create_node(sel);
if (sel)
{
tree.edit(sel);
}
At the time when you create the jstree instance you just need to configure the
'core' setting as shown bellow:
$(function () {
$('#jstree').jstree({
'core':{check_callback : true}
});
You have to set the type of the newly created node like so:
$('#tree').jstree().create_node('#', {'id': 'blah', 'text': 'new node', 'type': 'folder'}, 'last', function() {
console.log('done');
});
jstree documentation should be improved.
using code from the other answers, I was able to make the following work:
Please note, this actually works. I am using it to create menus for an external ajax API.
function makeNode(menunode, menuname){
var inst = $.jstree.reference("#treemenu"); //get menu instance
var obj = inst.get_node(menunode);
inst.create_node(obj, menuname); //creates nodes. use "#" to make root nodes
inst.open_node(obj); // open the node (unfold)
});
usage:
//create menu instance and allow tree changes
$('#treemenu').jstree({'core' : {'check_callback': true}});
makeNode("#", "main menu"); //makes root node
makeNode("#j1_1", "submenu in main menu"); //makes sub node
this is assuming that you have a div with id="treemenu" thusly
<div id="treemenu"></div>

KendoUI: Unable to bind data to HTML elements from JSON file.

I am new to kendo ui and mvvm, and I'm facing this issue:
I'm having a JSON file in the follow format:
[
{
"Id":1,
"img":"shoes.png"},
{"Id":2,
"img":"books.png"}
}
]
I am reading the file using the sample mentioned online by kendo guys as follows:
var crudServiceBaseUrl = "pro.json";
var viewModel = kendo.observable({
productsSource: new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl,
dataType: "json"
},
update: {
url: crudServiceBaseUrl,
dataType: "json"
},
destroy: {
url: crudServiceBaseUrl,
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
return options;
}
},
batch: true,
schema: {
model: {
id: "Id"
}
}
})
});
kendo.bind($("#form-container"), viewModel);
I am able to bind the data from the data source to a Kendo Control such as a dropdownlist or some other Kendo Control. But when I try binding the data to an HTML Control (mostly an img tag). It stops working and gives an error saying "this.parent" is not a function.
following is the HTML which works:
Select Product: <select data-role="dropdownlist" data-value-field="Id" data-text-field="img"
data-bind="source: productsSource"></select>
However binding to a normal <img> tag does not work. In short I need to bind images based on src value to a div using kendo ui mvvm.
Kindly help me out. Thanks!!
-
Hardik
Currently Kendo MVVM cannot bind a data source to an HTML element. Only Kendo UI widgets can be bound to a kendo.data.DataSource. Using a widget e.g. the ListView would work for a DIV:
<div data-role="listview"
data-template="template"
data-bind="source: productsSource">
</div>
<script id="template" type="text/x-kendo-template">
<img data-bind="attr: { src: img }" />
</script>

How to export kendoui dataviz chart to (.png) or (.jpg) image format by poping up Save-As window?

I am using kendoui dataviz charts, and I need to export those charts into (.png) or (.jpg) image format.
Basically kendoui dataviz chart has a built-in method called 'svg()'.
'svg()' Returns the SVG representation of the current chart. The returned string is a self-contained SVG document.
Example
var chart = $("#chart").data("kendoChart");
var svgText = chart.svg();
Now svgText contains details of chart image..can anybody tell me how to convert these data to actual image format and pop up a Save As prompt ???
code example: I tried this, but it doesn't prompt any 'SaveAs' popup
<div id="example" class="k-content">
<div class="chart-wrapper">
<div id="chart"></div>
<center>
<div>
<input type="button" value="click" onclick="disp();" />
</div>
</center>
<div>
<canvas id="canvas"></canvas>
</div>
</div>
</div>
<script type="text/javascript">
function disp() {
var chart = $("#chart").data("kendoChart");
var svgText = chart.svg();
var c = document.getElementById('canvas');
canvg(c,svgText);
var img = c.toDataURL("image/png");
document.write('<img src="' + img + '"/>');
window.win = open(imgOrURL);
setTimeout('win.document.execCommand("SaveAs")', 100);
}
function createChart() {
$("#chart").kendoChart({
theme: $(document).data("kendoSkin") || "default",
title: {
text: "Internet Users"
},
legend: {
position: "bottom"
},
chartArea: {
background: ""
},
seriesDefaults: {
type: "bar"
},
series: [{
name: "World",
data: [15.7, 16.7, 20, 23.5, 26.6]
}, {
name: "United States",
data: [67.96, 68.93, 75, 74, 78]
}],
valueAxis: {
labels: {
format: "{0}%"
}
},
categoryAxis: {
categories: [2005, 2006, 2007, 2008, 2009]
},
tooltip: {
visible: true,
format: "{0}%"
}
});
}
$(document).ready(function () {
setTimeout(function () {
createChart();
},100);
$(document).bind("kendo:skinChange", function (e) {
createChart();
});
});
<script>
UPDATE 2
The Chart now includes various export options - PNG, SVG and a vector PDF. See the Export demo for reference.
UPDATE
The Chart now has built-in method for obtaining the exported image (base64 encoded):
var img = chart.imageDataURL();
I'm not aware of a cross-browser way to display a "Save As" dialog.
See also: API Reference
Original response follows:
Exporting the Chart image in-browser is not possible. We have prepared a demo that shows how to convert the SVG document to PNG/PDF on the server using Inkscape.
The demo application is implemented in ASP.NET MVC, but does not depend on any of its features and can be ported to other frameworks.
You can find the demo on GitHub:
https://github.com/telerik/kendo-examples-asp-net/tree/master/chart-inkscape-export
U can do like this.
For this approach u need svg.dll
U can download from this link.
http://svg.codeplex.com/releases/view/18884
Javascript:
var chart = $("#chart").data("kendoChart");
var svgString = escape(chart.svg());
$.ajax({
url: "/MyController/Sample",
data: { svg: svgString },
async: false,
type: 'Post',
success: function (data) {
window.location = "/MyController/getPdf";
}
});
Controller:
[HttpPost]
[ValidateInput(false)]
public void Sample(string svg)
{
var svgText = System.Web.HttpUtility.UrlDecode(svg);
Session["chrtData"] = svgText;
}
public void getPdf()
{
string svgText = Session["chrtData"].ToString();
var byteArray = Encoding.ASCII.GetBytes(svgText);
using (var stream = new MemoryStream(byteArray))
{
var svgDocument = Svg.SvgDocument.Open(stream);
//First Way
var bitmap = svgDocument.Draw();
MemoryStream docMemStream = new MemoryStream();
bitmap.Save("D:\\hi.png", System.Drawing.Imaging.ImageFormat.Png);
}
}