best practise for ASP.NET Lifecycle in regards to data loading? - c#

I have a question regarding the best practises in terms of data loading with ASP.NET and C#
As an overview, we have a web page that uses a supporting web service to obtain an fairly large XML file. That file is then translated into client side JavaScript for use of loading ListViews.
protected string clientSideJavaScripts;
protected void Page_Init(object sender, EventArgs e)
{
// code goes here to submit a request and receive an XML Response from the web service
// code goes here to set clientSideJavaScripts = translated Java Script from the XML Document
// other code goes here
}
The ASP file has something along the lines of:
<head>
<title></title>
<script type="text/javascript>
<%=clientSideJavaScripts%>
</scrpit>
</head>
...
However additionally there are several buttons on the form that cause postbacks. These are not directly related to the javascript above.
Everything works well, however I believe (with my limited knowledge of the ASP.NET lifecycle), that that webservice is getting called every postback. So every time anyone clicks on of the few asp:buttons on the webpage, it is doing the overhead of loading that file regardless of the nature of the button, since a postback will cycle through the stages of the lifecyce from Init up to and past the postback event handling.
The obvious thing to do would be to not call the webservice on postback. I.E:
protected string clientSideJavaScripts;
protected void Page_Init(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// code goes here to submit a request and receive an XML Response from the web service
// code goes here to set clientSideJavaScripts = translated Java Script from the XML Document
}
// other code goes here
}
However the result of that is that the server side string 'clientSideJavaScripts' no longer gets instanciated, and therefore client side no longer gets the required javascript after tje first postback.
I am sure that I am missing an obvious (and probably common) method to deal with the persistancy of the javascript in a case like this, however I don't know of it and therefore I am looking to anyones advice regarding this. What would be the best practise to ensure that the Webservice is only called once?
I am also using AJAX and JQuery Mobile, if that makes any difference
Any advice would be greatly appreciated.
Many thanks

Related

No WCF service response - C#

I have added a service reference, directed to a WSDL which loaded all existing WSDLs from the location. I am trying to request data by calling one of the methods like this:
protected void Page_Load(object sender, EventArgs e)
{
string fLastname, folder, status, header, responsible;
int date;
PyramidServices.ServiceSoapClient client = new PyramidServices.ServiceSoapClient();
string activity = client.GetUserActivity("xxxx", "xxxx", out fLastname, out folder, out status, out date, out header, out responsible);
}
When debugging, the vars are all null. . I have a hard time understanding trace messages since this is not my field. I don't know what to look for, so here is pretty much all the information I get when tracing (Sorry for the Swedish version!):
Sending:
Receiving:
Answer # Channel:
Stop:
[EDIT]
I tested the method using WCF Test Client and received following:
So it's kind of obvious that I am doing something wrong with the code when parsing the data from the response? My question is, how do I accomplish this?
With a lot of help from #TomW, we finally found out what the problem was. The code for the WSDL is created in a system that lets me add XML nodes surrounding the data like below:
<wrap>
<data1></data1>
<data2></data2>
<data3></data3>
</wrap>
instead of:
<data1></data1>
<data2></data2>
<data3></data3>
<data1></data1>
<data2></data2>
<data3></data3>
<data1></data1>
<data2></data2>
<data3></data3>
Therefor, the code generated by Visual Studio in Service Reference did not like the way I wrapped the data with unwanted tags. After removing the tag from my code in the system, I received exactly what I wanted with the code at the top.

Can my oauth2 callback page be the same html page? and how do I get the token?

First off, I'm using static html and javascript and C# Web API.
So I have a link that calls an oauth2 server, on my html file, say index.html
Now is it ok to set the callback page to index.html
It seems to work, and it gets sent to index.html?code=125f0...
Is this ok to do or do I need a seperate callback page. Is code, the token?
Now how should I consume this?The javascript doesn't seem to get hit on the call back.
Edit, actually, the javascript seems to get hit on the call, back but I'm not getting anything undefined from:
$(function () {
var params = {},
queryString = location.hash.substring(1),
regex = /(^&=]+)=([^&*])/g,
m;
while (m = regex.exec(queryString)) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
if (params.error) {
if (params.error == "access_denied") {
sAccessToken = "access_denied";
//alert(sAccessToken);
}
} else {
sAccessToken = params.code;
alert(sAccessToken);
}
});
Also, can my callback page be a C# web api call? And send the token that way. I'm guessing no, cus then you'd never know what user agent is sending it, and couldn't communicate back unless you somehow passed a id and used signalR? It seems better to get it in javascript and send the token to web api. But then can web api make calls to the resource if it has the token?
sorry, I'm still learning
OAuth2 has various "profiles". The "Authorization Code Grant" flow (what you are using) requires a server side component that exchanges the code for token.
Single Page Applications, typically use the implicit flow. See here for a quick description: https://docs.auth0.com/protocols#5 (ignore references to "Auth0", the underlying protocol is the same regardless of the implementation).
See here for a more thorough description of both flows: What is the difference between the 2 workflows? When to use Authorization Code flow?
Sorry, it was sorta of strange question and bad wording. But what I ended up doing is making an HTML callback page which takes in the code. I popup the OAuth2 server page in a window then it calls my callback page. Then my callback page will close the window and pass the code back to my parent page.

How do i catch page cannot load message?

Hi i hope someone can help,
In basic terms i am trying to stop the embedded browser, in my Windows Forms app, from navigating to the 'This program cannot display the webpage' page and instead display my own error page.
The C# application is a Web Browser embedded in my Windows Forms, its purpose is allowing the user to click on the provided buttons that navigate the browser to predefined WebService URL's. If the Service is not running on the Machine then instead of the browser saying that it was unable to load i need to to navigate to my custom page instead.
I have looked around and as yet had no luck in finding a solution apparently HttpStatusCodes are a way to go but i have no idea how to use them.
Code Snippet:
private void currentMachineToolStripMenuItem_Click(object sender, EventArgs e)
{
webBrowser1.Navigate("http://localhost:2021/wsservice/status");
}
As you can see, currently very simple program.
You can try this:
Private void WebBrowser1_NavigateError(Object sender, EventArgs e)
{
WebBrowser1.Navigate( App.Path + "\retry.htm");
}
Taken from this link -
You would need to use an HttpWebRequest and an HttpWebResponse object to do
this. Create the HttpWebRequest with the desired URL, using the
WebRequest.Create(url) method. Then use the GetResponse() method to get the
HttpWebResponse. The HttpWebResponse will have the status code returned from
the server. This will tell you if the URL exists or not. 404 indicates "Page
not Found." 200 indicates "Success." Etc.
http://msdn.microsoft.com/en-us/library/8y7x3zz2(vs.71).aspx
Also another link which might help you - http://www.vcskicks.com/check-website.php
You can check the page content for a word that indicates that the page did not load correctly
if(webBrowser1.Document.InnerHtml.Contains("error"))
You can check too the returned document url, find the resource address that webBrowser use to show error page:
if (webBrowser1.Document.Url.ToString().Contains("res://ieframe.dll/dnserrordiagoff.htm") )
...

Server side include external HTML?

In my asp.net-mvc application I need to include a page that shows a legacy page.
The body of this page is created by calling an existing Perl script.
This Perl script is externally hosted.
Is there a way to do something like this:
<!-- #Include virtual="http://www.example.com/theScript.plx"-->
Not as a direct include, because ASP.NET server-side-includes require the page to be compiled at the server.
You could use jQuery to download the HTML from that URL when the page loads, though I appreciate that's not perfect.
Alternatively (and I have no idea whether this will work) you could perform a WebRequest to the perl webpage from your ASP.NET MVC controller, and put the resulting HTML in the view as text. That way you could make use of things like output caching to limit the hits to the perl page if it doesn't change often.
If you wanted to do it all in one go, you could do an HTTP Request from the server and write the contents to the page?
Something like this:
Response.Write(GetHtmlPage("http://www.example.com/theScript.plx"));
Calling this method:
public String GetHtmlPage(string strURL)
{
// the html retrieved from the page
String strResult;
WebResponse objResponse;
WebRequest objRequest = System.Net.HttpWebRequest.Create(strURL);
objResponse = objRequest.GetResponse();
// the using keyword will automatically dispose the object
// once complete
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
strResult = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
return strResult;
}
(Most code ripped blatantly from here and therefore not checked)
You could implement this in a low-key fashion by simply using a frame and setting the frame source to the url that needs to be included. This is quite simple and can be down without any server or client side scripting, so that'd be my preferred approach, if possible.
If you want the html to appear to come from your server, however, you'll need to manually include it - typically by using WebRequest as Neil says. You may wish to cache the remote page for performance, though, since it's a perl script, I'll assume the page is dynamic, so this might not be a great idea.

Problem with ASP.NET asynchronous calls, waiting for handler to return

I'm trying to find an answer for a problem my developers are having. I don't know this well enough myself...
We are using ASP.NET with C#.
When a user presses a button on a page, we call a hander to save the session variables to the current view state of the form (some IDs that are used).
Then, we call a GreyBox window with other functionality.
Because this is asynchronous, greybox doesn't wait for the handler to respond.
In many cases the greybox is loaded before the session variables are saved to the view state, and in this case, grey box doesn't have the IDs that are necessary.
On the localhost, it is fast enough that we never realized the problem. In production, it is a problem.
What would be the correct solution here?
The asynchronous call to the server to save the session will return a response to the client. Don't start greybox until you have a successful reply from the server. If there is only one thing causing async postbacks on your form, then you can plug into the reply by doing this:
<script type="text/javascript">
//<![CDATA[
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(endRequest);
function endRequest(sender, e) {
// Do stuff
}
//]]>
</script>
For more complicated scenarios see the article on MSDN on this subject.
You need to make sure that you're additional code is running in a callback method from your AJAX request.
If you're manually calling a web service or page method the Sys.Net.WebServiceProxy.invoke method takes a callback: http://msdn.microsoft.com/en-au/library/bb383814.aspx
I have a feeling that the PageRequestManager which David suggested only works if you are using an UpdatePanel to perform the AJAX request.

Categories