2022年1月3日 星期一

用 Scaffold-DbContext 指令時遇到「Login failed. The login is from an untrusted domain and cannot be used with Integrated authentication.」錯誤訊息!?

 呃,應該是說之前為什麼沒遇到這問題吧

因為之前用Scaffold建置EF時是連到本機的資料庫,而這次是連接remote sql server的資料庫

所以原先的 connection string --「"Server=遠端DBIP;Database=資料庫;Trusted_Connection=True;"」

要改成「"Server=遠端DBIP;Database=資料庫;;User ID=帳號;Password=登入密碼;Trusted_Connection=True;"」 是的,題就出在trusted connection

以上參考這篇

老句話,要執行Scaffold指令前別忘了備份一下專案(最少DBcontext檔要備份)

新年快樂

2021年12月23日 星期四

Xamarin.form 如果你用的是shell架構,如何 handle "back button"事件

 最近因為要在back (< ) button事件中加上動畫(沒辦法,資料總是要從網路下載)

真的是試破頭殼了

其原因是因為我忘了是套用了shell架構,所以content page上方的back button點擊時是不會觸發OnBackButtonPressed 事件的 (但如果是用螢幕下方的 "<" button,是會觸發這個事件的)

好在先進有類似的情境(如,回上一頁時要先做確認的動作)

這時就可以參考這篇文章了

在此介紹給xamarin form的同好

一起加油吧!!

2021年12月21日 星期二

OSM圖資概念相關連結

 osm的技術官網:

https://wiki.openstreetmap.org/wiki/API

在的網頁內嵌入osm,ref https://noob.tw/openstreetmap/

tile的觀念: http://blog.changyy.org/2012/05/openstreetmap-api.html 

(觀念很重要,因為日後從緯經度推算tile一定會用到)

就static map而言,就應該是緯經度推算成tile,所以請參考以下網址

https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames


有了tile,那推算出大致位置的方式,就用比例去推算了

參考這則討論


如果,你真的只是要產出幾張圖,那就到

https://www.openstreetmap.org 用右手側工具區有個「分享」icon 
就可把你目前看到的地圖輸出成png/jpeg/pdv/svg 了
(有了底圖了,那在上面加些圖示標記就是你的事了)
大不了時辰到了,不,時間到了,再叫值日生來這下載圖片來用
(如果卡骨力一點,你直接用browser的debuger去看reuqest送出什麼,自己包api也行)

如果貴公司的用量(請求數)每月不超過15000次請求的話,那就去MapQuest註冊API來用吧
https://business.mapquest.com/pricing-plans


O.S.明明專案只是要幾張可能不會異動的地圖,居然花了半個月來study這東西,沒辦法,Google map是要錢的啊....





2021年12月10日 星期五

how to resize an existing vdi disk in vbox + resize an Ubuntu 18.04/20.04 LVM disk

step 1..to resize vdi of VBox ,please refer to :

https://www.howtogeek.com/124622/how-to-enlarge-a-virtual-machines-disk-in-virtualbox-or-vmware/

 File > Virtual Media Manager in the main VirtualBox window

step2 .extend to 100 free space.

ref:
https://kb.vander.host/operating-systems/how-to-resize-an-ubuntu-18-04-lvm-disk/

用sudo -i  (root身份去執行)

其中,

-------------------------------------

user@server:~# parted
GNU Parted 3.2
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) resizepart
Partition number? 3
End? [26.8GB]?   <--這地方要自己輸入,不能只按enter,
因為parted 是不知道你有多少空間可以用 
(在上一個指令「fdisk -l」裡「Disk /dev/sda: 30.25 GiB」就是我們可用(用步驟1改的vdi大小)的大小,
所以請在此填入32.25G)
(parted) quit
Information: You may need to update /etc/fstab.
----------------------------------------------
接著用
 pvresize /dev/sda3
上述才會生效
又,我是直接用「lvextend -l +100%FREE /dev/mapper/ubuntu--vg-ubuntu--lv」
確定它出現以下訊息
------------------------------------------
 Size of logical volume ubuntu-vg/ubuntu-lv changed from <9.00 GiB (2303 extents) to 29.24 GiB (7486 extents).
  Logical volume ubuntu-vg/ubuntu-lv successfully resized.
---------------------------------------------
才是正確地完成了lvextend指令,
當然別忘了之後的「resize2fs /dev/mapper/ubuntu--vg-ubuntu--lv」指令,再用df -h 確定LVM有擴充
才是真的功德圓滿了
以上,加油了!!

------------------------------------

apt-update時遇到「Err:1 http://tw.archive.ubuntu.com/ubuntu focal InRelease Splitting up /var/lib/apt/lists/tw.archive.ubuntu.com_ubuntu_dists_focal_InRelease into data and signature failed」錯誤訊息

 最近在用ubuntu 安裝sql server 時出現以問題
-------apt update後----
Hit:1 http://tw.archive.ubuntu.com/ubuntu focal InRelease
Hit:2 http://tw.archive.ubuntu.com/ubuntu focal-updates InRelease
Hit:3 http://tw.archive.ubuntu.com/ubuntu focal-backports InRelease
Hit:4 http://tw.archive.ubuntu.com/ubuntu focal-security InRelease
Err:1 http://tw.archive.ubuntu.com/ubuntu focal InRelease
  Splitting up /var/lib/apt/lists/tw.archive.ubuntu.com_ubuntu_dists_focal_InRelease into data and signature failed
Err:2 http://tw.archive.ubuntu.com/ubuntu focal-updates InRelease
  Splitting up /var/lib/apt/lists/tw.archive.ubuntu.com_ubuntu_dists_focal-updates_InRelease into data and signature failed
Err:3 http://tw.archive.ubuntu.com/ubuntu focal-backports InRelease
  Splitting up /var/lib/apt/lists/tw.archive.ubuntu.com_ubuntu_dists_focal-backports_InRelease into data and signature failed
------------------------------------------
google了一下,有些解法
1.直接用「apt-get clean」在這討論的內容
2.dhcp問題  ,參考這裡
我是用apt-get clean解決的
為了怕日後遇到又要查很多,特此誌之

2021年12月1日 星期三

Dictionary to Dynamic class object

在轉成json時常常有動態屬性的必要,這時dictionary是很需要的

以下是個不錯的extension,來源在此 

直接copy paste 了

-----------------------------------------------

public static class Extensions
{
    public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> items)
    {
        foreach (var item in items)
        {
            collection.Add(item);
        }
    }

    public static dynamic ToDynamicObject(this IDictionary<string, object> source)
    {
        ICollection<KeyValuePair<string, object>> someObject = new ExpandoObject();
        someObject.AddRange(source);
        return someObject;
    }
}
----------------------------------------------

很好用,推薦給c# codder們

2021年11月30日 星期二

Ubuntu 20.04+ asp.net core webapi + Nginx 速戰速決

---這裡沒有什麼原理解說(因為我也不懂),如果先進要補充指正的....麻煩鞭小力一點-----

先安裝.net sdk & runtime環境

 ref : https://tecadmin.net/how-to-install-net-core-on-ubuntu-20-04/

裝.net之後,移駕到我們複製上去的webapi專案publish資料夾裡

用「dotnet xxxx.dll」啟動那個webapi (以vs2019提供的weatherforecase範例為例)

然後用curl http://locahost:5000/weatherforecast 測看看.net core runtime & web api有沒有起來

有出現該有的json資料,有再進行Nginx安裝

接著安裝nginx

install nginx,別忘了先去找到80 port的服務先關掉.(指令 sudo netstat -peanut|grep ":80 " )

之後.安裝nginx

----------------------

sudo apt install nginx

---------------------------

---start nginx by command---


sudo systemctl start nginx

----------------------------------

//用localhost檢查Nginx有沒有起來

因為我們新的環境允許對個別site做port&SSL 設定,

所以我們只要在nginx加個site config檔就可以

但是cert & pem是一定要做,參考黑暗大大的好文

https://blog.darkthread.net/blog/aspnetcore-with-nginx/

----------因為private目錄已經有了,所以要另外定義一個資料夾-----------------------

sudo mkdir /etc/ssl/private4ngix

sudo chmod 700 /etc/ssl/private4ngix

//以下的360是天數

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private4ngix/nginx-selfsigned.key -out /etc/ssl/certs/nginx-selfsigned.crt

sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048

------------------------------------------

---要把port 80錯開(不然其他用到80port的東西會起不來),

因為不想一一說明,我直接給你.conf檔,日後有需要再行調整/新增
------------/etc/nginx/nginx.conf-----------------------------------------------------
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
worker_connections 768;
# multi_accept on;
}

http {

##
# Basic Settings
##

sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;

# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
        include /etc/nginx/proxy.conf;

include /etc/nginx/mime.types;
default_type application/octet-stream;

##
# SSL Settings
##

ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;

##
# Logging Settings
##

access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;

##
# Gzip Settings
##

gzip on;

# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

##
# Virtual Host Configs
##

include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}


#mail {
# # See sample authentication script at:
# # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
# 
# # auth_http localhost/auth.php;
# # pop3_capabilities "TOP" "USER";
# # imap_capabilities "IMAP4rev1" "UIDPLUS";
# 
# server {
# listen     localhost:110;
# protocol   pop3;
# proxy      on;
# }
# 
# server {
# listen     localhost:143;
# protocol   imap;
# proxy      on;
# }
#}
---------------------------------------------------------------------------
------------/ext/nginx/proxy.conf---------------------------------
proxy_redirect          off;
proxy_set_header        Host $host;
proxy_set_header        X-Real-IP $remote_addr;
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header        X-Forwarded-Proto $scheme;
client_max_body_size    10m;
client_body_buffer_size 128k;
proxy_connect_timeout   90;
proxy_send_timeout      90;
proxy_read_timeout      90;
proxy_buffers           32 4k;
-----------------------------------------------------------
把預設的nginx port80切到9090,因為port 80已經被佔用了
-----------------/ext/nginx/sites-enable/default----------------------
##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
listen 9090 default_server;
listen [::]:9090 default_server;

# SSL configuration
#
# listen 443 ssl default_server;
# listen [::]:443 ssl default_server;
#
# Note: You should disable gzip for SSL traffic.
# See: https://bugs.debian.org/773332
#
# Read up on ssl_ciphers to ensure a secure configuration.
# See: https://bugs.debian.org/765782
#
# Self signed certs generated by the ssl-cert package
# Don't use them in a production server!
#
# include snippets/snakeoil.conf;

root /var/www/html;

# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;

server_name abc.mycompany.com;

location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}

# pass PHP scripts to FastCGI server
#
#location ~ \.php$ {
# include snippets/fastcgi-php.conf;
#
# # With php-fpm (or other unix sockets):
# fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
# # With php-cgi (or other tcp sockets):
# fastcgi_pass 127.0.0.1:9000;
#}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}


# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
# listen 80;
# listen [::]:80;
#
# server_name example.com;
#
# root /var/www/example.com;
# index index.html;
#
# location / {
# try_files $uri $uri/ =404;
# }
#}
------------------------------------------------------------------
同理,因為port 443也被佔用了,所以我們的web api也要改到別的port,下例為https://網站IP:4430/....
--------/etc/nginx/sites-enable/api_port_4430.conf---------------
日後新的專案請比照新增這檔案就可以了,當然asp.net webapi的launchSettings.json裡的port也要錯開就是了
----------------------------------------------------------------------------
server {
    listen 4430 http2 ssl;
    listen [::]:4430 http2 ssl;

    server_name abc.mycompany.com;

    ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;
    ssl_certificate_key /etc/ssl/private4ngix/nginx-selfsigned.key;
    ssl_dhparam /etc/ssl/certs/dhparam.pem;

    underscores_in_headers on;

    location / {
        proxy_pass_request_headers on;
        proxy_pass         http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
        proxy_redirect     http://localhost:5000/ http://$host:$server_port;
    }
}
-------------------------------------------------
asp.net webapi方面,因應Nginx proxy forward需要,請在setup做以下調整
---------------------------------------------------------------
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {

  if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) {
                app.UseForwardedHeaders(new ForwardedHeadersOptions {
                    ForwardedHeaders=ForwardedHeaders.XForwardedFor|ForwardedHeaders.XForwardedProto,
                    ForwardedForHeaderName="CF-CONNECTING-IP"
                });
            }
//以下照舊...
--------------------------------------------------
別忘了sudo ufw allow 剛才那些新開的port.
其他(把dotnet xxxx.dll設定做service,以便開機啟動等)
請參考
https://docs.microsoft.com/zh-tw/aspnet/core/host-and-deploy/linux-nginx?view=aspnetcore-6.0
之「建立服務檔」單元
本文多數資訊是來自
特此誌謝

(以上範例皆為虛構,如有雷同純屬故意調工)



2021年11月19日 星期五

for Xanarin.Form : 「處理中」的過場提示訊息

 最近想說MAUI快拍板定案了,那麼Xamarn.Form 這幾年經過各位大神補完下來也應該夠成熟好用了.

真正是「明仔在的窟仔,咱微軟給你挖便便啊」..呃.不是啦,是「明仔在的氣力,咱Xamarin給你傳便便啊」(碼你個B~),所以下個案子,可以考慮用xamarin.form加速開發

我個人最常在畫面會用到的東西是那些過場畫面效果元件,像是「處理中....」這類的東西,所以今天就小小分享一下實作及效果的差異 

(先不說  DisplaySnackBarAsync ,如果你不要自帶動畫的話,這可以直接套用,參考這個影音教學)

先開箱Popup元件,這東西不錯用,日後會非常倚重它,參考以下教學網址
Pass Data From and To Popups with Xamarin Community Toolkit
直接上code

-----ProcessingPopup.xmal--------------------------

<?xml version="1.0" encoding="UTF-8" ?>
<xct:Popup
    xmlns="http://xamarin.com/schemas/2014/forms"

    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
    xmlns:local="clr-namespace:LoraWanApp.Views.PopUp"

    x:TypeArguments="local:PopupResult"
    Size="300,150"
    IsLightDismissEnabled="False"
    x:Class="mycompany.Views.PopUp.ProcessingPopup">
    <StackLayout>

        <Label x:Name="myLabel"  Text="Porcessing......." VerticalOptions="CenterAndExpand"                    HorizontalOptions="CenterAndExpand"/>

    </StackLayout>
</xct:Popup>

----ProcessingPopup.xmal.cs------------------

//Clasable介面沒什麼東西,就只有一個DoClose函數罷了

public class PopupResult {
        public string ReturnData { get; set; }
 }
public partial class ProcessingPopup : Popup<PopupResult>, Closable {
        private PopupResult _result;
        int count = 1;
        bool toLoop = true;
        public ProcessingPopup(PopupResult result) {
            InitializeComponent();
            _result=result;

           //順便學會在form裡用執行緒的技巧
          //UI thread請參考這裡(楓花雪岳)更詳細說明

            Device.BeginInvokeOnMainThread(async () => {
                while(toLoop) {
                    if(count>5)
                        count=1;
                    myLabel.Text="Please Wait"+".....".Substring(0, count);
                    count++;
                    await Task.Delay(500);
                }
                //DoClose();
            });
    }
        public async void DoClose() {
            toLoop=false;
            await Task.Delay(500);
            Dismiss(new PopupResult {
                ReturnData="Close from  Login"
            });
        }
    }

---------------------------------------The caller -- LoginPage.xmal.cs---------------------------
  login按鈕事件:

           //可以用這方式把參數傳給popup   
          var popupResult = new PopupResult {
                ReturnData="Initial data"
            };
            var popup = new ProcessingPopup(popupResult);
            var result = Navigation.ShowPopupAsync(popup) ;  <-- Xamarin.CommunityToolkit.Extensions的popup召喚術!!
            await Task.Delay(10000);//模擬呼叫遠端作業,讓子彈飛一會
            popup.DoClose();
            var r2=await result;
            //日後用到popup做一些比較複雜的對話介面時,就會需要用到傳回技術了
            await DisplayAlert("get msg from Processing", $"return value:{ r2.ReturnData}", "OK");
            await Shell.Current.GoToAsync($"//{nameof(AboutPage)}");
------------------------------------------------------------------------------------------------------------
結果: 左為IOS,右為android,可惜的是目前沒有mask選項可以設定,當然你可以在popup裡加上一些小動畫元件,這次我只是用文字做測試,以確定GUI thread可以運作.有必要時再加上frame或許會好一點





「阿你之前用AndroidHud & BTProgressHUD 很好看啊,怎麼不拿來用? 」...好吧,可是AndroidHud是有點東西要加工的,
原本在Xamarin.Android裡的一堆函數會用到的ActivityContext
如「AndroidHUD.AndHUD.Shared.Show(this,"msg",-1,MaskType.Clear)」這裡面的 this是當下的ActivityContext,移植到Xamarin.Form就是Forms.Context,但是!!!!...
Xamarin.Form 2.5之後就不給用Forms.Context,所以要另外加點工
(討論參考這裡)
經上述討論建議,我直接改了Application那裡....
--------------MainApplication.cs----------------------------------

[Application]
public partial class MainApplication : Application, Application.IActivityLifecycleCallbacks {
internal static Context ActivityContext { get; private set; }
public MainApplication(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer) { }
public override void OnCreate() {
base.OnCreate();
RegisterActivityLifecycleCallbacks(this);
}
public override void OnTerminate() {
base.OnTerminate();
UnregisterActivityLifecycleCallbacks(this);
}
public void OnActivityCreated(Activity activity, Bundle savedInstanceState) {
ActivityContext=activity;
}
public void OnActivityResumed(Activity activity) {
ActivityContext=activity;
}
public void OnActivityStarted(Activity activity) {
ActivityContext=activity;
}
public void OnActivityDestroyed(Activity activity) { }
public void OnActivityPaused(Activity activity) { }
public void OnActivitySaveInstanceState(Activity activity, Bundle outState) { }
public void OnActivityStopped(Activity activity) { }
} 
---------------------------------------------------
------Android實作---------------------------------
    public class DroidHudToaster : IProcessingToast {
        public void dismissProcessAndShowMsg(bool success, string msg) {
            AndHUD.Shared.Dismiss();
            if(success) {
                AndHUD.Shared.ShowSuccessWithStatus(MainApplication.ActivityContext, msg, MaskType.Black, TimeSpan.FromSeconds(3));
            } else {
                AndHUD.Shared.ShowErrorWithStatus(MainApplication.ActivityContext, msg, MaskType.Black, TimeSpan.FromSeconds(3));
            }
        }
        public void showProcessing(string processingMsg = null) {
            AndroidHUD.AndHUD.Shared.Show(MainApplication.ActivityContext,
               (string.IsNullOrWhiteSpace(processingMsg) ? "Loading..." : processingMsg), -1, MaskType.Clear);
        }
    }

------IOS實作----------------------------------
    public class IosToaster : IProcessingToast {
        public void dismissProcessAndShowMsg(bool success, string msg) {
            BTProgressHUD.Dismiss();
            if(success) {
                BTProgressHUD.ShowSuccessWithStatus($"Process Ok:{msg}", MaskType.Black, 3000);
            } else {
                BTProgressHUD.ShowErrorWithStatus($"Errors msg:{msg}", MaskType.Black, 3000);
            }
        }
        public void showProcessing(string processingMsg=null) {
            BTProgressHUD.ShowContinuousProgress((string.IsNullOrWhiteSpace(processingMsg) ? "Loading..." : processingMsg), MaskType.Black);
        }
    }
----------------------------在共同專案裡用DI呼叫---------------
             DependencyService.Get<IProcessingToast>()?.showProcessing("Login now....");
            await Task.Delay(5000);
            DependencyService.Get<IProcessingToast>()?.dismissProcessAndShowMsg(true, "Login OK");
            await Task.Delay(3000);
            await Shell.Current.GoToAsync($"//{nameof(MainFuncsPage)}");
-------------------------------------------------------------------------
結果..... (左為ios,右為android) 果然是DI大法好啊...
-----------------------------------------------------------------

------------------------------------------------------------------------------ 
相信日後MAUI也要更好用好開發了
一起加油吧!!





2021年9月10日 星期五

For Xamain.IOS:File sharing需要什麼條件

 參考文件,請參考官方範例
https://docs.microsoft.com/zh-tw/xamarin/ios/app-fundamentals/file-system

info.plist需要兩個鍵值,如果光只有「UIFileSharingEnabled」

是無法在你的iphone上面的檔案app裡找到你的app分享出來的檔案的

想要讓iphone的「檔案」app用瀏覽「我的iphone」裡出現你的app icon資料夾(MyDocument).

就要另一個鍵值--「LSSupportsOpeningDocumentsInPlace」了

這篇也是不錯的討論,用模擬器開發的朋友可以參考

可是問題來了,先前你放在MyDocument裡特殊資料(像是json啦、SQLite db啦.....)不就都被看光了?

解決之道就在最初那份文件--把敏感資料搬到MyDocument上層的library裡就是了

(至於用「更新」的方式搭配上述的搬檔,有沒有work,知道的朋友麻煩指導在下一下,謝謝先了)


同場加映:

Xamarin.android的下載目錄在哪?

答案 : Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath

以上,大家加油了


2021年9月6日 星期一

For Xamarin Android: 比較簡潔地請求權限

 之前到安卓8以後已經有一種寫法了,太煩瑣了,

好在最近又有update了

今天把它記錄下來,以免下次又要找到天窮碧落下黃泉之窘境了

------------------------------------------------------

using Xamarin.Essentials;

...

 protected override void OnCreate(Bundle savedInstanceState) {

            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);

  ...

  }

//-----以下整碗做你捧去,我也是copy改出來的-------

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults) {

            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        }

        public async Task<Xamarin.Essentials.PermissionStatus> CheckAndRequestPermissionAsync<T>(T permission)

                    where T : Xamarin.Essentials.Permissions.BasePermission {

            var status = await permission.CheckStatusAsync();

            if (status != Xamarin.Essentials.PermissionStatus.Granted) {

                status = await permission.RequestAsync();

            }

            return status;

        }

//以下以存檔權限為例,請自己改其他權限來用

        public async Task ExportToExcelnAsync() {

            var status = await CheckAndRequestPermissionAsync(new Xamarin.Essentials.Permissions.StorageWrite());

            if (status != Xamarin.Essentials.PermissionStatus.Granted) {

                // Notify user permission was denied

                return;

            }


            await  你預訂得到權限後要做的事();

        }

   //-----Code海無邊,回頭是岸-----

--------------------------------

為什麼要寫出套件全名?因為很不巧一個叫「Plugin」的套件也有類似的權限套件

為了不被混淆,就全名標示了

本文技巧出處參考這裡

PS. 拜託安卓跟蘋果:你們可以不要再改了嗎?每次一版我就要重學,很累的耶,能不能像大話西遊一樣「如果非要在這些架構套件開發技術上加一個期限,我希望是……一萬年」啊