2021年7月5日月曜日

win32 C++ でWMI(Windows Management Instrumentation)を使用する

以下は指定IP(szIPaddr)に ping を打った時の status を取得する

// 主スレッドで呼出し
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, 0);

// Ping status
HRESULT hr;
CComPtr< IWbemLocator > pLocator;
hr = CoCreateInstance(CLSID_WbemAdministrativeLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (void**)(&pLocator));
if (SUCCEEDED(hr))
{
  CComPtr< IWbemServices > pService;
  //hr = pLocator->ConnectServer(L"root\\cimv2", NULL, NULL, NULL, WBEM_FLAG_CONNECT_USE_MAX_WAIT, NULL, NULL, &pService);
  hr = pLocator->ConnectServer(L"root\\cimv2", NULL, NULL, NULL, 0, NULL, NULL, &pService);
  if (SUCCEEDED(hr))
  {
    CString szSQL;
    szSQL.Format(_T("SELECT * FROM Win32_PingStatus WHERE Address='%s'"), szIPaddr);
    _bstr_t bzSQL(_bstr_t(CT2W((LPCTSTR)szSQL)));
    CComPtr< IEnumWbemClassObject > pEnumObj;
    hr = pService->ExecQuery(L"WQL", bzSQL, (WBEM_FLAG_RETURN_IMMEDIATELY|WBEM_FLAG_FORWARD_ONLY), NULL, &pEnumObj);
    if (SUCCEEDED(hr))
    {
      CComPtr< IWbemClassObject > pObj;
      ULONG uReturned;
      //hr = pEnumObj->Reset();
      hr = pEnumObj->Next(WBEM_INFINITE, 1, &pObj, &uReturned);
      if (!FAILED(hr))
      {
        _variant_t vtBuf;
        hr = pObj->Get(L"StatusCode", 0, &vtBuf, 0, 0);
        pObj.Release();
      }
      pEnumObj.Release();
    }
    pService.Release();
  }
  pLocator.Release();
}

2021年3月27日土曜日

VB.net での nothing (null) の扱い

勝手に初期値に変換される!

Dim dt as Date = nothing
としても dt は初期値がセットされている (nothingではない)
if (dt is Nothing) then
 → エラー

Nothing を許容するには
Dim dt? as Date = nothing  
変数名のおしりに"?" をつけると nothing が代入できる
if (dt is Nothing) then
 → OK


Date型またはNothingを返す関数
Function GetDate() as Nullable(of Date)


Databaseへの登録
Nothing と DBNull.value は異なる

adoCmd.parameter.Add("DATE_VALUE",type.date).value = IIf (dt is nothing, DBNull.value, dt)

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

Sub Test() 
    Dim dt1 As Date = Nothing
    Dim dt2? As Date = Nothing

    'If (dt1 Is Nothing) Then
    '    Console.WriteLine("dt1 is nothing")
    'End If
    If (dt2 Is Nothing) Then
        Console.WriteLine("dt2 is nothing")
    End If

    Console.WriteLine(String.Format("value1: {0}", dt1.ToString()))
    Console.WriteLine(String.Format("value2: {0}", dt2.ToString()))

    Console.WriteLine(String.Format("F1: {0}", F1().ToString()))
    Console.WriteLine(String.Format("F2: {0}", F2().ToString()))
End Sub

Function F1() As Date
    Return Nothing
End Function

Function F2() As Nullable(Of Date)
    Return Nothing
End Function