Hello all i have code snippet like this
Case "adhoc_searchResult"
Dim cubeid As Integer = Request("cubeid")
Dim dimArr As String = Request("dimArr")
Dim tmethod As String = Request("tmethod")
Dim tstr As String = Request("tstr")
Dim search_result As DataView = New DataView()
search_result = HostAnalytics.HostAnalyzer.HostAnalyzer.getDimensionSearchResults(cubeid, dimArr, tmethod, tstr)
Response.Write(JsonConvert.SerializeObject(search_result))
Case Else
Response.Write("Invalid call")
End Select
Catch ex As Exception
Common.GetLogErrorInJson("105", "Following error occurred while getting data : " & ex.Message & " :: " & ex.StackTrace().ToString())
End Try
End Sub
End Class
Here in the vb method, it is returning Dataview object, and now i am serializing this with jsonconver.serializeObject().
but it is throwing an expcetion stating like that cirular reference occurs...
but the getDimensionSearchResult() method returning correct value, that value is not capturing in this code block.
how to overcome this and is there any mistake in my code, please help me.
Thanks
Related
I have a functionality which saves the information from a webform to the database, which is working fine.
This is my code for save functionality in Onspec.aspx.vb page
Public Sub SaveClick(ByVal sender As Object, ByVal e As System.EventArgs)
If Not Page.IsValid Then
litMessage.Text = ""
Exit Sub
End If
Try
Dim sName As String = ""
With EmployerCandidate
.employerid = Master.Employer.ID
.employeruserid = 0
Try
.CVID = DocId
Catch
End Try
.Name = uxName.Text
.SurName = uxSurname.Text
Try
.PostCode = uxPostcode.Text
Catch ex As Exception
End Try
.Email = uxEmail.Text
Try
.MobileNo = uxMobileNo.Text
Catch ex As Exception
End Try
.OnSpec = True
.OnSpecType = uxOnSpecCategory.SelectedItem.Text
.Source = uxSourceID.SelectedItem.Text
.LastEmployer = uxEmployer.Text
.LastJobTitle = uxJobtitle.Text
.Profile = uxProfile.Text.Trim
End With
' email()
ResetForm()
panForm.Visible = False
panUpload.Visible = True
uxSubmit.Visible = False
uxUpload.Visible = True
litMessage.Text = "Thank you for submitting your details! We'll be in touch when appropriate vacancy arises. <a href='#' onclick='parent.$.colorbox.close()'>Close</a>"
UploadPanel.Visible = False
Response.Redirect("onspec-complete.aspx?e=" & Master.Employer.ID)
Catch ex As Exception
litMessage.Text = Core.Helper.FancyMessage("Error as occurred - " & ex.Message.ToString, "ERROR")
End Try
End Sub
Now, I want to send emails along with saving the data in the database so I added the following lines of code before ResetForm().
Dim specmatch As DataRow = DB.GetRow("SELECT TOP 1 name,email,password FROM [user] usr JOIN employeruser empUsr ON usr.id = empUsr.userid WHERE empUsr.empusertype = 1 AND empUsr.employerid = #eid ", DB.SIP("eid", LocalHelper.UserEmployerID))
If my query returns a value then I want to send email by calling the email function.
If specmatch IsNot Nothing Then
email()
End If
But in this line of code the employerid value is sometimes empty. It can't pick the id therefore it is returning an empty row. And therefore it's not calling the email function.
This id is the same as
.employerid = Master.Employer.ID
But if I replace the LocalHelper.UserEmployerID with Master.Employer.ID the form gives an error:
Object reference not set to an instance of an object.
employerid is an integer value.
I have also tried to add the following lines of code in this page(Onspec.aspx.vb)
Public ReadOnly Property EmployerId() As Integer
Get
Return Master.Employer.ID
End Get
End Property
But I get the same error:
Object reference not set to an instance of an object.
The above lines of code does not make any difference.
So I replaced Master.Employer.ID with LocalHelper.UserEmployerID
Where in localhelper.vb file (under appcode folder) it is determining employerid from the website with following lines of code.
Public Shared Function UserEmployerID() As Integer
If HttpContext.Current.Items("lh_useremployerid") Is Nothing Then
If LocalHelper.UserTypeCode = "e" Then
HttpContext.Current.Items("lh_useremployerid") = Core.DB.GetInteger("SELECT employerid FROM employeruser WHERE userid = " & LocalHelper.UserID)
Else
HttpContext.Current.Items("lh_useremployerid") = 0
End If
End If
Return HttpContext.Current.Items("lh_useremployerid")
End Function
These lines of code has been used in many places and works perfectly fine. In this case as well, it was working fine last Friday and now it's not. There was no changes made.
This is my email function
Private Sub email()
Dim strCandidateName As String = uxName.Text.Trim & " " & uxSurname.Text.Trim
Dim strCandidateSurname As String = uxSurname.Text
Dim strCandidateEmail As String = uxEmail.Text.Trim
Dim strCandidatePhone As String = uxMobileNo.Text.Trim
Dim strCPass As String = "mpb123"
Dim strContactType As String = "Speculative Application has been submited on the category of " & uxOnSpecCategory.SelectedItem.Text
Dim strContactMessage As String = uxProfile.Text.Trim
'''''''''''''''''''variable
Dim qq As String = String.Format("Select top 1 name, email, password FROM [user] WHERE id in (Select userid FROM employeruser WHERE empusertype=1 and employerid= " & LocalHelper.UserEmployerID & ")")
Dim drow As DataRow = Core.DB.GetRow(qq)
Dim semail As String = drow.Item("email").ToString
Dim sname As String = drow.Item("name").ToString
Dim spass As String = drow.Item("password").ToString
'''''''''''''''''''variable
Dim Email As Core.Email
'New Onspec Candidate Email sent to EmployerUser who is assigned to receive onspec email
Email = New Core.Email
With Email
.ContentID = 99
.Replacement("ContactName", strCandidateName)
.Replacement("ContactEmail", strCandidateEmail)
.Replacement("ContactTelephone", strCandidatePhone)
.Replacement("ContactType", strContactType)
.Replacement("ContactMessage", strContactMessage)
.Replacement("AdminContactName", sname)
.Replacement("AdminContactEmail", semail)
.Replacement("SiteName", LocalHelper.AppSetting("sitename"))
Dim attachments As New Generic.List(Of String)
If EmployerCandidate.CVID > 0 Then
Dim doc As New Document(EmployerCandidate.CVID)
attachments.Add(doc.PathOnDisc)
End If
.Attachments = Join(attachments.ToArray(), ";")
.Send()
End With
End Sub
GetRow function is defined in my database.vb page like following which is also used in many other places.
Shared Function GetRow(ByVal selectQueryText As String, ByVal ParamArray params As SqlParameter()) As DataRow
Return GetRowFromDB(selectQueryText, CommandType.Text, params)
End Function
And
Shared Function GetRowFromDB(ByVal selectCommandText As String, ByVal selectCommandType As CommandType, ByVal ParamArray params As SqlParameter()) As DataRow
Dim conn As SqlConnection = Nothing
Try
conn = GetOpenSqlConnection()
Return GetRowFromDB(conn, selectCommandText, selectCommandType, params)
Finally
If conn IsNot Nothing Then conn.Dispose()
End Try
End Function
Please suggest ways on how I can organize my code so that it works all the time.
So I created an object called Report. A Report object has several different properties, including a DataSet. This DataSet is supposed to contain at least one DataTable. Report is serializable. In a Unit Test I instantiate a Report object, give its properties values, then serialize it, then deserialize it.
After adding a method to populate the DataSet, the Deserialization function gives me Error: Unable to cast object of type 'System.Data.DataTable' to type 'System.Collections.IEnumerable'.
Shouldn't it be getting serialized as a DataSet...not a DataTable? I'm not sure exactly what is causing me this error. Code snippets are below. Any help is appreciated!
<Serializable> Public Class Report
Private titleStr As String
Private startDateTime As DateTime
Private endDateTime As DateTime
Private numIntervalsShort As Short
Private binnedDataSet As DataSet
...property gets and sets...namely:
Property BinnedData As DataSet
Get
Return binnedDataSet
End Get
Set(ByVal value As DataSet)
binnedDataSet = value
End Set
End Property
End Class
<TestClass()> Public Class ReportObjectTest
<TestMethod()> Public Sub TestCreateReport()
Dim testReport As New Project.Report
testReport.Title = "Test Title"
testReport.StartDate = "1/1/2015 1:00 AM"
testReport.EndDate = "1/2/2015 6:00 PM"
testReport.NumIntervals = 41
PopulateDataSet(testReport)
Serialize(testReport)
Deserialize()
End Sub
Private Sub PopulateDataSet(ByRef report As Project.Report)
report.BinnedData = New DataSet()
Dim DT1 As DataTable = New DataTable("Test Table1")
report.BinnedData.Tables.Add(DT1)
DT1.Columns.Add(New DataColumn("Column1", GetType(Int32)))
DT1.Columns.Add(New DataColumn("Column2", GetType(Int32)))
DT1.Columns.Add(New DataColumn("Column3", GetType(Int32)))
Dim Row1 As DataRow = DT1.NewRow()
Dim Row2 As DataRow = DT1.NewRow()
Dim Row3 As DataRow = DT1.NewRow()
Row1("Column1") = 32
Row1("Column2") = 15
Row1("Column3") = 9
Row2("Column1") = 3
Row2("Column2") = 27
Row2("Column3") = 98
Row2("Column1") = 1
Row2("Column2") = 12
Row2("Column3") = 65
End Sub
Private Sub Serialize(ByRef report As Project.Report)
Dim stream As New FileStream("TestReport.xxx", FileMode.Create)
Dim mySerializer As BinaryFormatter = New BinaryFormatter()
Try
mySerializer.Serialize(stream, report)
Catch ex As SerializationException
Console.WriteLine("Error saving the report. " & ex.Message)
Throw
Finally
stream.Close()
End Try
End Sub
Private Sub Deserialize()
Dim readTestReport As New Project.Report()
Dim stream As New FileStream("TestReport.xxx", FileMode.Open)
Dim myDeserializer As BinaryFormatter = New BinaryFormatter()
Try
readTestReport = DirectCast(myDeserializer.Deserialize(stream), Project.Report)
Catch ex As SerializationException
Console.WriteLine("Error opening the report. " & ex.Message)
Throw
Finally
stream.Close()
End Try
Console.WriteLine(Environment.NewLine & "Values after Deserialization:")
Console.WriteLine("Title = " & readTestReport.Title)
Console.WriteLine("Start Date = " & readTestReport.StartDate)
Console.WriteLine("End Date = " & readTestReport.EndDate)
Console.WriteLine("Number of Intervals = " & readTestReport.NumIntervals)
For Each Table In readTestReport.BinnedData.Tables
For Each Row In Table
Console.WriteLine("Table Row = " & Row.ToString)
For Each DataColumn In Row
Console.WriteLine(DataColumn.ToString)
Next
Next
Next
End Sub
End Class
I was right...figured it out. The issue lay in how I was trying to display the values of the table after deserializing. DataTables and DataRows are not enumerable, but the way I was trying to display it was by looping through the way you only can with an enumerable type.
I modified that block to assign the table to a View instead:
Dim tableView As DataView = New DataView(readTestReport.BinnedData.Tables(0))
Console.WriteLine("Table = ")
Dim rowView As DataRowView
Dim i As Integer
For Each rowView In tableView
For i = 0 To tableView.Table.Columns.Count - 1
Console.Write(rowView(i) & vbTab)
Next
Console.WriteLine()
Next
These articles helped:
https://msdn.microsoft.com/en-us/library/23a0aths%28v=vs.110%29.aspx
https://msdn.microsoft.com/en-us/library/bb669099%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
So I'm trying to change this sub in to a function so that I can reference it and set a label.text as it's result, this is so I don't have to creating new subs to update different labels.
Dim drive As String = "C"
Dim disk As ManagementObject = _
New ManagementObject _
("win32_logicaldisk.deviceid=""" + drive + ":""")
disk.Get()
Dim serial As String = disk("VolumeSerialNumber").ToString()
Label1.Text = ("Serial: " & serial)
Can someone tell me how I can change this in to a function? I've tried declaring Serial as an empty String and then changing the last line to read:
Return serial = disk("VolumeSerialNumber").ToString()
At the moment this just sets Label1.Text to display "False", like I've set it as a Boolean or something?!
I'm learning functions at the moment, I'm trying to make things cleaner as up until now I've just been creating different subs to update labels etc...
I'm looking for some tips so I can try and get this myself.
It is really a simple refactoring operation.
Sub Main
Dim driveLetter = "X"
Try
Dim result = DriveSerialNumber(driveLetter)
Console.WriteLine(result)
Catch ex as Exception
Console.WriteLine("Error: drive " & driveLetter & ": " & ex.Message)
End Try
End Sub
Public Function DriveSerialNumber(drive as String) As String
Dim disk As ManagementObject = _
New ManagementObject _
("win32_logicaldisk.deviceid=""" + drive + ":""")
disk.Get()
return disk("VolumeSerialNumber").ToString()
End Function
However, be prepared to receive Exceptions if you pass an invalid drive letter
this is my very first project on vb.net and i am now struggling to migrate a vba working add in to a vb.net COM Add-in. I think i'm sort of getting the hang, but error handling has me stymied.
This is a test i've been using to understand the try-catch and how to pass exception to caller
Public Sub test()
Dim ActWkSh As Excel.Worksheet
Dim ActRng As Excel.Range
Dim ActCll As Excel.Range
Dim sVar01 As String
Dim iVar01 As Integer
Dim sVar02 As String
Dim iVar02 As Integer
Dim objVar01 As Object
ActWkSh = Me.Application.ActiveSheet
ActRng = Me.Application.Selection
ActCll = Me.Application.ActiveCell
iVar01 = iVar02 = 1
sVar01 = CStr(ActCll.Value)
sVar02 = CStr(ActCll.Offset(1, 0).Value)
Try
objVar01 = GetValuesV(sVar01, sVar02)
'DO SOMETHING HERE
Catch ex As Exception
MsgBox("ERROR: " + ex.Message)
'LOG ERROR SOMEWHERE
Finally
MsgBox("DONE!")
End Try
End Sub
Private Function GetValuesV(ByVal QryStr As Object, ByVal qryConn As String) As Object
Dim cnn As Object
Dim rs As Object
Try
cnn = CreateObject("ADODB.Connection")
cnn.Open(qryConn)
rs = CreateObject("ADODB.recordset")
rs = cnn.Execute(QryStr)
If rs.EOF = False Then
GetValuesV = rs.GetRows
Else
Throw New System.Exception("Query Return Empty Set")
End If
Catch ex As Exception
Throw ex
Finally
rs.Close()
cnn.Close()
End Try
End Function
i'd like to have the error message up to test, but
MsgBox("ERRORE: " + ex.Message)
pops out something unexpected (Object variable or With block variable not set)
What am i doing wrong here??
Thanks
D
It may be because you're doing a
Throw ex
Try using
Throw
instead. This maintains the error stack, instead of generating a new one each time.
Based on your comments, I think the specific problem you're getting is in your Finally block. You're trying to close the recordset and the connection, but if you got an error when you instantiated them, they will not exist; therefore, you get the Object variable or with block error.
(I would put the connection is a using statement anyway).
This is my code. I keep having an error "value of type string cannot be converted to system.data.datatable"
Function GetTable() As DataTable
Dim SQLConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("Zeinchatconnection").ToString())
Dim CommSQL As New SqlClient.SqlCommand
Dim ChatDataAdapter As SqlDataAdapter
Dim paramSQL As SqlClient.SqlParameter
Dim DStable As DataSet
Dim table As New DataTable
Dim szName As String = ""
Dim szNumber As String = ""
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
End If
CommSQL.Connection = SQLConnection
CommSQL.CommandType = CommandType.StoredProcedure
CommSQL.CommandText = "spc_newselect"
CommSQL.ExecuteNonQuery()
ChatDataAdapter = New SqlDataAdapter(CommSQL)
ChatDataAdapter.Fill(DSTable)
table.Rows.Clear()
table.Clear()
table = DStable.Tables(0)
Dim i As Integer = 0
For i = 0 To table.Rows.Count - 1
szName = szName & " " & table.Rows(i).Item(0) & table.Rows(i).Item(1)
szNumber = szNumber & " " & table.Rows(i).Item(0) & table.Rows(i).Item(1)
Next
GetTable = "1"
Catch ex As System.Data.SqlClient.SqlException
GetTable = "0"
Catch ex As Exception
GetTable = "0"
If (IsNothing(ChatDataAdapter) = False) Then ChatDataAdapter.Dispose()
If (IsNothing(CommSQL) = False) Then CommSQL.Dispose()
SQLConnection.Close()
End Try
Return table
End Function
The part where the errors are is gettable= "1" and below.
GetTable = "1" indicates that you want to set the returnValue of your function. As your function is defined as Function GetTable() As DataTable your compiler shows an error!
A few lines below there is a correct return stmt (Return table) so I am not quite sure what your goal is with GetTable = "1"?
I would assume that you would like to have an additional returnValue indicating whether your function call was successful or not. But as a matter of fact functions may only have one returnValue.
You may choose to set your table var to nothing, or use a ref param ...
' possible solution 1 - using nothing value
Function GetTable() As DataTable
Try
' your code goes here
' remove GetTable = "1"
Catch ex as Exception
' change GetTable = "0" to
table = nothing
End Try
' other code ...
End Function
' possible solution 2 - ref param
Function GetTable(ByRef status as integer) as DataTable
Try
' your code goes here
' remove GetTable = "1"
status = 1
Catch ex as Exception
' change GetTable = "0" to
status = 0
End Try
' other code ...
End Function
At solution 2 you may also choose a boolean parameter indicating your call was successful or not.
Your function GetTable returns a DataTable
you can't convert "1" to a DataTable as the message suggests which is what is happening on the line GetTable = "1"
If you want to return a DataTable and Set a flag to see the status; change your function definition as so:
Function GetTable(byref result as Integer) As DataTable
Then instead of GetTable = "1" change this to result = 1. This way you can inspect the result value and return a DataTable:
Dim res as Integer
Dim dt as DataTable = GetTable(res)
If res = 1 then
'It worked!
End If
Side Note: Turn Option Strict On