Write 2 hta program in single hta and call sub hta as new window - hta

How to write sub hta in my main hta so that the sub hta is hidden in main hta and when clicking a button from main hta, the sub hta should pop up just like a window.
I don't want to program these main and sub hta's as 2 separate files and call sub hta from main hta.

There is a way -that I can think of- to do that but it's really painful. The same way Teemu mentioned. But If you insist on a single hta file, here's your code:
<html>
<head>
<title>Main HTA</title>
<HTA:APPLICATION
SCROLL="no"
INNERBORDER="no"
/>
</head>
<body>
This is the main HTA <br /><br />
<input type="button" value="open sub hta" onclick="runSubHTA(subhta)" />
<script type="text/javascript">
// path to the new (sub) hta file
var subhta = "subhta.hta";
// function to create and launch the sub hta file
function runSubHTA(path) {
// creating the new hta file
var fso = new ActiveXObject("Scripting.FileSystemObject");
var sub = fso.CreateTextFile(subhta, true);
// writing to the created hta file
sub.WriteLine("<title>Sub HTA<\/title>");
sub.WriteLine("Welcome to the sub HTA <br />");
// this code will run on the sub hta before exit
// and it'll delete the sub hta file, meaning itself
sub.WriteLine('<script type="text/javascript">');
sub.WriteLine('var subhta = "subhta.hta";');
sub.WriteLine('window.onbeforeunload = function() {');
sub.WriteLine('var fso = new ActiveXObject("Scripting.FileSystemObject");');
sub.WriteLine('var sub = fso.DeleteFile(subhta, 1);');
sub.WriteLine('}<\/script>');
// closing the connection to the file, we're done writing
sub.Close();
// launching the sub hta file
WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run(path, 1, false);
}
</script>
</body>
</html>
Coding 2 separate hta files would be much easier. This way you have to embed your sub hta code line by line. But there might be a better way to do it. Like writing the whole page in a single line with line-breaks and indenting. I haven't tried something like this before so I can't help on this. But if you find a way to do it, do share.

Related

asp.net placeholder in the head of a page

I have a page that includes javascript which I only want to run under certain conditions. To do this I have placed the scripts into an asp:placeholder
This actually seems to work but when I run a debug on the page I get the following warning.
Element 'placeholder' is not a known element. This can occur if there is a compilation error in the Web site, or the web.config file is missing.
If I move the placeholders into the body of the page the warning goes, but that means I'm left with scripts in the body which I also want to avoid. Does anyone have any hints on the best practice for this scenario?? thanks
Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
dim lt as new Literal()
lt.text = "<script type='text/javascript' src='scripts/pageLoadAnimations.js'></scr" & "ipt>"
me.Header.Controls.Add(lt)
End Sub
You can include JS file straight from code behind:
If (some condition is true) Then
Page.ClientScript.RegisterClientScriptInclude("jQuery", "jquery-version.js")
End If
A couple of ways which fit your needs are:
Firstly, you could change your <head> tag to <head id="header" runat="server"> then this allows you to dynamically add anything into it, e.g.
dim lt as new Literal()
lt.text = "<script type='text/javascript' src='pathtojavascriptfile'></script>"
me.Header.Controls.Add(lt)
Or you could create a Public string on your page, then stick the javascript in this.
Public _JS as string
Page_Load
_JS = "alert('here');" ' Or what ever your javascript is
ASPX Page
<head>
<script type="text/javascript" src="jquery-version.js"></script>
<script type="text/javascript">
$().ready(function(){
<%=(me._JS) %>
});
</script>
</head>
You might consider looking into the ClientScriptManager. This will allow you to inject scripts into the header properly using whatever conditions you require.
Including Custom Client Script in ASP.NET Pages
ClientScriptManager Class

JavaScript question

calling a js function using onclick...
onclick="SubmitAge(66, 'ctl00_MainContent_arTo_upAgeRange')"
function just calls an updatePanel from the client... but its saying object expected at the onclick= part!!!
here is the function, is there anything wrong with the code?
function SubmitAge(age, UpdatePanelID) {
$get('HiddenAge').value = age;
__doPostBack(UpdatePanelID);
}
EDIT: THE SUBMITAGE FUNCTION IS INSIDE A .JS FILE (AGERANGE.JS) AND ONLY WHEN MOVED HERE DOES IT STOP WORKING: HERE IS THE LINKING METHOD/HEADERS FROM THE ASCX USERCONTROL INWHICH IT IS ALL CONTAINED...
%# Control Language="VB" ClassName="AgeRange" %
%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AjaxCT" %
script src="AgeRange.js" type="text/javascript" /script
(arrow tags removed here as it wont display, hint: stackoverflow!!!)
im printing it like this from the server...
Public Sub AppendToSB(ByRef sb As StringBuilder, ByVal CurNo As Byte, Optional ByVal clickedNo As Byte = 0)
Dim sConfirmClick = ""
If clickedNo = CurNo Then ' maybe dont make it clickable...
sConfirmClick = "return confirm('The number " & CurNo.ToString & " is already selected, are you sure you want to select it again?');"
End If
sb.Append("<a href=""#"" onclick=""" & sConfirmClick & "SubmitAge(" & CurNo.ToString & ", '" & upAgeRange.ClientID &
"')"" runat=""server"">" & CurNo.ToString & "</a>")
End Sub
Complete rewrite of my post after several clarifications:
The problem is that the ASPX page is referencing an ASCX user control that is located in a different folder. That ASCX control has an HTML <script> tag that is using a relative path to the JS file.
The solution is to correctly resolve the URL to the JS file by using some extra code:
<script src="<%= ResolveClientUrl("MyScriptLibrary.js") %>" type="text/javascript">
</script>
To prevent the script file from being referenced multiple times I recommend using the approaches specified in this other post:
ASP.NET dynamically insert code into head
Here's what it looks like in the user control's code:
// Register a script reference:
Page.ClientScript.RegisterClientScriptInclude(GetType(), "myLibraryScript", "~/Scripts/MyScriptLibrary.js");
here is how i decided to do it, ResolveClientURL is important, static link will not always work, also the if check will prevent the script being added several times in one page if you use the control multiple times on same page...
If Not Page.ClientScript.IsClientScriptIncludeRegistered("AgeRangeJS") Then ' no point in registering it twice!
' AND its registered in the header, where it should be, not two copies in the body :)
Page.ClientScript.RegisterClientScriptInclude("AgeRangeJS", ResolveClientUrl("AgeRange.js")) ' ResolveClientUrl("AgeRange.js")
End If

ASP.NET which control could wrap JS block and extractable so I could render it back to header

As title, basically I have a user control placed inside a page and then the page is placed inside the master page. I want to extract a block of javascript and put it back to the page head. When I try to wrap the code inside any block control (e.g. a div runat server) and access divID.InnerText then ASP.NET bust off with
Cannot get inner content of startup_script because the contents are not literal.
I dont want to extract JS inside cs file, thats awfully ugly approach (all sort of escapes and people wont even notice you have JS written unless they drill your CS file), what can I do?
You could store the javascript in a separate file, and then add it to the page using Page.RegisterClientScriptBlock()
Add the javascript you want to a .js file and add the .js file to your project.
Alter the properties of the .js file so that it is an Embedded Resource.
Then use code like this somewhere in your UserControl (maybe the Page_Load) to pull the code from the file and drop it into the page:
string javaScript = "";
// the javascript is in a separate file which is an 'embedded resource' of the dll
using (StreamReader reader =
new StreamReader((typeof(ThisClass).Assembly.GetManifestResourceStream(typeof(ThisClass), "NameOfJavaScriptFile.js"))))
{
javaScript = String.Format("<script language='javascript' type='text/javascript' >\r\n{0}\r\n</script>", reader.ReadToEnd());
}
Page.RegisterClientScriptBlock("MyScriptBlock", javaScript);
Note that RegisterClientScriptBlock() will put the script near the top of the page, but apparently not in the page header.
(edited bit about header after comment)
<%# Page Language="C#"%>
<script runat=server>
protected override void OnLoad(EventArgs e)
{
string scriptText = someID.InnerHtml;
//if you really want it in the header...
//Page.Header.Controls.Add( new LiteralControl(String.Format( "<scr" + "ipt language=\"javascript\">{0}</scri" + "pt>\\n", scriptText )));
//doesnt add to header and requires form runat=server
Page.ClientScript.RegisterStartupScript(this.GetType(), "SomeScript", scriptText, true);
base.OnLoad(e);
}
</script>
<head runat=server></head>
<form runat=server>
<div id="someID" runat=server>alert('hi');</div>
</form>
Okay, I've probably done this in a horrible, horrible way, but I wanted to add a script to the head element in a recent project from a user control. This script didn't require any data from my server, but I only wanted it on specific pages, so I put the script in a .js-file, and added it to the head like this:
HtmlGenericControl script = new HtmlGenericControl("script"); // Creates a new script-element
script.Attributes.Add("type","text/javascript");
script.Attributes.Add("src","src/to/js-file.js");
Page.Master.FindControl("head").Controls.Add(script); // Finds the element with ID "head" on the pages master page.
Not entirely sure if the code works as I think it does as the code I wrote for the project is on another machine, but you get the idea, right?
Edit:
After googling your error message for a bit, I think this might be a solution to your problem:
using System.IO;
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
yourDivID.RenderControl(h);
String str = sw.GetStringBuilder().ToString();
If you combine the two examples, you should be able to get the result you want. I haven't tested this, but it works in my head.

Programmatically adding Javascript File to User Control in .net

How do you add Javascript file programmatically to the user control?
I want the user control to be a complete package - ie I don't want to have to add javascript that's related to the user control on the page where it's used, when I can do it inside the control itself.
Since there is no Page object in the user control, how would you do it?
In the Page_Load method of control.ascx.cs file:
LiteralControl jsResource = new LiteralControl();
jsResource.Text = "<script type=\"text/javascript\" src=\"js/mini-template-control.js\"></script>";
Page.Header.Controls.Add(jsResource);
HtmlLink stylesLink = new HtmlLink();
stylesLink.Attributes["rel"] = "stylesheet";
stylesLink.Attributes["type"] = "text/css";
stylesLink.Href = "css/mini-template-control.css";
Page.Header.Controls.Add(stylesLink);
This will load css and Javascript into the head tag of the main page, just make sure that the head has runat="server".
You can register client script includes using the ClientScriptManager.
Page is accessible through the Control.Page property.
Page.ClientScript.RegisterClientScriptInclude (
typeof ( MyControl ), "includeme.js", "js/includeme.js" );
EDIT: Sorry, for a total "complete package", its possible using scripts as Embedded Resources,
and aquire dynamic URL's through the WebResource.axd handler.
If this is not considered totally complete, then i guess it could be put in App_LocalResources, but it never gonna be just one file,
unless the code and script is inline.
The same as gnomixa's response, only a bit cleaner:
HtmlGenericControl js = new HtmlGenericControl("script");
js.Attributes["type"] = "text/javascript";
js.Attributes["src"] = "jscript/formfunctions.js";
Page.Header.Controls.Add(js);
from http://www.aspdotnetfaq.com/Faq/How-to-Programmatically-add-JavaScript-File-to-Asp-Net-page.aspx
In my site I Place all needed scripts and styles to placeHolder
<asp:placeHolder runat="Server" ID="phHead">
<script src="/header/widget/script.js" type="text/javascript"></script>
<link href="/header/widget/style.css" rel="stylesheet" type="text/css" />
</asp:placeHolder>
and
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Page.Header.Controls.Add(phHead)
End Sub
Good question!
A UserControl should be a single package without any dependency on a JavaScript or a CSS file. You will need to make the JS and CSS files as embedded resources. Right click properties and set build action to embedded resources. Then you need to inject the JavaScript and CSS files as WebResources.
Here is one article that I wrote yesterday which talks about the same scenario:
http://highoncoding.com/Articles/502_Creating_RadioButton_Validation_Using_Custom_Validator.aspx
I generally do it when rendering the HTML for the control and depending on whether it's a library injection or an instance injection I use the Items collection to specify whether or not I have already produced the code for a control of this type during the current request using a unique identifier.
Something to the effect of:
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
//Check if the Object Script has already been rendered during this request.
if (!Context.Items.Contains("xxx"))
{
//Specify that the Object Script has been rendered during this request.
Context.Items.Add("xxx", string.Empty);
//Write the script to the page via the control
writer.Write([libraryinjection]);
}
//Write the script that instantiates a new instance for this control
writer.Write([instanceinjection]);
}
If you have the text of the actual javascript in your .CS file, you can call Page.ClientScript.RegisterClientScriptBlock.
The following assumes that "GetScript()" returns the actual javascript you want added to the rendered control.
Page.ClientScript.RegisterClientScriptBlock(GetType(), "controlScriptName", GetScript());
I found this to be a more elegant way to fix-link to your javascript.
In your .ascx, link to your script files the following way:
<script src='<%= ResolveClientUrl("~/Scripts/jquery-1.7.1.min.js") %>' type="text/javascript"></script>
<script src='<%= ResolveClientUrl("~/Scripts/jquery.maskedinput-1.3.min.js") %>' type="text/javascript"></script>
That way, no matter which subfolder/page you add your user control to, the link to your scripts will always be correctly resolved.

Directory Structure within TreeView VB

Started to look at the Treeview control.
Is there anyway to tie the Tree View control into a Directory structure on the Web Server using Visual basic?
I have a lot of legacy files, which are updated and added often. Obviously I could code the structure in XML but this would be laborious and hard to train out to the end user.
I guess it would be a dynamic creation of an XML file perhaps?
Here's an elementary sample that I created awhile ago when learning to play with the TreeView. I have now converted the code to VB.NET using an online converter for your benefit.
It recursively walks the directory tree starting from the root of the virtual directory and creates nodes for each sub-directory or file encountered. I think this is exactly what you needed.
For visual separation, I had used icons to differentiate files from folders (folder.gif and file.gif). You can remove that parameter if you want.
Complete ASPX follows (You can paste it into a new page and it should run):
<%# Page Language="VB" %>
<%# Import Namespace="System.IO" %>
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Page.IsPostBack Then
Dim rootDir As New DirectoryInfo(Server.MapPath("~/"))
' Enter the RecurseNodes function to recursively walk the directory tree.
Dim RootNode As TreeNode = RecurseNodes(rootDir)
' Add this Node hierarchy to the TreeNode control.
Treeview1.Nodes.Add(RootNode)
End If
End Sub
Private Function RecurseNodes(ByVal thisDir As DirectoryInfo) As TreeNode
Dim thisDirNode As New TreeNode(thisDir.Name, Nothing, "Images/folder.gif")
' Get all the subdirectories in this Directory.
Dim subDirs As DirectoryInfo() = thisDir.GetDirectories()
For Each subDir As DirectoryInfo In subDirs
thisDirNode.ChildNodes.Add(RecurseNodes(subDir))
Next
' Now get the files in this Directory.
Dim files As FileInfo() = thisDir.GetFiles()
For Each file As FileInfo In files
Dim thisFileNode As New TreeNode(file.Name, Nothing, "Images/file.gif")
thisDirNode.ChildNodes.Add(thisFileNode)
Next
Return thisDirNode
End Function
</script>
<html>
<head>
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:treeview ID="Treeview1" runat="server"></asp:treeview>
</form>
</body>
</html>
A custom sitemap provider is a good bet.
There is a good article on 4guys title "Examining ASP.NET 2.0's Site Navigation - Part 4 "

Resources