Passing a bool in c# - c#

hey i'm making a discord bot and im trying to set it so that with a command a bool can be set to true / false (it will initiate a different response futher on) but when i do it, it stays as false despite it being set to true. im fairly sure its due to not passing the variable through. how would i go about doing it in this instance?
the bool is called (opse)
namespace ConsoleApp5
{
public class Commands : ModuleBase<SocketCommandContext>
{
bool opse;
[Command("opsset")]
public async Task trueset(string op)
{
if (op == "true")
{
opse = false;
Console.WriteLine("Operations is set to active! Set by " +
Context.Message.Author.Username);
}
if (op == "false")
{
opse = true;
Console.WriteLine("Operations is set to inactive! Set by " +
Context.Message.Author.Username);
}
}
[Command("operations")]
public async Task ops()
{
if (opse = true)
{
await Context.Channel.SendMessageAsync("Operations are not currently active. Check your
designated schedule to see when operations are active");
}
if (opse = false)
{
await Context.Channel.SendMessageAsync("Operations are currently active. Message you SO
or file an absent report");
}
}
}
}

You're using a single = to check for the value of opse, which is incorrect. A single = is used to assign new values.
To compare values you should use ==:
if (opse == true)
{
...
}
if (opse == false)
{
...
}

Related

how to disable userinteraction of nsview

I am trying to do something similar as UserInteractionEnabled = false in iOS, but it seems that this property is not available in NSView. I also see that one approach is to implement the hittest method to return null, but the hittest for this lass already has a non-trivial implementation and I don't think I can set it to return null. I found a (deprecated) property called acceptsTouchEnabled, and I m wondering if it can achieve the same thing as UserInteractionEnabled.
The project is done in Xamarin, btw.
FreeHandView = new PaintBoardControl
{
BackgroundColor = UIColor.Clear,
TranslatesAutoresizingMaskIntoConstraints = false,
UserInteractionEnabled = false
};
this is the original declaration of the variable, where the UserInteractionEnabled is set to false.
and this is the implementation of the hittest method in my Mac app:
public override NSView HitTest(CGPoint aPoint)
{
aPoint = ContentContainer.ConvertPointFromView(aPoint, this);
aPoint = new CGPoint(aPoint.X + _freehandViewLeftConstraint.Constant,
aPoint.Y + _freehandViewTopConstraint.Constant);
if (_hitTestBitArray != null && aPoint.X >= 0 && aPoint.Y >= 0 &&
_hitTestBitArrayWidth > aPoint.X && _hitTestBitArrayHeight > aPoint.Y)
{
var index = aPoint.Y * _hitTestBitArrayWidth + aPoint.X;
return _hitTestBitArray.Get((int)index) ? this : null;
}
return null;
}
Sometimes hitTest don't work at all try using something like this maybe mousedown can help you
public class ExtendedNSView : NSView
{
public bool IsEnabled { get; set; }
public override void MouseDown(NSEvent theEvent)
{
if (IsEnabled)
{
base.MouseDown(theEvent);
}
}
}

Better way to return debug information instead of using lots of if-else

So I have a boolean method that is used to verify if a command is valid. This is used inside of an engine in which it verifies that the process can continue or not. This is the validation method:
private bool CommandIsValid(WC command)
{
if (command.Address == null ||
command.UserId < 0 ||
String.IsNullOrEmpty(command.CurrencyCode) ||
command.Amount < .01m ||
command.Address.PrimitiveAddress == null ||
String.IsNullOrEmpty(command.Address.Source) ||
String.IsNullOrEmpty(command.Address.PrimitiveAddress.City) ||
String.IsNullOrEmpty(command.Address.PrimitiveAddress.Country) ||
String.IsNullOrEmpty(command.Address.PrimitiveAddress.FirstName) ||
String.IsNullOrEmpty(command.Address.PrimitiveAddress.LastName) ||
String.IsNullOrEmpty(command.Address.PrimitiveAddress.Region) ||
command.Address.Created <= DateTime.MinValue)
{
return false;
}
return true;
}
And is called here inside of my method here:
if (!CommandIsValid(cmd))
{
_logger.Debug("Invalid command);
}
The issue is that I want to have some type of information regarding what failed validation. The best solution would have a list of what validations didn't pass, so I could relay that in my logging debugger. Obviously I could do this using a bunch of if-else statements, but it seems sloppy, as having a bunch of if else statements seems very poor style and I was wondering if there is any way in c# or in general I can do to avoid this.
Are you familiar with DataAnnotations and it's associated Validator class?
It would require modifications to your object.
public PrimitiveAddress
{
[Required]
public string City {get;set;}
}
and then you use it like so:
var context = new ValidationContext(command.Address.PrimitiveAddress);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(recipe, context, results);
if (!isValid)
{
foreach (var validationResult in results)
{
Console.WriteLine(validationResult.ErrorMessage);
}
}
if you've got a base command class you could probably add it in a more generic fashion. You can create your own validation attributes, use IValidatableObject for anything complex, customize the error messages
[Required(ErrorMessage="This is required.")]
Instead of returning a bool, return a container of bool values where first is the overall status False/True then each one reflects a condition of the above. If first element is False, then you check which condition (index) is the false. Looks like it is fixed in size then you may just agree on the sequence.
Something like this:
List<bool> YourFunction(YourDebuggerThing Input)
{
List<bool> Result = new List<bool>();
if (Input.Condition1 == false || Input.Condition2 == false || Input.Condition3 == false || Input.Condition4 == false || Input.Condition5 == false)
Result.Add(false); // first element is always the overall status
if(Input.Condition1 == false) Result.Add(false); else Result.Add(true); // element 2 is condition 1
if(Input.Condition2 == false) Result.Add(false); else Result.Add(true); // element 3 is condition 2
// ..
// ConditionN
return Result;
}
One idea might be to implement your checks within the Get/Set methods of the class' properties, using a custom exception. Such as;
public class PrimitiveAddresses
{
private string _city;
public string City
{
get
{
if(_city != null) {return _city;}
else {throw new CommandInvalidException("No valid city provided");}
}
set
{
_city = value;
}
}
}
public class CommandInvalidException: Exception
{
public CommandInvalidException(string message)
: base(message)
{
}
}
Then during you implementation, use a try/catch to handle the specific error;
public void foo()
{
try
{
if (String.IsNullOrEmpty(command.Address.PrimitiveAddress.City)){} // Ect
}
catch (CommandInvalidException e)
{
Console.WriteLine("Command invalid due to " + e.message);
// Or any other way you want to deal with the missing data
}
}
Hope it helps :)

Loading the method body from a string?

For very special circumstances, I'd like to be able to store C# code in a configuration entry and fill in an empty function with this code at runtime. For example, let's say on initial run I start out with a method such as this:
bool Evaluate(int number)
{
return false;
}
I have a configuration entry that looks like this:
<add key="EvaluateCode" value="if (number > 5) { return true; } else { return false; }"/>
After loading the EvaluateCode configuration entry I'd like to replace the function body of Evaluate so that it looks like this:
bool Evaluate(int number)
{
if (number > 5) { return true; } else { return false; }
}
After this 'replacement' is made, the Evaluate function should behave as the code dictates, just as it would as if the code had not been loaded dynamically.
How could I acheive this in C#?
Bonus: What would be the risks of implementing such a feature? How can I mitigate those risks?
Essentially you are asking for the ability to compile c# code at run time, which is possible, and is described here
This sounded like fun.. so I decided to try it.
No need to upvote.. just popping this here so I can reference it in future :)
Given the below class:
class DynamicMethodTest {
private MethodInfo _methodToCall;
private object _obj;
public void PerformInjection(string newBody) {
using (var codeProvider =
new Microsoft.CSharp.CSharpCodeProvider()) {
var res = codeProvider.CompileAssemblyFromSource(
new System.CodeDom.Compiler.CompilerParameters() {
GenerateInMemory = true
},
"public class StubClass { public bool Evaluate(int number) { " + newBody + " }}"
);
var type = res.CompiledAssembly.GetType("StubClass");
_obj = Activator.CreateInstance(type);
_methodToCall = _obj.GetType().GetMethod("Evaluate");
}
}
public bool Evaluate(int number) {
if (_methodToCall != null)
return (bool)_methodToCall.Invoke(_obj, new object[] { number });
return false;
}
}
We can do this:
public class Program {
public static void Main() {
var dynamicTest = new DynamicMethodTest();
Console.WriteLine(dynamicTest.Evaluate(15)); // False
dynamicTest.PerformInjection("if (number > 5) { return true; } else { return false; }");
Console.WriteLine(dynamicTest.Evaluate(15)); // True
Console.Read();
}
}
This results in:
False
True
As output. Basically, before the "Injection" (its not really injection.. its more of a fascade) the method returns false. After "Injection" it returns true (as expected).

Claims permission check fails when ClaimsPrincipalPermission is applied to class & method within it

I have the following class:
[ClaimsPrincipalPermission(SecurityAction.Demand, Operation = "view", Resource = "agreement")]
public class AgreementViewModel : Screen
{
[ClaimsPrincipalPermission(SecurityAction.Assert, Operation = "save", Resource = "agreement")]
public async void Save()
{
}
}
My problem is that even though the principal has both claims specified above, the call to Save fails. If i take off the claims from class level it works fine. The class also instantiates just fine. My "manual" check to figure out if the user can execute action works fine, it's the actual execution the fails. Manual check is defined as following:
public bool CanExecute(object sender, [CallerMemberName] string callerMethod = null)
{
string targetMethodName = callerMethod;
if (callerMethod == null)
return true;
if (callerMethod.StartsWith("Can"))
targetMethodName = callerMethod.Substring(3, callerMethod.Length - 3);
if (string.IsNullOrEmpty(targetMethodName))
return true;
var claimsAttribute = sender.GetType().GetMethods()
.Where(x => x.Name == targetMethodName)
.SelectMany(x => x.GetCustomAttributes(typeof(ClaimsPrincipalPermissionAttribute), true).Cast<ClaimsPrincipalPermissionAttribute>())
.FirstOrDefault();
return CanExecute(claimsAttribute);
}
private bool CanExecute(ClaimsPrincipalPermissionAttribute claimsAttribute)
{
if (claimsAttribute == null)
return true;
try
{
claimsAttribute.CreatePermission().Demand();
}
catch (SecurityException)
{
return false;
}
return true;
}

Return ComboBox as Boolean

I know its not best practice to use a boolean for a comboBox but for this application which returns data a yes/no is all thats required. I'm trying to return whether its yes or no but am getting a warning 'possible unintended reference' Any help cleaning up the code is greatly appreciated.
public bool PlayDataToEnd
{
get
{
return this.PlayDataToEnd.SelectedValue == "Yes";
}
set
{
this.PlayDataToEnd.SelectedValue = true;
}
}
Suppose your internal ComboBox is named playDataToEndCombo:
public bool PlayDataToEnd
{
get
{
return playDataToEndCombo.SelectedValue.ToString() == "Yes";
}
set
{
playDataToEndCombo.SelectedValue = value ? "Yes" : "No";
}
}
I think you should use Index with a convention: 0 for Yes and 1 for No:
public bool PlayDataToEnd
{
get
{
return playDataToEndCombo.SelectedIndex == 0;
}
set
{
playDataToEndCombo.SelectedIndex = value ? 0 : 1;
}
}

Categories