I am absolutely certain I'm mixing two kinds of syntax incorrectly due to trying to hack together from different samples. I am not familiar with either ASPX nor VB.Net, and am stuck at the first hurdle.
The aim is for a user to enter a string of numbers (from a lastlogontimestamp in epoch time) and return it formatted as a local date/time.
It's failing at line 4 in IIS 7 - CS1026: ) expected.
<%# Page Language="VB" %>
<script runat="server">
Sub submit(sender As Object, e As EventArgs)
long value = (long)txt1.text
DateTime pwdLastSet = (DateTime.FromFileTimeUtc(value)).ToLocalTime
lbl1.Text="Converted date: " & pwdLastSet
End Sub
</script>
<html>
<head></head>
<body>
<form runat="server">
Enter the date string:
<asp:TextBox id="txt1" runat="server" />
<asp:Button OnClick="submit" Text="Submit" runat="server" />
<p><asp:Label id="lbl1" runat="server" /></p>
</form>
</body>
</html>
Update
Thanks for the comments, everyone. I'm definitely not a programmer. I did use the C# solution suggested in the comments as an exercise, with slight corrections. However, I am slightly more familiar with VB, so I should stick with that - the accepted answer was more intuitive to me.
<script runat="server">
void submit(Object sender, EventArgs e) {
long value = Convert.ToInt64(txt1.Text);
DateTime conValue = (DateTime.FromFileTimeUtc(value)).ToLocalTime();
lbl1.Text = "Converted date: " + conValue;
}
</script>
As the Page level language is defined as C# , so the compiler will try to compile the code as C#, and hence the expected exception is appearing. So changing the Language solves the exception
<%# Page Language="VB" %>
Now the actual Vb code is also wrong. As the way variables and casting is written its not the Way happen in VB.
<script runat="server" >
Sub submit(sender As Object, e As EventArgs)
Dim value = txt1.Text
Dim pwdLastSet = (DateTime.FromFileTimeUtc(value)).ToLocalTime
lbl1.Text="Converted date: " & pwdLastSet
End Sub
</script>
So I will suggest get the hold of language which you want to proceed with C# or VB, and do the changes accordingly.
As others have pointed out you have posted a weird hybrid between VB and C#. I'm not very familiar with C# but this should be more like it.
void submit(Object sender, EventArgs e) {
long value = (long)txt1.text;
DateTime pwdLastSet = (DateTime.FromFileTimeUtc(value)).ToLocalTime();
lbl1.Text = "Converted date: " + pwdLastSet;
}
Related
I have a few large, specifically formatted to the customer's request, tables with input. It looks similar to the following...
<body id="Body" class="Window" runat="server">
<form id="Form" runat="server" defaultbutton="SubmitLinkButton">
<!-- Markup for a the SubmitLinkButton and DropDownList -->
<!-- to pick which Table is shown -->
<asp:Table ID="Table1" runat="server">
<asp:TableRow class="row" runat="server">
<asp:TableCell runat="server">
<pre> Some Input1 </pre>
<pre>___________________</pre>
<pre>|___<asp:Textbox ID="Textbox1" runat="server"></asp:Textbox>____|</pre>
<pre>|_________________|</pre>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
<asp:Table ID="Table2" runat="server">
<asp:TableRow class="row" runat="server">
<asp:TableCell runat="server">
<pre> Some Input2 </pre>
<pre>___________________</pre>
<pre>|___<asp:Textbox ID="Textbox2" runat="server"></asp:Textbox>____|</pre>
<pre>|_________________|</pre>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</form>
</body>
Underwhelming, right?
Only one of the four tables is visible or not depending on the selection chosen in the DropDownList. Each table has upwards of 30-40 inputs and each area with inputs is formatted uniquely. All formatted the same way (^^^like above^^^), but one may have a section with 3 inputs and lots of text or 8 inputs and little text or no inputs and just a section of text.
Hopefully all of that makes sense.
What I need to figure out is how to have the user be able to "Submit" the form via the SubmitLinkButton which will send an email that looks identical to the form they filled out to a group of email addresses setup in the SystemFramwork.config.
I've attempted to do this, using Visual Basic, with RenderControl(), but I kept getting errors saying my Textboxes needed to be inside a form with runat="server" in it, and as you can see in my code above I have that. So, I'm not sure what was going on there.
Since the form is formatted so customized, If I can't somehow render the HTML form from page to email to have them look identical, I don't know any other option than to add the markup to the email manually, which just seems like a waste of time and making redundancies in the project.
Any insight would be greatly appreciated!
I'm still currently working with a pseudo solution that looks something like this...
Public Sub SubmitLinkButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SubmitLinkButton.Click
Dim result As String = vbNull
Dim stringWriter As New StringWriter()
Dim htmlWriter As New HtmlTextWriter(stringWriter)
'If the user selected something with the DropDown
If (DDL_Selection IsNot "")
Dim email As New MailMessage(FromConfigVar, ToConfigVar)
email.Subject = DDL_Selection.SelectedValue & " Table"
email.IsBodyHtml = True
Select Case DDL_Selection
Case "Table1"
Try
htmlWriter.RenderBeginTag(HtmlTextWriterTag.Table)
Table1.RenderControl(htmlWriter)
htmlWriter.RenderEndTag()
htmlWriter.Flush()
result = stringWriter.ToString()
Finally
htmlWriter.Close()
stringWriter.Close()
End Try
End Select
mailMessage.Body = result
Else
'Do nothing
End If
End Sub
Again, this solution is not working, nor do I think I'm even close to being on the right track. Just thought I'd show what I've tried.
If you override the Page's VerifyRenderingInServerForm Method to not perform the validation that is causing the issue you can get around this problem:
'This is in the Page's Code Behind.
Public Overrides Sub VerifyRenderingInServerForm (control As Control)
'Do Nothing instead of raise exception.
End Sub
I got this version working but did not get any user-input returned.
This puts the html into an email; uses HtmlAgilityPack.
using HtmlAgilityPack;
etc.
protected void btnTableToEmail_Click(object sender, EventArgs e)
{
try
{
StringWriter sw = new StringWriter();
using(HtmlTextWriter writer = new HtmlTextWriter(sw))
{
writer.AddAttribute("runat", "server");
writer.RenderBeginTag("form");
writer.Write(GetTableHTML());
writer.RenderEndTag();
}
SendEmail(sw);
}
catch(Exception)
{
throw;
}
}
private string GetTableHTML()
{
// uses HtmlAgilityPack.
var html = new HtmlDocument();
html.Load(Server.MapPath("~/yourpage.aspx")); // load a file
var root = html.DocumentNode;
var table = root.Descendants().Where(n => n.GetAttributeValue("id", "").Equals("Table1")).Single();
return table.InnerHtml;
}
private void SendEmail(StringWriter sw)
{
// your email routine.
// ...
msg.Body = sw.ToString();
}
Despite the firing of the method associated with a form and button click, my fileupload will not pass a value to a string, am I doing something obviously wrong (or just wrong in general)?
Do I need to attach a handler to the fileupload
Here is some sample source, note, it is the only code in the project, I have not made any definitions to the button or fileupload anywhere else:
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button_Click()
Dim FileUpload1 As New FileUpload()
Dim X As String = FileUpload1.FileName
Response.Write(X)
End Sub
End Class
and the form:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="Test.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button_Click" text="Submit"/>
<%-- <input type="file" />--%>
</form>
</body>
</html>
After trying FileUpload.HasFile, it appears as though not only can I not get the file name (described to me in the answer below), but the FileUpload.HasFile is nothing when a file is associated with it as well, is there any reason for this?
Protected Sub Button_Click()
Dim FileUpload1 As New FileUpload()
'Dim X As String = FileUpload1.FileName
'Response.Write(X)
If (FileUpload1.HasFile) Then
' Do Something
' SaveFile(FileUpload1.PostedFile)
Else
End If
End Sub
If you are looking for the path of the uploaded file in the client's machine, that is not allowed for security reasons.
However you should be able to get just the file name using the FileName property.
I check the file name in my applications when i want to test the to see the filetype that is uploaded.
I do not think the following line is required in your Protected Sub Button_Click() function:
Dim FileUpload1 As New FileUpload()
That must be creating a new instance causing it to show you an empty File Name.
If you just need the file name and not the entire path you could try the above.
Edit: Just saw the edit to your questions. The line I asked you to remove may be causing HasFile property to be empty as well.
You can not pass/assign name asp:FileUpload, as it is converted to input type file it is not allowed due to security reason. As it could breach the security of client machine that is browsing the website. The only possibility to assign it a value is through user selection that is browsing and assigning the file by user from client (browser)
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.saveas.aspx
You can use FileUpload.SaveAs method to save the selected file.
FileUpload1.SaveAs(savePath);
I am implementing a web application using ASP.NET/VB. The front-end (.aspx) executes an external .js file as:
<script type =" text/javascript" src="External.js"></script>
where it contains some functions. One of these functions called populateHidden() is used to assign a value to the hiddenField I defined on the front-end (.aspx) as follows:
In External.js
document.getElementByID('Hidden2').value = "dsadsadas";
In .aspx
<input id="Hidden2" type ="hidden" runat="server" />
what I have been trying to do is to get the value assigned to Hidden2 and pass it to the server-side (.aspx.vb) using:
Dim str = Hidden2.value
However, since server-side code executes first,str would be empty and unless a postback is done somehow whether using a Button or a Timer to reload the front-end, then str will have dsadsadas. I do not intend to reload the page or initialize a postback. I tried window.onload = populateHidden() with no luck. This situation made me desperate since I tried to many things making sure I do not use postbacks or reloads until I came across ClientScriptManager.RegisterClientScriptInclude Method . I couldn't not get around onto how I can use such an example to solve my situation.
The idea in mind is to call or execute External.js from the server side (since it executes first), then populate Hidden2 on the front-end, go back to the server side and retrieve Hidden2.value.
However the example in the link mentioned earlier, the server-side code is written in the front-end but I want to write it on the server-side (.aspx.vb).
The reason why I need Hidden2.value in the server-side is to store it in my sql_database. Any suggestions, advice or solutions to get Hidden2.value from the front-end would be really appreciated.
The following solution uses only ASP.Net Ajax Engine. In PageLoad event, a call to populateHidden() function is being registered. In the codebehind, a method marked with the WebMethod attribute was added, allowing it to be called by an Ajax request (without postback). So, when the button is clicked, the javascript function sendHiddenValueToServer() is called, making an Ajax request to the Page Method, passing the Hidden Field Value as Parameter.
First, you will need a ScriptManager declared with the EnablePageMethods property set to true:
<asp:ScriptManager runat="server" EnablePageMethods="true" />
I tested using the following markup:
<html>
<head runat="server">
<title></title>
<script src="External.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" EnablePageMethods="true" />
<div>
<asp:HiddenField ID="Hidden2" runat="server" ClientIDMode="Static" />
<button id="button1" onclick="sendHiddenValueToServer();">
Send Value to Server</button>
</div>
</form>
</body>
</html>
In the Javascript file:
function populateHidden() {
document.getElementById('Hidden2').value = "dsadsadas";
}
function sendHiddenValueToServer() {
PageMethods.ReceiveHiddenValue(
document.getElementById('Hidden2').value,
function () { alert("success!") },
function () { alert("error!") });
}
And in the codebehind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "register", "populateHidden();", True)
End If
End Sub
<System.Web.Services.WebMethod()>
Public Shared Sub ReceiveHiddenValue(ByVal value As String)
Dim str As String = value
' Save Value to database
End Sub
I've been poking at this all morning and I can't seem to find the way to do this.
I have a web app that has to show a tooltip on one of its div-s. The tooltip's contents come from some DB querying
< div style="height: 10px; clear: both;" title="<%=dbCount %> device(s) with version <%=devVersion %> in this group">
This works fine.
If I try replacing the <%=dbCount %> with an expression:
< div style="height: 10px; clear: both;" title="<%=dbCount > 0 ? ""+dbCount : "No " %> device(s) with version <%=devVersion %> in this group">
then on PageLoad I get an exception CS1518: Expected class, delegate, enum.
It doesn't matter how I structure the expression, if I put parenthesis or not, if I use String.Format or ternary expression - any sort of expression, besides using the variable name only, causes the error.
I tried replacing <%= with <%# and tried <% Response.Write(dbCount>0 ? "some" : "none") %> and I get the same error. This is the only line in the aspx I'm editing so the error is due to it, not elsewhere on the page.
I could use an <% if(...){ construct but then the designer is having trouble with finding the closing div and I don't want to pollute the source with too much junk, I'd rather keep the original version.
Do you know why is the compiler error showing up and how can I prevent it and use the output expression <%= devCount>0?"some":"none" %>?
Do not write code like that.
Aspx files only support that for backward compatibility.
If you really really must do it, Write only public properties that way.
Refer: Embeded code blocks
Embedded code blocks are supported in ASP.NET Web pages primarily to
preserve backward compatibility with older ASP technology. In general,
using embedded code blocks for complex programming logic is not a best
practice, because when the code is mixed on the page with markup, it
can be difficult to debug and maintain. In addition, because the code
is executed only during the page's render phase, you have
substantially less flexibility than with code-behind or script-block
code in scoping your code to the appropriate stage of page processing.
That said, the link does show you how to properly use embeded code.
If you really must do it this way, use Response.Write.
< div style="height: 10px; clear: both;" title="<%
{
string countMessage = dbCount > 0 ? ""+dbCount : "No ";
Response.Write(countMessage );
}
%> device(s) with version <%=devVersion %> in this group">
I've created a test web app and your code (<%=dbCount > 0 ? ""+dbCount : "No " %>) works fine (I'm assuming that "< div" is a mistype). I'm assuming that dbCount is an int and devVersion is a string. Is there something else going on? Is dbCount a public property that calls a method? Is it a public variable?
What is dbCount in your app?
All these variants are running ok here, among the C# samples I include the case you mentioned which is also running fine:
In VB.NET
MarkUp:
<body>
<form id="form1" runat="server">
<div id="<%If dbCount = 1 Then%><%="22"%><%Else%><%="55"%><% End If%>">
<%=dbCount.ToString()%>
</div>
</form>
</body>
Codebehind:
Partial Class varIn
Inherits System.Web.UI.Page
Public dbCount As Short = 0
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
dbCount = 1
End If
End Sub
End Class
In C#
MarkUp:
<div id="<%if (dbCount == 1) { %><%="22"%><%;}else{%><%="55"%><%;}%>">
<%=dbCount.ToString()%>
</div>
Or:
<div id="<%=dbCount > 0 ? ""+dbCount : "No " %>">
<%=dbCount.ToString()%>
</div>
Codebehind:
public partial class _Default : System.Web.UI.Page
{
public short dbCount;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dbCount = 1;
}
}
}
I have an ASP.NET 3.5 WebForm that leverages the frameworks Page.ClientScript.GetCallbackEventReference() method and I'd like some of the calls to be synchronous.
Now, the documentation says that the 5th parameter (see below) controls this. Specifically, when you pass 'false' it's supposed to be a non-asynchronous call. However, regardless if it's true or false, it still processes the call asynchronously.
Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context",false);
Is there a work-around for this or perhaps I'm doing something wrong?
ASPX Page
<%# Page Language="VB" AutoEventWireup="false" CodeFile="How-to-use-GetCallbackEventReference.aspx.vb" Inherits="How_to_use_Callback" %>
<!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>How to use GetCallbackEventReference</title>
<script type="text/javascript">
function GetNumber() {
UseCallback();
}
function GetRandomNumberFromServer(txtGetNumber, context) {
document.forms[0].txtGetNumber.value = txtGetNumber
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="Get Random Number" onclick="GetNumber()" /><br /><br />
<asp:TextBox ID="txtGetNumber" runat="server"></asp:TextBox> </div>
</form>
</body>
</html>
Code Behind
Partial Class How_to_use_Callback
Inherits System.Web.UI.Page
Implements System.Web.UI.ICallbackEventHandler
Dim CallbackResult As String = Nothing
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim cbReference As String = Page.ClientScript.GetCallbackEventReference(Me, "arg", "GetRandomNumberFromServer", "context")
Dim cbScript As String = "function UseCallback(arg,context)" & "{" & cbReference & " ; " & "}"
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "UseCallback", cbScript, True)
End Sub
Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
Return CallbackResult
End Function
Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
CallbackResult = Rnd().ToString()
End Sub
End Class
For any other poor souls still using the MS AJAX library I found the following post:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/f4134c2e-ca04-423a-9da3-c613713a7b52/synchronous-callbacks-with-the-net-20-framework?forum=netfxjscript
The last comment from an MS source says:
This is actually by design. In order not to block the UI of the browser, this parameter doesn't actually do the request synchronously but makes sure the requests are queued and only one is going on at any given time. The effect is pretty much the same, except that the end-user can still use the browser UI while the request is going on and he won't have to kill the process if the server fails to respond or the network connection falls.
The MSDN page confirms this:
When sending data synchronously in a callback scenario, synchronous callbacks return immediately and do not block the browser. No two synchronous callbacks callback can execute at the same time in the browser. If a second synchronous callback is fired while one is currently pending, the second synchronous callback cancels the first and only the second callback will return.