Problem with Crystal Report in ASP.NET - ExportToHttpResponse - c#

I am using the code to export pdf file from a popup.
On button click
function popupReport()
{
var url = 'Report.aspx';
window.open(url, 'winPopupReport', 'width=300,height=300,resizable=no,scrollbars=no,toolbar=no,directories=no,status=no,menubar=no,copyhistory=no');
return false;
}
and in Report.aspx.cs
ReportDocument repDoc = ( ReportDocument ) System.Web.HttpContext.Current.Session["StudyReportCrystalDocument"];
// Stop buffering the response
Response.Buffer = false;
// Clear the response content and headers
Response.ClearContent();
Response.ClearHeaders();
try
{
repDoc.ExportToHttpResponse( CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Response, true, "StudyReport" );
}
catch( Exception ex )
{
}
The code works fine in IE7. But in IE6 the popup window is not closing. Why this happends?

Some browser deny automatic closing for web pages in some conditions.
Try this workround to close a page.
Write a script, in the page that you want to close, that opens another page; in this sample the script is injected via code after a button click, but you can write it directly in HTML if you need it.
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('Success.htm', '_self', null);", true);
Create Success.htm page this way
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title></title>
<script language="javascript" type="text/javascript">
var redirectTimerId = 0;
function closeWindow() {
window.opener = top;
redirectTimerId = window.setTimeout('redirect()', 2000);
window.close();
}
function stopRedirect() {
window.clearTimeout(redirectTimerId);
}
function redirect() {
window.location = 'default.aspx';
}
</script>
</head>
<body onload="closeWindow()" onunload="stopRedirect()" style="">
<center><h1>Please Wait...</h1></center>
</body></html>

Related

ASP.NET Core Razor Page: Write html content to new browser tab?

Using HttpClient, I make a GET request which returns a html response.
Request to url in method handler:
var response = string.Empty;
var result = await _httpClient.CreateClient().GetAsync(newUrl);
if (result.IsSuccessStatusCode)
{
response = await result.Content.ReadAsStringAsync();
var bytesResponse = Encoding.ASCII.GetBytes(response)
// How to open bytesResponse in a new browser tab?
}
Html response content from request:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
</style>
</head>
<body>
<!-- body content -->
<script>
</script>
</body>
</html>
Attempting to add await Response.Body.WriteAsync(bytesResponse, 0, bytesResponse.Length); will throw an System.ObjectDisposedException: IFeatureCollection has been disposed. exception
Would appreciate assistance on how to display the response in a new browser tab.
Firstly,if you want to open a new browser tag,it cannot be done in razor handler.It need to be done in view.You need to decorate your link with the "_blank" attribute like this:
<a asp-page-handler="xxxxx" target="_blank">link</a>
Here is a demo worked:
test.cshtml:
<a asp-page-handler="Html" target="_blank">link</a>
test.cshtml.cs:
public IActionResult OnGet()
{
return Page();
}
public ActionResult OnGetHtml()
{
return base.Content("<div>Hello</div>", "text/html");
}
result:

How to download files through a HTML page hosted using HTTPListener in a self hosted application

I have a very simple page hosted in a WPF application using httplistener
ThreadPool.QueueUserWorkItem(o =>
{
Console.WriteLine("Webserver running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem(c =>
{
var ctx = c as HttpListenerContext;
try
{
if (ctx == null)
{
return;
}
var requestUrl = ctx.Request.Url.LocalPath.Trim('/');
var rstr = _responderMethod(ctx.Request);
var buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
}
catch (Exception ex)
{
// TODO: add log here.
Debug.WriteLine(ex.Message);
}
finally
{
// Always close the stream.
if (ctx != null)
{
ctx.Response.OutputStream.Close();
}
}
}, _listener.GetContext());
}
}
catch (Exception ex)
{
// TODO: add log here.
Debug.WriteLine(ex.Message);
}
});
And it is hosting this HTML page which should only be able to allow clients to download some local files that were previously generated by the main app.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Self Hosted WebServer</title>
</head>
<body>
<div>
<h2>
Downloads
</h2>
<ul style="font-size:large">
<li>
File 001 (<a href="V1.xlsx" download>xlsx</a> | <a href="v1.pdf" download>pdf</a> | <a href="v1.zip" download>zip</a>)
</li>
</ul>
</div>
</body>
</html>
However, when I access the web page and try to download, it wont actually get the local file. I have tried different and absolute path locations but it still isn't able to actually download the file.
Is there something I'm missing, do I really need to process the request somehow instead of having a simple HTML href download link?
Or is there any other hosting way to provide this simple solution?
I'm using VS 2017, C# 4.6.1 and my main app is a WPF.

Google+ signin not redirecting

I have the following code to authenticate a user via the Google+ signin button:
<html>
<head>
<!-- google api -->
<meta name="google-signin-client_id" content="xxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com">
<meta name="google-signin-scope" content="email">
</head>
<body>
<div id="google-signin"></div>
<script>
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
function onGoogleSuccess(googleUser) {
// get the token
var id_token = googleUser.getAuthResponse().id_token;
// console.log('Logged in as: ' + googleUser.getBasicProfile().getName());
}
function onGoogleFailure(error) {
console.log(error);
}
function renderButton() {
gapi.signin2.render('google-signin', {
'scope': 'https://www.googleapis.com/auth/plus.login',
'width': 242,
'height': 56,
'longtitle': true,
'theme': 'dark',
'onsuccess': onGoogleSuccess,
'onfailure': onGoogleFailure
});
}
</script>
</body>
</html>
When I click the button, an authentication popup windows appear, and once I authorize it, the function 'onGooglesuccess' runs, but it doesn't redirect to a page. I want it to redirect to a specific .aspx page where I can grab the code, replace it with a tokrn and grab user info.
How can I do that? I tried reading the docs on Google, but I just can't figure how to do it.
I'm developing my application in ASP.NET 4.5 / C# / Javascipt

OAuth 2.0 access using javascript

I want to insert, update data from the fusion tables.
While selecting from the fusion table all seems to work fine. But during row addition i need to used OAuth 2.0 but unable to find a suitable solution to get the access token and use it during the insert.
A code sample would help a lot.
var fusiondata;
function initialize() {
// Initialize JSONP request
var script = document.createElement('script');
var url = ['https://www.googleapis.com/fusiontables/v1/query?'];
url.push('sql=');
var query = 'insert into 1bPbx7PVJU9NaxgAGKqN2da4g5EbXDybE_UVvlAE (name,luckynumber) values('abc',89)';
var encodedQuery = encodeURIComponent(query);
url.push(encodedQuery);
url.push('&callback=viewData');
url.push('&key=AIzaSyA0FVy-lEr_MPGk1p_lHSrxGZDcxy6wH4o');
script.src = url.join('');
var body = document.getElementsByTagName('body')[0];
body.appendChild(script);
}
function viewData(data) {
// code not required
}
I know most of you are suffering for google auth and inserting and updating fusion table. I am providing the entire code how to use the gauth lib to insert in a simple manner
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Authorization Request</title>
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
function auth() {
var config = {
'client_id': '365219651081-7onk7h52kas6cs5m17t1api72ur5tcrh.apps.googleusercontent.com',
'scope': 'https://www.googleapis.com/auth/fusiontables'
};
gapi.auth.authorize(config, function() {
console.log('login complete');
console.log(gapi.auth.getToken());
});
}
function insert_row(){
alert("insert called");
gapi.client.setApiKey('AIzaSyA0FVy-lEr_MPGk1p_lHSrxGZDcxy6wH4o');
var query = "INSERT INTO 1T_qE-o-EtX24VZASFDn6p3mMoPcWQ_GyErJpPIc(Name, Age) VALUES ('Trial', 100)";
gapi.client.load('fusiontables', 'v1', function(){
gapi.client.fusiontables.query.sql({sql:query}).execute(function(response){console.log(response);});
});
}
</script>
</head>
<body>
<button onclick="auth();">Authorize</button>
<p> </p>
<button onclick="insert_row();">Insert Data</button>
</body>
</html>

Simple log in with Facebook C# SDK not working

I'm new to the Facebook apps and recently read the doc available. Then, I proceeded to get the Facebook C# SDK from NuGet and read the get started tutorial.
I modified it a little. I have 3 pages:
Default.aspx : has the "log in with facebook" button
Protected.aspx : the page that I ultimately want to be unaccessible without first logging in
DoSignIn.aspx : contains the request for the token and redirects back to Default.aspx
On the Default.aspx, I have a button that redirects me to the Protected.aspx page. On it, I have a label showing me the token.
Now, my issue is this:
When I click on the "log in with facebook" button, the button doesn't change to show that I'm logged in. It only shows that I'm logged in if I do a refresh on the page.
If I click on the button to redirect me to the Protected.aspx page, I can't see the token in the Label because the DoSignIn.aspx page was never called.
If someone could point me in what I do wrong (as I nearly copied the tutorial example), I would be very grateful. I spent the past 3 hours fiddling with this and searching Google and SO all over and don't know where to search anymore.
Thank you for your time.
PS. I have the latest Facebook C# SDK and the App ID seems to work fine as when I manually refresh my browser, I am indeed logged in.
I add the code for the 3 pages:
Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<div id="fb-root">
</div>
<script type="text/javascript">
window.fbAsyncInit = function () {
FB.init({
appId: 'I_INSERTED_MY_APP_ID_HERE', // App ID
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
FB.Event.subscribe('auth.authResponseChange', function (response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
// - Handle the access token -
// Do a post to the server to finish the logon
// This is a form post since we don't want to use AJAX
var form = document.createElement("form");
form.setAttribute("method", 'post');
form.setAttribute("action", 'DoSignIn.aspx');
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'accessToken');
field.setAttribute("value", accessToken);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
};
// Load the SDK Asynchronously
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
} (document));
</script>
<form id="form1" runat="server">
<div>
<div class="fb-login-button" data-show-faces="true" data-width="400" data-max-rows="1">
Log in with Facebook</div>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Go to protected" />
</div>
</form>
</body>
</html>
Default.aspx.cs:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Protected.aspx");
}
}
DoSignIn.aspx.cs:
public partial class DoSignIn : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var accessToken = Request["accessToken"];
Session["AccessToken"] = accessToken;
Response.Redirect("Default.aspx");
}
}
Protected.aspx.cs:
public partial class Protected : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["AccessToken"] != null)
{
Label1.Text = Session["AccessToken"].ToString();
}
else
{
Label1.Text = "Not authenticated";
}
}
Right, I have spent hours searching and finally found why it is not working. It has nothing to do with the code above but with a Facebook bug. Actually, it seems that many people can't have the auth.authResponseChange to fire as the session refreshes. I found several bugs reports on FB describing the complete issue, one of them being here.
This issue I had when developing on /localhost/. I had already moved to a different way to integrate Facebook Login when, before deleting the above samples, I tried uploading it on an actual hosting server under a domain name. For a reason I can't explain, it just works from there.
Anyway, the implementation for the Facebook login I'm currently pursuing is explained here.

Categories