How to escape quotation marks in Enterprise Architect Code Generation Template - code-generation

I want to give enumeration values a further description. Therefore I'm adding a custom Tagged Value to the attributes of the enumeration called Description, if a description shall be provided. The goal is, to add a custom C# attribute to the tagged enumeration attribute during code generation, but only if such a Tagged Value exists. Therefore I need to edit the code generation template for Attribute Declaration. Currently it works using:
$hasDescription = %attTag:"Description" ? "true" : "false"%
%if $hasDescription == "true"%
[Description(%qt%%attTag:"Description"%%qt%)]
%endIf%
which gives me the desired output. But if there are quotation marks in the value, it breaks the output code file. It won't compile. Therefore I need to replace/escape all quotation marks in the value field of the Tagged Value. I tried the following (in various combinations):
%REPLACE(attTag:"Description", "\"", "\\\"")%
%REPLACE(attTag:"Description", """", "\\""")%
%REPLACE(attTag:"Description", "%qt%", "%sl%%qt%")%
%REPLACE(attTag:"Description", %qt%, %sl%%qt%)%
Note: %qt% is used to insert ", %sl% is used to insert \ (reference)
None of them works. Either the string as it is will be inserted into the generated code file or nothing happens to the quotation marks in the value of Tagged Value.
So is there a way to escape those characters to be able to replace them in a string within a Code Template?
Using Enterprise Architect 13.5.1351
Question asked first on SE Software Engineering

I looked through the other templates provided and finally found the solution after some more fiddling. The macro take either some text in quotation marks or variables as parameters. Since using the escape sequences directly in the REPLACE macro didn't work, I tried assigning them to variables beforehand:
$qt = %qt%
$escape = %sl% + %qt%
$description = %REPLACE(attTag:"Description", $qt, $escape)%
That's it. Finally works. It is important to add the + between %sl% and %qt% on the second line, even though the documentation on Code Template Syntax > Literal Text states it otherwise. $escape = %sl%%qt% does not work, as it yields me just a \ without the ".
The variable $description is not necessary, but added for readability.

Related

Powershell function reference and naming conventions

I recently discovered that you can get powershell's functions by reference using the modifier $function:. But I noticed a strange problem...
By convention, POSH uses a {Verb}-{Noun} convention for function names, where {Verb} is part of aproved POSH verb names. For instance: Get-Member or Invoke-WebRequest.
The thing is, that calling $function:Get-Member, for example, is not valid because of the hyphen; it works just fine if you declare a function like ShowMessage and calls: $fn = $function:ShowMessage. So I'd like to know if there's a way to escape this call.
PS.: I do know of another option, but is much much more verbose:
function Show-Message { Write-Host "Foo"; }
$fn = (Get-Item "function:Show-Message").ScriptBlock;
$fn.Invoke();
Update: Although #PetSerAl was very helpfull and explained the problem, I'll mark #Ansgar Wiechers's response as the answer because it's better documented.
function: is a PSDrive, not a (scope)modifier. As for using it with variable-like notation ($function:name): the rules for variable names with special characters apply here as well.
From the documentation:
VARIABLE NAMES THAT INCLUDE SPECIAL CHARACTERS
Variable names begin with a dollar sign. They can include alphanumeric characters and special characters. The length of the variable name is limited only by available memory.
Whenever possible, variable names should include only alphanumeric characters and the underscore character (_).Variable names that include spaces and other special characters, are difficult to use and should be avoided.
To create or display a variable name that includes spaces or special characters, enclose the variable name in braces. This directs PowerShell to interpret the characters in the variable name literally.
Your notation should thus look like this:
${function:Show-Message}
It can be invoked like this:
& ${function:Show-Message}

How to replace similar code in VS 2017.

I am replacing our logging functionality and it is taking a long time to manually go through all of the code and replace it.
Here is the current code:
Error Messages:
cLogger.LogMessage(ComponentID.ClientID, CLASS_NAME, "AddContextMenuItem", MessageType.mtErrorMessage, "Null MenuItem provided. MenuItem's status not changed");
cLogger.LogMessage(ComponentID.ClientID, CLASS_NAME, "enableDisableToolbarItem", MessageType.mtErrorMessage, "Invalid toolbaritem provided.");
Exceptions:
cLogger.LogMessage(ComponentID.ClientID, CLASS_NAME, "enableDisableContextMenuItem", MessageType.mtException, ex);
cLogger.LogMessage(ComponentID.ClientID, CLASS_NAME, "AddToolbarItem", MessageType.mtException, exc);
Is there a simple way to create a macro (never used a macro before) or power shell or notepad++ script or something else to find and replace all of these different instances so that they look like the following:
New Error Messages:
logger.Log(LogLevel.Error, CLASS_NAME + " AddContextMenuItem - Null MenuItem provided. MenuItem's status not changed");
logger.Log(LogLevel.Error, CLASS_NAME + " enableDisableToolbarItem - Invalid toolbaritem provided.");
and
New Exceptions:
logger.Log(LogLevel.Exception, CLASS_NAME + " enableDisableContextMenuItem - " + ex);
logger.Log(LogLevel.Exception, CLASS_NAME + " AddToolbarItem - " + exc);
I am replacing the code in the entire project and it will just simply take way too long to go through and manually change all of the logging code manually. Any help is greatly appreciated.
There are a few options:
Regex Search & Replace in Visual Studio:
search for the exception example
\w+logger.LogMessage\([^,]+,([^,]+),([^,]+),[^,]+,([^\",]+)\);
replace
logger.Log(LogLevel.Exception, $1 + $2 + $3);
Use Resharper structural Search & Replace
Build a CodeFix for Roslyn
Yes, you can likely do this with a Regular Expression, easier in PowerShell perhaps than in Notepad++ or perhaps VSCode.
It's difficult to tell from your examples precisely what you are changing in each item, but the basic concept is to do the following:
Match the static text that establishes the type of item to change
Also match the variable text with wildcards (.* etc) enclosed in CAPTURING parentheses
Replace with new static text and 'rearranged' variable text using the $1, $2, etc backreferences to the capture groups (or $Matches[1] etc.)
If #3 is more complicated, you'll need to further alter the variable text before replacing -- this is where a script language has an advantage over a pure search and replace.
Here is a simplified example (PowerShell but similar in other langauges or editors that support Regexes) for statically replacing the "FunctionOldName" while swapping the order of Param1 and Param2 and altering the names based on the original names for these params:
"Function_OldName Param1 Param2" -replace 'Function_OldName\s+(\w+)\s+(\w+)',
'NewFunctionName New$2Parm New$1Parm'
The $1 and $2 are backreferences to the "1st parens" and "2nd parens" respectively in the match string.
If you can write out clear examples showing which parts of your changed text must be matched, simply altered, rearranged, or rebuilt then it might be possible to show you some more relevant examples....
You can do this across many files with either PowerShell or the editors, but generally doing it to many files is again a bit easier in a Programming language (e.g., PowerShell.)
Get-ChildItem *.PS1 -recurse | ForEach-Object {
'Function_OldName\s+(\w+)\s+(\w+)', # your match goes here
'NewFunctionName New$2Parm New$1Parm' # your replacement goes here
}

How to replace content within quotes via a file

Why I cannot use str_replace() to replace content between the ""? While I replace links within a file they get skipped since they are within quotes.
Example.
href="/path/to/file/is/here"
should be
href="/New/Path/To/File/Goes/Here"
If the paths/urls were not in quotes, str_replace() would work.
I'm assuming this is PHP. So, from the examples here:
http://php.net/manual/en/function.str-replace.php
You can see that you should not intercalate the same type of quotes.
So try changing the quotes in your code to single quotes or, change, the double quotes in your html to single quotes.
If that's not it, I hope at least that doc reference helps you.
This might help I usually code in java but php is pretty similar. Next time input part of your code so that the community can see your logic.
In your if statement on line 67 the 3rd variable $stringToSearch should be regex not the string your assigning it to. The purpose of regex as you know is to replace characters you don't want in your code as you already know
What you had that was not working:
// replacing string from files
//$stringToSearch = str_replace('"', "!!", $stringToSearch);
$stringToSearch = str_replace($toBeReplaced, $toBeReplacedWith, $stringToSearch);
//$stringToSearch = str_replace("!!", '"', $stringToSearch);
What I am thinking it should be:
$stringToRegex = str_replace('"', "!!", $stringToSearch);
$stringToSearch = str_replace($toBeReplaced, $toBeReplacedWith, $stringToRegex );
If anyone else has any suggestion it would be appreciated as i don't code in php.

Xcode breakpoint shell command argument length

Trying to pass a large string to a shell script using a breakpoint in Xcode
let value = Array(repeating: "a", count: 1500).joined()
let string = "{\"key\": \"\(value)\"}"
Unfortunately, the string is being truncated. Is this limitation documented and can it be overcome?
It's been nearly a year since you asked this, and I'm not sure if it will solve your question, but I've recently had a similar problem so thought I'd share my solution.
I had two issues:
LLDB was truncating any arguments to my shell script (and string variables printed in the console using po foo) to 1023 characters. I believe this is the issue to which your question relates.
Xcode was incorrectly confusing a comma , in my string as a separator for multiple arguments (e.g. passing foo, bar, and baz as arguments to the script wouldn't work correctly if any of the variables contained a , as Xcode would try to create another argument).
So, firstly, the LLDB issue...
It seems that by default LLDB has a limit on the character length that it will print to the console (or pass to a shell script via a breakpoint argument) of around 1023 characters. You can easily change this to something larger by setting another breakpoint before the breakpoint that uses your variable and running (lldb) set set target.max-string-summary-length 10000 in the console. This can be a bit annoying so I created a ~/.lldbinit file and placed set set target.max-string-summary-length 10000 in there instead so I don't have to keep setting it in the console.
Secondly, the comma issue...
Inside the Edit breakpoint... menu that you provided a screenshot of above there is the option to not only provide a path to a script but to also provide arguments. I can see from your question that you provided the argument #string#. For my script, I was passing multiple arguments, which Xcode allows you to do using a comma separated list, e.g. #foo#, #bar#, #baz#. Each of these arguments was a string.
I noticed that sometimes one or more of these strings would truncate if they contained a comma: ,.
So the string:
{ "num_friends" : "7" }
would be passed to my script as expected. But the string:
{ "num_friends" : "7", "num_deleted_friends" : "1" }
would truncate and would be passed to my script as two separate arguments. It seems that Xcode would split any string with a , even when entered using #string#.
I validated this in my script by simply using something like:
for var in "$#"
do
echo "$var"
echo "===="
done
Where $# expands to contain each argument. From this I could see that #string# was being correctly passed to my script but separated as multiple arguments wherever there was a ,. So if #string# contained a comma my script would print:
#"{ \"num_friends\" : \"7\"
====
\"num_deleted_friends\" : \"1\" }"
instead of what I expected which was:
#"{ \"num_friends\" : \"7\", \"num_deleted_friends\" : \"1\" }"
So it seems like it might be a bug in how Xcode passes strings inside # expressions in the breakpoint editor window.
My crude solution has been to just replace any commas with another character and then replace them back again inside my script. There's probably a better way to do this but I don't require it for my needs.

What is the meaning of ${} in powershell?

I have a script where function parameters are expressed like this:
param(
${param1},
${param2},
${param3}
)
What does it mean? I have been unable to find documentation on this.
What's the point of writing parameters that way instead of the more usual
param(
$param1,
$param2,
$param3
)
?
#MikeZ's answer is quite correct in explaining the example in the question, but as far as addressing the question title, there is actually more to say! The ${} notation actually has two uses; the second one is a hidden gem of PowerShell:
That is, you can use this bracket notation to do file I/O operations if you provide a drive-qualified path, as defined in the MSDN page Provider Paths.
(The above image comes from the Complete Guide to PowerShell Punctuation, a one-page wallchart freely available for download, attached to my recent article at Simple-Talk.com.)
They are both just parameter declarations. The two snippets are equivalent. Either syntax can be used here, however the braced form allows characters that would not otherwise be legal in variable names. From the PowerShell 3.0 language specification:
There are two ways of writing a variable name: A braced variable name, which begins with $, followed by a curly bracket-delimited set of one or more almost-arbitrary characters; and an ordinary variable name, which also begins with $, followed by a set of one or more characters from a more restrictive set than a braced variable name allows. Every ordinary variable name can be expressed using a corresponding braced variable name.
From about_Variables
To create or display a variable name that includes spaces or special characters, enclose the variable name in braces. This directs Windows PowerShell to interpret the characters in the variable name literally.
For example, the following command creates and then displays a variable named "save-items".
C:\PS> ${save-items} = "a", "b", "c"
C:\PS> ${save-items}
a
b
c
They are equivalent. It's just an alternative way of declaring a variable.
If you have characters that are illegal in a normal variable, you'd use the braces (think of it as "escaping" the variablename).
There is one additional usage.
One may have variable names like var1, var2, var11, var12, var101, etc.
Regardless if this is desirable variable naming, it just may be.
Using brackets one can precisely determine what is to be used:
assignment of $var11 may be ambiguous, using ${var1}1 or ${var11} leaves no room for mistakes.