Add incoming querystring to all outgoing links/traffic c# - c#

If i have a page called www.testsite.com and I link to that page using a querystring in the url, is it possible to attach that same querystring to all the outgoing links/traffic somehow?
For instance, say I link to that page like this www.testsite.com?parameter1=somevalue
And then, on that page I click a link to for instance google, and I would like the parameter to be passed so the url would be www.google.com?parameter1=somevalue.
I know how to do this manually, but is there someway it can be appended to the url automatically? Like catch the outgoing request before happening and add the parameter?
Thanks!
Eric

you could do this pretty simply with javascript or javascript using jQuery
$("a").click(function(e){
e.preventDefault();
window.location = $(this).attr("href") + window.location.search;
});
that should get you started
if you wanted a non-jQuery solution you can look into binding events using javascript only
http://www.digimantra.com/tutorials/change-onclick-function-anchor-tag-javascript/
http://forums.techarena.in/software-development/1308647.htm

You can implement an intercepting filter through an httpmodule which modifies the html you emit back to the client. For more details see: http://msdn.microsoft.com/en-us/library/ff649096.aspx
And a few more examples:
Http Response Filter
SO: Get HTML content for modification

Unless you have a central location where you output the outgoing links, you will have to do this manually (possibly the visual studio search/replace can help here, but I would be careful as you may end up changing links you didn't want to).

You can use following to use Query String parameters
You can loop through all your query string parameters like this
int loop1, loop2;
// Load NameValueCollection object.
NameValueCollection coll = Request.QueryString;
// Get names of all keys into a string array. String[] arr1 = coll.AllKeys;
string parameters = "";
for (loop1 = 0; loop1 < arr1.Length; loop1++)
{
parameters += Server.HtmlEncode(arr1[loop1]) + "=" + coll.GetValues(arr1[loop1]);
for (loop2 = 0; loop2 < arr2.Length; loop2++)
{
parameters += Server.HtmlEncode(arr2[loop2]);
}
}
its just basic idea. But you can loop through parameters without knowing the names.

Related

How do I send a URL with Query Strings as a Query String

I am doing a redirect from one page to another and another redirect from the second page to a third. I have imformation from the first page which is not used on the second page but must be transfered to the third page. Is it possible to send the URL of the third page with its Query Strings as a Query String to the second page. Here's an example:
Response.Redirect("MyURL1?redi=MyURL2?name=me&ID=123");
My problem is that the URL being sent as a Query String has two Query String variables, so how will the system know that what's after the & is the second variable of the second URL and not a second variable of the first URL? Thank you.
You must encode the url that you pass as a parameter in your redirect URL. Like this:
MyURL = "MyURL1?redi=" + Server.UrlEncode("MyURL2?name=me&ID=123");
This will create a correct url without the double '?' and '&' characters:
MyURL1?redi=MyURL2%3fname%3dme%26ID%3d123
See MSDN: HttpServerUtility.UrlEncode Method
To extract your redirect url from this encoded url you must use HttpServerUtility.UrlDecode to turn it into a correct url again.
Your query string should look like this:
MyURL1?redi=MyURL2&name=me&ID=123
Check: http://en.wikipedia.org/wiki/Query_string
You should have one ? sign and all parameters joined with &. If parameter values contain special characters just UrlEncode them.
I find it helpful to encode query string parameters in Base64 before sending. In some cases this helps, when you need to send all kinds of special characters. It doesn't make for good debug strings, but it will protect ANYTHING you are sending from getting mixed with any other parameters.
Just keep in mind, the other side who is parsing the query string will also need to parse the Base64 to access the original input.
using System.IO;
using System.Net;
static void sendParam()
{
// Initialise new WebClient object to send request
var client = new WebClient();
// Add the QueryString parameters as Name Value Collections
// that need to go with the HTTP request, the data being sent
client.QueryString.Add("id", "1");
client.QueryString.Add("author", "Amin Malakoti Khah");
client.QueryString.Add("tag", "Programming");
// Prepare the URL to send the request to
string url = "http://026sms.ir/getparam.aspx";
// Send the request and read the response
var stream = client.OpenRead(url);
var reader = new StreamReader(stream);
var response = reader.ReadToEnd().Trim();
// Clean up the stream and HTTP connection
stream.Close();
reader.Close();
}

twitter streaming API location

I'm trying to implement a twitter stream viewer in C#, my problem doesn't lie within C# itself.
I'm just trying to use the geo-location boxing capability of twitter's streaming API. I'm trying to send a request in this form
private string url = #"https://stream.twitter.com/1/statuses/filter.json?track=";
and then I append my parameters
for (int i = 0; i < keywords.Count; i++)
{
url += keywords[i].ToString() + "%2C";
}
Up until this, the query works fine, it stops working when I add this
url += #"&locations=" + location;
Where, location variable has the value
-121.75,36.8,-122.75,37.8
So I'm ending up with the query looking like this
https://stream.twitter.com/1/statuses/filter.json?track=twitter%2Cfacebook%2Ciphone&locations=-121.75,36.8,-122.75,37.8
I'm getting a response 406 Not Acceptable, any ideas why?
Try replacing the & with a standard ampersand.

How to read the query string when it contains unencoded data?

I have the below asp.net page which accepts a "url" query string key whose value can be an un-encoded url:
http://localhost:4104/WebSiteForTest/TinyUrl.aspx?url=http://www.google.co.uk/#hl=en&q=life&oq=life&aq=f&aqi=g-s1g9&aql=&gs_sm=3&gs_upl=2803373l2803701l2l2803826l4l4l0l0l0l0l188l453l0.3l3l0&bav=on.2,or.r_gc.r_pw.r_cp.,cf.osb&fp=94681dc4659502d1&biw=1680&bih=883
Now from this page, how would that be possible to read the text after ".aspx?"?
I checked the Request.Url.AbsoluteUri property and it only showed
"http://localhost:4104/WebSiteForTest/TinyUrl.aspx?url=http://www.google.co.uk/"
I also checked with the Request.QueryString with the below code:
private void getQueryString()
{
var sb = new StringBuilder();
var queryStringCount = Request.QueryString.Keys.Count;
for (int keyIndex = 0; keyIndex < queryStringCount; keyIndex++)
{
sb.Append(Request.QueryString.Keys[keyIndex]).Append("=").Append(Request.QueryString[keyIndex]);
if (keyIndex != (queryStringCount - 1))
{
sb.Append("&");
}
}
}
However, the code after "#" doesn't appear in any query string.
how would that be possible to read the text after ".aspx?"?
if you say it's not possible, how Google uses "#" in their url then when you search for something?!
http://www.google.co.uk/#hl=en&site=&q=life&oq=life&aq=f&aqi=g-s1g9&aql=&gs_sm=3&gs_upl=3317l3630l0l3755l4l4l0l0l0l0l125l391l3.1l4l0&bav=on.2,or.r_gc.r_pw.r_cp.,cf.osb&fp=94681dc4659502d1&biw=1680&bih=849
Thanks,
It's not possible to get value after anchor on server side, you can check this with fiddler or something similar, you should deal with this on client. Browser simply strips all after anchor.
Retrieving Anchor Link In URL for ASP.Net
c# get complete URL with "#"
Update:
I don't know how google exactly do this, but if you look with fiddler after initial request there goes another without #, here is a fidller log for request from your question :
so my advice is look with fiddler how google do this, or maybe ask another question
Use Request.QueryString
http://localhost:4104/WebSiteForTest/TinyUrl.aspx?url=http://www.google.co.uk/#hl=en&q=life&oq=life&aq=f&aqi=g-s1g9&aql=&gs_sm=3&gs_upl=2803373l2803701l2l2803826l4l4l0l0l0l0l188l453l0.3l3l0&bav=on.2,or.r_gc.r_pw.r_cp.,cf.osb&fp=94681dc4659502d1&biw=1680&bih=883
<%=Request.QueryString("url")%> will get the ?url parameter
I assume you're using C# to do this. You can easily get the parameters and their values by iterating through the request object. Or in this case, since you know the name of the parameter, simply do this:
String url = Request.QueryString["url"];
More information on iterating through your request parameters can be found here.
The Uri Type works as well.
String yourHttpUri ="....";
Uri yourURI = new Uri(yourHttpUri);
yourURI.query // "?url=http://www.google.co.uk/"
yourURI.fragment // "#hl=en&q=life&oq=life&aq=f&aqi=g-s1g9&aql=&gs_sm=3&gs_upl=2803373l2803701l2l2803826l4l4l0l0l0l0l188l453l0.3l3l0&bav=on.2,or.r_gc.r_pw.r_cp.,cf.osb&fp=94681dc4659502d1&biw=1680&bih=883"
Edit:
Have you tried Request.Url.ToString(); (And create a new Uri from the result)

HttpWebRequest with POST and GET at the same time

I need to redirect a user to http://www.someurl.com?id=2 using a POST method.
Is it possible? If yes, then how?
Right now I have following and it forwards the POST data properly, but it removes the ?id=2:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.someurl.com?id=2");
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(postData);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Response.Write(reader.ReadToEnd());
}
The reason I need both query string data -> ?id=2 and POST data is because I pass the query string to page in which javascript is going to be handling the query string data and .NET is going to work with data sent via POST method. The POST data that I am passing can be longer than maximum amount of characters that GET method allows, therefore I can't use only GET method... so, what are your suggestions?
More information:
I am writing a routing page, which adds some custom information to query string and then routes all of the data, old and new further to some URL that was provided. This page should be able to redirect to our server as well as to someone's server and it doesn't need to know where it came from or where it goes, it just simply needs to keep the same POST, GET and HEADER information as well as additional information received at this step.
No. There is no fathomable reason to mix POST and GET.
If you need to make parameters passed in with the request available to Javascript, simply POST them to the server, and have the server spit out the relevant information in a hidden field...
<input type="hidden" value="id=2,foo=bar" disabled="disabled" />
Simple as that.
Note: Disable the hidden field to exclude it from the subseqient POST, if there is one ;)
The problem i think that the problem could be that postData does not contain the id parameter as it is supplied through querystring.
Posted data is in the body of the request and querystring data is in the url.
You probably need to fetch the id from request.querystring to you postdata variable.
Given the extra information to your question, that you require to submit to an external source, what I believe you must do is process all of the data and return a form with hidden fields. Add some javascript to submit that form to the external URL immediately upon load. Note that you won't get file uploads this way, but you can appropriately handle POST and GET data.
As far as I know, it isn't possible to redirect with POST. Couldn't you simply pretend (internally handle as if) that the request was made to the page you want to redirect the user to?
The closest answer I've found to this problem is here, but it's not transparent to the user, therefore it's not good enough for me --> Response.Redirect with POST instead of Get?
If anybody has any other suggestions, please respond!
Try sending all of the data including the id in POST. Then when you are processing the data in C#, you can read the id variable in and write it back out to your webpage within a tag:
<script type="text/javascript">
id = <%=request_id%>
</script>
Then just make sure your javascript starts running after fully loaded with an onload() call and you're good to go.
What you are actually trying to do is redirect your POST data. May I ask why? I can't see any reason why you would want to do this if in fact both pages are on your servers.
What you should be doing is processing all of your POST data in script #1, and then redirecting to something like script2.aspx?id=234 where the ID 234 is in reference to the data in your database. You can then recall it later on script2 and dump all the data into Javascript variables for your client-side stuff to use.
Either way, something about this process sounds fishy to me. Mixing up your data processing client-side and server side is like mixing vodka and milk. It rarely works well. (But white russians sure are tasty!)
Actually I was able to achieve the desired result by mixing Javascript and Codebehind code. So, what I've done is in server side code I've built an entire web page like following:
var strForm = new StringBuilder();
strForm.Append("<form id=\"" + formId + "\" name=\"" + formId + "\" action=\"" + url + queryString +"\" method=\"POST\">");
foreach (string key in data)
{
strForm.Append("<input type=\"hidden\" name=\"" + key + "\" value=\"" + data[key].Replace("\"", """) + "\">");
}
strForm.Append("</form>");
And in addition to this form built on server side, I add a javascript code that submits the form I've just built.
var strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var v" + formId + " = document." + formId + ";");
strScript.Append("v" + formId + ".submit();");
strScript.Append("</script>");
strForm.Append("</form>");
So, what this code does, is as you see, the form action is an URL with query string parameters attached to it... but since the form method is POST, we submit the values we added as a hidden fields as POST parameters... So we end up submitting both POST and GET parameters.
Hope this solution will help somebody =)

C# HTTP programming

i want to build a piece of software that will process some html forms, the software will be a kind of bot that will process some forms on my website automatically.
Is there anyone who can give me some basic steps how to do this job...Any tutorials, samples, books or whatever can help me.
Can some of you post an working code with POST method ?
Check out How to: Send Data Using the WebRequest Class. It gives an example of how create a page that posts to another page using the HttpWebRequest class.
To fill out the form...
Find all of the INPUT or TEXTAREA elements that you want to fill out.
Build the data string that you are going to send back to the server. The string is formatted like "name1=value1&name2=value2" (just like in the querystring). Each value will need to be URL encoded.
If the form's "method" attribute is "GET", then take the URL in the "action" attribute, add a "?" and the data string, then make a "GET" web request to the URL.
If the form's "method" is "POST", then the data is submitted in a different area of the web request. Take a look at this page for the C# code.
To expand on David and JP's answers':
Assuming you're working with forms whose contents you're not familiar with, you can probably...
pull the page with the form via an HttpWebRequest.
load it into an XmlDocument
Use XPath to traverse/select the form elements.
Build your query string/post data based on the elements.
Send the data with HttWebRequest
If the form's structure is known in advance, you can really just start at #4.
(untested) example (my XPath is not great so the syntax is almost certainly not quite right):
HttpWebRequest request;
HttpWebResponse response;
XmlDocument xml = new XmlDocument();
string form_url = "http://...."; // you supply this
string form_submit_url;
XmlNodeList element_nodes;
XmlElement form_element;
StringBuilder query_string = new StringBuilder();
// #1
request = (HttpWebRequest)WebRequest.Create(form_url));
response = (HttpWebResponse)request.GetResponse();
// #2
xml.Load(response.GetResponseStream());
// #3a
form_element = xml.selectSingleNode("form[#name='formname']");
form_submit_url = form_element.GetAttribute("action");
// #3b
element_nodes = form_element.SelectNodes("input,select,textarea", nsmgr)
// #4
foreach (XmlNode input_element in element_nodes) {
if (query_string.length > 0) { query_string.Append("&"); }
// MyFormElementValue() is a function/value you need to provide/define.
query_string.Append(input_element.GetAttribute("name") + "=" + MyFormElementValue(input_element.GetAttribute("name"));
}
// #5
// This is a GET request, you can figure out POST as needed, and deduce the submission type via the <form> element's attribute.
request = (HttpWebRequest)WebRequest.Create(form_submit_url + "?" + query_string.ToString()));
References:
Link
http://www.developerfusion.com/forum/thread/26371/
http://msdn.microsoft.com/en-us/library/system.xml.xmlelement.getattribute.aspx
http://msdn.microsoft.com/en-us/library/system.xml.xmlelement.selectnodes.aspx
If you don't want to go the HttpWebRequest route, I would suggest WatiN. Makes it very easy to automate IE or Firefox and not worry about the internals of the HTTP requests.

Categories