How to edit URL with Fiddler(script)? - c#

I want to edit a URL using fiddler. Doesn't have to be with fiddler script, but heres an approximation of how I'm doing it currently:
if (oSession.url.contains("example.com") {
String oldUrl = oSession.url.ToString();
Regex rgx = new Regex("1.2");
String newUrl = rgx.Replace(oldUrl, "1.0");
}
This code is giving me a compiler error on the regex instantiation line: "The list of attributes does not apply to the current context". I'm not entirely sure what this means.
I'm also unsure how exactly to change the url.
Any ideas?

Just got it:
oSession.url = oSession.url.Replace("1.2","1.0");

You can also use
oSession.PathAndQuery = oSession.PathAndQuery.replace('/test1/', '/changed1/');

Related

Bug? System.UriFormatException: Invalid URI: The URI scheme is not valid

The strings are identical but when passed as a variable it is not valid?
What the hell is going on? Is it a language bug? I'm running this in C# .Net Core
var postUrl = "​http://www.contoso.com";
var postUri = new Uri("http://www.contoso.com"); // works
var uri = new Uri(postUrl); // does not work
If you pulling your hair, then it because there is space after first opening quote in postUrl. Please remove that space & your bug will be begone.
Worked around the problem by using.
var postUrl = "​http://www.contoso.com";
var uriBuilder = new UriBuilder(postUrl);
var uri = uriBuilder.Uri
Still wondering wtf?
Just the daily wtf of a programmer doing his job.

Uri.EscapeDataString or HttpUtility.UrlEncode does not work for my case

I have an API in a project which I coded as following:
[Route("api/SearchCustomer/{customer}")]
[HttpGet]
public List<Customer> SearchCustomer(string customer)
{
return customerRepo.GetSearchJoined(customer);
}
At first, I got an issue when I am calling this API from my front end, if customer contains dot or space(for example: https://www.somesite.com/walmart Inc.), I will get 404 error(cannot found this API). I find an easy way to solve this problem. Just add a "/" will solve this problem.(https://www.somesite.com/walmart Inc./ )
Now I need to call this API in another project at the back end. So I did something like this:
var urlParm = "https://www.somesite.com/api/SearchCustomer/" + name + "/";
response = client.GetAsync(urlParm).Result;
var dataObjects = response.IsSuccessStatusCode ? response.Content.ReadAsAsync<IList<Customer>>().Result : null;
return dataObjects;
Unfortunately, adding the "/" at back does not work. I am still getting 404 error. Then, I tried to use Uri.EscapeDataString or HttpUtility.UrlEncode to encode "name".(Does C# have an equivalent to JavaScript's encodeURIComponent()?)
name = Uri.EscapeDataString(name)
or name = HttpUtility.UrlEncode(name)
or name = HttpUtility.UrlPathEncode(name)
var urlParm = "https://www.somesite.com/api/SearchCustomer/" + name + "/";
or var urlParm = = "https://www.somesite.com/api/SearchCustomer/" + name
response = client.GetAsync(urlParm).Result;
var dataObjects = response.IsSuccessStatusCode ? response.Content.ReadAsAsync<IList<Customer>>().Result : null;
return dataObjects;
I have tried all the different matches of above code. All of them did not work. I am still getting the 404 error. Does anyone know what I am doing wrong here?
Sorry for the typo, I removed some sensitive information so I deleted the "api" by mistake. The route is not the problem. I have tested that the api call from the back end worksif name contains only letters or numbers but fails when name contains dot.
The problem is not relevant the customer parameter is encoded or not. You should specify the routing and apply the request correctly. Firstly fix the route;
[Route("api/SearchCustomer/{customer}")]
Then apply the request.
https://www.somesite.com/api/SearchCustomer/samplecustomer

Using Regex to insert domain name into url

I am pulling in text from a database that is formatted like the sample below. I want to insert the domain name in front of every URL within this block of text.
<p>We recommend you check out the article
<a id="navitem" href="/article/why-apples-new-iphones-may-delight-and-worry-it-pros/" target="_top">
Why Apple's new iPhones may delight and worry IT pros</a> to learn more</p>
So with the example above in mind I want to insert http://www.mydomainname.com/ into the URL so it reads:
href="http://www.mydomainname.com/article/why-apples-new-iphones-may-delight-and-worry-it-pros/"
I figured I could use regex and replace href=" with href="http://www.mydomainname.com but this appears to not be working as I intended. Any suggestions or better methods I should be attempting?
var content = Regex.Replace(DataBinder.Eval(e.Item.DataItem, "Content").ToString(),
"^href=\"$", "href=\"https://www.mydomainname.com/");
You could use regex...
...but it's very much the wrong tool for the job.
Uri has some handy constructors/factory methods for just this purpose:
Uri ConvertHref(Uri sourcePageUri, string href)
{
//could really just be return new Uri(sourcePageUri, href);
//but TryCreate gives more options...
Uri newAbsUri;
if (Uri.TryCreate(sourcePageUri, href, out newAbsUri))
{
return newAbsUri;
}
throw new Exception();
}
so, say sourcePageUri is
var sourcePageUri = new Uri("https://somehost/some/page");
the output of our method with a few different values for href:
https://www.foo.com/woo/har => https://www.foo.com/woo/har
/woo/har => https://somehost/woo/har
woo/har => https://somehost/some/woo/har
...so it's the same interpretation as the browser makes. Perfect, no?
Try this code:
var content = Regex.Replace(DataBinder.Eval(e.Item.DataItem, "Content").ToString(),
"(href=[ \t]*\")\/", "$1https://www.mydomainname.com/", RegexOptions.Multiline);
Use html parser, like CsQuery.
var html = "your html text here";
var path = "http://www.mydomainname.com";
CQ dom = html;
CQ links = dom["a"];
foreach (var link in links)
link.SetAttribute("href", path + link["href"]);
html = dom.Html();

Special character replacement from code of the apostrophe in a file name path

The problem I'm having is in regards to a file that is being generated on the server and the .NET code is invoking a Javascript method to download a file to the client, but it fails if the file name has an apostrophe (').
So for example:
If the ExportExcelFileName = "C:\HereIsMyFile.xls" it works fine.
However, if the
ExportExcelFileName = "C:\Here'sMyFile.xls"
it throws a failure to evaluate exception.
I tried adding [.Replace("'", "\\'")] and [.Replace("'", "%27")] but no luck...
string script = string.Format("DownLoadFile('{0}')", e.Result.ExportExcelFileName).Replace('\\', '/');
HtmlPage.Window.Eval(script);
I figured it out:
when I tried this:
string script = string.Format("DownLoadFile('{0}')", e.Result.ExportExcelFileName).Replace('\\', '/').Replace("'", "\\'");
HtmlPage.Window.Eval(script);
It was also replacing the single quotes in the javascript command of DownloadFile('{0}').
So I simply did the replacement first like so:
var escapedFileName = ((e.Result.ExportExcelFileName).Replace('\\', '/')).Replace("'", "\\'");
string script = string.Format("DownLoadFile('{0}')", escapedFileName);
HtmlPage.Window.Eval(script);
Would a simple method like this work?
private static string quoteReplace(string psString)
{
return psString.Replace("'", "");
}
Try using URI escaping for the file name:
Uri.EscapeDataString(filePathHere);. See Uri.EscapeDataString on MSDN.
Also see: If filename has single quote C# javascript does not get executed

Validate folder name in C#

I need to validate a folder name in c#.
I have tried the following regex :
^(.*?/|.*?\\)?([^\./|^\.\\]+)(?:\.([^\\]*)|)$
but it fails and I also tried using GetInvalidPathChars().
It fails when i try using P:\abc as a folder name i.e Driveletter:\foldername
Can anyone suggest why?
You could do that in this way (using System.IO.Path.InvalidPathChars constant):
bool IsValidFilename(string testName)
{
Regex containsABadCharacter = new Regex("[" + Regex.Escape(System.IO.Path.InvalidPathChars) + "]");
if (containsABadCharacter.IsMatch(testName) { return false; };
// other checks for UNC, drive-path format, etc
return true;
}
[edit]
If you want a regular expression that validates a folder path, then you could use this one:
Regex regex = new Regex("^([a-zA-Z]:)?(\\\\[^<>:\"/\\\\|?*]+)+\\\\?$");
[edit 2]
I've remembered one tricky thing that lets you check if the path is correct:
var invalidPathChars = Path.GetInvalidPathChars(path)
or (for files):
var invalidFileNameChars = Path.GetInvalidFileNameChars(fileName)
Validating a folder name correctly can be quite a mission. See my blog post Taking data binding, validation and MVVM to the next level - part 2.
Don't be fooled by the title, it's about validating file system paths, and it illustrates some of the complexities involved in using the methods provided in the .Net framework. While you may want to use a regex, it isn't the most reliable way to do the job.
this is regex you should use :
Regex regex = new Regex("^([a-zA-Z0-9][^*/><?\"|:]*)$");
if (!regex.IsMatch(txtFolderName.Text))
{
MessageBox.Show(this, "Folder fail", "info", MessageBoxButtons.OK, MessageBoxIcon.Information);
metrotxtFolderName.Focus();
}

Categories