Remove backslash from string c# - c#

I am trying to add a value to a queryparameters for reporting services programmatically.
List<QueryParameter> lst = new List<QueryParameter>();
QueryParameter qp = new QueryParameter();
qp.Name = "#UserID";
qp.Value = "[#UserID]";
lst.Add(qp);
The values are getting inserted, but with \ character and is it because of #. My QueryParameter value should be like [#UserID] and instead it is displayed as \[#UserID\].
How can I remove the \ from the value and the \ doesn't show when I debug.
Really appreciate any suggestions.
Update1:

If I'm understanding your problem right:
testString = testString.Replace(#"\","");

Related

replace \\ to \ when using # symbol

Issue with replacing text...username is 'JoelFarrell'
userName = #"WILD\" + userName; // returns "WILD\\JoelFarrell"
I only want "WILD\JoelFarrell" so ive tried to replace it
userName = userName.Replace("\\", #"\");//this does not work
userIdInDNNUsersTable = DbContext.Users.Where(x => x.Username == userName).Count();//returns 0 results because it is searching for 'WILD\\JoelFarrell' where as if it was searching for 'WILD\JoelFarrell' I would get what I am looking for
Any one have any ideas? thanks for any replies
If i test it in quick watch and change userName = "WILDFIRE\JoelFarrel" it says unrecognized rewscapce sequece. but if I search SQL for the record in the db `
select * FROM [Dot].[dbo].[Users]
where username LIKE '%WILDFIRE\JoelFarrell%'`
returns the result I am looking. So how do I get this result in code?
Actually
userName = #"WILD\" + userName; // returns "WILD\\JoelFarrell"
Returns
WILD\JoelFarrell
Its just that the debugger is displaying it as \\ (very unhelpfully IMHO)
When you look at userName in the debugger, you're seeing the escaped version. Hit the magnifying glass beside the watch or tooltip. That will give you the non-escaped version.

Remove characters from C# string not belonging to a specicif code page

In C# I have a string that goes on to be inserted into a db table using codepage 37 US. So for instance, the '€' will cause the insert operation to fail.
What is a good way to clean my string of characters not represented in code page 37 and possible replace those charaters with some default character?
Something like this?
var euroString = "abc?€./*";
var encoding37 = System.Text.Encoding.GetEncoding(
37,
new EncoderReplacementFallback("_"), //replacement char
new DecoderExceptionFallback());
var byteArrayWithFallbackChars = encoding37.GetBytes(euroString);
var utfStringFromBytesWithFallback = new string(encoding37.GetChars(byteArrayWithFallbackChars));
//returns "abc?_./*"
P.S.: you can just use GetEncoding(37), but in this case replacement char is ? which I think is not really OK for DB :)
Here is a regex to restrict input to a range of allowed characters:
https://dotnetfiddle.net/WIrSSO
const string Allowed = #"1-9\."; //Add allowed chars here
string cleanStr = Regex.Replace("£1.11", "[^" + Allowed + "]", "");

command line using string.Format() to handle escape characters

Thank for reading my thread.
Here is the command line I like to call within my C# code:
C:\>"D:\fiji-win64\Fiji.app\ImageJ-win64.exe" -eval "run('Bio-Formats','open=D:\\Output\\Untitiled032\\ChanA_0001_0001_0001_0001.tif display_ome-xml')"
This is the exact command I can see from my console window, and it runs and gives me what I need. I want to run this command line from from my C# code, so there is escape character problem I don;t know how to handle
There are two strings I'd like to make them flexible
D:\fiji-win64\Fiji.app\ImageJ-win64.exe
D:\Output\Untitiled032\ChanA_0001_0001_0001_0001.tif
I am wondering how I can use string.Format() to formulate this command line?
This is my current code, it opens the image, but the display_ome-xml did not get called:
string bioformats = "Bio-Formats";
string options = string.Format("open={0} display_ome-xml", fileName.Replace("\\", "\\\\"));
string runCommand = string.Format("run(\"'{0}'\",\"'{1}'\")", bioformats, options);
string fijiCmdText = string.Format("/C \"\"{0}\" -eval {1}", fijiExeFile, runCommand);
where fijiExeFile works fins, it is just the runCommand keeps ignoring the display_ome-xml. Anyone has any suggestions? It is really really confusing. Thanks a lot.
As #Kristian pointed out, # can help here. It also appears that there may be some extra or misplaced \" in the code above. This seems to give the desired output string:
string fijiExeFile = #"D:\fiji-win64\Fiji.app\ImageJ-win64.exe";
string fileName = #"D:\\Output\\Untitiled032\\ChanA_0001_0001_0001_0001.tif";
string bioformats = "Bio-Formats";
string options = string.Format("open={0} display_ome-xml", fileName);
string runCommand = string.Format("run('{0}','{1}')", bioformats, options);
string fijiCmdText = string.Format("\"{0}\" -eval \"{1}\"", fijiExeFile, runCommand);
The easiest way is to use the verbatim string literal.
Just put a # before your string like so:
#"c:\abcd\efgh"
This will disable the backslash escape character
If you need " inside your string, you will have to escape the the quotation marks like so:
#"c:\abcd\efgh.exe ""param1"""
Your example could be:
String.Format(#"""{0}"" -eval ""run('Bio-Formats','open={1} display_ome-xml')""", #"D:\fiji-win64\Fiji.app\ImageJ-win64.exe", #"D:\Output\Untitiled032\ChanA_0001_0001_0001_0001.tif")
or
string p1 = "D:\\fiji-win64\\Fiji.app\\ImageJ-win64.exe";
string p2 = "D:\\Output\\Untitiled032\\ChanA_0001_0001_0001_0001.tif";
String.Format(#"""{0}"" -eval ""run('Bio-Formats','open={1} display_ome-xml')""", p1, p2);

how to get unknown amount of variables sent by url - C#

In a webform i have the following tag:
<a href="download.aspx?file0=test0&file1=test1.......></a>
I don't know in advance how many variables are sent.
In C# i tried to get them all:
int cpt=0;
string[] pdfs = new string[];
while ( Request["'file'.cpt"] != null) //<-----ERROR
{
pdfs[cpt] = Request['"file".cpt'] ;
cpt++;
}
Unfortunately i have the following error :
Too many characters in character literal
Can anyone help me to fix this ?
Thanks
Your error message is specifically due to the line:
pdfs[cpt] = Request['"file".cpt'];
You should swap the single and double quotes so that it looks like:
pdfs[cpt] = Request["'file'.cpt"];
In C# a string must be quoted with double quotes. Single quotes can only be used to delimit characters.
You are attempting to add the current value of the cpt variable to a "file" literal, but it doesn't work this way. Please try the following:
Request[String.Format("file{0}", cpt)]
By the way - this can be done quicker:
var pdfs = Request.QueryString
.Keys
.Cast<String>()
.Where(key => key.StartsWith("file"))
.Select(key => Request.QueryString[key])
.ToArray();
To retrieve an unknown number of variables in the format you describe, you need to do this.
List<string> pdfs = new List<string>();
foreach(string k in Request.QueryString.Keys)
{
if (k.StartsWith("file"))
pdfs.Add(Request.QueryString[k]);
}

Find/parse server-side <?abc?>-like tags in html document

I guess I need some regex help. I want to find all tags like <?abc?> so that I can replace it with whatever the results are for the code ran inside. I just need help regexing the tag/code string, not parsing the code inside :p.
<b><?abc print 'test' ?></b> would result in <b>test</b>
Edit: Not specifically but in general, matching (<?[chars] (code group) ?>)
This will build up a new copy of the string source, replacing <?abc code?> with the result of process(code)
Regex abcTagRegex = new Regex(#"\<\?abc(?<code>.*?)\?>");
StringBuilder newSource = new StringBuilder();
int curPos = 0;
foreach (Match abcTagMatch in abcTagRegex.Matches(source)) {
string code = abcTagMatch.Groups["code"].Value;
string result = process(code);
newSource.Append(source.Substring(curPos, abcTagMatch.Index));
newSource.Append(result);
curPos = abcTagMatch.Index + abcTagMatch.Length;
}
newSource.Append(source.Substring(curPos));
source = newSource.ToString();
N.B. I've not been able to test this code, so some of the functions may be slightly the wrong name, or there may be some off-by-one errors.
var new Regex(#"<\?(\w+) (\w+) (.+?)\?>")
This will take this source
<b><?abc print 'test' ?></b>
and break it up like this:
Value: <?abc print 'test' ?>
SubMatch: abc
SubMatch: print
SubMatch: 'test'
These can then be sent to a method that can handle it differently depending on what the parts are.
If you need more advanced syntax handling you need to go beyond regex I believe.
I designed a template engine using Antlr but thats way more complex ;)
exp = new Regex(#"<\?abc print'(.+)' \?>");
str = exp.Replace(str, "$1")
Something like this should do the trick. Change the regexes how you see fit

Categories