Flutter - How to get mac address without using package - macos

I Know how to get mac address by using get_mac flutter package
can anyone here tell me How to Get MAC Address without using any package in flutter

You can't really get the mac address for privacy concerns. Old versions of android may give it up, but new ones will just give you placeholders.

Use this method
class GetMacAddress {
static const MethodChannel _channel = const MethodChannel('get_mac');
static Future<String> get macAddress async {
final String macID = await _channel.invokeMethod('getMacAddress');
return macID;
}
}
Call it like this
print(GetMacAddress.macAddress);

Related

Problem with building paths iOS v MacOs in Xamarin Forms app

I have this code:
var myDocuments = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "Shared");
_rootPath = Path.Combine(myDocuments, "VisitsRota.MacOS");
_stylesPath = Path.Combine(_rootPath, "Styles");
_vrrDataFile = Path.Combine(_rootPath, "VisitsRotaData.xml");
// Read in the required data
vrrData = DeserializeFromXml<VisitsRotaData>(_vrrDataFile);
// Build list of month names. Should this property also have a private counterpart?
ListMonths = DateTimeFormatInfo.CurrentInfo.MonthNames.TakeWhile(m => m != String.Empty).ToList();
// Select the current month in the list
ListMonthsSelectedItem = DateTime.Now.ToString("MMMM");
string[] stylesArray = Directory.GetFiles(_stylesPath, "ElderlyInfirm-Schedule-*.xsl")
.Select(file => Path.GetFileName(file)).ToArray<string>();
On the Mac it runs as expect. But on the iOS simulator (which I am new to using) it raises an exception:
System.IO.DirectoryNotFoundException: Could not find a part of the
path
'/Users/xxxxxxx/Library/Developer/CoreSimulator/Devices/B812608B-8131-4386-B189-C646684A8965/data/Containers/Data/Application/EF23B73D-8D38-4F41-995E-FCAE13AE3035/Shared/VisitsRota.MacOS/Styles'.
How should I be able to replicate testing on my iOS build? if I use literal paths instead of Path.Combine etc. I do not have a problem.
I was able to resolve this. My related question / answer about resources helped.
In the comments to this question I was asked:
How are these files being deployed with your app?
That was the key!
I added a constructor to the AppDelegate class:
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public AppDelegate()
{
InstallApplicationFiles();
}
The linked Q & A has more info. By getting the app to copy the default files from the resources the issue of paths with the iOS simulator is resolved.

PostAsync hanging in Xamarin Forms works on emulator but hangs on actual Mobile phone

I have Xamarin Forms project where I'm trying to POST and GET data to/from a Web API but when I'm making an async/await call, it works on the emulator (not without its original problems!) but when I try it on my actual phone mobile (Samsung S8+), it just hangs indefinitely.
Note that I'm only concentrating on the Android part right now, not iOS, not that the problem should make any difference in either.
This is the code I'm using:
IDataService.cs
Task<TResponse> PostDataAsync<TRequest, TResponse>(string uri, TRequest data)
where TRequest : class
where TResponse : class;
DataService.cs:
public async Task<TResponse> PostDataAsync<TRequest, TResponse>(string
additionalUri, TRequest data)
where TRequest : class
where TResponse : class
{
return await WebClient
.PostData<TRequest, TResponse>
(string.Concat(this.Uri, additionalUri), data);
}
WebClient.cs
using (var client = new HttpClient())
{
var jsonData = JsonConvert.SerializeObject(data);
using (var response = await client.PostAsync(
uri,
new StringContent(jsonData,
Encoding.UTF8,
"application/json" )))
{
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TResponse>(content);
}
}
}
Method 1:
LoginPageViewModel.cs
public DelegateCommand SignInCommand => _signInCommand ??
(this._signInCommand = new DelegateCommand(SignInCommandAction));
private async void SignInCommandAction()
{
try
{
....
var user = await this._dataService
.PostDataAsync<LoginRequestDto,
LoginResponseDto>(#"Accounts/Login", loginRequestDto);
....
}
...
}
Method2:
LoginPageViewModel.cs
public DelegateCommand SignInCommand => _signInCommand ??
(this._signInCommand =
new DelegateCommand(async () => await SignInCommandAction()));
private async Task SignInCommandAction()
{
try
{
....
var user = await this._dataService
.PostDataAsync<LoginRequestDto,
LoginResponseDto>(#"Accounts/Login", loginRequestDto);
....
}
...
}
The PostDataAsync works with both methods when I call my local web API i.e. http://10.0.2.2/MyApp/api/ but both methods still hangs when calling external my web service from web provider i.e. http://myapp-123-site.atempurl.com/api/ which is a temp url for testing purpose.
The same apply to my GetDataAsync which is not demonstrated in question but I just thought I'd mention it.
Based on the above, you would think that my async/await code is correct since it works when calling the local web api but then what's causing it to hang when calling the remote web api.
As mentioned, I did enable my INTERNET permission in the manifest.
Any suggestions welcomed?
Thanks.
UPDATE-1:
Note that I've just tried to call a GET opertation within the same function and this is working in the emulator but hanging with the actual mobile.
using (var client = new HttpClient())
{
using (var response = await client.GetAsync(uri))
{
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return Newtonsoft.Json.JsonConvert
.DeserializeObject<TResponse>(content);
}
}
}
UPDATE-2:
This is somehow working and I have no idea why! The only thing that comes to mind is that I upgraded my libraries. This included PRISM which may have been at the source of the problem but I have no idea.
Sorry I can't provide more details. I could role back my code and try to see if it's hanging again but I just don't have the time to go and experiment some more considering the amount of time I've already spent on this. Sorry.
The requested url is an IP or a domain name.
If it is ip, only the IP of the public network can be accessed by devices on multiple network segments.
If it is a domain name, it needs to support the domain name resolution service.
If you do not have these environments for a while, you need the IP of the device and the IP of the server on the same network segment.
The PostDataAsync works with both methods when I call my local web API i.e. http://10.0.2.2/MyApp/api/ but both methods still hangs when calling external my web service from web provider i.e. http://myapp-123-site.atempurl.com/api/ which is a temp url for testing purpose.
From this phenomenon , the reason should be the temp url. From this domain name (myapp-123-site.atempurl.com) can not find the right local IP (10.0.2.2).And when you test in local network , I guess this will work.However the network of actual mobile can be not the same with local network , such as using 3G/4G network , then this will not working.

Xamarin.Form HttpClient for WebAPI failed in iOS

I'm creating Xamarin.Forms for Android and iOS using WebAPI as the web service. The whole thing went well in Android but I hit error in iOS, particularly when doing "JsonConvert.DeserializeObject". Below is the sample code
Model
public class WsObjTest
{
public string name { get; set; }
public string code { get; set; }
public string age { get; set; }
}
WebAPI
[HttpGet]
public WsObjTest HelloWorld()
{
WsObjTest wsObjTtest = new WsObjTest();
wsObjTtest.name = "John Doe";
wsObjTtest.code = "ABC123";
wsObjTtest.age = "18";
return wsObjTtest ;
}
In my Xamarin.Forms, this is how I call and deserialize the response
HttpClient client = new HttpClient();
var response = await client.GetStringAsync(apiURL.Replace("##action##", "HelloWorld"));
return JsonConvert.DeserializeObject<WsObjTest>(response); //ERROR HERE
I got the response as below, but error thrown at the return statement.
"{\"code\":\"ABC123\",\"name\":\"John Doe\",\"age\":\"18\"}"
The error message is below
Unhandled Exception:
System.MemberAccessException: Cannot create an abstract class:
System.Reflection.Emit.DynamicMethod occurred
I think it's because iOS doesn't support JIT compilation or dynamic methods of some sort? May I know if there is anyway to overcome this error? Thanks.
Based on https://learn.microsoft.com/en-us/xamarin/ios/internals/limitations, it is not possible to use any facilities that require code generation at runtime in Xamarin.iOS because code on the iPhone is statically compiled ahead of time instead of being compiled on demand by a JIT compiler.
What I have to do now is read and create the object manually as below. Should anybody got better solution please share with me.
HttpClient client = new HttpClient();
var response = await client.GetStringAsync(apiURL.Replace("##action##", "HelloWorld"));
JObject jObject = (JObject) JsonConvert.DeserializeObject(response);
WsObjTest wsObjTest = new WsObjTest();
wsObjParent.name = jObject["name"].ToString();
wsObjParent.code = jObject["code"].ToString();
wsObjParent.age = jObject["age"].ToString();
return wsObjTest;
Extracted from the link
Since the iOS kernel prevents an
application from generating code dynamically, Xamarin.iOS does not
support any form of dynamic code generation. These include:
The System.Reflection.Emit is not available.
No support for
System.Runtime.Remoting.
No support for creating types dynamically (no
Type.GetType ("MyType`1")), although looking up existing types
(Type.GetType ("System.String") for example, works just fine).
Reverse
callbacks must be registered with the runtime at compile time.
So the System.Reflection.Emit thus the error that I received.

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);
}

Retrieve manufacturer information from device that AIR app is running on

Does anybody know of a way to retrieve information about the manufacturer/model of the device that the AIR app is running on. The Capabilities class doesn't seem to cut it.
The solution only needs to work for AIR apps running on Windows desktops or laptops, and it needn't be a descriptive string of the model - as long as it is a piece of data unique to a specific model or device (or at least the specific manufacturer).
On Windows, it's possible to query the motherboard's serial number with WMIC, or Windows Management Instrumentation Command-line. Therefore, you can simply pass the command wmic baseboard get serialnumber as an argument to cmd.exe using flash.desktop.NativeProcess without the need for a Native Extension.
Since the AIR NativeProcess API is being used, you must use the Extended Desktop application profile and package your application with a native installer.
package
{
//Imports
import flash.display.Sprite;
import flash.display.StageScaleMode;
import flash.display.StageAlign;
import flash.desktop.NativeProcess;
import flash.desktop.NativeProcessStartupInfo;
import flash.events.ProgressEvent;
import flash.filesystem.File;
//Class
[SWF(width = "600", height = "250", frameRate = "60", backgroundColor = "0x000000")]
public class Main extends Sprite
{
//Constants
private static const MOTHERBOARD_SERIALNUMBER_COMMAND:String = "wmic baseboard get serialnumber";
//Properties
private var nativeProcess:NativeProcess;
//Constructor
public function Main():void
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
init();
}
//Init
private function init():void
{
if (!NativeProcess.isSupported)
{
throw new Error("Native Process is not supported.");
}
var file:File = new File("C:\\Windows\\System32\\cmd.exe");
var args:Vector.<String> = new Vector.<String>();
args.push("/c");
args.push(MOTHERBOARD_SERIALNUMBER_COMMAND);
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
nativeProcessStartupInfo.executable = file;
nativeProcessStartupInfo.arguments = args;
nativeProcess = new NativeProcess();
nativeProcess.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, outputDataEventHandler);
nativeProcess.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, outputErrorEventHandler);
nativeProcess.start(nativeProcessStartupInfo);
}
//Output Data Event Handler
private function outputDataEventHandler(event:ProgressEvent):void
{
var output:String = nativeProcess.standardOutput.readUTFBytes(nativeProcess.standardOutput.bytesAvailable);
nativeProcess.exit();
trace(output);
}
//Output Error Event Handler
private function outputErrorEventHandler(event:ProgressEvent):void
{
nativeProcess.exit();
throw new Error(event);
}
}
}
[EDIT]
Alternatively, if you would also like to retreive the motherboard's manufacturer, model number and serial number, you can update the string constant to this:
//Constants
private static const MOTHERBOARD_INFO:String = "wmic baseboard get product, manufacturer, serialnumber";
[EDIT 2]
I just learned that the following WMIC command will return the name, vendor and identifying number of a machine. It sounds exactly what your looking for:
//Constants
private static const CSPRODUCT_INFO:String = "wmic csproduct get name, vendor, identifyingNumber";
However, keep in mind that for custom built PCs, such as my own, this command returns nothing. Well, not exactly nothing, but instead of something typical like:
IdentifyingNumber Name Vendor
99L9891 Latitude D610 Dell Inc.
My custom build returns this:
IdentifyingNumber Name Vendor
System Serial Number System Product Name System manufacturer

Resources