Control web session using c# - c#

I have a web portal that I'm trying to pass information to another website. When the user clicks on a link I'd like to load the new web page and stuff the two form fields with information then SUBMIT to automate a process.
I found this: Autofill 2 Fields on a Web Page with C#
However, this assumes I open a new webbrowser control but instead I want to use the current web session.
Is this possible or is there another way to accomplish this?
Thanks!

Use WebClient class. Place it inside onclick event of your link.
var client = new System.Net.WebClient();
string url = "www.mysite.com?a=xyz&b=123";
cli.Downloadstring(url);

Related

WPF redirect to a page with POST request body

I have a simple WPF application with a button. When I click the button, I want to open the URL in the default browser and pass some data through POST body.
I know how to do that with GET, but what I want is using POST method.
Example:
Uri uri = new Uri("http://mypage.com");
string data = somedata;
// what to do next to redirect with POST method?
Note: I want to open the page in the user's default browser but not the .NET browser control.
Try using Process.Start(uri); it will detect the protocol (http) and open the default app for that protocol which will be your browser.
But that will result in a GET. Maby its better to use a WebRequest or RestAPI.

Logging in to a website with C#

I'm sorry if this subject has already been answered, but I couldn't find what I needed (yet).
I'm working on a program that downloads files from university websites that use the same infrastructure. It's an open source project which I'm trying to support in my free time
(hosted in goodle code: http://code.google.com/p/highlearner/)
Until now we used GET and POST requests to login into the right page and download stuff. But the universities keep changing their websites and every little change requires teaking in Highlearner, which requires a new version, auto-updating all users, etc. Also, every university has its own login page, requiring me to tailor a login sequences..
So I'm looking for a more robust solution. Instead of manually redirecting and setting the HTTP parameters. Is there some kind of mini browser that supports with HTML + Javascript? No GUI is needed, I just need the engine.
This way, I will simply need to fill out the form parameters and let the browser do the work.
Thanks,
Nitay
You could try to automate the process with WatiN library . It allows you to click buttons, submit forms, etc.
using (var ie = new IE(loginUrl))
{
if (ie.TextField("username").Exists
&& ie.TextField("password").Exists)
{
ie.TextField("username").Value = "username";
ie.TextField("password").Value = "password";
ie.Button(Find.ByName("submit")).Click();
}
}

Facebook C# SDK Authorization Problem

I have an iFrame Facebook application. I am using the Facebook C# SDK, Facebook and Facebook.Web libraries.
When a user first comes to my application I create a FacebookApp object on page_load(). If the app.Session is null I create a CavasAuthorizer(app) then call Authorize().
Two problems:
First, the redirect URL that is generated by calling Authorize causes Facebook to error with a bad "next" parameter. Says the "next" parameter is not owned by the application. It looks like this:
next=http://localhost:4002/facebookredirect.axd/mygame_dev/mygame.aspx
I can edit the code in CanvasURLBuilder to make the next look like this:
next=http://localhost:4002/mygame.aspx
At this point the URL works if I cut and paste into a browser however it brings me to my second issue.
When the code runs the user is presented with a mostly empty page with a mid-sized Facebook image and a link "go to Facebook". When the user clicks on the link it then takes the user to the correct authorization page for my application.
I have a feeling these are two possibly related issues but potentially separate.
Any help here would be greatly appreciated.
-Andy
For the first problem
Make sure the site Url in the app configuration page is set to http://apps.facebook.com/[your_app]/
For the second problem.
When you are not authorized you are redirected to the login url but you can't do it from your iframe since it will redirect the iframe and you will get a Facebook inside facebook.
You should use window.top.location = ... to redirect the parent window.
EDIT
Facebook C# SDK Already does this for you when using the Mvc part of the SDK. Since you are using webforms you should use this code that is the equivalent.
protected void Page_Load(object sender, EventArgs e)
{
var fb = new FacebookApp();
var auth = new CanvasAuthorizer(fb);
if (!auth.IsAuthorized())
{
var url = auth.GetLoginUrl(new HttpRequestWrapper(Request));
var content = CanvasUrlBuilder.GetCanvasRedirectHtml(url);
Response.ContentType = "text/html";
Response.Write(content);
Response.End();
return;
}
//...Go on if authorized
}
To test locally make sure your Site URL and Canvas URL in facebook is something like http://localhost:8181/yourpage. Then make sure in VS you set the setting under project properties\Web so that ports are not dynamically generated and you can use 8181 (or whatever port you like, as long as it is the same as in FB).
I think your Callback url in your web config is pointing to localhost. You can't do that since the code actually runs inside of Facebooks IFrame. Localhost is localhost to the facebook web server. You will have to give a valid url in the Callback key in your web.config. If you don't have a domain you can map to your ip then check out any of the free dynamic dns clients out there. No-ip is one exammple (and one I use personally).

Accessing a master page from httphandler

I am developing a small application in asp.net (writing in c#).
In my application I am using jquery to perform asynchronous call to the server.
I have an http handler that listens in to the requests and does what it needs to do.
Problems start when in the handler I need to access information stored in the page , from where the asynchronous call started. When I try this:
Page page = HttpContext.Current.Handler as Page;
I don't get a page.
How else can I access the page itself?
Thank you
You have a slight design issue. The Page class IS an HttpHandler. It is in fact the default HttpHandler that handles requests. When you define your own HttpHandler, there is no Page class... and hence no Master either.
If you need to access information from a different page, you need to do that via the normal ASP.NET mechanisms... Session, Cache, etc.
You can create new instance of page.
SomePage page = new SomePage();

How to POST Data to another web application (cross domain)

Please consider the following scenario,
There are two web applications App1 & App2. A user would submit his information on App1 though a form. On click of a specific button/link on App1, the same data should be posted to a page on App2 and the user should also be redirected to the same page on App2.
I would like some help in finding out the best way to implement this functionality.
One of the approaches that I have already tried out is by creating a temporary HTML form at runtime, setting the action attribute of the form to the App2 Page and get the form posted by using javascript submit. The data can then be fetched on App2 page by using the response.form object.
This approach works well, but i was still wondering if there is any other way to implement the required functionality.
I would really appriciate if you can give some insights on using RESTful webservices to implement this, or else, using some HttpModule to intercept requests at App1 and modify redirect response to app2 or any other approach that you might find fit for the purpose.
Edit:
Using querystring isnt an option for me.
I've had a need to do similar things with feed agregation and building rss feeds from web page content on different domains.
User Gets app1 page, fills in details and submits then on the server for app1 I have a method that looks like this ...
HTMLDocument FetchURL( string url )
{
WebClient wc = new WebClient();
string remoteContent = wc.DownloadString(url);
// mshtml api is very weird but lets just say you have to do things this way ...
HtmlDocument doc = new HTMLDocument();
IHTMLDocument2 doc2 = (IHTMLDocument2)doc;
doc2.write(new object[] { remoteContent });
return (HTMLDocument)doc2;
}
This function does 2 things of use ...
It gets the page of content at "url"
It parses that content in to a HTMLDocument object
Once you have this function you can then call it passing it the url to the remote page and get back a html doucment.
The functions in the HTMLDocument object will allow you to do javascript like dom queries such as :
docObject.GetElementById("id");
I then have different functions that do different things with this object based on the page / site i'm returning data from.
There is however one fatal flaw here ...
This is likely to work really well with sites that don't change much in structure and are built by code but not so well on less dynamic sites.
With stackoverflow for example its easy to pull out a question and the accepted answer for that question so I could use this code to pull and publish content from here on my own web site.
However ...
This is not going to help you for user / login related details as this sort of information is not shared to generally everyone.
It's bit like me going and trying this to link facebook profiles to my own website, I would have to go through some form of api that asked the user to authenticate their details before making the request.
simply pulling a web page based on a url only will give the other site no authentication information unless that site accepts the user login details in the quesrystring and you already have them.
You may however be able to chain requests by ripping apart my sample method, requesting the login page parsing the results, filling in the form, then posting back using the same web client instance to login then requesting the url.
The idea being that you would have a form that asks the user to put in their login details for the remote site on your site then you go and find their profile page based on that.
This would be best farmed out to a class rather than just a simple method like i have here.
In my case though i was only after something simple (the bbc top 40 uk charts) which i pulled information from not only the bbc but places like amazon, google, and youtube, then i built a page :)
It's neat but serves no functional purpose other than pulling all your other fave sources of info on to 1 page.
If you are already committed to using javascript, then why not an ajax post, and change the window.location based on the response?
You can use HttpServerUtility.Transfer this will preserve your form contents and transfer the user to the new page.
http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.transfer.aspx
I have built something like what you are describing, and I found that using a <form> tag to POST to app2 is the most reliable way... basically, the way you found that worked well.
If App2 is residing on a different domain, it's usually best to create your own interface for the submission, and have that interface handle the posting from App1 to App2.
(Browser) -> Submits form to App1 ->
(App1) -> validate input
-> stores local info
-> creates an HttpRequest/POST object
-> posts to App2
(App2) -> handles the post
<- returns the response
-> confirms the results of App2
<- returns the results to the browser.
In essense, you want to control and proxy requests from your Applications domain to any outside interfaces as much as possible.
Note: I'm answering my own question
just to have a correct answers marked
against it. All the suggestions
provided by various members here are
correct in their own way, but they
were not apt for my requirements.
Hence, I cant accept any of them as
correct.
The way I have Implemented is by creating a custom control which would have a configurable property containing the URL to post data and another one accepting a dictionary object as the data input to be posted.
This control would internally create a HTML form with action attribute set to the URL specified by the user and have the data feilds created out of the dictionary object. This form would then be posted on the button click event on the page hosting this control.

Categories