How to remove bracketed sections of a Url - c#

In my c# application I am building a routine that will parse through a url replace any sections of the url with the appropriate data.
For instance, if I have a url like:
api.domain.com/users/{id}
and the user provides the id, i replace the id with the given value.
This is simple enough:
if(path.Contains("{id}") path = path.Replace("{id}", id);
However, what I want is to be able to remove the {id} from the url if no id is provided so that the final url is:
api.domain.com/users
I would also want it to intelligently be able to remove items in the middle of the path so that if the url were:
api.domain.com/users/{id}/photos
I would get:
api.domain.com/users/photos
For this, I would not know the text of the key ahead of time so {id} could be anything such as:
{name} {sometext} {anyvalue}
But I do know that each MUST be contained in curly braces.
Any help would be greatly appreciated!

You can do something like this:
public string UrlReplace(string Url, string key, string value = "")
{
var replaceString = "{" + key + "}"; //get the string to replace
//if the value is empty remove the slash
if (string.IsNullOrEmpty(value))
{
//find the index of the replace string in the url
var index = url.IndexOf(replaceString) + replaceString.Length;
if (url[index] == '/')
{
url = url.Remove(index, 1); //if the character after the string is a slash, remove it
}
}
return url.Replace(replaceString, value); //replace the string with the value
}
Then you'd use it like
string url = "api.domain.com/users/{id}/photos";
url = UrlReplace(url,"id","test");
//returns "api.domain.com/users/test/photos"
url = UrlReplace(url, "id", "");
//returns "api.domain.com/users/photos"

Related

Remove only the first match in string

From a string, check if it starts with a value 'startsWithCorrectId'...if it does remove the value from the start. Problem being if this value is also found again in the string, it will also remove it. I realise this is what .replace does...but is there something like .startsWith to RemoveAtStart?
string startsWithCorrectId = largeIconID.ToString();
//startsWithCorrectId will be '1'
string fullImageName = file.Replace("_thumb", "");
//fullImageName will be "1red-number-1.jpg"
//file will be '1red-number-1_thumb.jpg'
if(file.StartsWith(startsWithCorrectId))
{
fullImageName = fullImageName.Replace(startsWithCorrectId, "");
//so yes this is true but instead of replacing the first instance of '1'..it removes them both
}
Really what I would like is for '1red-number-1.jpg' to become 'red-number-1.jpg'....NOT 'red-number-.jpg'..replacing all instances of 'startsWithCorrectId' I just want to replace the first instance
One solution is to use Regex.Replace():
fullImageName = Regex.Replace(fullImageName, "^" + startsWithCorrectId, "");
This will remove startsWithCorrectId if it's at the start of the string
if(file.StartsWith(startsWithCorrectId))
{
fullImageName = fullImageName.SubString(startsWithCorrectId.Length);
}
if I have undestood your correctly you would need to get a string starting from correctId.Length position
if(fullImageName .StartsWith(startsWithCorrectId))
fullImageName = fullImageName .Substring(startsWithCorrectId.Length);
if you like extensions:
public static class StringExtensions{
public static string RemoveFirstOccuranceIfMatches(this string content, string firstOccuranceValue){
if(content.StartsWith(firstOccuranceValue))
return content.Substring(firstOccuranceValue.Length);
return content;
}
}
//...
fullImageName = fullImageName.RemoveFirstOccuranceIfMatches(startsWithCorrectId);
You can do so with a regular expression where you can encode the requirement that the string starts at the beginning:
var regex = "^" + Regex.Escape(startsWithCorrectId);
// Replace the ID at the start. If it doesn't exist, nothing will change in the string.
fullImageName = Regex.Replace(fullImageName, regex, "");
Another option is to use a substring, instead of a replace operation. You already know that it's at the start of the string, you can just take the substring starting right after it:
fullImageName = fullImageName.Substring(startsWithCorrectId.Length);

Add a directory name to a URL address using C#

I have a textbox where users can paste a URL address. I want to add a directory name to the URL before saving it in the database.
<asp:TextBox ID="urlTextbox" runat="server"></asp:TextBox>
Code behind
TextBox url = urlTextbox as TextBox;
string urlString = urlTextbox.Text;
Let's say the urlString = "mydomain.com/123456". I want to replace it with "mydomain.com/directory/123456". mydomain.com/directory is the same for all the URLs. The last part "123456" changes only.
Thank you
I'd suggest seeing if your needs are met with the UriBuilder class.
UriBuilder url = new UriBuilder(urlTextbox.Text);
Now you can use the various properties to change your url.
string formattedUrl = string.Format("{0}://{1}/directory/{2}", url.Scheme, url.Host, url.Path);
A better idea is to adjust the URL with another / same UriBuilder as noted by Jared.
UriBuilder url = new UriBuilder(urlTextbox.Text);
url.Path = string.Format("directory/{0}", url.Path);
Use this object as a Uri by simply doing this
Uri formattedUrl = url.Uri;
Or convert to a string if needed.
string formattedUrl = url.ToString();
You can also use Uri.TryParse(...) to verify if it's a valid URL being entered into the text box.
To get the individual query parameters, you can look at the Uri object.
UriBuilder url = new UriBuilder("mydomain.com/123456?qs=aaa&bg=bbb&pg=ccc");
url.Path = string.Format("directory/{0}", url.Path);
Uri formattedUrl = url.Uri;
string queryString = formattedUrl.Query;
// parse the query into a dictionary
var parameters = HttpUtility.ParseQueryString(queryString);
// get your parameters
string qs = parameters.Get("qs");
string bg = parameters.Get("bg");
string pg = parameters.Get("pg");
You can use string functions Split and Join to achieve your result. An example code is shown below
List<string> parts = urlString.Split(new char[] { '/'}).ToList();
parts.Insert(parts.Count - 1, "directory");
urlString = string.Join("/", parts);
This is one way of doing. Split the urlString using .split() function.
string[] parts = urlString.Split('/');
parts[parts.Length-1] will have that number. Append it to the string you want.
I'd do something like this:
//Assuming the address in urlString has the format mydomain.com/123456
string[] urlParts = urlString.Split('/');
string directory = "directory";
string finalUrl = urlParts[0] + "/" + directory + "/" + urlParts[1];
Be careful if the address has other "/" characters, like if preceded by http:// or something like that.
Hope it helps.
Simply use concatenation:
save in a temporary string
temp="mydomain.com/directory/"
and save the changing part in another string like
temp2="123456"
now concatenate both temp1 and temp2 like below.
urlString=temp1+temp2;

Get page name from URI, substring between two characters

I want to get the page name from a URI for instance if I have
"/Pages/Alarm/AlarmClockPage.xaml"
I want to get AlarmClockPage
I tried
//usage GetSubstring("/", ".", "/Pages/Alarm/AlarmClockPage.xaml")
public static string GetSubstring(string a, string b, string c)
{
string str = c.Substring((c.IndexOf(a) + a.Length),
(c.IndexOf(b) - c.IndexOf(a) - a.Length));
return str;
}
But because the string being search may contain one or more forward slashes, I don't think this method work in such case.
So how do I consider the multiple forward slashes that may present?
Why don't you use method which is already in the framework?
System.IO.Path.GetFileNameWithoutExtension(#"/Pages/Alarm/AlarmClockPage.xaml");
If you only want to use string functions, you may try:
var startIdx = pathString.LastIndexOf(#"/");
var endIdx = pathString.LastIndexOf(".");
if(endIdx!=-1)
{
fileName = pathString.Substring(startIdx,endIdx);
}
else
{
fileName = pathString.Substring(startIdx);
}
It gives file name from a given file path. try this
string pageName = System.IO.Path.GetFileName(#"/Pages/Alarm/AlarmClockPage.xaml");

base64 decode null reference excpetion on URL

So i have this code on my cs page that takes decodes a key from my Url string. The key is "Reauth_URL" and its a link that is decoded in base64 to UTF8.
////base 64 decoding for Reauth_URL key in URL query string
string encodedString = Convert.ToString(HttpContext.Current.Request.Params["Reauth_URL"]).Trim(')');
byte[] data = Convert.FromBase64String(encodedString);
string decodedString = Encoding.UTF8.GetString(data);
I'm trying to use decodedString but i keep on getting a null refence exception but i can see that the key and value are there.
once i can return the string value id like to ba able to send it into a hyperlink that's on my aspx page.
the encoded url is set up from IronPort which allows a user to lg in as differnt user if they've been blocked from a website. so this reauth_url key in the query string allows them to log in as different user. by the reauth_url needs to be decoded and linked to the hyperlink. I know the key and value is there but i cant get by this null exception, and when i say i know they are there obviously i don't mean in the code above, ive had to split the url query by ? and & and print it out somewhere else and they exist. The code below is used earlier and the key and value i need is there.
string currentUrl = HttpContext.Current.Request.Url.Query;
txtBlockedUrl.Visible = true;
string [] result = currentUrl.Split(new Char[]{'?','&'});
foreach (string r in result)
{
txtBlockedUrl.Text += HttpUtility.UrlDecode(r) + "\n";
}
div style="font-size: medium">
LogIn as Different User
</div>
If HttpContext.Current.Request.Params["Reauth_URL"] is null, Convert.ToString will throw a null reference exception.
Please note that the Params indexer will return null when "Reauth_URL" is not available.
So you have to check first if it exists: (what if the url does not provide it?)
string value = HttpContext.Current.Request.Params["Reauth_URL"];
if (value!=null) {
string encodedString = Convert.ToString(HttpContext.Current.Request.Params["Reauth_URL"]).Trim(')');
//...
Ended Up doing this....
//splitting url string for textbox using name value collection
NameValueCollection collection = new NameValueCollection();
string currentUrl = HttpContext.Current.Request.Url.Query;
string [] result = currentUrl.Split('&');
foreach (string r in result)
{
string[] parts = HttpUtility.UrlDecode(r).Split('=');
if (parts.Length > 0)
{
string key = parts[0].Trim(new char[] { '?', ' ' });
string val = parts[1].Trim();
collection.Add(key, val);
}
}

Regex for replace page number in URL

I'm not good with regex and I'm not able to figure out an applicable solution, so after a good amount of searching I'm still unable to nail this.
I have an URL with an optional page=123 parameter. There can be other optional get parameters in the url too which can occur before or after the page parameter.
I need to replace that parameter to page=--PLACEHOLDER-- to be able to use it with my paging function.
If the page parameter does not occur in the url, I would like to add it the way described before.
I'm trying to write an extension method for on string for this, but a static function would be just as good.
A bit of explanation would be appreciated too, as it would give me a good lesson in regex and hopefully next time I wouldn't have to ask.
Also I'm using asp.net mvc-3 but for compatibility reasons a complex rewrite occurs before the mvc-s routing, and I'm not able to access that. So please don't advise me to use mvc-s routing for this because I cant.
I suggest skipping the regex and using another approach:
Extract the querystring from the url.
Build a HttpValueCollection from the querystring using HttpUtility.ParseQueryString
Replace the page parameter in the collection.
Call .ToString() on the collection and you get a new querystring back.
Construct the altered url using the original minus the old querystring plus the new one.
Something like:
public static string SetPageParameter(this string url, int pageNumber)
{
var queryStartIndex = url.IndexOf("?") + 1;
if (queryStartIndex == 0)
{
return string.Format("{0}?page={1}", url, pageNumber);
}
var oldQueryString = url.Substring(queryStartIndex);
var queryParameters = HttpUtility.ParseQueryString(oldQueryString);
queryParameters["page"] = pageNumber;
return url.Substring(0, queryStartIndex) + queryParameters.ToString();
}
I haven't verified that this compiles, but it should give you an idea.
You want it as a static method with regular expression, here is a first state :
public static string ChangePage(string sUrl)
{
string sRc = string.Empty;
const string sToReplace = "&page=--PLACEHOLDER--";
Regex regURL = new Regex(#"^http://.*(&?page=(\d+)).*$");
Match mPage = regURL.Match(sUrl);
if (mPage.Success) {
GroupCollection gc = mPage.Groups;
string sCapture = gc[1].Captures[0].Value;
// gc[2].Captures[0].Value) is the page number
sRc = sUrl.Replace(sCapture, sToReplace);
}
else {
sRc = sUrl+sToReplace;
}
return sRc;
}
With a small test :
static void Main(string[] args)
{
string sUrl1 = "http://localhost:22666/HtmlEdit.aspx?mid=0&page=123&test=12";
string sUrl2 = "http://localhost:22666/HtmlEdit.aspx?mid=0&page=125612";
string sUrl3 = "http://localhost:22666/HtmlEdit.aspx?mid=0&pager=12";
string sUrl4 = "http://localhost:22666/HtmlEdit.aspx?page=12&mid=0";
string sRc = string.Empty;
sRc = ChangePage(sUrl1);
Console.WriteLine(sRc);
sRc = ChangePage(sUrl2);
Console.WriteLine(sRc);
sRc = ChangePage(sUrl3);
Console.WriteLine(sRc);
sRc = ChangePage(sUrl4);
Console.WriteLine(sRc);
}
which give the result :
http://localhost:22666/HtmlEdit.aspx?mid=0&page=--PLACEHOLDER--&test=12
http://localhost:22666/HtmlEdit.aspx?mid=0&page=--PLACEHOLDER--
http://localhost:22666/HtmlEdit.aspx?mid=0&pager=12&page=--PLACEHOLDER--
http://localhost:22666/HtmlEdit.aspx?&page=--PLACEHOLDER--&mid=0

Categories