How to get onyl part of the URL in c# - 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;
}

Related

How can I replace the parameters in my request url using 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";

How can I make a string out of a complex URL address

I've been trying to make this URL a workable string in C#, but unfortunately using extra "" or "#" is not cutting it. Even breaking it into smaller strings is proving difficult. I want to be able to convert the entire address into a single string.
this is the full address:
<https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT="+URLEncode(""+[Material].[Material - Key])+"&lsIZV_MAT=>
I've also tried this:
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"+ URLEncode("" +[Material].[Material - Key]) + """"";
string url3 = #"&lsIZV_MAT=";
Any help is appreciated.
The simplest solution is put additional quotes inside string literal and use string.Concat to join all of them into single URL string:
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"""+URLEncode(""+[Material].[Material - Key])+""";
string url3 = #"&lsIZV_MAT=";
string resultUrl = string.Concat(url, url2, url3);
NB: You can use Equals method or == operator to check if the generated string matches with desired URL string.
This may be a bit of a workaround rather than an actual solution but if you load the string from a text file and run to a breakpoint after it you should be able to find the way the characters are store or just run it from that.
You may also have the issue of some of the spaces you've added being left over which StringName.Replace could solve if that's causing issues.
I'd recommend first checking what exactly is being produced after the third statement and then let us know so we can try and see the difference between the result and original.
You are missing the triple quotes at the beginning of url2
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"""+URLEncode(""+[Material].[Material - Key])+""";
string url3 = #"&lsIZV_MAT=";
I just made two updates
t&lsMZV_MAT=" to t&lsMZV_MAT="" AND
[Material - Key])+" to [Material - Key])+""
string s = #"<https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=""+ URLEncode([Material].[Material - Key])+""&lsIZV_MAT=>";
Console.Write(s);
Console.ReadKey();

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

Code returning false on equal compare?

Problem I currently have:
My server returns data back to the client, this includes a name. Now I want the client to grab this name and compare it. However for the past 3 hours I am stuck at this problem and I dont want to cheap fix around it.
My server returns a value and then a name, ex: random23454#NAMEHERE
I split the value using:
string[] values = returndata.Split('#');
And then I am doing:
if (textBox3.Text == values[1]) {
MessageBox.Show("equal");
}
However, the problem here is. I cant get it to be equal, I tried other methods but it just dont display equal.
What I have done:
Print textBox3.Text to a textbox and print values[1] to a other textbox and compared with my eye and mouse (Using invoke due to threading).
Used the .Trim() function
Using the .ToString() on values[1] (Just for the hell of it)
Assigned them both to a complete new string, trimmed them and compared them
Dragged the comparing outside the thread using:
this.Invoke((MethodInvoker)delegate()
{
outside(name);
});
and perform the same check.
My code:
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
readData = "" + returndata;
if (readData.Contains("#") && readData.Contains("random"))
{
string[] values = returndata.Split('#');
string name = values[1].Trim();
if (textBox3.Text == name)
{
MessageBox.Show("true");
}
else
{
MessageBox.Show("false");
this.Invoke((MethodInvoker)delegate()
{
outside(name);
});
}
What else can I do? I just dont understand that it is not equal..
Thanks in advance.
The data you're getting back from the server could be an array of bytes. Try converting the response to a string first before splitting. Also try printing the response (or the response's type) to console to see what you get before going any further.
Also make sure the length of each string is the same. Maybe give utf-8 a try instead of ASCII? Like so:
System.Text.Encoding.UTF8.GetString(inStream);
string name = values[1].Trim();
I think you want values[2] here. The way I read the documentation for Split, the element at index 1 will be the (blank) separator indicator.

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