Asp.net display sum of columns total in gridview footer - javascript

I have a program that uploads an excel file. After uploading the value of excel file will be transferred in gridview.
What I want to do is to get the total value per column and will be placed in footer.Does anyone can help me with this? Thank you.
Here's what I have so far.
Protected Sub Button1_Click(sender As Object, e As System.EventArgs)Handles Button1.Click
Dim fl As String = FileUpload1.PostedFile.FileName
GridView1.DataSource = OpenExcelFile(fl)
GridView1.DataBind()
savetoDB(OpenExcelFile(fl))
End Sub
Protected Function OpenExcelFile(ByVal fileName As String) As Object
Dim dataTable As New System.Data.DataTable()
Dim exl As String = FileUpload1.PostedFile.FileName
Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & exl & ";Extended Properties=" & """Excel 12.0 Xml;HDR=YES;"""
Dim adapter As New OleDbDataAdapter("SELECT [NAME],[FIL],[ENG],[SCI],[MTH]", connectionString)
adapter.Fill(dataTable)
Return dataTable
End Function
Protected Sub savetoDB(dt As System.Data.DataTable)
Dim cmd As New SqlCommand
Dim con As New SqlConnection("myconnectionhere")
Dim dt2 As New System.Data.DataTable
dt2 = OpenExcelFile(FileUpload1.PostedFile.FileName)
Using bulk As SqlBulkCopy = New SqlBulkCopy(con)
bulk.DestinationTableName = "studnt_table"
bulk.ColumnMappings.Add("[NAME]", "st_name")
bulk.ColumnMappings.Add("[FIL]", "sbj_fil")
bulk.ColumnMappings.Add("[ENG]", "sbj_eng")
bulk.ColumnMappings.Add("[SCI]", "sbj_sci")
bulk.ColumnMappings.Add("[MTH]", "sbj_mth")
con.Open()
bulk.WriteToServer(dt2)
con.Close()
con.Close()
End Using
End Sub
And here is my front end
here is the sample layout I want to achieve. I want to get the sum of the columns in line and display the total in footer. Does anyone knows how can I achieve this? Any help would be much appreciated. Thank you/

Try this. I've only added sample for 1 column to get an idea. Extend the OpenExcelFile after adatapter.Fill(dataTable) IsNull Check
adatapter.Fill(dataTable)
Dim sumRow As DataRow
Dim Col1Tot,Col2Tot,Col3Tot,Col4Tot As Decimal
For Each row1 As DataRow In dataTable.Rows
If Not row1.IsNull("FIL") Then
Col1Tot = Col1Tot + Convert.toDecimal(row1("FIL"))
End If
If Not row1.IsNull("ENG") Then
Col2Tot = Col2Tot + Convert.toDecimal(row1("ENG"))
End If
If Not row1.IsNull("SCI") Then
Col3Tot = Col3Tot + Convert.toDecimal(row1("SCI"))
End If
If Not row1.IsNull("MTH") Then
Col4Tot = Col4Tot + Convert.toDecimal(row1("MTH"))
End If
Next row1
'Do the remaining columns in same way
'Finally add it to the Datatable as a new row
sumRow = dataTable.NewRow()
sumRow("FIL") = Col1Tot
dataTable.Rows.Add(sumRow)
sumRow = dataTable.NewRow()
sumRow("ENG") = Col2Tot
dataTable.Rows.Add(sumRow)
sumRow = dataTable.NewRow()
sumRow("SCI") = Col3Tot
dataTable.Rows.Add(sumRow)
sumRow = dataTable.NewRow()
sumRow("MTH") = Col4Tot
dataTable.Rows.Add(sumRow)
return dataTable;
Let us know your findings.

Related

Excel - json data - return certain elements to adjacent cells formula/macro

I have a lot of json data in rows and need to extract certain pieces of data from it in Excel, is there a way to do this? I have provided a sample of a typical cell, to keep it simple, how would I extract the "Lat" and "lng" values from this and place them in the adjacent cells. So let's say the json is in cell D2, I need the 'lat' in E3 and 'Lng' in F3:
projectId:'5571511970726f3903000000',
lat:13.737738,
lng:100.566147,
destinations:[{"id":"57bc75550ce0fe28af001609","name":"BrownEyesRestaurant","category_name":"restaurant","category_class_name":"restaurants","lat":13.737875,"lng":100.566806,"travel_time":"lessthanaminutebyfoot","distance_human":"39m","distance_in_meters":39},{"id":"57bc75550ce0fe28af00160a","name":"HanaHana","category_name":"restaurant","category_class_name":"restaurants","lat":13.738215,"lng":100.566701,"travel_time":"1minutebyfoot","distance_human":"48m","distance_in_meters":48},{"id":"57bc75550ce0fe28af001602","name":"7-Eleven","category_name":"convenience_store","category_class_name":"shopping","lat":13.73763,"lng":100.566934,"travel_time":"1minutebyfoot","distance_human":"55m","distance_in_meters":55},{"id":"57bc75550ce0fe28af001636","name":"GoldenShrine","category_name":"pokestop","category_class_name":"pokemon_places","lat":13.737763,"lng":100.567128,"travel_time":"1minutebyfoot","distance_human":"74m","distance_in_meters":74},{"id":"57bc75550ce0fe28af00160d","name":"FatFishSeafoodBistro","category_name":"restaurant","category_class_name":"restaurants","lat":13.737128,"lng":100.567127,"travel_time":"2minutesbyfoot","distance_human":"130m","distance_in_meters":126},{"id":"57bc75550ce0fe28af001635","name":"NARZStoneBalls","category_name":"pokestop","category_class_name":"pokemon_places","lat":13.738174,"lng":100.56538,"travel_time":"2minutesbyfoot","distance_human":"140m","distance_in_meters":142},
Example of desired output on screengrab:
If you don't intent to extract json, try this code.
Sub test()
Dim s As String
Dim vSplit
s = Range("d2")
vSplit = Split(s, ",")
Range("e2") = Val(Replace(vSplit(1), "lat:", ""))
Range("f2") = Val(Replace(vSplit(2), "lng:", ""))
End Sub
Edit
Sub test()
Dim s As String
Dim vSplit
Dim vDB, vR()
Dim i As Long, n As Long
vDB = Range("d2", Range("d" & Rows.Count).End(xlUp))
n = UBound(vDB, 1)
ReDim vR(1 To n, 1 To 2)
For i = 1 To n
s = vDB(i, 1)
vSplit = Split(s, ",")
vR(i, 1) = Val(Replace(vSplit(1), "lat:", ""))
vR(i, 2) = Val(Replace(vSplit(2), "lng:", ""))
Next i
Range("e2").Resize(n, 2) = vR
End Sub

Store data Array from code behind into javascript in ASP.Net

I have code like this :
Dim ListMyDate = New List(Of MyDate)()
Dim cek As Date = "2017/10/15","2017/10/16"
ListMyDate.Add(New MyDate() With {.ShowDate = cek})
allRecords = ListMyDate.ToArray()
For Each obj As MyDate In ListMyDate
Response.Write(obj.ShowDate.ToString() + ",")
Next
This code work for me, but I want store data result from my array to javascript.

VBA webscraping across multiple tables and pages of Javascript website

I have a program written in VBA which scrapes the first table of the website i am working with. I added a component for it to loop through all the items on that page by clicking the next button to view the next 50 results.
What I am having trouble with is coding which table I am referencing. My code only takes the first table on the webpage and I need all the tables but I also need the program to click through all the results.
Here is my code:
Sub ETFDat()
Dim ie As Object, i As Long, strText As String
Dim jj As Long
Dim hBody As Object, hTR As Object, hTD As Object
Dim tb As Object, bb As Object, Tr As Object, Td As Object, ii As Long
Dim doc As Object, hTable As Object
Dim y As Long, z As Long, wb As Excel.Workbook, ws As Excel.Worksheet
Set wb = Excel.ActiveWorkbook
Set ws = wb.ActiveSheet
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
y = 1 'Column A in Excel
z = 1 'Row 1 in Excel
Sheets("Fund Basics").Activate
Cells.Select
Selection.Clear
ie.navigate "http://www.etf.com/channels/smart-beta-etfs/channels/smart- beta-etfs?qt-tabs=0#qt-tabs" ', , , , "Content-Type: application/x-www-form-urlencoded" & vbCrLf
Do While ie.busy: DoEvents: Loop
Do While ie.ReadyState <> 4: DoEvents: Loop
Set doc = ie.document
Set hTable = doc.getElementsByTagName("table") '.GetElementByID("tablePerformance")
ii = 1
Do While ii <= 17
For Each tb In hTable
Set hBody = tb.getElementsByTagName("tbody")
For Each bb In hBody
Set hTR = bb.getElementsByTagName("tr")
For Each Tr In hTR
Set hTD = Tr.getElementsByTagName("td")
y = 1 ' Resets back to column A
For Each Td In hTD
ws.Cells(z, y).Value = Td.innerText
y = y + 1
Next Td
DoEvents
z = z + 1
Next Tr
Exit For
Next bb
Exit For
Next tb
With doc
Set elems = .getElementsByTagName("a")
For Each e In elems
If (e.getAttribute("id") = "nextPage") Then
e.Click
Exit For
End If
Next e
End With
ii = ii + 1
Application.Wait (Now + TimeValue("00:00:05"))
Loop
MsgBox "Done"
End Sub
I think you would have an easier time if you called their json files and then parsed it in your VBS code.
http://www.etf.com/etf-finder-channel-tag/Smart-Beta%20ETFs/-aum/50/50/1
http://www.etf.com/etf-finder-channel-tag/Smart-Beta%20ETFs/-aum/50/50/2
http://www.etf.com/etf-finder-channel-tag/Smart-Beta%20ETFs/-aum/50/50/3
...

VB 2013: Auto login from my.settings issue

I am using the latest version of Awesomium for the WebControl for my application. When my application arrives at "accounts.google.com/ServiceLogin" it is supposed to execute some Javascript to have it automatically log in. In my.settings.java I have:
"document.getElementById('Email').value=""1"";document.getElementById('Passwd').value=""2"";document.getElementById('signIn').click()"
Value "1" being the email, and "2" being the password. So when the document is ready I have this:
Private Sub WebBrowser1_DocumentReady(sender As Object, e As Awesomium.Core.UrlEventArgs) Handles WebBrowser1.DocumentReady
If WebBrowser1.Source.ToString.Contains("accounts.google.com/ServiceLogin") = True Then
WebBrowser1.ExecuteJavascript(My.Settings.java.ToString)
Else
End If
I don't know why this is not working. When I paste the code directly in like this:
WebBrowser1.ExecuteJavascript("document.getElementById('Email').value=""1"";document.getElementById('Passwd').value=""2"";document.getElementById('signIn').click()")
The code works perfectly and it logs in. The reason I have it in my.settings is because I originally have it in a textbox, then I ask the user for their email and password, and then replace "1" with the email, and "2" with the password, then save the edited textbox text in my.settings.java. Then I have it look for the Javascript there instead of hard coding it into the application, and not being able to customize it for each user. Is any of my code wrong, or is there another way of doing this with Awesomium. Also, I am using the Awesomium WebControl1, I just changed it to WebBrowser1 because that is what I am used to typing. Sorry if this question is simple, as I am a student developer, with very limited knowledge in Javascript.
I never user my.settings when it comes to sensitive data like passwords (even emails). What I always do, I encrypt them in XML file using a simple yet dynamic encryption like this :
Public Function Encrypt(ByVal plainText As String) As String
Dim passPhrase As String = **My.Computer.Name.ToString**
Dim saltValue As String = **My.Computer.Info.OSFullName.ToString**
Dim hashAlgorithm As String = "SHA1"
Dim passwordIterations As Integer = 2
Dim initVector As String = "#1B2c3D4e5F6g7H8"
Dim keySize As Integer = 256
Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
Dim plainTextBytes As Byte() = Encoding.UTF8.GetBytes(plainText)
Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
Dim symmetricKey As New RijndaelManaged()
symmetricKey.Mode = CipherMode.CBC
Dim encryptor As ICryptoTransform = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)
Dim memoryStream As New IO.MemoryStream()
Dim cryptoStream As New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)
cryptoStream.FlushFinalBlock()
Dim cipherTextBytes As Byte() = memoryStream.ToArray()
memoryStream.Close()
cryptoStream.Close()
Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)
Return cipherText
End Function
Public Function Decrypt(ByVal cipherText As String) As String
Dim passPhrase As String = **My.Computer.Name.ToString**
Dim saltValue As String = **My.Computer.Info.OSFullName.ToString**
Dim hashAlgorithm As String = "SHA1"
Dim passwordIterations As Integer = 2
Dim initVector As String = "#1B2c3D4e5F6g7H8"
Dim keySize As Integer = 256
Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
Dim cipherTextBytes As Byte() = Convert.FromBase64String(cipherText)
Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
Dim symmetricKey As New RijndaelManaged()
symmetricKey.Mode = CipherMode.CBC
Dim decryptor As ICryptoTransform = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)
Dim memoryStream As New IO.MemoryStream(cipherTextBytes)
Dim cryptoStream As New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
Dim plainTextBytes As Byte() = New Byte(cipherTextBytes.Length - 1) {}
Dim decryptedByteCount As Integer = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length)
memoryStream.Close()
cryptoStream.Close()
Dim plainText As String = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)
Return plainText
End Function
And it's still not that safe. The best way is to let the user put the password.
As for your answer , if I understand you question, you need to create profiles, and store them in files/registry. (I recommend files or database). So that when "John" uses your program, he will select the "John" profile ... and so on.

Xml.XmlDataDocument() obsolete message

I am running a simple program in which you enter a user number into a text box, click the submit button, and then the program is supposed to go to a database look up the number you entered and display that rows information. Simple enough.
The problem is I keep getting the error that Xml.XmlDataDocument() is obsolete. I've googled this issue, which led me to here, but the replacements suggested do not work within my program.
Also, I have not studied VB and this is for an XML class.
I've double checked my code for any errors and do not see anything. But, I could be missing the forest for the trees. Would like to have another set of eyes take a look at my code to see if I've missed something, or to offer up a replacement for the Xml.XmlDataDocument() line.
Thank you in advance for any help you can offer.
Here is the code I am using:
Javascript for the onClick event
<script language="javascript" type="text/javascript">
function btnSearch_onclick() {
var docSubmit = new ActiveXObject("MSXML2.DOMDocument");
docSubmit.loadXML("<?xml version='1.0'?><request><customerID>" + txtCustID.value + "</customerID></request>")
var objSocket = new ActiveXObject("MSXML2.XMLHTTP");
objSocket.open("POST", "Lookup.aspx", false)
objSocket.send(docSubmit)
alert(objSocket.responseXML.xml)
lblFirstName.innerHTML = objSocket.responseXML.selectSingleNode("//FirstName").firstChild.nodeValue
lblLastName.innerHTML = objSocket.responseXML.selectSingleNode("//LastName").firstChild.nodeValue
lblAddress.innerHTML = objSocket.responseXML.selectSingleNode("//Address").firstChild.nodeValue
lblCity.innerHTML = objSocket.responseXML.selectSingleNode("//City").firstChild.nodeValue
lblState.innerHTML = objSocket.responseXML.selectSingleNode("//State").firstChild.nodeValue
lblZip.innerHTML = objSocket.responseXML.selectSingleNode("//Zip").firstChild.nodeValue
}
</script>
And here is the VB code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim docReceived As New System.Xml.XmlDataDocument()
docReceived.Load(Request.InputStream)
Dim CustomerID = docReceived.SelectSingleNode("//customerID").FirstChild.Value
Dim myConnection As New System.Data.OleDb.OleDbConnection
Dim myConnectionString As String
myConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source = " & _
Server.MapPath("customer.mbd")
myConnection.ConnectionString = myConnectionString
Dim strSQL As String
strSQL = "Select * From CustomerInfo where CustomerID = " & CustomerID
Dim myAdapter As New System.Data.OleDb.OleDbDataAdapter(strSQL, myConnection)
Dim myDataSet As New System.Data.DataSet("CustomerInfo")
Dim intRecords As Integer
intRecords = myAdapter.Fill(myDataSet, "Customer")
Response.ContentType = "text/xml"
If intRecords > 0 Then
myDataSet.WriteXml(Response.OutputStream)
Else
Response.Write("<?xml version='1.0'?><customer><FirstName>Not Found</FirstName><LastName>***</LastName><Address>***</Address><City>***</City><State>***</State><Zip>***</Zip><Phone>***</Phone><Email>***</Email></customer>")
End If
myDataSet.WriteXml(Response.OutputStream)
myConnection.Close()
myAdapter.Dispose()
myConnection.Dispose()
End Sub
XmlDataSet is obsolete. As you can see on the msdn it may even be removed in the next version of the .NET Framework ([ObsoleteAttribute("XmlDataDocument class will be removed in a future release.")]
). In your case I don't think you need it at all. The easies fix seems to be to use just XmlDocument. I believe you won't have to change anything else in your code but this line
Dim docReceived As New System.Xml.XmlDataDocument()
to:
Dim docReceived As New System.Xml.XmlDocument()

Categories

Resources