Visual Studio debugger automatic variable assignment - c#

Yes, I see the other topic: Visual Studio Debugger - Automatic Variable Assignment
But I needed a solution today, and found one before I see it, and I'm wondering if is there a better one out there?
My case:
I have a list of entities and I set up some policy related property based on a lot of factor. But it's not implemented yet or simply I want to test the UI when the entity has a right and when not (change it as fast as possible to do the real job).
So I set up the entity as if it has the right, so I can test the UI with this. But I don't want to break at every element in the list, and change the flag from true to false (to test the other case). I looked for a way to change a variable from debugger automatically. I came up with this solution:
Set a breakpoint
Setup a condition for it, which is a 'fake' one, but it gonna change the variable's value
run in debug mode
if I need the case 1. I enable the breakpoint, if I need the other one, I disable the breakpoint
Simplified example:
namespace AutoVariable
{
class Program
{
static void Main(string[] args)
{
try
{
new Program().Entrance();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
}
}
public void Entrance()
{
var entities = new List<Entity>
{
new Entity() { Name = "A" },
new Entity() { Name = "B" },
new Entity() { Name = "C" }
};
entities.ForEach(setRight);
entities.ForEach(Console.WriteLine);
}
protected void setRight(Entity entity)
{
//not implemented
bool hasRight = true;
entity.HasRight = hasRight;
}
}
class Entity
{
public bool HasRight { get; set; }
public string Name { get; set; }
public override string ToString()
{
return string.Format("{0} - {1}", Name, HasRight);
}
}
}
I set up a condition breakpoint to: entity.HasRight = hasRight;
with this condition: (hasRight = false)
so the hasRight will be false and the breakpoint never got a hit.
But it can be used in other cases also, for example in Jason Irwin's post, you can use something like: (userName = "Jason").Length < 1
So my question that is it a good solution or I am missing something from the 'native' debugger toolset?
Thanks in advance!
negra

You want to do an action using the debugger right? There's a thing called Trace Points.
It is explained here:
http://weblogs.asp.net/scottgu/archive/2010/08/18/debugging-tips-with-visual-studio-2010.aspx
and go down to "TracePoints – Custom Actions When Hitting a BreakPoint"
Is that what you need?

Related

Using IsValueCreated before accessing LazyLoadObject.Value

I'm working with some C# code that's using .Net 4 Lazy loads and I'm not super familiar with it. I'm trying to figure out if this particular code is useless or not.
Originally the property and code below where in the same class, but now I've moved the code to an external class that no longer has access to the private "lazyRecords" property. I'm wondering what the point of checking "lazyRecords.IsValueCreated" is since the lazyRecords.Value has not been invoked yet, wouldn't it always be false? Or is it checking to see if another thread somehow invoked the Value? Or is it doing this in case of a thread exception that resulted in not loading the object?
Property:
private Lazy<List<Record>> lazyRecords;
public List<Record> Records
{
get
{
return lazyRecords.Value;
}
set
{
lazyRecords = new Lazy<List<Record>>(() => value);
}
}
Code:
public Category LoadCategory(BaseClient client)
{
Category category = new Category();
category.Records = client.RecordClient.GetRecordsByCategoryID(category.ID);
if (lazyRecords.IsValueCreated)
{
category.WorldRecord = category.Records.FirstOrDefault();
}
else
{
category.WorldRecord = client.RecordClient.GetWorldRecord(category.ID);
}
}
The code is pretty useless, yes. To help you understand why, consider this very minimal version of Lazy (the real class has more options and logic to take care of multiple threads, but this is the rough idea):
public class Lazy<T>
{
private readonly Func<T> _creator;
private T _cachedValue;
public Lazy(Func<T> creator) => _creator = creator;
public bool IsValueCreated { get; private set; }
public T Value
{
get
{
if (!IsValueCreated)
{
_cachedValue = _creator();
IsValueCreated = true;
}
return _cachedValue;
}
}
}
The delegate passed to the constructor is called on demand, the first time the Value is requested. In the code you've posted there is no point to this because the delegate simply returns the value passed into the setter.
As to the LoadCategory method, the code you posted is hard to decipher. It directly accesses lazyRecords, implying it's a method of the same class. But then it accesses Records on a different object.

Get permitted triggers with guard conditions in Stateless (.NET state machine library)

Background:
I have same Trigger with mutually exclusive guard conditions defined with PermitIf that will cause transition to different states depending on those conditions.
Guards have Descriptions defined and they show up nicely in brackets in exported DOT graph, so it is easy to follow through.
machine
.Configure(Status.Registered)
.PermitIf(Activity.Submit, Status.Submitted, IsGoodRating, "Is good rating")
.PermitIf(Activity.Submit, Status.Denied, IsBadRating, "Is bad rating")
Now, I know there is machine.PermittedTriggers property that returns allowed Triggers in current state which is great, but here is the question.
Question :
Is there a way to get a list of PermittedTriggers with corresponding guard conditions for status Registered in this case?
I guess you could do something like this, but... I don't know how helpful it is:
class Program
{
enum Status { Registered, Submitted, Denied }
static void Main(string[] args)
{
int currentRating = 91;
RatingTrigger RatingTrigger = new RatingTrigger();
StateMachine<Status, Trigger> _sm = new StateMachine<Status, Trigger>(Status.Registered);
_sm.Configure(Status.Registered)
.PermitIf(RatingTrigger, Status.Submitted, () => RatingTrigger.Guard(currentRating), RatingTrigger.GuardDescription)
.PermitIf(RatingTrigger, Status.Denied, () => RatingTrigger.Guard(currentRating), RatingTrigger.GuardDescription);
var list = _sm.PermittedTriggers;
foreach (var item in list)
{
if (item.GetType().Equals(typeof(RatingTrigger)))
{
Console.WriteLine(((RatingTrigger)item).GuardDescription);
}
else
Console.WriteLine(item);
}
}
private static bool evaluate()
{
return true;
}
}
public abstract class Trigger
{
public abstract bool Guard(object something);
}
public class RatingTrigger : Trigger
{
public string GuardDescription = "This Guard evaluaties the current rating. Retuns true if good rating, false if bad rating";
public override bool Guard(object rating)
{
return (((int)rating) > 90);
}
}

Static code analysis on mandatory variable evaluation

I have this C# solution in which we use a certain pattern. A function returns true/false whether it succeed, and some value. If the function returned false, the value may not be used. Thus in the scope where such a function (with this particular pattern) is called, the IsSuccessful boolean must be evaluated.
We work with VS2013 + ReSharper 9. Is there a way to automatically check whether this pattern is obeyed in the code? If it is not possible with these tools, are there other tools? My last resort would be to write a unit test that performs this static code analysis.
Code example:
public ReturnValue<T> MyMethod()
{
try
{
....
return new ReturnValue<T>(someValue);
}
catch(Exception ex)
{
return new ReturnValue<T>(ex);
}
}
var returnValue = MyMethod();
if(!returnValue.IsSuccesful)
{
//Log error
return; //Can't go on, previous function failed
}
//Is successful continue code
public class ReturnValue<T>
{
public bool IsSuccessful { get; private set; }
public T Value { get; private set; }
public ReturnValue<T>(Exception ex)
{
IsSuccessful = false;
}
public ReturnValue<T>(T valueToReturn)
{
IsSuccessful = true;
Value = valueToReturn;
}
}
Edit:
I semi-solved my issue. Upon creation of the object the current stacktrace is saved (new StackTrace()). Upon destruction of the object (when the garbage collectors cleans it up), it is checked whether the IsSuccesful property of the object was ever evaluated during its lifespan. If not, a warning with the stacktrace is logged.

Using a returned error message to determine if error is present

I was recently talking with a buddy about return values taking only a single meaning. At my previous job, we worked with C++ and had typedef'ed wBOOL so that a 0 was wFALSE, and 1 was wTRUE. The architect said that we can also return 2, 3, 4... for more information, which I think is a horrible idea. If we expect wTRUE = 1 and wFALSE = 0 and wBOOL = {wTRUE, wFALSE}, returning anything else should be avoided... now, on to today's C#.
I recently reviewed a piece of code where there were a collection of functions that determined if there was an error and returned the string back to the user:
private bool IsTestReady(out string errorMessage)
{
bool isReady = true;
errorMessage = string.Empty;
if(FailureCondition1)
{
isReady = false;
errorMessage = FailureMessage1;
}
else if(FailureCondition2)
{
isReady = false;
errorMessage = FailureMessage2;
}
//... other conditions
return isReady;
}
Then, to use these functions...
private enum Tests
{ TestA, TestB, TestC }
private void UpdateUI()
{
string error = string.Empty;
bool isTestReady;
switch(this.runningTest) // which test are we running (TestA, TestB, or TestC)
{
case Tests.TestA:
isTestReady = IsTestAReady(error);
break;
case Tests.TestB:
isTestReady = IsTestBReady(error);
break;
case Tests.TestC:
isTestReady = IsTestCReady(error);
break;
}
runTestButton.Enabled = isTestReady;
runTestLabel.Text = error;
}
I thought to separate these out into two methods:
private string GetTestAErrorMessage()
{
//same as IsTestReady, but only returns the error string, no boolean stuffs
}
private bool IsTestAReady
{
get{ return string.IsNullOrEmpty(GetTestAErrorMessage()); }
}
Does this violate the principal of not having a return value mean more than one thing? For instance, in this case, if there error message IsNullOrEmpty, then there is no error. I think that this does not violate that principal; my co-worked does. To me, it's no different than this:
class Person
{
public int Height {get;}
public bool IsTall() { return Height > 10; }
}
Any thoughts or suggestions on a different approach to this issue? I think the out parameter is the worst of the solutions.
The return value and the error message are technically not bound together. You could have a developer come along at a later time and add a new failure condition to IsTestReady, and that failure condition may not set an error message. Or, perhaps there is a message, but it doesn't exactly represent a failure (like, perhaps a warning or something), so the error message parameter may get set, but the return value is true.
An exception doesn't really work in this case either, for the exact reason that StriplingWarrior wrote in his comment - exceptions should be used for non-normal operational states, and a non-ready test is a normal state.
One solution might be to remove the error message parameter and have the IsTestReady function return a class:
public class TestReadyResult {
public bool IsReady { get; set; }
public string Error { get; set; }
}
There is just one property to check - TestReadyResult.IsReady - for test state, and if necessary, the Error property can be used for non-ready states. There is no extra parameter to manage for the function call, either.
I'm not a big fan of having the null or empty return value indicate that nothing is wrong. A better comparison than the one you gave is:
class Person
{
public int Height {get;}
public bool IsBorn() { return Height > 0; }
}
In .NET, it is common practice to use the "bool return with out parameter" pattern you see in your original method (see the various TryParse methods, for example). However, if you prefer, another solution would be to create a TestReadyCheck class with both the boolean and the string as properties. I've done something similar with the following class, and been quite happy with it.
public class RequestFilterResult
{
public static readonly RequestFilterResult Allow = new RequestFilterResult(true, null);
public static RequestFilterResult Deny(string reason) { return new RequestFilterResult(false, reason); }
protected RequestFilterResult(bool allowRequest, string denialReason)
{
AllowRequest = allowRequest;
DenialReason = denialReason;
}
public bool AllowRequest { get; private set; }
public string DenialReason { get; private set; }
}
This allows for the following usage:
public RequestFilterResult Filter(...)
{
if (FailureCondition1) return RequestFilterResult.Deny(FailureMessage1);
if (FailureCondition2) return RequestFilterResult.Deny(FailureMessage2);
return RequestFilterResult.Allow();
}
It's concise, while enforcing that failure results provide a failure message, and success results don't.
On a side note, the structure of your switch statement feels like a code smell to me. You may want to consider ways to leverage polymorphism. Maybe make each test have its own class, with an IsTestReady method on it?
I would use exceptions to convey information about failure states, rather than relying on the caller to know how to use an error message field (even though it's private).

Using strings to select Object Properties

I'm having a bit of trouble with a C# program I'm writing and it'd be great if someone could help.
The background is this, not terribly important, but it's why I need to figure out how to do it:
I'm using a database's Web Services to retrieve information about an entry in the database. Each access to the database returns an Object with many many properties. Using the ID of the database entry, you tell it what information you want filled in about the object it returns by filling an array of which properties to be retrieved. Any property not in the array is left as it's default value (usually null)
The Problem:
I want the user to be able to select a property of an Object (not get the value, just select which property) as below:
projectFields[0] = Primavera.Ws.P6.Project.ProjectFieldType.(project_properties.Text);
Where project_properties.Text is a string of the name of the Property I want to set projectFields[0] to.
Can anyone help? Thanks in Advance :)
Edit: Thanks for the answer guys. While they do let me get the value out of Objects Dynamically, that isn't quite what I was looking for... I'm not looking to retrieve a value, I'm only looking to set which Property projectFields[0] is equal too. for example, suppose the user selects Id as the information they want returned about the project. To do that, I'd set:
projectFields[0]=Primavera.Ws.P6.Project.ProjectFieldType.Id;
then I'd make a call to the Database, and I'd get the project Object back, with Id having been filled out for the project while all other properties would be left to their defaults. Basically, if I were to do it the way these examples suggest, I'd have to retrieve every property in the Object first, then access the member the user is interested in which would be slow/inefficent if I can make the way I'm trying to do it work.
I know it's strange how the database is accessed, but I'm using web Services so I don't have the option to change anything about the calls to the database.
You can probably achieve what you want through Reflection (example), but I get a distinct feeling that there may be an issue with the design of your system.
C# is a statically typed language. The compiler wants to know you property you mean at compile time.
However, you can do this with reflection if you want to. Alternatively, if you know the type of the data in advance, you could use a switch statement. (Example of both approaches coming.)
using System;
using System.Reflection;
public class Demo
{
public string Foo { get; set; }
public string Bar { get; set; }
public string Baz { get; set; }
}
public class Test
{
static void Main()
{
Demo demo = new Demo {
Foo = "foo value",
Bar = "bar value",
Baz = "surprise!"
};
ShowProperty(demo, "Foo");
ShowProperty(demo, "Bar");
ShowProperty(demo, "Baz");
ShowDemoProperty(demo, "Foo");
ShowDemoProperty(demo, "Bar");
ShowDemoProperty(demo, "Baz");
}
// Here we don't know the type involved, so we have to use reflection
static void ShowProperty(object x, string propName)
{
PropertyInfo property = x.GetType().GetProperty(propName);
if (property == null)
{
Console.WriteLine("No such property: {0}", propName);
}
else
{
Console.WriteLine("{0}: {1}", propName,
property.GetValue(x, null));
}
}
// Here we *know* it's a Demo
static void ShowDemoProperty(Demo demo, string propName)
{
string value;
// Note that this is very refactoring-unfriendly. Generally icky!
switch (propName)
{
case "Foo": value = demo.Foo; break;
case "Bar": value = demo.Bar; break;
case "Baz": value = demo.Baz; break;
default:
Console.WriteLine("No such property: {0}", propName);
return;
}
Console.WriteLine("{0}: {1}", propName, value);
}
}
I agree with the other answers which suggest this probably shows a slightly scary design...
You can use reflection - See property info class.

Categories