How can I replace the parameters in my request url using C#? - c#

I have n number of request urls, like below
https://{user.id}/{user.name}/testing1
https://{user.number}/{user.name}/testing1
https://{user.age}/{user.height}/testing1
https://{user.gender}/{user.name}/testing1
https://{user.height}/{user.age}/testing1
https://{user.weight}/{user.number}/testing1
I have the below test data class which has n number of values.
public class User{
public string id = "123";
public string name = "456";
public string age = "789";
public string gender = "1478";
public string height = "5454";
public string weight = "54547";
public string number = "88722";
.......
.......
.......
}
And I need to make the url
https://{user.number}/{user.name}/testing1 into
https://{88722}/{456}/testing1
In my code, I will be randomly getting a request url(from a json file) and i need to replace the parameters with the values given in the class. Can this be done? If yes please help. Thanks
I have tried using string.format() - but it doesnot work, because I am randomly getting the url and I am not sure which value needs to be replaced.
I also tried using the interpolation, but found not helpful either unless i can do something like
User user = new User();
string requesturl = GetRequestJSON(filepath);
//The requesurl variable will have a value like
//"https://{user.id}/{user.name}/testing1";
string afterreplacing = $+requesturl;
Update: After some more googling, I found out that my question is very much similar to this. I can use the first answer's alternate option 2 as a temporary solution.

Unless I am clearly missing the point (and lets assume all the values are in when you do new user(); )
You just want
User user = new User();
string requesturl = $"https://{user.id}/{user.name}/testing1";
then all the variables like {user.id} are replaced with values. such as "https://88722/456/testing1" if you need the {} in there you can add extra {{ to go with such as
string requesturl = $"https://{{{user.id}}}/{{{user.name}}}/testing1";

Related

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);
}

How to get onyl part of the URL in c#

I am creating a module using C# which will need to refer the URL
So i have 2 example URLs for you here.
http://www.website.com/ProductDetail/tabid/86/rvdsfpid/1gb-dual-port-iscsi-8660/rvdsfmfid/qlogic-174/Default.aspx
&&
http://www.website.com/ProductDetail/tabid/86/rvdsfpid/49950/default.aspx
Now what i need from both the URls is the product ID which in the first case is 8660 & the second case is 49950. I cannot change the way these URls are generated. The easiest way would have been
http://www.website.com/ProductDetail/tabid/86/default.aspx?rvdsfpid=49950
and then i could do the following and life would be easy.
string Pid= Request.Querystring["rvdsfpid"];
However since i dont have control on the way the URL is generatyed how can i catch the URL and fetch only the productId.
Assuming that's the URL format you're being passed and there's nothing else you can do....You're going to need to get the full url and then split it. Here's the basic, you're going to have to add some extra checks and stuff in there;
string url = "http://www.website.com/ProductDetail/tabid/86/rvdsfpid/1gb-dual-port-iscsi-8660/rvdsfmfid/qlogic-174/Default.aspx"
//string url = "http://www.website.com/ProductDetail/tabid/86/rvdsfpid/49950/default.aspx";
url = url.Replace("http://", ""); //get rid of that, add code to check for https?
string[] x = url.Split('/');
string productCode = x[5]; //assuming the product code is always the 6th item in the array!
string code = "";
if (productCode.IndexOf("-") > -1)
{
code = productCode.Substring(productCode.LastIndexOf("-")+1);
}
else
{
code = productCode;
}

Function to locate a string in a text

What would be the most efficient way of searching for a specific string in a text then displaying only a portion of it?
Here is my situation: I am currently hosting a .txt file on my server. The function I want to create would access this .txt (maybe even download for efficiency?), search an ID (ex. 300000000) and then put the name in a string (ex. Island Andrew).
Here is an example of the .txt file hosted on my server:
ID: 300000000 NAME: Island Andrew
ID: 300000100 NAME: Island Bob
ID: 300000010 NAME: Island George
ID: 300000011 NAME: Library
ID: 300000012 NAME: Cellar
I have already complete code for a similar example, however, the formatting is different and it is not in c#.
Here it is;
If anyone can help me accomplish this in c#, it would be greatly appreciated.
Thanks.
Simplistic approach without proper error handling.
Main part to look at is regex stuff.
using System;
using System.Net;
using System.Text.RegularExpressions;
using System.Collections.Generic;
class Program
{
static void Main()
{
var map = new Map();
Console.WriteLine(map[300000011]);
}
}
public class Map: Dictionary<int, string>
{
public Map()
{
WebClient wc = new WebClient()
{
Proxy = null
};
string rawData = wc.DownloadString("<insert url with data in new format here>");
PopulateWith(rawData);
}
void PopulateWith(string rawText)
{
string pattern = #"ID: (?<id>\d*) NAME: (?<name>.*)";
foreach (Match match in Regex.Matches(rawText, pattern))
{
// TODO: add error handling here
int id = int.Parse( match.Groups["id"].Value );
string name = match.Groups["name"].Value;
this[id] = name;
}
}
}
You could try this to create an array of names in C#:
Dictionary<int,String> mapDictionary;
string[] mapNames = rawData.Split(splitChar, StringSplitOptions.None);
foreach(String str in mapNames)
{
{
String mapid = str.Substring(str.IndexOf(":"));
String mapname = str.Remove(0, str.IndexOf(':') + 1);
mapDictionary.Add(Convert.ToInt32(mapid), mapname);
}
}
Remove all carets (^)
Convert all member access operators (->) to dots
Change gcnew to new Convert array to string[]
Remove private and public modifiers from class, have them on methods
explicitly (e.g. public void CacheMaps())
Change ref class to static class
Change nullptr to null
Change catch(...) to only catch
Move using namespace to the very top of the file, and replace scope resolution operator (::) to dots.
That should be about it.
simplest way would be to do a token separator between ID: 30000 and Name: Andrew Island and remove the ID and Name as such
30000, Andrew Island
Then in your C# code you would create a custom class called
public class SomeDTO {
public long ID{get; set;}
public string Name {get; set;}
}
next you would create a new List of type SomeDTO as such:
var List = new List<SomeDTO>();
then as you're parsing the txt file get a file reader and read it line by line for each line ensure that you have a token separator that separates the two Values by the comma separation.
Now you can simply add it to your new List
var tempId = line[1];
var tempName = line[2];
List.Add(new SomeDTO{ ID = tempId, Name = tempName});
Now that you have the entire list in memory you can do a bunch of searching and what not and find all things you need plus reuse it because you've already built the list.
var first = List.Where(x => x.Name.Equals("Andrew Island")).FirstOrDefault();

C# how to add parameters to a string with braces at the beginning?

I have the next string:
public const string BaseAddress = "http://test.i-swarm.com/i-swarm/api/v1/";
public const string LoginURL = "{0}sessions";
I want to make a url of LoginURL where the {0} is the BaseAddress.
The logical way is not working:
string str = string.Format(BaseAddress, LoginURL);
It only prints the BaseAddress.
It will work if I do this:
string str = string.Format(LoginURL, BaseAddress); //Is this the correct way?
It's not logical way, you are defining parameter in LoginUrl not in BaseAddress, so it's working correctly
If you want it work logicaly do it that way:
public const string BaseAddress = "http://test.i-swarm.com/i-swarm/api/v1/{0}";
public const string LoginURL = "sessions";
string.Format is replacing {0} with first parameter, so it will now work like you want it to work.
string str = string.Format(LoginURL, BaseAddress); //Is this the correct way?
Yes, that is the correct way. Although it doesn't follow the usual pattern people use. Please read the documentation for the function located here: http://msdn.microsoft.com/en-us/library/system.string.format.aspx
The first argument is the Format, the second are the arguments/replacement values. Assuming you want to maintain a constant format, that is usually a hardcoded in the argument as such:
string str = string.Format("{0}sessions", BaseAddress);
Being as it seems the base address is normally more consistent (but may still be variable) an approach such as the following may be better:
public const string BaseAddress = "http://test.i-swarm.com/i-swarm/api/v1/";
public const string LoginURL = "sessions";
string str = string.Format("{0}{1}", BaseAddress, LoginURL);
If your end-goal is just URL combination rather than an exercise using string.Format, the following may still be a better approach:
Uri baseUri = new Uri("http://test.i-swarm.com/i-swarm/api/v1/");
Uri myUri = new Uri(baseUri, "sessions");
That way you don't have to worry about whether or not a separator was used in the base address/relative address/etc.
There is no logical way, there's just one way to comply to how String.Format works. String.Format is defined so that the first parameter contains the string into which parameters will be inserted, then follows a list of the parameters.
If you define the strings like you do, the only correct way is
string str = string.Format(LoginURL, BaseAddress);
It would be more intuitive, however, if the BaseAddress was the format string:
public const string BaseAddress = "http://test.i-swarm.com/i-swarm/api/v1/{0}";
public const string LoginURL = "sessions";
So you could write
string str = String.Format(BaseAddress, LoginURL);
Yes the correct way is:
string str = String.Format(LoginURL, BaseAddress);
The format string should always be the first parameter.
Though I feel that:
string str = String.Format("{0}sessions", BaseAddress);
Is more readable.
You can use C#'s interpolated strings.
string BaseAddress = "http://test.i-swarm.com/i-swarm/api/v1/";
string LoginURL = $"{BaseAddress}sessions";
You can have multiple parameters. This is a safer method of formatting strings as when using string.Format you need to make sure that order of parameters are correct. With this new way you don't have to.
string foo = "foo";
int bar = 4;
string result = $"{bar} hello {foo}";
Reference:
What's with the dollar sign ($"string")
MSDN - Interpolated Strings

Taking params from a url

Take these two URLs:
www.mySite.com?name=ssride360
www.mySite.com/ssride360
I know that to get the name param from url 1 you would do:
string name = Request.Params['name'];
But how would I get that for the second url?
I was thinking about attempting to copy the url and remove the known information (www.mySite.com) and then from there I could set name to the remainder.
How would I do a url copy like that? Is there a better way to get 'ssride360' from the second url?
Edit Looking on SO I found some info on copying URLs
string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx
string path = HttpContext.Current.Request.Url.AbsolutePath;
// /TESTERS/Default6.aspx
Is this the best way for me? each url have one additional param (mySite.com/ssride360?site=SO) for example. Also I know that mySite.com/ssride360 would reference a folder in my project so wouldn't i be getting that file along with it (mySite.com/ssride360/Default6.aspx)?
At this point I think there are better ways then a url copy.
Suggestions?
Uri x = new Uri("http://www.mySite.com/ssride360");
Console.WriteLine (x.AbsolutePath);
prints /ssride360
This method will allow you to get the name even if there is something after it. It is also a good model to use if you plan on putting other stuff after the name and want to get those values.
char [] delim = new char[] {'/'};
string url = "www.mySite.com/ssride360";
string name = url.Split(delim)[1];
Then if you had a URL that included an ID after the name you could do:
char [] delim = new char[] {'/'};
string url = "www.mySite.com/ssride360/abc1234";
string name = url.Split(delim)[1];
string id = url.Split(delim)[2];
URL rewriting is a common solution for this problem. You give it the patterns of the URL's you want to match and what it needs to change it into. So it would detect www.mySite.com/ssride360 and transform it into www.mySite.com?name=ssride360. The user of the website sees the original URL and doesn't know anything changed, but your code sees the transformed URL so you can access the variables in the normal way. Another big plus is that the rules allow you to set the patterns that get transformed as well as the ones that just get passed through to actual folders / files.
http://learn.iis.net/page.aspx/461/creating-rewrite-rules-for-the-url-rewrite-module/
Like javascript? If so...
<script type="text/javascript">
function getName() {
var urlParts = window.location.pathname.split('/'); //split the URL.
return urlParts[1]; //get the value to the right of the '/'.
}
</script>

Categories

Resources