How to get data from a client on load? - c#

I'm aware that data can be passed in through the URL, like "example.com/thing?id=1234", or it can be passed in through a form and a "submit" button, but neither of these methods will work for me.
I need to get a fairly large xml string/file. I need to parse it and get the data from it before I can even display my page.
How can I get this on page load? Does the client have to send a http request? Or submit the xml as a string to a hidden form?
Edit with background info:
I am creating a widget that will appear in my customer's application, embedded using C# WebBrowser control, but will be hosted on my server. The web app needs to pass some data (including a token for client validation) to my widget via xml, and this needs to be loaded in first thing when my widget starts up.

ASP.NET MVC 4 works great with jQuery and aJax posts. I have accomplished this goal many times by taking advantage of this.
jQuery:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/{controller}/{action}/",
data: { clientToken: '{token}', foo: 'bar',
success: function (data, text) {
//APPEND YOUR PAGE WITH YOUR PARSED XML DATA
//NOTE: 'data' WILL CONTAIN YOUR RETURNED RESULT
}
});
});
MVC Controller:
[HttpPost]
public JsonResult jqGetXML(string clientToken, string foo)
{
JsonResult jqResult = new JsonResult();
//GET YOUR XML DATA AND DO YOUR WORK
jqResult.Data = //WHATEVER YOU WANT TO RETURN;
return jqResult;
}
Note: This example returns Json data (easier to work with IMO), not XML. It also assumes that the XML data is not coming from the client but is stored server-side.
EDIT: Here is a link to jQuery's Ajax documentation,
http://api.jquery.com/jQuery.ajax/

Assuming you're using ASP.NET, since you say it's generated by another page, just stick the XML in the Session state.

Another approach, not sure if it helps in your situation.
If you share the second level domain name on your two sites (i.e. .....sitename.com ) then another potential way to share data is you could have them assert a cookie at this 2nd level with the token and xml data in it. You'll then be provided with this cookie.
I've only done this to share authentication details, you need to share machine keys at a minimum to support this (assuming .Net here...).

You won't be able to automatically upload a file from the client to the server - at least not via a browser using html/js/httprequests. The browser simply will not allow this.
Imagine the security implications if browsers allowed you to silently upload a file from the clients local machine without their knowledge.

Sample solution:
Background process imports xml file and parses it. The background process knows it is for customer YYY and updates their information so it know the xml file has been processed.
A visitor goes to the customer's web application where the widget is embedded. In the markup of the widget the customer token has been added. This could be in JavaScript, Flash, iFrame, etc.
When the widget loads, it makes a request to you app which then checks to see if the file was parsed for the provided customer (YYY) if it has, then show the page/widget.

If the XML is being served via HTTP you can use Liqn to parse the data.
Ex.
public partial class Sample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string url = "http://news.yahoo.com/rss/";
var el = XElement.Load(url).Elements("channel");
StringBuilder output = new StringBuilder();
foreach (var c in el.Elements())
{
switch (c.Name.LocalName.ToLower())
{
case "title":
output.Append(c.Value);
output.Append("<br />");
break;
}
}
this.Label1.Text = output.ToString();
}
}

It is not exactly clear what the application is and what kind of options you have, and what kind of control over web server you have.
If you are the owner of the web server/application your options are way wider. You can first send a file to web-server with HTTP POST or PUT, including a random token, and then use the same token for GET with token in the query string
or use other options, applicable to third party-owned websites
if you are trying to consume some auth api, learn more about it. since you are hosting web browser control, you have plenty of options to script it. including loading whatever form, setting textarea or hidden field text with your xml and then simulating a submit button click. you can then respond to any redirects and html responses.
you can also inject javascript inside the page that would send it to server with ajax request.
the choice heavily depends on the interaction model.
if you need better advice, it would be most helpful if you provided sample/simplified url/url pattern, form content, and sequence of events that is expected from you from code/api/sdk perspective. they are usually quite friendly.

There are limited number of ways to pass data between pages. Personally for this I would keep in session during the generating page and clear it when it is retrieved in the required page.
If it is generated server side then there is no reason to retrieve it from client side.
http://msdn.microsoft.com/en-us/library/6c3yckfw(v=vs.100).aspx

Create a webservice that your C# app can POST the XML to and get back HTML in response. Load this HTML string into the WebBrowser control rather than pointing the control to a URL.

Related

Parse page using AngleSharp

I want to parse website using c# with AngleSharp, it's easy to do with static pages, but there is a problem, I can't parse info avalible only for authorized users. What should I do to autorize programmatically into website and parse all info avalible for me?
Depending on the used authorization scheme this may either be super simple or ultra hard / impossible.
So let's first visit what can be done with AngleSharp:
Any kind of requests incl. their manipulation (on request, but also before response)
General cookie management (and their manipulation, of course)
Querying the DOM and perform "simple" actions (e.g., clicking a button, submitting a form)
Running trivial JavaScript files
Here trivial means: Scripts that do not need any capabilities beyond what AngleSharp offers, e.g., rendering tree information, advanced CSSOM access, ... - or scripts that require non-ES5 compliant parsers (e.g., make use of ES6 or some special non-standard capabilities).
Now since I do not know what is the authorization scheme or exact problem that you are hitting (some code / MWE would be helpful!) I'll just go for a simple click example.
var context = BrowsingContext.New(Configuration.Default.WithDefaultLoader().WithCookies());
var loginPage = await context.OpenAsync("http://yourpage.com");
var loginForm = loginPage.QuerySelector<IHtmlFormElement>("form");
var profilePage = await loginForm.SubmitAsync(new { userName = "myUser", password = "password" });
// get something on profilePage
Note that in this example the form field names for the login form are userName and password - they may be different for your login page. Also note that your page may contain multiple forms and the selector could be more sophisticated than a simple form.
HTH!

unable to get complete url after # using query string in asp.net c# [duplicate]

I know on client side (javascript) you can use windows.location.hash but could not find anyway to access from the server side. I'm using asp.net.
We had a situation where we needed to persist the URL hash across ASP.Net post backs. As the browser does not send the hash to the server by default, the only way to do it is to use some Javascript:
When the form submits, grab the hash (window.location.hash) and store it in a server-side hidden input field Put this in a DIV with an id of "urlhash" so we can find it easily later.
On the server you can use this value if you need to do something with it. You can even change it if you need to.
On page load on the client, check the value of this this hidden field. You will want to find it by the DIV it is contained in as the auto-generated ID won't be known. Yes, you could do some trickery here with .ClientID but we found it simpler to just use the wrapper DIV as it allows all this Javascript to live in an external file and be used in a generic fashion.
If the hidden input field has a valid value, set that as the URL hash (window.location.hash again) and/or perform other actions.
We used jQuery to simplify the selecting of the field, etc ... all in all it ends up being a few jQuery calls, one to save the value, and another to restore it.
Before submit:
$("form").submit(function() {
$("input", "#urlhash").val(window.location.hash);
});
On page load:
var hashVal = $("input", "#urlhash").val();
if (IsHashValid(hashVal)) {
window.location.hash = hashVal;
}
IsHashValid() can check for "undefined" or other things you don't want to handle.
Also, make sure you use $(document).ready() appropriately, of course.
[RFC 2396][1] section 4.1:
When a URI reference is used to perform a retrieval action on the
identified resource, the optional fragment identifier, separated from
the URI by a crosshatch ("#") character, consists of additional
reference information to be interpreted by the user agent after the
retrieval action has been successfully completed. As such, it is not
part of a URI, but is often used in conjunction with a URI.
(emphasis added)
[1]: https://www.rfc-editor.org/rfc/rfc2396#section-4
That's because the browser doesn't transmit that part to the server, sorry.
Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX).
Regards
Artur
You may see also how to play with back button and browser history
at Malcan
Just to rule out the possibility you aren't actually trying to see the fragment on a GET/POST and actually want to know how to access that part of a URI object you have within your server-side code, it is under Uri.Fragment (MSDN docs).
Possible solution for GET requests:
New Link format: http://example.com/yourDirectory?hash=video01
Call this function toward top of controller or http://example.com/yourDirectory/index.php:
function redirect()
{
if (!empty($_GET['hash'])) {
/** Sanitize & Validate $_GET['hash']
If valid return string
If invalid: return empty or false
******************************************************/
$validHash = sanitizeAndValidateHashFunction($_GET['hash']);
if (!empty($validHash)) {
$url = './#' . $validHash;
} else {
$url = '/your404page.php';
}
header("Location: $url");
}
}

how to get return value from javascript to .cs page

// JScript File
function fnCheckBrowserType(var k)
{
if(k>0)
{
document.getElementByID('<%=HhdnBrowsertype.ClientID%>').value="1"
return true;
}
else
{
document.getElementByID('<%=HhdnBrowsertype.ClientID%>').value="0"
return false;
}
in.cs page load
Page.ClientScript.RegisterStartupScript(typeof(string), "fnCheckBrowserType", "fnCheckBrowserType();", true);
here i need to gets its return vale based on the return value "true " or "false"
i need to check the condition
pls help me to get the value from javascript to .cs page
thanks
prince
To send data to the server from the client, you have some options:
Send in a form.
Use Ajax.
Indirectly request a resource from the server and use a query string to send the information (for instance, adding an img element which uses a query string in its src). Not recommended, but possible and perhaps useful in some edge cases (for instance, when you need to send the data cross-origin and need to avoid the Same Origin Policy, as with many ad serving scripts).
Have the data piggy-back on your next normal request by setting a cookie.
Given the scenario you describe, Ajax may be your best option.

Receive data from PostBack in JavaScript

I'm using jQuery to make postback then in my .ascx file I have code like this:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
if (args.get_error() == undefined) {
var dataItems = args.get_dataItems();
alert(dataItems['ctl00_cphContent_articleList_tbUpdate']);
}
}
Where on the Internet can I find specification of args object? What methods has it got?
Second, why do I have to pass in my server side data into control using ScriptManager?
Code on the server side is:
ScriptManager.GetCurrent(this.Page).RegisterDataItem(tbUpdate, DateTime.Now.ToString());
and tbUpdate is the control on the site.
Is there any more elegant way to get access to data sent back to the client side. Do I have to send this data to any control? What does it really mean that data is sent to control?
How can I consume this data from that control? I had to use Firebug to find the id of the control and get access to it.
It sounds like you're trying to do an AJAX call to the server, and use the resulting data client side to either inject into an existing control, or create new controls for the data from the server.
I can only suggest you read these articles that explain how this works in far more detail than I can go into in an answer here:
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
and
http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
These are the clearest and most concise documents I have found on the subject.

Verify E-mails as they are typed

On my page a users (internal staff members) can type a comma separated list of e-mail addresses. What I would like to do is every time a comma is typed it checks that the newly written e-mail address is in the address book.
Currently I have the address book stored as a Hashtable for O(1) search times but I can easily switch to another data structure if it is recommended.
You can do that with JavaScript and AJAX to communicate with the server side.
You can do the next steps:
Create a web service that gets the string from the client (which is the email the user has typed), checks it and returns true/false.
Add [ScriptService] attribute to the
web service class.
On the page, add an ASP.NET
ScriptManager control with
Scripts/ScriptReference that points to the web service from step 1.
On the page, add javascript code that hooks to the onkeydown event of the emails textbox
In this event handler, if the user types a comma, execute a web service request to the server with the textbox value. When the respond (true or false) is received, do whatever you need with it.
You can read more on MSDN here and here.
You might also find helpful the AutoComplete AJAX extender.
In order for it to be done on keypress there is going to be javascript (or client side vbscript if you're using IE) involved. This cannot be done without it if you're looking to do it based on keyed input.
If you were to do it when the user leaves that text box, then you could use AutoPostback and code it in C# on the server side - I have to say though, I think that approach is ugly. Requiring a synchronous postback to validate data is a huge imposition on the user in my opinion and therefore should only really be a last resort or a stopgap while you're getting asynchronous script to do the work. You could also do it at post time (when they're trying to submit the form) and validate them and give the user back a validation message if any of the addresses fail, but once again, this is synchronous and the user doesn't get the benefit of early feedback.
I would do this using either a Windows Service (or use RESTful service) using a javascript call (using the XmlHttpRequest object). Bind your textbox's keydown event to a JavaScript method.
<input type="text" onKeyDown="javascript:CheckInput(this)" />
Then set up your javascript call - this is the guts of what's going on:
(Disclaimer: This code is not production ready, it's merely an example that should give you some direction)
var req;
function CheckInput()
{
if (window.event) keycode = window.event.keyCode;
if (keycode == 188) //KeyCode 188 = Comma;
{
//I haven't provided code for this, you will need to code
//the extraction of the address you wish to test for yourself...
var addressToCheck = ParseLastAddressFromTextBox();
req = new XMLHttpRequest();
//Replace <SERVICEADDRESS> with the URL of your web service
//the 'true' parameter specifies that the call should be asynchronous
req.open("POST", "<SERVICEADDRESS>", true);
req.onreadystatechange = MatchSearchComplete; //This is the callback method
//Set up the post headers
req.setRequestHeader("Host", "localhost");
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var params = addressToCheck;
req.setRequestHeader("Content-Length", params.length);
//Iitiate the call to the service
req.send(params); }
}
//The XMLHttpRequest object will fire this method when the
//onreadystatechange event fires...
function MatchSearchComplete()
{
//Check that the response has the correct state and status
//indicating that we've received a response from the server.
if (req.readyState == 4 && req.status == 200)
{
//Our call to the service is complete
var result = req.responseText;
if (result == "false")
alert('The address "'+ req.params +'" is not valid.);
}
}
So what you're doing here is setting up an XMLHttpRequest, pushing the data into it and firing it off to a web service.
Your ASP.NET web application will need a web service built in to it that will be doing the validation of the address.
I might also warn: What if there's only a single address and the user doesn't hit the comma? You should move the guts of the CheckInput() method out to it's own method which parses the addresses. The KeyDown method really should only check if the ',' was pushed. This way you can call the web service to check when the textbox loses focus also. I would also worry about modification of existing addresses without the user hitting the comma again. Therefore, I would wonder about this approach. I would consider that once an address is validated you should have a javascript that only allows that address to be deleted, it shouldn't be editable... whatever approach you take, I'm just warning you that there's some issue with just checking them using the entered ',' approach.
You have to do this with Javascript. After the comma is typed, only then you can pass the email back to C# backend for verification.

Categories

Resources