What causes "Variable does not exist in current context" message - c#-4.0

I'm trying to write a very simple C# program in VS2015. I keep getting a message "The name (variable) does not exist in the current context." This is true for both my bool variable and string variable.
namespace PTouch
{
public class PTouch
{
bool lb_rc;
string strLabel;
lb_rc = false;
strLabel = "C:\BenchTop10\Standard 1in.lbx";
bpac.Document doc = new Document();
lb_rc = doc.Open("C:\BenchTop10\Standard 1in.lbx");
if lb_rc != false
{
doc.StartPrint("", 0);
doc.PrintOut(1, 0);
doc.EndPrint();
doc.Close();
}
else
{
MessageBox.Show("Open Error: " + doc.ErrorCode);
}
}
}
There are probably several problems with this code, but the first one is error about the variables not existing in the current context.
Any assistance is greatly appreciated.

I just discovered the problem... All the code has to be inside of a method, not just the class. I added a method to the class,
public void PrintLabel()
{ bool lb_rc; ... }
All errors cleared up, except MessageBox...
Thank you,
Tracy

Related

How I can resolve this error in Katalon Groovy:unexpected token: do // Groovy:unexpected token: if // Groovy:expecting EOF, found 'if'

// Read data from XML file
public static String getElementTextByTagName(String tagName) {
try {
String dirPath = System.getProperty('user.dir') + "\\DataFiles\\TestData.xml"
List<File> xmlFiles = getXMLFilesByDirectory(dirPath);
Iterator var3 = xmlFiles.iterator();
XMLSearchResult searchResult;
do {
if (!var3.hasNext()) {
throw new ElementNotFoundInXMLException("Element Not Found");
}
File xmlFile = (File)var3.next();
searchResult = searchForElementInsideFile(xmlFile, tagName);
} while(!searchResult.isFound());
return searchResult.getElementText();
} catch (ElementNotFoundInXMLException var6) {
var6.printStackTrace();
return null;
}
}
enter image description here
The error is appearing on the do statement line and below the same for if statement
Katalon Studio uses a version of Groovy, at the time of this answer, that does not support do-while loops.
For that effect, you'll have to do something like what's outlined in this question.
Consider it a professional courtesy that I take the time to link the answer here, instead of voting to close the question because it's already answered by that other question.
Welcome to StackOverflow.

Passing a std::unique_ptr as a void* parameter to a function (CPtrArray::Add)

My code:
void CAssignSelectedColumnDlg::AddColumnData(CString strHeading, CStringArray* pAryStrNames, int iColumnIndex, int iCustomIndex /*-1*/, BOOL bFixedCustomType /*FALSE*/)
{
//COLUMN_DATA_S *psData = nullptr;
//psData = new COLUMN_DATA_S;
auto psData = std::make_unique<COLUMN_DATA_S>();
if (psData != nullptr)
{
// Note: we don't "own" pAryStrNames
psData->strHeading = strHeading;
psData->pAryStrNames = pAryStrNames;
psData->sActionListInfo.byColumnIndex = iColumnIndex;
psData->sActionListInfo.byCustomIndex = iCustomIndex;
psData->sActionListInfo.bFixedCustomType = bFixedCustomType ? true : false;
m_aryPtrColumnData.Add(psData);
}
}
Code analysis was suggesting I use std::make_unique instead of new. So I adjusted teh code but now get a compile error. I tried to find a suitable approach:
No suitable conversion function from std::unique_ptr<COLUMN_DATA_S>, std::default_delete<COLUMN_DATA_S>> to void * exists.
The function in question is CPtrArray::Add. I am still trying to gras the smart pointers and their usage in a context like this.
Note that we should not be deleting the pointer when the function ends. The deletion of the collection is done in a dialog event handler.

Eclipse JDT resolve unknown kind from annotation IMemberValuePair

I need to retrieve the value from an annotation such as this one that uses a string constant:
#Component(property = Constants.SERVICE_RANKING + ":Integer=10")
public class NyServiceImpl implements MyService {
But I am getting a kind of K_UNKNOWN and the doc says "the value is an expression that would need to be further analyzed to determine its kind". My question then is how do I perform this analysis? I could even manage to accept getting the plain source text value in this case.
The other answer looks basically OK, but let me suggest a way to avoid using the internal class org.eclipse.jdt.internal.core.Annotation and its method findNode():
ISourceRange range = annotation.getSourceRange();
ASTNode annNode = org.eclipse.jdt.core.dom.NodeFinder.perform(cu, range);
From here on you should be safe, using DOM API throughout.
Googling differently I found a way to resolve the expression. Still open to other suggestions if any. For those who might be interested, here is a snippet of code:
if (valueKind == IMemberValuePair.K_UNKNOWN) {
Annotation ann = (Annotation)annotation;
CompilationUnit cu = getAST(ann.getCompilationUnit());
ASTNode annNode = ann.findNode(cu);
NormalAnnotation na = (NormalAnnotation)annNode;
List<?> naValues = na.values();
Optional<?> optMvp = naValues.stream()
.filter(val-> ((MemberValuePair)val).getName().getIdentifier().equals(PROPERTY))
.findAny();
if (optMvp.isPresent()) {
MemberValuePair pair = (MemberValuePair)optMvp.get();
if (pair.getValue() instanceof ArrayInitializer) {
ArrayInitializer ai = (ArrayInitializer)pair.getValue();
for (Object exprObj : ai.expressions()) {
Expression expr = (Expression)exprObj;
String propValue = (String)expr.resolveConstantExpressionValue();
if (propValue.startsWith(Constants.SERVICE_RANKING)) {
return true;
}
}
}
else {
Expression expr = pair.getValue();
String propValue = (String)expr.resolveConstantExpressionValue();
if (propValue.startsWith(Constants.SERVICE_RANKING)) {
return true;
}
}
}
//report error
}
private CompilationUnit getAST(ICompilationUnit compUnit) {
final ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(compUnit);
parser.setResolveBindings(true); // we need bindings later on
CompilationUnit unit = (CompilationUnit)parser.createAST(null);
return unit;
}

FormBuilder Code execution suddenly jumps to FormCompletion delegate

I have below code in Bot framework app.
You can see in below code I have commented ValidateStartDate delegate, the reason behind it is that if I include delegate in formflow then after the delegate execution code jumps directly to BookingComplete delegate of "context.Call(Booking, BookingComplete);" i.e end of conversation.But ideally, it should execute rest of the fields from form builder.
Note that here StartDate is of type String, and I am manually validating date part.Also, no visible exception occurs during code execution
public static IForm<ConferenceBooking> BuildForm()
{
return new FormBuilder<ConferenceBooking>().Message("Tell me meeting details!")
.Field(nameof(title))
.Field(nameof(StartDate))//, validate: ValidateStartDate
.Field(nameof(EntryTime), validate:ValidateCallTime)
.Build();
}
Below is delegate part for StartDate
private static Task<ValidateResult> ValidateStartDate(ConferenceBooking state, object response)
{
var result = new ValidateResult();
DateTime startDt = Convert.ToDateTime(GetDate(Convert.ToString(response)));
if (startDt == null || startDt == DateTime.MinValue)
{
result.IsValid = false;
result.Feedback = "I could not understand this format.";
}
else if (startDt.Date < DateTime.Now.Date)
{
result.IsValid = false;
result.Feedback = "Sorry, back dated bookings are not allowed";
}
else
{
result.IsValid = true;
result.Value = startDt;
}
return Task.FromResult(result);
}
I have also noticed this behavior before and this was always due to an exception. The FormBuilder appears to catch all exceptions and exits the form in the catch block. This is why you don't see any exceptions popping up. Try going over your code step by step or executing it from outside the form.

SynchronizationLockException when using Threading::Monitor on String

I think we are having an issue on using Monitor::TryEnter and Monitor::Exit on a String (I suppose this is the issue, but I'm looking for some extra information).
if (Monitor::TryEnter(m_sLogFile, 200)) {
try {
m_sLogFile = IO::Path::GetDirectoryName(Application::ExecutablePath) + "\\" + LOG_FILE_DEFAULT;
// SOME EXTRA CODE
}
finally {
Monitor::Exit(m_sLogFile);
}
}
[m_sLogFile is a String declared in my class]
The SynchronizationLockException is thrown on Monitor::Exit call, with this message:
Object synchronization method was called from an unsynchronized block
of code
I want to be sure that error is that we are locking the string and we are changing its content.
The problem is not that you are using a string for Monitor.Enter/Exit, the problem is that you are using one string for Enter and different one for Exit:
if (Monitor::TryEnter(m_sLogFile, 200)) {
try {
m_sLogFile = IO::Path::GetDirectoryName(Application::ExecutablePath) + "\\" + LOG_FILE_DEFAULT;
// SOME EXTRA CODE
}
finally {
Monitor::Exit(m_sLogFile);
}
}
See the m_sLogFile = .... inside?
You need to use a field which doesn't change (something like readonly object m_Lock; should be sufficient).

Resources