Getting value from SQL query to textbox - javascript

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.

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)

Reflecting kintone data to Excel

Thank you for your help.
I want to access the specified app of kintone from VBA and reflect the data acquired from it in Excel.
"Error number 438 Object does not support this property or method"
And an error is displayed and the value cannot be reflected.
I would appreciate if you could tell me how to solve it.
Option Explicit
Const DOMAIN_NAME As String = "XXXXXXXX.cybozu.com"
Const BASE_URL As String = "https://" & DOMAIN_NAME & "/k/v1/"
Const APP_ID As String = "XXX"
Const API_TOKEN As String = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
Const cellFromRecNumber = "A2"
Const cellFromRecNumber2 = "B4"
Dim strURL As String
Dim objHttpReq As Object
Dim strJSON As String
Dim objJSON As Object
Dim strFromRecNumber As String
Dim strToRecNumber As String
Dim strQuery As String
Dim record As Variant
Dim rep As Variant
Dim js As Object
Dim strFunc As String
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range(cellFromRecNumber)) Is Nothing Then
Exit Sub
Else
Set js = CreateObject("ScriptControl")
js.Language = "JScript"
strFunc = "function jsonParse(s) { return eval('(' + s + ')'); }"
js.AddCode strFunc
strFromRecNumber = Range(cellFromRecNumber)
strQuery = "Userid = """ & strFromRecNumber & """"
strQuery = js.CodeObject.encodeURIComponent(strQuery)
strURL = BASE_URL & "records.json?&app=" & APP_ID & "&query=" & strQuery
Set objHttpReq = CreateObject("MSXML2.XMLHTTP")
objHttpReq.Open "GET", strURL, False
objHttpReq.setRequestHeader "Host", DOMAIN_NAME & ":443"
objHttpReq.setRequestHeader "X-Cybozu-API-Token", API_TOKEN
objHttpReq.setRequestHeader "If-Modified-Since", "Thu, 01 Jun 1970 00:00:00 GMT"
objHttpReq.send (Null)
If objHttpReq.Status <> 200 Then
MsgBox ("Send:Error")
End
End If
strJSON = objHttpReq.responseText
strJSON = Replace(strJSON, """$revision"":", """kintone_revision"":")
Set objJSON = js.CodeObject.jsonParse(strJSON)
For Each record In objJSON.records
Worksheets(1).Range(cellFromRecNumber2).Value = record.Officename.Value
Next record
Set objHttpReq = Nothing
Set js = Nothing
End If
End Sub

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;

can javascript accept a string with length 27601?

I have a webmethod which will return an object with strings(i.e)str is object and str(0) would be string. str(0)'s length would be 27601. likewise all other array members having the same length.(i.e) str(1)'s length is 27601 also str(2),str(3)......
my webmethod return the exact object. but on the client side javascript doesn't accept the value it immediately fire the error method.
sample code is,
PageMethods.paging("","",pospara,"position_select","stored Procedure",function sucMulti(result){
alert(result);
});
web method is
<WebMethod()> _
<ScriptMethod()> _
Public Shared Function paging(ByVal query As String, ByVal tbl As String, ByVal para() As Object, ByVal spname As String, ByVal cmdtype As String) As Object()
Dim dsrt As New DataSet, dbacc As New dataaccess
If cmdtype = "stored Procedure" Then
dsrt = dbacc.retds1(spname, conn, para)
Else
dsrt = dbacc.retds(query, tbl, conn)
End If
'here dsrt will have 19 rows. so i split them by 8.
Dim no As Integer
Dim rows As Integer = 8
Dim r As Integer
no = Floor(dsrt.Tables(0).Rows.Count / rows)
If dsrt.Tables(0).Rows.Count < rows Then
r = 0
Else
r = dsrt.Tables(0).Rows.Count Mod rows
End If
Dim start As Integer = 0
Dim last As Integer = 7
Dim str(0) As Object
Dim dv As New DataView
dv = dsrt.Tables(0).DefaultView
If r <> 0 Then
no += 1
End If
If no >= 1 Then
ReDim str(no - 1)
For i As Integer = 1 To no
Dim ds As New DataSet
Dim dt As New DataTable
dt = dsrt.Tables(0).Clone
dt.Rows.Clear()
For j As Integer = start To last
dt.ImportRow(dsrt.Tables(0).Rows(j))
Next
start = (rows * i)
If r <> 0 And i = no - 1 Then
last = last + r
Else
last = start + 7
End If
ds.Tables.Add(dt)
str(i - 1) = ds.GetXml
Next
Else
str(0) = dsrt.GetXml
End If
Dim len As Integer = str(0).ToString.Length
Return str
End Function
everything goes fine . str will contain 4 rows, each row would have a string with 27601 length. but javascript doesn't alert the result. why?
I found a solution that to increase the jason max length by the following.
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="5000"/>
</webServices>
</scripting>
I put the above code inside the tag of web Config file.It works but it gives tooltip error message on the first tag. any suggestions to correct it?
the error message is,
"the element 'configuration' in namespace 'http://schemas.microsoft.com/.NetConfiguration/v2.0' has invalid child element 'system.we.extensions' in namespace 'http://schemas.microsoft.com/.NetConfiguration/v2.0'. List of possible elements expected: 'system.net' in namespace 'http://schemas.microsoft.com/.NetConfiguration/v2.0'"

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

Categories