I'm using JavaScriptCore in one of my Objective-C project, and I'd like to know at any time what's the current file & line when falling into a JS callback.
There is no way to do it with the public headers, so I took a look at the sources and it seems possible to access the file & line by using some C++ code.
// ctx is a JSContextRef, that's the only type I have an access to
JSC::JSValue jsCtx = toJS(ctx);
CodeBlock* codeBlock = jsCtx->codeBlock();
// Line
unsigned sourceOffset = codeBlock->sourceOffset();
// Source URL
SourceProvider* sourceProvider = codeBlock->source();
const String& url = sourceProvider->url();
It obviously requires the definitions of JSC, JSValue, CodeBlock, and SourceProvider. I have all these in separate headers, but it's really massive.
Should I directly include those headers?
What if those files require other headers? I might end by having multiple headers that I won't use.
Let's forget that the internal source code might change: is what I want to do even possible?
You can know this information from the public Headers itself. Here you go:
When the exception occurs, the exception object contains the following keys:
line, sourceId, sourceURL, name, message
You can access the values for these keys to find in which file (sourceURL) and in which line number (line) the exception has occurred.
Example:
JSObjectRef exceptionObj = JSValueToObject(context, exception, NULL);
//Convert the exceptionObj into dictionary (I leave the implementation of this to you..)
NSDictionary *exceptionDict = [self convertJSObjectToDictionary:exceptionObj];
NSString *lineNumber = [exceptionDict objectForKey:#"line"];
NSString *fileName = [exceptionDict objectForKey:#"sourceURL"];
NSLog(#"Exception has occurred in file:%# at line number:%#", fileName, lineNumber);
Hope this helps!
~ Sunil Phani Manne
Related
I want to get the email body from my Gmail account for an email so i use this code i found it in an example for how to read emails using c++ builder pop3
the code to extract body used
TIdText *EText;
int message = SpinEdit1->Value;
MyPoP3->Retrieve(message, MyEmail);
Edit1->Text = MyEmail->Subject + " | " + MyEmail->From->Address;
Memo1->Clear();
for (int i = 0; i < MyEmail->MessageParts->Count; i++) {
Memo1->Lines->Add(MyEmail->MessageParts->Items[i]->ContentType);
EText = dynamic_cast<TIdText*>(MyEmail->MessageParts->Items[i]);
Memo1->Lines->Add(EText->Body);
}
the problem is that i got undefine symbol to TidText and what i tried is to change it from TIdText to TIdMessage, but i got that i can't convert to it.
also i tried to try this without loop or something MyEmail->Body->Text
this return empty string.
the video i got this code from it here i don't know maybe the c++ builder he use is old. now i want to know how to extract the body text from the email address.
Thanks in advance.
the problem is that i got undefine symbol to TidText
Your code is missing an #include <IdText.hpp> statement.
what i tried is to change it from TIdText to TIdMessage, but i got that i can't convert to it.
Because TIdMessage does not contain nested TIdMessage objects.
also i tried to try this without loop or something MyEmail->Body->Text this return empty string.
If your email is MIME encoded, its text is not stored in the TIdMessage::Body property, but in a nested TIdText object within the TIdMessage::MessageParts collection. You have to look at the TIdMessage::ContentType property to know what kind of structure the email contains. For instance, if the CT begins with text/, the text is in the TIdMessage::Body. But if the CT begins with multipart/, the text is somewhere in the TIdMessage::MessageParts instead.
You should read this blog article on Indy's website for an example of how emails might be structured:
HTML Messages
the video i got this code from it here i don't know maybe the c++ builder he use is old.
No, it is not.
I made a test JWT using something like the following code
String jwt = Jwts.builder()
.setHeaderParam("typ", "jwt")
.setId("myid")
.setIssuer("ExampleIssuer")
.setSubject("JohnDoe")
.setIssuedAt(Date.from(LocalDateTime.now().toInstant(ZoneOffset.ofHours(-4))))
.setExpiration(Date.from(LocalDateTime.now().toInstant(ZoneOffset.ofHours(-4)).plusSeconds(600)))
.claim("perms",perms)
.signWith(SignatureAlgorithm.HS512, "SECRET")
.compact();
"perms" is a custom claim, which contains an ArrayList of Strings (permissions).
So when I receive the JWT back, I use the following code
try{
Jwt<?, ?> claims = Jwts.parser().setSigningKey("SECRET").parse(jwt);
System.out.println(claims.getBody().toString());
} catch (SignatureException e){
//Error
}
And I get something like
{jti=myid, iss=ExampleIssuer, sub=JohnDoe, iat=1495678299, exp=1495678899, perms=[CREATE, VIEW]}
My question is: is this the correct (intended) way to get the claims back? It seems from now I will need to parse the result with a custom method, but I think somehow that is not the intended way.
Thank you.`
I found a solution, not sure if the intended one, but it works. I need to use
Claims claims = new DefaultClaims();
try{
claims = Jwts.parser().setSigningKey("SECRET").parseClaimsJws(jwt).getBody();
} catch (SignatureException e){
//Signature error
}
I can use Map methods on claims, but also the built-in methods to recover the individual claims:
String jti = claims.getId();
String iss = claims.getIssuer();
String sub = claims.getSubject();
String iat = claims.getIssuedAt().toString();
String exp = claims.getExpiration().toString();
#SuppressWarnings("unchecked")
ArrayList<String> perms = (ArrayList<String>) claims.get("perms");
I think I can suppress the warning on the unchecked casting because since I created the custom claim with the same value class, I know what to expect on it. Now the claims in the token are parsed correctly into variables I can work with.
Requirement:
Get the CodeElement (Function/Class etc) from the current cursor position in C++ source and Header files in Visual Studio using Automation Model EnvDTE.
Problem:
When the cursor is in a header file and I iterate the code elements from that header file for getting their position, I get the corresponding elements position in its source file. Because of which I am getting "Value does not fall within specified range" exception.
Example:
This is the code snippet
private CodeElement GetCodeElementAtTextPoint(vsCMElement eRequestedCodeElementKind, CodeElements codeElements, TextPoint objCursorTextPoint)
{
CodeElement objResultCodeElement = null;
CodeElements colCodeElementMembers;
CodeElement objMemberCodeElement;
if (codeElements != null)
{
foreach (CodeElement objCodeElement in codeElements)
{
if (objCodeElement.Kind == vsCMElement.vsCMElementFunction)
{
var infoLoc = objCodeElement as CodeType;
}
if (objCodeElement.StartPoint.GreaterThan(objCursorTextPoint))
{
}
else if (objCodeElement.EndPoint.LessThan(objCursorTextPoint))
{
}
else
..
In the above code snippet objCodeElement.StartPoint gives me the start point of that CodeElement in source file and hence I am getting the exception at that line
e.g. Suppose in a header file function fun() is declared at line 20 and defined at line 901 in the source file. If I clicked on line 20 then during iteration I get the line number 901 for function fun() which is clearly not is range of header file.
Note: I have tried using CodeElementFromPoint method in FileCodeModel and VCFileCodeModel but it is not reliable.
Did anybody encounter such issue? Please help.
Or please suggest me the correct approach to satisfy my requirement.
Thanks in advance.
Figured it out myself
The property StartPoint in "objCodeElement.StartPoint" by default gives a position of the element definition.
So instead of using property I used function get_StartPointOf on CodeElement. This function takes two parameters first 'Part of the element' and second 'element from where' (declaration or definition). So giving the second argument as a declaration will give start position of the element declaration in its header file.
e.g.
startPoint = objCodeElement.get_StartPointOf(vsCMPart.vsCMPartWholeWithAttributes, vsCMWhere.vsCMWhereDeclaration);
endPoint = objCodeElement.get_EndPointOf(vsCMPart.vsCMPartWholeWithAttributes, vsCMWhere.vsCMWhereDeclaration);
I work with Tika File Detector. It checks which file Typ my file is.
At the moment my Code is like this
if (Type.endsWith("application/msword")){ //Match if its .doc
}
else if (Type.endsWith("application/vnd.ms-powerpoint")){ //Match if its .ppt
}
else if (Type.endsWith("application/vnd.ms-excel")){ //Match if its .xls
}
else if (Type.endsWith("application/vnd.openxmlformats-officedocument.wordprocessingml.document")){ //Match if its .docx
Now I want to Store the Result in a list, which list has two entries. When I checked all files I want to save the list in a csv file.
I tried this with a hashmap but that didn't work.
You could use parallel arrays. I'm guessing one for the file name and one for the file type, but there is no need to store the info in a temporary data structure if you are just writing to .csv.
If you want to write filename, mime string and extension to a csv, do something like this, where you iterate through your files in main()...
static Tika tika = new Tika();
static MimeTypes mimeTypes = TikaConfig.getDefaultConfig().getMimeRepository();
static void processFile(Path p, Writer writer) throws IOException, MimeTypeException {
String mimeString = tika.detect(p);
MimeType mt = mimeTypes.forName(mimeString);
writer.write(String.format("%s,%s,%s,%n",
p.getFileName(),mimeString,mt.getExtension()));
}
You'll want to add exception handling, and it is always better to use a genuine CSV writer (see Apache Commons csv) than to "hope" than none of your data has a comma/newline or to roll your own.
I'm trying to control Word through a c++ builder 5 application. I would like to
open a ".dot" model file created with Word and modify it. In the ".dot" model file
there are some fields. For example, Title, LastName, FirstName, Address
and so on, and I would like to modify these fields putting text into them and then
saving file with a new name, for example "Warning.doc" leaving the ".dot" file
unaltered.
I can open the file, count the number of fields it contains, but then
when it comes to replacing each field with a string I don't know how to do because
I don't have a complete documentation on OleFunction and OlePropertyGet methods. I attach my source code to this message, can anybody help me to solve this problem please?
try
{
my_word = Variant::CreateObject("word.application");
}
catch (...)
{
Application->MessageBox("Unable to obtain Word automation object",
"Error:",MB_OK | MB_ICONERROR);
}
my_word.OlePropertySet("Visible", (Variant)true);
void __fastcall TForm1::Button2Click(TObject *Sender)
{
Variant this_doc;
Variant my_fields;
Variant test;
int k,field_count;
AnsiString test1;
AnsiString filename = "d:\\ProgrammaWord\\1-Avviso.dot";
my_docs = my_word.OlePropertyGet("Documents");
this_doc = my_docs.OleFunction("Open", filename);
my_fields = this_doc.OlePropertyGet("Fields");
field_count = my_fields.OlePropertyGet("Count");
for(k = 1; k <= field_count; k++)
{
test = my_fields.OleFunction("Item",(Variant)k);
test1 = test.OleFunction("Value"); //This instruction throws an exception
// "Value" is not a recognized parameter
// in this case
Memo1->Lines->Add(test1);
}
}
I never used word Ole but I used it for Outlook and Excel, I can't try it with word since I'm currently on OSX but you should try something similar as what I did.
The generic way of using Ole was to OleGetproperty() while you get the targeted field then OleSetProperty("action", ...).
for example when I wanted to change the color of the text in a particular cell of my excel document I used:
Variant _excel = Variant::CreateObject("Excel.Application");
Variant _workbook = _excel.OlePropertyGet("WorkBooks").OleFunction("Open", filename);
Variant _worksheet = _workbook.OlePropertyGet("WorkSheets", sheet);
_worksheet.OlePropertyGet("Cells", row, col).OlePropertyGet("Font").OlePropertySet("Color", color);
Here I instanciate an excel object, then I load a file into it (_workbook), then I select the _worksheet from the _workbook and I start my business.
Here comes the interesting part:
It concist of getting to a particular cell, getting the font object from it, and then setting the color of this font object.
Disclaimer: This is an example from my sources for excel, it's not directly related to your example, but maybe you can understand the principe with it. I can't try to figure out what you need because I have no windows right now.
Hope this can help you. Finding ressources for OLE can be fierce if you don't have the good patterns to look for.