Best way of mapping external error codes to internal codes - c#

What I mean is that if we get an error code 300 from some service, and need to map it to our own internal error code (say 450), then whats the best way of doing this.
Current system uses constants to keep track of internal errors:
public const string ERROR_SOME = "450"; public const string ERROR_ANOTHER = "460";...
So I was thinking of just having another set of constants for external errors and then have function for mapping the two:
public const string EXT_ERROR_SOME = "300";
public const string EXT_ERROR_ANOTHER = "800";
...
public string MapError(string externalError)
{
if(externalError == EXT_ERROR_SOME) // can be a switch statement
return ERROR_SOME;
else if (externalError == EXT_ERROR_ANOTHER)
return ERROR_ANOTHER;
...
}
The question is: "Is there a better way"?

You can use a Dictionary<string, string>:
private readonly var errorMap = new Dictionary<string, string>() {
{EXT_ERROR_SOME, ERROR_SOME},
⋮
};
public string MapError(string externalError)
{
return errorMap[externalError];
}

Not a C# question but merely an architectural issue. I wouldn't put that in any code in any language but completely externalize the entire map (as long as its not only this one pair above). And make it somewhat "complete" like
"external code : internal code : msg ID"
next
"language : msg ID : user friendly hint .... "
etc. There are several libs for all kind of purposes out there doing this, even in C#.

Related

What is syntax for creating a class in C# that would be equal to a Module in VB.net

I do almost all of my programming in VB.net (all flavors). I am now been assigned a task to make a new routine in an existing C# application. What I want to be able to do is pass a string variable to a class where I can figure out device type of a symbol handheld and figure out where an executable resides on device.
I am trying to keep the class to contain changes we make going forward in one place.
so a brief description is on a screen there will be a button. on that button click I want pass the text of the button to a (what would be a module in VB) a class and depending on text being passed and device type call a separate executable that lives on the device.
Everything I have tried so far has thrown errors.
On my button click i have
String Reponse = clsCallAction("Activity");
but that gets a message that clsCallAction is a type but is used like a variable.
here is the smaple of clsCallaction
internal static partial class clsCallAction
{
public static object GetPath(object lAppName)
{
string resp = "";
if (lAppName.Equals("Activity"))
{
resp = #"\application\activity.exe";
}
return resp;
}
}
If I put new in front of the clsCallAction("Activity") on button click I get a
cannot create instance of the static class 'clsCalACtion'
appreciate any pointers. very new at C#
It would look something like this:
public static class CallAction
{
public static object GetPath(object lAppName)
{
string resp = "";
if (lAppName.Equals("Activity"))
{
resp = #"\application\activity.exe";
}
return resp;
}
}
And would be used like this:
String Reponse = CallAction.GetPath("Activity");
Don't prefix classes with cls
Avoid using object if possible - it just makes everything harder work than it needs to be.. Kinda like calling everything "thing" - ("Put the thing in the thing and open the thing" is harder to understand than "put the key in the lock and open the door")

how do i get a class name variable

Im trying to get the class variable name
static void Main()
{
TaskAction m_first = new TaskAction();
m_first.Increment();
m_first.Increment();
TaskAction m_Second = new TaskAction();
m_Second.Increment();
}
public class TaskAction
{
private int m_Current;
public TaskAction()
{
m_Current = 0;
}
public void Increment()
{
m_Current++;
write(" TaskAction " + vairableName + " " + m_Current);
}
}
i want to it to write out:
TaskAction m_first 1
TaskAction m_first 2
TaskAction m_second 1
Retrieving metadata about your program like that is both complex and unnecessary, just add the name by passing it to the constructor.
static void Main()
{
TaskAction m_first = new TaskAction("m_first");
m_first.Increment();
m_first.Increment();
TaskAction m_Second = new TaskAction("m_Second");
m_Second.Increment();
}
public class TaskAction
{
private int m_Current;
private string m_taskName;
public TaskAction(string taskName)
{
m_taskName = taskName;
m_Current = 0;
}
public void Increment()
{
m_Current++;
write(" TaskAction " + m_taskName + " " + m_Current);
}
}
Short Answer: You can't.
Long Answer:
Technically, it's possible to determine a variable name by inspecting the IL (the intermidate language created by the C# compiler), but this operation is hard and error-prone. Also, you ignore some important questions:
First of all, as already asked here: Why? how such thing will enhance your program?
Each instance of the class can have multiple variables pointing to it (see my answer about types in .NET here). Which of them you want to get? For example, consider the following program:
var v1 = new TaskAction();
var c2 = new TaskAction();
c1.Increment(); // 1 c1
c2 = c1;
c2.Increment(); // 2 c1? 2 c2? 2 c1 c2?
By doing so, you break the encapsulation in a difficult way - any reflection breaks the encapsulation, and really don't use it unless you really need it - but so much? Reflection breaks the hidden information about the private interface, you question breaks the internal interface!
Since you didn't give enough information, I can't know why you tought you need that. But here is some solutions:
If you want, for example, logging with categories - simply pass the category to the constructor, as sugegsted above.
If you want to know which type the variable is - using its name is very very very bad approach, even though you have conventions - use polymorphism instead (best), or, at least, check the type with is/as, for example:
if (this is Drived)
{
((Drived)this).SomeDrivedMethod();
}
Note that it breaks the OOP principles: a class shouldn't know about its drived classes.
Hope this helped you. Have a nice day!
Edit:
For your purpose, you can do one of the following:
Best - debug your code, see the call stack etc.
Worse - print the caller method name, instead of the object name. It's can be done using System.Runtime.CompilerServices.CallerMemberNameAttribute:
void Increment([System.Runtime.CompilerServices.CallerMemberName] string caller = null)
{
// Default value to `caller` is neccessary
// ...
Console.WriteLine("Caller: {0}", caller);
}
Note: the compiler fills the caller parameter, not in runtime.
Get object.GetHashCode() if you want to uniquely identify class object or provide name to class by using custom constructor.

What is value shadowing?

hi everyone
private const string abc="__abc";
private const string abcd="__abcd";
pageLoad()
{
this.xyz();
}
xyz()
{
if postback()
{
}
else
{
string k1=this.Request[abc];//some 'value shadowing error is shown here by my tool . This makes it
unsecure and vulnerable to user edits .
string k2=this.Request[abcd];//
}
}
I want to resolve this issue but I am unsure about where to begin?
- List item
As a short answer:
In the context of ASP.NET it means a user can pass in what is supposed to be let's say a form field as a query string parameter.
To fix instead of going
Request["xyz"]
you go
Request.Form["xyz"]
You can read more here https://www.jardinesoftware.net/2011/06/07/asp-net-value-shadowing/

Implementing a CVAR system

I would like to implement what I know as a CVAR System, I'm not entirely sure on what the official name of it is (if any).
It's essentially a system used in some programs and video games, where a user can pull down a console and input a command, such as "variable 500" to set that variable to 500. Instances of this can be found in any Half-Life game, Doom and Quake games, and many more. The general idea seems to be to hide the underlying architecture, but still allow protected access, for instance, one may be able to view the value for, say, gravity, but not change it. Some of these values may also be functions, for instance, a user may be able to input "create " to create an enemy type at their location, or some other location specified.
Looking through the Half Life 2 SDK, and from what I remember on the GoldSrc SDK, it seems like they at least implemented "flagging" of sorts, where certain commands would only work under certain conditions, such as if another value was set, or if the user has some permission level.
My initial thought was to create a Dictionary, or an object similar to do that, and use that to bind string values to function delegates, as well as keep a "protection" level of sorts, to limit usage of certain commands. However, this seems rather cumbersome, as I believe I would have to go through and add in a new entry manually for each value or function I wanted to implement. I also don't know if this would give me the control level I'm looking for.
I believe ideally what I would like would be a CVAR System class, as well as a Register function that can take it say, a variable/function delegate, a string to access it, and whatever protection level I need. This way I can add what I need as I see them, so everything is still in it's related classes and files.
I'm really just looking for some ideas here, so my questions are:
Has anyone ever done something like this before, and if so, how?
Would my implementation work? (Theoretically, if not, can you think of a better way?)
If someone is more knowledgeable with how one of the previously mentioned titles does it, can you elaborate on that a bit? It seems to be hard to find documentation on them.
I'm not really looking for specific code, just more of structuring design. And it doesn't have to be "commercial" or work just like another, I just need something to get me going.
Were you thinking about something like this?
class CVAR
{
[ProtectionLevel(CVARFlags.InGameOnly | CVARFlags.Admin)]
private float gravity = 0.1f;
[ProtectionLevel(CVARFlags.InGameOnly | CVARFlags.Admin)]
private float friction = 0.1f;
[ProtectionLevel(CVARFlags.ReadOnly)]
private string serverVersion = "x.x.x";
public void SetCVARValue(string commandLine) {
string cvarName = GetCvarName(commandLine); // parse the cmd line and get the cvar name from there
object cvarValue = GetCvarValue(commandLine); // parse the value from the string
FieldInfo field = typeof(CVAR).GetField(cvarName);
object[] attributes = field.GetCustomAttributes(typeof(ProtectionLevel), false);
if(attributes.Length > 0) {
ProtectionLevelAttribute attr = (ProtectionLevelAttribute)attributes[0];
if(attr.CheckConditions(World.Instance)) {
field.SetValue(this, cvarValue);
} else {
// error report
}
}
}
}
You could write a parser that looks for commands like
/object_property value
/object_method arg1 arg2
A dictionary, like you suggested, could map those strings to properties and functions. The creation of the dictionary could be done dynamically using reflection by looping through eligible objects, taking their public methods and accessors, and generating a string for them.
Then the dictionary could be mapped in a class for convenience and error checking.
For the methods, the dictionary values could be delegates that take 0..n arguments, for the properties/fields, you will need to be able to some data binding between your actual fields and the dictionary value. UNLESS, your objects themselves refer to the dictionaries for their values, in which case the values only live in place.
To do so, you could simply register your properties using reflection in the object constructor, then call the dictionary in your properties.
[Flags]
public enum CVarAccessibilities
{
Settable,
Gettable
}
public class CVar<T>
{
public CVarAccessibilities Accessibility { get; set; }
T val;
public T Value {
get { return val; }
set
{
if (!Accessibility.HasFlag(CVarAccessibilities.Settable))
return; // just don't set it, maybe print some warning
val = value;
}
}
}
public static class CVarRegistry
{
static Dictionary<string, Object> CVars;
static CVarRegistry { /* use reflections to initialize the dictionary */ }
public static T GetValue<T>(Type owner, string paramName)
{
CVar cvar;
if (!CVars.TryGetValue(owner.Name + "_" + paramName, out cvar)
throw new MyCustomException();
return (T)cvar.Value;
}
public static void SetValue<T>(Type owner, string paramName, T value)
{
CVar cvar;
if (!CVars.TryGetValue(owner.Name + "_" + paramName, out cvar)
throw new MyCustomException();
cvar.Value = value;
}
}
public class MyObject
{
public static int MyRegisteredValue
{
get { return Global.CVarRegistry.GetValue<int>(typeof(MyObject), "MyRegisteredValue"); }
set { Global.CVarRegistry.SetValue(typeof(MyObject), "MyRegisteredValue"); }
}
}
Hope that helps!
This is more commonly known as 'tweak' variables.
Good discussion here: https://gamedev.stackexchange.com/questions/3631/tweaking-and-settings-runtime-variable-modification-and-persistence

C# Delegates & guid.newguid()

I just started using C# this afternoon, so be a little gentle.
Currently I am working on a type of "template engine" where one of the callbacks needs to generate a globally unique ID. I am using delegates to manage the callbacks.
Currently the code looks like this (though I have also tried an anonymous function & returning NewGuid directly w/o a variable):
static string UID(List<string> p)
{
string s = Guid.NewGuid().ToString();
return s;
}
Which, when called directly, works fine. However if I try to call it via the delegate (added to a StringDictionary via addCallback("generate UID", new CallbackWrapper(UID))), the program will generate the same GUID regardless of how many times I duplicate it; even though calling the method directly both before & after the event occurs results in a unique ID as expected. I'v
No doubt it's just something simple I've missed, inevitably stemming from me being relatively inexperienced at C#.
Any help would be appreciated.
Thanks.
Well, I've now tried Dictionary with the same result.
CallbackWrapper is just the delegate, it's defined like this:
delegate string CallbackWrapper(List<string> parameters);
The remainder of the work is done in another class, which looks like this:
class TemplateParser
{
private Dictionary<string, CallbackWrapper> callbackMap;
public TemplateParser(string directivePrefix, string directiveSuffix)
{
...
callbackMap = new Dictionary<string,CallbackWrapper>();
}
public TemplateParser() : this("<!-- {", "} -->") {}
{
callbackMap.Add(name, callback);
}
public string parse(string filename)
{
...
string replacement =
callbackMap[directiveName](new List<string>(parameters.Split(new string[] { ";", " " }, StringSplitOptions.RemoveEmptyEntries));
...
}
}
I've stripped out the majority of the string handling code to save some space.
The issue is in your calling code, not in the code itself, nor in the delegate.
Using delegates here definitely works if called correctly.
Furthermore, your code can be slightly simplified:
static string UID(List<string> p)
{
return Guid.NewGuid().ToString();
}
(The variable is utterly redundant.)
use delegate.invoke
The difference between direct function call and delegate.invoke is here
http://social.msdn.microsoft.com/Forums/en/csharplanguage/thread/f629c34d-6523-433a-90b3-bb5d445c5587
StringDictionary will automatically cast your CallbackWrapper to a string, meaning it will only run once and store the output of CallbackWrapper.ToString(). This is probably not what you want.
Try using Dictionary<string, CallbackWrapper> instead.

Categories