ASP.NET Core 2.0.0 Web application on Windows IoT - asp.net-core

I have a RPI running Windows 10 IoT. Using this link I managed to get a web api running that says "Hello world", but now I'm stuck.
What I want is a web page with a few buttons that I can put some code behind to control stuff.
I have searched to find a simple button -> action example but all I found was way over the top (for my purpose) MVC examples. I just need something simple but I can't figure it out.
Hope someone can point me in the right direction.

You can choose jQuery+ajax to excute behind code, for example :
Razor Page(Contact.cshtml)
<input type="button" value="Button1" id="button1" />
<input type="button" value="Button2" id="button2" />
JavaScript Code
$(function () {
$("#button1").click(function () {
$.post("/Sample/Action1", function (result) {
alert("Click Button1,Action1 Success!");
});
});
$("#button2").click(function () {
$.post("/Sample/Action2", function (result) {
alert("Click Button2,Action2 Success!");
});
});
});
Behind Code(SampleController.cs)
[HttpPost]
public JsonResult Action1()
{
//action 1 ...
return Json(new { Success = true });
}
[HttpPost]
public JsonResult Action2()
{
//action 2 ...
return Json(new { Success = true });
}
Before that, you should make sure jquery library is included in your page.

Related

How to force Blazor to re-render a component

I'm building a simple web app with Blazor (client-side) and need to get Blazor to re-render the component.
Is there way to notify the framework to re-render?
On this Razor page, I have a simple checkbox that shows if the web app is granted a certain permission by user.
ShouldRender() always returns True. When isGranted field is set to True, the checkbox isn't rendered and
remains unchecked.
Razor page:
#page "/foo"
#inject IJSRuntime js
<input type="checkbox" disabled #bind="isGranted" /> Some Permission
#code {
bool isGranted;
protected override async Task OnInitAsync() {
await js.InvokeAsync<object>(
"foo.bar",
DotNetObjectRef.Create(this),
nameof(BarCallback)
);
}
[JSInvokable]
public void BarCallback(bool result) {
Console.WriteLine($"BarCallback(result: {result})");
isGranted = result;
}
protected override bool ShouldRender() {
Console.WriteLine("Blazor is checking for re-rendering...");
return true;
}
}
JavaScript function:
window.foo = {
bar: (dotnetObjRef, callback) => {
navigator.storage.persist()
.then(result => {
dotnetObjRef.invokeMethodAsync(callback, result)
.catch(reason => console.warn('Failed to call .NET method.', reason));
})
.catch(reason => console.warn('Failed to get permission.', reason));
}
}
Output in the Chrome's console:
WASM: Blazor is checking for re-rendering...
WASM: BarCallback(result: True)
.NET Core SDK: 3.0.100-preview6-012264
Blazor Template: Microsoft.AspNetCore.Blazor.Templates::3.0.0-preview6.19307.2
Usually, you force a re-render by calling the StateHasChanged method.
For this app to work, you should place StateHasChanged(); at the end of the BarCallback method.
Hope this helps.
Just remove disabled from input control and it will work. Change:
<input type="checkbox" disabled #bind="isGranted" />
by:
<input type="checkbox" #bind="isGranted" />
See your code working at blazorfiddle

.Net Framework, WebApi and SignalR

I have created a ASP.NET Web Application (.Net Framework) in VS2017, I have selected an Empty project and ticked the Web API checkbox. I don't want MVC. I install from Nuget Microsoft.AspNet.SignalR. All is well. Then I
Add an OWIN Startup class and add the line app.MapSignalR(); in the Configuration method.
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(WebApplication4.Startup))]
namespace WebApplication4
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
I create a Hub called MyTestHub with a single method Activate.
using Microsoft.AspNet.SignalR;
namespace WebApplication4
{
public class MyTestHub : Hub
{
public string Activate()
{
return "Monitor Activated";
}
}
}
I create an html page to test with the following:
<script src="Scripts/jquery-1.6.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.2.js"></script>
<script src="signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var notificationHub = $.connection.myTestHub;
$.connection.hub.start(function () {
notificationHub.activate(function (response) {
console.log("response", response);
});
});
});
</script>
The hub is created, $.connection.hub.start is fine, but notificationHub.activate returns "Object doesn't support property or method 'activate'". I cannot find the function on notificationHub but I do find it on notificationHub.server. However, calling notificationHub.server.activate does nothing.
I have tried the latest stable version of SingnalR and 2.2.2 (as the sample project) but nothing works. signalr/hibs is OK.
Any ideas? All the examples I have seen basically do this, but I cannot get it to work.
Found the answer
notificationHub.server.activate().done(function (response) {
console.log("response", response);
});

Cannot get json data with ajax in Razor Pages [duplicate]

This question already has answers here:
Example AJAX call back to an ASP.NET Core Razor Page
(8 answers)
Closed 5 years ago.
i am trying to get some data from Razor Pages in ASP.NET Core 2.0.
But the problem is that it does not returns any data.
I also tried debugging it, it does not fire that method (OnGetProducts) at all.
The model Index.cshtml.cs:
private IProductRepository _productRepository;
public IndexModel(IProductRepository repository)
{
_productRepository = repository;
}
public void OnGet()
{
}
public IActionResult OnGetProducts(int page)
{
var model = _productRepository.GetProducts().Skip(page * 10).Take(10);
return new JsonResult(model);
}
the razor page Index.cshtml
<div id="products">
</div>
#section scripts{
<script>
$(function () {
getProducts(0);
});
var isInitialized = false;
function getProducts(page) {
$.ajax({
type: 'GET',
url: "Products",
contentType: "application/json",
dataType: "json",
data: {
handler: 'Products',
page: page
},
success: function (datas) {
console.log(datas);
}
});
}
</script>
}
p.s. this page in in folder Pages/Products/Index.cshtml(.cs)
I usually use razor functions to generate URLs instead of hard coding them in js. If your action is not even being triggered, assuming that you are not accidentally in release mode, it is because the URL doesn't point to the right location. First of all set js variables in razor something like this:
var productsURL = #Url.Context("~/products");
Also run yourdomain/products in your browser and if you get a 404.
Alternatively I use this function to directly use c# objects in js:
public static IHtmlContent ToJS(this IHtmlHelper htmlHelper, object obj)
=> htmlHelper.Raw(JsonConvert.SerializeObject(obj));
With this function created in a static class, you can also create a js object directly something like this:
<script>
var products = #Html.ToJS(repository.GetProducts().Skip(page * 10).Take(10));
</script>
Of course this will only create the object in page load, if you want it to change after page load, you can consider creating a partial view via ajax. Also note that the second alternative will be slower than the first for ajax.

Auth2 Object unidentified when trying to sign out (Angular2)

Good Day,
I am trying to sign out an auth2 client. This process was working fine before I upgraded my router to fit in with new RC requirements. Now it seems as if the auth2 object is cleared or lost along the way from signing in to signing out.
Here is my sign out tag:
<a role="button" (click)="signOut()" style="padding-left: 30px;">Log out</a>
it simply calls a signOut() function found in navbar.component.ts (See below)
signOut() {
var auth2 = this._navigationService.getAuth2();
auth2.signOut().then(function () {
});
console.log('User signed out.');
sessionStorage.clear();
localStorage.clear();
this.router.navigate(['Login'])
window.location.reload()
}
here is the navigationService code it is calling:
import { Injectable } from '#angular/core';
#Injectable()
export class NavigationService {
onEditMode:boolean;
auth2:any;
constructor() {
this.onEditMode=true;
}
getEditMode(){
return this.onEditMode;
}
setEditMode(editMode:boolean){
this.onEditMode=editMode;
}
setAuth2(auth2:any){
this.auth2=auth2;
}
getAuth2(){
return this.auth2;
}
}
Here is my login.component.ts which sets the auth2 object seen in navigationService.ts:
onGoogleLoginSuccess = (loggedInUser) => {
this.isLoading=true;
console.log(loggedInUser)
this._navigationService.setAuth2(gapi.auth2.getAuthInstance());
console.log("Google gapi" + gapi.auth2.getAuthInstance());
sessionStorage.setItem('gapi',gapi.auth2.getAuthInstance());
this._zone.run(() => {
this.userAuthToken = loggedInUser.hg.access_token;
this.userDisplayName = loggedInUser.getBasicProfile().getName();
var strClientID = document.getElementsByTagName('meta')['google-signin-client_id'].getAttribute('content')
this.objTrimbleAuthentication.ClientID = document.getElementsByTagName('meta')['google-signin-client_id'].getAttribute('content');
this.objTrimbleAuthentication.IDToken = loggedInUser.getAuthResponse().id_token;
this._trimbleAuthenticationService.sendAndVerify(this.objTrimbleAuthentication).subscribe(data=>{
if(data.tokenIsValid==true){
sessionStorage.setItem('S_USER_EMAIL',loggedInUser.getBasicProfile().getEmail());
sessionStorage.setItem('S_USER_NAME',loggedInUser.getBasicProfile().getName());
sessionStorage.setItem('S_ID_TOKEN',this.userAuthToken);
this.objExternalBindingModel.ExternalAccessToken=this.userAuthToken;
this.objExternalBindingModel.Provider="Google";
this.objExternalBindingModel.UserName = loggedInUser.getBasicProfile().getName();
this._LoginService.obtainLocalAccessToken(this.objExternalBindingModel).subscribe(data=>{
// console.log(data);
this.isLoading=false;
this._router.navigate(['/Home']);
sessionStorage.setItem("access_token",data.access_token);
},error=>{
console.log(error);
})
}else{
this.isLoading= false;
this.showModal('#trimbleAuthError');
}
}, error=>{
})
});
}
onGoogleLoginSuccess is called from login.component.html:
<div style="margin-left:8% !important" id="{{googleLoginButtonId}}"></div>
So this process was working fine until I update my router to use the latest Angular2 Release Candidate. I am out of ideas on what could possibly be causing the following error when I click the sign out button:
Error in component.html/navbar.component.html:12:33
ORIGINAL EXCEPTION: TypeError: Cannot read property 'signOut' of undefined
if you need any other information or components please ask I hope I have given enough information. As I said it was working so keep that in mind, please.
Update
Waiting for additional info ...
In the following code, auth2:any; is undeclared. Is setAuth2 called anywhere before signOut()?
import { Injectable } from '#angular/core';
#Injectable()
export class NavigationService {
onEditMode:boolean;
auth2:any;
constructor() {
this.onEditMode=true;
}
getEditMode(){
return this.onEditMode;
}
setEditMode(editMode:boolean){
this.onEditMode=editMode;
}
setAuth2(auth2:any){
this.auth2=auth2;
}
getAuth2(){
return this.auth2;
}
}
Base on limited information and code posted, my guess is a logical bug in the logout process.
In signOut(), the window.location.reload() reload the page at the current url, which also clear all variables/objects. However, after reload, your app properly try to do signout again (due to url?).
In your navbar.component, you may need to add more logic in ngInit() to handle the situation.
Or can your code work without window.location.reload()? It seems odd to use that with angular2, especially with routing.
Right, the solution i found to the above question was that signing out using localhost will not work. So i just used this block of code when deploying the website and keep it commented out when running the website on localhost.
this is my signOut() function found in navbar.component.ts:
signOut() {
//////////////////////////////////////// Uncomment block for live deployment //////////////////////////////
// var auth2 = gapi.auth2.getAuthInstance();
// auth2.signOut().then(function () {
// console.log('User signed out.');
// });
//////////////////////////////////////////////////////////////////////////////////////////////////////////
sessionStorage.clear();
localStorage.clear();
this.router.navigate(['/']);
window.location.reload();
}
although getAuthInstance gives an error when trying to run it in localhost, deploying the web application to a server seems to work fine.

fb:like_box failed to resize in 45s

Is there any working solutions to prevent Facebook Like Box to not breaking his container or something ? Have set the async to TRUE but still gets out. As I can see on stackoverflow there are issues only for fb:login_button, however I receive the same warning to console:
fb:like_box failed to resize in 45s
To sum up, here is my code, perhaps I am missing something.
HTML Tag
<html lang="en" xmlns:fb="http://ogp.me/ns/fb#">
FB Initialization
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId: <?php echo $this->config['facebook']['appId']; ?>,
status: true,
cookie: true,
xfbml: true
});
/* All the events registered */
FB.Event.subscribe('auth.login', function (response) {
// do something with response
alert("login success");
});
FB.Event.subscribe('auth.logout', function (response) {
// do something with response
alert("logout success");
});
FB.getLoginStatus(function (response) {
if (response.session) {
// logged in and connected user, someone you know
alert("login success");
}
});
};
(function () {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
} ());
</script>
FB Like Box
<div class="facebook-plugin">
<div class="fb-like-box" data-href="https://www.facebook.com/****" data-width="346" data-show-faces="true" data-header="true" data-stream="false" data-show-border="true"></div>
</div>
This is it. Any help would be appreciated. Thanks in advance!
Accordingly to new Facebook API upgrade, they give up to Like Box, therefore this is no longer an issue.
With the release of Graph API v2.3, the Like Box plugin is deprecated. Please use the new Page Plugin instead. The Page Plugin allows you to embed a simple feed of content from a Page into your websites.
If you do not manually upgrade to the Page Plugin, your Like Box plugin implementation will automatically fall back to the Page Plugin by June 23rd 2015.
Page Plugin link is https://developers.facebook.com/docs/plugins/page-plugin