PageMethods not working - javascript

I am trying to learn how to use PageMethods with VB.NET and I'm running into some issues. For some reason I can't manage to get the method called by PageMethods to run.
Here is the javascript function:
<script type="text/javascript">
function AddHouse() {
var address = document.getElementById("addrTxt").valueOf;
var city = document.getElementById("cityTxt").valueOf;
var state = document.getElementById("stateTxt").valueOf;
var zip = parseInt(document.getElementById("zipTxt").valueOf);
var firstName = document.getElementById("rFirstName").valueOf;
var lastName = document.getElementById("rLastName").valueOf;
var rent = parseInt(document.getElementById("rentAmt").valueOf);
PageMethods.InsertHouse(address, city, state, zip, firstName, lastName, rent);
}
</script>
And here's the VB.NET code:
Public Class _Default
Inherits Page
Private Shared dbConnection As String
Private file As String = "C:\\Projects\\HousingInfo\\HousingInfo\\bin\\housingInfo.db3"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dbConnection = String.Format("Data Source={0}", file)
CreateTables()
End Sub
Private Sub CreateTables()
Dim connection = New SQLiteConnection(dbConnection)
If Not My.Computer.FileSystem.FileExists("C:\\Projects\\HousingInfo\\HousingInfo\\bin\\housingInfo.db3") Then
SQLiteConnection.CreateFile("C:\\Projects\\HousingInfo\\HousingInfo\\bin\\housingInfo.db3")
End If
Using Query As New SQLiteCommand()
connection.ConnectionString = dbConnection
connection.Open()
With Query
.Connection = connection
.CommandText = "CREATE TABLE IF NOT EXISTS houses(id INTEGER PRIMARY KEY AUTOINCREMENT, address TEXT, city TEXT, state TEXT,
zipCode INTEGER, rent INTEGER, rFirstName TEXT, rLastName TEXT)"
End With
Query.ExecuteNonQuery()
connection.Close()
End Using
End Sub
<Services.WebMethod()>
Public Shared Sub InsertHouse(ByVal addr As String, ByVal city As String, ByVal state As String, ByVal zip As Integer, ByVal firstName As String,
ByVal lastName As String, ByVal rent As Integer)
Dim connection = New SQLiteConnection(dbConnection)
Using Query As New SQLiteCommand()
connection.ConnectionString = dbConnection
connection.Open()
With Query
.Connection = connection
.CommandText = String.Format("INSERT INTO houses(address, city, state, zipCode, rent, rFirstName, rLastName) VALUES ('{0}', '{1}', '{2}', {3}, {4}, '{5}', '{6}'",
addr, city, state, zip, firstName, lastName, rent)
End With
Query.ExecuteNonQuery()
connection.Close()
End Using
End Sub
End Class

You are using the wrong property to get the value of the controls, rename 'valueOf' to 'value' as follows:
Do this for all other occurrences of 'valueOf'
var address = document.getElementById("addrTxt").value;

Related

Classic ASP error on function Base64_HMACSHA1

I have a function Base64_HMACSHA1 and am getting the error Expected ')'. The full code is:
Public Function Base64_HMACSHA1(ByVal sTextToHash As String, ByVal sSharedSecretKey As String)
Dim asc As Object, enc As Object
Dim TextToHash() As Byte
Dim SharedSecretKey() As Byte
Set asc = CreateObject("System.Text.UTF8Encoding")
Set enc = CreateObject("System.Security.Cryptography.HMACSHA1")
TextToHash = asc.Getbytes_4(sTextToHash)
SharedSecretKey = asc.Getbytes_4(sSharedSecretKey)
enc.Key = SharedSecretKey
Dim bytes() As Byte
bytes = enc.ComputeHash_2((TextToHash))
Base64_HMACSHA1 = EncodeBase64(bytes)
Set asc = Nothing
Set enc = Nothing
End Function
Private Function EncodeBase64(ByRef arrData() As Byte) As String
Dim objXML As MSXML2.DOMDocument
Dim objNode As MSXML2.IXMLDOMElement
Set objXML = New MSXML2.DOMDocument
' byte array to base64
Set objNode = objXML.createElement("b64")
objNode.DataType = "bin.base64"
objNode.nodeTypedValue = arrData
EncodeBase64 = objNode.Text
Set objNode = Nothing
Set objXML = Nothing
End Function
I've tried adding an ) in multiple places but I still get an error. The error message is for Line: 84, Column:51, which is this line: Public Function Base64_HMACSHA1(ByVal sTextToHash As String, ByVal sSharedSecretKey As String)
The code for the url is:
Dim objOAuth : Set objOAuth = New cLibOAuth
objOAuth.ConsumerKey = "0b57d617-7a92-4504-a5e1-25273e3b0384"
objOAuth.ConsumerSecret = "joSPols5B8uyKQqYzkk8uiwHrJ7nq3VwravLnTdJTFXMqSAq0KSBvPVoLETAmUiS"
objOAuth.EndPoint = "https://login.windstream.com/as/token.oauth2"
objOAuth.RequestMethod = OAUTH_REQUEST_METHOD_POST
objOAuth.TimeoutURL = "authenticate.asp"
'objOAuth.Parameters.Add "username", Request.Cookies("username")
'objOAuth.Parameters.Add "password", Request.Cookies("password")
objOAuth.Parameters.Add "oauth_callback", "callback.asp"
objOAuth.Send()
Dim strResponse : strResponse = _
objOAuth.Get_ResponseValue(access_token)

Unable to print the page after pdf generation in vb.net

Unable to print the window after pdf generation. Only pdf generation screens gets loaded. Please find the code below,
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim fileData As Byte() = Nothing
Dim sJscript As String
If (Session("PrintDestinationStream") IsNot Nothing) Then
fileData = CType(Session("PrintDestinationStream"), Byte())
Session("PrintDestinationStream") = Nothing
End If
Response.Clear()
Response.ContentType = application/pdf
Response.BinaryWrite(fileData)
Response.Flush()
Response.Close()
If Session("Print") IsNot Nothing AndAlso Session("Print").ToString() = "PrintDoc" Then
Dim s As String = "<script language=""javascript"">"
s = s & "window.focus();window.print();"
s = s & "</script" & ">"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "printdoc", s)
Session("Print") = Nothing
End If
End Sub
To open pdf file and to print the document

Converting Mysql TIME data type to JS Date - Hibernate HQL?

I'm trying to convert a simple HQL query to a readable time format (HH:MM) and honestly I'm a bit at a loss here.
My table definition (mysql) is as follows
CREATE TABLE `Concert` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT 'Concert Id',
`stage_id` INT NOT NULL COMMENT 'Stage Id',
`concert_time` TIME NOT NULL COMMENT 'Concert Time (HH:MM)',
`band_id` INT NOT NULL COMMENT 'Band Id',
PRIMARY KEY (`id`),
FOREIGN KEY (stage_id) REFERENCES Stage (id),
FOREIGN KEY (band_id) REFERENCES Band (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Class Model:
public class Concert {
private int id;
#Temporal(TemporalType.TIMESTAMP)
private Timestamp concertTime;
private Stage stage;
private Band band;
DAO:
public List<Concert> getConcertsByStageId(int id){
Session session = sessionFactory.getCurrentSession();
Query q = session.createQuery("Select c.id, c.concertTime from Concert c where c.stage.id= :id");
q.setParameter("id", id);
List<Concert> concertList = (List<Concert>)q.list();
System.out.println("count: " + concertList.size());
return concertList;
}
I'm getting string outputs via AJAX like '1508763630000' (that is if i use DATETIME instead of date, when using date I could not convert the output).
I wanted to convert that string to a JavaScript Date object, which can I would display in my view later.
I'm aware that one can use the TIME_FORMAT() function in mysql, but that doesn't seem to work in my HQL query. Is there a chance I could achieve this with JS? Or anything I need to add to my hibernate query??
Thanks in advance!
In case anyone comes across a similar issue, here's how I managed to solve it:
SQLQuery query = session.createSQLQuery("Select c.id, TIME_FORMAT(c.concert_time, '%H:%i'), c.band_id, "
+ "b.name, b.band_type, b.set_length, b.encore, b.relevance from Concert c left join Band b on b.id = c.band_id "
+ "where c.stage_id = :id");
query.setParameter("id", id);
List<Object[]> rows = query.list();
List<Concert> concertList = new ArrayList<Concert>();
And then iterate over result rows to construct your objects:
for(Object[] row : rows){
}

Getting value from SQL query to textbox

Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim cons, query As String
Dim con As OdbcConnection
Dim adpt As OdbcDataAdapter
'Dim num As Integer
cons = "dsn=Courier; UID=Courier; PWD=123;"
con = New OdbcConnection(cons)
con.Open()
query = "select Name from EMPLOYEE where EMPLOYEE_ID=" + DropDownList1.SelectedValue
Dim ds As DataSet
adpt = New OdbcDataAdapter(query, con)
ds = New DataSet
adpt.Fill(ds, "Courier")
' TextBox1.Text = ds
con.Close()
End Sub
I want to display the name of the employee in Textbox whoos ID is specified in query, what can I do for that?
You should use DataRow but to answer your question, try this.
TextBox1.Text = ds.Tables(0).Rows(0)("Name").ToString()
Since you only want one value back you should skip the dataset and adapter altogether.
query = "select Name from EMPLOYEE where EMPLOYEE_ID=" + DropDownList1.SelectedValue
Dim TempName As String = query.ExecuteScalar
TextBox1.Text = TempName
ExecuteScalar returns the first cell of the first row, that's all you need.
You should read about parameters as well.

Can't get jQuery AutoComplete to work with External JSON

I'm working on an ASP.NET app where I'm in need of jQuery AutoComplete. Currently there is nothing happening when I type data into the txt63 input box (and before you flame me for using a name like txt63, I know, I know... but it's not my call :D ).
Here's my javascript code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js" type="text/javascript"></script>
<script src="http://jquery-ui.googlecode.com/svn/tags/latest/external/jquery.bgiframe-2.1.1.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/i18n/jquery-ui-i18n.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
var theSource = '../RegionsAutoComplete.axd?PID=<%= hidden62.value %>'
$(function() {
$('#<%= txt63.ClientID %>').autocomplete({
source: theSource,
minLength: 2,
select: function(event, ui) {
$('#<%= hidden63.ClientID %>').val(ui.item.id);
}
});
});
and here is my HTTP Handler
Namespace BT.Handlers
Public Class RegionsAutoComplete : Implements IHttpHandler
Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
''# the page contenttype is plain text'
context.Response.ContentType = "application/json"
context.Response.ContentEncoding = Encoding.UTF8
''# set page caching'
context.Response.Cache.SetExpires(DateTime.Now.AddHours(24))
context.Response.Cache.SetCacheability(HttpCacheability.Public)
context.Response.Cache.SetSlidingExpiration(True)
context.Response.Cache.VaryByParams("PID") = True
Try
''# use the RegionsDataContext'
Using RegionDC As New DAL.RegionsDataContext
''# query the database based on the querysting PID'
Dim q = (From r In RegionDC.bt_Regions _
Where r.PID = context.Request.QueryString("PID") _
Select r.Region, r.ID)
''# now we loop through the array'
''# and write out the ressults'
Dim sb As New StringBuilder
sb.Append("{")
For Each item In q
sb.Append("""" & item.Region & """: """ & item.ID & """,")
Next
sb.Append("}")
context.Response.Write(sb.ToString)
End Using
Catch ex As Exception
HealthMonitor.Log(ex, False, "This error occurred while populating the autocomplete handler")
End Try
End Sub
End Class
End Namespace
The rest of my ASPX page has the appropriate controls as I had this working with the old version of the jQuery library. I'm trying to get it working with the new one because I heard that the "dev" CDN was going to be obsolete.
Any help or direction will be greatly appreciated.
Well, after a bunch of hours working on this, I got my iHttpHandler delivering data fairly nicely. Feel free to comment if you feel this could be better
Imports System.Linq
Imports System.Collections.Generic
Namespace BT.Handlers
Public Class RegionsAutoComplete : Implements IHttpHandler
Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Public Shared _PID As Integer
Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
''# the page contenttype is plain text'
context.Response.ContentType = "application/json"
context.Response.ContentEncoding = Encoding.UTF8
''# set query string parameters into global variables'
Dim _term As String = If(context.Request.QueryString("term") <> "", context.Request.QueryString("term"), "")
_PID = Integer.Parse(context.Request.QueryString("PID"))
''# create a string builder to store values'
Dim sb As New StringBuilder
sb.Append("[" & vbCrLf)
Dim item As BTRegionsList
Try
''# now we loop through the array'
''# and write out the ressults'
For Each item In BT.Handlers.RegionsAutoComplete.RegionsListInstance
''# make sure the added items are valid to the search'
''# we are also doing a case insensitive search'
If item.Region.ToLower.Contains(_term.ToLower) Then
''# this is actually writing out some JSON data'
sb.Append(vbTab & "{ ""label"": """ & item.Region & """, ""value"": """ & item.Region & """, ""id"": """ & item.Id.ToString & """ }," & vbCrLf)
End If
Next
Catch ex As Exception
''# log any errors to the Health Monitor'
HealthMonitor.Log(ex, False, "This error occurred while populating the autocomplete handler")
End Try
sb.Append("]")
''# write out the string builder'
context.Response.Write(sb.ToString)
''# set the string builder values to zero'
sb.Length = 0
sb = Nothing
item = Nothing
End Sub
''# this is the instance of the BTRegionsList object'
Friend Shared _RegionsListInstance As List(Of BTRegionsList)
Friend Shared UsedPID As Integer ''# this is the PID of the most recent instance
Public Shared ReadOnly Property RegionsListInstance() As List(Of BTRegionsList)
Get
Dim r As New List(Of BTRegionsList)
''# only populate the _RegionsListInstance if it is currently empty'
If _RegionsListInstance Is Nothing Or UsedPID = _PID Then
Using RegionDC As New DAL.RegionsDataContext
''# query the database based on the querysting PID'
Dim q = (From reg In RegionDC.bt_Regions _
Where reg.PID = Integer.Parse(HttpContext.Current.Request.QueryString("PID")) _
Select reg.Region, reg.ID)
For Each item In q
r.Add(New BTRegionsList(item.ID, item.Region))
Next
_RegionsListInstance = r
End Using
Else
''# if _RegionsListInstance is not empty'
''# then we want to set our BTRegionsList to '
''# equal _RegionsListInstance'
r = _RegionsListInstance
End If
''# Set the PID for this instance'
UsedPID = _PID
''# now we return our BTRegionsList'
Return r
End Get
End Property
End Class
''# a singleton class to store region information'
''# this helps us to not have to hit the database too many times'
Public Class BTRegionsList
Private _Region As String
Private _ID As Integer
Public Property Id() As Integer
Get
Return _ID
End Get
Set(ByVal value As Integer)
_ID = value
End Set
End Property
Public Property Region() As String
Get
Return _Region
End Get
Set(ByVal value As String)
_Region = value
End Set
End Property
Public Sub New(ByVal ID As Integer, ByVal Region As String)
_ID = ID
_Region = Region
End Sub
End Class
End Namespace

Categories