How to use Microsoft Graph Toolkit with SPFX 1.15.2 - spfx

I created a new SPFX solution with yo. Then I followed this guide:
Installed with
npm install #microsoft/mgt-spfx
and
npm install #microsoft/mgt-react
Then I changed the init method in the webpart.ts file to following code
protected onInit(): Promise<void> {
if (!Providers.globalProvider) {
Providers.globalProvider = new SharePointProvider(this.context);
}
return super.onInit();
}
Added the import
import { SharePointProvider, Providers } from '#microsoft/mgt-spfx';
In the tsx component file I changed the render to
public render(): React.ReactElement<IPeoplePickerTestProps> {
return (
<div>
Test
<Person personQuery="me" view={ViewType.image}></Person>
</div>
);
}
and added the import
import { Person, ViewType } from '#microsoft/mgt-react/dist/es6';
Then I uploaded the latest toolkit spfx package (got it here) to the app catalog (deployed to all sites), builded my solution (gulp bundle --ship, gulp package-solution --ship) and uploaded it to the app catalog. Created a new site collection and installed my solution. Its not working at all. There is nothing rendered except the text "Test". In the console I can see following error which does not really help me:
Toolkit version: 2.6.1
SPFX version: 1.15.2
Tested on different tenants.

I got similar issue, try importing from
#microsoft/mgt-react/dist/es6/spfx
so:
import { Person } from '#microsoft/mgt-react/dist/es6/spfx';
import { ViewType } from '#microsoft/mgt-spfx';
Hope that helps

Related

'fileSystemModule' was not found in '#nativescript/core'

Trying to write to a local file in Android.
Tried import {fileSystemModule} from "#nativescript/core"; but get error 'fileSystemModule' was not found in '#nativescript/core'.
Have also tried import {fileSystemModule} from "#nativescript/core/file-system" but it doesn't exist. I'm using plain Javascript.
Nativescript 8.0.2
The import paths are updated in the recent versions of NativeScript. You can access these directly now without having to go through fileSystemModule. See code below:
import { knownFolders, File, Folder } from '#nativescript/core';
To write to a local file using the latest NativeScript would look like this:
writeToFile(): void {
const folder = knownFolders.documents().getFolder(FOLDER_NAME);
const file = folder.getFile(FILE_NAME.txt);
file.writeText(SOME_STRING_TO_WRITE_TO_FILE);
}
To write to an accessible location in Android, you can use the following:
writeToFile(): void {
const folderPath = path.join(android.os.Environment.getExternalStorageDirectory().getAbsolutePath().toString())
const folder = Folder.fromPath(folderPath);
const file = folder.getFile(FILE_NAME.txt);
file.writeText(SOME_STRING_TO_WRITE_TO_FILE);
}

FilePicker class cannot be found in Xamarin project

I'm creating a Xamarin forms app which enables user uploads. I have installed the latest version of the Xamarin.Essentials package but the classes and methods which I would expect to be available cannot be found. I can move ahead with the xamarin.plugins.filepicker package but this is not well documented and I would prefer to use the standard library. Any assistance with this would be greatly appreciated! The default is below.
'''
async Task<FileResult> PickAndShow(PickOptions options)
{
try
{
var result = await FilePicker.PickAsync();
if (result != null)
{
Text = $"File Name: {result.FileName}";
if (result.FileName.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) ||
result.FileName.EndsWith("png", StringComparison.OrdinalIgnoreCase))
{
var stream = await result.OpenReadAsync();
Image = ImageSource.FromStream(() => stream);
}
}
}
catch (Exception ex)
{
// The user canceled or something went wrong
}
}
'''
For the Xamarin.Essentials package, update to the latest version on both Xamarin.Form NuGet Package and Android NuGet Package. After that you could fix the errors like below.
Error CS0246 The type or namespace name 'PickOptions' could not be found (are you
missing a using directive or an assembly reference?)
For the usage of Xamarin.Essentials: File Picker, you could check the MS document.
https://learn.microsoft.com/en-us/xamarin/essentials/file-picker?tabs=android
If you wanna the source file, you could download from the link below. https://github.com/xamarin/Essentials/tree/main/Xamarin.Essentials/FilePicker

How to download and open a file with NS 6.0

I'have migrate to NativeScript 6.0 and need some help on how to download and open a file with Android support lib (AndroidX) in the Downloads folder.
Actually, in NS 5.x, i have used FileProvider from Android support lib (android.support.v4.content.FileProvider) and works great. After the migration, using (androidx.core.content.FileProvider), i have errors opening the App.
But in Android docs, i can't find any method or information to migrate the code for Native download and Open (Downloads Folder).
Previous Method:
private openFile(fileName: string, mimeType: string, extension: string) {
try {
if (isAndroid) {
const intent = new android.content.Intent(android.content.Intent.ACTION_VIEW);
const context = applicationModule.android.context;
console.log("android.ctx=", context);
const nativeFile = new java.io.File(fileName);
console.log("nativeFile=", nativeFile);
const uri = android.support.v4.content.FileProvider.getUriForFile(context, "com.otisw.gescon.app.provider", nativeFile);
intent.setDataAndType(uri, mimeType);
intent.addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION);
const choosedIntent = android.content.Intent.createChooser(intent, "Open file...");
console.log("choosedIntent=>", choosedIntent);
context.startActivity(choosedIntent);
} else {
// const documents = fs.knownFolders.currentApp();
// const file = this.documents.getFile(fileName);
const open = utils.ios.openFile(fileName);
}
} catch (e) {
console.log(e);
}
}
Tried:
private openFile(fileName: string, mimeType: string, extension: string) {
try {
if (isAndroid) {
const intent = androidx.core.content.IntentCompat.makeMainSelectorActivity(
"android.content.Intent.ACTION_VIEW",
"??"
);
File reference.d.ts:
/// <reference path="./node_modules/tns-core-modules/tns-core-modules.d.ts" />
/// <reference path="./node_modules/tns-platform-declarations/ios.d.ts" />
/// <reference path="./node_modules/tns-platform-declarations/android/androidx-26.d.ts" />
Does anyone tries to upgrade the code for Download and Open from NativeScript to new AndroidX or knows a workaround to do this ?
Thanks!
You will have to use androidx.core.content.FileProvider on AndoridX and android.support.v4.content.FileProvider in lower versions.
With the release of Android 9.0 (API level 28) there is a new version
of the support library called AndroidX which is part of Jetpack. The
AndroidX library contains the existing support library and also
includes the latest Jetpack components.
You can continue to use the support library. Historical artifacts
(those versioned 27 and earlier, and packaged as android.support.*)
will remain available on Google Maven. However, all new library
development will occur in the AndroidX library.
We recommend using the AndroidX libraries in all new projects. You
should also consider migrating existing projects to AndroidX as well.

Auto-updates to Electron

I'm looking to deploy an auto-update feature to an Electron installation that I have, however I am finding it difficult to find any resources on the web.
I've built a self contained application using Adobe Air before and it seemed to be a lot easier writing update code that effectively checked a url and automatically downloaded and installed the update across Windows and MAC OSX.
I am currently using the electron-boilerplate for ease of build.
I have a few questions:
How do I debug the auto update feature? Do I setup a local connection and test through that using a local Node server or can I use any web server?
In terms of signing the application I am only looking to run apps on MAC OSX and particularly Windows. Do I have to sign the applications in order to run auto-updates? (I managed to do this with Adobe Air using a local certificate.
Are there any good resources that detail how to implement the auto-update feature? As I'm having difficulty finding some good documentation on how to do this.
I am also new to Electron but I think there is no simple auto-update from electron-boilerplate (which I also use). Electron's auto-updater uses Squirrel.Windows installer which you also need to implement into your solution in order to use it.
I am currently trying to use this:
https://www.npmjs.com/package/electron-installer-squirrel-windows
And more info can be found here:
https://github.com/atom/electron/blob/master/docs/api/auto-updater.md
https://github.com/squirrel/squirrel.windows
EDIT: I just opened the project to try it for a while and it looks it works. Its pretty straightforward. These are pieces from my gulpfile.
In current configuration, I use electron-packager to create a package.
var packager = require('electron-packager')
var createPackage = function () {
var deferred = Q.defer();
packager({
//OPTIONS
}, function done(err, appPath) {
if (err) {
gulpUtil.log(err);
}
deferred.resolve();
});
return deferred.promise;
};
Then I create an installer with electron-installer-squirrel-windows.
var squirrelBuilder = require('electron-installer-squirrel-windows');
var createInstaller = function () {
var deferred = Q.defer();
squirrelBuilder({
// OPTIONS
}, function (err) {
if (err)
gulpUtil.log(err);
deferred.resolve();
});
return deferred.promise;
}
Also you need to add some code for the Squirrel to your electron background/main code. I used a template electron-squirrel-startup.
if(require('electron-squirrel-startup')) return;
The whole thing is described on the electron-installer-squirrel-windows npm documentation mentioned above. Looks like the bit of documentation is enough to make it start.
Now I am working on with electron branding through Squirrel and with creating appropriate gulp scripts for automation.
You could also use standard Electron's autoUpdater module on OS X and my simple port of it for Windows: https://www.npmjs.com/package/electron-windows-updater
I followed this tutorial and got it working with my electron app although it needs to be signed to work so you would need:
certificateFile: './path/to/cert.pfx'
In the task config.
and:
"build": {
"win": {
"certificateFile": "./path/to/cert.pfx",
"certificatePassword": "password"
}
},
In the package.json
Are there any good resources that detail how to implement the auto-update feature? As I'm having difficulty finding some good documentation on how to do this.
You don't have to implement it by yourself. You can use the provided autoUpdater by Electron and just set a feedUrl. You need a server that provides the update information compliant to the Squirrel protocol.
There are a couple of self-hosted ones (https://electronjs.org/docs/tutorial/updates#deploying-an-update-server) or a hosted service like https://www.update.rocks
Question 1:
I use Postman to validate that my auto-update server URLs return the response I am expecting. When I know that the URLs provide the expected results, I know I can use those URLs within the Electron's Auto Updater of my Application.
Example of testing Mac endpoint with Postman:
Request:
https://my-server.com/api/macupdates/checkforupdate.php?appversion=1.0.5&cpuarchitecture=x64
JSON Response when there is an update available:
{
"url": "https:/my-server.com/updates/darwin/x64/my-electron=app-x64-1.1.0.zip",
"name": "1.1.0",
"pub_date": "2021-07-03T15:17:12+00:00"
}
Question 2:
Yes, your Electron App must be code signed to use the auto-update feature on Mac. On Windows I'm not sure because my Windows Electron app is code signed and I did not try without it. Though it is recommended that you sign your app even if the auto-update could work without it (not only for security reasons but mainly because otherwise your users will get scary danger warnings from Windows when they install your app for the first time and they might just delete it right away).
Question 3:
For good documentation, you should start with the official Electron Auto Updater documentation, as of 2021-07-07 it is really good.
The hard part, is figuring out how to make things work for Mac. For Windows it's a matter of minutes and you are done. In fact...
For Windows auto-update, it is easy to setup - you just have to put the RELEASES and nupkg files on a server and then use that URL as the FeedURL within your Electron App's autoUpdater. So if your app's update files are located at https://my-server.com/updates/win32/x64/ - you would point the Electron Auto Updater to that URL, that's it.
For Mac auto-update, you need to manually specify the absolute URL of the latest Electron App .zip file to the Electron autoUpdater. So, in order to make the Mac autoUpdater work, you will need to have a way to get a JSON response in a very specific format. Sadly, you can't just put your Electron App's files on your server and expect it to work with Mac just like that. Instead, the autoUpdater needs a URL that will return the aforementioned JSON response. So to do that, you need to pass Electron's Auto Updater feedURL the URL that will be able to return this expected kind of JSON response.
The way you achieve this can be anything but I use PHP just because that's the server I already paid for.
So in summary, with Mac, even if your files are located at https://my-server.com/updates/darwin/x64/ - you will not provide that URL to Electron's Auto Updater FeedURL. Instead will provide another URL which returns the expected JSON response.
Here's an example of my main.js file for the Electron main process of my App:
// main.js (Electron main process)
function registerAutoUpdater() {
const appVersion = app.getVersion();
const os = require('os');
const cpuArchitecture = os.arch();
const domain = 'https://my-server.com';
const windowsURL = `${domain}/updates/win32/x64`;
const macURL = `${domain}/api/macupdates/checkforupdate.php?appversion=${appVersion}&cpuarchitecture=${cpuArchitecture}`;
//init the autoUpdater with proper update feed URL
const autoUpdateURL = `${isMac ? macURL : windowsURL}`;
autoUpdater.setFeedURL({url: autoUpdateURL});
log.info('Registered autoUpdateURL = ' + (isMac ? 'macURL' : 'windowsURL'));
//initial checkForUpdates
autoUpdater.checkForUpdates();
//Automatic 2-hours interval loop checkForUpdates
setInterval(() => {
autoUpdater.checkForUpdates();
}, 7200000);
}
And here's an example of the checkforupdate.php file that returns the expected JSON response back to the Electron Auto Updater:
<?php
//FD Electron App Mac auto update API endpoint.
// The way Squirrel.Mac works is by checking a given API endpoint to see if there is a new version.
// If there is no new version, the endpoint should return HTTP 204. If there is a new version,
// however, it will expect a HTTP 200 JSON-formatted response, containing a url to a .zip file:
// https://github.com/Squirrel/Squirrel.Mac#server-support
$clientAppVersion = $_GET["appversion"] ?? null;
if (!isValidVersionString($clientAppVersion)) {
http_response_code(204);
exit();
}
$clientCpuArchitecture = $_GET["cpuarchitecture"] ?? null;
$latestVersionInfo = getLatestVersionInfo($clientAppVersion, $clientCpuArchitecture);
if (!isset($latestVersionInfo["versionNumber"])) {
http_response_code(204);
exit();
}
// Real logic starts here when basics did not fail
$isUpdateVailable = isUpdateAvailable($clientAppVersion, $latestVersionInfo["versionNumber"]);
if ($isUpdateVailable) {
http_response_code(200);
header('Content-Type: application/json;charset=utf-8');
$jsonResponse = array(
"url" => $latestVersionInfo["directZipFileURL"],
"name" => $latestVersionInfo["versionNumber"],
"pub_date" => date('c', $latestVersionInfo["createdAtUnixTimeStamp"]),
);
echo json_encode($jsonResponse);
} else {
//no update: must respond with a status code of 204 No Content.
http_response_code(204);
}
exit();
// End of execution.
// Everything bellow here are function declarations.
function getLatestVersionInfo($clientAppVersion, $clientCpuArchitecture): array {
// override path if client requests an arm64 build
if ($clientCpuArchitecture === 'arm64') {
$directory = "../../updates/darwin/arm64/";
$baseUrl = "https://my-server.com/updates/darwin/arm64/";
} else if (!$clientCpuArchitecture || $clientCpuArchitecture === 'x64') {
$directory = "../../updates/darwin/";
$baseUrl = "https://my-server.com/updates/darwin/";
}
// default name with version 0.0.0 avoids failing
$latestVersionFileName = "Finance D - Tenue de livres-darwin-x64-0.0.0.zip";
$arrayOfFiles = scandir($directory);
foreach ($arrayOfFiles as $file) {
if (is_file($directory . $file)) {
$serverFileVersion = getVersionNumberFromFileName($file);
if (isVersionNumberGreater($serverFileVersion, $clientAppVersion)) {
$latestVersionFileName = $file;
}
}
}
return array(
"versionNumber" => getVersionNumberFromFileName($latestVersionFileName),
"directZipFileURL" => $baseUrl . rawurlencode($latestVersionFileName),
"createdAtUnixTimeStamp" => filemtime(realpath($directory . $latestVersionFileName))
);
}
function isUpdateAvailable($clientVersion, $serverVersion): bool {
return
isValidVersionString($clientVersion) &&
isValidVersionString($serverVersion) &&
isVersionNumberGreater($serverVersion, $clientVersion);
}
function getVersionNumberFromFileName($fileName) {
// extract the version number with regEx replacement
return preg_replace("/Finance D - Tenue de livres-darwin-(x64|arm64)-|\.zip/", "", $fileName);
}
function removeAllNonDigits($semanticVersionString) {
// use regex replacement to keep only numeric values in the semantic version string
return preg_replace("/\D+/", "", $semanticVersionString);
}
function isVersionNumberGreater($serverFileVersion, $clientFileVersion): bool {
// receives two semantic versions (1.0.4) and compares their numeric value (104)
// true when server version is greater than client version (105 > 104)
return removeAllNonDigits($serverFileVersion) > removeAllNonDigits($clientFileVersion);
}
function isValidVersionString($versionString) {
// true when matches semantic version numbering: 0.0.0
return preg_match("/\d\.\d\.\d/", $versionString);
}

ServiceStack Caching Working in VS2012, but not in Xamarin Studio 4.2.3 (build 60)

My application makes an AJAX call to the route /{Lang}/cook to retrieve an rendered Razor partial.
In VS2012 via Cassini, I am able to get a response;
However, in Xamarin 4.2.3 (build 60), I get the following error:
Failed to load resource: the server responded with a status of 405 (NotImplementedException)
http://127.0.0.1:8080/en-us/cook
Any ideas why the route works in one IDE, but not the other?
I am using Service Stack 4.0.12.0, with In-Memory caching.
The system is being run in free/evaluation mode.
Here is a service method that uses caching:
Inside public class ScenarioService: Service
[DefaultView("cook")]
public object Get(CookScenario request)
{
var cacheKey = GetCacheKey ("cook", request.Lang);
return base.Request.ToOptimizedResultUsingCache (base.Cache, cacheKey, () => {
CookScenarioResponse response = LoadJson<CookScenarioResponse>(request.Lang, "cook");
return response;
});
}
Inside AppHost.cs
public override void Configure(Funq.Container container)
{
//Set JSON web services to return idiomatic JSON camelCase properties
ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;
//Configure User Defined REST Paths
container.Register<ICacheClient>(new MemoryCacheClient());
this.GlobalRequestFilters.Add((request, response, requestDto) =>
{
var localizedReq = requestDto as LocalizedRequest;
if (localizedReq != null)
{
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture = new CultureInfo(localizedReq.Lang);
}
});
Plugins.Add(new RazorFormat());
}
EDIT:
I tried removing the ToOptimizedResultUsingCaching and the service for "/en-us/cook" worked fine; so, the issue is definitely an issue with the ToOptimizedResultUsingCaching in Service Stack 4.0.12.0 on Xamarin Studio 4.2.3 (build 60) on a Mac OS 10.7.5.
Here is the mono version info:
Mono JIT compiler version 3.2.6 ((no/9b58377 Thu Jan 16 17:49:56 EST 2014)
Resolution 3/27/2014 1PM PST
After I grabbed the pre-release version (4.0.16) of ServiceStack I was able to confirm that in-memory caching now works on Xamarin 4.2.3 (build 60) against my Macbook pro laptop (OSX 10.7.5).
Thanks again for the help!
I believe the error you are seeing is a shortcoming of Mono, and the XSP/fastcgi-server-4 host which is used by Xamarin Studio.
I previously experience the same problem with ToOptimizedResult/ToOptimizedResultUsingCache methods not working because they rely on a call to System.Web.HttpContextWrapper.GetService which has not been implemented in Mono.
See here for the relevant Mono source code:
public class HttpContextWrapper : HttpContextBase
{
...
[MonoTODO]
public override object GetService (Type serviceType)
{
throw new NotImplementedException ();
}
}
I found the only way to work around this issue with Mono was to use a Self Hosted ServiceStack application because it uses System.Net.HttpListener which does not suffer from this issue. See my previous answer on this issue which describes this in more detail.
Fix:
A commit to ServiceStack has been made to address this issue, and it will be fixed in version 4.0.16

Resources