Multiple service( Controller) in breezejs - javascript

This below code for one controller
var serviceName = 'breeze/todos', // route to the Web Api controller
manager = new breeze.EntityManager(serviceName);
But i have many controller. How can i do this?

The same above code can apply for as much Breeze controllers as you want.
File : Todos-datacontext.js
var serviceName = 'breeze/todos', // route to the Web Api controller
var manager = new breeze.EntityManager(serviceName);
File: Accounts-datacontext.js
var serviceName = 'breeze/accounts', // route to the Web Api controller
var manager = new breeze.EntityManager(serviceName);
etc...

Do not use several controllers! Every EntityManager you create, fetches metadata - makes http request to associated controller Metadata method.
Instead create 1 controller and work only with it
You should use different controllers+EntityManagers only if you have different repositories

Related

Should I use an OData server or a custom XSJS service implemenation?

We are on a SAP HCP. For our application we need to provide a Web API.
We are unsure wheather to use an OData Service or a custom XSJS service implementation for this.
A few things we need to accomplish. All items also need to do a certain user authorization.
Select data from the database
Writing data into the database
Providing API functions that don't perfrom CRUD operations on the database, but for example send data to another server in the background
In my understanding an OData service would only fit the first two items, but does not provide a way to do anything that is not database (CRUD) related. Is this correct?
Are there any best practices for this scenario? Any suggestions and pointings in the right direction are welcome.
XSOData would no be able to perform non CRUD operations. With XSJS you can achieve this. I have done all of the three requirements on an on-premise
system & the same concepts should apply to HCP as well.
Sample code for executing a query & displaying data :
var queryString = "SELECT * FROM Table";
var connection = $.db.getConnection(); // DB Connection
var stmt = connection.prepareStatement(queryString);
var rs = stmt.executeQuery();
var output = "";
while (rs.next()) // Column setting
{
output += ("Col1:"+rs.getString(0)+", Col2:"+rs.getString(1)+";";
}
$.response.setBody(output);
To check for any GET or POST request & request parameters you can use $.request. With these you can perform your CRUD operations
You can refer to the XSJS API Reference for more info
http://help.sap.com/hana/SAP_HANA_XS_JavaScript_API_Reference_en/
For sending data to another server, one way would be by providing a web service from the second server. XSJS can make Web Request to a configured destination so you can POST data to your server. You will need to create a destination file(.xshttpdest) for accessing you server
Some sample Code:
var dest = $.net.http.readDestination("<package path to destination file>", "<destination file name>");
var client = new $.net.http.Client();
var req = new $.web.WebRequest($.net.http.POST, "/");
req.contentType = "application/json";
req.setBody("My data");
client.request(req, dest);
var response = client.getResponse();
You can find details on the below link to create a HTTP Destination & send data https://help.hana.ondemand.com/help/frameset.htm?06ca24043b0f4eb78cf39c6bc1d8a8dc.html

AngularJS how to store client-side only info on a $resource instance

I'm trying to figure out "the right way" to store client-side-only state for an instance of a resource.
Suppose I have an ng-resource, Blerg which has only one data field, "name" and per the docs, I do something like
var blergInstance = new Blerg();
blergInstance.name = "Frankie";
blergInstance.$save();
This results in an http POST to the resource URL with json {name: "Frankie"}. Ok, great.
But I actually need to pass that blergInstance around my client-side application interface for a while, and I want to store some state about that blergInstance to tell the client-side application how to display it or how to interact with it. E.g. I've got a directive that wants to optionally display to the user that "Your blergInstance hasn't been saved yet". Or I've got a button elsewhere that will "Moog this Blerg", and I only want to allow a Blerg to be Mooged once before saving.
My first (admittedly naive) approach would be to do something like
var blergInstance = new Blerg();
blergInstance.name = "Frankie";
blergInstance.saved = false //
blergInstance.hasBeenMooged = false //
// pass the blergInstance around to other services, directives, etc
blergInstance.$save();
But now the http POST looks like {name: "Frankie", saved: false, hasBeenMooged: false}.
So how should I attach "state" to the resource instance that is only relevant to the client-side, and which should not be sent to the server?
Why shouldn't you wrap the resource and state into an simple object and pass around, where resource will have the necessary properties only
var stateful = {};
var blergInstance = new Blerg();
blergInstance.name = "Frankie";
stateful.resource = blergInstance;
stateful.saved = false;
stateful.hasBeenMooged = false;
// pass the blergInstance around to other services, directives, etc
stateful.resource.$save();
Here's an alternative to code-jaff's solution
Warning: coffeescript ahead
Step 1:
Create a service with all your API calls
app.service 'Api', ['$resource', ($resource) ->
{
Blerg: $resource "/api/v1/blerg/:id", {id: "#id"}
....
}
]
Step 2:
Call your Api service and pass in an explicit object
app.controller 'Ctrl', (Api) ->
saveBlerg = {}
saveBlerg.name = Blerg.name
Api.Blerg.save(saveBlerg)

Sharepoint authentication using javascript Rest api or jquery

I am just developing an sharepoint application in mobile by using javascript, But dont know how to start. Is there any api in javascript(jquery) to authenticate in sharepoint and get user details.
Thanks in advance.
For developing web applications in SharePoint 2013 and Online you have 2 main options for querying data from lists, libraries or users details, The Client Object Model and the SharePoint REST API.
Here is an example of updating list data using the Client object model
ClientContext context = new ClientContext("http://SiteUrl");
List announcementsList = context.Web.Lists.GetByTitle("Announcements");
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem newItem = announcementsList.AddItem(itemCreateInfo);
newItem["Title"] = "My New Item!";
newItem["Body"] = "Hello World!";
newItem.Update();
context.ExecuteQuery();
Another option, which is preferred is to use the REST API to query endpoints. There are a number of APIs you can query in SharePoint, the most useful will be the Search API or the Social API, User Profile API, etc...
Here is an example endpoint you could query to retrieve JSON data, you can put it in the browser or post to the url to see what is returned.
http://<siteCollection>/<site>/_api/social.feed/my/feed/post
Here is an example of getting user profile data for the current user in SharePoint
$(document).ready(function(){
// Ensure the SP.UserProfiles.js file is loaded
SP.SOD.executeOrDelayUntilScriptLoaded(loadUserData, 'SP.UserProfiles.js');
});
var userProfileProperties;
function loadUserData(){
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
//Get properties of the current user
userProfileProperties = peopleManager.getMyProperties()
clientContext.load(userProfileProperties);
clientContext.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {
console.log(userProfileProperties.get_displayName());
}
function onFail(sender, args) {
console.log("Error: " + args.get_message());
}

Chrome app - error when call channel.open() using GAE channel javascript API

My server is running on google app engine, my client is a chrome app using angular framework. I'm trying to implement Channel Java API service of GAE.
My problem is when channel.open() was called angular show this error at the console: 'beforeunload is not available in packaged apps.' Below is my code, written in controller:
var channel = new goog.appengine.Channel(token);
console.log("channel");
var socket = channel.open();
console.log("socket");
socket.onopen = function(){
console.log(open);
};
console.log("on open");
socket.onmessage = function(msg){
console.log("Message: "+msg);
}
(Console show "channel" but not "socket")
Create an AngularJS service to hold the list of the chats. This is
not required but it is the recommended way to share an observable
array (which means with two-way data binding) between controllers.
Initiate the Channel API inside that service. Now there's the trick : for the modifications to the observable array to be pushed to the controllers, we need to use the $rootScope method.
Ref - app-engine-channel-api-and-angularjs

Javascript Backbone model design

Fairly new to JavaScript so it might be a noobish question.
At the moment for my project I'm using NodeJS for my server and Backbone for the client. The client will send a request to the server and the server will send list of files in the server, my aim was to simply return the list of files and when user click on the file it will send another request to the server to load the file.
Currently in the client level my model and collection is defined something like:
app.MyFile = Backbone.Model.extend({
defaults: {
modifiedDate: new Date(),
path: '',
content: '' // content of the file
}
});
var MyFileList = Backbone.Collection.extend({
model: app.MyFile,
url: '/api/files'
});
// create global collection of files
app.MyFiles = new MyFileList();
app.AppView = Backbone.View.extend({
initialize: function () {
// fetch all files
app.MyFileList.fetch();
}
});
// app.js (point of entry)
$(function() {
// Kick things off by creating the **App**.
new app.AppView();
});
And my server code:
var application_root = __dirname,
express = require("express"),
...
app.get('/api/files', function(req, res) {
...
// return file list
}
app.get('/api/files/:id', function(req, res) {
...
// return file content?
}
Since it doesn't make sense to load all files in the directory and send it back to the client, what I did was I created the model in the server and fill up modifiedDate and path while leaving content to null. But the problem now is that how do I fill up the content when user clicks on the file? I'm not sure how to manually send an HTTP request from Backbone View or controller. Or is there any better way of doing this? One way that I can think of is to create another model that only keeps modifiedDate and path but to me this looks very verbose and repetitive.
Given what you have on the client side, you may not need anything more.
app.MyFiles = new MyFileList();
app.MyFiles.fetch().done(function() {
// your collection is fetched but each model's content is empty.
// now, I assume at this point you will show them in some view/views.
});
Now when one of those things is clicked on, you can fetch the content.
var model = app.MyFiles.get(id);
model.fetch().done(function() {
// now the model's content attribute will be set
});
This might work with no more code than what you showed. Because the url a model uses to fetch is created by default by appending the model's id to the end of its collection's url.
So from your server, you return a json array from '/api/files': [{id:1, path:'foo'}, {id:2, path:'bar'}]
Then from '/api/files/1': {id:1, path:'foo', content:'whatever'}
When user clicks the file, you can call backbone's fetch method on the model. Then your model will be filled with data from the server.
Note that for this to be working you should return collection from the server first, where models at least have id's. Every other field will be filled after fetch call. Also, you should override model url, if it differs from standard (which is collection/id).

Categories