Execute VB Script on page_load - asp.net

I am having VB Script in ASPX page.I need to use that Script in codeBehind in Page _load with in a For loop,for each iteration.
My Code is :-
(.ASPX Page with VB Script. )
<script type="text/vbscript" language="vbscript" >
sub wordit()
'Opens Word application and does some process
end sub
</script>
VB Code Behind Part:-
For i As Integer = 1 To colSelRowIndex
CheckboxTemplateId = colSelRowKeys(i).ToString 'I get the ID from here
ViewState("TemplateID") = CheckboxTemplateId 'I need to send the value to the sub routines
hen()'sub
den()'sub
cs.RegisterStartupScript(cstype, csname1 & i, "wordit();", True)
Next
I need to open a word doc for an ID and another document for another ID from the loop.

Try this:
For i As Integer = 1 To 10
cs.RegisterStartupScript(cstype, csname1 & i, "wordit();", True)
Next
That second argument in that function call is looking for a unique key. This is a feature, to prevent accidentally programmatically adding the same script more than once. If you want to do it on purpose, you need a unique key each time.
But that you want to do this at all indicates a possible fundamental misunderstanding about what's going on. While your server code (including Page_Load) is running, your client page in the web browser doesn't exist. The purpose of the server code is always to generate an html response to web request. The server code can never directly manipulate a page DOM.
Obviously this is true for a first request to a page in session: the server must first generate the initial page to send the client. But even on subsequent postbacks, the browser will destroy the prior instance of a page. The server must rebuild the entire page from scratch. Every. Time. While this happens, the page you're looking at in your browser window is only a sort of after-image. The browser has already destroyed any prior DOM, and is waiting for the server to supply a whole new set of HTML.
I also wonder at your use of vbscript, rather than javascript. Using vbscript pretty much guarantees you're page will only work with Internet Explorer.

Related

Call VB Sub from Embedded GeckoWebBrowser using window.external.Sub1();

I have an aspx page on my webserver which I load through an embedded web browser on a windows form. I am able to call the Sub1 from javascript window.external procedure. This is only when using the standard VB control WebBrowser. I have the necessary permissions active with
<PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
<System.Runtime.InteropServices.ComVisibleAttribute(True)> _
This works just fine. However, I am in need of using GeckoFx as my javascript is too complex for the standard WebBrowser as well as my styling.
I have tried the same approach as is, just with the geckobrowser, but it does not work at all, is there any:
GeckoPrefereces.User("somesetting") = True
that I need to activate to get it to work or is there something else I am missing?
I would just like to call the 'form close' procedure of my windows form, from the webpage which is embedded in the GeckoBrowserControl.
Refer the following link for your answer as it is solved here.
How to call C# method in javascript by using GeckoFX as the wrapper of XULRunner
Change this process to C# as VB cannot send the message to a procedure, only store the value and this creates a difficult situation in reading the data later.
then:
private void showMessage(string s)
{
if (s == "some data")
{
//Do stuff here you need to, ie. close the form, etc
}
}
This allows you to read the message sent and do with it what you wish.
Also important:
browser.AddMessageEventListener("myFunction", ((string s) => this.showMessage(s)));
must be before you load the html or the url
myBrowser.Navigate("www.google.com");

Property in viewstate different on one page to another

This is really weird error i'm getting and i'll try and explain as best I can.
I have two pages - Page 1 (form) and Page 2 (completed page)
From page 1 I put a variable into a database and then do a server.transfer to page two like so...
Server.Transfer("Page2.aspx", True)
On page 2 I then grab the variable called paymentOnHold which is set on Page 1 and goes into the database...
Here is how I set paymentOnHold on Page 1
Public Property paymentOnHold() As String
Get
Dim _paymentOnHold As Object = ViewState("paymentOnHold")
If _paymentOnHold IsNot Nothing Then
Return CType(_paymentOnHold, String)
Else
Return Nothing
End If
End Get
Set(ByVal value As String)
If Not String.IsNullOrEmpty(value) Then
ViewState("paymentOnHold") = value
Else
ViewState("paymentOnHold") = Nothing
End If
End Set
End Property
...
paymentOnHold = Date.Now.ToString("yyyyMMddHHmmss")
Here's how I grab the value on Page 2...
Dim myValue As String
If TypeOf PreviousPage Is Page1 Then
myValue = DirectCast(PreviousPage, Page1).paymentOnHold
End If
In my development environment where the databases are local the value in the DB and the value on page 2 both match - as you would expect...
In live environment the DB value is 3 or 4 seconds different (before) the one on Page 2 - even though I do not reset it or anything?
This has been driving me crazy for the last few hours and cannot work it.
Does anyone have any ideas/suggestions as to what might be causing this?
Thanks in advance
This could be an issue of saving the view state in first Page (form-1)
In asp.net Page lifecycle
1. Initalization (controls raise their Init event)
2. Load ViewState (Only on post back)
3. Load PostbackData
4. Load
5. Raise PostbackEvent
6. Save View State
7. Render
Server.Transfer() stops rendering the current page and starts rendering another one.That's why Server.Transfer() cannot be used to redirect to pages served by another server.
If you are doing Server.transfer before Event--> 6. Save View State you are not saving viewstate on the form-1
Solution
Response.redirect and session cache, as it is intended to exist per user and across multiple pages in the application.
Using ViewState in this manner is a brittle solution, because ViewState is not intended to exist outside of the scope of the page it was initiated in, much less passed between pages, which I realize you are not quite doing, but you are getting dangerously close to doing it.
The better approach is to use Session cache, as it was intended to exist per user and span multiple page requests.
Try this:
To store in Session, do this:
Session("PaymentOnHold") = [Date].Now.ToString("yyyyMMddHHmmss")
To retrieve a value from Session, do this:
' First check to see if the value is in Session cache or not
If Session("PaymentOnHold") IsNot Nothing Then
' Everything in Session cache is stored as an object so you need to cast it to get it out
Dim datePaymentOnHold As DateTime = TryCast(Session("PaymentOnHold"), DateTime)
End If
Now the Session value will be available no matter how you navigate to pages (Server.Transfer or Response.Redirect).

Session and XMLHTTP

I have two asp pages on the same server. The first one generates XML dynamically using querystring informations and session information. The second one reads the first one using an XMLHTTP object and do things using the XML datas.
However, my problem is that the XMLHTTP request is done server-side. Thus, the session variables of the client are not accessible when the xml should be generated.
How can I do so that the page that generates the XML receives the session variables ?
Thanks.
There are many problems with what you are trying to do, not least is that it can lead a busy server to lock up entirely.
Here is the another approach.
Add a third page to your solution. This page contains simply a function which returns an XML DOMDocument. This function contains all the logic from your original xml generating page but builds the XML into the DOM (which you were probably doing all ready right?).
Now your original page simply includes this new function page, calls the function and sends the DOM to the response:
<!-- #include file="xmlFunction.asp" -->
<%
Response.ContentType = "text/xml"
Response.CharSet = "UTF-8"
GenerateXml().Save Response
%>
Your client page can now look this
<!-- #include file="xmlFunction.asp" -->
<%
. . .
Dim dom: Set dom = GenerateXml()
''# Code that uses the XML in the dom.
%>
No additional "Request to self" is needed hence no potential lock up. Since code in the xmlFunction.asp is running as part of the original request the appropriate Session object is accessible.

Why do session variables not work properly when following a link from an MS Word document

If you have a link to a webpage in a MicroSoft Word document and you follow this link to get to the web page ASP.Net session variables do not always work as expected.
In particular they work the first few times and then later on they stop working.
For instance if you have a link to an MVC Page like:
http://localhost/Home/TransferToWebForm
and in the controller you have:
public ActionResult TransferToWebForm()
{
Session["SessionVarFromMVC"] = "Some Value";
return Redirect("~/WebForm.aspx");
}
Then in the target page (WebForm.aspx) you try to retrieve these session variables they are empty.
<%= string.IsNullOrEmpty(Session["SessionVarFromMVC"])
? "***Session Empty***"
: Session["SessionVarFromMVC"] %>
(I discovered in Office 2007 and I'm not sure if the problem exists in other versions)
The problem is that when you first follow the link from Microsoft Word the server sets a cookie (ASP.NET_SessionId) and word remembers this. Subsequent clicks on the link cause the same cookie to be sent to the server with the new request.
Everything works fine with this process until that session times out on the server. On the next click Word sends the cookie with the request and the server no longer has a valid session for it. In this case the the session variables set by the first page simply fall off the end of the earth (so to speak) and are not available to the next page.
The thing that is puzzling to me is why is Word storing the session cookie?

is it possible to issue dynamic include in asp-classic?

I mean, like php'h include...
something like
my_file_to_be_included = "include_me.asp"
-- >
for what I've seen so far, there are a couple of alternatives, but every one of them has some sort of shortcoming...
what I'm trying to figure out is how to make a flexible template system... without having to statically include the whole thing in a single file with a loooooong case statement...
here there are a couple of links
a solution using FileSysmemObject, just lets you include static pages
idem
yet another one
same thing from adobe
this approach uses Server.Execute
but it has some shortcomings I'd like to avoid... seems like (haven't tried yet) Server.Execute code runs in another context, so you can't use it to load a functions your are planning to use in the caller code... nasty...
same thing
I think this one is the same
this looks promising!!!
I'm not sure about it (couldn't test it yet) but it seems like this one dinamycally handles the page to a SSDI component...
any idea???
No you can't do a dyanmic include, period.
Your best shot at this is a server.execute and passing whatever state it needs via a Session variable:-
Session("callParams") = BuildMyParams() 'Creates some sort of string
Server.Execute(my_file_to_be_included)
Session.Contents.Remove("callParams")
Improved version (v2.0):
<%
' **** Dynamic ASP include v.2.0
function fixInclude(content)
out=""
if instr(content,"#include ")>0 then
response.write "Error: include directive not permitted!"
response.end
end if
content=replace(content,"<"&"%=","<"&"%response.write ")
pos1=instr(content,"<%")
pos2=instr(content,"%"& ">")
if pos1>0 then
before= mid(content,1,pos1-1)
before=replace(before,"""","""""")
before=replace(before,vbcrlf,""""&vbcrlf&"response.write vbcrlf&""")
before=vbcrlf & "response.write """ & before & """" &vbcrlf
middle= mid(content,pos1+2,(pos2-pos1-2))
after=mid(content,pos2+2,len(content))
out=before & middle & fixInclude(after)
else
content=replace(content,"""","""""")
content=replace(content,vbcrlf,""""&vbcrlf&"response.write vbcrlf&""")
out=vbcrlf & "response.write """ & content &""""
end if
fixInclude=out
end function
Function getMappedFileAsString(byVal strFilename)
Dim fso,td
Set fso = Server.CreateObject("Scripting.FilesystemObject")
Set ts = fso.OpenTextFile(Server.MapPath(strFilename), 1)
getMappedFileAsString = ts.ReadAll
ts.close
Set ts = nothing
Set fso = Nothing
End Function
execute (fixInclude(getMappedFileAsString("included.asp")))
%>
Sure you can do REAL classic asp dynamic includes. I wrote this a while back and it has opened up Classic ASP for me in a whole new way. It will do exactly what you are after, even though people seem to think it isn't possible!
Any problems just let me know.
I'm a bit rusty on classic ASP, but I'm pretty sure you can use the Server.Execute method to read in another asp page, and then carry on executing the calling page. 15Seconds had some basic stuff about it - it takes me back ...
I am building a web site where it would have been convenient to be able to use dynamic includes. The site is all ajax (no page reloads at all) and while the pure-data JSON-returning calls didn't need it, all the different html content for each different application sub-part (window/pane/area/form etc) seems best to me to be in different files.
My initial idea was to have the ajax call be back to the "central hub" main file (that kicks the application off in the first place), which would then know which sub-file to include. Simply including all the files was not workable after I realized that each call for some possibly tiny piece would have to parse all the ASP code for the entire site! And using the Execute method was not good, both in terms of speed and maintenance.
I solved the problem by making the supposed "child" pages the main pages, and including the "central hub" file in each one. Basically, it's a javascript round-trip include.
This is less costly than it seems since the whole idea of a web page is that the server responds to client requests for "the next page" all the time. The content that is being requested is defined in scope by the page being called.
The only drawback to this is that the "web pieces" of the application have to live partly split apart: most of their content in a real named .asp file, but enough of their structure and relationship defined in the main .asp file (so that, for example, a menu item in one web piece knows the name to use to call or load another web piece and how that loading should be done). In a way, though, this is still an advantage over a traditional site where each page has to know how to load every other page. Now, I can do stuff like "load this part (whether it's a whole page or otherwise) the way it wants to be loaded".
I also set it up so each part can have its own javascript and css (if only that part needs those things). Then, those files are included dynamically through javascript only the first time that part is loaded. Then if the part is loaded repeatedly it won't incur an extra overhead.
Just as an additional note. I was getting weird ASCII characters at the top of the pages that were using dynamic includes so I found that using an ADODB.Stream object to read the include file eliminated this issue.
So my updated code for the getMappedFileAsString function is as follows
Function getMappedFileAsString(byVal strFilename)
Dim fso
Set fso = CreateObject("ADODB.Stream")
fso.CharSet = "utf-8"
fso.Open
fso.LoadFromFile(Server.MapPath(strFilename))
getMappedFileAsString = fso.ReadText()
'Response.write(getMappedFileAsString)
'Response.End
Set fso = Nothing
End Function

Resources