Check like operator pattern whether if its valid - vb.net

I have a TextBox where the user can write "Like pattern" to see if a string is matching. However if the user doesn't close the "[" the like operator will throw an error, that the argument is invalid for "pattern".
So I wrote something like this:
Private Function ValidateLikeString() As Boolean
Try
Dim valid As Boolean = DummyText Like TextBoxPrefix.Text
Return True
Catch ex As Exception
Return False
End Try
End Function
The problem is the following: if DummyText is 123 and TextBoxPrefix.Text is [1, it will work just fine.
However if TextBoxPrefix.Text is 2[1, it won't throw the exception because the first character won't match so the like operator will return false sooner than the exception is thrown. Of course if the DummyText will be 232 the exception will throw.
What I want to achieve is check TextBoxPrefix.Text against all cases if it's valid for pattern. I haven't found another case where the pattern is invalid only if the [ isn't closed, but if there are other problematic strings I want a test on those too.

Related

Java Parser comment statement

I am trying to comment a particulate statement.
My first approach is to return a comment in case statement is an 'Expression Statement' and expression is a particular 'Method Call Expression'.
new ModifierVisitor<Object>() {
public Visitable visit(ExpressionStmt expStmt, Object arg) {
Expression exp = expStmt.getExpression();
if (exp.isMethodCallExpr()) {
// My other logic goes here
return new LineComment(expStmt.toString());
}
}
}
But it failed while dumping the unit back to string.
java.lang.ClassCastException: com.github.javaparser.ast.comments.LineComment cannot be cast to com.github.javaparser.ast.stmt.Statement
at com.github.javaparser.printer.DefaultPrettyPrinterVisitor.visit(DefaultPrettyPrinterVisitor.java:1329)
at com.github.javaparser.printer.DefaultPrettyPrinterVisitor.visit(DefaultPrettyPrinterVisitor.java:163)
at com.github.javaparser.ast.stmt.BlockStmt.accept(BlockStmt.java:76)
at com.github.javaparser.printer.DefaultPrettyPrinterVisitor.visit(DefaultPrettyPrinterVisitor.java:1220)
at com.github.javaparser.printer.DefaultPrettyPrinterVisitor.visit(DefaultPrettyPrinterVisitor.java:163)
at com.github.javaparser.ast.body.MethodDeclaration.accept(MethodDeclaration.java:104)
at com.github.javaparser.printer.DefaultPrettyPrinterVisitor.printMembers(DefaultPrettyPrinterVisitor.java:190)
at com.github.javaparser.printer.DefaultPrettyPrinterVisitor.visit(DefaultPrettyPrinterVisitor.java:419)
at com.github.javaparser.printer.DefaultPrettyPrinterVisitor.visit(DefaultPrettyPrinterVisitor.java:163)
at com.github.javaparser.ast.body.ClassOrInterfaceDeclaration.accept(ClassOrInterfaceDeclaration.java:98)
at com.github.javaparser.printer.DefaultPrettyPrinterVisitor.visit(DefaultPrettyPrinterVisitor.java:325)
at com.github.javaparser.printer.DefaultPrettyPrinterVisitor.visit(DefaultPrettyPrinterVisitor.java:163)
at com.github.javaparser.ast.CompilationUnit.accept(CompilationUnit.java:133)
at com.github.javaparser.printer.DefaultPrettyPrinter.print(DefaultPrettyPrinter.java:104)
at com.github.javaparser.ast.Node.toString(Node.java:320)
As it suggests that you can replace a 'Statement' with another statement so instead I tried another approach to replace the statement and with an 'Empty Statement'. It kind of worked for me but the output does not look good as it leaves extra ';' after the commented line.
At third I tried to go deeper and instead of replacing the statement I tried to replace the expression with an comment. That too failed as mentioned in SO - Javaparser comment expression.
Any idea how to fix this ?
I tried a workaround which does not feel like a good solution, but gives me the expected result for now:
BlockStmt blockStmt = (BlockStmt) expStmt.getParentNode().get();
blockStmt.getStatement(blockStmt.getStatements().indexOf(expStmt) + 1).setLineComment(expStmt.toString());
return null;

Applescript Get value of property by string name of property

In AppleScript. Let's say I have a record with a property called Title.
Let's say I set a variable to the text "Title"; can I use that variable to get the value of the property Title? Basically, is there any way to do something like this:
set result to property named "Title" of myRecord
Instead of:
set result to Title of myRecord
I found the answer. I also realize I didn't ask the correct question. The value I'm trying to obtain is from a property list item.
Here's what I learned, and how to accomplish this:
use framework "Foundation"
set _plist to ...
set _objcPlist to GetAppleScriptObjectAsObjcObject(_plist)
set _value to GetObjcPropertyValueByName("MyProperty", item 1 of _objcPlist)
on GetAppleScriptObjectAsObjcObject(asObject)
set a to current application
set cClass to class of asObject
if (cClass is record) then
return a's NSDictionary's dictionaryWithDictionary:asObject
else if (cClass is list) then
return a's NSArray's arrayWithArray:asObject
else
error "Unexpected Class Type"
end if
end GetAppleScriptObjectAsObjcObject
on GetObjcPropertyValueByName(propertyName, objcItem)
return (objcItem's valueForKey:propertyName) as text
end GetObjcPropertyValueByName
you may try the try ... on error approach:
set aRecord to {title:"hello world", author:"who's who"}
try
aRecord as Unicode text
on error error_message
set err to error_message
end try
err
-- "Can’t make {title:\"hello world\", author:\"who's who\"} into type Unicode text."
then parse err (it's text now). it depends on the complexity of aRecord, if it's a record of nested lists, or records; the parsing would be very complicated. have fun :)

CASE-WHEN within function POSTGRESQL

I have a function to insert some values into a table, but before inserting I want to check if e-mail address it's right. If not, break the function and returns an error. Case true, go on.
case when _email ~ '^[^#\s]+#[^#\s]+(\.[^#\s]+)+$' = true
then raise exception 'Incorrect email'
_email is the parameter of funcion.
But it's not working. Should I use "IF" or other conditional?
CASE works, but IF seems more appropriate.
You have some pointless noise in the expression and I think you got the logic backwards: 'Incorrect email' should be triggered if _email does not match the pattern:
IF _email ~ '^[^#\s]+#[^#\s]+(\.[^#\s]+)+$' -- drop the pointless "= true"
THEN -- do nothing - I inverted the logic
ELSE RAISE EXCEPTION 'Incorrect email';
END IF;
The new ASSERT (Postgres 9.5+) would also work, but that's really meant for debugging:
ASSERT _email ~ '^[^#\s]+#[^#\s]+(\.[^#\s]+)+$', 'Incorrect email';
You should be able to use the case inside plpgsql. Obviously what you are trying to do can be done through if statement as well...
case when _email ~ '^[^#\s]+#[^#\s]+(\.[^#\s]+)+$' = true then
raise exception 'Incorrect email';
else
--proceed with insert
end case;

Flag invalid attribute in ActiveRecord

I am trying to implement functionality wherein an attribute, once set, cannot be changed on an ActiveRecord model. To this end, I have written the following methods:
def address
self[:address]
end
def address=(val)
if new_record?
self[:address] = val
else
errors.add(:address, "Cannot change address, once it is set")
return false # tried return nil here first, did not work
end
end
Am I doing something wrong here? I want the object to be invalid once I try to change an address, but I do not get any errors when I do obj.valid?
EDIT: The value is not changed once it is set, but I would like to get invalid object when I do the validation via obj.valid?
When you do obj.valid?, it clears all of your errors, and then runs each of the validations in turn. To have this produce an error on validation, you'll have to move that logic into a validation block.
Here's an example of one way to do that with an instance variable:
def address=(val)
if new_record?
self[:address] = val
else
#addr_change = true
return false # tried return nil here first, did not work
end
end
validate do |user|
errors.add(:address, "Cannot change address, once it is set") if #addr_change
end

Powershell and SQL parameters. If empty string, pass DBNull

I got this parameter:
$objDbCmd.Parameters.Add("#telephone", [System.Data.SqlDbType]::VarChar, 18) | Out-Null;
$objDbCmd.Parameters["#telephone"].Value = $objUser.Telephone;
Where the string $objUser.Telephone can be empty. If it's empty, how can I convert it to [DBNull]::Value?
I tried:
if ([string]:IsNullOrEmpty($objUser.Telephone)) { $objUser.Telephone = [DBNull]::Value };
But that gives me the error:
Exception calling "ExecuteNonQuery" with "0" argument(s): "Failed to convert parameter value from a ResultPropertyValueCollection to a String."
And if I convert it to a string, it inserts an empty string "", and not DBNull.
How can this be accomplished?
Thanks.
In PowerShell, you can treat null/empty strings as a boolean.
$x = $null
if ($x) { 'this wont print' }
$x = ""
if ($x) { 'this wont print' }
$x = "blah"
if ($x) { 'this will' }
So.... having said that you can do:
$Parameter.Value = $(if ($x) { $x } else { [DBNull]::Value })
But I'd much rather wrap this up in a function like:
function CatchNull([String]$x) {
if ($x) { $x } else { [DBNull]::Value }
}
I don't know about powershell, but in C# I would do something like this:
if ([string]::IsNullOrEmpty($objUser.Telephone))
{
$objDbCmd.Parameters["#telephone"].Value = [DBNull]::Value;
}
else
{
$objDbCmd.Parameters["#telephone"].Value = $objUser.Telephone;
}
Always append +"" at the end of db values...
$command.Parameters["#EmployeeType"].Value= $ADResult.EmployeeType + ""
Many years later, let me clarify:
Josh's answer shows a helpful simplification for testing strings for emptiness (relying on PowerShell's implicit to-Boolean conversion[1]), but it is unrelated to Tommy's (the OP's) problem.
Instead, the error message
"Failed to convert parameter value from a ResultPropertyValueCollection to a String."
implies that it is the non-null case that caused the problem, because $objDbCmd.Parameters["#telephone"].Value expects either a string value or [DBNull]::Value, whereas $objUser.Telephone is of type [ResultPropertyValueCollection], i.e. a collection of values.
Thus, in the non-null case, a string value must be assigned, which must be derived from the collection; one option is to take the first collection element's value, another would be to join all values with a separator to form a single string, using, e.g., [string]::Join(';', $objUser.Telephone) or, if joining the elements with spaces is acceptable (not a good idea with multiple phone numbers), simply with "$($objUser.Telephone)".[2]
Detecting an empty collection via [string]:IsNullOrEmpty() actually worked, despite the type mismatch, due to how PowerShell implicitly stringifies collections when passing a value to a [string] typed method parameter.[2]
Similarly, using implicit to-Boolean conversion works as expected with collections too: an empty collection evaluates to $false, a non-empty one to $true (as long as there are either at least two elements or the only element by itself would be considered $true[1])
Therefore, one solution is to use the first telephone number entry:
$objDbCmd.Parameters["#telephone"].Value = if ($objUser.Telephone) {
$objUser.Telephone[0].ToString() # use first entry
} else {
[DBNull]::Value
}
Note: If $objUser.Telephone[0] directly returns a [string], you can omit the .ToString() call.
In PowerShell v7+ you can alternatively shorten the statement via a ternary conditional:
$objDbCmd.Parameters["#telephone"].Value =
$objUser.Telephone ? $objUser.Telephone[0].ToString() : [DBNull]::Value
[1] For a comprehensive summary of PowerShell's automatic to-Boolean conversions, see the bottom section of this answer.
[2] When implicitly converting a collection to a string, PowerShell joins the stringified elements of a collection with a single space as the separator by default; you can override the separator with the automatic $OFS variable, but that is rarely done in practice; e.g., array 'foo', 'bar' is converted to 'foo bar'; note that this conversion does not apply when you call the collection's .ToString() method explicitly, but it does apply inside expandable (interpolating) strings, e.g., "$array".