Print a picture of a web application in asp.net - html

Hello I have my web application but I want to give the possibility to download and Printer-friendly image attached to a form, I have no idea how to do because I'm obviously new to C # and asp.net . As I can start ?
i try with onserverclick but i don´t have idea with i do to communicate with printer is my question How communicate with printers controllers to print a image?
I implemented the following and I get an error with the printer, but I do not get no window available printers.
protected void imprime_tiff(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(pqr);
pd.Print();
}
void pqr(object o, PrintPageEventArgs e)
{
System.Drawing.Image i = System.Drawing.Image.FromFile("C:\\Users\\MaxImage\\Desktop\\firma6.png");
Point p = new Point(100, 100);
e.Graphics.DrawImage(i, p);
}
and in my html i put the next
<button name="printButton" id="printButton" type="button" class="btn btn- default" onserverclick=" imprime_tiff" runat="server" >
Imprime
</button>

You won't be able to interact directly with the printer from a web browser. PrintDocument is only for WinForms applications and won't work with web applications.
The client browser needs to trigger the printing either manually (File > Print...) or through interaction with the page such as clicking on a button after which you can trigger the print dialog using JavaScript - https://developer.mozilla.org/en-US/docs/Web/API/Window/print
You can control the rendering of your page to make it "printer friendly" using a print style-sheet, there is a thorough write up here: http://www.smashingmagazine.com/2011/11/24/how-to-set-up-a-print-style-sheet/

Related

MediaCapture and Window VisibilityChanged

[Question]
On Windows Phone 8.1, what exactly happens in between the time when the user leaves the app and the OnSuspended event fires? I'm having trouble with the ability to manage objects in that span, in particular MediaCpture object.
To better explain the problem, here is the scenario:
The user is on a page with a video preview being pumped to a CaptureElement
The user taps the Start button
The user taps Back button and returns to the page with a broken MediaCapture
With WinRT there isn't an ObscuredEvent and OnNavigatingFrom doesn’t fire unless you’re going to another page in the same Frame. After some investigation, I've found that the only event that fires is Window.Current.VisibilityChanged
I've gone ahead and hook it when the page is NavigatedTo and unhooked in OnNavigatedFrom (see ex2 below). Inside the event, I check for parameter that tells if the app is hiding or showing and dispose/initialize accordingly(see ex.1 below).
[Problem]
However, this only works with the debugger attached. If I do this without the debugger attached, it doesn't reinitialize and frequently crashes the camera and I have to literally reboot the device.
Code Example 1 (note: e.Visible == false is leaving the app and true when returning)
async void Current_VisibilityChanged(object sender, VisibilityChangedEventArgs e)
{
if (!e.Visible) //means leaving the app
{
await DisposeAll(); //cleans the MediaCapture and CaptureElement
}
else
{
if(mediaCaptureManager != null) await DisposeAll();
await Initialization(); //set up camera again
}
}
Example 2 (hooking into the event)
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Window.Current.VisibilityChanged += Current_VisibilityChanged;
this.navigationHelper.OnNavigatedTo(e);
}
protected async override void OnNavigatedFrom(NavigationEventArgs e)
{
Window.Current.VisibilityChanged -= Current_VisibilityChanged;
this.navigationHelper.OnNavigatedFrom(e);
}
[Update: Resolution]
Instead of using VisibilityChanged, hook into Window.Current.Activated on the page's constructor. With the debugger completely detached, the Activated event will provide the WindowActivationState parameter in the WindowActivatedEventArgs. Like this:
private async void CurrentOnActivated(object sender, WindowActivatedEventArgs e)
{
if(e.WindowActivationState == CoreWindowActivationState.Deactivated)
{
//dispose MediaCapture here
}
else if(e.WindowActivationState == CoreWindowActivationState.CodeActivated || e.WindowActivationState == CoreWindowActivationState.PointerActivated)
{
//initialize MediaCapture here
}
}
See my answer in https://stackoverflow.com/a/28592882/3998132. Using Window.VisibilityChanged in conjunction with your Page\UserControl Loaded\Unloaded handler should solve your issue I believe.
Using Window.Activated is less desirable than Window.VisibilityChanged because Activated relates to being visible AND having focus where as VisibilityChanged only pertains to visibility. For showing a preview having focus is not applicable. Since Windows Store apps on Windows Phone can only have one Window showing there is no difference in using either however if your app becomes universal and runs on let's say on Windows 8+ Modern shell (which can show multiple Store apps with the Snap window feature) or Windows 10 desktop (which can support multiple Store apps showing at the same time) you will not want to stop preview when a user changes focus from your app but your app is still showing.
I'm not sure if it wouldn't be more suitable to use Suspending/Resuming events. Note only that in this case, you will have to debug it properly - it behaves little different while being run with/without debugger attached.
As for the code - hooking your event in OnNavigatedTo/OnNavigatedFrom is not a good idea - when the OS suspends the app and you are using SuspensionManager then OnNavigatedFrom will be called, but when you go back to your app (resume it), then OnNavigatedTo will not be called.
Using Window events may also work here, but why not subscribe it once, somewhere in constructor? - it's window-wide and hence in phone there is only one window, which stands for app, then subscribe once. In this case, you may add a line that recognizes the current page in window and if that page contains mediacapture then dispose (create similar). Then you can also dispose/initialize in navigation events in case user doesn't leave your app and just navigate.

Showing m.bing.com in the WP8 WebBrowser control

I'm having a problem getting bing.com to load in a WebBrowser control on Windows Phone 8. It seems that doing that will launch the WP8 Search App (same as pressing the Search button on the phone). The problem is, once you click a result in that search app, it doesn't take you back to your original app - it goes to IE to show the result. This isn't going to work for me and seems to be a massive flaw (IMO) in the WebBrowser behavior.
There does seem to be a few apps out there that have succeeded in being able to show bing.com without launching the phone's search app - for example Image Downloader Free. There was another one, but I can't remember what it was...
After some research, I've found that the WebBrowser_Navigating event gets fired 3 times when going to bing.com: first request to the user-entered URL (www.bing.com), it then gets redirected to http://wp.m.bing.com/?mid=10006, then it redirects to bing://home/?mid=10006.
Preventing it from forwarding to the Bing search app is quite simple, just add this to the Navigating event:
e.Cancel = (e.Uri.Scheme == "bing");
The problem is, it then only shows the Bing search page place holder which says "Bing Search" and has a link that says "Back to Bing search" which does nothing (it would typically relaunch the Bing Search app).
I have a few thoughts, but I'm not sure how feasible they are.
In the WP8 WebBrowser control, is it possible to fake the User Agent?
Can one of the items in the WebBrowser.Uri.Flags property be removed or added to affect the way Bing.com handles the request?
If none of those work, I can simply create a dummy page on my web server, redirect all bing.com requests to it, and have it grab the m.bing.com front page with a card-coded user-agent. I really would like to avoid having to do this option though. From an End-User perspective, they would never know, but I just added a whole new layer of overhead, maintenance and resource-wise.
If you're interested, attached are the diff's for the EventArgs object between the 3 requests that occur in the WebBrowser.Navigating event:
Request 1 (bing.com) -> Request 2 (forwarded to wp.m.bing.com/?mid=10006)
Request 2 (forwarded to wp.m.bing.com/?mid=10006) -> Request 3 (forwarded to bing://home/?mid=10006)
tl;dr Does anyone know of a way to prevent www.bing.com from causing the search app to launch in the WebBrowser control in my application?
Thank you!
I don't know if there's a better way to handle this, but I found a solution. I haven't gotten it to work perfectly when the back button is clicked, so I will update my answer if/when I found a more solid solution. I still think this is a big flaw in the WebBrowser control in WP8.
Here is the code:
private bool _customHeaderRequest = false;
private void MainBrowser_Navigating(object sender, NavigatingEventArgs e)
{
string host = e.Uri.Host.ToLowerInvariant().Trim();
if ((host == "bing.com" || host.EndsWith(".bing.com")) && !_customHeaderRequest)
{
e.Cancel = true;
Dispatcher.BeginInvoke(() =>
MainBrowser.Navigate(e.Uri, null,
"User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; NOKIA; Lumia 710)\r\n"));
_customHeaderRequest = true;
return;
}
_customHeaderRequest = false;
}
private void MainBrowser_Navigated(object sender, NavigationEventArgs e)
{
_customHeaderRequest = false;
}
I don't have access to my emulator, but I tried it on my phone, and:
The redirect doesn't happen when you "Prefer desktop version" and open m.bing.com. Warning: The mobile version isn't very pretty.
Try disabling scripts on your WebBrowser, that could stop the redirect from happening.
Any chance you could just use Google?

Unhandled exception when firing WinRT 8.1 WebView ScriptNotify

I'm trying to create an MVVM Caliburn-based WinRT 8.1 app (I know that CM won't be perfectly compatible with 8.1 until version 2.0 is out, but the error does not seem to be related, as it is raised also when the handler is placed in the view code behind). One of its views contains a WebView control, whose content is set via NavigateToString (HTML contents come from app's installed assets). The HTML loaded into this control includes several hyperlinks, most of them representing cross-references to other asset-based HTML content. So when users click the link I want to override the standard navigation action, get my viewmodel notified, and let it load another HTML content from the app assets.
Here is what I did, following the post Open links in external browser in WebView (WinRT):
in the XAML code, I added to the WebView control an attribute for attaching the ScriptNotify event to my VM: cal:Message.Attach="[Event ScriptNotify] = [Action GetFromLink($eventArgs)]" (see https://caliburnmicro.codeplex.com/wikipage?title=All%20About%20Actions).
in my VM, the method signature is public void GetFromLink(NotifyEventArgs e).
whenever my VM loads some HTML into the WebView, it first injects a script in the HTML head which replaces the click handler of each anchor representing a cross-reference (all these anchors are marked by a class="xref" attribute). This script is hold in a constant in my VM:
private const string SCRIPT = "for (var i = 0; i < document.links.length; i++) {" +
"var className = document.links[i].getAttribute(\"class\");" +
"if (className && className === \"xfer\") {" +
"document.links[i].onclick = function() {" +
"window.external.notify('url:' + this.href);" +
"return false;" +
"}}}";
Now, when I launch the app, load an item containing one of these xref's and click on it, I get an unhandled exception telling me that "navCancelInit is undefined". I suppose this error is surfacing from JS code, but I cannot see where and how this function should be defined.
According to http://msdn.microsoft.com/library/windows/apps/br227713, I do not need any additional step for ScriptNotify when HTML has been loaded via NavigateToString. Could anyone suggest a solution?
I got an answer from a MS guy about this, so credit is not mine for this answer: it is a timing issue. I must ensure that the page has fully loaded before running the script which changes the DOM; pretty simple, if you think. Just moving the script at the end of the page, or wrapping it in an onload handler, should make the trick. Hope this can save some hair-pulling to others!
If you listen to this event: http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.webview.domcontentloaded.aspx WebView.DOMContentLoaded event, All of the script should be loaded in the WebView and you should be able to access and execute, if you are trying to do this before the scripts won't be loaded.

Fast App Resume issues in windows phone 8

When i set ActivationPolicy="Resume" in WMAppManifest.xml page tile navigation(navigation URL) is not working in Tombstone state, it reloads the last back stack page(URL). It works fine with Dormant state with out reloading the page. If don't set this property (ActivationPolicy="Resume") it reloads the page in both states [Dormant state and Tombstone state].
But how can we achieve the navigation to secondary url's, when we set that property.
Please help me .
Adding ActivationPolicy="Resume" is not the only step needed to have your app support Fast App Resume. I believe the behavior you are describing is normal when you only set that one property. I think there are a few ways to implement "Fast App Resume", but I found this to be the easiest way.
Set the activation policy like you just described and then do the following:
Go into App.xaml.cs in the "App" class add:
private bool reset
You should then have a method for InitializePhoneApplication that initializes the RootFrame. Add this:
RootFrame.Navigating += RootFrame_Navigating;
RootFrame.Navigated += RootFrame_Navigated;
Then you can go and add those methods:
void RootFrame_Navigating(object sender, NavigatingCancelEventArgs e)
{
if (reset && e.IsCancelable && e.Uri.OriginalString == "/MainPage.xaml")
{
e.Cancel = true;
reset = false;
}
}
void RootFrame_Navigated(object sender, NavigationEventArgs e)
{
reset = e.NavigationMode == NavigationMode.Reset;
}
If you implement this properly, your app should resume from the last page you were on.
Same problem here. I got WP8 application with Fast App Resume enabled. I can pin tiles pointing to specific pages in my apps. It works fine when app is just Suspended, but when the app is Tombstoned, then clicking secondary tile has the same effect as clicking the main tile.
I receive only one RootFrameNavigating event with NavigationMode == Back and Uri == /MainPage.xaml. The app then shows the previous page that was there before I suspended the app.
I guess this is actual bug in the platform for this specific scenario - Fast App Resume + tombstoned app + navigation from pinned tile, that we as developers cannot solve.

To use doPost yet stay in the same page

Hi I am working on a webbased application with JSPs and servlets. I have a page which has a button in it. I have written some javascript to pop-up a small window when the button is clicked and also it invokes the doPost method. The code is something like this --
]
"<form name='downloadFrm1' method='post' action='S2VServlet'
.. ..
"<input name='submitBtn' type='submit' value='Download Files With Warnings' onClick="+popup+">\n"+
"</form><BR></div><p><BR></p> \n";
However, I invoke the doPost method only to do some internal work. I don't want the parent page to be redirected anywhere. But what is happening is that when I click on the button the small popup window appears but the parent page also moves to a blank page. How can I make the parent page stay as is and not get redirected ? The code for doPost is something like ths--
public void doPost(HttpServletRequest p_req, HttpServletResponse p_res) throws IOException, ServletException {
try {
String downloadKey = p_req.getParameter(DOWNLOAD_KEY_ELEMENT);
....
if (//put my condition)) {
//just set some internal value and return
....
return;
}
You can't do it without ajax (javascript). The standard request/response cycle requires a change in the page.
Take a look at jQuery. You can do $.post("S2VServlet", {param:param}) which will execute in the background.
I think you can end your doPost method doing doGet. Doing so will "repeat" the page, but the user thinks he/she has not moved.