I'm sure this must be simple, but I can't figure out how to word it correctly in Google...
I have a config which has a field:
TimeToPoll="1d"
Now I want to do something like:
TimeSpan.Parse(TimeToPoll);
Returning a timespan of one day.
In C#
EDIT:
I'm looking for a method which allows parse of "1d" as well as "1s" or "1y" etc. Is this possible?
Meaning:
"1d" parses to {1.00:00:00}
"1h" parses to {0.01:00:00}
"1m" parses to {0.00:01:00}
"1s" parses to {0.00:00:01}
This is my resolution:
public static TimeSpan ConvertToTimeSpan(this string timeSpan)
{
var l = timeSpan.Length - 1;
var value = timeSpan.Substring(0, l);
var type = timeSpan.Substring(l, 1);
switch (type)
{
case "d": return TimeSpan.FromDays(double.Parse(value));
case "h": return TimeSpan.FromHours(double.Parse(value));
case "m": return TimeSpan.FromMinutes(double.Parse(value));
case "s": return TimeSpan.FromSeconds(double.Parse(value));
case "f": return TimeSpan.FromMilliseconds(double.Parse(value));
case "z": return TimeSpan.FromTicks(long.Parse(value));
default: return TimeSpan.FromDays(double.Parse(value));
}
}
The d is not needed and is the reason your parse fails.
var oneDay = TimeSpan.Parse("1");
Update:
For what you are looking to do, there is no built in support. You would need to write your own parser.
You should store your values in your config file in one of the formats that TimeSpan.Parse can work with. There are several samples on that page.
EDIT: The examples are in the code toward the bottom of the page.
Related
I have used below code in a project and someone ask me to use ToLower() or ToUpper() and I think it is unnecessary.
public somefun(Classabc clsabc, string emptype, string id)
{
switch(emptype)
{
case :"AnyInput":
{
//do
}
break;
case :"StringInput":
{
//do
}
break;
}
}
if(emptype=="AnyInput")
{
///
}
Is the above perfect or we need to use ToLower() or ToUpper() with empType in if()? Is there any issue or programming rule violation with my code? According to me in case (switch) we are using email type as constant for case matching and if emptype value can be used in case matching then there is no need to add extra functions to convert to there case before string matching.
Depends on what you guys are looking for.
If the comparison is case sensitive, you can keep the switch-case comparison like you did in the example you provided.
In case the comparison is insensitive, you can pattern matching (C# 7 and above) and write something like this:
switch (true)
{
case bool b when emptype.Equals("AnyInput", StringComparison.InvariantCultureIgnoreCase):
// do
break;
case bool b when emptype.Equals("StringInput", StringComparison.InvariantCultureIgnoreCase):
// do
break;
default:
break;
}
This question already has answers here:
Convert a string to an enum in C#
(29 answers)
Closed 3 years ago.
I have a problem about some simple code in console. Precisely I created a public enum called Year which contains 4 seasons (obvious). I want the program to ask at the beginning what is the season of the year and then generate an answer to each option. The problem is I don't know how to convert my string input to each option of this enum. Maybe it will be more clear if i show you the code (it's short).
Console.WriteLine("What time of year is it?");
var input = Console.ReadLine();
//earlier it was just
//time = Year.Winter;
switch (time)
{
case Year.Autumn:
Console.WriteLine("You're gonna have to grab the leaves");
break;
case Year.Summer:
Console.WriteLine("Let's go to the beach");
break;
case Year.Winter:
Console.WriteLine("Better to warm up at home");
break;
case Year.Spring:
Console.WriteLine("Best time of the year!");
break;
default:
Console.WriteLine("I don't know this time of year");
break;
}
I want to make something like this but dunno what to put inside this switch statement because I can't just put there my string 'input'. Is it possible in the way I am thinking of it?
You can parse a try to parse a string into an Enum by using one of the Enum class.
In particular, you can use the typed method TryParse in this eay
var ignoreCase = true; // decide this
if (Enum.TryParse<MyEnum>("my string", ignoreCase, out var r))
// use r
else
Console.WriteLine("Please enter the correct value.");
You can use string contain() function before the switch statment like below i haven't tested if it works like this (nested) if not you have to use if and else if condition
time = input.Trim().Contains("winter") ? Year.Winter: (input.Trim().Contains("summer") ?Year.Summer :(input.Trim().Contains("autumn") ?Year.Autumn:i(nput.Trim().Contains("autumn") ?Year.Autumn: null)));
The other thing you can do is give user option like 1 Year.Autumn,2 Year.Summer,3 Year.Winter,4 Year.Spring and get a number on which you can use the switch statment
I know that string.Format and ToString() can apply formatting to a string,
In my case i have a string with the value (typically it will have a string representation of a data but can have string representations of other base datatypes) and i have another string that represents the desired format. These values are coming from a database, what i need is to apply one to the other
I'm not even sure this is possible at all, so any pointers are welcome. I haven't been able to apply any version of ToString or Format. because these require that you declare on the spot what format you want and mine are dynamic
Is there some formatting method like the tryParse (in the sense that it would try any possible formatting for the data it is given?
EDIT: some examples as requested:
stringInput = "Jan 31 2012"; //string representation of a date
inputFormat="dd/MM/yyyy, HH mm"
outputString = "31/Jan/2015, 00:00";
stringInput = "100"; //string representation of a number
inputFormat="D6"
outputString = "000100";
string.Format(string, string) takes 2 string arguments so you can take them from db and apply them directly:
string formatToApply = "{0} and some text and then the {1}";
string firstText = "Text";
string secondText = "finsh.";
// suppose that those strings are from db, not declared locally
var finalString = string.Format(formatToApply, firstText, secondText);
// finalString = "Text and some text and then the finish."
However, there is a great risk to have wrong number of specifiers or wrong number of arguments. If you have a call like this, it will throw an exception:
var finalString = string.Format(formatToApply, firstText);
//An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll;
//Additional information: Index (zero based) must be greater than or
//equal to zero and less than the size of the argument list.
So wrap your call into a try/catch/ (maybe) finally to handle this situation accordingly to your needs.
Later Edit after desired examples were posted:
First example: you might want to take advantage of DateTime class from C# which knows to format its output values. So you need first to convert stringInput into a DateTime:
var inputDateTime = DateTime.Parse(stringInput);
var outputString = inputDateTime.ToString(inputFormat);
Second example: again, you might want to take advantage of Double class and conversion occurs again:
var inputDouble = Double.Parse(stringInput);
var outputString = inputDouble.ToString(inputFormat);
In summary of those two examples, you need to know the type of input string, type which you specified in your comments ("string representation of a date"). Knowing this you can take advantage of each specific class and its ability to format output strings. Otherwise it would be difficult to design yourself some kind of general formatter. A simple method might look like this:
public string GetFormattedString(string inputString, string inputFormat, string type)
{
switch (type)
{
case "double":
var inputDouble = Double.Parse(inputString);
return inputDouble.ToString(inputFormat);
break;
case "datetime":
var inputDateTime = DateTime.Parse(inputString);
return inputDateTime.ToString(inputFormat);
break;
case "...": // other types which you need to support
default: throw new ArgumentException("Type not supported: " + type);
}
}
This switch is only an idea of how the logic may occur but you will need to handle errors for Parse methods and for ToString methods and if you have many types to support is better to take advantage of some design patterns like Factory.
Trying to use System.Double.Parse(string) method for strings such as "-1.#IND" and "INF" representing special values results in a FormatException.
Is there any built-in .NET framework support to parse these?
No, the only non-numeric values double.Parse recognizes are the string values returned by double.Nan.ToString(), double.PositiveInfinity.ToString(), and double.NegativeInfinity.ToString() (dependent on Culture).
In your case I would just use a switch:
double dblValue;
switch strValue
{
case "-1.#IND":
dblValue = double.Nan;
break;
case "INF":
dblValue = double.Infinity;
break;
//... other casess
default:
dblValue = double.Parse(strValue);
break;
}
NaN and other values are parsed in the specified culture (or neutral, if no culture is specified). You can play with those here if you want.
If you have to parse something more special, then just
public double MyParse(string text)
{
if(text == "blablabla")
return double.NaN;
if(text.Contains("blablabla")) ...
if(text.StartsWith(...
return double.Parse(text);
}
I am trying to display an error to the user of a web page using a javascript alert popup, I currently have the following code to clean the error string:
errorMessage.Replace("'", "\'")
But this is not sufficient as some illegal characters are not being removed, is there a static method somewhere in the framework that will format my string for clean insertion into html?
Update: my initial question was slightly ambiguous.
the string needs to be valid as in alert('this is some 'illegal text' that will not popup');
I will try Server.HtmlEncode, hopefully it will do the trick.
If you have a look at the AntiXSS module in the Web Protection Library, you'll find that it has a JavaScriptEncode(string) method for just this sort of thing.
There's a simple solution...use the DataContractJsonSerializer and "serialize" the string value. By serializing the string to JSON, you're by definition ensuring that it'll work nicely inside an alert statement.
You want to avoid XSS vulnerabilities, which is good. The following cheat sheet should assist you (and also contains a reference to code for escaping the string):
http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
To escape a string for clean insertion into html you can use HttpUtility.HtmlEncode method. I'm not sure it this helps you with the javascript.
http://msdn.microsoft.com/en-us/library/73z22y6h.aspx
If you are using ASP.NET 4 you can use the new <%: %> syntax to HtmlEncode the generated string AND replace the default encoder with AntiXSS, or any other library you may prefer. Phil Haack explains how to do this in Using AntiXss as the default encoder for ASP.NET
This way you can write an alert like this:
alert('<%: this.ErrorMessage %>');
In previous versions you can use what others have suggested, either HtmlEncode or AntiXss like this:
alert('<%= HttpUtility.HtmlEncode(this.ErrorMessage) %>');
or
alert('<%= AntiXss.HtmlEncode(this.ErrorMessage) %>');
Thanks for the help but none of the answers presented gave me the complete solution.
Joe's answer was closest but it did not account for \r\n newline. I could not find a way to translate c# newline into a javascript equivalient.
public static string EscapeAlertMessage(string value)
{
value = value.Replace("\\", "\\\\");
value = value.Replace("'", "\\'");
value = value.Replace("\"", "\\\"");
value = value.Replace(Environment.NewLine, "--");
return value;
}
HttpUtility.HtmlEncode will not encode a single quote (') and is not suitable for encoding a string to be used as an alert message. Personally I do it like this:
public static string EscapeAlertMessage(string value)
{
value = value.Replace("\\", "\\\\");
value = value.Replace("'", "\\'");
value = value.Replace("\"", "\\\"");
return value;
}
If your message contains multiple lines, you can replace them by "\n" - e.g. if the lines are separated by Environment.NewLine:
value = value.Replace(Environment.NewLine, "\\n");
Or if you don't know what the separators are (\r\n, \n or \r only) you could use:
value = value.Replace("\r", "\\r");
value = value.Replace("\n", "\\n");
I use the following function in my projects. It escpaes all possible characters for Javascript:
/// <summary>
/// Encodes a string to be represented as a string literal. The format
/// is essentially a JSON string.
///
/// Example Output: Hello \"Rick\"!\r\nRock on
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string EncodeJsString(string s)
{
StringBuilder sb = new StringBuilder();
foreach (char c in s)
{
switch (c)
{
case '\"':
sb.Append("\\\"");
break;
case '\\':
sb.Append("\\\\");
break;
case '\b':
sb.Append("\\b");
break;
case '\f':
sb.Append("\\f");
break;
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '\t':
sb.Append("\\t");
break;
case '\'':
sb.Append("\\'");
break;
default:
int i = (int)c;
if (i < 32 || i > 127)
{
sb.AppendFormat("\\u{0:X04}", i);
}
else
{
sb.Append(c);
}
break;
}
}
return sb.ToString();
}