I'm using the following url and I need to delete the ?$format=xml from the url. Is there a simple way to achieve this ?
Uri uri = new Uri("https://ldcorp:435/mtp/op/ota/ind/Customer/?$format=xml);
Maybe with simple string methods:
uriString = uri.ToString();
int indexOfQuestionMark = uriString.IndexOf("?");
if(indexOfQuestionMark >= 0)
{
uri = new Uri(uriString.Substring(0, indexOfQuestionMark));
}
or with the Uri class itself and string.Format:
string pathWithoutQuery = String.Format("{0}{1}{2}{3}", uri.Scheme,
uri.Scheme, Uri.SchemeDelimiter, uri.Authority, uri.AbsolutePath);
uri = new Uri(pathWithoutQuery);
Related
The first part of the program is to retrieve the employee user ID (or signature) from an API URL once the name has been entered. (Which I have done)
The second part, the user will enter a specific "to" and "from" date.
Using the signature obtained from the first part and the dates that the user enters, the program should pass this information to an API address and obtain information accordingly.
My question is that I am not sure how to pass the obtained signature to the new API address + the "to" and "from" date.
The first part of the program to retrieve the signature (works perfectly):
namespace TimeSheets_Try_11.Controllers
{
class WebAPI
{
public string Getsignature(string name)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var cookies = FullWebBrowserCookie.GetCookieInternal(new Uri(StaticStrings.UrlIora), false);
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("Cookie:" + cookies);
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.UseDefaultCredentials = true;
string uri = "";
uri = StaticStrings.UrlIora + name;
var response = wc.DownloadString(uri);
var status = JsonConvert.DeserializeObject<List<Employeename>>(response);
string signame = status.Select(js => js.signature).First();
return signame;
}
The second part that I have written so far:
public string[] GetTime(double fromDate, double toDate, string username)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var cookies = FullWebBrowserCookie.GetCookieInternal(new Uri(StaticStrings.UrlNcert), false);
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("Cookie:" + cookies);
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.UseDefaultCredentials = true;
string url = "";
url = StaticStrings.UrlNcert + username + "&fromDate=" + fromDate + "&toDate=" + toDate;
var respons = wc.DownloadString(url);
OracleHour ndata = JsonConvert.DeserializeObject<OracleHour>(respons);
var Get_Odnum = ndata.orderNumber;
var Dt_Work = ndata.dateOfWork;
var hrType = ndata.hourType;
var hr = ndata.hours;
var des = ndata.description;
var surname = ndata.surveyor;
string[] myncertdata = { Get_Odnum, Dt_Work.ToString(), hrType, hr.ToString(), des, surname };
return myncertdata;
}
}
}
The API strings:
namespace TimeSheets_Try_11.Controllers
{
class StaticStrings
{
public static string UrlIora = "https://iora.dnvgl.com/api/dictionary/employee/";
public static string UrlNcert = "https://cmcservices.dnvgl.com/Finance/api/oracleReportingCost?user=VERIT" + #"\";
}
}
For example if we are using the name "Jane Dow" from the date 9/22/20 - 9/29/20, the api strings will be
UrlIora = "https://iora.dnvgl.com/api/dictionary/employee/Jane
UrlNcert = "https://cmcservices.dnvgl.com/Finance/api/oracleReportingCost?user=VERIT\JDOW&fromDate=2020-09-22&toDate=2020-09-29"
Trivial way - change UrlNcert to url without query at first:
class StaticStrings
{
public static string UrlIora = "https://iora.dnvgl.com/api/dictionary/employee/";
public static string UrlNcert = "https://cmcservices.dnvgl.com/Finance/api/oracleReportingCost";
}
Then in your api call get values for username, fromDate and toDate and use string interpolation.
var url = $"{StaticStrings.UrlNcert}?user={username}&fromDate={fromDate:yyyy-MM-dd}&toDate={toDate:yyyy-MM-dd}";
If you want more complex way, check UriBuilder
I try to get image url using regex, and my code is below.
string IMG_REX_PATTERN = #"<[Ii][Mm][Gg][^>]*src\s*=\s*[\""\']?(?<IMAGE_URL>[^""'>\s]*)[\""\']?[^>]*>";
Match match = Regex.Match(result[i]["N_Dext5EditorField"].ToString(), IMG_REX_PATTERN, RegexOptions.IgnoreCase);
string src = string.Empty;
if (match.Length > 0)
{
//portalUrl = https://test.beta.co.kr
string portalUrl = DevelopmentHelper.GetPortalUrl();
src = match.Groups[1].Value.Replace(portalUrl, "");
}
else
{
src = "";
}
But, sometimes src contains port number like this.
src = :443/dext5editordata/2017/12/20171228_191217524_37634.png
I want to get url like this(not included port number)
src = /dext5editordata/2017/12/20171228_191217524_37634.png
I thought easy way is portalUrl + ":443", but port number is sometimes diffrent.
How can I fix my code? Please help me.
Just update it
string src = ":443/dext5editordata/2017/12/20171228_191217524_37634.png";
int firstindex=src.IndexOf("/");
string witoutportno=src.Substring(firstindex);
You can also Check my code here
http://rextester.com/CRS51521
based on your replies, I changed my code.
if (match.Length > 0)
{
//portalUrl = https://test.beta.co.kr
string portalUrl = DevelopmentHelper.GetPortalUrl();
string tempsrc = match.Groups[1].Value;
var uri = new UriBuilder(tempsrc);
string targetUrl = uri.Uri.ToString();
src = targetUrl .Replace(portalUrl, "");
}
else
{
src = "";
}
I'm trying to create a HTTP url request to get Amazon items by its ASIN Array. I'm using the same code in my Objective-c code for the same reason and it's work perfectly.
But i'm getting this messeage everytime i try to access the url in my chrome:
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
This is the code i'm using:
private void GetFinalUrlForAsinArray(ArrayList asinArr)
{
String timeStamp = GetTimeStamp();
String amazonAPIUrl = "http://webservices.amazon.com/onca/xml?";
ArrayList param = new ArrayList();
param.Add("AWSAccessKeyId=myawsaccesskeyid");
param.Add("AssociateTag=myassociatetag");
param.Add("IdType=ASIN");
param.Add(string.Join(",", asinArr.ToArray()));
param.Add("Operation=ItemLookup");
param.Add("ResponseGroup=ItemAttributes,Offers");
param.Add("Service=AWSECommerceService");
param.Add(String.Format("Timestamp={0}", timeStamp));
amazonAPIUrl += string.Join("&", param.ToArray());
string queryString = new System.Uri(amazonAPIUrl).Query;
var queryDictionary = HttpUtility.ParseQueryString(queryString);
ArrayList queryItemsNew = new ArrayList();
foreach (var query in queryDictionary)
{
String name = HttpUtility.UrlEncode((string)query);
String value = HttpUtility.UrlEncode((string)queryDictionary.Get((string)query));
queryItemsNew.Add(String.Format("{0}={1}", name,value));
}
String path = string.Join("&", queryItemsNew.ToArray());
String finalPath = String.Format("GET\nwebservices.amazon.com\n/onca/xml\n{0}",path);
string signature = HmacSha256Digest(finalPath);
String finalUrl = String.Format("http://webservices.amazon.com/onca/xml?{0}&Signature={1}", path, signature);
}
private String GetTimeStamp()
{
DateTime d = DateTime.UtcNow;
String str = d.ToString("yyyy-MM-dd''T''HH:mm:ss''Z''");
return str;
}
private static string HmacSha256Digest(string message)
{
UTF8Encoding encoding = new UTF8Encoding();
HMACSHA256 hmac = new HMACSHA256(encoding.GetBytes(mysecret));
string signature = Convert.ToBase64String(hmac.ComputeHash(encoding.GetBytes(message)));
String sigEncoded = Uri.EscapeDataString(signature);
return sigEncoded;
}
Having had a look at the API documentation it looks like you've missed the ItemId key here:
param.Add(string.Join(",", asinArr.ToArray()));
I'm guessing you meant it to be:
param.Add("ItemId=" + string.Join(",", asinArr.ToArray()));
It otherwise looks to comply with the spec, the only other thing I noted was the example had the URL encoding as uppercase i.e. %3A rather than the C# default %3a.
how to get host domain from a string URL?
GetDomain has 1 input "URL", 1 Output "Domain"
Example1
INPUT: http://support.domain.com/default.aspx?id=12345
OUTPUT: support.domain.com
Example2
INPUT: http://www.domain.com/default.aspx?id=12345
OUTPUT: www.domain.com
Example3
INPUT: http://localhost/default.aspx?id=12345
OUTPUT: localhost
You can use Request object or Uri object to get host of url.
Using Request.Url
string host = Request.Url.Host;
Using Uri
Uri myUri = new Uri("http://www.contoso.com:8080/");
string host = myUri.Host; // host is "www.contoso.com"
Try like this;
Uri.GetLeftPart( UriPartial.Authority )
Defines the parts of a URI for the Uri.GetLeftPart method.
http://www.contoso.com/index.htm?date=today --> http://www.contoso.com
http://www.contoso.com/index.htm#main --> http://www.contoso.com
nntp://news.contoso.com/123456#contoso.com --> nntp://news.contoso.com
file://server/filename.ext --> file://server
Uri uriAddress = new Uri("http://www.contoso.com/index.htm#search");
Console.WriteLine("The path of this Uri is {0}", uriAddress.GetLeftPart(UriPartial.Authority));
Demo
Use Uri class and use Host property
Uri url = new Uri(#"http://support.domain.com/default.aspx?id=12345");
Console.WriteLine(url.Host);
try following statement
Uri myuri = new Uri(System.Web.HttpContext.Current.Request.Url.AbsoluteUri);
string pathQuery = myuri.PathAndQuery;
string hostName = myuri.ToString().Replace(pathQuery , "");
Example1
Input : http://localhost:4366/Default.aspx?id=notlogin
Ouput : http://localhost:4366
Example2
Input : http://support.domain.com/default.aspx?id=12345
Output: support.domain.com
The best way, and the right way to do it is using Uri.Authority field
Load and use Uri like so :
Uri NewUri;
if (Uri.TryCreate([string with your Url], UriKind.Absolute, out NewUri))
{
Console.Writeline(NewUri.Authority);
}
Input : http://support.domain.com/default.aspx?id=12345
Output : support.domain.com
Input : http://www.domain.com/default.aspx?id=12345
output : www.domain.com
Input : http://localhost/default.aspx?id=12345
Output : localhost
If you want to manipulate Url, using Uri object is the good way to do it.
https://msdn.microsoft.com/en-us/library/system.uri(v=vs.110).aspx
var url = Regex.Match(url, #"(http:|https:)\/\/(.*?)\/");
INPUT = "https://stackoverflow.com/questions/";
OUTPUT = "https://stackoverflow.com/";
Try this
Console.WriteLine(GetDomain.GetDomainFromUrl("http://support.domain.com/default.aspx?id=12345"));
It will output support.domain.com
Or try
Uri.GetLeftPart( UriPartial.Authority )
You should construct your string as URI object and Authority property returns what you need.
public static string DownloadImage(string URL, string MetaIcon,string folder,string name)
{
try
{
WebClient oClient = new WebClient();
string LocalState = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
string storesIcons = Directory.CreateDirectory(LocalState + folder).ToString();
string path = Path.Combine(storesIcons, name + ".png");
//si la imagen no es valida ej "/icon.png"
if (!TextBoxEvent.IsValidURL(MetaIcon))
{
Uri uri = new Uri(URL);
string DownloadImage = "https://" + uri.Host + MetaIcon;
oClient.DownloadFile(new Uri(DownloadImage), path);
}
//si la imagen tiene todo ej https://www.mercadolibre.com/icon.png
else
{
oClient.DownloadFile(new Uri(MetaIcon), path);
}
return path;
}
catch (Exception ex)
{
return ex.ToString();
}
}
Here's a solution that will work for all kinds of URLs.
public string GetDomainFromUrl(string url)
{
url = url.Replace("https://", "").Replace("http://", "").Replace("www.", ""); //Remove the prefix
string[] fragments = url.Split('/');
return fragments[0];
}
it will take only domain name (www.bla.com -> bla)
no Uri required
static string GetDomainNameOnly(string s)
{
string domainOnly = "";
if (!string.IsNullOrEmpty(s))
{
if (s.Contains("."))
{
string domain = s.Substring(s.LastIndexOf('.', s.LastIndexOf('.') - 1) + 1);
string countryDomain = s.Substring(s.LastIndexOf('.'));
domainOnly = domain.Replace(countryDomain, "");
}
else
domainOnly = s;
}
return domainOnly;
}
WWW is an alias, so you don't need it if you want a domain.
Here is my litllte function to get the real domain from a string
private string GetDomain(string url)
{
string[] split = url.Split('.');
if (split.Length > 2)
return split[split.Length - 2] + "." + split[split.Length - 1];
else
return url;
}
There's a lot of information for building Uris from Controller and Action names, but how can I do this the other way around?
Basically, all I'm trying to achieve is to get the Controller and Action names from the referring page (i.e. Request.UrlReferrer). Is there an easy way to achieve this?
I think this should do the trick:
// Split the url to url + query string
var fullUrl = Request.UrlReferrer.ToString();
var questionMarkIndex = fullUrl.IndexOf('?');
string queryString = null;
string url = fullUrl;
if (questionMarkIndex != -1) // There is a QueryString
{
url = fullUrl.Substring(0, questionMarkIndex);
queryString = fullUrl.Substring(questionMarkIndex + 1);
}
// Arranges
var request = new HttpRequest(null, url, queryString);
var response = new HttpResponse(new StringWriter());
var httpContext = new HttpContext(request, response)
var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
// Extract the data
var values = routeData.Values;
var controllerName = values["controller"];
var actionName = values["action"];
var areaName = values["area"];
My Visual Studio is currently down so I could not test it, but it should work as expected.
To expand on gdoron's answer, the Uri class has methods for grabbing the left and right parts of the URL without having to do string parsing:
url = Request.UrlReferrer.GetLeftPart(UriPartial.Path);
querystring = Request.UrlReferrer.Query.Length > 0 ? uri.Query.Substring(1) : string.Empty;
// Arranges
var request = new HttpRequest(null, url, queryString);
var response = new HttpResponse(new StringWriter());
var httpContext = new HttpContext(request, response)
var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
// Extract the data
var values = routeData.Values;
var controllerName = values["controller"];
var actionName = values["action"];
var areaName = values["area"];
To add to gdoran's accepted answer, I found that the action doesn't get populated if a custom route attribute is used. The following works for me:
public static void SetUpReferrerRouteVariables(HttpRequestBase httpRequestBase, ref string previousAreaName, ref string previousControllerName, ref string previousActionName)
{
// No referrer found, perhaps page accessed directly, just return.
if (httpRequestBase.UrlReferrer == null) return;
// Split the url to url + QueryString.
var fullUrl = httpRequestBase.UrlReferrer.ToString();
var questionMarkIndex = fullUrl.IndexOf('?');
string queryString = null;
var url = fullUrl;
if (questionMarkIndex != -1) // There is a QueryString
{
url = fullUrl.Substring(0, questionMarkIndex);
queryString = fullUrl.Substring(questionMarkIndex + 1);
}
// Arrange.
var request = new HttpRequest(null, url, queryString);
var response = new HttpResponse(new StringWriter());
var httpContext = new HttpContext(request, response);
var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
if (routeData == null) throw new AuthenticationRedirectToReferrerDataNotFoundException();
// Extract the data.
var previousValues = routeData.Values;
previousAreaName = previousValues["area"] == null ? string.Empty : previousValues["area"].ToString();
previousControllerName = previousValues["controller"] == null ? string.Empty : previousValues["controller"].ToString();
previousActionName = previousValues["action"] == null ? string.Empty : previousValues["action"].ToString();
if (previousActionName != string.Empty) return;
var routeDataAsListFromMsDirectRouteMatches = (List<RouteData>)previousValues["MS_DirectRouteMatches"];
var routeValueDictionaryFromMsDirectRouteMatches = routeDataAsListFromMsDirectRouteMatches.FirstOrDefault();
if (routeValueDictionaryFromMsDirectRouteMatches == null) return;
previousActionName = routeValueDictionaryFromMsDirectRouteMatches.Values["action"].ToString();
if (previousActionName == "") previousActionName = "Index";
}
Here is a lightweight way to do this without creating response objects.
var values = RouteDataContext.RouteValuesFromUri(Request.UrlReferrer);
var controllerName = values["controller"];
var actionName = values["action"];
Uses this custom HttpContextBase class
public class RouteDataContext : HttpContextBase {
public override HttpRequestBase Request { get; }
private RouteDataContext(Uri uri) {
var url = uri.GetLeftPart(UriPartial.Path);
var qs = uri.GetComponents(UriComponents.Query,UriFormat.UriEscaped);
Request = new HttpRequestWrapper(new HttpRequest(null,url,qs));
}
public static RouteValueDictionary RouteValuesFromUri(Uri uri) {
return RouteTable.Routes.GetRouteData(new RouteDataContext(uri)).Values;
}
}
#gordon's solution works, but you need to use
return RedirectToAction(actionName.ToString(), controllerName.ToString(),values);
if you want to go to previous action
The RouteData object can access this info:
var controller = RouteData.Values["controller"].ToString();
var action = RouteData.Values["action"].ToString();
This is a method I made to extract url simplified from referrer because I had token (finished with "))/") in my URL so you can extract easily controller and action from this:
private static string GetURLSimplified(string url)
{
string separator = "))/";
string callerURL = "";
if (url.Length > 3)
{
int index = url.IndexOf(separator);
callerURL = url.Substring(index + separator.Length);
}
return callerURL;
}
I don't believe there is any built-in way to retrieve the previous Controller/Action method call. What you could always do is wrap the controllers and action methods so that they are recorded in a persistent data store, and then when you require the last Controller/Action method, just retrieve it from the database (or whatever you so choose).
Why would you need to construct ActionLink from a url ? The purpose of ActionLink is just the opposite to make a url from some data. So in your page just do:
var fullUrl = Request.UrlReferrer.ToString();
Back