Parse a graph url string C# - c#

I have the following string
https://graph.microsoft.com/v1.0/groups/group-id/members/user-id/$ref
How do I parse the url string and get the value user-id?
var a = requestStep; //requestStep is of type Microsoft.Graph.BatchRequestStep
var b = requestStep.Request.RequestUri;
b has the value:
https://graph.microsoft.com/v1.0/groups/group-id/members/user-id/$ref

There are a few ways to skin that cat ...
string url = "https://graph.microsoft.com/v1.0/groups/group-id/members/user-id/$ref";
string userId = url.Split('/')[url.Split('/').Length - 1];
Console.WriteLine(userId);

You can also use the following regex pattern :
^https:\/\/graph\.microsoft\.com\/.+\/members\/(.+)\/\$ref$

Related

Splitting the string by few delimeter

I have a string with me and I want to call a rest method from that string. Can anyone think of a better approach then the one I described below for converting str to Rest Call Url.
str : https://P1.P2.com/ProjectName/_build?definitionId=123
Extract P1 and ProjectName and definitionId
Rest Call : https://dev.azure.com/P1/ProjectName/_apis/pipelines/123/runs?api-version=6.0-preview.1
Here, after getting the string, split it with "//" and then split array[1] with "/" and then get P1, ProjectName and then find something with "=" and then the number ?
Not sure if this might be ok.
Update :
I can get this as a URI. But how to convert it then ?
First off, use Uri to parse out the host, path, and query parts of the URI:
var uri = new Uri("https://P1.P2.com/ProjectName/_build?definitionId=123");
For extracting P1 from the host, it's probably going to be easiest to split on .:
string subdomain = uri.Host.Split('.')[0]
For ProjectName, just look at uri.Segments:
string projectName = uri.Segments[1];
For definitionId, parse the query string with HttpUtility.ParseQueryString:
var query = HttpUtility.ParseQueryString(uri.Query);
string definitionId = query["definitionId"];
To construct the new Uri, use a UriBuilder:
var builder = new UriBuilder()
{
Scheme = "https",
Host = "dev.azure.com",
Path = $"{subdomain}/{projectName}_apis/pipelines/{definitionId}/runs",
Query = "api-version=6.0-preview.1",
};
string result = builder.ToString();
See it on dotnetfiddle.net

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;

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 :)).

How to select only the characters after a repeated symbol in a long string

If i am using C# and i have a string coming in from a database like this:
\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML
And i only want this part of the string:
1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML
How can i get this string if there is more than one "\" symbol?
You can use the LastIndexOf() method of the String class:
string s = #"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA.xml";
Console.Out.WriteLine(s.Substring(s.LastIndexOf('\\') + 1));
Hope, this helps.
Use String.Split to split string by parts and then get the last part.
Using LINQ Enumerable.Last() :
text.Split('\\').Last();
or
// todo: add null-empty checks, etcs
var parts = text.Split('\\');
strign lastPart = parts[parts.Length - 1];
You can use a combination of String.LastIndexOf("\") and String.Substring(lastIndex+1). You could also use (only in the sample you provided) Path.GetFileName(theString).
string[] x= line.Split('\');
string goal =x[x.Length-1];
but linq will be easier
You can use regex or split the string by "\" symbol and take the last element of array
using System.Linq;
public class Class1
{
public Class1()
{
string s =
#"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML";
var array = s.Split('\\');
string value = array.Last();
}
}
newstring = string.Substring(string.LastIndexOf(#"\")+1);
It seems like original string is like filePath.
This could be one easy solution.
string file = #"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA.xml";
string name = System.IO.Path.GetFileName(file);

C# Remove URL from String

This seems like a really easy one but everything I try doesn't seem to work
say I have the following string:
string myString = "http://www.mysite.com/folder/file.jpg";
How can I process that to remove the URL and just leave "file.jpg" as the string value?
Thanks!
Kris
You can always use System.IO.Path methods
string myString = "http://www.mysite.com/folder/file.jpg";
string fileName = Path.GetFileName(myString); // file.jpg
If you do want to process more complex URIs you can pass it thought the System.Uri type and grab the AbsolutePath
string myString = "http://www.mysite.com/folder/file.jpg?test=1";
Uri uri = new Uri(myString);
string file = Path.GetFileName(uri.AbsolutePath);
string lastPart = myString.Substring(myString.LastIndexOf('/') + 1);

Categories

Resources