Can't get jQuery AutoComplete to work with External JSON - javascript

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

Related

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){
}

After many iterations, VBA call to Acrobat API starts returning "The remote procedure call failed"

I'm trying to loop through a bunch of PDFs and, for each one, flatten it using the Acrobat API to access the PDF's JS Object. Because VBA doesn't have a code-accessible stack trace, I have a wrapper class AcroExchWrapper that wraps each Acrobat API function to identify the function if it fails, e.g.
Public Sub ClosePDF()
On Error GoTo errHandler
'AcroDoc is created with CreateObject("AcroExch.PDDoc")
AcroDoc.Close
Exit Sub
errHandler:
Err.Raise Err.Number, "AcroExchWrapper.ClosePDF (" & Err.source & ")", Err.Description, Err.HelpFile, Err.HelpContext
End Sub
Each PDF is flattened using the following code:
Private Function flattenPDF(pdfPath As String, savePath As String, deleteOld As Boolean) As String
Dim pageCount As Integer
Dim jso As Object
Dim saveResult As Long
Dim openResult As Long
Dim creatingApp As String
On Error GoTo errHandler
creatingApp = ""
If deleteOld Then
If fso.FileExists(savePath) Then
fso.DeleteFile savePath
End If
End If
acroExch.ClosePDF
openResult = acroExch.OpenPDF(pdfPath)
If openResult = 0 Then
Err.Raise "-1", "Flattener.flattenPDF", "unable to open PDF"
End If
DoEvents
Set jso = acroExch.GetJSObject
DoEvents
If jso Is Nothing Then
Err.Raise "-1", "Flattener.flattenPDF", "unable to get JS object"
Else
pageCount = acroExch.GetNumPages
creatingApp = acroExch.GetInfo("Creator")
If pageCount <> -1 Then
flattenPages jso, 0, pageCount - 1
Else
flattenPages jso
End If
DoEvents
saveResult = acroExch.SavePDF(savePath)
If saveResult = 0 Then
Err.Raise "-1", "Flattener.flattenPDF", "unable to save PDF"
End If
acroExch.ClosePDF
If pdfPath <> savePath Then
loggerObj.addEntry pdfPath, savePath, "flattened", creatingApp
End If
End If
flattenPDF = savePath
Exit Function
errHandler:
loggerObj.addErrorEntryFromErrorObj pdfPath, "", "flattenPDF", Err, creatingApp
flattenPDF = ""
End Function
'wrapper for jso.flattenPages to allow for stack trace
Private Sub flattenPages(jso As Object, Optional startPage As Long = -1, Optional endPage As Long = -1)
On Error GoTo errHandler
If startPage = -1 Then
jso.flattenPages
Else
jso.flattenPages startPage, endPage
End If
Exit Sub
errHandler:
Err.Raise Err.Number, "flattenPages (" & Err.source & ")", Err.Description, Err.HelpFile, Err.HelpContext
End Sub
After going through several thousand files--the number is different each time I run the script--flattenPages() raises the following error:
Automation error
The remote procedure call failed.
After that, for all remaining files, when flattenPDF() runs, the first call to acroExch.ClosePDF() raises this error:
The remote server machine does not exist or is unavailable
I haven't been able to find any documentation on why these errors occur when using Acrobat API, whether with the Javascript API (jso.flattenPages()) or the IAC API (PDDoc.Close()). More mysterious is that the application runs fine until it gets to some varying number of files and only then starts throwing these exceptions.
EDIT: I added the following function to AcroExchWrapper to reset Acrobat, to be performed every 100 files:
Public Sub Reset()
ClosePDF
AcroApp.Exit
Set AcroApp = CreateObject("AcroExch.App")
Set AcroDoc = CreateObject("AcroExch.PDDoc")
Exit Sub
However, the same exceptions are still being thrown. This seems to be occurring once 1500-2500 files have been processed.

PageMethods not working

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;

Javascript access JavascriptSerializer JSON string Correctly

In Javascript I'm calling a function that retrieves data from a data table and converts it to javascriptSerializer, I then use the data in a Javascript chart. Everything works fine the first time round, as soon I change the Dataset selection parameters i.e dates etc, and call Function PopulateChart() again to try to pull a new set of data, I have a problem retrieving it in the javascript. The data and json string is populated correctly on the server but not on the client, the old string of data still exists.
var chartData still shows the old Data, even through the returned serializer.Serialize(rows) shows the correct data on the server
Below is my code and what I'm trying to achieve.
ASPX
var chartData = <%= PopulateChart() %>;
VB
Public Function PopulateChart() As String
''Get Chart Data
Dim daChart As New dsSVTableAdapters.clsChart
Dim dtChart As New dsSV.webV1_ChartsDataTable
Dim drChart As dsSV.webV1_ChartsRow
dtChart = daChart.GetChart(hChartID.Value)
If dtChart.Rows.Count > 0 Then
drChart = dtChart.Rows(0)
hChartName.Value = drChart.Description
HInterval.Value = drChart.Interval
Dim dtData As DataTable
Dim ds As New DataSet()
ds = GetData(4, DateTime.Parse("2012-05-01"), DateTime.Parse("2012-06-30"))
dtData = ds.Tables(0)
Dim serializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
Dim rows As New List(Of Dictionary(Of String, Object))
Dim row As Dictionary(Of String, Object)
For Each dr As DataRow In dtData.Rows
row = New Dictionary(Of String, Object)
For Each col As DataColumn In dtData.Columns
If col.ColumnName = "DateAndTime" Then
Dim dts As DateTime = DateTime.Parse(dr(col).ToString())
row.Add(col.ColumnName, dts.ToString("yyyy-MM-dd hh:mm:ss"))
ElseIf col.ColumnName = "Time" Then
Dim ts As DateTime = DateTime.Parse(dr(col).ToString())
row.Add(col.ColumnName, ts.ToString("hh:mm:ss"))
Else
row.Add(col.ColumnName, dr(col))
End If
Next
rows.Add(row)
Next
serializer.MaxJsonLength = Int32.MaxValue
Return serializer.Serialize(rows)
End If
End Function
var chartData = <%= PopulateChart() %>; will only get evaluated server side at each page load, the <%=....%> is an asp.net wrapper for rendering content in a webpage when and only at a page request. it will not make the PopulateChart() function available to JavaScript on the client side.
you will need to load new data either by ajax calls or reloading the entire page with request parameters indicating what data is to be loaded.
Here is an article on codeproject about asp.net and ajax using jquery.
http://www.codeproject.com/Articles/17203/Using-jQuery-for-AJAX-in-ASP-NET

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.

Categories