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/
Related
Today I came across a problem: I was trying to check the errors of a software in order to provide the right behavior of the program when it incurs in the error.
I had to check if a user already exists in the database.
The problem is that the back-end doesn't provide an errorId so I have to check the errors by the text.
Errors are displayed as this:
The user Name already Exists!
The Switch statement is this:
switch (error.text)
{
case "User Test already exists":
Console.WriteLine("The user already Exists"); //this is a test behaviour.
break;
default:
Console.WriteLine("I couldn't behave in any way :<");
}
As you can imagine the names are all different (it's a unique field in the DB), so the word "Test" in the case statement should be the name of the user.
Can I dynamically change the string?
Seems like a Regex would do the trick. I've built this Regex based off the pattern:
The user Name already Exists!
where Name can be any value. The Regex is:
(the user .* already exists)
To use it you'll do something like this:
Regex.IsMatch(error.text, "(the user .* already exists)", RegexOptions.IgnoreCase)
Which would return a true or false based on the match. Now, this can't be done in the switch, but you could just run the value through a number of Regexes to determine which it matched. One thing you might consider is an extension method. Consider this one:
public static class RegexExtensions
{
private static readonly Regex UserNameAlreadyExists = new Regex("(the user .* already exists)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
public static bool IsUserNameAlreadyExists(this string inputValue)
{
return UserNameAlreadyExists.IsMatch(inputValue);
}
}
The usage for this would be really nice:
if (error.text.IsUserNameAlreadyExists())
{
// do something
}
The extension method is a really nice way of working through it. It's fully encapsulated and would keep the usage really clean. Furthermore, it's easier to define the Regex in one place and thus set it to Compiled making it faster.
Preferably change the back-end or have it changed (it definitely should return some sort of error code instead of an already localized message obviously meant to be shown to the user - that's clearly a front-end task).
To answer the question, no; consider using something like this instead (original phrasing, be aware that these string comparisons are case sensitive):
if(error.text.StartsWith("User ") && error.text.EndsWith(" already Exists"))
{
Console.WriteLine("The user already Exists"); //this is a test behaviour.
}
else
{
Console.WriteLine("I couldn't behave in any way :<");
}
I suppose this would be a fairly simple solution:
class Program
{
int errorIndex = 5; //Based on error expected text. Can add more criteria here.
private static bool testResponse = false;
static void Main(string[] args)
{
string text = "The user already exists";
getErrorMessage(text);
}
private static void getErrorMessage(string message)
{
var user = message.Substring(4, 4);
var exists = message.Substring(17, 6);
if (user == "user" && exists == "exists")
//Write the error message.
Console.WriteLine(message.ToString());
var errorMessage = message;
if (errorMessage != null)
{
testResponse = true;
}
Console.ReadLine();
}
}
This is if you know the exact location of the length and index of certain words of the error message. You could use that information to further narrow down the errors you expect. This is assuming that there is no errorId.
just to be sure: The back-end doesn't provide any errorID? If you use C# for the database connection (i.e. ADO.Net) you have possibilitys for efficent error handling.
Is it possible to just check if error.text is empty or not?
if(error.text=="")Console.WriteLine("The User already exists");
else Console.WriteLine("I couldn't behave in any way");
If you want to check if there are duplicates in the "user" column you could check the database directly via SQL.
i have one page i.e default.aspx and its in the main root and i have another folder which has a file with name of test.aspx . it means my test file is => Folder->test.aspx .
Now can you help me that how can i declare a string variable in my main file ( default.aspx ) and call or change its value in my test.aspx file .
I tryed this code but i didnt get result :-
Thank you
in default.cs
public static class globalvar
{
public static string test="null";
}
in folder->test.cs
class program
{
public static void main()
{
globalvar.test = "arash";
}
}
Why don´t you use Session state?
in default.cs
public void SetSessionValue (string value)
{
Session["test"] = value;
}
And on the other page:
in folder->test.cs
public string GetSessionValue ()
{
return Session["test"];
}
There are numerous ways in accomplishing the above said tasks, selecting an appropriate way for an appropriate situation is vested in the hands of programmer. Some of the most prominent techniques are:
QueryString.
PreviousPage.FindControl() and Request.Form[]
Session State
Cookies
Application Variables
Context.Items[]
See link with examples http://www.intstrings.com/ramivemula/asp-net/data-transfer-between-two-asp-net-pages/
session
You can use session instead using global .
In your main page you should :
Session["test"] = "arash";
and if you want to access its value just do this :
string test = Session["test"];
For more information take a look :
http://www.codeproject.com/Articles/32545/Exploring-Session-in-ASP-Net
Url
You can use urlto transfer your value between the pages
here is an example :
http://www.website.com/test/names.asp?test=arash
And to get the values:
<%
Response.Write(Request.QueryString("test"))
%>
The file names.asp would display the following:
arash
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#.
Hey guys I am new to Unity and finding it really hard to adapt to the concept of things. My problem is that I have a method that returns a string , and another method in a different class which calls on the method to get that string any time I try implement this the string is never accessed from the other class.
here is the method that returns the string
public string getString(){
string hi = "why hello";
return hi;
}
And here is the method which prints the above string when a button is clicked
void OnMouseUp(){
firstScript log = (firstScript)FindObjectOfType(typeof(firstScript));
string hello = log.getString()
print (hello);
}
You need to reference to the GameObject where you have the class on:
firstScript log =GameObject.find("NameOfGameObject").GetComponent<firstScript>();
Debug.Log(log.GetString());
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.