HTML5 notifications in Blazor - c#

I'm trying to use HTML5 notifications (those displayed at the OS level) in Blazor. I can't bring up a dialog asking if the user wants to enable these notifications.
The compiler reports that it requires additional arguments (like object?[]?), but I can't find which ones. Can someone please advise me how this call should look like?
Edit: Blazor WASM + .net 6
#inject IJSRuntime JsRuntime
private async Task AllowNotif()
{
await JSRuntime.InvokeAsync<string>("Notification.requestPermission");
}

Related

Prevent Blazor Mud Snackbar from opening across different browser sessions

I've followed the guide here on creating a MudBlazor Snackbar notification on a Blazor server app:
https://mudblazor.com/components/snackbar
However when I publish my site, and invoke the "ShowSnackbar" method below on a user machine, I see the snackbar showing across all browser sessions, even across different machines.
#inject ISnackbar Snackbar
<MudButton OnClick="ShowSnackbar"></MudButton>
#code {
public async void ShowSnackbar()
{
Snackbar.Add($"Snackbar ID: {Guid.NewGuid()}", Severity.Normal);
}
}
How can I restrict this to show only on the session on which the button was clicked?
I copied the code directly from the MudBlazor site, expecting it to behave the way it does on their page:
As you can see, I click the Open Snackbar button here, and it only shows on 1 session.

How to Use or Deal With Server-Side SDKs not Designed for Concurrency in ASP.NET Core 2.1 with Razor Pages

Update: As per it's request, the following is a more clean explanation of what I am trying to achieve, and a description of the context in which I am working.
Essentially, I am making a website using ASP.NET Core 2.1 with the Razor Pages framework, configured entirely with the default setup for everything. The important note is that I need to use a specific external provider as the app's data management service and thus cannot just implement a database with ASP.NET. Because of this, in the server-side code for most of the Pages, I am using a client SDK for said management service because it is easier to interact with than a REST API. The issue is that I am running into concurrency problems due to the fact that the SDK was designed to be used with one session at a time, and thus exposes static properties containing the session data such as the "current user". What I am asking is how I could possibly create a new execution or memory domain for each session that is created, so that each one can have it's own "current user", or how I could otherwise solve the concurrency nightmare that emerges when an SDK is used that is designed to only have the client deal with one user and/or session at a time in the entire backend. My previous notes about Blazor where attempting to describe the easiest analog for what I think could be a solution to this issue. I have heard about storing session data; however, as far as I am aware, everything must be serialized to JSON and stored in a file somewhere, which does not work for me as the data could be confidential.
Old Explanation (Still Somewhat Relevant): I am creating a website powered by ASP.NET Core 2.1 and am attempting to use an SDK that was designed to be used on an AppDomain that is unique to one specific application instance and/or session; this means that the SDK has multiple APIs which expose data-storage members (fields, properties, etc.) that are static. In terms of using such an SDK with ASP.NET Core, this exposure structure seems to be an issue because the runtime only allocates one single AppDomain, on the server-side, for all of the sessions collectively, and thus possibly multiple separate users, to share. If I do not have access to the source of this SDK and/or it cannot be changed, for purposes related to platform-agnosticism, how do I use the SDK successfully without only being able to store the data for one session at a time. Here is a simplified version of what I am working with:
Sample API:
public sealed class User
{
public static User ActiveUser { get; private set; }
public static int TotalLogCyclesThisSession { get; private set; } = 0
public string Username { get; internal set; }
private string Password { get; internal set; }
public string Name { get; internal set; }
public string AccessKey { get; }
public User(string username, string password)
{
/* Populate Instance Properties with Relevant Data */
ActiveUser = this;
}
public void Logout()
{
/* Clear Data from Settable Instance Properties */
ActiveUser = null;
TotalLogCyclesThisSession++;
}
}
Assume that the static variables are used elsewhere in the SDK as well.
So basically, if the API above were real, how would I use it in ASP.NET Core, so that every session would have it's own entire copy of the SDK to use, including session-specific static variables. If possible, I am looking for something like how it is possible to create a Blazor "Client" assembly, that has a new AppDomain for every session, and a "Server" assembly, though I understand that solution implemented by Blazor may not be applicable considering that it has a browser-local runtime active as well, whereas ASP.NET Core does not. Worst-case scenario, the API can be modified, but it still must be platform-agnostic to most extents. Thanks in advance for all help.
I have hard time to understand your problem. But I think the issue is some confusion about Blazor, but correct me if I'm wrong.
"create a Blazor "Client" assembly, that has a new AppDomain for every session"
Blazor is a client side SPA build on .NET and runs WebAssembly in the browser. So technically you don't have classic "sessions", no session cookie, nothing. And definitely not multiple ones because the whole context is in the browser memory which used by a single user. Think about Blazor like a JS SPA e.g. Angular or React App.
SPAs usually used with (stateless) APIs which can be authorized or not. You can do the same here. Just acquire a JWT token (OAuth2) and pass it to your API. Here is an example code which does something similar with a user object than you were asking: UserModel.cs and here is the Authorized client ApiClient.cs code.
If you want to think in "sessions" and the classic way. Technically the session is in the browser memory, SPA state. The lifetime of the session is the expiration time of the token. But it is the same with every SPA application no mater if it JS or Blazor.
I hope this helps and answers your question.
UPDATE: Since now Blazor is officially available with .NET Core 3.1 you should read about Microsoft Balzor Authentication.

Saving Data from phone to a OnceDrive account

Currently have no experience in programming and have been chucked in the deep end. I've currently made a simple UWP app that has a text box and a button. I want it so when I type in the text box and hit the button, the content from that text box is stored into a onedrive account as a text file. currently I have thee layout done and I've double clicked the button to enter the cose but I don't know what else to do and I havent had much luck with googling around. Any help or solutions? Thanks!
We can use OneDrive API to do this in UWP apps. This is a modern REST API and based on this API there are some OneDrive SDKs for different platforms to quickly start using the OneDrive API without the need to get into all the details of authentication, JSON parsing, HTTP connections and more. As you are using C#, OneDrive SDK for C# is strongly recommended.
For more info about how to use this SDK in UWP apps, please see Getting started and Documentation and resources on GitHub and also the article: Windows 10 - Implementing a UWP App with the Official OneDrive SDK.
Following is a simple sample. In the sample, I used OneDrive's App Folder, this folder is a dedicated, special folder for your app. It is typically named after your app, and is found in the Apps folder in the user's OneDrive. If you request the onedrive.appfolder permission scope and the user authorizes it, your app gets read and write access to this folder.
private async void Button_Click(object sender, RoutedEventArgs e)
{
var oneDriveClient = await OneDriveClientExtensions.GetAuthenticatedUniversalClient(new[] { "onedrive.appfolder" });
using (var contentStream = new MemoryStream(Encoding.UTF8.GetBytes(textBox.Text)))
{
var item = await oneDriveClient.Drive.Special.AppRoot.ItemWithPath("backup.txt").Content.Request().PutAsync<Item>(contentStream);
}
}

What's the best (easy&efficient) solution for asp.net developers to develop a mobile version of their existing website

I hope the question is self-describing.
I'm currently developing an asp.net website which uses a MS SqlServer database in the data layer.
And I was thinking what are my options to get a mobile version (most importantly supports BlackBerry and iPhone and hopefully every mobile device!) and when used on blackberry I want to be able to let it run at the BB's background.
I was thinking about asp.net mobile controls but the projects page seems like a dead/not-updated framework and not sure exactly if supports only windows mobiles or what!
Edit
Thank you for your questions, but they all covered my problem from only one respective .. I mean how this is going to let me use the BlackBerry Appliction options like letting my website run at the device background or sending notifications to my users!
This is mostly going to be a product of styling. Mobile websites work just like regular websites these days, except you want to use CSS and images that work well on a mobile device. You can use a product like 51 Degrees that will give you a bunch of information on what type of device is connected, so you can customize your output based on resolution or any number of other things if you so desire.
You could also try a book on mobile design, such as "Mobile Web Design" by Cameron Moll.
If you use ASP.Net MVC to create your app and create regular and mobile views. You can use jQuery Mobile to help with the mobile views too.
This question covers how to change your view based on the device type,
If you use WebForms, you can change your MasterPage depending on the browser thus giving you the ability to swap to mobile versions more easily:
protected void Page_PreInit(object sender, EventArgs e)
{
if (Request.Browser.IsMobileDevice)
MasterPageFile = "~/Mobile.Master";
}
Or use a Global.asax to redirect mobile requests completely:
void Session_Start(object sender, EventArgs e)
{
// Redirect mobile users to the mobile home page
HttpRequest httpRequest = HttpContext.Current.Request;
if (httpRequest.Browser.IsMobileDevice)
{
string path = httpRequest.Url.PathAndQuery;
bool isOnMobilePage = path.StartsWith("/Mobile/",
StringComparison.OrdinalIgnoreCase);
if (!isOnMobilePage)
{
string redirectTo = "~/Mobile/";
// Could also add special logic to redirect from certain
// recognized pages to the mobile equivalents of those
// pages (where they exist). For example,
// if (HttpContext.Current.Handler is UserRegistration)
// redirectTo = "~/Mobile/Register.aspx";
HttpContext.Current.Response.Redirect(redirectTo);
}
}
}
Either way read this article: http://www.asp.net/learn/whitepapers/add-mobile-pages-to-your-aspnet-web-forms-mvc-application
You don't really need to do anything special; Just create an alternative stylesheet that is optimized for 320px width viewport. You can serve this stylesheet through a separate stylesheet using the "media" attribute of the LINK element, or you can use CSS Media Queries within your mater stylesheet. Some relevant info:
http://googlewebmastercentral.blogspot.com/2011/02/making-websites-mobile-friendly.html
http://www.css3.info/preview/media-queries/
If you are using asp.net MVC be sure to check out
Web Application Toolkit for Mobile Web Applications

What are the available functions to send notifications to a Facebook user?

Currently I am using Codeplex's Facebook Developer Toolkit version 2 for my ASP.net Facebook application. I would like to be able to send notifications to a user's Inbox or wall of the application and was wondering what are the available functions to do that? If not in the API, then please provide example functions from the main Facebook library. This will help immensely. Thanks!
After a brief search I found an example of sending notifications using the toolkit:
facebook.Components.FacebookService fs
= new facebook.Components.FacebookService();
fs.ApplicationKey =
ConfigurationManager.AppSettings["APIKey"];
fs.Secret =
ConfigurationManager.AppSettings["Secret"];
string sessionKey =
dict["facebook_session_key"];
fs.SessionKey = sessionKey; fs.uid =
long.Parse(member.FacebookId);
fs.notifications.send(member.FacebookId,
"notification message");
(from: http://facebooktoolkit.codeplex.com/Thread/View.aspx?ThreadId=49876)
After looking through the Codeplex source it's clear that this sends a user-to-user notification, and therefore requires an active user session of the sender.
Codeplex does not appear to support app-to-user notifications which do not require a session, but adding this feature would be trivial. Add a type variable to the send method and set it accordingly based on the API documentation here: http://wiki.developers.facebook.com/index.php/Notifications.send
The source code for the notifications.send method in the Codeplex Developer Toolkit is here:
http://facebooktoolkit.codeplex.com/SourceControl/changeset/view/28656#233852
Please keep in mind that the Codeplex developer toolkit source code has not been updated in over 3 months. This means that it does not support many new Facebook API features and changes. You may want to browse the client library wiki page to find a library that is more up to date: http://wiki.developers.facebook.com/index.php/Client_Libraries

Categories