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也要更好用好開發了
一起加油吧!!