I am simply using a cftry/cfcatch block for handling any exception. Take this simple exception:
<cftry>
<cfset abc = 1/0>
<cfcatch>
<cfdump var="#cfcatch.getClass().getName()#">
<cfdump var="#isStruct(cfcatch)#">
<cfdump var="#isObject(cfcatch)#">
<cfdump var="#structKeyExists(cfcatch, 'type')#">
</cfcatch>
</cftry>
And the above code's output is like this:
coldfusion.runtime.DivideByZeroException
NO
YES
YES
My question is:
Why structKeyExists is not throwing an error as cfcatch is not of type struct?
And on dumping cfcatch it seems like it is a struct.
Any suggestions.
I think what is confusing you is that you need to remember that ColdFusion is a typeless language.
ColdFusion documentation on data types
Data types
ColdFusion is often referred to as typeless because you do not assign types to variables and ColdFusion does not associate a type with the variable name. However, the data that a variable represents does have a type, and the data type affects how ColdFusion evaluates an expression or function argument. ColdFusion can automatically convert many data types into others when it evaluates expressions. For simple data, such as numbers and strings, the data type is unimportant until the variable is used in an expression or as a function argument.
ColdFusion variable data belongs to one of the following type categories:
Simple One value. Can use directly in ColdFusion expressions. Include numbers, strings, Boolean values, and date-time values.
Binary Raw data, such as the contents of a GIF file or an executable program file.
Complex ** A container for data. Generally represent more than one value. ColdFusion built-in complex data types include arrays, structures, queries, and XML document objects. You cannot use a complex variable, such as an array, directly in a ColdFusion expression, but you can use simple data type elements of a complex variable in an expression. For example, with a one-dimensional array of numbers called myArray, you cannot use the expression myArray * 5. However, you could use an expression myArray3 * 5 to multiply the third element in the array by five.
Objects Complex constructs. Often encapsulate both data and functional operations. The following table lists the types of objects that ColdFusion can use, and identifies the chapters that describe how to use them:
So the code within the <cfcatch> block contains an object that can be referred to as a "structure". By default the name of that structure is cfcatch. You can override that name by specifying the name attribute within the <cfcatch> tag.
The easiest way to see everything that is available to you is to <cfdump> the entire structure within the <cfcatch> block.
<cfcatch>
<cfdump var="#cfcatch#">
</cfcatch>
CFCatch documentation on cfcatch
The cfcatch variables provide the following exception information:
cfcatch variable Content
cfcatch.type Type: Exception type, as specified in cfcatch.
cfcatch.message Message: Exceptions diagnostic message, if provided; otherwise, an empty string; in the cfcatch.message variable.
cfcatch.detail Detailed message from the CFML interpreter or specified in a cfthrow tag. When the exception is generated by ColdFusion (and not cfthrow), the message can contain HTML formatting and can help determine which tag threw the exception.
cfcatch.tagcontext An array of tag context structures, each representing one level of the active tag context at the time of the exception.
cfcatch.NativeErrorCode Applies to type = "database". Native error code associated with exception. Database drivers typically provide error codes to diagnose failing database operations. Default value is -1.
cfcatch.SQLState Applies to type = "database". SQLState associated with exception. Database drivers typically provide error codes to help diagnose failing database operations. Default value is 1.
cfcatch.Sql Applies to type = "database". The SQL statement sent to the data source.
cfcatch.queryError Applies to type ="database". The error message as reported by the database driver.
cfcatch.where Applies to type= "database". If the query uses the cfqueryparam tag, query parameter name-value pairs.
cfcatch.ErrNumber Applies to type = "expression". Internal expression error > number.
cfcatch.MissingFileName Applies to type = "missingInclude". Name of file that could not be included.
cfcatch.LockName Applies to type = "lock". Name of affected lock (if the lock is unnamed, the value is "anonymous").
cfcatch.LockOperation Applies to type = "lock". Operation that failed (Timeout, Create Mutex, or Unknown).
cfcatch.ErrorCode Applies to type = "custom". String error code.
cfcatch.ExtendedInfo Applies to type = "application" and "custom". Custom error message; information that the default exception handler does not display.
(Too long for comments..)
Adding to Miguel-F's comments about CF's "typelessness"... according to the documentation, IsStruct uses the following rules (emphasis mine):
Returns True, if variable is a ColdFusion structure or is a Java
object that implements the java.lang.Map interface. The return value
is False if the object in variable is a user-defined function (UDF).
CFCatch does not meet that criteria. Hence why IsStruct returns false.
If you dump the cfcatch object, and examine the class hierarchy, you will see it is actually implemented as a subclass of java.lang.Exception:
coldfusion.runtime.DivideByZeroException
coldfusion.runtime.ExpressionException
coldfusion.runtime.NeoException
java.lang.RuntimeException
java.lang.Exception
java.lang.Throwable
java.lang.Object
... not coldfusion.runtime.struct ie CF structure:
coldfusion.runtime.Struct
coldfusion.util.FastHashtable
coldfusion.util.CaseInsensitiveMap
java.lang.Object
So as Miguel-F said, though it can be used like a structure (as can most complex object), technically it is not a CF structure, which explains why IsStruct returns false.
As an aside, the reason you can access its properties using dot notation, like with CF structures, is probably because the cfcatch class uses the JavaBean pattern:
ColdFusion can automatically invoke get_PropertyName_() and
set_PropertyName_(value) methods if a Java class conforms to the
JavaBeans pattern. As a result, you can set or get the property by
referencing it directly, without having to explicitly invoke a method.
So for example, you can access the "message" property of cfcatch using:
cfcatch.message
.. instead of invoking its "getter" method for that property:
cfcatch.getMessage()
cfcatch object acts like a struct, but it is not one. This is a special case.
What you can do is make a duplicate of cfcatch object and try isStruct method on it, it will return true.
for example-
<cftry>
<cfset abc = 1/0>
<cfcatch>
<cfset dup = duplicate(cfcatch)>
<cfdump var="#isStruct(dup)#">
<cfdump var="#isStruct(cfcatch)#">
<cfdump var="#isObject(cfcatch)#">
</cfcatch>
</cftry>
The output would be like
YES
NO
YES
Related
In my AutoMapper scenario, I have a string property on my source type but a Uri property on the destination. Occasionally, this conversion is expected to fail when the source data is bad:
UriFormatException: Invalid URI: The hostname could not be parsed.
at Uri.ctor(String uriString)
When this happens, I would like AutoMapper to set the problematic property to null on the destination & continue on with the process of mapping the other elements. Known solutions to this are:
Writing a custom converter (with try/catch) just for that element
Using BeforeMap() as described here
But I feel that if I have to take those extra steps, AutoMapper hasn't fulfilled its promise as a time-saving tool. Isn't there some global 'continue-on-error' flag that I can set? Note that I am less concerned about Uris in particular than I am about the lack of configurable error handling.
No special setup needed to repro this--just a vanilla CreateMap() call that registers two classes with differently typed properties.
I am creating an Alloy model of the iCalendar data format.
An iCalendar file contains properties. There are a lot of codependencies among the properties. I want to see if anything breaks when a property is removed (i.e., when the property is constrained to zero occurrences).
I want to write an assert and have the Alloy Analyzer search for counterexamples, but I am struggling with how to write the assert. I want the assert to say something like this:
If property X is removed (i.e., property X is constrained to zero
occurrences), there are no instances that are invalid as a result of
removing X.
In pseudocode, I want this:
assert NoProblemFilteringX {
(no prop: X | prop in iCalendar.properties) => all instances are still valid
}
Would you provide some guidance on formulating the desired assert, please?
Suggestion:
Write your codependency checks in a predicate taking as parameter a
set of properties. The predicate holds iff the codependencies are satisfied amongst those properties given in parameter.
Rewrite your fact ensuring those codependencies so as to call this predicate with the set of all iCalendar properties as parameters.
Call this predicate in the assert while this time giving iCalendar.properties - X as parameter
I am attempting to use the Roslyn SDK and StackExchange.Precompilation (thank you!) to implement aspect-oriented programming in C#6. My specific problem right now is, starting with an IdentifierNameSyntax instance, I want to find the "member type" (method, property, field, var, etc.) that the identifier refers to. (How) can this be done?
Background:
The first proof-of-concept I am working on is some good old design-by-contract. I have a NonNullAttribute which can be applied to parameters, properties, or method return values. Along with the attribute there is a class implementing the StackExchange.Precompilation.ICompileModule interface, which on compilation will insert null checks on the marked parameters or return values.
This is the same idea as PostSharp's NonNullAttribute, but the transformation is being done on one of Roslyn's syntax trees, not on an already compiled assembly. It is also similar to Code Contracts, but with a declarative attribute approach, and again operating on syntax trees not IL.
For example, this source code:
[return: NonNull]
public string Capitalize([NonNull] string text) {
return text.ToUpper();
}
will be transformed into this during precompilation:
[return: NonNull]
public string Capitalize([NonNull] string text) {
if (Object.Equals(text, null))
throw new ArgumentNullException(nameof(text));
var result = text.ToUpper();
if (Object.Equals(result, null))
throw new PostconditionFailedException("Result cannot be null.");
return result;
}
(PostconditionFailedException is a custom exception I made to compliment ArgumentException for return values. If there is already something like this in the framework please let me know.)
For properties with this attribute, there would be a similar transformation, but with preconditions and postconditions implemented separately in the set and get accessors, respectively.
The specific reason I need to find the "member type" of an identifier here is for an optimization on implementing postconditions. Note in the post-compilation sample above, the value that would have been returned is stored in a local variable, checked, and then the local is returned. This storage is necessary for transforming return statements that evaluate a method or complex expression, but if the returned expression is just a field or local variable reference, creating that temporary storage local is wasteful.
So, when the return statement is being scanned, I first check if the statement is of the form ReturnKeyword-IdentifierSyntaxToken-SemicolonToken. If so, I then need to check what that identifier refers to, so I avoid that local variable allocation if the referent is a field or var.
Update
For more context, check out the project this is in reference to on GitHub.
You'll need to use SemanticModel.GetSymbolInfo to determine the symbol an identifier binds to.
Use SemanticModel.GetTypeInfo.Type to obtain the TypeInfo and use it to explore the Type
I need to implement a domain specific language. I have a panel and some shapes on it.
'panel' name = ID '(' title = STRING',' bgcolor = Color',' width = INT',' height = INT ')''{'((rects += Rect)| (ellipse += Ellipse)|(arcs += Arc)|)*'}'
and each shape has a unique rule with some other features. for example:
RoundRect:
'roundrectangle' name = ID '{'
(fill ?= 'filled' (fillpattern?='fillpattern' fillpaint=Paint)?)?
(stroke?='stroke' str=Stroke)?
'paint' paint=Paint
'coordination' x=INT ',' y=INT
'dimention' height=INT ',' width=INT
'arc' archeight=INT ',' arcwidth=INT
'}'
as it obvious in this DSL, I used some references. But I don't know this rules is correct or I should use cross-reference in those?
This rule works fine and I receive the correct output that I expected. But I know when a feature is not of the basic type (string, integer, and so on), it is
actually a reference (an instance of EReference),this is a containment reference, although for non-containment references, the referenced object is stored somewhere else,
for example, in another object of the same resource or even in a different resource.
And point is that a cross-reference is implemented as a non-containment reference.
I need to know when I should use cross-reference and when use containment reference?
As far as I know the difference is as following:
A containment-reference is if you want to reference to the content of a rule so it's just lazy for redefining the rule's content everytime you use the containment-reference.
A cross-reference behaves a bit different: If you use a cross-reference the parser need the user having typed in content of the rule the cross-reference refers to beforeallowing him to refer to that already typed in content.
An example would be a real programming language: A Method call would be a cross-reference as the method of this name should already be declared somewhere in the code because otherwise it doesn't exist. In contrary the normal code would be implemented as a containment-reference as it can be used (for example) within a class, a field or a method and the code you are typing in just needs to fullfill the existance of a few keywords and structures but these are only defined in the parser itself and needn't be defined by the user himself before beeing able to use them.
I hope I have illustrated it well enough so you now know about the difference and the meaning of these reference types.
Greeting Krzmbrzl
Your grammar describes the AST of your language. Therefore, a meta model is derived from your grammar. To describe references between your AST elements you can use containmend references and cross references. A containment reference is used if you want to describe a parent-child relation where the child object is "created" / declared during the parent object is created. A cross reference is used if the parent object points to a child object which is created / declared in an other parent object. To "draw a picture": A containment reference is a top -> bottom reference and a cross reference is a left -> right reference.
For example assume you have a field (private int field = 42;) or method (public void foo() {...}) declaration of a Java class. This declaration is modeled with a containment reference, because a Java class contains field and method declarations. On the other you have a statement field++; within the method body of foo(). There you use the former declared field foo and it is modeled as a cross reference.
In general I would say: Any declaration is modeled as a containment reference and any usage of an already declared whatever is modeled as a cross reference.
I am working with the classes in the System.Windows.Documents namespace, trying to write some generic code that will conditionally set the value of certain dependency properties, depending on whether these properties exist on a given class.
For example, the following method assigns an arbitrary value to the Padding property of the passed FrameworkContentElement:
void SetElementPadding(FrameworkContentElement element)
{
element.SetValue(Block.PaddingProperty, new Thickness(155d));
}
However, not all concrete implementations of FrameworkContentElement have a Padding property (Paragraph does but Span does not) so I would expect the property assignment to succeed for types that implement this property and to be silently ignored for types that do not.
But it seems that the above property assignment succeeds for instances of all derivatives of FrameworkContentElement, regardless of whether they implement the Padding property. I make this assumption because I have always been able to read back the assigned value.
I assume there is some flaw in the way I am assigning property values. What should I do to ensure that a given dependency property assignment is ignored by classes that do not implement that property?
Many thanks for your advice.
Tim
All classes that derive from Block have the Padding property. You may use the following modification:
void SetElementPadding(FrameworkContentElement element)
{
var block = element as Block;
if (block == null) return;
block.Padding = new Thickness(155d);
}
Even without this modification everything would still work for you because all you want is for Padding to be ignored by classes that do not support it. This is exactly what would happen. The fact that you can read out the value of a Padding dependency property on an instance that does not support it is probably by design but you shouldn't care. Block and derivatives would honor the value and all others would ignore it.