How to get string from formatted url in asp.net c# - asp.net

Suppose We are on the page www.abc.com/apple-store
then how to get string apple-store in asp C# code.
to store into another variable.

You can use string.last() to extract it.
string lastPartUrl =HttpContext.Current.Request.Url.AbsoluteUri.Split('/').Last();

You should use the Request.RawUrl property. See more details here.
Alternatelly you can also use the Request.Url (see here) property to get different parts of the current URL. For example you will get the same result using Request.Url.LocalPath.

You can get the url in a string variable. Further you can implement the below logic which will save the value in a variable.
string str = "www.abc.com/apple-store";
string result = "";
int i= 0;
int len = str.Length;
//Get the index of the character
i = str.IndexOf('/');
//store the result in the variable
result = str.Substring(i+1,len-i-1);
Console.WriteLine("Resultant:- {0}", result);`
Hope this helps a bit.

Related

Accessing the query string value using ASP.NET

I have been trying to find the question to my answer but I'm unable to and finally I'm here. What I want to do is access the value passed to a webpage (GET, POST request) using asp.net. To be more clear, for example:
URL: http://www.foobar.com/SaleVoucher.aspx?sr=34
Using asp.net I want to get the sr value i.e 34.
I'm from the background of C# and new to ASP.NET and don't know much about ASP.NET.
Thanx.
Can you refer to this QueryString
Here he says how to access the query string using:
Request.Url.Query
That is not called a Header, but the Query String.
the object document.location.search will contain that and the javascript to get any query string value based on the key would be something like:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
code from other question: https://stackoverflow.com/a/901144/28004

Get client id of the control

I got the client Id of dropdown value as
ctl00_TimecardContentPlaceHolder_UC_0_1_drpdwnCompany
I have get the value from above string value as 1 only from that client Id.
Any methods like substring() are there to get that value specifically from that string.
Solution
GetClientIdFromConrol(Control control)
{
string strId=control.ClientID;
string strClientsId = strId.Substring(38, 1);
return Convert.ToInt32(strClientsId);
}
If you want to get only 1.
you can use split function to do that job.
string dropdown="ctl00_TimecardContentPlaceHolder_UC_0_1_drpdwnCompany";
string[] split=dropdown.split('_');//split by underscore character;
string result=split[4].ToString(); // Here you will get 1 to the result
Hope this helps.
Use ID not ClientID.
Also seeControl.ClientIDMode Property

Read XML from String

I have data in XML format. I stored it in varchar datatype column. I have retrieved it by using Linq to sql in visual studio 2010. I got xml format data in string variable. now i need read it as a Xml. I need to take value in particular node.
for example,
<Sale>
<LTV>150</LTV>
<CLTV>350</CLTV>
<DLTV>600</DLTV>
</sale>
I NEED TO TAKE CLTV value.
This code should work for you:
using System.Xml;
...
string xmlStr = "<sale><LTV>150</LTV><CLTV>350</CLTV><DLTV>600</DLTV></sale>";
XmlDocument x = new XmlDocument();
x.LoadXml(xmlStr);
MessageBox.Show(x.GetElementsByTagName("CLTV")[0].InnerText);
var value = XDocument.parse("YOUR_XML_STRING").Root.Element("ELEMENT_NAME").Value;
try
var xml = XElement.Parse("your xml");
//Gives you the value of the CLTV node
xml.Descendants("CLTV").FirstOrDefault().Value;
To change the value
xml.Descendants("CLTV").FirstOrDefault().Value = "1";
//Save to disk
xml.Save({stream or file location});
//Get a string back
xml.ToString();
Descendants will give you a list of XElements that you can enumerate or by doing FirstOrDefault you will get the first one it finds or an empty Element.

How to extract website hostname from full url using VB.NET?

I get ReffererUrl from current User, if refferer is exists i need to extract hostname without .com/.co.uk .... etc. value from it. So if ReffererUrl is http://main.something.biz/sup.aspx?r=e3432r3 i want to get just "something".
Doesn't matter whether it is Regex or something else.
thanks...
Note: it is just for your specs only: you can extend it by adding more condition at the end of my code. but i'd say that it wont work when path is like "abc.ss33.video.somthing.co.us"
Uri u = new Uri("http://main.something.biz/sup.aspx?r=e3432r3");
string a = u.DnsSafeHost;
string[] arr1 = a.Split('.');
string somethinVar = String.Empty;
if (arr1.Length == 3)
somethinVar = arr1[1];
There is no built-in way to do this in the sense you describe, because neither IIS nor ASP.NET knows the difference between the host name and domain name.
You have to write some code to do that.
an example could be:
string hostName=ReffererUrl.split('.')[1];
This code works only if the ReffererUrl look like the one you have posted and you have to make sure the array that the split function return an array with a number of elements greater than 1
HttpContext.Current.Request.ServerVariables("HTTP_HOST")
Extract domain with subdomain if present:-
Public Function ExtractSubAndMainDomainFromURL(URL As String) As String
'
' cut-off any url encoded data
URL = URL.Split("?"c)(0)
'return array of segments between slashes
Dim URLparts() As String = URL.Split("/"c)
'find first segment with periods/full-stops
Dim Domain As String = Array.Find(URLparts, Function(x) (x.Contains(".")))
'check if nothing returned - if necessary
If IsNothing(Domain) Then Domain = String.Empty
Return Domain
End Function

Modify request querystring parameters to build a new link without resorting to string manipulation

I want to dynamically populate a link with the URI of the current request, but set one specific query string parameter. All other querystring paramaters (if there are any) should be left untouched. And I don't know in advance what they might be.
Eg, imagine I want to build a link back to the current page, but with the querystring parameter "valueOfInterest" always set to be "wibble" (I'm doing this from the code-behind of an aspx page, .Net 3.5 in C# FWIW).
Eg, a request for either of these two:
/somepage.aspx
/somepage.aspx?valueOfInterest=sausages
would become:
/somepage.aspx?valueOfInterest=wibble
And most importantly (perhaps) a request for:
/somepage.aspx?boring=something
/somepage.aspx?boring=something&valueOfInterest=sausages
would preserve the boring params to become:
/somepage.aspx?boring=something&valueOfInterest=wibble
Caveats: I'd like to avoid string manipulation if there's something more elegant in asp.net that is more robust. However if there isn't something more elegant, so be it.
I've done (a little) homework:
I found a blog post which suggested copying the request into a local HttpRequest object, but that still has a read-only collection for the querystring params. I've also had a look at using a URI object, but that doesn't seem to have a querystring
This will work as long as [1] you have a valid URL to begin with (which seems reasonable) [2] you make sure that your new value ('sausages') is properly escaped. There's no parsing, the only string manipulation is to concatenate the parameters.
Edit
Here's the C#:
UriBuilder u = new UriBuilder(Request.Url);
NameValueCollection nv = new NameValueCollection(Request.QueryString);
/* A NameValueColllection automatically makes room if this is a new
name. You don't have to check for NULL.
*/
nv["valueOfInterest"] = "sausages";
/* Appending to u.Query doesn't quite work, it
overloaded to add an extra '?' each time. Have to
use StringBuilder instead.
*/
StringBuilder newQuery = new StringBuilder();
foreach (string k in nv.Keys)
newQuery.AppendFormat("&{0}={1}", k, nv[k]);
u.Query = newQuery.ToString();
Response.Redirect(u.Uri.ToString());
UriBuilder u = new UriBuilder(Request.Url);
NameValueCollection nv = new NameValueCollection(Request.QueryString);
nv["valueofinterest"] = "wibble";
string newQuery = "";
foreach (string k in nv.Keys)
{
newQuery += k + "=" + nv[k] + "&";
}
u.Query = newQuery.Substring(0,newQuery.Length-1);
Response.Redirect(u.ToString());
that should do it
If you can't find something that exists to do it, then build a bullet-proof function to do it that is thoroughly tested and can be relied upon. If this uses string manipulation, but is efficient and fully tested, then in reality it will be little different to what you may find any way.

Resources