Url with = sign and get value from it - c#

I'm trying to get multiple value from URL. But i don't know how Url is getting multiple = sign. That is why i am unable to get it using the querystring. So i am accessing the full URL and trying to get the value from it but i am unable to remove % sign from values.
Here is my code.
string fullUrl = Request.Url.AbsoluteUri.ToString();
string str = fullUrl.Substring(fullUrl.LastIndexOf("Amount"));
Here fullUrl has the value as below:-
fullUrl =
"http://localhost:10372/Customer/Success.aspx?URL=Amount=10&Name=Shami%20%20Sheikh&EmailOfPayer=ansitshami911#gmail.com&bussness=61339393592016_Preevet&CompanyName=Shami%20Sheikh&PaymentDate=07/03/2018%2015:50:48&SecuritiesandComplianceFee=0.47&BackmyUri=http://localhost:11181/Payment.aspx&phone=1234567891&Cardnumber=973638353835&Country=198&St=354&Other=&city=Delhi&Address=Delhi&ZipCode=201301&EmailOfReceiver=ansitshami911#gmail.com&Planrateforaccount=40&Planrateforcard=60&Planrateforcheck=2018&PlanYear=2018"
str variable has the value as below
str =
Amount=10&Name=Shami%20%20Sheikh&EmailOfPayer=ansitshami911#gmail.com&bussness=61339393592016_Preevet&CompanyName=Shami%20Sheikh&PaymentDate=07/03/2018%2015:50:48&SecuritiesandComplianceFee=0.47&BackmyUri=http://localhost:11181/Payment.aspx&phone=1234567891&Cardnumber=973638353835&Country=198&St=354&Other=&city=Delhi&Address=Delhi&ZipCode=201301&EmailOfReceiver=ansitshami911#gmail.com&Planrateforaccount=40&Planrateforcard=60&Planrateforcheck=2018&PlanYear=2018
Here is my code to get the value from URL :-
string s = str;
String[] arr = s.Split('&');
var Namearr = from word in arr
where word.StartsWith("Name")
select word;
foreach (var item1 in Namearr)
{
string str1 = item1.ToString();
string[] strArr = str1.Split('=');
string Name = strArr[1];
}
But the value assigned in variable is Name = "Shami%20%20Sheikh"
Now when i am trying to get the value of Name it returns the value with % sign .
How can i get the actual value from URl?

You can get query string values that are already processed using:
Request.QueryString["Name"]

By using the following code you will get the all the queryString parameters from where you can find your element queryString parameter and it's value.
foreach (string key in Request.QueryString.AllKeys) {
Response.Write("Key: " + key + " Value: " + Request.QueryString[key]);
}

I think you're looking for System.Uri.UnescapeDataString(Name)
https://msdn.microsoft.com/en-us/library/system.uri.unescapedatastring(v=vs.110).aspx

By using server.UrlDecode it works fine.
string fullUrl = Server.UrlDecode(Request.Url.AbsoluteUri.ToString());

Related

How to get substrings from an Xpath using C#?

I have an Xpath property inside of a JSON file and I'd like to get two substrings from this Xpath to assisting these substrings into two variables.
The JSON object is as follows;
{
'selectGateway':'0',
'waitingTime':'20000',
'status':'200',
'correlationID':'1',
'matchString':[{'xpath':'/whitelist/locations/location/var-fields/var-field[#key="whitelist-entry" and #value="8.0440147AA44A80"]','value':''}],
'matchInteger':[],
'matchSortedList':[]
}
This is my attempt so far it's working properly, I'm just looking for a way to do this more dynamically and in a better way if it's possible.
int firstStringPositionForKey = matchString[index].xpath.IndexOf("#key=\"");
int secondStringPositionForKey = matchString[index].xpath.IndexOf("\" and");
string betweenStringForKey = matchString[index].xpath.Substring(firstStringPositionForKey+6, secondStringPositionForKey-firstStringPositionForKey-6);
int firstStringPositionForValue = matchString[index].xpath.IndexOf("#value=\"");
int secondStringPositionForValue = matchString[index].xpath.IndexOf("\"]");
string betweenStringForValue = matchString[index].xpath.Substring(firstStringPositionForValue+8, secondStringPositionForValue-firstStringPositionForValue-8);
I expect the output to be like:
key is : whitelist-entry
value is : 8.0440147AA44A80
I believe you are getting value of xPath in matchString[index].xpath, so here is the solution
//Test is nothing but your xPath
string test = "/whitelist/locations/location/var-fields/var-field[#key=\"whitelist-entry\" and #value=\"8.0440147AA44A80\"]";
//Split your string by '/' and get last element from it.
string lastElement = test.Split('/').LastOrDefault();
//Use regex to get text present in "<text>"
var matches = new Regex("\".*?\"").Matches(lastElement);
//Remove double quotes
var key = matches[0].ToString().Trim('\"');
var #value = matches[1].ToString().Trim('\"');;
//Print key and value
Console.WriteLine("Key is: ${key}");
Console.WriteLine("Value is: ${value}");
Output:
Key is: whitelist-entry
Value is: 8.0440147AA44A80
.net fiddle
Using Regex (Link to formula)
var obj = JObject.Parse("your_json");
var xpath = ((JArray)obj["matchString"])[0]["xpath"].Value<string>();
string pattern = "(?<=key=\")(.*?)(?=\").*(?<=value=\")(.*?)(?=\")";
var match = new Regex(pattern).Match(xpath);
string key = match.Groups[1].Value;
string value = match.Groups[2].Value;

OpenDicom Library C#, problems with Real Value of a tag

I need help in visualize a Tag value ( int , string or others ) in unity using OpendDicom library (C#).
The problem of the code, is that I don't know how to Get the exact value of a tag i.e. the sex of the patient as a String, his/her age as an int...
public void ReadData(AcrNemaFile file)
{
Sequence sq = file.GetJointDataSets().GetJointSubsequences();
string tag = string.Empty;
string description = string.Empty;
string value = string.Empty;
string op = string.Empty;
string val_rep = string.Empty;
string war = string.Empty;
foreach (DataElement el in sq)
{
tag = el.Tag.ToString(); //tag group and element
op = el.VR.Tag.GetDictionaryEntry().Description;//tag description
val_rep = el.VR.ToString();//value representative
war = el.Value.ToString();//
Debug.Log( tag + " : " + op + " \n " + val_rep);
}
}
This is the code to Display the Tags and the related things
The library allows you to get the array of values with .ToArray().
With this you will have a array of objects. Then, you only have to cast or convert the object to the type you want. In this case, you can use the VR to know which kind of type has the object; Decimal String (DS), DateTime (DT), etc...

How to extract an url from a String in C#

I have this string :
"<figure><img
src='http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg'
href='JavaScript:void(0);' onclick='return takeImg(this)'
tabindex='1' class='myclass' width='55' height='66' alt=\"myalt\"></figure>"
How can I retrieve this link :
http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg
All string are the same type so somehow I need to get substring between src= and href. But I don't know how to do that. Thanks.
If you parse HTML don't not use string methods but a real HTML parser like HtmlAgilityPack:
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html); // html is your string
var linksAndImages = doc.DocumentNode.SelectNodes("//a/#href | //img/#src");
var allSrcList = linksAndImages
.Select(node => node.GetAttributeValue("src", "[src not found]"))
.ToList();
You can use regex:
var src = Regex.Match("the string", "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase).Groups[1].Value;
In general, you should use an HTML/XML parser when parsing a value from HTML code, but with a limited string like this, Regex would be fine.
string url = Regex.Match(htmlString, #"src='(.*?)'").Groups[1].Value;
If your string is always in same format, you can easily do this like so :
string input = "<figure><img src='http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg' href='JavaScript:void(0);' onclick='return takeImg(this)' tabindex='1' class='myclass' width='55' height='66' alt=\"myalt\"></figure>";
// link is between ' signs starting from the first ' sign so you can do :
input = input.Substring(input.IndexOf("'")).Substring(input.IndexOf("'"));
// now your string looks like : "http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg"
return input;
string str = "<figure><imgsrc = 'http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg'href = 'JavaScript:void(0);' onclick = 'return takeImg(this)'tabindex = '1' class='myclass' width='55' height='66' alt=\"myalt\"></figure>";
int pFrom = str.IndexOf("src = '") + "src = '".Length;
int pTo = str.LastIndexOf("'href");
string url = str.Substring(pFrom, pTo - pFrom);
Source :
Get string between two strings in a string
Q is your string in this case, i look for the index of the attribute you want (src = ') then I remove the first few characters (7 including spaces) and after that you look for when the text ends by looking for '.
With removing the first few characters you could use .IndexOf to look for how many to delete so its not hard coded.
string q =
"<figure><img src = 'http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg' href = 'JavaScript:void(0);' onclick = 'return takeImg(this)'" +
"tabindex = '1' class='myclass' width='55' height='66' alt=\"myalt\"></figure>";
string z = q.Substring(q.IndexOf("src = '"));
z = z.Substring(7);
z = z.Substring(0, z.IndexOf("'"));
MessageBox.Show(z);
This is certainly not the most elegant way (look at the other answers for that :)).

Get value off querystring by it's position

I have a URL that's going to have one parameter on it but the 'name' of this parameter will, in some cases, be different eg.
www.mysite.com/blog/?name=craig
www.mysite.com/blog/?city=birmingham
and what I'm trying to do is always get the value (craig / birmingham) of the first (and only) parameter on the string regardless of it's name (name/ city). Is there any code that will do that or will I have to check the possible options?
thanks,
Craig
Try something like this:
string valueOfFirstQueryStringParameter = "";
string nameOfFirstQueryStringParameter = "";
NameValueCollection n = Request.QueryString;
if (n.HasKeys())
{
nameOfFirstQueryStringParameter = n.GetKey(0);
valueOfFirstQueryStringParameter = n.Get(0);
}

C# IndexOf (Read from resource.resx)

I created config file with some texts and this file i added to resource.resx. Now i created string for this text.
// String will be contains all texts from resource file
string TextFromResources = Resource.konfigurace;
TextFromResources - > View:
#################
# Settings
#################
RealmID = 1
#################
For next step i need use function "IndexOf".
int value = TextFromConfig.IndexOf("RealmID");
value = TextFromConfig.IndexOf('=');
value2 = TextFromConfig.IndexOf("/r/n");
RealmID = int.Parse(TextFromConfig.Substring(value, value2));
I need that realmID return me int value "1", but now its return me nothing. Please, can you help with my problem?
If index will be correctly so it will be return me value "1" nothing more.
Ah, the substring needs to start after value. Here's a simplified version of your example that works for me:
var text = "RealmID = 1\r\n";
var value = text.IndexOf('=');
var value2 = text.IndexOf("\r\n", value);
var id = int.Parse(text.Substring(value + 1, value2 - value));
Also, I modified the IndexOf call for getting value2 so that it searches for "\r\n" after the location of '='.
Another option is to use a regular expression to find the RealmID value.
var regex = new Regex(#"RealmID = (\d+)");
var match = regex.Match(text);
int realmID = int.Parse(match.Groups[1].Value);

Categories

Resources