Replacing placeholders in HTML template with textbox values - html

I've created an HTML template with placeholders, like #Name#, #Address#, #City#, etc.
How can I access the file and replace the placeholders with TextBox values from the form? Then, once the replacements have been made, how can I save the file with a new name.
I'm trying StreamReader and StreamWriter at the moment, but not having much success. Here's what I have so far. Im getting this exception upon button click:
System.InvalidCastException: 'Conversion from string "C:\test.html" to type 'Integer' is not valid.'
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ReadTextFile()
Dim TempText As String
Dim TextPath = "C:\test.html"
TempText = ReadTextFile(TextPath)
TempText = TempText.Replace("#Name#", TextBox1.Text)
WebBrowser1.Navigate("C:\test.html")
End Sub
Public Function ReadTextFile()
Dim TempString As String
Dim TextFileName As String = "C:\test.html"
Dim StreamToDisplay As System.IO.StreamReader
StreamToDisplay = New System.IO.StreamReader(TextFileName)
TempString = StreamToDisplay.ReadToEnd
StreamToDisplay.Close()
Return TempString
End Function
End Class

Related

How to deserialize json in VB.Net

I have a JSON that I want to deserialize.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim client As New RestClient(BaseUrl)
Dim Respons As Object
client.Authenticator = OAuth1Authenticator.ForProtectedResource(PublicKey, PrivateKey, Token, TokenSecret)
Dim request As New RestRequest("xml/devices/list", Method.Get)
Respons = client.Execute(request)
Console.WriteLine(Respons.Content)
Console.ReadLine()
Dim request2 As New RestRequest("json/sensor/history?id=1556402310&IncludeUnit=1&InculdeHumanReadableDate=1", Method.Get)
Respons = client.Execute(request2)
Console.WriteLine(Respons.Content)
Console.ReadLine()
End Sub
So the JSON is in Respons, but I haven't a clue how to deserialize it
Have not done anything because I don't know how.
This is how the JSON looks like
Something like this:
Public Class Sensor_class
Public Property thing As Integer
Public Property thing2 As Object
Public Property results As Result()
End Class
Dim o as Sensor_class
o = JsonConvert.DeserializeObject(Of Sensor_class)(Respons.Content)

WebService Asp.Net Json not serialize a List(Of Class)

after a lot of time searching here and in the web, i'm posting my problem and my code for yours teach me how i do this works.
The problem is that the Json not serialize listUsuarios, when i use JavaScriptSerializer the return is "{}" and when i use JsonConvert.SerializeObject the return is "False".
Sorry for my bad english.
Here is the code...
USUARIOS.VB
Imports Microsoft.VisualBasic
Public Class Usuarios
Private _Codigo As Long
Private _Nome As String
Private _Telefone As String
Public Property Codigo As Integer
Get
Return _Codigo
End Get
Set(ByVal value As Integer)
_Codigo = value
End Set
End Property
Public Property Nome() As String
Get
Return _Nome
End Get
Set(ByVal value As String)
_Nome = value
End Set
End Property
Public Property Telefone() As String
Get
Return _Telefone
End Get
Set(ByVal value As String)
_Telefone = value
End Set
End Property
End Class
Public Class ListUsuarios
Private listUsuarios As List(Of Usuarios)
Public Sub New()
listUsuarios = New List(Of Usuarios)
End Sub
Public Sub AddItem(ByVal usuario As Usuarios)
listUsuarios.Add(usuario)
End Sub
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
Public Function Item(ByVal Index As Integer) As Usuarios
Return CType(listUsuarios.Item(Index), Usuarios)
End Function
Public Function Count() As Integer
Return listUsuarios.Count
End Function
End Class
ANDROID.VB
Imports Newtonsoft.Json
Imports System.Configuration
Imports System.Data
Imports System.Data.OleDb
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Xml
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Android
Inherits System.Web.Services.WebService
Dim Dt As DataTable
Dim Da As New OleDbDataAdapter
Dim Cmd As New OleDbCommand
Dim cn As New OleDb.OleDbConnection
<WebMethod()> _
Public Function Android(query As String) As String
Dim listUsuario As ListUsuarios = carregaDadosAccess(query)
Return retornaDadosJSON(listUsuario)
End Function
Private Function getConexaoDB() As OleDbConnection
Try
cn.ConnectionString = ConfigurationManager.ConnectionStrings("MyLocalAccess").ConnectionString
cn.Open()
Return cn
Catch ex As Exception
Throw ex
End Try
End Function
Private Sub closeConexaoDB(ByVal cn As OleDbConnection)
Try
If cn.State = ConnectionState.Open Then
cn.Close()
End If
Catch ex As Exception
Throw ex
End Try
End Sub
Private Function carregaDadosAccess(selectCommmand As String) As ListUsuarios
Dim usuario As Usuarios = Nothing
Dim listUsuario As New ListUsuarios
Dim i As Long = 0
Try
cn = getConexaoDB()
Dim da As New OleDb.OleDbDataAdapter(selectCommmand, cn)
Dim dt As New DataTable
Dim arrImage() As Byte = Nothing
Dim myMS As New IO.MemoryStream
da.Fill(dt)
If dt.Rows.Count > 0 Then
Do
usuario = New Usuarios
usuario.Codigo = dt.Rows(i).Item("key-codigo")
usuario.Nome = dt.Rows(i).Item("dad-descri")
usuario.Telefone = dt.Rows(i).Item("dad-telefo")
listUsuario.AddItem(usuario)
i = i + 1
If i = dt.Rows.Count Then Exit Do
Loop
Else
listUsuario = Nothing
End If
Catch ex As Exception
Throw ex
Finally
closeConexaoDB(cn)
End Try
Return listUsuario
End Function
Private Function retornaDadosJSON(listUsuario As ListUsuarios) As String
'Json serializer do prĂ³prio .net
'Dim JsonSerializer As New JavaScriptSerializer
'Return JsonSerializer.Serialize(listUsuario)
'Json serializer James Newton-King
Dim JsonSerializer As String = ""
Return JsonSerializer = JsonConvert.SerializeObject(listUsuario)
End Function
End Class
The first problem is you are returning a value that compares an empty string with the serialized json string and since the json serialized string is not empty. This is where the result of "False" is coming from.
You can fix that problem by changing the method to:
Private Function retornaDadosJSON(listUsuario As ListUsuarios) As String
Return JsonConvert.SerializeObject(listUsuario)
End Function
You can prevent this type of issue in the future by adding the following directives to the top of each file:
Option Explicit On
Option Strict On
or by setting the corresponding values in the project's Compile property page (you can also set these to default values for new projects in Visual Studio's Tools > Options > Projects and Solutions > VB Default).
Option Strict On would have prevented that code from compiling. It would also show you that there is a data type difference between _Codigo and Codigo (one is Long the other is Integer).
The second problem is that ListUsuarios isn't defined well for what you are trying to do with it. It would be much better to inherit from List(Of Usuarios) than your current design.
Changing to the following class will both reduce the code and ensure the data is serialized correctly:
Public Class ListUsuarios
Inherits List(Of Usuarios)
Public Sub AddItem(ByVal usuario As Usuarios)
Me.Add(usuario)
End Sub
End Class

Decode JSON (String) - visual basic

How can I decode a JSON String in Visual Basic (without download programs)
Private Sub ViewHintToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ViewHintToolStripMenuItem.Click
Dim instance As Net.WebClient = New Net.WebClient
Dim address As String = "https://pr2hub.com/files/artifact_hint.txt"
Dim returnValue As String
returnValue = instance.DownloadString(address)
Artifact.Text = returnValue
HintText.Show()
HintText.RichTextBox1.Text = returnValue
HintText.RichTextBox2.Text = returnValue
End Sub
By Decode I am assuming you mean Deserialize. Have you tried System.Web.Script.Serialization.JavaScriptSerializer ?
I don't understand what you're trying to deserialize above but here's a generic example:
Dim s as String = "{ 'name':'Fred', 'address':'123 Main', 'phone':'333-4444'}"
Dim jss As New JavaScriptSerializer
Dim o As Object = jss.Deserialize(Of Object)(s)
Note there is also a jss.Serialize method available.

asmx won't return JSON

I've completely rewritten this old asmx service function but I still can't get it to return JSON. It returns XML, even if I use ajax() and set the datatype and contenttype to json. I'm trying to use this function with Jquery dataTables. And I know there are tons of questions like this but all of them I've found are C# and I was unable to adapt them.
up-to-date pastebin of full asmx file: http://pastebin.com/swXKqgd4
new code
<WebMethod()> _
<WebGet(ResponseFormat:=WebMessageFormat.Json)> _
Public Function rptPendingServerRequests() As Generic.List(Of request)
Dim _conn As SqlConnection = New SqlConnection(connectionString)
Dim _dr As SqlDataReader
Dim Sql As String = String.Empty
Sql += "<My query here>"
Try
Dim _cmd As SqlCommand = New SqlCommand(Sql, _conn)
_conn.Open()
_dr = _cmd.ExecuteReader(CommandBehavior.CloseConnection)
If _dr.HasRows Then
Dim s As request
Dim c As New Generic.List(Of request)
While _dr.Read
s = New request
With s
.requestID = _dr("request_id")
.status = _dr("status")
.requester = _dr("req_by_user_id")
.assignee = _dr("user_id")
.nextAction = _dr("description")
End With
c.Add(s)
End While
Return c
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
_conn.Close()
End Try
End Function
New class
<Serializable()> _
Public Class request
Private _requestID As Integer
Public Property requestID() As Integer
Get
Return _requestID
End Get
Set(ByVal value As Integer)
_requestID = value
End Set
End Property
Private _requester As String
Public Property requester() As String
Get
Return _requester
End Get
Set(ByVal value As String)
_requester = value
End Set
End Property
Private _requestDate As Date
Public Property requestDate() As Date
Get
Return _requestDate
End Get
Set(ByVal value As Date)
_requestDate = value
End Set
End Property
Private _status As Integer
Public Property status() As Integer
Get
Return _status
End Get
Set(ByVal value As Integer)
_status = value
End Set
End Property
Private _assignee As String
Public Property assignee() As String
Get
Return _assignee
End Get
Set(ByVal value As String)
_assignee = value
End Set
End Property
Private _nextAction As String
Public Property nextAction() As String
Get
Return _nextAction
End Get
Set(ByVal value As String)
_nextAction = value
End Set
End Property
End Class
Original Code
<WebMethod()> _
<WebGet(ResponseFormat:=WebMessageFormat.Json)> _
Public Function rptPendingServerRequestsOld() As DataSet
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
sql = ""
sql += "<MY query here>"
connection = New SqlConnection(connectionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
connection.Close()
Return ds
Catch ex As Exception
End Try
End Function
Client
$('#report').dataTable({
"bProcessing": true,
"sAjaxSource": 'reportdata.asmx/rptPendingServerRequests'
});
Since you're calling this method from JS instead of
<WebGet(ResponseFormat:=WebMessageFormat.Json)>
use
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
attribute. Also don't forget to mark your WebService class with
<ScriptService()>
attribute.
Change this line.
Public Function rptPendingServerRequests() As Generic.List(Of request)
to
Public Function rptPendingServerRequests() As String.

Telerik Dock is duplicating boxes and "_breaking_" the webpage, how can I fix the problem?

Here is the Code:
VB:
Imports System.Web.Script.Serialization
Partial Class MyLanding
Inherits System.Web.UI.Page
Private LoginClass As New LoginClass
Private _dockStateCleared As Boolean = False
Private _conn As New SqlConnection(ConfigurationManager.ConnectionStrings("MidwestPartsConnectionString").ConnectionString)
Private ReadOnly Property CurrentDockStates() As List(Of DockState)
Get
'Get saved state string from the database - set it to dockState variable for example
Dim dockStatesFromDB As String = ""
_conn.Open()
Dim command As New SqlCommand("SELECT JavascriptStr FROM SysProperties WHERE (UserID = #UserID)", _conn)
command.Parameters.Add("#UserID", SqlDbType.UniqueIdentifier).Value = Me.LoginClass.ReturnUserID()
Try
dockStatesFromDB = command.ExecuteScalar().ToString()
_conn.Close()
Catch ex As Exception
_conn.Close()
Me.CreateSavedLayout("")
End Try
Dim _currentDockStates As New List(Of DockState)()
Dim stringStates As String() = dockStatesFromDB.Split("|"c)
For Each stringState As String In stringStates
If stringState.Trim() <> String.Empty Then
_currentDockStates.Add(DockState.Deserialize(stringState))
End If
Next
Return _currentDockStates
End Get
End Property
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
If Not Page.IsPostBack Then
If CurrentDockStates.Count = 0 Then
Me.LoadItems()
End If
End If
End Sub
Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Init
Dim i As Integer = 0
While i < CurrentDockStates.Count
If CurrentDockStates(i).Closed = False Then
Dim dock As RadDock = CreateRadDockFromState(CurrentDockStates(i))
dlColumnOne.Controls.Add(dock)
CreateSaveStateTrigger(dock)
LoadUserControl(dock)
End If
System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
End While
End Sub
Protected Sub dlColumnOne_LoadDockLayout(ByVal sender As Object, ByVal e As DockLayoutEventArgs)
For Each state As DockState In CurrentDockStates
e.Positions(state.UniqueName) = state.DockZoneID
e.Indices(state.UniqueName) = state.Index
Next
End Sub
Protected Sub dlColumnOne_SaveDockLayout(ByVal sender As Object, ByVal e As DockLayoutEventArgs)
Dim stateList As List(Of DockState) = dlColumnOne.GetRegisteredDocksState()
Dim serializedList As New StringBuilder()
Dim i As Integer = 0
While i < stateList.Count
serializedList.Append(stateList(i).ToString())
serializedList.Append("|")
System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
End While
Dim dockState As String = serializedList.ToString()
If dockState.Trim() <> [String].Empty Then
_conn.Open()
Dim command As New SqlCommand([String].Format("update sysproperties set javascriptstr = '{0}' Where UserID = #UserID ", dockState), _conn)
command.Parameters.Add("#UserID", SqlDbType.UniqueIdentifier).Value = Me.LoginClass.ReturnUserID()
command.ExecuteNonQuery()
_conn.Close()
End If
End Sub
Private Function CreateRadDockFromState(ByVal state As DockState) As RadDock
Dim dock As New RadDock()
dock.DockMode = DockMode.Docked
dock.UniqueName = state.UniqueName
dock.ID = String.Format("RadDock{0}", dock.UniqueName)
dock.ApplyState(state)
dock.Commands.Add(New DockCloseCommand())
dock.Commands.Add(New DockExpandCollapseCommand())
Return dock
End Function
Private Function CreateRadDock(ByVal DockTitle As String) As RadDock
Dim docksCount As Integer = CurrentDockStates.Count
Dim dock As New RadDock
dock.DockMode = DockMode.Docked
Dim UniqueName As String = Guid.NewGuid().ToString()
UniqueName = UniqueName.Replace("-", "")
dock.UniqueName = UniqueName
dock.ID = String.Format("RadDock{0}", UniqueName)
dock.Title = DockTitle
dock.Width = Unit.Pixel(400)
dock.Commands.Add(New DockCloseCommand())
dock.Commands.Add(New DockExpandCollapseCommand())
Return dock
End Function
Private Sub LoadItems()
Dim DocksDataTable As DataTable = Me.ReturnReports()
For i = 0 To DocksDataTable.Rows.Count() - 1
Dim dock As RadDock = Me.CreateRadDock(DocksDataTable.Rows(i).Item("ReportTitle").ToString())
Dim dz As RadDockZone = Me.dzColumnOne
Dim dl As RadDockLayout = Me.dlColumnOne
dz.Controls.Add(dock)
Me.CreateSaveStateTrigger(dock)
dock.Tag = DocksDataTable.Rows(i).Item("ReportPath")
Me.LoadUserControl(dock)
Next
End Sub
Public Function ReturnReports() As DataTable
Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("MidwestPartsConnectionString").ConnectionString)
Dim Query As String = "SELECT Reports.ReportPath, Reports.ReportTitle, UserReports.UserID FROM UserReports INNER JOIN Reports ON UserReports.ReportID = Reports.ReportID WHERE (UserReports.UserID = #UserID)"
Dim adapter As New SqlDataAdapter
adapter.SelectCommand = New SqlCommand(Query, connection)
adapter.SelectCommand.Parameters.Add("#UserID", SqlDbType.UniqueIdentifier).Value = Me.LoginClass.ReturnUserID()
Dim table1 As New DataTable
connection.Open()
Try
adapter.Fill(table1)
Finally
connection.Close()
End Try
Return table1
End Function
Private Function ReturnLayout() As DataTable
Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("MidwestPartsConnectionString").ConnectionString)
Dim Query As String = "select * from sysproperties"
Dim adapter As New SqlDataAdapter
adapter.SelectCommand = New SqlCommand(Query, connection)
adapter.SelectCommand.Parameters.Add("#UserPropertiesID", SqlDbType.Int).Value = 1
Dim table1 As New DataTable
connection.Open()
Try
adapter.Fill(table1)
Finally
connection.Close()
End Try
Return table1
End Function
Private Sub LoadUserControl(ByVal dock As RadDock)
If String.IsNullOrEmpty(dock.Tag) Then
Return
End If
Dim usercontrol As Control = LoadControl(dock.Tag)
dock.ContentContainer.Controls.Add(usercontrol)
End Sub
Private Sub CreateSaveStateTrigger(ByVal dock As RadDock)
dock.AutoPostBack = True
dock.CommandsAutoPostBack = True
Dim saveStateTrigger As New AsyncPostBackTrigger()
saveStateTrigger.ControlID = dock.ID
saveStateTrigger.EventName = "DockPositionChanged"
UpdatePanel1.Triggers.Add(saveStateTrigger)
saveStateTrigger = New AsyncPostBackTrigger()
saveStateTrigger.ControlID = dock.ID
saveStateTrigger.EventName = "Command"
UpdatePanel1.Triggers.Add(saveStateTrigger)
End Sub
Private Sub CreateSavedLayout(ByVal JavascriptStr As String)
Dim sqlConn As New SqlConnection(ConfigurationManager.ConnectionStrings("MidwestPartsConnectionString").ConnectionString)
Dim strSqlInsert As String = "INSERT INTO SysProperties(UserID, JavascriptStr) VALUES (#UserID, #JavascriptStr)"
strSqlInsert += "; SELECT SCOPE_IDENTITY() ;"
Dim sqlCmd As New SqlCommand(strSqlInsert, sqlConn)
With sqlCmd.Parameters
.Add("#JavascriptStr", SqlDbType.Text).Value = JavascriptStr
.Add("#UserID", SqlDbType.UniqueIdentifier).Value = Me.LoginClass.ReturnUserID()
End With
sqlCmd.Connection.Open()
sqlCmd.ExecuteScalar()
sqlCmd.Connection.Close()
End Sub
Protected Sub btnAddReports_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddReports.Click
Try
Response.Redirect("~/MyUserAccount/SelectedReports.aspx", False)
Catch ex As Exception
End Try
End Sub
End Class
Your could looks fine. Possible reasons for this problem include the following:
Dragging the Dock control very quickly causes an ajax conflict, and an error is shown. To avoid this from happening you could show an AjaxLoading panel during the process of an ajax request (search/ask in the telerik forums for a sample showing how to do this). Additionally you should make sure the UpdatePanels on your site are configured as in the following online demo: http://demos.telerik.com/aspnet-ajax/dock/examples/myportal/defaultcs.aspx.
The error is a result of a ViewState problem. This telerik forum thread provides a possible solution: www.telerik.com/community/forums/aspnet-ajax/docking/failed-to-load-view-state-error-when-moving-dynamically-created-widgets-around-the-raddocklayout.aspx