Mark values as being entered by user or calculated by application - c#

I'm currently planning a new application. The values used in this application can either be entered by the user or calculated by the application itself.
What I need to do is to mark the values in a way that I can clearly identify the source (user or app).
EDIT (additional information): The idea is not to identify that a user can input a value or not. The idea is to clearly have the possibility to flag values as being calculated or entered by the users. The value will not only be used in the view but also in calculations.
A class A would have a double v. This double can either be calculated or have been entered by a user.
class A
{
public double v; // <-- this would be the value I'd like to mark as program-defined or user defined
}
So, when I do this:
v = 1.0;
it would be marked as program-defined.
Has anyone a hint on how to achieve this in C#?
In C++ I would create a base class and derive from it. But in C# I would like to take a more general approach which doesn't force me to create a class per input type.
Any ideas on how to achieve this?
Thanks.

If you are looking for way to mark some properties or classes that they are used for user input or internally you can use attributes for this. https://learn.microsoft.com/en-us/dotnet/standard/attributes/writing-custom-attributes

Have a general class that implements a variable which identifies whether or not it is a value entered by the app or the user.
Possible variable types:
a string ('user', 'app' ...)
an enum, so if the enum is called Source it will be Source.User, if app Source.App.
an integer (as ID)
If you have a limited amount of types I'd personally go with an enum as it allows you to have suggested options. If you have many types I'd go with a string or an integer.

Related

I'm looking for a way to create new "primitive" types with additional constraints which are visible at coding time to users of the type

Suppose I have an entity in my universe of discourse called a Widget.
Suppose the Widget has an attribute called a WidgetCode. This attribute is defined (by the system of record) to be an alphanumeric value (ie, it's a string) of length exactly 8.
I might implement that in code as follows:
class Widget
{
private string _WidgetCode;
public string WidgetCode
{
get => _WidgetCode;
set
{
if (value.Length != 8) { throw new Exception("length must be 8"); }
_WidgetCode = value;
}
}
}
This is OK, but not ideal. The test in the setter will prevent the property from accepting an invalid value at runtime. But if some other developer wants to make use of my class, then the only way they can find out that the constraint exists is by looking at the implementation of the setter. Which would, of course, violate some pretty fundamental computer science 101 concepts.
In contrast we can look into the world of relational databases. In that world there is a fundamental type. "character", but I can create what is essentially a completely different type when I actually make use of it by specifying the length as part of the type. In the case of a WidgetCode, that would be a char(8). I can add other restrictions as well, in the form of check constraints.
When I do this, I have effectively created a new, more "refined" primitive type, which represents a WidgetCode, and does not represent any arbitrary string value of any arbitrary length.
More importantly, any SQL developer who needs to interact with my schema can see the constraints on my new type. They don't have to go and read separate documentation stored outside the schema. They don't have to live in ignorance of the constraint and hope that they never run afoul of some hidden constraint that they can't see while writing code. The constraint is declared in the schema, and the same thing which implements the constraint also documents it. It is impossible for the "documentation" to get out of synch with the implementation.
This idea doesn't have to be limited to strings. We might want to store a property called Percentage, and declare its domain as a real number between 0 and 1 with scale 3, such that it should not be possible to write the value 1.5 to this property. Once again in a relational schema, that could be a Percentage decimal(4,3) not null check (Percentage between 0 and 1).
Is there any mechanism in C# whereby that same kind of more refined type can be created, and where developers using that type can see the constraint at coding-time without having to go and read some external documentation, hoping that the documentation is up to date?
DataAnnotations get some of the way there, but they are clearly designed to inform users (specifically of GUIs) about a problem with an entered value at runtime. I am looking for a similar kind of tagging which provides the same information to developers making use of the type at coding time.
This question has been answered to my satisfaction through a combination of the comments by Eric Lippert and Matthew.
There is no particular built in language support, nor any particular annotation package, but one possibly functional approach may be to use T4 text templates.

How to differentiate between user specified null and default value in WCF data contract

I need to define a WCF API to enable user to update large object. While I can define few smaller methods and let the user update specific parts of the large object at a time. But for some reason I am not able to do that. The other way I tried is defined the data contract as collection of key-value (key is an enum and value is some string) and let the user add whatever he wants to update. This api very compact but it's not very intuitive and can be confusing for the user. Also since the value is of string type, so it's not very type safe.
So I now I have create one api, where the user can update the entire object.
for example:
public UpdateResult UpdateAPI(UpdateParam param){}
Now the UpdateParam class will several nullable fields.
Q: If there is a null value in one of the fields, how can differentiate at the server side,
the null value was specified by the user or it's default non-specified one? Is there something in the incoming soap message that can help differentiate?
Any help would be greatly appreciated.
Similar questions asked are
1. Data member default values, how to figure out whether something was really sent?
2.
no, as far as i know there is no way to tell the conditions apart if you only have a nullable field ...
however, you could provide an additional bool per property that could serve as a flag to indicate if the value was set by the user or is still on its default value
You can implement the setters of your properties to automatically set the corresponding bool when your properties are set

Requires a generic approach to validate control of ASP.Net form

I have a B2B we app having lots of forms taking input from registered users. So validation is mandatory there. I am using 3 tier architecture for my app. I am just ignoring server validation controls and client side validations. Instead i am thinking of Code Behind based validation, which i know will increase hit to my server, but too is most secure, if I am not wrong.
So what i am thinking is,
to enumerate all the controls of the page and check their validity. But this wayI can check only whether it is empty or not. Also I have to write it on each and every page.
Another approach, if i can set the maxlength , mandatory etc somewhere in my Model Layer where I have skeleton classes,and compare it while save button hit and tell what is missing and where.
Some common method that will take entire page controls as array of controls and check for validity...
Please guide me which one is possible or any other good solution.So that i can avoid code repetitions.
Model Layer means
public class Employee
{
public string Name {get;set;}
}
You can add a set of controls that inherit from ASP.NET controls, only with (a)additional type classification. For example: TextBox that accepts an attribute of DataType (enum) and values like: int, double, email etc. Another idea is for int type add a min/max values (i.e 15-32). And (b) a Validate function that returns true/false if the value matches the datatype.
Then, create a page base that inherits from Page and exposes a function called ValidateAllMyControls that iterates through all those special controls that are in use in the current form and calls the Validate function for each one. If one of them returns false - the form is not valid. :)

C# Changing a constant

I have inherited a small windows form based program written in C# that uses a 'constant' (See below), I need to modify this program so 'PROPERTY_NAME' can be "jobs" and "careers".
private const string PROPERTY_NAME = "jobs";
I'm guessing a constant isn't designed to change so should I need to change this. The line above is set once at the top of a class file and then PROPERTY_NAME is used throughout that file.
On the main form I would like to add two radio buttons 1 called 'jobs' and one called 'careers' and then change the PROPERTY_NAME in the class file based on which is selected. Would I need to pass the radio button status to the method in the class file? I recall reading that I can't simply read the radio button value from the class file.
Many thanks for your advice.
Jane
My best (and simplest) guess (I could elaborate into cleaner things but this is just for speed) without seeing any other part of the code would be to remove the const and add readonly so PROPERTY_NAME is just a plain old class member variable that cannot change outside of the constructor.
In the class's constructor, take in a string parameter, and have the code that creates an instance of this class pass in either "jobs" or "careers" (coming from the selected radio button probably) and set the PROPERTY_NAME variable.
EDIT:
Like Sasha says, another way would be using an enum but it depends what exactly is being done with PROPERTY_NAME as to whether this is appropriate for your application.
If the quantity you are representing changes ever throughout the history of the universe then do not make it a constant. Constants are things like the number of eggs in a dozen or the atomic weight of lead. Things like version numbers or the current price of gold change over time and therefore are not constant. Only make actually constant values into constant fields. The compiler will treat constant fields as constant for all time, which can introduce semantic errors if they change.
make an enum (my preferred way) and make it a readonly property. Set this property in the constructor. It isn't changeable after creation and should do what you need.
-sa
You cannot make constant having two values. It looks like that you need to make a field storing current property name and use it allover your form. And you will be able to init such field from the radio button.

How to avoid dependencies between Enum values in code and corresponding values in a database?

I have a number of user permissions that are tested throughout my ASP.NET application. These permission values are referenced in an Enum so that I can conveniently test permissions like so:
btnCreate.Enabled = PermissionManager.TestPermission(Permission.AllowCreate);
However, I also have these permissions stored in the database because I need hold more info about them than just their Id. But this creates a horrible dependency between the enum values and those in the database, an ill considered change to either and I have problems throughout my application. Is there a better way around this issue? Has anyone dealt with this before?
I do not know what the best solution is, I would like to hear that.
Our solution is to explicitly type the enum like
public enum MyEnum : int
{
None =0,
Value = 1,
AnotherValue =2
}
And save the integer value to the database. When for instance the Value 1 is removed, you will still be able to use the enumeration and AnotherValue still has the value 2 in the database.
Or maybe store the enumvalues as string in the DB. ToString();
Using enum values is acceptable to do as long as you never change the already assigned values. If you were using the standard role-based authorization in .NET you would still be relying on the exisistence of certain text strings in the corresponding role table in the database.
We use a small application that generates enum code (example: NorthwindEnums.cs) from the database. We make sure to run it and update affected libraries whenever the database changes.
We also try to keep our enums starting at 0 and sequential to avoid issues with web service references in C#.
A while back I built a little tool to do this for my company that would use attributes on the enum fields to allow "synchronisation" with the table in the database.
The tool could scan an assembly and generate appropriate INSERT/UPDATE SQL commands that would sync the database with the enum definition in the code.
I add an extended property on any table that I will need to access in code as an enum. I then use code generation software (codesmith, T4, whatever) to generate all my enum's for me by looking up any table with this property. Any table that is to be used for this abides by some basic rules (must have a Name column, etc.) so the code generator knows which column to use as the name for the enum's elements.
Once values are added to those tables we take care to virtually never change them to avoid breaking the build.

Categories