Adding Bing Map into Blazor application - .net-core

I am working on a .Net Core Blazor project and I need to add Bing Map to my application. I have added the map and everything seems to work fine:
_Host:
<script async defer src="https://www.bing.com/api/maps/mapcontrol?callback=GetMap&&key=[key]"></script>
My javascript function:
function GetMap() {
var map = new Microsoft.Maps.Map('#myMap', {
credentials: "[key]"
});
var loc = new Microsoft.Maps.Location(lan, lat);
map.setView({ center: loc, zoom: 15 });
}
In my contact us page I have added the div:
<div id="myMap" style='position:relative;width:100%;height:400px;'></div>
The problem is that the map will not show up when I navigate to the contact page, it will appear only after clearing the cache (Crtl + F5)
I have also tried to call the function using the JSRunTime:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("GetMap");
}
}
But I have received this failure:
Error: Microsoft.JSInterop.JSException: Cannot read property
'prototype' of null TypeError: Cannot read property 'prototype' of
null
Does anybody know the reason and how to fix it?
================
Edit
I have also tried to remove the CallBack function from the javascript call and I get this failure:
Microsoft.JSInterop.JSException: Microsoft is not defined
ReferenceError: Microsoft is not defined

Related

How to make Polymer 2.x Function async

I am trying to use the Shape Detection API (https://developers.google.com/web/updates/2019/01/shape-detection) and am getting an error:
Uncaught SyntaxError: await is only valid in async function
After going through the Polymer 2.x docs (https://polymer-library.polymer-project.org/2.0/api/namespaces/Polymer.Async) I get the following:
ready() {
super.ready();
this.initImageDetection();
}
initImageDetection() {
const barcodeDetector = new BarcodeDetector({
formats: [
'code_128'
]
});
try {
const barcodes = await barcodeDetector.detect(image);
barcodes.forEach(barcode => console.log(barcode));
} catch (e) {
console.error('Barcode detection failed:', e);
}
}
This pattern also failed with the same error:
this.async(() => {
const barcodes = await barcodeDetector.detect(image)
barcodes.forEach(barcode => console.log(barcode)
)});
Also, running initImageDetection prefixed with async and running from a paper-button after the DOM is loaded.
async initImageDetection() {
...
}
I get the following error:
Uncaught (in promise) ReferenceError: BarcodeDetector is not defined
How do I properly make a function async in Polymer 2.x?
How can I instantiate BarcodeDetector in Polymer 2.x?
async functionName() {
// function code here
}
Is the proper way to set async functions in Polymer. However, the BarcodeDetector object is hidden behind a flag in Chrome, so must be enabled in chrome://flags Experimental Web Platform features before using.

Meteor patrickml:braintree Authentication Error

This command meteor add patrickml:braintree was run in a Meteor app directory.
In the client.main.js:
A squiggly line Under the variable braintree and the IDE says "unresolved variable or type".
Template.payment.onRendered(function () {
Meteor.call('getClientToken', function (error, clientToken) {
if (error) {
console.log(error); //<---- always prints out
} else {
//vvvvvvvvv
braintree.setup(clientToken, "dropin", {
container: "payment-form", // Injecting into <div id="payment-form"></div>
onPaymentMethodReceived: function (response) {
var nonce = response.nonce;
console.log(nonce);
}
});
}
});
});
In the server code below, clientId is always undefined.
//server/main.js
'getClientToken': function (clientId) {
console.log(clientId); //<--------- undefined
let generateToken = Meteor.wrapAsync(gateway.clientToken.generate, gateway.clientToken);
let options = {};
if (clientId) {
options.clientId = clientId;
}
let response = generateToken(options);
return response.clientToken;
}
And the server console prints out:
Exception while invoking method 'getClientToken' authenticationError: Authentication Error
Any idea what is wrong and how to fix it? thx
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
When you configure your gateway object, make sure that you use the API credentials documented in your Sandbox Control Panel. Here's how you can find them:
Log into the sandbox Control Panel
Navigate to Account > My user
Under API Keys, Tokenization Keys, Encryption Keys, click View Authorizations
If no API keys appear, click Generate New API Key
Click View under the Private Key column to see your public and private keys, merchant ID, and environment
When you have them, use them to configure your gateway object. For example:
var braintree = require("braintree");
var gateway = braintree.connect({
environment: braintree.Environment.Sandbox,
merchantId: "replaceWithYourMerchantId",
publicKey: "replaceWithYourPublicKey",
privateKey: "replaceWithYourPrivateKey"
});

ng2 display object in html

I'm trying to work out how to display an object in html using angular2. In ng1 I assigned to a variable and double braced the variable name in the html and bingo! Now I can't seem to get any data displayed at all.
Here is my simple method call:
onSubmit(value: oSearch): void {
console.log('you submitted value: ', value);
Meteor.call('methodName',value.type,value.year,value.idNumber, function(error,result) {
if (error) {
console.log('failed', error);
} else {
this.oResult = result[0];
console.log('successful call', this.oResult);
}
})
}
The object gets printed to the console. But I cannot get it to render by using:
{{oResult}}
oResult is declared using
oResult:Object;
Completely new to ts and ng2.
Update
Okay, I tried NgZone, but that didn't work. I'm getting behaviour I really don't understand.
} else {
console.log('successful call', result[0].topItem);
this.oResult = result[0];
console.log('successful call', this.oResult);
Both console.logs print the object correctly but oResult displays as [object Object]
If I change to:
this.oResult.topItem = result[0].topItem
then I get a Meteor error thrown and the 2nd console.log doesn't print. The error is:
Exception in delivering result of invoking 'methodName': TypeError: Cannot set property 'topItem' of undefined
My server method was working perfectly with ng1. I've tried a synchronous version of http but no change in behaviour has resulted.
Perhaps someone knows of a tutorial demo of http method call using updated angular2-meteor that I can fork?
Angular doesn't recognize the value change if fields are updated by code running outside Angulars zone. Inject zone: NgZone and run the code within zone.run(...). It might also be sufficient to initialize the library within Angular to make it use the async API patched by Angular which notifies Angular about possible changes.
constructor(private zone: NgZone) {
}
onSubmit(value: oSearch): void {
console.log('you submitted value: ', value);
Meteor.call('methodName',value.type,value.year,value.idNumber, function(error,result) {
if (error) {
console.log('failed', error);
} else {
zone.run(function() {
this.oResult = result[0];
console.log('successful call', this.oResult);
});
}
});
}
See also Service events do not affect template correctly for an example.

access data from iron-router in rendered function

I'm trying to access data passed from iron router in the javascript function
router.js
this.route('editOrganization', {
path: '/editOrganization',
waitOn: function() {
return [
Meteor.subscribe('organization', this.userId)
];
},
data: function() {
return Organizations.findOne();
}
});
now if I wanted to access a property of organization in html (editCompany.html) I can do the following
{{name}}
but how do I access that same property in the js file
Template.editOrganization.rendered = function() {
//how do I access name?
}
UPDATE:
so if I click a link to edit organization I can get the value via
this.data.name
However, if I reload the page (same url) it throws an error saying data is null.
It is accessible through the rendered function context.
Template.editOrganization.rendered = function() {
var name = this.data && this.data.name;
};
This is confusing for many people but you need to configure the router to actually wait for the subscriptions you returned with waitOn.
Router.onBeforeAction('loading')
You can read the author's explanation here:
https://github.com/EventedMind/iron-router/issues/554#issuecomment-39002306

Issue binding JSONP data with Knockout.js

I am working on a web project that involves a cross-domain call, and I decided to use Knockout.js and ASP.NET Web Api. I used the Single Page Application template in VS 2012, and implemented the Knockout class as it is. The page works great when I make JSON call from the same domain, but when I try using JSONP from the remote server the knockout does not seem to bind the data. I can see the JSON data received from the remote while making JSONP call, but knockout cannot bind the data.
Here is my JavaScript ViewModel classes:
window.storyApp.storyListViewModel = (function (ko, datacontext) {
//Data
var self = this;
self.storyLists = ko.observableArray();
self.selectedStory = ko.observable();
self.error = ko.observable();
//Operations
//Load initial state from the server, convert it to Story instances, then populate self
datacontext.getStoryLists(storyLists, error); // load update stories
self.selectStory = function (s) {
selectedStory(s); $("#showStoryItem").click(); window.scrollTo(0, 0);
storyItem = s;
}
//append id to the hash for navigating to anchor tag
self.backToStory = function () {
window.location.hash = storyItem.id;
}
self.loadStories = function () {
datacontext.getStoryLists(storyLists, error); // load update stories
}
return {
storyLists: self.storyLists,
error: self.error,
selectStory: self.selectStory
};
})(ko, storyApp.datacontext);
// Initiate the Knockout bindings
ko.applyBindings(window.storyApp.storyListViewModel);
And my DataContext class as below:
window.storyApp = window.storyApp || {};
window.storyApp.datacontext = (function (ko) {
var datacontext = {
getStoryLists: getStoryLists
};
return datacontext;
function getStoryLists(storyListsObservable, errorObservable) {
return ajaxRequest("get", storyListUrl())
.done(getSucceeded)
.fail(getFailed);
function getSucceeded(data) {
var mappedStoryLists = $.map(data, function (list) { return new createStoryList(list); });
storyListsObservable(mappedStoryLists);
}
function getFailed() {
errorObservable("Error retrieving stories lists.");
}
function createStoryList(data) {
return new datacontext.StoryList(data); // TodoList is injected by model.js
}
}
// Private
function clearErrorMessage(entity) {
entity.ErrorMessage(null);
}
function ajaxRequest(type, url, data) { // Ajax helper
var options = {
dataType: "JSONP",
contentType: "application/json",
cache: false,
type: type,
data: ko.toJSON(data)
};
return $.ajax(url, options);
}
// routes
function storyListUrl(id) {
return "http://secure.regis.edu/insite_webapi/api/story/" + (id || "");
}
})(ko);
This page: http://insite.regis.edu/insite/index.html makes the cross-domain call to secure.regis.edu, and it is not working. However the same page on secure.regis.eduinsite/index.html making JSON call works just fine.
What am I doing wrong? Any help will be greatly appreciated.
Thanks for those provided help.
I manage to solve the issue by adding WebApiContrib.Formatting.Jsonp class to my WebApi project as explained in https://github.com/WebApiContrib/WebApiContrib.Formatting.Jsonp, and making a slight modification to my jQuery Ajax helper class as below:
function ajaxRequest(type, url, data, callbackWrapper) { // Ajax helper
var options = {
dataType: "jsonp",
crossDomain : true,
type: type,
jsonp: "callback",
jsonpCallback: callbackWrapper,
data: ko.toJSON(data)
};
return $.ajax(url, options);
}
Everything worked as a charm.
I suggest the following:
Create a simplified example (without Knockout) that just makes the AJAX call with simple, alert-style success and error callbacks. Affirm that it is throwing an error in the cross-domain case.
Check the following link: parsererror after jQuery.ajax request with jsonp content type. If that doesn't tell you enough, search the Web (and StackOverflow) for information on jQuery JSONP parserrors and callbacks.
If you're still stuck, and you've done #1 and seen what I expect you will see, re-write this post with your simplified example, and remove any references to Knockout (in title, tags). I know Knockout, but I don't know JSONP, and the folks who know JSONP don't seem to be touching this, so I think this question is reaching the wrong audience. Changing the title and tags to emphasize the JSONP/cross-domain aspect may get you the help you need.

Resources