Using websockets/Server sent events with Angular dart - dart

I was trying to use angular dart with websockets/server sent events and could not find any documentation/examples (there are some for angularJS but that seems very different for such things). A few things I tried also did not work.
Does anyone know how to do this?
Here is one version of what I tried and the error:
#NgController (
selector: "ACdistribution",
publishAs : "dstbn")
class ACDstbnController{
List <WtdPres> distbn;
void updateDstbn(List<WtdPres> newdstbn){
distbn = newdstbn;
}
final dstbnsrc = new EventSource("../dstbns")
..onMessage.listen((event){
List wps = JSON.decode(event.data);
List <WtdPres> newdistbn = wps.map((wp) => new WtdPres.fromJson(wp));
updateDstbn(newdistbn);
});
}
The error I got in pub build was:
web/provingground.dart:55:5:
'updateDstbn' is only available in instance methods.
updateDstbn(newdistbn);
^^^^^^^^^^^

There are limitations on what you can do on initializers for final fields.
Can you try to put this code inside the constructor
var dstbnsrc;
ACDstbnController() {
dstbnsrc = new EventSource("../dstbns")
..onMessage.listen((event){
List wps = JSON.decode(event.data);
List <WtdPres> newdistbn = wps.map((wp) => new WtdPres.fromJson(wp));
updateDstbn(newdistbn);
});
}

Related

Random image from folder

How can I make possible that the app will load all of the images from the specific folder and then put in array and choose one image randomly? When chose one then pass to the fronted to show the image. How to do that too?
I am C# developer but not long time ago I found ElectronJS and this framework does everything easier so therefore I am moving to this framework.
I did in C# programming this way:
// basic settings.
var ext = new List<string> { ".jpg", ".gif", ".png" };
// we use same directory where program is.
string targetDirectory = Directory.GetCurrentDirectory() + "\\assets\\" + "images\\" + "animals\\";
// Here we create our list of files
// New list
// Use GetFiles to getfilenames
// Filter unwanted stuff away (like our program)
if (Directory.Exists(targetDirectory))
{
Files = new List<string>
(Directory.GetFiles(targetDirectory, "*.*", SearchOption.TopDirectoryOnly)
.Where(s => ext.Any(es => s.EndsWith(es))));
// Show first picture so we dont need wait 3 secs.
ChangePicture();
}
else
{
panel5.BackgroundImage = new Bitmap(Resources.doggy);
}
I don't know how to do in ElectronJS.
Thank you in advance the answers.
Alright. I found the solution.
However I don't understand the people who are giving negative reputation for the opened question. If they are giving negative reputation then they could explain why.
Well anyway, I did fix this issue with this way:
I created images.js file and added this:
var fs = require('fs');
function getRandImage() {
var files = fs.readdirSync('./assets/images/animals/')
/* now files is an Array of the name of the files in the folder and you can pick a random name inside of that array */
let chosenFile = files[Math.floor(Math.random() * files.length)]
console.log('../assets/images/animals/' + chosenFile);
return '../assets/images/animals/' + chosenFile;
}
module.exports = { getRandImage }
I used console to see if the value is correct, otherwise others can delete that part.
Sending the data to the renderer process:
const { getRandImage } = require('./images');
child.webContents.send('random-image', getRandImage());
I did put in the preload.js file the following (I used the starter pack electronjs github to start with something):
var { ipcRenderer } = require('electron');
ipcRenderer.on('random-image', function (event, store) {
document.getElementById("randompic").src = store;
console.log(store);
});
Same here, I did use console.log just for test the value is correct and I used to change the randompic ID related image src html to the randomly chosen image.
Hopefully I did helping those people who are newbie as me.

Unable to move jira support ticket to Done status using Rest Client

I am using Java rest client with following maven dependency:
<dependency>
<groupId>com.atlassian.jira</groupId>
<artifactId>jira-rest-java-client-app</artifactId>
<version>5.2.0</version>
</dependency>
And the following code:
void markDuplicateAndClose(IssueRestClient client, ...) {
...
Iterable<Transition> transitions = client.getTransitions(duplicateIssue.getTransitionsUri()).claim();
Transition doneTransition = getTransitionByName(transitions, "Done");
String requiredFieldId = null;
for (Field f : doneTransition.getFields()) {
if (f.isRequired())
requiredFieldId = f.getId();
};
Collection<FieldInput> fieldInputs = Arrays.asList(new FieldInput(requiredFieldId, "Duplicate"));
TransitionInput ti = new TransitionInput(doneTransition.getId(), fieldInputs);
promise = client.transition(keyToIssuesMap.get(duplicate), ti).claim();
...
}
private Transition getTransitionByName(Iterable<Transition> transitions, String stateName) {
for (Transition t: transitions) {
if (t.getName().equals(stateName))
return t;
}
return null;
}
However, I get the following error:
Exception in thread "main" RestClientException{statusCode=Optional.of(400), errorCollections=[ErrorCollection{status=400, errors={customfield_10212=Could not find valid 'id' or 'value' in the Parent Option object.}, errorMessages=[]}]}
at com.atlassian.jira.rest.client.internal.async.DelegatingPromise.claim(DelegatingPromise.java:45)
at com.xyz.jira_accessor.jira.Util.markDuplicates(Util.java:109)
at com.xyz.jira_accessor.jira.Util.main(Util.java:132)
Caused by: RestClientException{statusCode=Optional.of(400), errorCollections=[ErrorCollection{status=400, errors={customfield_10212=Could not find valid 'id' or 'value' in the Parent Option object.}, errorMessages=[]}]}
at com.atlassian.jira.rest.client.internal.async.AbstractAsynchronousRestClient$2.apply(AbstractAsynchronousRestClient.java:176)
What is wrong with my code?
As discussed in below comments, I tried to see the underlying codes for the option:
Option shown as compulsory on the UI
HTML from Chrome Debugger for the same:
And so I changed the above code to:
Collection<FieldInput> fieldInputs = Arrays.asList(new FieldInput("customfield_11607", "12091"));
TransitionInput ti = new TransitionInput(doneTransition.getId(), fieldInputs);
promise = client.transition(keyToIssuesMap.get(duplicate), ti).claim();
But it still did not work.
Just that the error message changed to:
errors={customfield_11607=Could not find valid 'id' or 'value' in the Parent Option object.}
(To Jira Team) Can you make the error messages bit more meaningful and simplify the API please? It is very hard to figure out things. Or at least, provide some more examples which are easily searchable on the Internet.

passing parameters to power bi filter programmatically from asp.net MVC

I have developed a powerBI report and deployed the same in Workspace.
From PowerBI interface I viewed the report and am able to add filter like this:
filter=tablename~2Fcolumnname eq 4
The condition is working fine from the interface. But, when I add filter condition in the code of my asp.ner MVC application, filter does not work.
The condition is working fine from the interface.
But, when I add filter condition in the code of my asp.ner MVC application, filter does not work.
My sample code:
var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials);
var reports = await client.Reports.GetReportsInGroupAsync(WorkspaceId);
report = reports.Value.FirstOrDefault(r => r.Id == "aa07v254-8t46-2387-4k53-2725y90n3456");
report.EmbedUrl = report.EmbedUrl + "?filter=tablename/columnname%20eq%204";
Please help me diagnose, why the filter is not working.
You don't need to change the embed url, instead try to use the following example:
// Build the filter you want to use. For more information, See Constructing
// Filters in https://github.com/Microsoft/PowerBI-JavaScript/wiki/Filters.
const filter = {
$schema: "http://powerbi.com/product/schema#basic",
target: {
table: "Geo",
column: "Region"
},
operator: "In",
values: ["West"]
};
// Get a reference to the embedded report HTML element
var embedContainer = $('#embedContainer')[0];
// Get a reference to the embedded report.
report = powerbi.get(embedContainer);
// Set the filter for the report.
// Pay attention that setFilters receives an array.
report.setFilters([filter])
.then(function () {
Log.logText("Report filter was set.");
})
.catch(function (errors) {
Log.log(errors);
});

Ionic Prepopulated Database with Antair Cordova SQLitePlugin [help request]

____ INTRO
Hello everyone, first of all, three clarifications:
My english is not good, so I beg your pardon in advance for my mistakes,
I'm a newbie so forgive me for inaccuracies,
I have previously searched and tried the solutions I found on the internet but still I can not solve the problem of embedding a prepopulated database.
____ THE GOAL
I want to develop an app for iOS and Android with a prepopulated database.
Just for example, the database consists of 15.000 records each one made of three key-value pair (id, firstname and lastname).
___ WHAT I DID
Steps:
ionic start myapp blank
cd myapp
ionic platform add ios
ionic platform add android
Then I created an sqlite database for testing purpose, named mydb.sqlite, made of one table people containing two id, firstname, lastname records.
I decided to use the following plugin: https://github.com/Antair/Cordova-SQLitePlugin
That's because it can be installed with cordova tool.
ionic plugin add https://github.com/Antair/Cordova-SQLitePlugin
(Alert: I think that the instructions on the website show an incorrect reference - "cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin" - which refers to another plugin).
Then, following the instructions on the plugin website, I copied the database to myapp/www/db/ so that it can now be found at myapp/www/db/mydb.sqlite
I modified the index.html including the SQLite plugin just after the default app.js script:
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="SQLitePlugin.js"></script>
I also write some lines of code in index.html file to show a button:
<ion-content ng-controller="MyCtrl">
<button class="button" ng-click="all()">All</button>
</ion-content>
Finally I had modified ./js/app.js:
// Ionic Starter App
var db = null;
angular.module('starter', ['ionic' /* What goes here? */ ])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// some predefined code has been omitted
window.sqlitePlugin.importPrepopulatedDatabase({file: "mydb.sqlite", "importIfExists": true});
db = window.sqlitePlugin.openDatabase({name: "mydb.sqlite"});
}); // $ionicPlatform.ready
}) // .run
.controller('MyCtrl', function($scope){
$scope.all = function(){
var query = "SELECT * FROM people";
// I don't know how to proceed
}; // $scope.all
}); // .controller
___ THE PROBLEM
I don't know how to proceed in the controller section to query all the records (just an example of query) and show the results in the console.log.
I think that the following code must be completed in some way:
angular.module('starter', ['ionic' /* What goes here? */ ])
And also the code inside controller section must be completed:
$scope.all = function(){
var query = "SELECT * FROM people";
// I don't know how to proceed
}; // $scope.all
___ FINAL THANKS
Thank you in advance for the help you will give to me.
So this guy's code has helped a lot to encapsulate my DAL. I highly recommend that you use he's code pretty much verbatim.
https://gist.github.com/jgoux/10738978
You'll see he has the following method:
self.query = function(query, bindings) {
bindings = typeof bindings !== 'undefined' ? bindings : [];
var deferred = $q.defer();
self.db.transaction(function(transaction) {
transaction.executeSql(query, bindings, function(transaction, result) {
deferred.resolve(result);
}, function(transaction, error) {
deferred.reject(error);
});
});
return deferred.promise;
};
Let's break this down a bit. The query function takes a query string (the query param) and a list of possible bindings for ? in a query like "SELECT * FROM A_TABLE WHERE ID = ?". Because he's code is a service, the self value points to the service itself for all future invocations. The function will execute a transaction against the db, but it returns a promise that is only fulfilled once the db comes back.
His service provides a second helper function: fetchAll.
self.fetchAll = function(result) {
var output = [];
for (var i = 0; i < result.rows.length; i++) {
output.push(result.rows.item(i));
}
return output;
};
fetchAll will read the rows in their entirety into an array. The result param for fetchAll is the result variable passed in the query function's promise fulfillment.
If you copy and paste his code into your service file, you now have a bonafide DB service. You can wrap that service up in a DAL. Here's an example from my project.
.service('LocationService', function ($q, DB, Util) {
'use strict';
var self = this;
self.locations = [];
self.loadLocked = false;
self.pending = [];
self.findLocations = function () {
var d = $q.defer();
if (self.locations.length > 0) {
d.resolve(self.locations);
}
else if (self.locations.length === 0 && !self.loadLocked) {
self.loadLocked = true;
DB.query("SELECT * FROM locations WHERE kind = 'active'")
.then(function (resultSet) {
var locations = DB.fetchAll(resultSet);
self.locations.
push.apply(self.locations, locations);
self.loadLocked = false;
d.resolve(self.locations);
self.pending.forEach(function (d) {
d.resolve(self.locations);
});
}, Util.handleError);
} else {
self.pending.push(d);
}
return d.promise;
};
})
This example is a bit noisy since it has some "threading" code to make sure if the same promise is fired twice it only runs against the DB once. The general poin is to show that the DB.query returns a promise. The "then" following the query method uses the DB service to fetchAll the data and add it into my local memory space. All of this is coordinated by the self.findLocations returning the variable d.promise.
Yours would behalf similarly. The controller could have your DAL service, like my LocationService, injected into it by AngularJS. If you're using the AngularJS UI, you can have it resolve the data and pass it into the list.
Finally, the only issue I have with the guy's code is that the db should come from this code.
var dbMaker = ($window.sqlitePlugin || $window);
The reason for this is that the plugin does not work within Apache Ripple. Since the plugin does a fine job mirroring the Web SQL interface of the browser, this simple little change will enable Ripple to run your Ionic Apps while still allowing you to work your SQLite in a real device.
I hope this helps.

Notification at DART lang - html / browser / webkit / Desktop

I want to ask about the normal notification in DART, which is different than the Chrome Packaged App discussed here
I created the below code, the browser [DARTIUM] asked for permission as expected, but the response in both cases (Allow/Deny) appeared as "default" in the console, and the notification did not appear.
{
void main() {
Notification.requestPermission().then((String permission) {
print(permission); // ==> This is always = "default" for both Allow and Deny
if (permission == "default") {
print('permission granted');
var notification = new Notification('hello');
}
else print('sorry no permission!');
});
}
any thought! thanks
The code as it's currently written would never show a permission either way -- "default" means that permission hasn't been allowed or denied. You should be checking for permission == "granted" before displaying the notification.
Keep in mind, there is an outstanding bug with notifications and checking the current permissions, see https://code.google.com/p/dart/issues/detail?id=20585, although this may not be affecting you.
thanks Brian and Gunter, I made my own notification, inspired by this
I made used the same, CSS file, and made a custom element, notification.dart
part of myApp;
class NotificationElement extends HtmlElement {
// Define the custom element tag
static final tag = 'x-Notification';
factory NotificationElement() => new Element.tag(tag);
// Create the element and define its stylesheet
NotificationElement.created() : super.created(){
LinkElement styleSheet = new LinkElement()..rel = "stylesheet"..type="text/css"..href="./style/toastr.css";
document.head.append(styleSheet);
}
var notificationContainer = new Element.html('<div></div>')
..id='notification-container';
var notificationBody = new Element.html('<div></div>')
..classes.add('notification');
var notificationButton = new ButtonElement()
..classes.add('notification-close-button')
..text='x';
var notificationTitle = new Element.html('<div></div>')..classes.add('notification-title');
var notificationMsg = new Element.html('<div></div>')..classes.add('notification-message');
var notificationMsgLabel = new LabelElement();
Element launchElement(type,location,Title,Msg){
notificationButton.onClick.listen((e) => notificationContainer.nodes.remove(notificationBody));
notificationContainer..classes.add('notification-'+location);
notificationBody..classes.add('notification-'+type);
notificationTitle.text=Title;
notificationMsg.innerHtml='<label>'+Msg+'</label>';
notificationBody.nodes..add(notificationButton)..add(notificationTitle)..add(notificationMsg);
notificationContainer.nodes..add(notificationBody);
return (notificationContainer);
}
}
Element mynotification = querySelector('#notification-element');
void CreatefonixNotification(type,location,Title,Msg){
var notifyMe = new Element.tag('x-notification');
notifyMe = notifyMe.launchElement(type,location,Title,Msg);
mynotification.nodes.add(notifyMe);
}
in the index.dart, I registered the element:
document.registerElement(NotificationElement.tag, NotificationElement);
and in index.html, I added this div:
<div id='notification-element'></div>
and any place in the application, I can call it like:
CreateNotification('error','top-left','Error:','sorry we have some issue!!.')

Resources