Setting a WinRt AdvertisementFilter() to a substring of LocalName - c++

C++, WinRT, VS2017, Win10
I create a watcher to look for my Bluetooth LE device with
BluetoothLEAdvertisementWatcher watcher;
Now I want to set a filter for for the device that I am specifically looking for. Let's say that the LocalName for the device is "MyDevice_ABC1234". I can do this with
watcher.AdvertisementFilter().Advertisement().LocalName().c_str() == L"MyDevice_ABC1234";
But what I really want to do is set the filter to the manufacture's name and not the specific model number. I want to filter for "MyDevice" being in the LocalName. This would be easy enough given the luxury of a few lines of code but how would it be done in the context of
watcher.AdvertisementFilter().Advertisement().LocalName()
LocalName() has an operator for basic_string_view which has a find() method but for the life of me I can't get that to work properly. The find() is supposed to return the npos so I tried:
watcher.AdvertisementFilter().Advertisement().LocalName().operator std::basic_string_view<wchar_t, std::char_traits<wchar_t>>.find("MyDevice") == 8;
I actually tried this as simple code so I could debug the results with
hstring hstrLocalName = L"MyDevice_aBC1234";
bool bFind = hstrLocalName.operator std::basic_string_view<wchar_t, std::char_traits<wchar_t>>.find("MyDevice", 0) == 8;
and also
int iFind = hstrLocalName.operator std::basic_string_view<wchar_t, std::char_traits<wchar_t>>.find("MyDevice", 0);
But neither of these worked. They compiled but just never executed. Is there a way to get the basic_string_view.find() to work or would there be a better way to do this?

I see now, that when I do use the method mentioned above from StackOverflow here, it does filter for the LocalName that I set. However, and I remember this warning from the docs somewhere, that some advertisement packets come with the local name but not Uuids and visa versa. As it happenes, that is why I thought the filter was catching nothing. I was ignoring any packets that did not have services and these were the ones with the LocalName. Catch22.
For what it is worth, here is the method for setting a filter mentioned in the link above that also worked for me (with caveats)
auto filter = BluetoothLEAdvertisementFilter();
auto advert = BluetoothLEAdvertisement();
advert.LocalName(L"MyDevice_ABC1234");
filter.Advertisement(advert);
watcher.AdvertisementFilter(filter);

Related

VSIX how to get current snapshot document name?

I have been trying to to create an extension that highlights specific line numbers for me in Visual Studio in the margins.
I manged to get my marking in the margins using predefined line number but for it to work properly I need to know what the current document FullName is (Path and filename)
After much googling I figured out how to do it with the sample code (which is not ideal)
DTE2 dte = (DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.15.0");
var activeDocument = dte.ActiveDocument;
var docName = activeDocument.Name;
var docFullName = activeDocument.FullName;
Now I know the problems here
is that is for specific version bases on the text
there is no way to select which instance (when running more than one VS)
It seems to be very slow
I have a feeling I should be doing this with MEF Attributes but the MS docs examples are so simple that they do not work for me. I scanned a few SO questions too and I just cannot get them to work. They mostly talk about Services.. which I do not have and have no idea how to get.
The rest of my code uses SnapshotSpans as in the example Extension of Todo_Classification examples which is great if you do NOT need to know the file name.
I have never done any extensions development. Please can somebody help me do this correctly.
You can use following code to get a file from a snapshot without any dependencies.
public string GetDocumentPath(Microsoft.VisualStudio.Text.ITextSnapshot ts)
{
Microsoft.VisualStudio.Text.ITextDocument textDoc;
bool rc = ts.TextBuffer.Properties.TryGetProperty(
typeof(Microsoft.VisualStudio.Text.ITextDocument), out textDoc);
if (rc && textDoc != null)
return textDoc.FilePath;
return null;
}
If you don't mind adding Microsoft.CodeAnalysis.EditorFeatures.Text to your project it will provide you with an extension method Document GetOpenDocumentInCurrentContextWithChanges() on the Microsoft.VisualStudio.Text.Snapshot class. (Plus many other Rosyln based helpers)
using Microsoft.CodeAnalysis.Text;
Document doc = span.Snapshot.GetOpenDocumentInCurrentContextWithChanges();

Reverse engineering the checksum algorithm

I have an IP camera that receives commands using POST HTTP requests(for example to call PTZ commands or set various camera settings). The standard way of controlling it is through it's own web interface which is partially an ActiveX plugin and partially standard html+js. Of course because of the ActiveX part it only works in IE under Windows.
I'm attempting to change that by figuring out all the commands and writing a small python or javascript code to do the same, so that it is more cross platform.
I have one major problem. Each POST request contains a calculated "cc" field which I assume is a checksum. The JS code in the cam interface points out that it is calculated by calling a function inside the plugin:
tt = new Date().Format("yyyyMMddhhmmss");
jo_header["tt"] = tt;
if (getCpPlugin() != null && getCpPlugin().valid) {
jo_header["cc"] = getCpPlugin().nsstpGetCC(tt, session_id);
}
nsstpGetCC function obviously calculates the checksum from two parameters the timestamp and session_id. Real example(captured with Wireshark):
tt = "20171018231918"
session_id = "30303532646561302D623434612D3131"
cc = "849e586524385e1071caa4023a3df75401e5bb82"
Checksum seems to be 160bit. I tried both sha-1 and ripemd-160 and all combinations of concatenating tt and session_id I could think of. But I can't seem to get the same hash as the one the original plugin gets. The plugin dll seems to be written in c++. And I have almost no experience with decompilation to dive into this problem from that angle.
So my question basically is can someone figure out how they calculated that cc, or at least give me an idea in which direction to research further. Maybe I'm looking at wrong hash algorithms or something... Or give me some idea how I could somehow figure out what the original ActiveX function nsstpGetCC is doing for example by decompilation or maybe by monitoring it's operation in memory while running. What tools should I use?

Persistent and ephemeral nodes in ZooKeeper

I want to know how to create persistent nodes in ZooKeeper, using C++ client. I know from documentation, that there is a method zoo_acreate. And documentation says about this method that:
This method will create a node in ZooKeeper. A node can only be created if it does not already exists. The Create Flags affect the creation of nodes. If ZOO_EPHEMERAL flag is set, the node will automatically get removed if the client session goes away. If the ZOO_SEQUENCE flag is set, a unique monotonically increasing sequence number is appended to the path name.
But, unfortunatelly, almost as always with C++ libraries, this library completely lacks reasonable teeny-weeny examples demonstarting the usage of the library methods. As for example in this case where documentation page is about zoo_acreate method, but some terribly looking example is totally about something else (it does not even mention zoo_acreate method).
So, my question is how to set these flags ZOO_EPHEMERAL and ZOO_SEQUENCE. It would be great to see this in the context of some tiny examples. Thanks!
Googling for "zoo_acreate ZOO_EPHEMERAL" gave this as the seventh result:
string path = "/nodes/";
string value = "data";
int rc = zoo_acreate(zh, path.c_str(), value.c_str(), value.length(),
&ZOO_OPEN_ACL_UNSAFE, ZOO_EPHEMERAL | ZOO_SEQUENCE, &czoo_created, &where);
Source: https://issues.apache.org/jira/browse/ZOOKEEPER-348

Boost.Log: how to filter by current thread id

I'm using Boost.Log, which is a part of Boost v1.54. I have a sink, which I want to only accept log messages from the current thread. How can I achieve that?
BOOST_LOG_ATTRIBUTE_KEYWORD(thread_id, "ThreadID", logging::attributes::current_thread_id::value_type)
std::stringstream stream;
logging::add_common_attributes();
boost::shared_ptr<text_sink> sink = boost::make_shared<text_sink>();
sink->locked_backend()->add_stream(stream);
logging::core::get()->add_sink(sink);
boost::thread::id currentThreadId = boost::this_thread::get_id();
// At this line compiler complains about the '==' operator.
sink->set_filter(thread_id == currentThreadId);
Without the last line everything works fine, and when I configure sink formatter, it outputs the calling thread ID. What is the proper way to compare thread_id attribute with the currentThreadId?
I know I can use some custom attribute to tag messages with the current thread ID, and then filter them by that attribute, but what about the default boost's current_thread_id attribute? Is it usable for such a purpose?
Well, after spending half the night digging around I came across the (undocumented?) boost::log::aux namespace, where I found boost::log::aux::this_thread::get_id() function. It returns an object of the proper type which I am now able to compare with the thread_id keyword.
Now I wonder if the boost::log::aux namespace is meant for boost internal use only? Some time ago I used to utilize some internal features of boost mutexes/locks, and after the next library update they changed everything and I couldn't even compile my code against that new version of the library. So now I don't want to repeat my past mistakes :)

CRecordset::snapshot doesn't work in VS2012 anymore - what's the alternative?

Apparently, in VS2012, SQL_CUR_USE_ODBC is deprecated. [Update: it appears that the cursors library has been removed from VS2012 entirely].
MFC's CDatabase doesn't use it anymore (whereas it was the default for VS2010 and earlier versions of MFC), but instead uses SQL_CUR_USE_DRIVER.
Unfortunately, SQL_CUR_USE_DRIVER doesn't work properly with the Jet ODBC driver (we're interacting with an Access database). The driver initially claims to support positional operations (but not positional updates), but when an attempt is made to actually query the database, all concurrency models fail until the MFC library drops down to read-only interaction with the database (which is not going to fly for us).
Questions
Is this MS's latest attempt to force devs to move away from Jet based datasources and migrate to SQL Express (or the like)?
Is there another modality that we should be using to interact with our Access databases through VS 2012 versions of MFC/ODBC?(1)
See also:
http://social.msdn.microsoft.com/Forums/kk/vcmfcatl/thread/acd84294-c2b5-4016-b4d9-8953f337f30c
Update: Looking at the various options, it seems that the cursor library has been removed from VS2012's ODBC library. Combined with the fact that Jet doesn't correctly support positional updates(2), it makes "snapshot" mode unusable. It does appear to support "dynaset" as long as the underlying tables have a primary key. Unkeyed tables are incompatible with "dynaset" mode(3). So - I can stick with VS 2010, or I can change my tables to include an autonumber or something similar in order to ensure a pkey is available so I can use dynaset mode for the recordsets.
(1) e.g. should we be using a different open type for CRecordset? We currently use CRecordset::snapshot. But I've never really understood the various modes snapshot, dynamic, dynaset. A quick set of "try each" has failed to get a working updatable interface to our access database...
(2) it claims to when queried initially, but then returns errors for all concurrency modes that it previously claimed to support
(3) "dynamic" is also out, since Jet doesn't support it at all (from what I can tell from my tests).
I found a solution that appears to work. I overrode OpenEx the exact same way VS 2012 has it because we need that to call the child version of AllocConnect since it is not virtual in the parent. I also overrode AllocConnect as mentioned. In the derived version of CDatabase, try the following code:
MyCDatabase.h
BOOL OpenEx(LPCTSTR lpszConnectString, DWORD dwOptions = 0);
void AllocConnect(DWORD dwOptions);
MyCDatabase.cpp
BOOL MyCDatabase::OpenEx(LPCTSTR lpszConnectString, DWORD dwOptions)
{
ENSURE_VALID(this);
ENSURE_ARG(lpszConnectString == NULL || AfxIsValidString(lpszConnectString));
ENSURE_ARG(!(dwOptions & noOdbcDialog && dwOptions & forceOdbcDialog));
// Exclusive access not supported.
ASSERT(!(dwOptions & openExclusive));
m_bUpdatable = !(dwOptions & openReadOnly);
TRY
{
m_strConnect = lpszConnectString;
DATA_BLOB connectBlob;
connectBlob.pbData = (BYTE *)(LPCTSTR)m_strConnect;
connectBlob.cbData = (DWORD)(AtlStrLen(m_strConnect) + 1) * sizeof(TCHAR);
if (CryptProtectData(&connectBlob, NULL, NULL, NULL, NULL, 0, &m_blobConnect))
{
SecureZeroMemory((BYTE *)(LPCTSTR)m_strConnect, m_strConnect.GetLength() * sizeof(TCHAR));
m_strConnect.Empty();
}
// Allocate the HDBC and make connection
AllocConnect(dwOptions);
if(!CDatabase::Connect(dwOptions))
return FALSE;
// Verify support for required functionality and cache info
VerifyConnect();
GetConnectInfo();
}
CATCH_ALL(e)
{
Free();
THROW_LAST();
}
END_CATCH_ALL
return TRUE;
}
void MyCDatabase::AllocConnect(DWORD dwOptions)
{
CDatabase::AllocConnect(dwOptions);
dwOptions = dwOptions | CDatabase::useCursorLib;
// Turn on cursor lib support
if (dwOptions & useCursorLib)
{
::SQLSetConnectAttr(m_hdbc, SQL_ATTR_ODBC_CURSORS, (SQLPOINTER)SQL_CUR_USE_ODBC, 0);
// With cursor library added records immediately in result set
m_bIncRecordCountOnAdd = TRUE;
}
}
Please note that you do not want to pass in useCursorLab to OpenEx at first, you need to override it in the hacked version of AllocConnect.
Also note that this is just a hack but it appears to work. Please test all your code to be sure it works as expected but so far it works OK for me.
If anyone else runs into this issue, here's what seems to be the answer:
For ODBC to an Access database, connect using CDatabase mydb; mydb.OpenEx(.., 0), so that you ask the system not to load the cursor library.
Then for the recordsets, use dynaset CMyRecordset myrs; myrs.Open(CRecordset::dynaset, ...).
Finally, you must make sure that your tables have a primary key in order to use dynasets (keysets).
Derive CDatabase and override OpenEx. In your derived class CMyDatabase, replace the call to AllocConnect to MyAllocConnect. Obviously, your MyAllocConnect function should call SQLSetConnectOption with the desired parameter:
// Turn on cursor lib support
if (dwOptions & useCursorLib)
{
AFX_SQL_SYNC(::SQLSetConnectOption(m_hdbc, SQL_ODBC_CURSORS, SQL_CUR_USE_ODBC));
// With cursor library added records immediately in result set
m_bIncRecordCountOnAdd = TRUE;
}
Then use your CMyDatabase class instead of CDatabase for all your queries.