The requested built-in library is not available on Dartium - mongodb

I am trying to make a very simple application that looks up values in a database by using polymer elements to get input.
My main polymer class looks like this:
library index;
import 'package:polymer/polymer.dart';
import 'lookup.dart';
import 'dart:html';
#CustomTag('auth-input')
class AuthInput extends PolymerElement {
#observable String username = '';
#observable String password = '';
AuthInput.created() : super.created();
void login(Event e, var detail, Node target)
{
int code = (e as KeyboardEvent).keyCode;
switch (code) {
case 13:
{
Database.lookUp(username, password);
break;
}
}
}
}
and a secondary database helper class looks like this:
library database;
import 'package:mongo_dart/mongo_dart.dart';
class Database {
static void lookUp(String username, String password) {
print("Trying to look up username: " + username + " and password: " + password);
DbCollection collection;
Db db = new Db("mongodb://127.0.0.1/main");
db.open();
collection = db.collection("auth_data");
var val = collection.findOne(where.eq("username", username));
print(val);
db.close();
}
}
I keep getting this error and I cannot think of a way around it:
The requested built-in library is not available on Dartium.'package:mongo_dart/mongo_dart.dart': error: line 6 pos 1: library handler failed
import 'dart:io';
The strange thing is, I don't want to use dart:io. The code works fine either running database processes or running polymer processes. I can't get them to work together. I don't see why this implementation of the code will not run.

The first line at https://pub.dartlang.org/packages/mongo_dart says
Server-side driver library for MongoDb implemented in pure Dart.
This means you can't use it in the browser. Your error message indicates the same. The code in the package uses dart:io and therefore can't be used in the browser.
Also mongodb://127.0.0.1/main is not an URL that can be used from within the browser.
You need a server application that does the DB access and provides an HTTP/WebSocket API to your browser client.

Related

mongo_dart error: A value of type 'Rational' can't be assigned to a variable of type 'Decimal'

The code below tries to create a Dart server and open a Mongo database. When database section below is commented, then the server starts as expected. Uncommenting the database section dumps the below error on console.
../../.pub-cache/hosted/pub.dartlang.org/bson-
2.0.1/lib/src/types/decimal_128.dart:36:58: Error: A value of type 'Rational' can't
be assigned to a variable of type 'Decimal'.
Environment: MacOS_x64 12.6, Dart SDK version: 2.19.0-264.0.dev (dev)
import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_router/shelf_router.dart';
import 'package:mongo_dart/mongo_dart.dart';
// Configure routes.
final _router = Router()
..get('/', _rootHandler)
..get('/echo/<message>', _echoHandler);
Response _rootHandler(Request req) {
return Response.ok('Hello, World!\n');
}
Response _echoHandler(Request request) {
final message = request.params['message'];
return Response.ok('$message\n');
}
void main(List<String> args) async {
// Use any available host or container IP (usually `0.0.0.0`).
final ip = InternetAddress.anyIPv4;
// Configure a pipeline that logs requests.
final handler = Pipeline().addMiddleware(logRequests()).addHandler(_router);
// For running in containers, we respect the PORT environment variable.
final port = int.parse(Platform.environment['PORT'] ?? '8080');
final server = await serve(handler, ip, port);
print('Server listening on port ${server.port}');
/// Database Section ///
final db = Db('mongodb://localhost:27017/testdb');
try {
print('Opening database\n');
await db.open();
print('database connected');
print('Database connected');
} catch (e) {
print(e);
exit(0);
}
}
It would seem that the bson package is to blame for the error. I would post an issue ticket on their repository detailing this issue, and also post an issue on the mongo_dart package bringing it to their attention. Perhaps they are using an outdated version of the decimal or rational package. (Or maybe this has already been fixed in the bson package and it's the mongo_dart package that needs to update its dependencies.)
Per the documentation, Decimal.pow returns a Rational, and Decimal and Rational are not directly compatible types. They would need to use the extension method Rational.toDecimal to convert the value back to a Decimal.
// For example
final Decimal maxUint64 = Decimal(2).pow(64).toDecimal();

Running Acumatica import scenario from code

How to run select "Import by Scenario" scenario -> press "Prepare&Import" from code?
I have tried this:
var importGraph = PX.Data.PXGraph.CreateInstance<SYImportProcessSingle>();
SYMappingActive mapactive = PXSelect<SYMappingActive>.Search<SYMappingActive.mappingID>(importGraph, importproviderID);
importGraph.PrepareImport.PressButton();
but this did not work to run "Prepare & Import" for "import by scenario" graph for my DAC.
First thing to check. Can you execute the import scenario from the application instance? I refer to the Process Import Scenario screen (SM206036). The provider error could be that the import scenario has no data provider assigned, or the provider is not usable.
Here is example how you can do it. I have written this for SalesOrder but you can modify it for any other screen. Also if there exist more than one Import Scenario for the same screen this code will use first Active one.
public class SOOrderEntry_Extension : PXGraphExtension<SOOrderEntry>
{
#region Actions
public PXAction<SOOrder> RunScenario;
[PXButton(CommitChanges = true)]
[PXUIField(DisplayName = "RUN")]
protected void runScenario()
{
var importGraph = PXGraph.CreateInstance<SYImportProcessSingle>();
var myMapping = PXSelect<SYMapping, Where<SYMapping.screenID, Equal<Required<SYMapping.screenID>>>>.Select(importGraph, Base.Accessinfo.ScreenID.Replace(".", string.Empty));
if (myMapping.Any())
{
importGraph.MappingsSingle.Current = importGraph.MappingsSingle.Search<SYMappingActive.name>(((SYMapping)myMapping.First(x => ((SYMapping)x).IsActive ?? false)).Name);
importGraph.Prepare.Press();
PXLongOperation.WaitCompletion(importGraph.UID);
importGraph.Clear(PXClearOption.ClearAll);
importGraph.MappingsSingle.Current = importGraph.MappingsSingle.Search<SYMappingActive.name>(((SYMapping)myMapping.First(x => ((SYMapping)x).IsActive ?? false)).Name);
importGraph.Import.Press();
PXLongOperation.WaitCompletion(importGraph.UID);
}
}
#endregion
}

NullReferenceException occurs during offline sync to Azure Mobile Service

I am trying to make offline sync to table from azure mobile service. My Xamarin Form version is 1.4.2.6359.
I try to test my code in OnCreate method of MainActivity. All preparation steps such as MobileServiceClient initialization, MobileServiceSQLiteStore initialization, SyncTable creation, etc are ok.
When I try to call PullAsync, I am getting NullReferenceException. I capture the package using Package Capture App from mobile. The request goes to Azure Mobile service and it returns the correct json data successfully.
When I try the same code in Xamarin Android project (not Xamarin Form), it is working fine.
To reproduce the issue.
Just create Xamarin Form (Portable) project and use my code.
My Code
private async Task Test() {
const string applicationURL = #"https://xxxx.azure-mobile.net/";
const string applicationKey = #"xxxx";
CurrentPlatform.Init();
var client = new MobileServiceClient(applicationURL, applicationKey);
string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "store.db");
if (!File.Exists(path)) {
File.Create(path).Dispose();
}
var store = new MobileServiceSQLiteStore(path);
store.DefineTable<Product>();
await client.SyncContext.InitializeAsync(store);
var productTable = client.GetSyncTable<Product>();
try {
await client.SyncContext.PushAsync();
await productTable.PullAsync("allProducts", productTable.CreateQuery());
var t = await productTable.ToListAsync();
Console.WriteLine("Product Count : " + t.Count);
}
catch (Java.Net.MalformedURLException ex) {
Console.WriteLine(ex.Message);
}
catch (Exception e) {
Console.WriteLine(e.Message);
}
}
References:
http://azure.microsoft.com/en-us/documentation/articles/mobile-services-xamarin-android-get-started-offline-data/
http://blogs.msdn.com/b/carlosfigueira/archive/2014/04/07/deep-dive-on-the-offline-support-in-the-azure-mobile-service-managed-client-sdk.aspx
I got the solution for this case.
As far as my understanding, this is what is happening. During the application is loading, I call PullAsync. It is async call and during this call, application keeps loading other components. The actual NullReferenceException is coming from OnPrepareOptionsMenu function (Xamarin.Forms.Platform.Android.AndroidActivity.OnPrepareOptionsMenu). The exception is happening on other thread and the thread simply dies. That's why I cannot get stack trace from my main thread.
This NullReferenceException issue is totally not related to Azure Mobile Service.
I override OnPrepareOptionsMenu in MainActivity and add try-catch block to base class function call. The problem is solved. Here is my code in MainActivity class.
public override bool OnPrepareOptionsMenu(IMenu menu) {
try {
// I am always getting menu.HasVisibleItems = false in my app
if (menu != null && menu.HasVisibleItems) {
// Exception is happening when the following code is executed
var result = base.OnPrepareOptionsMenu(menu);
return result;
}
}
catch{
}
return true;
}
I don't really understand why it is happening. Please point me out if you have better understanding of this case and better solution.
I think my issue is same as this : http://forums.xamarin.com/discussion/23579/exception-whilte-trying-to-open-activity-from-xamarin-forms-page

Import mongo_dart package stops text from displaying

The following code works just fine...simply displaying some JSON in an unordered list:
import 'dart:html';
import 'dart:convert';
main() {
// Db db = new Db("mongodb://127.0.0.1/mongo_dart-showjson");
querySelector("#sample_text_id")
..onClick.listen(showJSON);
}
void reverseText(MouseEvent event) {
var text = querySelector("#sample_text_id").text;
var buffer = new StringBuffer();
for (int i = text.length - 1; i >= 0; i--) {
buffer.write(text[i]);
}
querySelector("#sample_text_id").text = buffer.toString();
}
void showJSON(MouseEvent event) {
var path = 'hcps.json';
var hcpDisplay = querySelector('#json_length_id');
HttpRequest.getString(path).then((String fileContents) {
List<String> hcpList = JSON.decode(fileContents);
for (int i = 0; i < hcpList.length; i++) {
hcpDisplay.children.add(new LIElement()..text = hcpList[i].toString());
}
});
}
However, when I add an import statement for mongo-dart, the JSON is not displayed, though I do not receive an error:
import 'dart:html';
import 'dart:convert';
import 'package:mongo_dart/mongo_dart.dart';
main() {
Db db = new Db("mongodb://127.0.0.1/mongo_dart-showjson");
querySelector("#sample_text_id")
..onClick.listen(showJSON);
}
...
The mongo_dart package has been added to pubspec.yaml as a dependency.
Does anyone have an idea as to why importing the mongo_dart package would cause the json text not to display, though there is no error? Thank you in advance.
As stated in package readme
mongo-dart is a server-side driver library for MongoDb implemented in
pure Dart
.
It cannot work at client side. Main reason for that - browsers do not have real sockets to connect to databases like mongodb, mysql, postgress and so on. You may look at some database with a RESTful API like CouchDB. Or you should use some middleware - for example objectory.
You could try
import 'package:mongo_dart/mongo_dart.dart' as mdb;
main() {
mdb.Db db = new mdb.Db("mongodb://127.0.0.1/mongo_dart-showjson");
to see if there is a conflict
You could also add a try/catch block
try {
mdb.Db db = new mdb.Db("mongodb://127.0.0.1/mongo_dart-showjson");
} catch(e) {
print(e)
}
sometimes exceptions are swallowed due to the use of zones (might not help here though) but I think it's worth a try.
It is possible that the package cache directory is corrupted.
You could try
pub cache repair

Twitter 4j with Netbeans

First time poster, but I'm really stuck.
I'm working on a little project and I'm trying to send out a tweet using a netbeans project. I'm using twitter4j and it seems like things have recently changed to where you have to use their OAuth function. I've created an application on twitter and tried some code but I keep getting this error:Exception in thread "main" connect timed outRelevant discussions can be on the Internet at:
http://www.google.co.jp/search?q=b2b52c28 or
http://www.google.co.jp/search?q=1b442895
TwitterException{exceptionCode=[b2b52c28-1b442895 b2b52c28-1b44286b], statusCode=-1, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.5}
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:200)
at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
at twitter4j.TwitterImpl.post(TwitterImpl.java:1929)
at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:433)
at login.Login.start(Login.java:36)
at login.Login.main(Login.java:63)
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:75)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:388)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:483)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:213)
at sun.net.www.http.HttpClient.New(HttpClient.java:300)
at sun.net.www.http.HttpClient.New(HttpClient.java:316)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:992)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:928)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:846)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1087)
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:158)
... 6 more
Java Result: 1
I'm not entirely sure what I'm doing wrong. Below is the code I've tried.
package login;
import java.io.IOException;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
public class Login {
private final static String CONSUMER_KEY = "******";
private final static String CONSUMER_KEY_SECRET =
"******";
public void start() throws TwitterException, IOException {
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
// here's the difference
String accessToken = getSavedAccessToken();
String accessTokenSecret = getSavedAccessTokenSecret();
AccessToken oathAccessToken = new AccessToken(accessToken,
accessTokenSecret);
twitter.setOAuthAccessToken(oathAccessToken);
// end of difference
twitter.updateStatus("Hi, im updating status again from Namex Tweet for Demo");
System.out.println("\nMy Timeline:");
// I'm reading your timeline
ResponseList list = twitter.getHomeTimeline();
/* for (Status each : list) {
System.out.println("Sent by: #" + each.getUser().getScreenName()
+ " - " + each.getUser().getName() + "\n" + each.getText()
+ "\n");
}*/
}
private String getSavedAccessTokenSecret() {
// consider this is method to get your previously saved Access Token
// Secret
return "oC8tImRFL6i8TuRkTEaIcWsF8oY4SL5iTGNkG9O0Q";
}
private String getSavedAccessToken() {
// consider this is method to get your previously saved Access Token
return "102333999-M4W1Jtp8y8QY8RH7OxGWbM5Len5xOeeTUuG7QfcY";
}
public static void main(String[] args) throws Exception {
new Login().start();
}
}
Could I suggest an alternative route..
I have recently been messing around with twitter4j and I approached this slightly differently - I found a nice and easy way to authenticate the client using a ConfigurationBuilder object and passing this to the factory that is getting the instance of the Twitter object you need.
package main;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.conf.ConfigurationBuilder;
public class Base {
protected Twitter twitter;
//protected TwitterStream twitterStream;
private ConfigurationBuilder configBuilder;
public Base(){
configBuilder = new ConfigurationBuilder();
configBuilder.setDebugEnabled(true);
configBuilder.setOAuthConsumerKey("[consumer key here]");
configBuilder.setOAuthConsumerSecret("[consumer secret key here]");
configBuilder.setOAuthAccessToken("[OAuthAccessToken here]");
configBuilder.setOAuthAccessTokenSecret("[secret OAuthAccessToken here]");
//use the ConfigBuilder.build() method and pass the result to the TwitterFactory
TwitterFactory tf = new TwitterFactory(configBuilder.build());
//you can now get authenticated instance of Twitter object.
twitter = tf.getInstance();
}
}
You could then extend this class with sub classes that implement the functionality you require or just create the ConfigurationBuilder/TwitterFactory/Twitter objects elsewhere in your code.
Below I have implemented a class that creates status' and can return the Status object that holds additional information such as createdAt() and the ID etc etc.
package main;
import twitter4j.Status;
import twitter4j.TwitterException;
public class StatusUpdater extends Base{
public StatusUpdater(){}
public Status updateStatus(String statusToUpdate) throws TwitterException{
Status status = twitter.updateStatus(statusToUpdate);
System.out.println("statusToUpdate: " + status + ".");
return status;
}
}
Then you can use the following statement to create the status. This can be done from mbean/ejb/servlet etc.
try {
StatusUpdater statusUpdater = new StatusUpdater();
String statusTextToSet = "test status";
Status updatedStatus = statusUpdater.updateStatus(statusTextToSet);
System.out.println("Created at: " + updatedStatus.getCreatedAt());
} catch (TwitterException tex) {
System.out.println(tex.getErrorMessage());
}
More info on the configuration process here
Your code looks ok. Have you confirmed your definitely using the correct consumer key and secret for your app? Try twitter.verifyCredentials() to see if you get the same error, or a more specific error.
If you're correcting to the net via a proxy, you will need to include your proxy settings to allow the connection to succeed, details can be found here http://twitter4j.org/en/configuration.html#HTTP%20proxy%20server
As an aside, you may want to remove you access token and secret from your post, if they're still valid then someone could login to your account with them.