I am developing an ASP.NET project for our intranet which retrieves client's MachineName and IPAddress and I am using the following code.
ajax/default.aspx.vb
Public Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Request.QueryString.Count > 0 Then
Select Case Request.QueryString("eval")
Case Else
Dim type As Type = type.GetType("ajax_default")
Dim method As MethodInfo = type.GetMethod("zzfxn_" & Request.QueryString("eval").ToString, BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance)
If method IsNot Nothing Then
method.Invoke(Me, New Object() {Request})
End If
End Select
End If
End Sub
Public Sub zzfxn_zGetClientInfo(ByVal r As System.Web.HttpRequest)
Response.Write("Client IP Address: " & Request.UserHostName & "|" & Request.UserHostAddress & "<br />")
Response.Write("Client Machine Name: " & System.Net.Dns.GetHostEntry(Request.UserHostName).HostName.Split(".")(0))
End Sub
test/Default.aspx
<%# Page Language="VB" AutoEventWireup="true" %>
<!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>
<style type="text/css">.hid{display: none;}</style>
</head>
<body>
<form id="form1" name="form1" runat="server">
<div>
<p>My client info is: <%= InvokeAjax("?eval=zGetClientInfo")%></p>
</div>
</form>
<script type="text/VB" runat="server">
Protected Function InvokeAjax(ByVal params As String) As String
Dim wc As New System.Net.WebClient
wc.Headers.Add("user-agent", Request.UserAgent)
Dim ru As String = Request.Url.ToString.Remove(Request.Url.ToString.IndexOf("/test")) & "/ajax/default.aspx"
Return wc.DownloadString(ru & params).ToString
End Function
</script>
</body>
</html>
I deployed the project to the test-server Windows Server 2000, ASP.NET 4 and I got the following results.
Running/viewing ajax/Default.aspx?eval=zGetClientInfo results to:
Client IP Address: 10.20.10.5|10.20.10.5
Client Machine Name: devctr
Running/viewing test/Default.aspx results to:
My client info is: Client IP Address: 10.20.10.60|10.20.10.60
Client Machine Name: test-server
10.20.10.5 or devctr is my machine so viewing directly to ajax/default.aspx returns the exact/true content, while 10.20.10.60 or test-server is my host/server.
Can someone please explain to me why they differ?
And how can I achieve the results of ajax/defaut.aspx to be exactly the same for test/Default.aspx?
In the test/Default.aspx example, you are creating a web request that is originating on the server, hence the "runat='server'" parameter. If you are trying to create an ajax request that originates from the client, you will need to use a client side script like javascript. You could use jQuery to do this by doing something like:
$.ajax({
url: "/?eval=zGetClientInfo"
}).done(function(data) {
//Set your html here
});
If you are really going to do this, however, I would consider looking into ASP.NET Web API. Your solution will be much more robust if you return your results in some sort of JSON or XML format, which web API will do.
Related
I have the following code:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Dynamic Reports</title>
<script language="javascript" src="js/DynamicReports.js" type="text/javascript"></script>
</head>
<body onload="doSelect()">
<asp:DropDownList ID="ddlDynReports" runat="server" DataSourceID="sdsDynReports" DataTextField="DynReportName" DataValueField="DynReportID">
</asp:DropDownList>
<asp:SqlDataSource ID="sdsDynReports" runat="server" SelectCommand="select v.object_id as DynReportID, substring(v.name, 11, LEN(v.name)) as DynReportName from sys.views v where v.name like 'DynReport[_]%'">
</asp:SqlDataSource>
</body>
</html>
It throws the following error at runtime:
The ConnectionString property has not been initialized.
My web.config file seems to be okay because I am doing many other sql calls in the .vb code. This is the first time I am doing sql in .aspx code.
I presume my connection that is available in my .vb code needs to be exposed to the .aspx code.
I am open to a solution that would move the select to the .vb code.
EDIT: I figured out that I should add ConnectionString="<%$ ConnectionStrings:constr %>" to the SqlDataSource element, but the problem is that I do not have connection strings in my web.config file. My connection strings are in a file called ApplicationConfig.vb.
So, how can I get the connection string out of ApplicationConfig.vb into the .aspx code?
EDIT: I am doing it this way because it is the sample code I found for populating a dropdown from a select statement. I am a vb.net noob so I am basically surviving by cutting and pasting from the SO. Suggestions for better ways is cheerfully accepted but I get lost if the example code is not complete. Example: Some example code I find on SO looks like what I want to do, but it is a series of snip-its and I don't know where to put those snip-its.
EDIT: Add .vb code:
Partial Class XXX_CommonPages_DynamicReports
Inherits System.Web.UI.Page
Protected Sub dynreport_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles dynreports_run.ServerClick
Dim ViewObjectId As String = ddlDynReports.SelectedValue
Dim DataOut As String = "some,data,out"
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=DynReport_" + ViewObjectId + ".csv")
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Length", DataOut.Length())
Response.Write(DataOut)
' Response.End ' Causes ThreadAbortException.
End Sub
End Class
EDIT: Here is the .vb code that contains the connection string:
Public Class ApplicationConfig
Public Class AppConfig
Implements IConfigurationSectionHandler
Private Const PRODUCTION_DATAACCESS_CONNECTIONSTRING_DEFAULT As String = "serve ..."
Public Shared ReadOnly Property ConnectionString() As String
Get
If fieldConnectionString Is Nothing Then fieldConnectionString = PRODUCTION_DATAACCESS_CONNECTIONSTRING_DEFAULT
Return fieldConnectionString
End Get
End Property
End Class
End Class
I am trying to translate an old "Classic ASP" page to ASP.NET page. I have limited ASP.NET knowledge.
I am reading some data from a SQL server.
I have a basic question, but so far I was not able to successfully implement any working solution.
The code attached is working well; shows the data I need.
I would like to have a similar code structure but this time I would like to assign the data from SQL to variables (I do not need to print these output values on the screen):
title (output of SQL query) ---> "titleV" variable (string)
father (output of SQL query) ---> "fatherV" variable (string)
age (output of SQL query) ---> "ageV" variable (number)
If possible, please suggest to me a piece of code I can test.
Thank you.
<%# Import Namespace="System.Data.OleDb" %>
<script runat="server">
sub Page_Load
dim dbconn,sql,dbcomm,dbread
dbconn=NewOleDbConnection("connection string to sql server")
dbconn.Open()
sql="SELECT * FROM photos"
dbcomm=New OleDbCommand(sql,dbconn)
dbread=dbcomm.ExecuteReader()
customers.DataSource=dbread
customers.DataBind()
dbread.Close()
dbconn.Close()
end sub
</script>
<!DOCTYPE html>
<html>
<body>
<form runat="server">
<asp:DataList id="customers" runat="server">
<ItemTemplate>
<%#Container.DataItem("title")%> in
<%#Container.DataItem("father")%> with
<%#Container.DataItem("age")%> years
</ItemTemplate>
</asp:DataList>
</form>
</body></html>
You can save one record in above 3 variables because you are not using array type or collections. You can assign the data from the table to your variables using the following code.
sub page_load()
dbconn = new oledbconnection("conn str")
dbconn.Open()
sql="SELECT * FROM photos"
dim adpt as OledbDataAdapter
dim rs as new DataTable
adpt = new OledbDataAdapter(sql,dbconn)
adpt.fill(rs)
customers.DataSource = rs
customers.DataBind()
dim titleV, fatherV As String
dim ageV as integer
titleV = rs.Rows(0).Item(0) 'Rows(0).Item(0) gives you first row's first field value.
fatherV = rs.Rows(0).Item(1)
ageV = rs.Rows(0).Item(2)
dbconn.Close()
end sub
</script>
<!DOCTYPE html>
<html>
<body>
<form runat="server">
<asp:DataList id="customers" runat="server">
<ItemTemplate>
<%#Container.DataItem("title")%> in
<%#Container.DataItem("father")%> with
<%#Container.DataItem("age")%> years
</ItemTemplate>
</asp:DataList>
</form>
</body></html>
My problem is Notify_url does not insert any value in database. Can anyone tell me where I am wrong. I have following code pages available
I have three pages: 1) default.aspx 2) sendpayment.aspx 3) PAypal.aspx
In default.aspx,
I have two textbox. I get those two values in session and on submit I redirect a page to Sendpayment.aspx
In sendpayment.aspx, I have following code
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Sendpayment.aspx.vb" Inherits="Sendpayment" Debug="true" %>
<!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 id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" id="form1"
name="form1">
<input type="hidden" name="cmd" value="_xclick"/>
<input type="hidden" name="business" value="naveed.mansuri#abc.com"/><!--Paypal or sandbox Merchant account -->
<input type="hidden" name="custom" value="<%=Session("regemail")%>"/><!--Custom Field for payer email -->
<input type="hidden" name="item_number" value="1"/>
<input type="hidden" name="amount" value="<%=Session("totalShoppingAmt")%>"/>
<input type="hidden" name="notify_url" value="http://www.abc.com/paypal.aspx"/><!--this should be your domain web page where you going to receive all your transaction variables -->
<input type="hidden" name="return" value="http://www.abc.com/thankyou.html"/><!--this page will be your redirection page -->
<input type="hidden" name="cancel_return" value="http://www.abc.com"/>
<input type="hidden" name="currency_code" value="USD"/>
</form>
<script type="text/jscript">
document.form1.submit();
</script>
I have assign notify url at http://www.abc.com/paypal.aspx
In Paypal.aspx,
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Paypal.aspx.vb" Inherits="Paypal" Debug="true" %>
<!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 id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html
and vb page of this is:
Imports System.Data
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Data.SqlClient
Imports System.IO
Imports System.Text
Imports System.Threading
Imports System.Net
Partial Public Class paypal
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs)
'Post back to either sandbox or live
Dim strSandbox As String = "https://www.sandbox.paypal.com/cgi-bin/webscr"
' string strLive = "https://www.paypal.com/cgi-bin/webscr";
Dim req As HttpWebRequest = DirectCast(WebRequest.Create(strSandbox), HttpWebRequest)
'Set values for the request back
req.Method = "POST"
req.ContentType = "application/x-www-form-urlencoded"
Dim param As Byte() = Request.BinaryRead(HttpContext.Current.Request.ContentLength)
Dim strRequest As String = Encoding.ASCII.GetString(param)
strRequest += "&cmd=_notify-validate"
req.ContentLength = strRequest.Length
'for proxy
'WebProxy proxy = new WebProxy(new Uri("http://url:port#"));
'req.Proxy = proxy;
'Send the request to PayPal and get the response
Dim txnid As String = Server.HtmlEncode(Request.Form("txn_id"))
Dim receiv_email As String = Server.HtmlEncode(Request.Form("receiver_email"))
Dim business As String = Server.HtmlEncode(Request.Form("business"))
Dim payer_email As String = Server.HtmlEncode(Request.Form("payer_email"))
Dim tnx_type As String = Server.HtmlEncode(Request.Form("txn_Type"))
Dim payment_type As String = Server.HtmlEncode(Request.Form("payment_type"))
Dim payment_stat As String = Server.HtmlEncode(Request.Form("payment_status"))
Dim regemail As String = Server.HtmlEncode(Request.Form("custom"))
' this is where i get my member's email adress
Dim constr As String = "data source=activehost.com;initial catalog=demo;password=R12ComSQ;persist security info=True;user id=demo_sa"
Dim insertsql As String = "INSERT INTO NOTIFICATION_PAYPAL_TRANSACTION (txn_id,receiver_email,business,payer_email,tnx_type,payment_status,LocalDate,payment_type,regemail) values('" & txnid & "','" & receiv_email & "','" & business & "','" & payer_email & "','" & tnx_type & "','" & payment_stat & "','" & DateTime.Now.ToString() & "','" & payment_type & "','" & regemail & "')"
Using myConnection As New SqlConnection(constr)
myConnection.Open()
Dim mycommand As New SqlCommand(insertsql, myConnection)
mycommand.ExecuteNonQuery()
myConnection.Close()
End Using
' for testing purposes i did not create any ipn status actions as i wanted to record every paypal status.
'If strResponse = "VERIFIED" Then
' 'UPDATE YOUR DATABASE
' 'check the payment_status is Completed
' 'check that txn_id has not been previously processed
' 'check that receiver_email is your Primary PayPal email
' 'check that payment_amount/payment_currency are correct
' 'process payment
' 'UPDATE YOUR DATABASE
'ElseIf strResponse = "INVALID" Then
' 'UPDATE YOUR DATABASE
'Else
'End If
End Sub
End Class
Check the IPN History in your PayPal to see if anything is getting sent or not. You may find that it's showing it's sending data but getting a bad response back.
If it shows it's sending data but getting anything other than a 200 response then something is wrong with the script that needs to be fixed. You can check your web server logs for help with that, or what I like to do is build an HTML form with the action set to my IPN script and a bunch of hidden fields that match what I expect to get from an IPN. Then I submit that in a browser and actually see the result on screen which can help trouble problems.
Once it's working that way you know you're good. Just remember the data isn't coming from PayPal when you do that, so it won't verify successfully. You'll need to make sure your code logic can handle that.
If your IPN History doesn't show anything is getting sent then I would question whether you're looking at the correct sandbox account. It's easy to get them confused and be looking at the wrong one.
I have a web app which displays a list of emails that need to be sent for the day. The user can select what emails to send, then click a button to generate them. When they click the Send button, a process gets started on another thread which generates the emails, then cleans up after itself by deleting a temp folder. Once the process is finished, the Repeater is rebound to update the User's view and remove the emails that have just been sent so they don't get sent again.
My problem is that when I delete the temp folder from my 2nd thread, the UI doesn't update with the new Repeater data. It updates correctly if I just delete the files in the folder instead of the folder itself, and it also updates correctly if I run the delete the folder on the original thread instead of the 2nd one.
New Thread code
Dim t as Thread = New Thread(New ThreadStart(AddressOf EmailLetters))
t.Start()
Delete folder code
Dim fs = Server.CreateObject("Scripting.FileSystemObject")
fs.DeleteFolder(Server.MapPath(".") + "\tmpEmailFiles")
Why won't the UI update to show the new repeater values when I delete a folder on another thread?
EDIT
Here is some sample code that shows the problem. Sorry if its a bit messy, but I just needed something simple to help me identify the problem.
When you click the button, a thread gets started and a javascript load script starts executing which does a PostBack every 10 seconds. Each postback checks if the thread is complete and updates the Status label showing the result. If I delete a folder from within the background thread, the final update to the status label never occurs. If I remove the DeleteFolder call, it does.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%# Import Namespace="System.Threading" %>
<%# Page Language="VB" Debug="true" %>
<%# Implements Interface="System.Web.UI.IPostBackEventHandler" %>
<SCRIPT language="vb" runat="server">
Sub Page_Load(Src As Object, e As EventArgs)
End Sub
Public Sub Test(src as Object, e as EventArgs)
Dim t as Thread = New Thread(New ThreadStart(AddressOf TestWorker))
t.Start()
Session("BackgroundThread") = t
End Sub
Public Sub TestWorker()
' 30 Second Delay
System.Threading.Thread.Sleep(30000)
Dim root as String = Server.MapPath(".")
Dim fs = Server.CreateObject("Scripting.FileSystemObject")
If Not fs.FolderExists(root + "\Test") Then fs.CreateFolder(root + "\Test")
fs.DeleteFolder(root + "\Test")
ErrMsg.Text = "Start: " + DateTime.Now.ToString()
End Sub
Public Sub RaisePostBackEvent(ByVal eventArgument As String) _
Implements IPostBackEventHandler.RaisePostBackEvent
If Session("BackgroundThread") is Nothing Then
Exit Sub
End If
Dim t as Thread = CType(Session("BackgroundThread"), Thread)
If t.ThreadState = ThreadState.Stopped Then
ErrMsg.Text = "Done: " + DateTime.Now.ToString()
Session("BackgroundThread") = Nothing
Else
ErrMsg.Text = "Processing: " + DateTime.Now.ToString() + " - " + t.ThreadState.ToString()
End If
End Sub
</SCRIPT>
<HTML>
<HEAD>
<SCRIPT language="javascript">
//<!--
function onLoad()
{
if(<%= IIF(Session("BackgroundThread") is Nothing, "false", "true") %>)
{
toggleLoading();
setTimeout("<%= Page.ClientScript.GetPostBackEventReference(Me, "") %>", 10000);
}
}
function toggleLoading(){
document.getElementById('imgLoading').style.display = 'block';
setTimeout("document.images['imgLoading'].src='images/loading.gif'", 100);
}
// -->
</SCRIPT>
</HEAD>
<BODY OnLoad="onLoad();">
<FORM runat="server">
<ASP:Button runat="server" Text="Test" OnClick="Test" onClientClick="javascript: toggleLoading();" />
<ASP:Label runat="server" Id="ErrMsg" />
<IMG id="imgLoading" src="images/loading.gif" style="display: none;" />
</FORM>
</BODY>
</HTML>
Figured out my problem. Turns out deleting any folder in the ASP root folder will restart the application and reset all Session variables.
To get around that I added the following to my Application_OnStart method in Global.asax
Dim p As System.Reflection.PropertyInfo = GetType(HttpRuntime).GetProperty("FileChangesMonitor", Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Static)
Dim o As Object = p.GetValue(Nothing, Nothing)
Dim f As System.Reflection.FieldInfo = o.GetType.GetField("_dirMonSubdirs", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.IgnoreCase)
Dim monitor As Object = f.GetValue(o)
Dim m As System.Reflection.MethodInfo = monitor.GetType.GetMethod("StopMonitoring", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
m.Invoke(monitor, New Object() {})
The problems is that this is a background thread on the server that is sending the emails finishes but the response has already been sent to the user. When The user opens the page the background thread is started off, and the server returns with the response on the parent thread, the background thread is still running away on the server for sometime AFTER the response has already been sent
To achieve what you want you would need to have the page refreshing on a Javascript or some ajax to poll the server and keep check if this background thread has completed. ie the background thread is started, and the user is told that emails are being proccessed, 2 seconds later the page is automatically refreshed and the user is still told emails are being processed. Finally When all emails are sent the repeater is updated and automatic refresh is disabled
Definitely at my wits end here. This should be simple. In a page to create new user accounts, we have a database with a little of allowable users. To streamline getting the Email address of the new user correct, we want to use an AutoComplete extended textbox.
Now I know that WebMethods are working because I have a cascading-drop-down tied to web methods in another page.
As I'm just starting on this page, the code is simple.
The page itself:
<cc1:ToolkitScriptManager ID="ScriptManager2" runat="server"/>
<p></p> Please enter new user's Email:
<asp:TextBox ID="txtUser" runat="server" />
<cc1:AutoCompleteExtender runat="server" ID="autUser" TargetControlID="txtUser"
ServiceMethod="ScanGALUsers" ServicePath="~/AutoScan.asmx"
MinimumPrefixLength="3" CompletionSetCount="150" /> <p></p>
The .asmx file is simple:
<%# WebService Language="VB" CodeBehind="~/App_Code/VB_Code/AutoScan.vb" Class="AutoScan" %>
The WebMethod:
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class AutoScan
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Shared Function ScanGALUsers(ByVal strPrefix As String, ByVal intMaxCount As Integer) As String()
Dim arlResults As New ArrayList
Dim intCount As Integer
Dim dt As DataTable
Dim colParameters As New SortedList
SysDA.LogDebug("ScanGALUsers called with parameters: " & strPrefix & " and count of " & intMaxCount.ToString)
... Deleted for brevity ...
If intCount > 0 Then
Dim arrResults(intCount - 1) As String
arrResults = arlResults.ToArray(GetType(System.String))
Return arrResults
Else
Return Nothing
End If
End Function
End Class
I'm not even getting to the LogDebug statement. I've used all the same boilerplate code (Inherits, the 'WebService' tags, etc) that worked in the other WebMethod with the appropriate changes to the Class name but this really has me stumped.
What am I missing that I'm not even making it to the method?
Did you ever resolve this issue? Have you tried removing Shared from your WebService declaration? This has worked for me before (and I don't know why!).