Invalid token 'while' in class, struct, or interface member declaratio - c#

I have the following code
class Card
{
string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
class Program
{
static void Main(string[] args)
{
int KaLP = 8000;
int YuLP = 8000;
Card bewd = new Card();
Card LOD = new Card();
var KaibaDeck = new List<Card>() { bewd, LOD };
var KaibaHand = new List<Card>() { };
var KaibaFusionDeck = new List<Card>() { };
var KaibaGraveyard = new List<Card>() { };
var YugiDeck = new List<Card>() { };
var YugiHand = new List<Card>() { };
var YugiFusionDeck = new List<Card>() { };
var YugiGraveyard = new List<Card>() { };
int KaibaDeckSize = KaibaDeck.Count;
string sDrawChoice;
int DrawChoice;
while (KaibaDeckSize > 0)
{
if (DrawChoice == 0)
{
break;
}
else
{
KaibaBattlePhase(KaibaHand, KaibaDeck, KaibaFusionDeck, YugiDeck, Field, KaibaGraveyard, YugiGraveyard, KaLP, YuLP, "Battle");
}
}
}
public static void KaibaBattlePhase(List<Card> KaibaHand, List<Card> KaibaDeck, List<Card> KaibaFusionDeck, List<Card> YugiDeck, List< List<Card> > Field, List<Card> KaibaGraveyard, List<Card> YugiGraveyard, int KaLP, int YuLP, const string Phase)
{
string sDecision;
int Decision;
while(true)//so the while loop NEVER breaks unless you have a 'break' later on
{
Console.WriteLine("Would you like to continue the Battle Phase? (Yes-'1' No-'0', Check Kaiba's Graveyard '-1', Check YUGI's graveyard '-2')");
sDecision = Console.ReadLine();
int.TryParse(sDecision, out Decision);
if (Decision==0)
{
break;
}
if (Decision==-1)
{
KaibaGraveyardFunction(KaibaGraveyard);
}
}
}
public static void KaibaGraveyardFunction(List<Card> KaibaGraveyard)
{
Console.WriteLine("Kaiba's graveyard contains: ");
foreach (Card KG in KaibaGraveyard)
{
Console.WriteLine(KG.Name);
}
}
}
I'm getting the following errors:
On the line KaibaGraveyardFunction(KaibaGraveyard);:
Method must have a return type
At while(true):
Invalid token 'while' in class, struct, or interface member declaration
In addition, I'm getting alot of other errors such as
"Invalid token '(', '=', '.' in class, struct, or interface member declaration"
"Syntax error, ']' expected"

At the end of your method declaration for KaibaBattlePhase you have this method parameter:
const string Phase
That's a syntax error which is confusing the compiler and causing it to not understand pretty much anything afterward. (I've never seen it get that confused from a keyword, usually that happens with missing/extra curly braces and such. But I guess this triggers it too.)
Why are you trying to pass a constant as a method parameter? That doesn't really make a lot of sense. If the method thinks it's a constant, it won't accept any value for it. If you pass it a constant, the method wouldn't know or care where the value came from.
If you remove const then the rest of the errors go away.
(Side note: The error becomes a lot easier to see if you clean up that method declaration. 10 parameters is a lot. It's highly likely that you can get away with some refactoring there to make it a lot cleaner. At its simplest, you can replace all of those parameters with a parameter DTO object which has those as properties. Potentially more useful would be the Replace Method With Method Object pattern, illustrated here.)

Not completely following your logic and not sure this is your issue but you never reevaluate KaibaDeckSize. If your intention is to simply use the while (KaibaDeckSize > 0) {} evaluation as a condition of entering the block, consider replacing it with a simple if statement: if (KaibaDeckSize > 0) {} Also, you never initialize DrawChoice which will generate a Use of unassigned local variable error during compilation. Use: int DrawChoice = 0; And this DrawCount` is never reassigned either.
Did you actually post your most recent code?
int KaibaDeckSize = KaibaDeck.Count;
string sDrawChoice;
int DrawChoice = 0;
while (KaibaDeckSize > 0)
{
if (DrawChoice == 0)
{
break;
}
else
{
KaibaBattlePhase(KaibaHand, KaibaDeck,
KaibaFusionDeck, YugiDeck, Field,
KaibaGraveyard, YugiGraveyard, KaLP, YuLP, "Battle");
}
KaibaDeckSize = KaibaDeck.Count;
}

Related

How to use AskAdjacentFacet function in NXOpen?

I am working with convergent facet bodies in NX and using C# in NXOpen. In the process, I am using UFSession.Facet.AskAdjacentFacet function to get the adjacent facets of each facet. But on using this particular command, the NXOpen throws error stating "NXOpen.NXException: The facet object is not supported for this operation". I went through the example given in NXOpen documentation (https://docs.plm.automation.siemens.com/data_services/resources/nx/10/nx_api/en_US/custom/ugopen_doc/uf_facet/uf_facet_eg2.c) and used similar approach, but this error shows up any way. Below is the script that I tried.
'''
public static void Main(string[] args)
{
NXOpen.UF.UFFacet myFacet = UFSession.Facet;
int facetID;
int edgeID;
int adjFacID;
int edgeIDinAdjFac;
int null_facet_ID = UFConstants.UF_FACET_NULL_FACET_ID;
facetID = null_facet_ID;
foreach (NXOpen.Facet.FacetedBody facetBody in workPart.FacetedBodies)
{
myFacet.CycleFacets(facetBody.Tag, ref facetID); // initialise for cycling
while (facetID != null_facet_ID)
{
List<int> Adj_fac_list = new List<int>();
for (edgeID = 0; edgeID < 3; edgeID++)
{
myFacet.AskAdjacentFacet(facetBody.Tag, facetID, edgeID, out adjFacID, out edgeIDinAdjFac);
if (adjFacID != UFConstants.UF_FACET_NULL_FACET_ID)
{
Adj_fac_list.Add(adjFacID);
}
}
}
}
}
Note: I could use the same model tag and facet id in the function UFSession.FACET.AskNumVertsInFacet and the script works fine. But I do not know why AskAdjacentFacet is not working. Can anyone help me on why there is an error and how to get this working?
On first glimpse, the problem I see is that you have not initialized the variable myFacet and it's null. And since it's null, you cannot call its members.
So change a single line of the code from
NXOpen.UF.UFFacet myFacet = UFSession.Facet;
To
NXOpen.UF.UFFacet myFacet = UFSession.GetUFSession().Facet;

Google Adwords adding Negative Keywords with special Characters via API

I am trying to add a Negative keyword via the CampaignCriterionService, of a Keyword that was retrieved from the SearchTerms Report for a specific Campaign.
I have working code that adds Negative keywords to a Campaign, great. The problem comes from where the Keyword text contains a "special character" (see here)
error:
Keyword text has invalid characters or symbols.. (Error: CriterionError.KEYWORD_HAS_INVALID_CHARS, FieldPath: operations[0].operand.criterion.text, Trigger: plain mirror 100 * 60)
I pulled the keyword from the Search Term report it has a Keyword Id. Therefore I tried to add the keyword as a negative, using the KeywordId using the below
example:
using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.Util.Reports.v201802;
using Google.Api.Ads.AdWords.v201802;
[TestMethod]
public void AddSingleNegativeKeywordToCampaign()
{
GoogleAdwords.Model.Campaign campaign = new GoogleAdwords.Model.Campaign(CampaignID);
List<Keyword> keywords = new List<Keyword> { new Keyword { id = 27736878000, matchType = KeywordMatchType.EXACT } };
campaign.AddNegativeKeywordstoCampaign(keywords);
}
public class Campaign : AdwordsBase
{
public long CampaignId { get; set; }
public string CampaignName;
public Campaign(long campaignId) : base()
{
CampaignId = campaignId;
}
public void AddNegativeKeywordstoCampaign(List<Keyword> ListofKeywords)
{
AddKeywordstoCampaign(ListofKeywords, Operator.ADD);
}
private void AddKeywordstoCampaign(List<Keyword> keywords, Operator #operator)
{
using (CampaignCriterionService campaignCriterionService =
(CampaignCriterionService)user.GetService(
AdWordsService.v201802.CampaignCriterionService))
{
List<CampaignCriterionOperation> operations = new List<CampaignCriterionOperation>();
foreach (Keyword keyword in keywords)
{
// Create the biddable ad group criterion.
NegativeCampaignCriterion keywordCriterion = new NegativeCampaignCriterion();
keywordCriterion.campaignId = CampaignId;
keywordCriterion.criterion = keyword;
// Create the operations.
CampaignCriterionOperation operation = new CampaignCriterionOperation();
operation.#operator = #operator;
operation.operand = keywordCriterion;
operations.Add(operation);
}
try
{
// Create the keywords.
CampaignCriterionReturnValue retVal = campaignCriterionService.mutate(
operations.ToArray());
// Display the results.
if (retVal != null && retVal.value != null)
{
foreach (CampaignCriterion campaignCriterion in retVal.value)
{
// If you are adding multiple type of criteria, then you may need to
// check for
//
// if (adGroupCriterion is Keyword) { ... }
//
// to identify the criterion type.
Debug.WriteLine("Keyword with Campaign id = '{0}', keyword id = '{1}', text = " +
"'{2}' and match type = '{3}' was {4}.", campaignCriterion.campaignId,
campaignCriterion.criterion.id, (campaignCriterion.criterion as Keyword).text,
(campaignCriterion.criterion as Keyword).matchType, #operator.ToString());
}
}
else
{
Debug.WriteLine("No keywords were added.");
}
}
catch (Exception e)
{
throw new System.ApplicationException("Failed to create keywords.", e);
}
}
}
}
BUT this doesn't work as the api reports the error:
Missing required field.. (Error: RequiredError.REQUIRED, FieldPath: operations[0].operand.criterion.text, Trigger: )
My question is
I can add the search term as a Negative in the Adwords UI, so, therefore, it must be possible. has anybody been able to achieve this using the most recent version of the Adwords API? (v201802)
to be perfectly clear, i don't think there is anything wrong with the code as such, its more of a question about how to add keywords that fall into this remit.
It appears that, true to the documentation here special characters cannot be added to a campaign though any medium.

How to pass var as another method`s parameter?

I am making a windows application.
At first I declared var and it contains another class method.
var ExtList = ExtTarget.GetExtTargets();
And GetExtTargets() is like this
public static List<ExtTarget> GetExtTargets()
{
var dt = SqlHelper.ExecuteDataTable(QueryHelper.ConnectionString,
#"
SELECT [seq],[SourceKind],[ExtKind],[DBKind],[ConnectionString]
,[FilePath],[TableName],[FileKind],[RowSplitter],[ColumnSplitter]
,[Title],[GroupName],[SyncOrder],[RepeatKind],[RepeatMonth]
,[RepeatDay],[RepeatHour],[RepeatMin],[RepeatWeek],[RepeatWeekNum]
,[LastSyncExecDate]
FROM [ExtTarget]
order by GroupName,SyncOrder");
return dt.Rows.Cast<DataRow>().Select<DataRow, ExtTarget>(a => ExtTarget.RowToModel(a)).ToList();
}
Then, I used it to foreach and then I want to pass Ext to another method's parameter.
Code is like this.
public void ProcessExtSync(object obj)
{
while (IsProcessGoing)
{
Thread.Sleep(ThreadDelay);
if (!IsProcessGoing) return;
var ExtList = ExtTarget.GetExtTargets();
foreach (var Ext in ExtList) // I want to use this Ext as parameter
{
while (IsSourceSyncGoing)
{
Thread.Sleep(ThreadDelay);
}
IsExtSyncGoing = true;
bool ExtSyncForceToRun = ConfigSettingHelper.Instance.IsServiceConfig(Words.ExtSyncForceToRun);
bool ExtSyncForceToRunOnlyError = ConfigSettingHelper.Instance.IsServiceConfig(Words.ExtSyncForceToRunOnlyError);
bool ExtSyncNeedToRun = ConfigSettingHelper.Instance.GetNextExecutingTime(Ext) < DateTime.Now;
if (ExtSyncForceToRun || ExtSyncNeedToRun)
{
//I want to pass Ext as parameter to this method
ServiceProcess.Instance.SyncExt();
if (ExtSyncForceToRun)
{
ConfigSettingHelper.Instance.SetServiceConfig(Words.ExtSyncForceToRun, false);
}
if (ExtSyncForceToRunOnlyError)
{
ConfigSettingHelper.Instance.SetServiceConfig(Words.ExtSyncForceToRunOnlyError, false);
}
}
if (!IsProcessGoing) return;
}
IsExtSyncGoing = false;
}
}
How can I modify that code? Please help me.
var is just a shortcut way of implicitly typing a variable. It saves some typing, but sometimes makes code harder to read when the reader can't determine the type. The compiler can figure out the strong type, though (or you'll get a compiler error), and if you hover over it in Visual Studio, the compiler will tell you the actual type.
With that out of the way, all you need to do is make sure that the method you want to pass your variable to takes in the type that you want to pass it (remember the type is not var, but in your case it is an ExtTarget).
The method you're calling should have a signature similar to this (although it may return any type):
public void SyncExt(ExtTarget extTarget)
{
// Implementation code here
}
Then in your code above you can call:
ServiceProcess.Instance.SyncExt(Ext);

Why does StringReader read '\uffff'?

I am writing a language of my own called SPL. It has an Input command which reads input from the ISplRuntime.Input property (it is a TextReader). All other commands run on this interface because this way I can write different apps with just one library!
I then wrote another console app to test my language. This is my implementation of ISplRuntime. Focus on the Input and constructor:
public class MyRuntime : ISplRuntime {
protected TextReader reader;
protected bool stopped;
public object Current {
get;
set;
}
public virtual TextReader Input {
get {
return reader;
}
}
public object[] Memory {
get;
protected set;
}
public TextWriter Output {
get {
return Console.Out;
}
}
public bool Stopped {
get {
return stopped;
}
set {
stopped = value;
if (value) {
Console.WriteLine ();
Console.WriteLine ("Program has finished");
}
}
}
public void ShowErrorMessage (string error) {
Console.WriteLine (error);
}
public MyRuntime () {
string s = Console.ReadLine ();
reader = new StringReader (s);
stopped = false;
Memory = new object[20];
}
}
When the runtime is constructed, it asks for input. And use that input to create a StringReader and return it in the Input property. So every time the input will only be one lline.
Then I write a program in SPL that outputs the input. And that is where the problem is! When I input 1 1 1 1 it prints 1 1 1 and threw a FormatException. This is how I read number input:
private bool ReadFromInput (ISplRuntime runtime, out int i) {
char stuffRead = (char)runtime.Input.Peek ();
if (stuffRead == ' ') {
i = 0;
runtime.Input.Read ();
return true;
}
if (char.IsNumber (stuffRead)) {
string numberString = "";
while (char.IsNumber (stuffRead)) {
stuffRead = (char)runtime.Input.Read ();
numberString += stuffRead;
}
i = Convert.ToInt32 (numberString); //This is where the exception occured! (Obviously, because there is no other methods that would throw it)
return true;
} else {
i = 0;
return false;
}
}
The parameter runtime is just the runtime you have just seen. It returns true if it successfully reads a number. And that number is the output parameter i.
After using the "Watch" window in Visual Studio, I found out that number string is "1\uffff" when the exception is thrown. That's why it throws it! I know (think) that '\uffff' is the end of line character. But why would it appear in my input? I know (think) that pressing Ctrl + Z makes a end of line, but I did not! Then I checked runtime.Input in the watch window. This is the result:
I see that there is a field called _s and I think that is the string that I told it to read from. See? _s doesn't even contain '\uffff', how come it reads it?
P.S. I already know the solution. I just need to change the while loop a little and it works. But I want to know why does it reads an end of line.
There is no mistery here - \uffff is produced by your code. All you need is to read the documentation and understand what the methods that you call return.
TextReader.Peek Method
Return Value
Type: System.Int32
An integer representing the next character to be read, or -1 if no more characters are available or the reader does not support seeking.
TextReader.Read Method
Return Value
Type: System.Int32
The next character from the text reader, or -1 if no more characters are available.
Hope you see the relation between -1 (0xffffffff) and \uffff.

Encapsulation with multiple classes C#

So my question is over basic encapsulation. I know I am setting up my getters and setters right (I actually have a question later about this) but I have multiple classes. I have another class and I understand that I am making pieces of my code view-able to my outside class by making certain things public. So I think I set up my first code file right. (Some background, I have a class that is connecting to a database and then another that is encapsulating all the data. The first code section posted is the encapsulating part, I then post my three methods I was messing up on.)
I feel okay with the getting and setting, I feel a little unsure of my constructor. I feel like I put my variables in the parameter list so that I put values in them from my outside class? Right? or should I be putting public forms of my private variables in my other code file and then passing those into my constructor in that same file?
/ this my first code file
using System;
public class clsEncapsulate
{
private int mID;
private string mName;
private string mClassification;
private DateTime mConvocationDate;
private string mLocation;
public int ID
{
get
{
return mID;
}
set
{
mID = value;
}
}
public string Name
{
get
{
return mName;
}
set
{
mName = value;
}
}
public string Classification
{
get
{
return mName;
}
set
{
mName = value;
}
}
private DateTime ConvocationDate
{
get
{
return mConvocationDate;
}
set
{
mConvocationDate = value;
}
}
private string Location
{
get
{
return mLocation;
}
set
{
mLocation = value;
}
}
public clsEncapsulate(int id, string name, string classification, DateTime convocationDate, string location)
{
bool running = false;
while(running == false)
{
ID = mID;
Name = mName;
Classification = mClassification;
ConvocationDate = mConvocationDate;
Location = mLocation;
running = true;
}
}
}
In my second code file I am just going to put the methods that I am having trouble with.
private void refreshbox()
{
string formattedConvocation;
string formattedDateTime;
string formattedConvocationName;
lstConvocations.Items.Clear();
foreach (clsEncapsulate currentConvocation in mConvocationAL)
{
formattedConvocationName = currentConvocation.Name;
formattedConvocationName = truncateString(formattedConvocationName, 30);
formattedConvocation = formattedConvocationName.PadRight(33);
formattedConvocation += currentConvocation.Classification.PadRight(17);
formattedDateTime = currentConvocation.ConvocationDate.ToShortDateString().PadRight(10)
+ currentConvocation.ConvocationDate.ToShortTimeString().PadLeft(8);
formattedConvocation += formattedDateTime;
lstConvocations.Items.Add(formattedConvocation);
}
}
Alright, so in order for my second code file to manipulate the variables in the first code file, I need to expose them to this method. I didn't know if I should be putting my public variables in the constructor, or if I should be declaring them somewhere in my first code file. I was very unsure of how to expose these variables to this method. I've fiddle around with it but my book doesn't address this situation exactly and I was having trouble figuring it out.
If someone does answer this question please break down why you're going to put what you're going to put! I want to understand why, say, I put my public variables in one place, and not another. Or why I declare an object of my encapsulate class in one place and not another. I was trying to declare an encapsulate object in my method so it would give this method access to the variables, but it wasn't working! Please tell me what I was doing wrong or if you want me to post more of my code.
Below are the two other methods I was messing up on.
/ second method from my second code file I was messing up on:
private void displayProperties(int index)
{
if (index == -1)
{
return;
}
clsEncapsulate selectedValue = (clsEncapsulate)mConvocationAL[index];
txtConvocationName.Text = selectedValue.Name;
txtConvocationClassification.Text = selectedValue.Classification;
txtConvocationDate.Text = selectedValue.ConvocationDate.ToShortDateString();
txtConvocationTime.Text = selectedValue.ConvocationDate.ToShortTimeString();
txtConvocationLocation.Text = selectedValue.Location;
txtID.Text = selectedValue.ID.ToString();
}
/ last method I was messing up on:
private void readConvocations(string filterConstraint, string sortField, string sortOrder)
{
OleDbConnection connection = null;
OleDbDataReader reader = null;
try
{
connection = new OleDbConnection();
connection.ConnectionString = mConnectionString;
connection.Open();
string statement = "SELECT ID, Name, Classification, Location, Date FROM Convocations ";
if(filterConstraint != "")
{
statement += "WHERE Name LIKE " + toSQL(filterConstraint, true) + " ";
}
string statement2 = statement;
statement = string.Concat(new string[]
{
statement2, "ORDER BY ", sortField, " ", sortOrder
});
OleDbCommand oleDbCommand = new OleDbCommand(statement, connection);
reader = oleDbCommand.ExecuteReader();
mConvocationAL.Clear();
while(reader.Read())
{
clsEncapsulteconvocation = new clsEncapsulate();
convocation.ID = (int)reader["ID"];
convocation.Name = (string)reader["Name"];
convocation.Classification = (string)reader["Classification"];
convocation.Location = (string)reader["Location"];
convocation.ConvocationDate = (DateTime)reader["Date"];
mConvocationAL.Add(convocation);
}
}
finally
{
if (reader != null)
{
reader.Close();
}
if (connection != null)
{
connection.Close();
}
}
}
Tell me if you need me to elaborate more to help you understand my situation. I am new at learning vocabulary and want to understand this! Thank you for helping. :)
The code you provided is one public object and a bunch of private methods so its difficult to get the overall picture of how your code it working together but there are a few principles you can apply to make your code better structured, now and in the future.
Have a read about SOLID (http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)). The S and the D would apply well to your example.
Also you mentioned construtors and private properties. Try looking into Imutable types. That means once the object is created you cannot change it. For your clsEncapsulate class that would mean making your fields read only and remove the public setters.
Good luck.

Categories