This question already has answers here:
Control cannot fall through from one case label
(8 answers)
Closed 2 years ago.
So I'm trying to code an escort command for my game using case switch. Basically I have tons of other commands but I've never done one where it makes a target user follow the session user. Basically the person using the command would type :escorts username and it would make the other user stand either in front of the person using the command. or behind them. Any help would be amazing.
#region Escorts User
case "escorting":
{
#region Generate Instances / Sessions / Vars
if (!RoleplayManager.ParamsMet(Params, 1))
{
Session.SendWhisper("Invalid syntax: :stun x");
return true;
}
string Target = Convert.ToString(Params[1]);
GameClient TargetSession = null;
RoomUser Actor = null;
RoomUser Targ = null;
TargetSession = RoleplayManager.GenerateSession(Target);
if (TargetSession == null)
{
Session.SendWhisper("The user was not found in this room!");
return true;
}
if (TargetSession.JobManager() == null)
{
Session.SendWhisper("The user was not found in this room!");
return true;
}
if (TargetSession.JobManager().GetRoomUser() == null)
{
Session.SendWhisper("The user was not found in this room!");
return true;
}
if (TargetSession.JobManager().GetRoomUser().RoomId != Session.JobManager().GetRoomUser().RoomId)
{
Session.SendWhisper("The user was not found in this room!");
return true;
}
Targ = TargetSession.JobManager().GetRoomUser();
Actor = Session.JobManager().GetRoomUser();
int MyJobId = Session.GetRoleplay().JobId;
int MyJobRank = Session.GetRoleplay().JobRank;
Vector2D Pos1 = new Vector2D(Actor.X, Actor.Y);
Vector2D Pos2 = new Vector2D(Targ.X, Targ.Y);
#endregion
#region Police Conditions
if (Params.Length == 1)
{
Session.SendWhisper("Opa, você esqueceu de inserir um nome de usuário!");
return true;
}
GameClient TargetClient = Plus.GetGame().GetClientManager().GetClientByUserName(Params[1]);
if (TargetClient == null)
{
Session.SendWhisper("Ocorreu um erro ao tentar encontrar esse usuário, talvez ele esteja offline.");
return true;
}
RoomUser RoomUser = Session.JobManager().CurrentRoom.GetRoomUserManager().GetRoomUserByHabbo(Session.JobManager().UserName);
if (!JobManager.validJob(Session.GetRoleplay().JobId, Session.GetRoleplay().JobRank) && Session.GetRoleplay().inCR == false)
{
Session.SendWhisper("Your job cannot do this!", false, 34);
return true;
}
bool isclose = false;
if (!Session.GetRoleplay().JobHasRights("police")
&& !Session.GetRoleplay().JobHasRights("gov")
&& !Session.GetRoleplay().JobHasRights("swat")
&& !Session.GetRoleplay().JobHasRights("service")
&& RoleplayManager.CR == false)
{
Session.SendWhisper("Your job cannot do this!");
return true;
}
if (!Session.GetRoleplay().Working && RoleplayManager.CR == false)
{
Session.SendWhisper("You must be working to do this!");
return true;
}
if (Session.GetRoleplay().Dead)
{
Session.SendWhisper("You cannot do this while you are dead!");
return true;
}
if (Session.GetRoleplay().Jailed)
{
Session.SendWhisper("You cannot do this while you are in jail!");
return true;
}
if (Targ.Frozen)
{
Session.SendWhisper("This user is already stunned!");
return true;
}
if (Session.JobManager().CurrentRoom.RoomData.Description.Contains("NOCOP"))
{
Session.SendWhisper("Can't do this in 'NOCOP' rooms.");
return true;
}
if (JobManager.validJob(Session.GetRoleplay().JobId, Session.GetRoleplay().JobRank))
{
if (Session.JobManager().CurrentRoom.RoomData.Description.Contains("WESTERN") && Session.GetRoleplay().JobHasRights("police"))
{
Session.SendWhisper("Can't do this in 'WESTERN' rooms.");
return true;
}
if (!Session.JobManager().CurrentRoom.RoomData.Description.Contains("WESTERN") && Session.GetRoleplay().JobHasRights("western"))
{
Session.SendWhisper("Can only do this in 'WESTERN' rooms.");
return true;
}
}
#endregion
#region Execute
Point ClientPos = new Point(RoomUser.X, RoomUser.Y);
double Distance = RoleplayManager.Distance(Pos1, Pos2);
if (Distance <= 1)
{
if (Session.GetRoleplay().Cop == true && Session.GetRoleplay().inCR == true)
{
RoleplayManager.Shout(Session, "*Fires their stun-gun at " + TargetSession.JobManager().UserName + "*");
TargetSession.GetRoleplay().EffectSeconds = 10;
TargetSession.GetRoleplay().StunnedSeconds = 10;
Targ.ApplyEffect(590);
Targ.CanWalk = true;
Targ.Frozen = false;
Targ.ClearMovement();
LevelManager.AddLevelEXP(Session, 30);
Session.GetRoleplay().SaveQuickStat("currentxp", +30);
return true;
}
}
else
{
Session.SendWhisper("Você deve se aproximar desse cidadão para escoltá-lo!");
return true;
}
}
#endregion
#endregion
The error says that each case block cannot fall through another one.
This means that each case must have a return or break at their ending.
Keep in mind that you may group multiple cases into one (technically this is falling through) when they contain no code.
For more information, see MSDN.
Your switch statement is massive and probably needs some refactoring.
Related
I'm looking for a way to create a delay in my code without stopping the rest of the code in this time frame. It has to work as follows. If a condition is true for X amount of seconds, set the alarm bool High. The code below is a part of code where I set the alarms but there needs to be a delay.
I'm very new to C# so try to dumb it down a bit, maybe a small example or links.
if (Valve.Parameter.NormallyOpen == false)
{
if (Valve.Status.Output == true & Valve.Status.Opened == false)
{
Valve.Alarm.NotOpened = true;
}
if (Valve.Status.Output == false & Valve.Status.Closed == false)
{
Valve.Alarm.NotClosed = true;
}
}
Some background info: this will be a valve control block in PLCNext written in C#. The control block should give a alarm if the valve is send open but does not give open feedback within X seconds (takes time to open).
using System;
using System.Threading;
using System.Iec61131Lib;
using Iec61131.Engineering.Prototypes.Types;
using Iec61131.Engineering.Prototypes.Variables;
using Iec61131.Engineering.Prototypes.Methods;
using Iec61131.Engineering.Prototypes.Common;
namespace EclrFirmwareLibrary1
{
[FunctionBlock]
public class Valve_Test
{
[InOut]
public Valve Valve;
[Output]
public bool Output;
double seconds = 1.00; // 1 Second Interval
[Initialization]
public void __Init()
{
//
// TODO: Initialize the variables of the function block here
//
}
[Execution]
public void __Process()
{
Valve.Status.Interlock = Valve.Control.Interlock;
Valve.Status.Opened = Valve.Control.FB_Open;
Valve.Status.Closed = Valve.Control.FB_Closed;
if (Valve.Control.Manual_Mode == true){
Valve.Status.Manual_Mode = true;
Valve.Status.Auto_Mode = false;
}
if (Valve.Control.Auto_Mode == true & Valve.Control.Manual_Mode == false){
Valve.Status.Manual_Mode = false;
Valve.Status.Auto_Mode = true;
}
if(Valve.Status.Interlock == false & Valve.Alarm.General == false)
{
if (Valve.Status.Manual_Mode & Valve.Control.Manual_Control)
{
Output = true;
Valve.Status.Output = true;
}
else if (Valve.Status.Auto_Mode & Valve.Control.Auto_Control)
{
Output = true;
Valve.Status.Output = true;
}
else
{
Output = false;
Valve.Status.Output = false;
}
}
else
{
Output = false;
Valve.Status.Output = false;
}
//Alarms---------------------------------------------------
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromSeconds(seconds);
var timer = new System.Threading.Timer((e) =>
{
CheckValve();
}, null, startTimeSpan, periodTimeSpan);
}
private void CheckValve()
{
if (Valve.Parameter.NormallyOpen == false)
{
if (Valve.Status.Output == true & Valve.Status.Opened == false)
{
Valve.Alarm.NotOpened = true;
}
if (Valve.Status.Output == false & Valve.Status.Closed == false)
{
Valve.Alarm.NotClosed = true;
}
}
else
{
if (Valve.Status.Output == false & Valve.Status.Opened == false)
{
Valve.Alarm.NotOpened = true;
}
if (Valve.Status.Output == true & Valve.Status.Closed == false)
{
Valve.Alarm.NotClosed = true;
}
}
if (Valve.Status.Opened == true & Valve.Status.Closed == true)
{
Valve.Alarm.OpenedAndClosed = true;
}
if (Valve.Alarm.NotClosed || Valve.Alarm.NotOpened || Valve.Alarm.OpenedAndClosed)
{
Valve.Alarm.General = true;
}
}
}
}
The important thing to note in this case is that the device you are using includes a .NET runtime implementation that is a subset and specialisation of the complete .NET runtime. This "eCLR" (Embedded CLR) is designed to operate in the deterministic real-time context required for many industrial control applications.
The details of this implementation can be seen in the PLCnext Info Center
When you create a PLCnext C# project in Visual Studio, the project includes a Programming Reference (.chm file). You will see from this reference that the Timer class is not included in the eCLR.
To your question:
There are a number of ways you can implement a delay function in a PLCnext C# function. Perhaps the simplest is to use the DateTime.Now property to get the current system time when the alarm condition is first seen, and remember this value. Then, on each call to the Process method, you can compare the current time to the time when the alarm condition was first seen. When the time period exceeds the preset time, then the output is set.
For more help with questions related to PLCnext Control devices, you can visit the PLCnext Community. There is an active forum there, where you can discuss these sorts of issues with other PLCnext users.
To call a method each x seconds you can use the TimeSpan Method provided by C# and just pass a method called CheckValve, where you put all your code into.
TimeSpan Example:
double seconds = 1.00; // 1 Second Interval
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromSeconds(seconds);
var timer = new System.Threading.Timer((e) =>
{
CheckValve();
}, null, startTimeSpan, periodTimeSpan);
I would also advise you to refactor some of your code:
You can replace bool == true checks with just the bool and bool == false checks with just the bool and a ! before the name.
I would also add an else if so if the if is true you don't need to check the other statement.
CheckValve Method:
private void CheckValve() {
if (!Valve.Parameter.NormallyOpen) {
if (Valve.Status.Output && !Valve.Status.Opened) {
Valve.Alarm.NotOpened = true;
}
else if (!Valve.Status.Output && !Valve.Status.Closed)
{
Valve.Alarm.NotClosed = true;
}
}
}
I have a form in C# for inputting some data into a List.
The form consists of text boxes and up and down numeric boxes. Everything works fine but I want to have an error handler (try/catch) in my code so it will check if any of the text boxes are empty or the numeric boxes are left to 0, if thats the case it should pop up an error message.
I tried :
try
{
//code
}
catch (NoNullAllowedException e) //tried it without the e as well
{
//code
}
The code I was having in the brackets its the following one. Sometimes the GetItemDetails() was throwing me an error saying that not all code paths returns a value.
Any thoughts why is doing this or how can I fix it?
public iRepairable GetItemDetails()
{
Shirt shirt = null;
TShirt tshirt = null;
Trouser trouser = null;
Shoe shoe = null;
Boolean isShirt = true;
Boolean isTshirt = true;
Boolean isTrouser = true;
Boolean isShoe = true;
if (rdoShirt.Checked == true)
{
shirt = new Shirt(txtBrand.Text, Convert.ToDouble(txtPrice.Text), Convert.ToInt32(txtAmount.Text), txtCollection.Text);
isTshirt = false;
isTrouser = false;
isShoe = false;
}
else if (rdoTShirt.Checked == true)
{
tshirt = new TShirt(txtBrand.Text, Convert.ToDouble(txtPrice.Text), Convert.ToInt32(txtAmount.Text), txtCollection.Text);
isShirt = false;
isTrouser = false;
isShoe = false;
}
else if (rdoTrouser.Checked == true)
{
trouser = new Trouser(txtBrand.Text, Convert.ToDouble(txtPrice.Text), Convert.ToInt32(txtAmount.Text), txtCollection.Text);
isShirt = false;
isTshirt = false;
isShoe = false;
}
else
{
shoe = new Shoe(txtBrand.Text, Convert.ToDouble(txtPrice.Text), Convert.ToInt32(txtAmount.Text), txtCollection.Text);
isShirt = false;
isTrouser = false;
isTshirt = false;
}
if (isShirt)
{
return shirt;
}
else if (isTshirt)
{
return tshirt;
}
else if (isTrouser)
{
return trouser;
}
else //if(isShoe)
{
return shoe;
}
First of all, the NoNullAllowedException is not for list or just null values. Is the exception that throws when you want to insert null values in a column that doesn't allow them (for more info, MSDN).
For your code, place at the bottom of your code a default return value (but as far as i can see, your code shouldnt break at all)
I am trying to find out that in ad, user has allowed to change password or not.
I have used SearchResponse to find out that user exists or not.
SearchResponse response = (SearchResponse)connection.SendRequest(request);
DirectoryAttribute attribute = response.Entries[0].Attributes["ntSecurityDescriptor"];
if (attribute != null)
{
const string PASSWORD_GUID = "{ab721a53-1e2f-11d0-9819-00aa0040529b}";
const int ADS_ACETYPE_ACCESS_DENIED_OBJECT = 6;
bool fEveryone = false;
bool fSelf = false;
ActiveDs.ADsSecurityUtility secUtility = new ActiveDs.ADsSecurityUtility();
ActiveDs.IADsSecurityDescriptor sd = (IADsSecurityDescriptor)secUtility.ConvertSecurityDescriptor((byte[])attribute[0], (int)ADS_SD_FORMAT_ENUM.ADS_SD_FORMAT_RAW, (int)ADS_SD_FORMAT_ENUM.ADS_SD_FORMAT_IID);
ActiveDs.IADsAccessControlList acl = (ActiveDs.IADsAccessControlList)sd.DiscretionaryAcl;
foreach (ActiveDs.IADsAccessControlEntry ace in acl)
{
if ((ace.ObjectType != null) && (ace.ObjectType.ToUpper() == PASSWORD_GUID.ToUpper()))
{
if ((ace.Trustee == "Everyone") && (ace.AceType == ADS_ACETYPE_ACCESS_DENIED_OBJECT))
{
fEveryone = true;
}
if ((ace.Trustee == #"NT AUTHORITY\SELF") && (ace.AceType == ADS_ACETYPE_ACCESS_DENIED_OBJECT))
{
fSelf = true;
}
break;
}
}
if (fEveryone || fSelf)
{
return Global.RequestContants.CANT_CHANGE_PASSWORD;
}
else
{
return string.Empty;
}
}
I am doing an assignment involving the creation of a simple Quiz type form application. However, whenever I run the program, only the first answer shows for a multiple question and I cannot for the life of me figure out why.
This is the contstructor:
MultipleChoice dlg =
new MultipleChoice(
new Question("What is the capital of Zimbabwe?",
new Answer("Paris", false),
new Answer("Washington D.C.", false),
new Answer("Harare", true),
new Answer("Cairo", false),
new Answer("N'Djamena", false)));
if (dlg.ShowDialog() == DialogResult.OK)
{
if (dlg.Correct) MessageBox.Show("You got something right!");
else MessageBox.Show("You couldn't be more wrong");
}
And this is the Question Form Code:
private Question Q;
public MultipleChoice (Question q)
{
Q = q;
InitializeComponent();
textPrompt.Text = Q.Prompt;
if (Q.A != null)
{
radioA.Text = Q.A.Prompt;
}
else radioA.Hide();
if (Q.B != null)
{
radioB.Text = Q.B.Prompt;
}
radioB.Hide();
if (Q.C != null)
{
radioC.Text = Q.C.Prompt;
}
radioC.Hide();
if (Q.D != null)
{
radioD.Text = Q.D.Prompt;
}
radioD.Hide();
if (Q.E != null)
{
radioE.Text = Q.E.Prompt;
}
radioE.Hide();
}
public bool Correct
{
get
{
if (Q == null) return false;
if (Q.A != null && Q.A.Correct && radioA.Checked) return true;
if (Q.B != null && Q.B.Correct && radioB.Checked) return true;
if (Q.C != null && Q.C.Correct && radioC.Checked) return true;
if (Q.D != null && Q.D.Correct && radioD.Checked) return true;
if (Q.E != null && Q.E.Correct && radioE.Checked) return true;
return false;
}
}
Where have I gone wrong?
There is no else for any option after A:
if (Q.B != null)
{
radioB.Text = Q.B.Prompt;
}
radioB.Hide(); //This is **always** going to be called - hiding radioB :)
Should be:
if (Q.B != null)
radioB.Text = Q.B.Prompt;
else
radioB.Hide();
I have the following line of code:
public bool dcpl_radar()
{
if (radar == null)
return false;
else
{
if (radar != null)
{
if (radar.InvokeRequired)
radar.BeginInvoke(new MethodInvoker(delegate()
{
radar.Visible = false;
}));
else
this.radar.Visible = false;
radar = null;
}
return true;
}//end of else statement
}
but VStudio keeps throwing an error on the invoke line. I've checked the Debugger and if (radar == null) is true, yet VStudio is trying to evaluate a part of the code it shouldn't be in. Can someone explain why it's doing this please?
Wait a minute... I think we have a race condition.
Lets say you BeginInvoke, almost immediately you set radar = null.
There really is no telling when your anonymous delegate will be executed.
I would imagine this should solve your issue.
public bool dcpl_radar()
{
if (radar != null)
{
if (radar.InvokeRequired)
{
radar.BeginInvoke(new MethodInvoker(HideRadar));
}
else
{
HideRadar();
}
return true;
}
return false;
}
private void HideRadar()
{
this.radar.Visible = false;
this.radar = null;
}
What is happening:
The anonymous delegate is being called after you set the radar to null.
How to fix it
public bool dcpl_radar()
{
if (radar == null)
return false;
else
{
if (radar != null)
{
if (radar.InvokeRequired)
radar.BeginInvoke(new MethodInvoker(delegate()
{
radar.Visible = false;
radar = null;
}));
else {
this.radar.Visible = false;
radar = null;
}
}
return true;
}//end of else statement
}
(Note where I've moved your 'null' assignments).
Though I am a bit worried about the point of setting a variable to null, it's generally a sign of a bad design.