WPF string escaping - Exception is thrown while creating control template - wpf

I am trying to construct a Control template from code behind. Things were working fine till recently I found that the code was throwing an exception because of escape characters in string. The error message is dynamically constructed by retrieving from resource file.
The exception is
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
Additional information: Name cannot begin with the '#' character, hexadecimal value 0x40. Line 1, position 537.
//In this case when exception is thrown,
//string errorMessage = "Name cannot contain any of the following characters $ \" # ; ^ | "
public static ControlTemplate GetErrorTemplate(string errorMessage)
{
string xamlString = "<ControlTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" " +
"xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" " +
"xmlns:nicefx=\"clr-namespace:NiceFx.Interop.UIComponents;assembly=NiceFx\" " +
"xmlns:wpfkit=\"http://schemas.microsoft.com/wpf/2008/toolkit\" >" +
" <DockPanel LastChildFill=\"True\">" +
"<TextBlock Foreground=\"White\" Background=\"Red\" FontSize=\"12\" Padding=\"2\" FontFamily=\"Trebuchet MS\" Margin=\"5,5,0,0\" TextWrapping=\"Wrap\" DockPanel.Dock=\"Bottom\" Text=\"" + errorMessage + "\"></TextBlock>" +
"<AdornedElementPlaceholder />" +
" </DockPanel>" +
" </ControlTemplate>";
//EXCEPTION OCCURS IN THIS LINE
ControlTemplate ct = (ControlTemplate)XamlReader.Load(XmlReader.Create(
new StringReader(xamlString)));
return ct;
}
How do I escape this string? I tried all possible ways but I am unable to do so.

According to the comment in your code, errorMessage contains a ", which will be inserted (without escaping it) into the XAML you are constructing. This " will then act as the closing quote of the Text attribute. At this point, the next non-whitespace character the parser encounters will be #, which is not an allowed character for the name of a XAML attribute, so it stops and reports the error.
That covers the why. As for how to escape it, you can use the XML entity for double quote: " Note that you may need to apply this escaping to multiple characters in your parameter.

Related

Why does DOORS `isBaseline` seem to always return FALSE?

I created a new major baseline in a DOORS module and then ran a small DXL script which includes lines
Module mp = current
Baseline bp = getMostRecentBaseline(mp)
int majorVersion = major(bp)
int minorVersion = minor(bp)
print "major " majorVersion " minor " minorVersion "\n"
string suff = suffix(bp)
print "suffix " suff "\n"
bool bstat
bstat = isBaseline(mp)
print "bstat " bstat "\n"
ModuleVersion mv = moduleVersion(mp)
string basind = baselineIndex(mp)
print "baseline index " basind "\n"
bool otherbstat = baseline(mp)
print "otherstat " otherbstat "\n"
bool basv = isBaseline(mv)
print "version base " basv "\n"
All of these return FALSE, indicating the module is not currently baselined. I have not done any edits to any attributes since baselining. I have done things like creating new Views. If I run the IBM DXL macro to compare the latest baseline against the "Current" version, it reports there are zero differences.
So my question is - what do the various isBaseline functions look at that is causing them to return FALSE? Or, am I going about this the wrong way - all I really need is a Q&D bit of DXL code to check that my module hasn't been edited for content since the last baseline was established.
The primary issue is that when your code gets a ModuleVersion (line 11), it uses a form of the function that gets the current version of the module. Line 14 should invoke isBaseline, not baseline, making the last two lines redundant.
See p310 of the current version (9.6.1) of the DXL Reference Manual for full details of the moduleVersion function.
The minimally modified version of your code that gets the result I think you were expecting, follows:
Module mp = current
Baseline bp = getMostRecentBaseline(mp)
int majorVersion = major(bp)
int minorVersion = minor(bp)
print "major " majorVersion " minor " minorVersion "\n"
string suff = suffix(bp)
print "suffix " suff "\n"
bool bstat
bstat = isBaseline(mp)
print "bstat " bstat "\n"
ModuleVersion mv = moduleVersion(uniqueID(mp), bp)
string basind = baselineIndex(mp)
print "baseline index " basind "\n"
bool otherbstat = isBaseline(mv)
print "otherstat " otherbstat "\n"
bool basv = isBaseline(mv)
print "version base " basv "\n"
In the version below, I've renamed variables, reordered some lines, and removed some content that wasn't required, for clarity:
Module modCurrent = current
Baseline blLatest = getMostRecentBaseline(modCurrent)
int iMajorVersion = major(blLatest)
int iMinorVersion = minor(blLatest)
string sBLSuffix = suffix(blLatest)
print "last baseline: major " iMajorVersion " minor " iMinorVersion " suffix " sBLSuffix "\n"
bool bIsBaseline = isBaseline(modCurrent)
print "bIsBaseline = " bIsBaseline "\n"
ModuleVersion mv = moduleVersion(uniqueID(modCurrent), blLatest)
Module modBaselined = load(mv, false)
string basind = baselineIndex(modBaselined)
print "baseline index = " basind "\n"
bIsBaseline = isBaseline(modBaselined)
print "bIsBaseline = " bIsBaseline "\n"
close(modBaselined)
Looks like isBaseline returns TRUE only if the current module View is set to display a selected baseline, as opposed to the "current" working view. `isBaseline and its brethren do not look at module contents, and thus won't see any potential differences between a baseline version and the current working view.
I'm aware of various DXL tools which perform a 'compare' on the contents, so that can be dealt with separately. As noted at this question, there are enhanced versions of the default "compare" script, such as one posted at this DOORS forum

Concatenate a character to a TextBox value

How to concatenate a character after the field value in a text box in Telerik Reporting?
I tried the below way. Its not working. Is there any way to achieve this task?
= {Fields.OlderThan} + " Days"
= {Fields.OlderThan} + Days
= {Fields.OlderThan} Days
textBox24.Value expression [= {Fields.OlderThan} "Days"] is not valid:
If Fields.OlderThan = 10
Result should be "10 Days"
You should get rid of those {}. It should work just fine without them: = Fields.OlderThan + " Days".
I also like to handle the case where the field might be null, because if Fields.OlderThan is null nothing will get printed in your text box:
= IsNull(Fields.OlderThan,"") + " Days"

Custom matchers in rspec

I am writing my first custom matcher in rspec. I would like to provide a failure message with a break down on why the comparison has failed. Effectively I would like to output the differences between the expected and the actual object. I effectively just need to do this with 2 arrays on the object. I have done some research and am trying to use =~ as described here. It mentions it has an informative failure message but I am struggling to access the failure message. I would effectively just like to return the combined failure message for two separate arrays to give an informative reason for the matcher returning false.
My attempt is as follows
RSpec::Matchers.define :have_same_state_as_measure_table do |expected_measure_table , max_delta = 1e-06|
match do |actual_measure_table|
actual_measure_table.equivalence(expected_measure_table, max_delta)
end
description do
"checks if measure has same state as expected measure table within a given number of precision"
end
# Optional method description
description do
"checks if measure has same state as expected measure table, within a given level of precision"
end
# Optional failure messages
failure_message do |actual_measure_table|
mismatch_string = ""
mismatch_string += (actual_measure_table.columns =~ expected_measure_table.columns || "")
mismatch_string += (actual_measure_table.names =~ expected_measure_table.names || "")
"Measure tables missmatch as follows %s" % (mismatch_string.to_s)
end
failure_message_when_negated do |actual_measure_table|
"expected friend not to be in zipcode"
end
end
My final matcher was as follows :
class CompareMeasureTables
attr_reader :expected_measure_table, :max_delta, :actual_measure_table
def initialize(expected_measure_table, max_delta=1e-06)
#expected_measure_table = expected_measure_table
#max_delta = max_delta
end
def description
"Checks if measure has same state as expected measure table, within a given level of precision"
end
def matches?(actual_measure_table)
#actual_measure_table = actual_measure_table
actual_measure_table.equivalence(expected_measure_table, max_delta, false)
end
def failure_message
#mismatch_description = ""
if actual_measure_table.columns.sort != expected_measure_table.columns.sort
#mismatch_description += "\nColumns mismatch \nExpected =" + expected_measure_table.columns.inspect
#mismatch_description += "\nActual =" + actual_measure_table.columns.inspect
end
if (#mismatch_description == "")
#mismatch_description += "\nData mismatch \nExpected =" + (expected_measure_table.records - actual_measure_table.records).inspect
#mismatch_description += "\nActual =" + (actual_measure_table.records - expected_measure_table.records).inspect
#mismatch_description += "\nTolerance set at #{#max_delta}"
end
"Measure tables mismatch as follows %s" % (#mismatch_description)
end
end

Code giving me an ArgumentExeption?

This code is giving me an ArgumentExeption when the correct values are put in both ComboBoxes, executing the code. The code basically just deletes a file and replaces it with a modified version taken from another folder.
Here is the exact text of the error message:
An unhandled exception of type 'System.ArgumentException' occurred in Microsoft.VisualBasic.dll
Additional information: The given file path ends with a directory separator character.
Here's the code:
If ComboBox1.Text = "Nokia" And ComboBox2.Text = "HTC" And My.Computer.FileSystem.FileExists("C:\Users\" + user + "\Documents\Fiddler2\Scripts\CustomRules.js") Then
My.Computer.FileSystem.DeleteFile("C:\Users\" + user + "\Documents\Fiddler2\Scripts\CustomRules.js")
My.Computer.FileSystem.CopyFile("Config\OEM\NokiaHTC.js", destinationFileName:="C:\Users\" + user + "\Documents\Fiddler2\Scripts\")
Else
My.Computer.FileSystem.CopyFile("Config\OEM\NokiaHTC.js", destinationFileName:="C:\Users\" + user + "\Documents\Fiddler2\Scripts\")
End If
The problem is that the destination file path ends with a "\" value. This isn't legal for the CopyFile API. Switch it to include the file name and this should fix the problem
My.Computer.FileSystem.CopyFile( _
"Config\OEM\NokiaHTC.js", _
destinationFileName:="C:\Users\" + user + "\Documents\Fiddler2\Scripts\NokiaHTC.js")

How to receive variables in a post in google app engine that contains string with chars like: õ á?

email = self.request.get('email')
name = self.request.get('name')
mail.send_mail(sender="myemail", email=email, body=name, subject="sss " + name + "sdafsaã")
// added ã: the problem was that "sdafsaã" should be u"sdafsaã". with a "u" before the string. and now it works
then i get this
main.py", line 85, in post
subject="sss " + name + "sdafsa",
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 36: ordinal not in range(128)
the might have chars like õ ó and something like that.
for more details:
the code to run the worker(the code before)
the name is the one that is received from the datastore and contains chars like õ and ó...
taskqueue.add(url='/emailworker', params={'email': e.email, 'name': e.name})
thanks
Try reading a little about how unicode works in Python:
Dive Into Python - Unicode
Unicode In Python, Completely Demystified
Also, make sure you're running Python 2.5 if you are seeing this error on the development server.
You should use:
email = self.request.get('email')
name = self.request.get('name')
mail.send_mail(sender="myemail",
email=email,
body=name,
subject="hello " + name.encode('utf-8') + " user!")
The variable name is a unicode string and should encoded in utf-8 or in the kind of encode you are using in you web application before concatenating to other byte strings.
Without name.encode(), Python uses the default 7 bits ascii codec that can't encode that specific character.
the problem is joining 2 strings: ||| body = name + "ã" => error ||| body = name + u"ã" => works!!! |||
Try with encode
t ='việt ứng '
m = MyModel()
m.data = t.encode('utf-8')
m.put() #success!

Resources