I use Java library. In exception class there is "localizedMessage" field and "description" field. I don't know why, but "description" (which is java String) is recognized as String! by Kotlin, and when "description" is null, condition description == null returns false.
Example of code:
mvpView?.showToast(it.description?:it.localizedMessage)
or without Elvis:
if (it.description.isNullOrBlank()) {
mvpView?.showToast(it.localizedMessage)
} else {
mvpView?.showToast(it.description)
}
it always tries to show "description", but "evaluate expression" in debug mode returns true on description == null (as expected).
Kotlin version is 1.1.1
The reason was in getter, it returned another string instead of description if description is null.
public String getDescription() {
if (description != null) {
return description;
}
if (UNKNOWN_ERROR.equals(getCode())) {
return String.format("Received error with code %s", getCode());
}
return "Failed with unknown error";
}
Related
I'm using EPPlus as a calculations server. Here is my code:
using (var xlp = new ExcelPackage(stream))
{
OfficeOpenXml.ExcelWorksheet Sheet = xlp.Workbook.Worksheets["sheet1"];
//Some code for feeding user data to excel sheet
//...
//We first invoke calculate method to let contraints of data validation get updated.
xlp.Workbook.Calculate();
var v = Sheet.DataValidations["A1"];
if (v != null)
{
switch (v.ValidationType.Type)
{
case OfficeOpenXml.DataValidation.eDataValidationType.DateTime:
OfficeOpenXml.DataValidation.ExcelDataValidationDateTime V1 = (OfficeOpenXml.DataValidation.ExcelDataValidationDateTime)v;
try
{
//this line doesn't do any thing
V1.Validate();
}
catch
{
}
break;
case ...
}
}
}
I had read somewhere that Validate() method throws exception for invalid data. It doesn't.
My question: How to use the Validate() method?
That would depend on what the content of the cell and the settings of the validator's Operator:
http://epplus.codeplex.com/SourceControl/latest#EPPlus/DataValidation/ExcelDataValidationOperator.cs
/// <summary>
/// Operator for comparison between Formula and Formula2 in a validation.
/// </summary>
public enum ExcelDataValidationOperator
{
any,
equal,
notEqual,
lessThan,
lessThanOrEqual,
greaterThan,
greaterThanOrEqual,
between,
notBetween
}
The ExcelDataValidationDateTime (eventually) derives from ExcelDataValidationWithFormula<IExcelDataValidationFormulaDateTime> which contains the implemenation of Validate():
http://epplus.codeplex.com/SourceControl/latest#EPPlus/DataValidation/ExcelDataValidationWithFormula.cs
public override void Validate()
{
base.Validate();
if (Operator == ExcelDataValidationOperator.between || Operator == ExcelDataValidationOperator.notBetween)
{
if (string.IsNullOrEmpty(Formula2Internal))
{
throw new InvalidOperationException("Validation of " + Address.Address + " failed: Formula2 must be set if operator is 'between' or 'notBetween'");
}
}
}
So it will throw an exception (invalidate) when the validation operation is either ExcelDataValidationOperator.between or ExcelDataValidationOperator.notBetween and Forumla2 is not set (not to be confused with the primary Formula). In other words, it considers the validator invalid when you are using an operation which requires TWO values/formulas to compare but only one is set.
I validate the input using ModelState.IsValid:
[HttpGet]
[Route("subjects")]
[ValidateAttribute]
public IHttpActionResult GetSubjects(bool? isActive = null)
{
//get subjects
}
If I pass in the uri ~/subjects/?isActive=abcdef, I get the error message:
The value 'abcdef' is not valid for Nullable`1.
If the input parameter is not nullable
public IHttpActionResult GetSubjects(bool isActive){
//get subjects
}
I get the error message:
The value 'abcdef' is not valid for Boolean.
I want to override the message if nullable type so I can maintain the message ("The value 'abcdef' is not valid for Boolean."). How can I do this since in the ModelState error I don't get the data type. I am implementing the validation as a custom ActionFilterAttribute (ValidationAttribute).
You can change callback that formats type conversion error messages. For example, let's define it right into Global.asax.cs:
public class WebApiApplication : HttpApplication
{
protected void Application_Start()
{
ModelBinderConfig.TypeConversionErrorMessageProvider = this.NullableAwareTypeConversionErrorMessageProvider;
// rest of your initialization code
}
private string NullableAwareTypeConversionErrorMessageProvider(HttpActionContext actionContext, ModelMetadata modelMetadata, object incomingValue)
{
var target = modelMetadata.PropertyName;
if (target == null)
{
var type = Nullable.GetUnderlyingType(modelMetadata.ModelType) ?? modelMetadata.ModelType;
target = type.Name;
}
return string.Format("The value '{0}' is not valid for {1}", incomingValue, target);
}
}
For not nullable types Nullable.GetUnderlyingType will return null, in this case we will use original type.
Unfortunately you cannot access default string resources and if you need to localize error message you must do it on your own.
Another way is to implement your own IModelBinder, but this is not a good idea for your particular problem.
Lorond's answer highlights how flexible asp.net web api is in terms of letting a programmer customize many parts of the API. When I looked at this question, my thought process was to handle it in an action filter rather than overriding something in the configuration.
public class ValidateTypeAttribute : ActionFilterAttribute
{
public ValidateTypeAttribute() { }
public override void OnActionExecuting(HttpActionContext actionContext)
{
string somebool = actionContext.Request.GetQueryNameValuePairs().Where(x => x.Key.ToString() == "somebool").Select(x => x.Value).FirstOrDefault();
bool outBool;
//do something if somebool is empty string
if (!bool.TryParse(somebool, out outBool))
{
HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
response.ReasonPhrase = "The value " + somebool + " is not valid for Boolean.";
actionContext.Response = response;
}
else
{
base.OnActionExecuting(actionContext);
}
}
Then decorate the action method in the controller with the action filter attribute
Dart specification states:
Reified type information reflects the types of objects at runtime and may always be queried by dynamic typechecking constructs (the
analogs of instanceOf, casts, typecase etc. in other languages).
Sounds great, but there is no instanceof-like operator. So how do we perform runtime type-checking in Dart? Is it possible at all?
The instanceof-operator is called is in Dart. The spec isn't exactly friendly to a casual reader, so the best description right now seems to be http://www.dartlang.org/articles/optional-types/.
Here's an example:
class Foo { }
main() {
var foo = new Foo();
if (foo is Foo) {
print("it's a foo!");
}
}
Dart Object type has a runtimeType instance member (source is from dart-sdk v1.14, don't know if it was available earlier)
class Object {
//...
external Type get runtimeType;
}
Usage:
Object o = 'foo';
assert(o.runtimeType == String);
As others have mentioned, Dart's is operator is the equivalent of Javascript's instanceof operator. However, I haven't found a direct analogue of the typeof operator in Dart.
Thankfully the dart:mirrors reflection API has recently been added to the SDK, and is now available for download in the latest Editor+SDK package. Here's a short demo:
import 'dart:mirrors';
getTypeName(dynamic obj) {
return reflect(obj).type.reflectedType.toString();
}
void main() {
var val = "\"Dart is dynamically typed (with optional type annotations.)\"";
if (val is String) {
print("The value is a String, but I needed "
"to check with an explicit condition.");
}
var typeName = getTypeName(val);
print("\nThe mirrored type of the value is $typeName.");
}
There are two operators for type testing: E is T tests for E an instance of type T while E is! T tests for E not an instance of type T.
Note that E is Object is always true, and null is T is always false unless T===Object.
Exact type matching is done via runtimeType property. Checking if an instance or any of its parent types (in the inheritance chain) is of the given type is done via is operator:
class xxx {}
class yyy extends xxx {}
void main() {
var y = yyy();
print(y is xxx);
print(y.runtimeType == xxx);
}
Returns:
true
false
Simply use .runtimeType on the property like below,
print(unknownDataTypeProperty.runtimeType)
Just to clarify a bit the difference between is and runtimeType. As someone said already (and this was tested with Dart V2+) the following code:
class Foo {
#override
Type get runtimeType => String;
}
main() {
var foo = Foo();
if (foo is Foo) {
print("it's a foo!");
}
print("type is ${foo.runtimeType}");
}
will output:
it's a foo!
type is String
Which is wrong.
Now, I can't see the reason why one should do such a thing...
T is The type
print( T.runtimeType)
if(value is int ) Returns true if the type of the value is int,
else if(value is! int )
To check the type of a variable use runtimeType
void main() {
int a = 10;
print(a.runtimeType);
}
to check whether the type of a variable is the same as your expected use is or runtimeType
void main() {
int a = 10;
print(a.runtimeType == int); // true
//or
print(a is int); // true
}
print("enter your phone number:\n");
var phone number = stdin.readLineSync();
if(phone number.runtimeType is int == true) // checks if the values input are integers
{
print('you have successfully input your phone number!');
}
else{
print('only numbers are allowed');
}
I have a table with the following:
CREATE TABLE [Location]([ADDRESS1] [nvarchar](50) NOT NULL DEFAULT (' '));
I import it into Entity Framework 4.1.
Entity Framework’s designer shows this:
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String ADDRESS1
{
get
{
return _ADDRESS1;
}
set
{
OnADDRESS1Changing(value);
ReportPropertyChanging("ADDRESS1");
_ADDRESS1 = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("ADDRESS1");
OnADDRESS1Changed();
}
}
private global::System.String _ADDRESS1 = " ";
partial void OnADDRESS1Changing(global::System.String value);
partial void OnADDRESS1Changed();
When I build it, I get a *.web.g.cs file in my Silverlight application and the field looks like this:
[DataMember()]
[Required()]
[StringLength(50)]
public string ADDRESS1
{
get
{
return this._address1;
}
set
{
if ((this._address1 != value))
{
this.OnADDRESS1Changing(value);
this.RaiseDataMemberChanging("ADDRESS1");
this.ValidateProperty("ADDRESS1", value);
this._address1 = value;
this.RaiseDataMemberChanged("ADDRESS1");
this.OnADDRESS1Changed();
}
}
}
Am I missing a setting in Entity Framework? It appears to me that if the field is NOT NULL code generation is flagging the field as required, even though I am telling it the default is string.empty (or blank).
NOT NULL means required. That's the only thing that controls where a value must be supplied.
An empty string for new records does not mean you can't explicitly insert a NULL value, but NOT NULL will stop you doing that.
How to get the properties of an interface within the type library the interface is defined, Keeps returning HRESULT but would like it to return the actual value of the property.
EDIT:
IDL:
interface IMyClassInterface : IDispatch
{
[propget, id(1), helpstring("Gets user Type")] HRESULT getUserDefineTypeVal([out,retval] UserDefineEnum *ptrVal);
[propput, id(1), helpstring("Sets user Type ")]HRESULT setUserDefineTypeVal([in] UserDefineEnum newVal);
}
Property in Header File:
STDMETHOD(getUserDefineTypeVal)(UserDefineEnum *ptrVal);
STDMETHOD(setUserDefineTypeVal)(UserDefineEnum newVal);
Property in MYClass.cpp:
STDMETHODIMP CMYClass::getUserDefineTypeVal(UserDefineEnum *ptrVal) {
*ptrVal = UserDefineEnum(private_var_UserDefineTypeVal);
return S_OK;
}
AnotherClass within the Type Library:
IMyClassInterface* private_var_MyClass
STDMETHODIMP CAnotherClass::someMethod(){
UserDefineEnum* p;
if(private_var_MyClass->getUserDefineTypeVal(p)){
//do somestuff
}
}
The problem is the if condition doesn’t return true. However the below partially works.
HRESULT hr = private_var_MyClass->getUserDefineTypeVal(p);
if(hr == S_OK){ do somestuff }
The problem with this is if I attempt a case statement the only value in hr is 0. I need to check the value being set on the clientside.
The value of S_OK is 0, that's why your if() statement doesn't execute. You should use the SUCCEEDED macro:
UserDefinedEnum value;
HRESULT hr = private_var_MyClass->getUserDefineTypeVal(&value);
if (SUCCEEDED(hr)) {
switch (value) {
// etc...
}
}
else {
// do something with the error...
}
COM usually uses out parameters to return values. In C/C++ you have to pass a pointer to a variable which will contain the result upon return.
The HRESULT return parameter is only used to report the success (or failure) of the method call.
EDIT For your code, you need to reserve the memory for the result by the caller:
UserDefineEnum p; // No * here ...
if (private_var_MyClass->getUserDefineTypeValue(&p) == S_OK) { // note '&' operator!
switch (p) {
case ENUM_1: // ...
case ENUM_2:
// ...
}
}