What is the Best way to creat multiple object Autocad? - visual-c++

I am learning about ObjectArx and as far as I know there are 3 common ways to create objects in Arx:
use acdbEntMake
use record.append (entity)
use a combination of record.append and transaction
so, my questions is:
can someone help me when I should use them in each case?
Do they have a big difference in performance with each other?
I am hesitant to use acdbentmake when the number of objects is large compared to the following two methods because I see very few examples that mention it.

I don't know what kind of entity You are creating but:
You don't need to use acdbEntMake in most cases. I'm using ObjectARX since about 8 years and never used it ;)
Transaction is used in .Net version of ObjectARX but You tagged visual-c++ so I suppose it's not this case.
If You warring about drawing large number of entities just test it. draw in the way You know and measure needed time. As long as You and Your clients accept drawing time, the way You are using is OK. In the future You always can refactor the code to get better performance if necessary.
To create for example line You may use this sample:
Acad::ErrorStatus AddLine(const AcGePoint3d SP , const AcGePoint3d EP , AcDbObjectId& id , AcDbObjectId Block )
{
AcDbLine* Line = new AcDbLine();
Line->setStartPoint(SP);
Line->setEndPoint(EP);
Acad::ErrorStatus es = Add( Line , Block );
if (es != Acad::eOk) { return es ;}
es = Line->close();
id = Line->objectId();
return es ;
}
Acad::ErrorStatus Add( AcDbEntity * pEnt, AcDbObjectId parent)
{
if ( !pEnt ) {
return Acad::eNullEntityPointer ;
}
Acad::ErrorStatus es;
if (parent.isNull()) {
parent = getActiveSpace()->objectId();
}
AcDbObject* pObj = NULL;
es = acdbOpenObject(pObj, parent , AcDb::kForWrite) ;
if (es != Acad::eOk) {
return es;
}
if (!pObj->isKindOf(AcDbBlockTableRecord::desc())) {
pObj->close();
return Acad::eWrongObjectType;
}
AcDbBlockTableRecord* Blok = AcDbBlockTableRecord::cast(pObj);
if ((es = Blok->appendAcDbEntity(pEnt)) != Acad::eOk )
{
Blok->close();
return es;
}
Blok->close();
return Acad::eOk;
}
AcDbBlockTableRecord* getActiveSpace()
{
AcDbBlockTableRecord* pOutVal = NULL;
AcDbDatabase * pDb = acdbHostApplicationServices()->workingDatabase();
if (!pDb) return NULL;
AcDbObjectId ActiveStpaceId = pDb->currentSpaceId();
AcDbObject* pObj = NULL;
Acad::ErrorStatus es;
es = acdbOpenObject(pObj, ActiveStpaceId , AcDb::kForRead);
if( es == Acad::eOk)
{
pOutVal = AcDbBlockTableRecord::cast(pObj);
es = pObj->close();
}
return pOutVal;
}

Related

Eclipse JDT resolve unknown kind from annotation IMemberValuePair

I need to retrieve the value from an annotation such as this one that uses a string constant:
#Component(property = Constants.SERVICE_RANKING + ":Integer=10")
public class NyServiceImpl implements MyService {
But I am getting a kind of K_UNKNOWN and the doc says "the value is an expression that would need to be further analyzed to determine its kind". My question then is how do I perform this analysis? I could even manage to accept getting the plain source text value in this case.
The other answer looks basically OK, but let me suggest a way to avoid using the internal class org.eclipse.jdt.internal.core.Annotation and its method findNode():
ISourceRange range = annotation.getSourceRange();
ASTNode annNode = org.eclipse.jdt.core.dom.NodeFinder.perform(cu, range);
From here on you should be safe, using DOM API throughout.
Googling differently I found a way to resolve the expression. Still open to other suggestions if any. For those who might be interested, here is a snippet of code:
if (valueKind == IMemberValuePair.K_UNKNOWN) {
Annotation ann = (Annotation)annotation;
CompilationUnit cu = getAST(ann.getCompilationUnit());
ASTNode annNode = ann.findNode(cu);
NormalAnnotation na = (NormalAnnotation)annNode;
List<?> naValues = na.values();
Optional<?> optMvp = naValues.stream()
.filter(val-> ((MemberValuePair)val).getName().getIdentifier().equals(PROPERTY))
.findAny();
if (optMvp.isPresent()) {
MemberValuePair pair = (MemberValuePair)optMvp.get();
if (pair.getValue() instanceof ArrayInitializer) {
ArrayInitializer ai = (ArrayInitializer)pair.getValue();
for (Object exprObj : ai.expressions()) {
Expression expr = (Expression)exprObj;
String propValue = (String)expr.resolveConstantExpressionValue();
if (propValue.startsWith(Constants.SERVICE_RANKING)) {
return true;
}
}
}
else {
Expression expr = pair.getValue();
String propValue = (String)expr.resolveConstantExpressionValue();
if (propValue.startsWith(Constants.SERVICE_RANKING)) {
return true;
}
}
}
//report error
}
private CompilationUnit getAST(ICompilationUnit compUnit) {
final ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(compUnit);
parser.setResolveBindings(true); // we need bindings later on
CompilationUnit unit = (CompilationUnit)parser.createAST(null);
return unit;
}

Flow for conditionals inside sequence diagram

I need to document in UML sequence diagram the method setRepresentative. This is the code method:
class ReptoolController extends PageController {
private function setRepresentative($request, $action, $case)
{
...
$repappConfig = new RepappConfig();
$repappConfig = $this->getDoctrine()->getRepository('AppBundle:RepappConfig')->findOneBy(array("app_id"=>$id));
$project_id = $repappConfig->getProjectId();
$company_id = $repappConfig->getCompanyId();
$project = $this->getDoctrine()->getRepository('AppBundle:Project')->find($project_id);
$brand = $this->getDoctrine()->getRepository('AppBundle:Brand')->findOneBy(array("project"=>$project_id));
$company = $this->getDoctrine()->getRepository('AppBundle:Company')->find($company_id);
$territory = new Territory();
if(is_numeric($territory_name))
{
$tempName = "ID";
}
else
{
$tempName = "territory";
}
if($territory = $this->getDoctrine()->getRepository('AppBundle:Territory')->findOneBy(array($tempName=>$territory_name)))
{
$territory_id = $territory->getID();
$response->territory_id = $territory_id;
if($brand)
{
$is_enabled = 1;
$position = 1;
$brand_id = $brand->getID();
$terr_brand_xrf = $this->getDoctrine()->getRepository('AppBundle:TerritoryBrandXref')->findOneBy(array("territory"=>$territory_id, "brand"=>$brand_id));
if(!$terr_brand_xrf)
{
$terr_brand_xref = new TerritoryBrandXref($territory,$brand,$position);
$terr_brand_xref->setIsEnabled($is_enabled);
$terr_brand_xref->updateTimestamps();
$em = $this->getDoctrine()->getEntityManager();
$em->persist($terr_brand_xref);
$em->flush();
}
}
}
else
{
$territory->setTerritory($territory_name);
$territory->setProject($project);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($territory);
$em->flush();
$territory_id = $territory->getID();
$response->territory_id = $territory_id;
if($brand)
{
$is_enabled = 1;
$position = 1;
$brand_id = $brand->getID();
$response->brand_id= $brand_id;
$terr_brand_xref = new TerritoryBrandXref($territory,$brand,$position);
$terr_brand_xref->setIsEnabled($is_enabled);
$terr_brand_xref->updateTimestamps();
$em = $this->getDoctrine()->getEntityManager();
$em->persist($terr_brand_xref);
$em->flush();
}
}
$controller_response = new Response( json_encode($response) );
$controller_response->headers->set('Content-Type', 'application/json; charset=utf-8');
return $controller_response;
}
}
This is the diagram as I have it now:
How do I diagram the conditionals inside this piece of code:
if($territory = $this->getDoctrine()->getRepository('PDOneBundle:Territory')->findOneBy(array($tempName=>$territory_name)))
{
...
} else {
...
}
How do I call the inside methods?
Actually what you are asking does not make sense (see my comment here: UML Sequence Diagram help needed). SDs are not meant to repeat algorithms in graphical notation. Code is much better for that purpose. The possibility to show loops and if conditions inside SDs is meant to be used only for a high level view of the system.
In your case you should concentrate on certain aspects of the runtime. Just like an important snapshot. Create a SD for the tech use case with a really sequential message flow. Eventually create more than one SD to light different aspects. But do NOT try to press the whole algorithm in a single SD.

Wrap conditional into a function or not represent it at all in a sequence diagram?

I've this PHP controller class (belongs to Symfony2 bundle):
class ReptoolController extends PageController
{
// ...
private function _get($request, $action, $case)
{
$app_id = $this->getRequested('app_id');
if( ( $repappConfig = $this->getDoctrine()->getRepository('PDOneBundle:RepappConfig')->findOneBy(array("app_id"=>$app_id))) )
{
$current_timestamp = new \DateTime(date('Y-m-d'));
if($repappConfig->getExpireDate())
$expire_date = $repappConfig->getExpireDate()->getTimestamp();
else
{
$temp = $current_timestamp;
$temp->modify("+7 day");
$temp->format("Y-m-d");
$expire_date = $temp->getTimestamp();
}
if($expire_date < $current_timestamp->getTimestamp())
{
$response = new \stdClass();
$response->status = FormUtilities::RESPONSE_STATUS_BAD;
$controller_response = new Response( json_encode($response) );
$controller_response->headers->set('Content-Type', 'application/json; charset=utf-8');
return $controller_response;
}
}
switch($case)
{
// ...
case FormUtilities::CASE_BRAND_CUSTOM_MESSAGES:
return $this->getBrandCustomMessages($request, $action, $case);
break;
// ...
default:
$response = new \stdClass();
$response->status = FormUtilities::RESPONSE_STATUS_BAD;
$controller_response = new Response( json_encode($response) );
$controller_response->headers->set('Content-Type', 'application/json; charset=utf-8');
return $controller_response;
break;
}
}
// ...
private function getBrandCustomMessages($request, $action, $case)
{
$id = $this->getRequested('app_id');
$reptool_records = $this->getRequestedSync();
$response = new \stdClass();
$response->status = FormUtilities::RESPONSE_STATUS_BAD;
$repappConfig = new RepappConfig();
$repappConfig = $this->getDoctrine()->getRepository('PDOneBundle:RepappConfig')->findOneBy(array("app_id"=>$id));
$project_id = $repappConfig->getProjectId();
$brand_table = $this->getDoctrine()->getRepository('PDOneBundle:Brand')->findBy(array("project"=>$project_id));
if($brand_table)
{
foreach($brand_table as $bt)
{
$brand_id = $bt->getID();
$brandCustomMessages = new BrandCustomMessages();
if( $brandCustomMessages = $this->getDoctrine()->getRepository('PDOneBundle:BrandCustomMessages')->findBy(array("brand_id"=>$brand_id) ))
{
$sync = array();
foreach ($brandCustomMessages as $brandCustomMessage)
{
$response->status = FormUtilities::RESPONSE_STATUS_VALID;
$brandCustMess = new PDOneResponse(
$brandCustomMessage->getID(),
strtotime($brandCustomMessage->getModifiedAt()->format("Y-m-d H:i:s"))
);
$brandCustMess->id = $brandCustomMessage->getID();
$brandCustMess->message_text = $brandCustomMessage->getMessageText();
$brandCustMess->message_code = $brandCustomMessage->getMessageCode();
$brandCustMess->brand_id = (int)$brandCustomMessage->getBrandId();
$reptool_records = $brandCustMess->setRecordStatus($reptool_records);
// ADD BACKEND RECORD TO SYNC
if($brandCustMess->status != FormUtilities::RESPONSE_STATUS_OK ) $sync[] = $brandCustMess;
}
// COMPOSITE SYNC WITH REPTOOL RECORDS
$sync = PDOneResponse::compositeSync($sync, $reptool_records);
$response->sync = $sync;
}
}
}
$controller_response = new Response( json_encode($response) );
$controller_response->headers->set('Content-Type', 'application/json; charset=utf-8');
return $controller_response;
}
// ...
I need to build a sequence diagram (SD) for the flow from the actor PDOneApp (which is an iPad application making get|set request to that controller). This is what I have done in the SD Version1, SD Version 2:
Version 1
Version 2
About the diagrams shown above I have the following doubts and taking as example the code shown above also:
Which diagram is the right one?
The calls (meaning the representation at diagram) for the entities: RepappConfig and Brand are right? In the code this calls are made from within the method getBrandCustomMessages() and I have them directly from the controller ReptoolController which makes me think that's wrong. If this is the case how they should be represented?
I know that SD is not mean to be for represent code as it is but, how do you represent conditionals on the function? Perhaps I can wrap the conditional in a function and call that function from within the getBrandCustomMessages() is this one the right way? What did you recommend me on this doubt?
As you will see on the function the last return is a Response object, is that part right on the diagram? Or the line should be dashed with return label?
Can any give some help for finish this diagram and understand the conditional part for UML SD?
Your 2nd diagram shows the internal call to getBrandCustomMessages correctly.
If you really want to show if then use fragments (http://www.uml-diagrams.org/sequence-diagrams-combined-fragment.html). You can divide fragments into single partitions (if/else or case; whatever fits).
The last response should not go to an entity but as return message (from after the internal call) to the actor. That's likely what you intend to show.

Get the most possible token types according to line and column number in ANTLR4

I would like to get a list of most possible list of tokens for a given location in the text (line and column number) to determine what has to be populated for auto code completion. Can this be easily achieved using ANTLR 4 API.
I want to get the possible list of tokens for a given location because the user might be writing/editing somewhere in the middle of the text which still guarantees the possible list of tokens.
Please give me some guidelines because I was unable to find an online resource on this topic.
One way to get tokens by line number is to create a ParseTreeListener for your grammar, use it to walk a given ParseTree and index TerminalNodes by line number. I don't know C#, but here is how I've done it in Java. Logic should be similar.
public class MyLineIndexer extends MyGrammarParserBaseListener {
protected MultiMap<Integer, TerminalNode> filelineTokenIndex;
#Override
public void visitTerminal(#NotNull TerminalNode node) {
// map every token to its file line for searching later...
if ( node.getSymbol() != null ) {
List<TerminalNode> tokens;
Integer line = node.getSymbol().getLine();
if (!filelineTokenIndex.containsKey(line)) {
tokens = new ArrayList<>();
filelineTokenIndex.put(line, tokens);
} else {
tokens = filelineTokenIndex.get(line);
}
tokens.add(node);
}
super.visitTerminal(node);
}
}
then walk the parse tree the usual way...
ParseTree parseTree = ... ; // parse it how you want to
MyLineIndexer indexer = new MyLineIndexer();
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(indexer, parseTree);
Getting the token at a line and range is now reasonably straight forward and efficient assuming you have a reasonable number of tokens on a line. For example you can add another method to the Listener like this:
public TerminalNode findTerminalNodeAtCaret(int caretPos, int caretLine) {
if (caretPos <= 0) return null;
if (this.filelineTokenIndex.containsKey(caretLine)) {
List<TerminalNode> nodes = filelineTokenIndex.get(caretLine);
if (nodes.size() == 0) return null;
int tokenEndPos, tokenStartPos;
for (TerminalNode n : nodes) {
if (n.getSymbol() != null) {
tokenEndPos = n.getSymbol().getCharPositionInLine() + n.getText().length();
tokenStartPos = n.getSymbol().getCharPositionInLine();
// If the caret is within this token, return this token
if (caretPos >= tokenStartPos && caretPos <= tokenEndPos) {
return n;
}
}
}
}
return null;
}
You will also need to ensure your parser allows for 'loose' parsing. While a language construct is being typed, it is likely not to be valid. Your Parser rules should allow for this.

How does Enumerate work in MonoTouch?

In MonoTouch I need to process each object in an NSSet. My attempt, using Enumerate, is as follows:
public override void ReturnResults ( BarcodePickerController picker, NSSet results )
{
var n = results.Count; // Debugging - value is 3
results.Enumerate( delegate( NSObject obj, ref bool stop )
{
var foundCode = ( obj as BarcodeResult ); // Executed only once, not 3 times
if ( foundCode != null )
{
controller.BarcodeScannedResult (foundCode);
}
});
// Etc
}
Although the method is invoked with three objects in results, only one object is processed in the delegate. I would have expected the delegate to be executed three times, but I must have the wrong idea of how it works.
Unable to find any documentation or examples. Any suggestion much appreciated.
You have to set the ref parameter to false. This instructs the handler to continue enumerating:
if ( foundCode != null )
{
controller.BarcodeScannedResult (foundCode);
stop = false; // inside the null check
}
Here is the ObjC equivalent from Apple documentation.
Or you could try this extension method to make it easier..
public static class MyExtensions {
public static IEnumerable<T> ItemsAs<T>(this NSSet set) where T : NSObject {
List<T> res = new List<T>();
set.Enumerate( delegate( NSObject obj, ref bool stop ) {
T item = (T)( obj ); // Executed only once, not 3 times
if ( item != null ) {
res.Add (item);
stop = false; // inside the null check
}
});
return res;
}
}
Then you can do something like:
foreach(BarcodeResult foundCode in results.ItemsAs<BarcodeResult>()) {
controller.BarcodeScannedResult (foundCode);
}
Note: Keep in mind this creates another list and copies everything to it, which is less efficient. I did this because "yield return" isn't allowed in anonymous methods, and the alternative ways I could think of to make it a real enumerator without the copy were much much more code. Most of the sets I deal with are tiny so this doesn't matter, but if you have a big set this isn't ideal.

Resources