Open a text file in new tab - javascript

I have a text file in my local drive. I want to show the content of it in a new tab.
I have tried the following
1st Try
string fileName = #"C:\MyFile.log";
Page.ClientScript.RegisterStartupScript(GetType(), "windowKey", "window.open('" + fileName + "');", true);
2nd Try
Response.Write("<script>");
Response.Write("window.open('C:\\MyFile.log', '_newtab');");
Response.Write("</script>");
Both of these open in new tab but the data inside the file is not displaying
After some search, I found this
FileStream MyFileStream = new FileStream(#"C:\MyFile.log", FileMode.Open);
long FileSize;
FileSize = MyFileStream.Length;
byte[] Buffer = new byte[(int)FileSize];
MyFileStream.Read(Buffer, 0, (int)MyFileStream.Length);
MyFileStream.Close();
Response.ContentType = "text/plain";
Response.AddHeader("content-disposition", "inline; filename=sample.txt");
Response.BinaryWrite(Buffer);
This is displaying the content in my file but along with that it is also displaying my aspx page
So my question is how to show a text file in a new tab

try those steps
create a log.aspx and put the code from the third snippet to it.
use 1st or 2nd snippet to open log.aspx in the new window (tab)
that way it should work.

I have tried like this:
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Test.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:Button id="btnShowContent" Text="Show me the text" runat="server" OnClick="btnShowContent_Click" />
</div>
</form>
</body>
</html>
Default.aspx.cs
protected void btnShowContent_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, typeof(string), "OpenTextFile", "Javascript:window.open('Resources/test.txt');", true);
}
You just need to update your file path.
Hope this is what you want.

Related

how to pass value from javascript to ASP control

Good day,
Been new to web development (i use ASP.NET) and i had this goal of passing/returning a value to display on HTML element such such as input. I had done searching and trying most of the solutions i found but none work, the output still returns an empty value on the HTML input. why is that? my code i'm working on can be seen below:
javacript:
function confirmExistence(entityValue) {
var entity = "Staff";
var result = "";
if (entityValue === '0') {
entity = "Student";
}
if (confirm(entity + " w/ same name is already registered. is this a different " + entity + "?")) {
result = "Yes";
} else {
result = "No";
}
alert(result);
document.getElementById('<%= fieldFirstNameStudent.ClientID %>').value = result;
}
html:
<asp:button class="by-button" id="btnStudentEnc" runat="server" text="Encode" OnClick="btnStudentEnc_Click" />
<asp:textbox type="text" class="mfield" placeholder="First Name" id="fieldFirstNameStudent" runat="server" />
asp c#:
protected void btnStudentEnc_Click(object sender, EventArgs e)
{ **some sql database condition here to run the clientscript below**
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"studentConfirmExistence", "confirmExistence('0');", true); }
Result is as follows on this image:
UPDATE: IF ABOVE IS TOO COMPLICATED. i created a new web form having simple block of codes that still doesn't work
Aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="LobbyStudents.aspx.cs" Inherits="LobbyStudents" %>
<asp:Content ID="Content0" ContentPlaceHolderID="title" Runat="Server">
LobbyStudents
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script>
function confirmExistence(entityValue) {
alert(entityValue);
document.getElementById("<%= fieldFirstNameStudent %>").value = "whatswrong?";
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:textbox placeholder="First Name" id="fieldFirstNameStudent" runat="server"/>
<asp:button runat="server" text="Encode" OnClick="btnStudentEnc_Click"></asp:button>
</asp:Content>
Aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class LobbyStudents : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnStudentEnc_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"studentConfirmExistence", "confirmExistence('0');", true);
}
}
ClientScript works and even does the alert box. Still textbox is still empty and doesn't contain "whatswrong?" value
unlike i try it on this one:
<!DOCTYPE html>
<html>
<body>
Name: <input type="text" id="myText" value="tch">
<p>Click the button to change the value of the text field.</p>
<button onclick="confirmExistence('0')">Try it</button>
<script>
function confirmExistence(entityValue) {
alert(entityValue);
document.getElementById("myText").value = "whatswrong?";
}
</script>
</body>
</html>
where it works.
What's the difference between the two and why it doesn't happen on asp controls
ok, figure out what is the issue for your first example, is not related to the position, but
change your
document.getElementById("<%= fieldFirstNameStudent %>").value = "whatswrong?";
to
document.getElementById("<%= fieldFirstNameStudent.ClientID %>").value = "whatswrong?";
this will generated in html as
document.getElementById("System.Web.UI.WebControls.TextBox").value = "whatswrong?";
which the js not able to find the control name as System.Web.UI.WebControls.TextBox
if assign with .ClientID, it will generate the correct id
document.getElementById("MainContent_fieldFirstNameStudent").value = "whatswrong?";

In a JSP file , how to call a Scriptlet code within a javascript

I have a static scriptlet code which works fine. I want to call this static code when the user clicks on a button in the html page. So is it possible to create a function in javascript, which is called when the user clicks the html button and inside the function the scriptlet code be placed?
Please give the exact code of how to achieve this
My static scriptlet code is as follows:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%# page import="java.io.*" %>
<%# page import="com.lowagie.text.Document" %>
<%# page import="com.lowagie.text.Element" %>
<%# page import="com.lowagie.text.html.simpleparser.HTMLWorker" %>
<%# page import="com.lowagie.text.html.simpleparser.StyleSheet" %>
<%# page import="com.lowagie.text.pdf.PdfWriter" %>
<%# page import="com.lowagie.text.pdf.codec.Base64" %>
<%# page import="java.util.ArrayList" %>
<%
// This scriptlet declares and initializes "date"
Document pdfDocument = new Document();
Reader htmlreader = new BufferedReader(new InputStreamReader(
new FileInputStream("E:\\test.html")
));
htmlreader.read();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(pdfDocument, baos);
pdfDocument.open();
StyleSheet styles = new StyleSheet();
styles.loadTagStyle("body", "font", "Bitstream Vera Sans");
ArrayList arrayElementList = HTMLWorker.parseToList(htmlreader, styles);
for (int i = 0; i < arrayElementList.size(); ++i) {
Element e = (Element) arrayElementList.get(i);
pdfDocument.add(e);
}
pdfDocument.close();
byte[] bs = baos.toByteArray();
String pdfBase64 = Base64.encodeBytes(bs); //output
File pdfFile = new File("E:\\test.pdf");
FileOutputStream output = new FileOutputStream(pdfFile);
output.write(bs);
output.close();
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>
Hello! The time is now
<%
// This scriptlet generates HTML output
out.println( String.valueOf( date ));
%>
</body>
</html>
is it possible to create a function in javascript which is called when the
user clicks the html button
Answer: Yes
and inside the function the scriptlet code be placed?
Answer: No
The solution is to make use of Javascript ajax. If you are using jquery make use of jquery ajax.

Getting session value in javascript

I am using an external javascript file for my asp.net project. Now i want to get the session value in that javascript. How can i get the session value in that javascript file?
Thanks in advance..
<script>
var someSession = '<%= Session["SessionName"].ToString() %>';
alert(someSession)
</script>
This code you can write in Aspx. If you want this in some js.file, you have two ways:
Make aspx file which writes complete JS code, and set source of this file as Script src
Make handler, to process JS file as aspx.
You can access your session variable like '<%= Session["VariableName"]%>'
the text in single quotes will give session value.
1)
<script>
var session ='<%= Session["VariableName"]%>'
</script>
2) you can take a hidden field and assign value at server;
hiddenfield.value= session["xyz"].tostring();
//and in script you access the hiddenfield like
alert(document.getElementbyId("hiddenfield").value);
For me this code worked in JavaScript like a charm!
<%= session.getAttribute("variableName")%>
hope it helps...
I tried following with ASP.NET MVC 5, its works for me
var sessionData = "#Session["SessionName"]";
protected void Page_Load(object sender, EventArgs e)
{
Session["MyTest"] = "abcd";
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
if (TextBox1.Text.Equals("")) { }
else {
Session["MyTest"] = TextBox1.Text;
}
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script language=javascript type="text/javascript">
function getMyvalSession() {
var txt = "efgh";
var ff = '<%=Session["MyTest"] %>' + txt;
return ff ;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack=true ></asp:TextBox>
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
If you are using VB as code behind, you have to use bracket "()" instead of square bracket "[]".
Example for VB:
<script type="text/javascript">
var accesslevel = '<%= Session("accesslevel").ToString().ToLower() %>';
</script>
var sessionVal = '#Session["EnergyUnit"]';
alert(sessionVal);

Current context value is not rendered from Usercontrol to .aspx page

i have default.aspx page and one user control.
usercontrol is having following code for multiple file uploads.
now the problem is when i add a file for upload that current context file is not giving me any value it is still zero i guess because it is rendering from user control.
what should i do?
My Usercontrol UPLOAD.ASCX
<%# Control Language="C#" AutoEventWireup="true" CodeFile="FileUpload.ascx.cs" Inherits="FileUpload" %>
<script type="text/javascript" src="_scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
var i = 1;
$(document).ready(function () {
$("#addfile").click(function () {
$("#dvfiles").append("<input name=" + i + "fu type=file /><a href=#>remove</a><br>");
i++;
});
$("#dvfiles a").live('click', function () {
$(this).prev("input[type=file]").remove();
$(this).remove();
});
});
$(document).submit(function () {
var flag = true;
$("#dvfiles input[type=file]").each(function () {
if ($(this).val() == "") {
$(this).css("background", "Red");
flag = false;
}
});
return flag;
});
</script>
<div id="Fileuploader">
Attach a file..<br />
<asp:Label ID="lblMessage" runat="server"></asp:Label><br />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
onclick="btnUpload_Click" />
</div>
UPLOAD.ASCX.CS
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
HttpFileCollection filecolln = Request.Files;
//here i don't get values of current files.
// this is zero. because of this following if condition failed
//please help here
if (filecolln.Count > 0)
{
for (int i = 0; i < filecolln.Count; i++)
{
HttpPostedFile file = filecolln[i];
if (file.ContentLength > 0)
{
file.SaveAs(ConfigurationManager.AppSettings["FilePath"] + System.IO.Path.GetFileName(file.FileName));
}
}
lblMessage.Text = "Uploaded Successfully!";
}
else
{
lblMessage.Text = "No files selected!";
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
}
Default.aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<%# Register TagPrefix="ucFileuploader" tagName="Fileuploader" src="FileUpload.ascx" %>
<!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>
<form id="form1" runat="server">
<div>
<ucFileuploader:Fileuploader ID="Fileuploder" runat="server" />
</div>
</form>
</body>
</html>
The problem is that you are using javascript an id names.
so when you have control with id addfile in .aspx it is rendered as is,
but when you have control with id addfile in user control with id Fileuploader,
than the rendered id is Fileuploader_addfile,
so change id name in java script with the proper id.
To chechk what is name of rendered id, open page in browser, open source of the page and find you element and copy id into java script.
Change all ids in java script with rendered id names.
I would suspect it could be this line:
<script type="text/javascript" src="_scripts/jquery-1.4.1.min.js"></script>
Which should be:
<script type="text/javascript" src="/_scripts/jquery-1.4.1.min.js"></script>

How to get the last modified date of the uploaded file?

I upload an XML file to migrate its contents to my database, but I want firstly store the last modified date of that file to assure that no change has happened to that file from the last one.
How do I get the last modified date of the file ?
Is there any javascript function to do that?
This information is never sent to the server when you use a file input to upload a file. Only the filename, mime type and contents are sent with multipart/form-data. You could use the HTML5 File API to obtain this information from the file before uploading it.
As requested in the comments section here's an example of an ASP.NET page which has an upload control and a hidden field which will be used to store and send the file last modified date to the server using the HTML5 File API:
<%# Page Language="C#" %>
<%# Import Namespace="System.Globalization" %>
<script type="text/C#" runat="server">
protected void BtnUploadClick(object sender, EventArgs e)
{
var file = Request.Files[0];
DateTime date;
if (DateTime.TryParseExact(lastModifiedDate.Value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
// you could use the date here
}
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="Form1" runat="server">
<label for="up">Pick a file</label>
<asp:FileUpload ID="up" runat="server" />
<asp:HiddenField ID="lastModifiedDate" runat="server" />
<asp:LinkButton ID="btnUpload" runat="server" Text="Upload" OnClick="BtnUploadClick" />
</form>
<script type="text/javascript">
if (!window.File) {
alert('Sorry, your browser doesn\'t support the File API so last modified date will not be available');
} else {
document.getElementById('<%= up.ClientID %>').onchange = function () {
if (this.files.length > 0) {
if (typeof this.files[0].lastModifiedDate === 'undefined') {
alert('Sorry, your browser doesn\'t support the lastModifiedDate property so last modified date will not be available');
} else {
var lmDate = this.files[0].lastModifiedDate;
var hidden = document.getElementById('<%= lastModifiedDate.ClientID %>');
hidden.value = lmDate.getFullYear() + '-' + (lmDate.getMonth() + 1) + '-' + lmDate.getDate();
}
}
};
}
</script>
</body>
</html>
So in this example we subscribe for the onchange event of the file input and if the client browser supports HTML5 File API we can obtain information about the selected file such as its name, size, last modified date, ... In this example we store the last modified date into a hidden field so that this information is available on the server once we upload the file.
System.IO.FileInfo object should yield a LastWriteTime property
FileInfo myFileInfo= new FileInfo(path) ;
myFileInfo.Refresh();
string t = myFileInfo.LastWriteTime.ToString("F")

Categories

Resources