How to print in VB? - asp.net

I have a web application build using classic ASP and VB. How do I print a document from within the back end VB code?
Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
End Sub
What i am trying to do is get user to click on button a letter is generated and sent to printer?

You could use the window.print javascript function which will open the print dialogon the client browser allowing him to choose the printer and print the page:
Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
ClientScript.RegisterStartupScript([GetType](), "print", "window.print();", true)
End Sub
As a side note, what you have is not a classic ASP application with VB, you have a classic ASP.NET WebForms application using VB.NET as a code behind.
UPDATE:
As requested in the comments section here's how you could write a generic handler which will dynamically generate the HTML you would like to print:
Imports System.Web
Imports System.Web.Services
Public Class Print
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/html"
context.Response.Write("<html><body onload=""window.print();""><table><tr><td>value1</td><td>value1</td></tr></table></body></html>")
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Now simply navigate to /Print.ashx.

you could look into some reports frameworks like CrystalReports (used to come with VS but you have to download it from SAP nowadays.
Here is a nice tutorial for the report-engine that comes packed into Visual Studio (I have to admit I don't have much experience with this but it looks fine to me): Creating an ASP.NET Report

Related

Update UI ASP.NET Control - Asynchronous (CallBack Approach) - Calling WebService Methods

Here is the sample code for WebService written in ASP.NET 1.1 using VB.NET:
<System.Web.Services.WebService(Namespace := "http://tempuri.org/WebService_Simple/Service1")> _
Public Class Service1
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function Add(ByVal A As Integer, ByVal B As Integer) As Integer
System.Threading.Thread.Sleep(2000)
Return A + B
End Function
End Class
Here is the Client code:
Public Class WebForm1
Inherits System.Web.UI.Page
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim proxy As New Service1
Dim ac As New AsyncCallback(AddressOf MyCallback)
Dim ar As IAsyncResult = proxy.BeginAdd(10, 20, ac, proxy)
System.Threading.Thread.Sleep(1000)
End Sub
Public Sub MyCallback(ByVal ar As IAsyncResult)
Dim proxy As Service1 = CType(ar.AsyncState, Service1)
Dim result As Integer = proxy.EndAdd(ar)
Label1.Text = "Result = " & result.ToString()
End Sub
End Class
I am using Visual Studio.NET 2003 (ASP.NET 1.1 / VB.NET). I am getting the right values into "result" variable. But it is NOT updating the UI element (Label1). I know the reason. Because UI - MAIN - thread is different than the one which is using CALLBACK - WORKER - thread. Can you provide me sample code so that it will update the UI (Label1) control using VB.NET in Visual Studio.NET 2003 ?
Thanks
This is the answer. It is negative but it is answer. You can't and shouldn't do this in ASP.NET Web Forms because Page cycle moves through well known set of steps. There shouldn't be any async/multi-threaded programming done in page cycle methods. and you definitely shouldn't make ASP.net thread sleeping.
Your Button1_Click is part of the cycle and when it executes, ASP.net framework already executes something else. And whatever you call asynchronously is just left behind. The code executes but values never affect anything.
If you trying to achieve asynchronous behavior in ASP.net web forms, you need to include some client-side devices that will call your web service. I am not even sure now that the old framework you use has something like update panel or there is AJAX toolkit for it. Bu that is how you need to achieve it without page reloading - you use jQuery or something else to call your web service. What you tried to do in your example is a dead end.
And seriously, start using new frameworks. At least 3.5.

vb.net web form generates extra blank lines

In a vb.net 2010 web form application the user loads 'template letters' to a web
interface, that they can modify letters sent out to various customers to generate
various late pay notifications. The user basically selects the 'template letter' they want
to generate for a specific customer, and hits the 'save' button.
The web interface has the tabs for 'preview', 'html', and 'design' as the bottom of
editor. These tabs are not part of any custom code, they must be part of a web
interface that is inherited.
The values for the editor are stored in a sql server 2012 database in a field
called 'strTemplate' and the value is actually html.
The problem is once the html value for 'strTemplate' is loaded for the user to edit, extra blank lines are loaded between different parts of the 'templates. Basically extra <br></br> tags are generated.
When the user hits the save button, more <br></br> tags are generated between the various parts of the letter.
I do not want these extra blank lines to be generated.
I have gone into the html tab, removed the <br></br> tags and hit the save button. The extra tags are still generated. I have stepped through the code to find where the tags are generated and can not find it.
Thus can you tell me what I can do to not have the extra <br></br> tags generated?
The following is some of the code that is used when accessing the part of that gets to the web interface:
Imports System.Data
Imports System.Reflection
Imports System.Windows.Forms
Imports Telerik.Web.UI
Imports System.Web.Script.Services
Imports System.Web.Script.Serialization
Imports System.Web.Services
Partial Class edittemplates_default
Inherits System.Web.UI.Page
Protected _master As MasterPage
#Region "Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load"
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
_master = CType(Page.Master, MasterPage)
_master.PageTitle = "Edit Templates"
If Not Page.IsPostBack Then
If (edittemplates_default.SiteUserManager.SessionUser IsNot Nothing) Then
LoadTemplates()
LoadVariables()
Else
'pnlEditor.Enabled = False
'pnlEditor.Visible = False
End If
End If
Master.Page.Title = "Login"
End Sub
#End Region
#Region "Protected Sub LoadTemplates()"
Protected Sub LoadTemplates()
Dim et As EditTemplates = New EditTemplates()
Dim dt As DataTable = et.SelectTemplates()
For i = 0 To dt.Rows.Count() - 1
ddlTemplates.Items.Add(New ListItem(dt.Rows(i)(dt.Columns(1).ColumnName()), dt.Rows(i)(dt.Columns(0).ColumnName())))
Next
End Sub
#End Region
#Region "Protected Sub LoadVariables()"
Protected Sub LoadVariables()
Dim et As EditTemplates = New EditTemplates()
Dim dt As DataTable = et.SelectAtnLtrVariables()
For i = 0 To dt.Rows.Count() - 1
rlbVariables.Items.Add(New RadListBoxItem(dt.Rows(i)(dt.Columns(1).ColumnName()), dt.Rows(i)(dt.Columns(0).ColumnName())))
Next
End Sub
#End Region
#Region "Protected Sub btnSaveTemplate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveTemplate.Click"
Protected Sub btnSaveTemplate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveTemplate.Click
Dim et As EditTemplates = New EditTemplates()
If ddlTemplates.SelectedValue <> 0 Then
et.UpdateTemplate(ddlTemplates.SelectedValue, ddlLanguage.SelectedValue, rEditor.Content.ToString())
End If
End Sub
#End Region
-------------------
Partial Class edittemplates_default
Inherits System.Web.UI.Page
Protected _master As MasterPage
-----------
You are using a very old version of RadEditor, which does not support IE9 where the reported problem exists. To fix the problem it is recommended to upgrade to the latest Q2 2014 version, which will ensure that the editor will function as expected in all modern browsers.
You can also verify that the problem is fixed in the online demos of RadEditor: http://demos.telerik.com/aspnet-ajax/editor/examples/saveindatabase/defaultcs.aspx

Scope of Page.Cache property in ASP.NET 4.0

I'm now work on ASP.NET project
and want to use Page.Cache property to cache the String data like bellow way.
but, it behaves like having a Session scope.
I understand Page.Cache property is retuning a current System.Caching.Cache object
and that must have an Application scope.
I could check below code works fine, but my project's code not -- it makes cache for per session.
And, that replaced Cache of Application (with Lock and UnLock) works fine too.
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim key_str As String = "cache_key"
Dim cached_value = Cache.Get(key_str)
If cached_value Is Nothing Then
cached_value = "stored_value"
Cache.Insert(key_str, cached_value, Nothing, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5), CacheItemPriority.Normal, New CacheItemRemovedCallback(AddressOf RemovedCallback))
End If
Label1.Text = cached_value
End Sub
Public Sub RemovedCallback(ByVal key As String, ByVal value As Object, ByVal removedReason As CacheItemRemovedReason)
Debug.WriteLine("#Callback!")
End Sub
End Class
above code
works fine
my project code
works like session scope
and If replaced Cache with Application, that works fine
Are there any possible to occur such a behavior or not?
(or I just made a mistake on anywhere else in logics?)
Please point out If concerning some configure files.
I maybe made a mistake.
My project is a Azure project and so Page.Cache is to store a data for per azure instance? Right?

Why am I getting an weird error on my asp.net webpage?

I am currently developing a asp.net webpage and a WCF publish subscribe service. The WCF service has been done up the subscriber is a winform app which is also done up. I am now trying to get the asp.net webpage to connect to my publish service for my WCF. However there is an weird error that I am getting. I have added the app.config and the generatedProxy.cs.vb to my asp.net project.
This is the code for my class
Public Class json
Implements IPostingContractCallback
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.ContentType = "application/json"
If Request.QueryString("action") = "postAlert" Then
Dim site As InstanceContext = New InstanceContext(New json())
Dim client As PostingContractClient = New PostingContractClient(site)
client.PublishPost("testing")
client.Close()
End If
End Sub
Public Sub PostReceived(ByVal postSampleData As String)
Console.WriteLine("PostChange(item {0})", postSampleData)
End Sub
the sub PostReceived is the callback method for my WCF service. It practically is meant to be do nothing as this is the Publisher, but I still have to implement it due to the WCF standards. The error that I am getting is
Class 'json' must implement 'Sub PostReceived(postSampleData As String)' for interface 'IPostingContractCallback'
How come i am getting the error when i have already implemented the sub as stated above?
Method signature must be: (Take a look at VB.NET Interfaces)
Public Sub PostReceived(ByVal postSampleData As String) Implements IPostingContractCallback.PostReceived
Console.WriteLine("PostChange(item {0})", postSampleData)
End Sub

problem using winforms WebBrowser in asp.net

i am using the WebBrowser control in asp.net page. here is the simple code:
Public Class _Default
Inherits System.Web.UI.Page
Private WithEvents browser As WebBrowser
Dim th As New Threading.Thread(AddressOf ThreadStart)
Sub ThreadStart()
browser = New WebBrowser
AddHandler browser.DocumentCompleted, AddressOf browser_DocumentCompleted
browser.Navigate("http://www.someurl.com/")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
th.SetApartmentState(Threading.ApartmentState.STA)
th.Start()
th.Join()
End Sub
Private Sub browser_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs)
If browser.Document IsNot Nothing Then
Dim textbox As HtmlElement = browser.Document.GetElementById("txt1")
textbox.InnerText = "some text"
Dim button As HtmlElement = browser.Document.GetElementById("btn1")
button.InvokeMember("click")
End If
End Sub
End Class
the problem is that the webbrowser's DocumentCompleted event is not being handled. It looks like the page request finishes before anything else could happen.
what's the solution to this problem?
I really recommend reading this article(He won a price for it..)
Using the WebBrowser Control in ASP.NET
http://www.codeproject.com/KB/aspnet/WebBrowser.aspx
His solution is to create 3 threads for it to work..
I'm not sure but I have some concerns about the way you wrote your code.
You are creating and initializing your thread as soon as your class instance is created. This is before the form has been loaded.
I can't say for sure this couldn't work but I would definitely recommend creating the thread in your Load event handler, just before you use it.
I wrote some similar code in C# to generate a website thumbnail. Although that code does not use the DocumentCompleted event, I played with that event when I wrote it and it seemed to work okay. You can compare my code to yours.
Also, I should mention I have one hosting account where the code doesn't work. It seems to simply die when I call Thread.Join. However, it doesn't appear that's the issue you're running into.

Resources