2021年3月16日 星期二

bitwise operation--合宜地操作bits ("ORing" and mask bits)

 就某32bit data而言  (ex : *pRccCfg)

經初始化0b0

我們把bit 22設定為1 之後 (by instruction : 「 *pRccCfg|= (1<<22) ; 」)

要把bit 24~26設定為0b110,又不能動到之前設定的其他bit值,如何是好?

作法1.一個bit一個bit設定

*pRccCfg!=(1<<25)

*pRccCfg!=(1<<26)

作法二,用罩除的方式,比較不建議請注意"~"的用法

*pRccCfg!=(7<<24); // "OR" the 3 bits by  0b111 

*pRccCfg &=~(1<<24);//shift the bit ,then "Complement them",then,use "AND" opeartion,

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

同理,只是想清除某幾個bit,也是先 shift "on" bits ,"Complement  them",then ,use "AND"operation

ex:要把21&22 bits清除,但不要動到其他bits,請用以下方式

*pAddrRccCfg &=~(0x3<<21);

務必注意!!

~(0x3<<21) 是

11111111100111111111111111111111

而(~0x3<<21) 是

11111111100000000000000000000000 

千萬要注意順序

2021年2月24日 星期三

APNS從by certificate 到by jwt 的升級側記

apns一直都運作的好端端的, app客戶說要再加一個姊妹作,但是仍用同樣的apns機制(因為資料源都是一樣,只是內容有點差異)
於是故事就這樣展開了
目前apns server是windows server 2012,web project 是asp.net 4.5
參考以下的方式改寫了推播apns那段 
從此公主跟PG就過著幸福快樂的生活了.....想的美

當你trace到 var secretKey = CngKey.Import 時,會遇到「system cannot find the file specified 」例外,
可是明明路徑都正確啊......是的,你需要比較高的權限
相對的,你的application pool identity也要提高權限
然後....
你明明在IDE中執行httpClient.SendAsync都很正常,可是怎麼放在iis給他執行就出現這種例外
「call to SSPI failed, see inner exception. StackTrace:   at System.Net.Security.SslState.InternalEndProcessAuthentication(LazyAsyncResult lazyResult)
...
..
...」
答案是......server 2012的IIS不支援http/2
所以,請把你的server升級到server 2016再來打怪吧

花了半天升級了server,結果又是在httpClient.SendAsync出錯,這時是....「timeout」!?
可是明明在IDE debug確又正常啊.....
那就是要升級你的framework的時候了,把專案從4.5升級到4.6吧
(前輩如是說的.....https://stackoverflow.com/questions/32685151/how-to-make-the-net-httpclient-use-http-2-0)
還有,別再用httpTwo了而是用「WinHttpHandler」,如同第33則po文一樣--
-------------------
1.Make sure you are on the latest version of Windows 10.

2.Install WinHttpHandler:

Install-Package System.Net.Http.WinHttpHandler

3.Extend WinHttpHandler to add http2.0 support:

public class Http2CustomHandler : WinHttpHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        request.Version = new Version("2.0");
        return base.SendAsync(request, cancellationToken);
    }
}

4.Pass above handler to the HttpClient constructor

using (var httpClient = new HttpClient(new Http2CustomHandler()))
{
      // your custom code
}
---------------------------------
(所以就是要用非同步的方式去呼叫了,沒差,用執行緒去做就是了)
雖然案主說你就再申請一個apns 憑證嘛.何必這樣大費周章?
可是每一個憑證每年都要換證,就是怕在換證時uer漏接了重要的訊息
這次一做,日後很多個APP都可以共用,也沒有期限問題,長痛不如短痛啊,根本性地解決問題,不亦快哉?

2021年2月21日 星期日

SecKeyChain.Add return Security.SecStatusCode.MissingEntitlement !?

 在xamarin ios經常更新,以往的加解密函數現在出現這現象
----code----

var s = new SecRecord(SecKind.GenericPassword) {

                ValueData = NSData.FromString(value),

                Generic = NSData.FromString(key),

                Invisible = true,

                CreationDate = NSDate.Now


            };

            var err = SecKeyChain.Add(s);

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

結果err傳回值是「Security.SecStatusCode.MissingEntitlement

好在別人已經踢到鐵板了,請參考以下的方式修改

https://forums.xamarin.com/discussion/145357/seckeychain-add-return-security-secstatuscode-missingentitlement

注意,其中的
------------

<key>keychain-access-groups</key>

<array>

<string>$(AppIdentifierPrefix)你的appBundle ID</string>

</array>

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

紅色字$(AppIdentifierPrefix)要去掉,

這是用vs2019 IOS manifest Editor打開加入keychain選項他自己加上去的

要小心--盡信editor不如無editor


加油!!

2021年1月16日 星期六

for android : notification with vibration not work !?

 安卓開發就怕一直在改版的問題一再發生

最近很多開發者都遇到明明在notification的震動機制好好的,怎麼升級後又惦惦了

google了一下是要加上 audioattribute--
---example-----

 audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_ALARM) //key
                    .build();
            mVibrator.vibrate(pattern, 1, audioAttributes);
-----------------
來源參考:
https://www.jianshu.com/p/3ec9158b2041
同場加映
有些圓標可以用線上的icon generator來產生
https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html












請多加利用左側功能表中的background color等屬性
https://romannurik.github.io/AndroidAssetStudio/index.html <--這裡還有 notification icon generator可以用哦
(一升級就搞得大家雞飛狗跳的,希望馬斯克的手機系統不會這樣麻煩)
大家加油吧

2021年1月9日 星期六

初經驗--把.net core 專案發佈到他台主機IIS上遇到的問題

當你把彼端IIS & MSSQL express裝好了,並且也把「安裝 ASP.NET Core 模組/裝載套件組合」 裝好後,檔案也搬好了,你以為這樣就打完收工了?不,我們奇妙的冒險旅程才正要開始呢, 首你,把你先建立好的web & applicatoin 設好,port bind 也設了,用本機的網址去查驗一下 localhost:5000 結果出現這畫面....
去IIS的log查也沒有什麼具體的說明,只會讓你懷疑人生罷了 你需要一些踢過鐵板的人的經驗,參考....這個
看來看去,好像只有第四個選項「stdoutLogEnabled 」才是那一窗門,是的,那就打開他吧
--------------web.config-------------------------
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\XXXXX.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>
---------------------------------------
改好改滿,重啟那個站台,再次request看看你的站台,你就會在你的.net core網站目錄下看到「logs」目錄,裡面有log檔了.....
--------------------------------
Unhandled exception. System.FormatException: Could not parse the JSON file.
 ---> System.Text.Json.JsonReaderException: 'S' is an invalid escapable character within a JSON string. The string should be correctly escaped. LineNumber: 10 | BytePositionInLine: 47.
   at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
   at System.Text.Json.Utf8JsonReader.ConsumeStringAndValidate(ReadOnlySpan`1 data, Int32 idx)
   at System.Text.Json.Utf8JsonReader.ConsumeString()
-------------------------------
喏,看到了吧,是json檔設定有問題了,在佈署的資料夾中看到的json檔
最可疑的就是「appsettings.json」
-----------------------------------------










----------------------------------------
又是萬惡的斜線問題了,再加一條斜線改好後,重啟IIS那個.net core web後,其本上你用localhost:5000
去看,就是正常了








....那有用到database的部分,如何設定?
你除了是把.net core web 的application pool的identity設定為NetowrkService之外,
也要有sql server security & login的設定配合才行
參考這裡比較快 

解決:使用者’IIS APPPOOL\ASPNET v4.0’的登入失敗

可能比較正規的做法是這樣....

註 2021/02/23,不必如何大費周章,直接在appsettings.json改,
在connection string中,加入「;Integrated Security=false;」這屬性就是了

以上,大家加油了
(.net core 效能不錯的樣子,真香啊.....)





2020年10月11日 星期日

for xamarin android : how to play sound file (mp3)

 1.檔案一定是要mp3格式(wav檔不行)

2.檔案請放在「Resources」之下,本例為了跟其他資源區分,放在Resources/raw之下,

(有a1.mp3,a2.mp3....)

3.play sound的語法
A.用MediaPlayer:

var  player =MediaPlayer.Create(ApplicationContext,Resource.Raw.a1);
  player.Start();

B.用RingToneManager:

var uriString="android.resource://" + your_package_name + "/" +Resource.Raw.a1;

var uri=Android.Net.Uri.Parse(uriString);

Ringtone r = RingtoneManager.GetRingtone(ApplicationContext, uri);
r.Play();

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

以上,大家加油了!!

2020年10月1日 星期四

xamarin: enable & receive UDP broadcast (Android 11 嘛會通哦)

 AndroidManifest.xml

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

...

...

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />

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

in android app Activity c# :

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

          var wifiManager = (WifiManager)GetSystemService(Context.WifiService);

            MulticastLock mLock = wifiManager.CreateMulticastLock("lock");

            mLock.Acquire();

            using (var udpClient = new UdpClient(你要聆聽的port number)) {

                var asyncResult = udpClient.BeginReceive(null, null);

                var timeToWait = TimeSpan.FromSeconds(30);//30秒,超過就結束

                asyncResult.AsyncWaitHandle.WaitOne(timeToWait);

                if (asyncResult.IsCompleted) {

                    IPEndPoint remoteEP = null;

                    byte[] receivedData = udpClient.EndReceive(asyncResult, ref remoteEP);

                    string msg = System.Text.Encoding.UTF8.GetString(receivedData);

                    Console.WriteLine($"get end point message:{msg}");

                    mLock.Release();

                } else {

                    mLock.Release(); 

                    Console.WriteLine("UDP failed!!!!!!");

                }

            }

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

參考 : 這裡

以上,希望對你有幫助


2020年9月30日 星期三

for extjs 4 & 6 , 去背的window

 一如文件「Extjs4 ,如何偵測是否點在pop up window 的外面

一樣,可以考慮在window的mask再加工

如果是全域設定,就直接改 .x-mask css就可以了

但是如果是各別的window (彈吧七彩霓虹window )

就要在show / close事件中加減cls了

----css --------------------------

.seemsNoWinMask.x-mask {

            filter: alpha(opacity=0);

            opacity: .0;

            background:white !important; 

    }

-----ext js 4------------------------------------

let win = Ext.create('Ext.window.Window', {

                    listeners: {

                        show: function (win) {

                            if (this.modal) {

                                var dom = Ext.dom.Query.select('.x-mask');

                                var el = Ext.get(dom[0]);

                                el.addCls('seemsNoWinMask');

                            }

                        },

                        close: function (win) {

                            if (this.modal) {

                                var dom = Ext.dom.Query.select('.x-mask');

                                var el = Ext.get(dom[0]);

                                el.removeCls('seemsNoWinMask');

                            }

                        }

                    },

......

....

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

extjs 6.2 

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

listeners: {

                show: function (win) {

                    if (this.modal) {

                        var dom = Ext.dom.Query.select('.x-mask');

                        for (var i = 0; i < dom.length; i++) {

                            Ext.get(dom[i]).addCls('seemsNoWinMask');

                        }

                    }


                },

                close: function (win) {

                    if (me.modal) {


                        var dom = Ext.dom.Query.select('.x-mask');

                        for (var i = 0; i < dom.length; i++) {

                            Ext.get(dom[i]).removeCls('seemsNoWinMask');

                        }

                    }

                    

                }

}

...

...

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

以上

(2020了,我還在寫extjs .....)

2020年9月26日 星期六

for extjs 6.2 :如何做個去邊的textfield ?

 之所以會想用這個去邊的textfield,

是因為在某次實作時,要實作一個很類似chrome的search textfield,又內含清空及搜尋的buttons

但又不想繼承field類別(好啦,我承認懶得試這方式),所以要用組裝的方式來做這東西

要把border去除一下,

(以下是extjs 6.2 )

----先準備一個css----------------------

.x-form-textfield-noborder .x-form-trigger-wrap-default {

    border-width: 0px;

    border-style: solid;

    border-color: #d0d0d0;

}

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

那麼,那個要套用css的texfield就是會像以下的例子

......................................

        //...外面包他的container

 {

                            xtype: 'container',

                            width: 170,

                            height: 25,

                            margin: '20 0 0 10',

                            //textfield去邊,要用外層的container做框來包textfield & buttons.

                            style: {

                                borderColor: 'lightgray',

                                borderStyle: 'solid',

                                borderWidth: '1px'

                            },

                            layout: {

                                align: 'stretch',

                                type: 'hbox'

                            },

                            items: [

            //-------------------重點來了---------------------------

           {

                            margin: '20 0 0 20',

                            xtype: 'textfield',

                            cls: 'x-form-textfield-noborder',


             },  //之下,是兩個button

                         {

                                    xtype: 'button',

                                    style: {

                                        background: 'white',

                                        borderRadius: '0px',

                                        borderStyle: 'solid',

                                        marginRight: '3px',

                                        marginTop: '1px',

                                        marginBottom: '1px',

                                        borderColor: '#d0d0d0;',

                                        borderWidth: '0px'


                                    },

                                    height: 16,

                                    width: 16,

                                    icon: './images/icon2del.gif'

                                },

                                {

                                    xtype: 'button',

                                    style: {

                                        background: 'white',

                                        borderRadius: '0px',

                                        borderStyle: 'solid',

                                        marginLeft: '3px',

                                        marginTop: '1px',

                                        marginBottom: '1px',

                                        borderColor: '#d0d0d0;',

                                        borderWidth: '0px'

                                    },

                                    height: 18,

                                    minWidth:20,

                                    icon:'./images/search18x18.png'

                                }

                     ]

            } 

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

當然,如果這個欄位只是display only的話,那就用displayfield

尤其是在layout type是table的情況之下,xtype:'label'通常怎麼喬margin & padding都沒用的情況之下

那就用displayfield或是這個去框的textfield吧

參考:

https://blog.csdn.net/onightfalls/article/details/78601091

https://stackoverflow.com/questions/29987504/extjs-displayfield-with-same-style-as-textfield


以上

2020年9月6日 星期日

for ReactJs : axios回傳的response值是 「undefined」!?

 實驗預期對的東西,是必須的,

然而,實驗"錯誤狀況"有無落實,更是一個系統良窳之所在

一般在react js用到axios都是用 promise的寫法:

 axios.get(url,body,header.....).then(response=>......).catch(error=>);

但是如果上述的url錯誤,或是權限問題,造成錯誤

執行上述的結果通常是「response is undefined」,更別就在then(....)裡做resp.data.....解析

就這樣丟出一個 「undefined」錯誤,誰看得懂啊

如何是好?

 如果,不要用要axios預設的包裝機制--我們把http狀態解釋權拿回來,會不會好一點?

是的,axios也有想到這點,所以有了這個設定參數「validateStatus:false」

奪回解釋權,axios負責傳送接收,接下來就是我們事了

-------以下雖然是用saga,但基本工作原理是一樣的------

--以udemy 課程「React-The complete Guide」 sample code : buger app為例-----

export function* doFetchOrderProcessBySaga(action) {

  yield put(actions.doBeginFetchOrders());

  /*

  const authState = yield select((state) => state.auth);

  const token = authState.token;

  const userId = authState.userId;

  */

  //let's finish above 3 command in one line

  const { token, userId } = yield select((state) => state.auth);

  const queryParam =

    "?auth=" + token + '&orderBy="userId"&equalTo="' + userId + '"';

  try {

    const resp = yield axios.get("/orders.json" + queryParam, {

      validateStatus: false

    });

    //if hoc/withErrorHandler instead of "withErrorHandler_class"

    //please DO NOT return by 「yield put(actions.fetchOrdersSeccess([]));」,or users can not see the error message &  Modal

    //(don't ask me  why)

    // if (!resp || resp === undefined) {

    //   yield put(actions.fetchOrdersFailed("return undefined.please check URL"));

    //   return;

    // }

    if (resp.status !== 200) {

      yield put(

        actions.fetchOrdersFailed(

          "ERROR:" + resp.status + " " + resp.statusText

        )

      );

      return;

    }


    let orderTmp = [];

    for (let key in resp.data) {

      orderTmp.push({

        ...resp.data[key],

        id: key

      });

    }


    yield put(actions.fetchOrdersSeccess(orderTmp));

  } catch (err) {

    yield put(actions.fetchOrdersFailed(err.message));

  }

}

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

驗證:


切到"orders"單元,在orders.js初次render時下載訂單資訊為例.

如果是正常的話,是如以下畫面

現在,到firebase realtime database  ,去修改api權限一下

(改完了別忘了「發布」才會生效)
之後,我們在react js app 切到別單元再進到Orders這裡,出現了權限問題
(應該的,不出現error才該打屁股了)

這樣,是不是明確多了?

參考連結:
https://stackoverflow.com/questions/54185997/how-to-get-axios-error-response-into-the-redux-saga-catch-method?rq=1

https://stackoverflow.com/questions/48298890/axios-how-to-get-error-response-even-when-api-return-404-error-in-try-catch-fi

https://github.com/redux-saga/redux-saga/issues/1730

http://codestudyblog.com/questions/sf/0421204826.html

以上,大家加油了