Problems using ReadDirectoryChanges in Rad Studio - c++builder

I am trying to load a file into a stream in BASS via ReadDirectoryChanges.
When I use a testfunction using FileOpenDialog I get a working result, but when I use RDC it craps out on me all the time. I must be doing something wrong, but for the life of me I can't figure it out. Maybe someone here can point me in the right direction.
Below is a snippet of the code I use:
void __fastcall TForm9::ToWav(FILE_NOTIFY_INFORMATION* File)
{
String FullFileName = OpokaClient.ImportLocation + copyfname(File);
int BassResult = 0;
LogLine("File added to: " + FullFileName, apSYSTEM);
HSTREAM convert = NULL;
convert = MyBASS_StreamCreateFile(false, FullFileName.c_str(), 0, 0, BASS_STREAM_DECODE | BASS_UNICODE);
BassResult = MyBASS_ErrorGetCode();
LogLine("Bass Result: " + IntToStr(BassResult), apSYSTEM);
}
//---------------------------------------------------------------------------
void __fastcall TForm9::Button2Click(TObject *Sender)
{
String FileName;
int BassResult = 0;
if(FileOpenDialog1->Execute()) {
FileName = FileOpenDialog1->FileName;
} else {
LogLine("No file selected. FileName empty", apWARNING);
return;
}
HSTREAM convert = NULL;
LogLine("ConverterMain: ToWav: FileName: " + FileName, apSYSTEM);
convert = MyBASS_StreamCreateFile(false, FileName.c_str(), 0, 0, BASS_STREAM_DECODE | BASS_UNICODE);
BassResult = MyBASS_ErrorGetCode();
LogLine("chan ErrorCode: " + IntToStr(BassResult), apSYSTEM);
}
//---------------------------------------------------------------------------
copyfname is in a different unit..
wchar_t* copyfname(FILE_NOTIFY_INFORMATION* pfi)
{
wchar_t* pfn;
pfn = new wchar_t[pfi->FileNameLength+1];
ZeroMemory(pfn, sizeof(wchar_t)*(pfi->FileNameLength+1));
memcpy(pfn, pfi->FileName, pfi->FileNameLength);
return pfn;
}

Related

Error IoTimedOut when reading data from the device

I used libUsbDotNet library (C#) to read data from USB device.
The program sees the device and turns to it, but gives a response IoTimedOut.
The program code is shown below.
public static UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x10C4, 0xEA61);
public static UsbDevice MyUsbDevice;
public static void Main()
{
MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
if (MyUsbDevice == null) throw new Exception("Device Not Found.");
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
wholeUsbDevice.SetConfiguration(1);
wholeUsbDevice.ClaimInterface(0);
}
UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
ErrorCode ec = ErrorCode.None;
int bytesRead = 0;
byte[] readBuffer = new byte[32];
while (true) {
Thread.Sleep(100);
ec = reader.Read(readBuffer, 1500, out bytesRead);
if (bytesRead > 0)
{
Console.WriteLine("Data Received");
// Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
}
else {
Console.Write("Error type: ");
Console.WriteLine(ec);
Console.ReadKey();
MyUsbDevice.Close();
break;
}
}
}
I tried to change the reading parameters but it doesn't help. Can you please tell me what it may be related to, it is not clear to me from the libUsbDotNet documentation?

How to get function definition/signature as a string in Clang?

How can I get a function's signature (or at least the entire definition?) as a string using Clang/Libclang, assuming I have its CXCursor or so?
I think that the definition may be somehow obtainable by using the cursor's extents, but I don't really know how (what function to use).
You can use this simple code to get prototype of a function ( name, return type, count of arguments and arguments[name,data type]).
string Convert(const CXString& s)
{
string result = clang_getCString(s);
clang_disposeString(s);
return result;
}
void print_function_prototype(CXCursor cursor)
{
// TODO : Print data!
auto type = clang_getCursorType(cursor);
auto function_name = Convert(clang_getCursorSpelling(cursor));
auto return_type = Convert(clang_getTypeSpelling(clang_getResultType(type)));
int num_args = clang_Cursor_getNumArguments(cursor);
for (int i = 0; i < num_args; ++i)
{
auto arg_cursor = clang_Cursor_getArgument(cursor, i);
auto arg_name = Convert(clang_getCursorSpelling(arg_cursor));
if (arg_name.empty())
{
arg_name = "no name!";
}
auto arg_data_type = Convert(clang_getTypeSpelling(clang_getArgType(type, i)));
}
}
CXChildVisitResult functionVisitor(CXCursor cursor, CXCursor /* parent */, CXClientData /* clientData */)
{
if (clang_Location_isFromMainFile(clang_getCursorLocation(cursor)) == 0)
return CXChildVisit_Continue;
CXCursorKind kind = clang_getCursorKind(cursor);
if ((kind == CXCursorKind::CXCursor_FunctionDecl || kind == CXCursorKind::CXCursor_CXXMethod || kind == CXCursorKind::CXCursor_FunctionTemplate || \
kind == CXCursorKind::CXCursor_Constructor))
{
print_function_prototype(cursor);
}
return CXChildVisit_Continue;
}
You could try using clang_Cursor_getMangling() and demangle the result in order to get the complete definition.
I'm using the following for a project I am working on and it works great for the definition. TL&DR clang_getCursorPrettyPrinted with the policy TerseOutput set to true.
std::string getStdString(const CXString &s)
{
std::string rv = clang_getCString(s);
clang_disposeString(s);
return rv;
}
bool isFunctionImplementation(CXCursor &cursor,std::string &decl,std::string &filename,unsigned &lineno)
{
std::string cs = getStdString(clang_getCursorPrettyPrinted(cursor,nullptr));
if (cs.find('{') == std::string::npos) // Just a declaration, not the "meat" of the function, so we dont care
return false;
clang::LangOptions lo;
struct clang::PrintingPolicy pol(lo);
pol.adjustForCPlusPlus();
pol.TerseOutput = true;
pol.FullyQualifiedName = true;
decl = getStdString(clang_getCursorPrettyPrinted(cursor,&pol));
CXSourceLocation location = clang_getCursorLocation( cursor );
CXFile f;
lineno = 0;
filename = "(None)";
clang_getSpellingLocation(location,&f,&lineno,nullptr,nullptr);
if (lineno)
{
filename = getStdString(clang_File_tryGetRealPathName(f));
}
return isAllowedDirectory(filename);
}
This one checks if the function call is "meat" or just a definition. Obviously you can adjust as needed, including writing your own isAllowedDirectory function. Just pass the cursor, two strings and an unsigned into this as you walk your AST when you hit a declaration type.
I use the following, shorter way with clang 10 (though its using a matcher, not a cursor):
The 2 helper functions are general helpers to get the code snippet as a string.
// helper function 1: find position of end of token
SourceLocation
end_of_the_end(SourceLocation const & start_of_end, SourceManager & sm)
{
using namespace clang;
LangOptions lopt;
return Lexer::getLocForEndOfToken(start_of_end, 0, sm, lopt);
}
// helper function 2:
std::string getSymbolString(clang::SourceManager & sm,
const clang::SourceRange & range)
{
return std::string(sm.getCharacterData(range.getBegin()),
sm.getCharacterData(end_of_the_end(range.getEnd(), sm)));
}
The actual code snippet to get the function declaration string is:
// ... in run() of a matcher:
virtual void run(corct::result_t const & result) override
{
using namespace clang;
FunctionDecl * f_decl = const_cast<FunctionDecl *>(
result.Nodes.getNodeAs<FunctionDecl>(fd_bd_name_));
if(f_decl) {
SourceManager & sm(result.Context->getSourceManager());
FunctionDecl * f_decl = const_cast<FunctionDecl *>(
result.Nodes.getNodeAs<FunctionDecl>(fd_bd_name_));
auto full_decl_string =
getSymbolString(sm, f_decl->DeclaratorDecl::getSourceRange());
}
}
This will output inline bool test2(std::string const & str, std::vector<std::string> & sss) for the following function:
inline bool test2(std::string const & str, std::vector<std::string> & sss)
{
return true;
}

How to perform Image comparison in Appium?

I need one help.
I am using Appium and I have a scenerio wherein I need to capture an image from the app under test, preserve that image as a baseline image and then capture another image from that app under test and then perform an image comparison between these two images.
Can anyone guide me how to do this please.
This is how you do it:
#Test(dataProvider = "search")
public void eventsSearch(String data) throws InterruptedException, IOException {
Thread.sleep(2000);
boolean status = false;
//WebElement img = driver.findElementByClassName("android.widget.ImageView");
//take screen shot
File screen = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
// for (String event : events) {
driver.findElementById("your id")
.sendKeys(data);
driver.hideKeyboard();
List<WebElement> list = driver
.findElementsByXPath("//*[#class='android.widget.TextView' and #index='1']");
System.out.println(list.size());
int i = 0;
for (WebElement el : list) {
String eventList = el.getText();
System.out.println("events" + " " + eventList);
if (eventList.equals("gg")) {
status = true;
break;
}
i++;
}
//capture image of searched contact icon
List<WebElement > imageList = driver.findElementsByXPath("//*[#class='android.widget.ImageView' and #index='0']");
System.out.println(imageList.size());
System.out.println(i);
WebElement image = imageList.get(1);
Point point = image.getLocation();
//get element dimension
int width = image.getSize().getWidth();
int height = image.getSize().getHeight();
BufferedImage img = ImageIO.read(screen);
BufferedImage dest = img.getSubimage(point.getX(), point.getY(), width,
height);
ImageIO.write(dest, "png", screen);
File file = new File("Menu.png");
FileUtils.copyFile(screen, file);
//verify images
verifyImage("Menu.png", "Menu.png" );
//Assert.assertTrue(status, "FAIL Event doesn't match" + data);
}
#DataProvider(name = "search")
public Object[][] searchData() {
return new Object[][] { { "gg" } };
}
public void verifyImage(String image1, String image2) throws IOException{
File fileInput = new File(image1);
File fileOutPut = new File(image2);
BufferedImage bufileInput = ImageIO.read(fileInput);
DataBuffer dafileInput = bufileInput.getData().getDataBuffer();
int sizefileInput = dafileInput.getSize();
BufferedImage bufileOutPut = ImageIO.read(fileOutPut);
DataBuffer dafileOutPut = bufileOutPut.getData().getDataBuffer();
int sizefileOutPut = dafileOutPut.getSize();
Boolean matchFlag = true;
if(sizefileInput == sizefileOutPut) {
for(int j=0; j<sizefileInput; j++) {
if(dafileInput.getElem(j) != dafileOutPut.getElem(j)) {
matchFlag = false;
break;
}
}
}
else
matchFlag = false;
Assert.assertTrue(matchFlag, "Images are not same");
}

Multiple Bills Printing in C#

I am developing a module in a billing system for a national Utility. The module is supposed to pick all successfully billed customers and print their bills.Bills are written as text files and saved on a local folder and the program has to pick them up and print them one by one.I'm using a DFX-9000 printer and pre-formatted roll paper,however,each time a new bill comes in,the printer skips some space before it prints it which distorts the 2nd and following bills.
I tried putting all the bills in a single text file which prints well when opened in notepad but not in my code.
Here is part of my code
Font printFont = new Font("Lucida Console", 10);
//static string filename;
StreamReader reader = new StreamReader(Filename);
public void Print()
{
try
{
PrintDocument pd = new PrintDocument();
pd.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("myPaper", 826, 1169);
pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
//pd.DefaultPageSettings.PrinterSettings.IsPlotter = true;
pd.DefaultPageSettings.PrinterResolution.Kind = PrinterResolutionKind.Custom;
pd.PrintPage += new PrintPageEventHandler(this.PrintTextFileHandler);
pd.Print();
if (reader != null)
reader.Close();
Console.WriteLine("Printout Complete");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void PrintTextFileHandler(object sender, PrintPageEventArgs pe)
{
StringFormat sf = new StringFormat();
Graphics g = pe.Graphics;
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = 40;//pe.MarginBounds.Left;
float topMargin = pe.MarginBounds.Top;
string line = null;
linesPerPage = 500;// pe.MarginBounds.Height / printFont.GetHeight(g);
while (count <= linesPerPage &&((line = reader.ReadLine()) != null))
{
yPos = topMargin + (count * printFont.GetHeight(g));
g.DrawString(line, printFont, Brushes.Black, leftMargin, yPos);
count++;
}
if (line != null)
{
pe.HasMorePages = true;
}
else
{
pe.HasMorePages = false;
}
Could your printing.papersize be wrong? I notice it's 1169, doesn't standard paper stop at 1100?

Read Image stored in Oracle using Long DataType

I want to read the image stored in Oracle Long datatype.
Number of images are stored in a remote Oracle database in a column with datatype long. I just need to retrieve those images and show them on my aspx page.
I could retrieve the image from database but when tried to caste it to byte array, it threw error that, string can not be converted to byte[]'.
Anybody have any suggestions on how to retrieve these images stored in long column in database.
byte[] signatureBlobReceived = cls_TBL_BROKER_BL.GetInstance().GetSignatureBlobFromAccountNumber_BL(strCRNnumber);
return File(signatureBlobReceived, "image/jpeg");
public byte[] GetSignatureBlobFromAccountNumber_BL()
{
object SignatureBlob = null;
Database db = DatabaseFactory.CreateDatabase("imageConnectionString");
DbCommand dbc = db.GetSqlStringCommand(ConfigurationSettings.AppSettings["signqry"].ToString());
dbc.CommandType = CommandType.Text;
SignatureBlob = db.ExecuteScalar(dbc);
byte[] array = Encoding.ASCII.GetBytes(Convert.ToString(SignatureBlob));
string aa = string.Empty;
return array;
}
Query used is:
<add key="signqry" value="SELECT image FROM table1"/> `
Try this (odp.net)
string connStr = "User Id=user;Password=pwd;Data Source=mySID;";
OracleConnection _conn = new OracleConnection(connStr);
_conn.Open();
string sel = #"select long_raw_col from long_raw_test";
OracleCommand cmd = new OracleCommand(sel, _conn);
cmd.InitialLONGFetchSize = 5000;
OracleDataReader reader = cmd.ExecuteReader();
int rows = 0;
// loop through rows from table
while (reader.Read())
{
rows++;
byte[] buf = new byte[5000];
long bytesRead = reader.GetBytes(reader.GetOrdinal("long_raw_col"), 0, buf, 0, 5000);
FileStream fs = new FileStream("C:\\test\\test_long" + rows + ".dat", FileMode.Create);
fs.Write(buf, 0, (int)bytesRead);
fs.Close();
Console.WriteLine("Row " + rows + ": Read " + bytesRead + " bytes from table, see test_long" + rows + ".dat");
}
This example just reads the long raw data from Oracle into a byte array, then outputs to a file. Note the InitalLONGFetchSize > 0.
I use this class :my database is informix and the images are stored in Byte type .Hope this can help you.
public class MyPhoto
{
public static Stream RetrievePhoto()
{
DBConnection DAL_Helper = new DBConnection(ConfigurationSettings.AppSettings["connection"].ToString());
Byte[] myByteBuff;
Stream myImgStream;
string qry = "----------";
DataTable dt = DAL_Helper.Return_DataTable(qry);
try
{
if (dt.Rows.Count > 0)
{
if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()))
{
myByteBuff = (Byte[])((object)(dt.Rows[0][0]));
myImgStream = new MemoryStream(myByteBuff);
}
else
{
myImgStream = RetrievePhotoNoProfile();
}
}
else
{
myImgStream = RetrievePhotoNoProfile();
}
}
catch (Exception ex)
{
myImgStream = RetrievePhotoNoProfile();
}
return myImgStream;
}
public static byte[] StreamToByteArray(Stream stream)
{
if (stream is MemoryStream)
{
return ((MemoryStream)stream).ToArray();
}
else
{
return ReadFully(stream);
}
}
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[input.Length];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
private static Stream RetrievePhotoNoProfile()
{
string noprofileimgPath = HttpContext.Current.Server.MapPath("~/images/noprofile.png");
System.IO.FileStream fs = new System.IO.FileStream(noprofileimgPath, System.IO.FileMode.Open, FileAccess.Read);
byte[] ba = new byte[fs.Length];
fs.Read(ba, 0, (int)fs.Length);
Stream myImgStream = new MemoryStream(ba);
fs.Close();
return myImgStream;
}
public static Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
}

Resources