toTitleCase while preserving in-word upperCasing - c#

I'm using reflection to invoke methods and access properties in C#. The names of these properties and and methods have already been declared (in strings from a certain data source), but not in a 'method friendly' manner.
For example, a particular object has the property "HasAModifiedShortStyle"
At runtime I don't know this. I know I'm looking for a property described with "has a modified ShortStyle".
So the easy thing is to convert to TitleCase using
System.Globalization.CultureInfo.CurrentCulture.TextInfo)
and replace " " with "".
This works fine, but the TextInfo.ToTitleCase() changes "ShortStyle" to "Shortstyle". That lower case 's' causes me to not find the propertyName.
For reference, I'm accessing the property with
currentObjectValue.GetType().GetProperty(propertyName);
Is there an easy way to convert to TitleCase while preserving the in-word capitilization?

How about this approach?
currentObjectValue.GetType().GetProperties().FirstOrDefault(propInfo => propInfo.Name.Equals("Shortstyle", StringComparison.InvariantCultureIgnoreCase));

Just use this for every word in your description:
yourString[0].ToString().ToUpper() + yourString.Substring(1)

This will split the description string into individual words, capitalize the first letter, and then join them back into a single string:
string s = "has a modified ShortStyle";
propName = string.Join(string.Empty,
(from word in s.Split(' ')
select word.Substring(0, 1).ToUpper() + word.Substring(1)).ToArray());

Related

"An expression tree may not contain a call or invocation that uses optional arguments" in LINQ expression with split string entity?

var list1 = _context.Employees.Where(x=> x.EmployeeId.Equals(empId)
&& **x.deptIds.Split(",")**.ToList().Any(p => (p!=(deptId.ToString()))));
Where, x.deptIds is department ids stored as string separated by comma.
Getting erro "An expression tree may not contain a call or invocation that uses optional arguments". How to solve it?
Just specify an optional parameter. string.Split(",") becomes string.Split(",", System.StringSplitOptions.None)
providing optional parameters to string.Split resolved my error
As the comments pointed out, storing multiple values in a field is a very bad design choice, so noone should ever get to the point when they have to use String.Split in a Linq.
But to answer your question, you can use String.Contains, String.StarsWith and String.EndsWith, these can be translated to SQL. For example you can write:
var list1 = _context.Employees.Where(x=> x.EmployeeId.Equals(empId)
&& (x.deptIds.Contains("," + deptId.ToString() + ",")
|| x.deptIds.StartsWith(deptId.ToString() + ",")
|| x.deptIds.EndsWith("," + deptId.ToString()
));
This solution can change depending on where you have spaces around the commas in the database.

C# Dynamic Linq: Strings are assumed to be integers?

I'm using the System.Linq.Dynamic library found here, which is simply an upload of Microsoft's library to be accessible via NuGet: https://github.com/kahanu/System.Linq.Dynamic
In my code, I have this function that gets a list of objects from a database that match a certain property. It needed to be as flexible as possible, so the parameters consist of three strings;
One for the "order by" statement
One for the property to match's name
One for the expected property's value
Here's the line of code that's giving me trouble:
public IQueryable<T> GetByProperty(string propertyName, string propertyValue,
string orderStatement)
{
return _context.Set<T>()
.OrderBy(orderStatement)
.Where(propertyName + " = " + propertyValue);
}
Here are the possible scenarios;
propertyValue contains only numbers: the query works perfectly.
propertyValue starts with numbers but has letters in it: the following error appears: Operator '=' incompatible with operand types 'String' and 'Int32'
propertyValue is anything else: the following error appears: No property or field '[the first part of the "propertyValue string, up until it meets an empty space, a "-" or some other specific characters]' exists in type '[Class name of <T>]'
I've tried using single quotes to surround my string, but I then get the error: 'Character literal must contain exactly one character'
I've also desperately tried to add ".ToString()" at the end to try and trick something into working, but I found the error: Digit expected.
Is there another way to use the "Where" clause, in Linq and Dynamic Linq, that would support the flexibility I'm trying to have using this structure?
You need to know the type of the property and format the value accordingly. If it is a string, enclose it in double quotes. i.e. name = "John" but age = 20.
It does not depend whether the value looks like a number or not.
If the type of the property is a number type then the value must be a number as well and not be enclosed in quotes.
If the type of the property is a string then the value must be enclosed in double quotes, even if the value is a number (e.g. code = "3").

c# xml SelectSingleNode issue unable to use variable in node name

Have the following line of code
// Load screen containers
serverTest = document.SelectSingleNode("Server/". this.serverName . "/test").InnerText;
C# isn't liking the "." concatenation character, not sure what to do here.
serverTest is a property of my class btw
Oops was using PHP concatenation character, was using that language an hour ago.
Could one of the mods delete this one, sorry for taking up space.
You have to do something like this.
document.SelectSingleNode(#"Server/" + this.serverName + #"/test").InnerText;
For string concatenation, use the "+" plus operator or maybe string.Format if it contains a lot of variables
document.SelectSingleNode(#"Server/" + this.serverName + #"/app").InnerText;
For lots of variables (multiple parameters may be usable once you require attribute based retrieval of nodes):-
// for [Server/localhost/App/MyApp/Module/Admin/Action/Test"
var location = string.Format(#"Server/{0}/App/{1}/Module/{2}/Action/{3}", this.serverName, this.appName, this.moduleName, this.actionName);
document.SelectSingleNode(location).InnerText;
By separating the location from the retrieval function, you can easily debug it and log in case any value is improper. Also makes code readable IMHO.
However for a single value, using concatenation inline can be ok in most cases.

Can't clear the white spaces with the most common methods

This is the case - I need to work with the Text property of a ToolStripItem and I need to clear all white spaces from the string before that. However I tried three very common (in my opinion) scenarios and neither of them returned a string with no white spaces. Here is what I tried:
string tempBtnText = tempItem.Text;
tempBtnText is defined inside the method where I work with the Text property. I find it easier this way. Then I tried those:
tempBtnText.Replace(" ", String.Empty);
tempBtnText = Regex.Replace(tempItem.Text, #"^\s*$\n", string.Empty);
string tempBtnTexts = Regex.Replace(tempItem.Text, #"\s+", "");
All those returned the string in it's original form (with white spaces). The only way to remove the white spaces was by using this method :
public string RemoveWhitespace(string input)
{
return new string(input.ToCharArray()
.Where(c => !Char.IsWhiteSpace(c))
.ToArray());
}
Which I found in a similar post here in SO. but I really don't understand why all of the above approaches don't work. I'm starting to think that there is something to do with the fact that I'm using a ToolStripItem Text property but as shown at the very begining I declare my own string variable that takes the value of the Text property and.
I don't know. Can someone tell me, what is the reason of this behavior. Not that it's that big of a problem to use another method for clearing the white spaces but the not working options are much more compact and readable and I would like to use one of them if possible.
Strings are immutable, what means that any operation produces a new instance, so you need assign any method result back to input:
string input = "...";
intput = intput.Replace(x, y);
You are not assigning the result back to tempBtnText
tempBtnText.Replace(" ", String.Empty);
it should be:
tempBtnText = tempBtnText.Replace(" ", String.Empty);
strings are immutable, string.Replace returns a new string, it doesn't modify the existing one.
abatischev is right so writing
tempBtnText = tempBtnText.Replace(" ", String.Empty);
should solve your problems. If you only want to remove Whitespaces in front and back then rather use:
tempBtnText = tempBtnText.Trim();

C# string masking/formatting/filtering with or without regex

Hopefully this isn't too complicated, I just can't seem to find the answer I need.
I have a string with variables in, such as: this is a %variable% string
The format of the variables within the string is arbitrary, although in this example we're using the filter %{0}%
I am wanting to match variable names to properties and ideally I don't want to loop through GetProperties, formatting and testing each name. What I'd like to do is obtain "variable" as a string and test that.
I already use RegEx to get a list of the variables in a string, using the given filter:
string regExSyntax = string.Format(syntax, #"(?<word>\w+)");
but this returns them WITH the '%' (e.g. '%variable%') and as I said, that filter is arbitrary so I can't just do a string.Replace.
This feels like it should be straight-forward....
Thanks!
"(?<word>\w+)"
Is just capturing anything alphnumeric and putting it into a named capturing group called "Word"
You might be interested in learning about lookbehind and lookahead. For example:
"(?<=%)(?<word>\w+)(?=%)"
You can make it a bit more generic with putting your filter in a seperate variable:
string Boundie = "%";
string Expression = #"(?<=" + Boundie + #")(?<word>\w+)(?=" + Boundie + #")";
I hope this is anywhere near what you are looking for.
Given that your regex syntax is: string regExSyntax = string.Format(syntax, #"(?<word>\w+)");, I assume you're then going to create a Regex and use it to match against some string:
Regex reExtractVars = new Regex(regExSyntax);
Match m = reExtractVars.Match(inputString);
while (m.Success)
{
// get the matched variable
string wholeVar = m.Value; // returns "%variable%"
// get just the "word"
string wordOnly = m.Groups["word"].Value; // returns "variable"
m = m.NextMatch();
}
Or have I completely misunderstood the problem?
Acron,
If you're going to roll-your own script parser... apart from being "a bit mad", unless that's the point of the exercise (is it?), then I strongly suggest that you KISS it... Keep It Simple Stoopid.
So what denotes a VARIABLE in your scripting syntax? Is it the percent signs? And they're fixed, yes? So %name% is a variable, but #comment# is NOT a variable... correct? The phrase "that filter is arbitrary" has me worried. What's a "filter"?
If this isn't homework then just use an existing scripting engine, with existing, well defined, well known syntax. Something like Jint, for example.
Cheers. Keith.

Categories

Resources