Reference to a non-shared member requires an object reference - vb.net

I am getting the above error now when I run one of my ASPX pages, written in VB.NET. So I tried following the solution at:
http://msdn.microsoft.com/en-us/library/zwwhc0d0(v=vs.80).aspx
The above link seemed promising, cause it seemed to describe my problem exactly. However, I got the following error from this solution:
Compiler Error Message: BC30456:
'GlobalF2' is not a member of
'GlobalFunctions' Line 88:
DSProductData =
GlobalFunctions.GlobalF2.ComplaintTrendingDrillDown3p(FirstMonthDate,
LastMonthDate, TheLevel, ProductGroup,
TheCategory, ListNumber)
And here is my modified source code causing this error, but based off of Mike Smith's solution:
Namespace GlobalFunctions
Public Class GlobalF
Public Function ComplaintTrendingDrillDown3p(ByVal FirstMonth As DateTime, ByVal LastMonth As DateTime, ByVal rowLevel As Integer, ByVal productGroup As String, ByVal category As String, ByVal ListNumber As String) As DataSet
Dim DSPageData As New System.Data.DataSet
Dim param(5) As SqlClient.SqlParameter
param(0) = New SqlParameter("#FirstMonthDate", SqlDbType.DateTime)
param(0).Value = FirstMonth
param(1) = New SqlParameter("#LastMonthDate", SqlDbType.DateTime)
param(1).Value = LastMonth
param(2) = New SqlParameter("#TheLevel", SqlDbType.Int)
param(2).Value = rowLevel
param(3) = New SqlParameter("#ProductGroup", SqlDbType.Varchar)
param(3).Value = productGroup
param(4) = New SqlParameter("#TheCategory", SqlDbType.Varchar)
param(4).Value = category
param(5) = New SqlParameter("#ListNumber", SqlDbType.Varchar)
param(5).Value = ListNumber
''# A Using block will ensure the .Dispose() method is called for these variables, even if an exception is thrown
''# This is IMPORTANT - not disposing your connections properly can result in an unrespsonsive database
Using conn As New SQLConnection(ConfigurationSettings.AppSettings("AMDMetricsDevConnectionString")), _
cmd As New SQLCommand("ComplaintTrendingDrillDown3p", conn), _
da As New SQLDataAdapter(cmd)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddRange(param)
da.Fill(DSPageData)
End Using
Return DSPageData
End Function
End Class
Public Class CallingClass
Dim GlobalF2 As New GlobalF
Public Function ComplaintTrendingDrillDown3p(ByVal FirstMonth As DateTime, ByVal LastMonth As DateTime, ByVal rowLevel As Integer, ByVal productGroup As String, ByVal category As String, ByVal ListNumber As String) As DataSet
Dim DSPageData As New System.Data.DataSet
Dim param(5) As SqlClient.SqlParameter
param(0) = New SqlParameter("#FirstMonthDate", SqlDbType.DateTime)
param(0).Value = FirstMonth
param(1) = New SqlParameter("#LastMonthDate", SqlDbType.DateTime)
param(1).Value = LastMonth
param(2) = New SqlParameter("#TheLevel", SqlDbType.Int)
param(2).Value = rowLevel
param(3) = New SqlParameter("#ProductGroup", SqlDbType.Varchar)
param(3).Value = productGroup
param(4) = New SqlParameter("#TheCategory", SqlDbType.Varchar)
param(4).Value = category
param(5) = New SqlParameter("#ListNumber", SqlDbType.Varchar)
param(5).Value = ListNumber
''# A Using block will ensure the .Dispose() method is called for these variables, even if an exception is thrown
''# This is IMPORTANT - not disposing your connections properly can result in an unrespsonsive database
Using conn As New SQLConnection(ConfigurationSettings.AppSettings("AMDMetricsDevConnectionString")), _
cmd As New SQLCommand("ComplaintTrendingDrillDown3p", conn), _
da As New SQLDataAdapter(cmd)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddRange(param)
da.Fill(DSPageData)
End Using
Return DSPageData
End Function
End Class
End Namespace
I think Mike Smith is correct about not using Shared, cause I think that caused this problem. However, I am a newbie at VB.NET and I'm not sure how else to declare an instance as an object variable and then reference this instance by variable name. Can you help?
OK, ur solution looked very good to me. I want to make sure I implemented it correctly though. Can you compare mine to urs?
Now I get the same error I had initially...Maybe it's overwriting data in the table?
Dim gf As New GlobalFunctions.CallingClass
DSProductData = gf.GlobalF2.ComplaintTrendingDrillDown3p(FirstMonthDate, LastMonthDate, TheLevel, ProductGroup, TheCategory, ListNumber)
...
Public Class CallingClass
Public GlobalF2 As New GlobalF
'Public Function CallingClass(ByVal FirstMonth As DateTime, ByVal LastMonth As DateTime, ByVal rowLevel As Integer, ByVal productGroup As String, ByVal category As String, ByVal ListNumber As String)
' Dim cc_new As New CallingClass()
'End Function
Public Function ComplaintTrendingDrillDown3p(ByVal FirstMonth As DateTime, ByVal LastMonth As DateTime, ByVal rowLevel As Integer, ByVal productGroup As String, ByVal category As String, ByVal ListNumber As String) As DataSet
Dim DSPageData As New System.Data.DataSet
Dim param(5) As SqlClient.SqlParameter
param(0) = New SqlParameter("#FirstMonthDate", SqlDbType.DateTime)
param(0).Value = FirstMonth
param(1) = New SqlParameter("#LastMonthDate", SqlDbType.DateTime)
param(1).Value = LastMonth
param(2) = New SqlParameter("#TheLevel", SqlDbType.Int)
param(2).Value = rowLevel
param(3) = New SqlParameter("#ProductGroup", SqlDbType.Varchar)
param(3).Value = productGroup
param(4) = New SqlParameter("#TheCategory", SqlDbType.Varchar)
param(4).Value = category
param(5) = New SqlParameter("#ListNumber", SqlDbType.Varchar)
param(5).Value = ListNumber
''# A Using block will ensure the .Dispose() method is called for these variables, even if an exception is thrown
''# This is IMPORTANT - not disposing your connections properly can result in an unrespsonsive database
Using conn As New SQLConnection(ConfigurationSettings.AppSettings("AMDMetricsDevConnectionString")), _
cmd As New SQLCommand("ComplaintTrendingDrillDown3p", conn), _
da As New SQLDataAdapter(cmd)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddRange(param)
da.Fill(DSPageData)
End Using
Return DSPageData
End Function
End Class
And the error:
System.ArgumentException: Column
'QXP_SHORT_DESC' does not belong to
table Table.
The offending line:
If pException("QXP_SHORT_DESC") =
TheCategory Then

You can't dim an instance of a class outside a method you can use
public GlobalF2 As New GlobalF
EDIT
I'm not sure exactly what you are attempting to do but pulling all of the extraneous code out.
Class File
Namespace GlobalFunctions
Public Class GlobalF
Public Sub DoSomthing()
Console.WriteLine("hi")
End Sub
End Class
Public Class CallingClass
Public GlobalF2 As New GlobalF
Public x As Int16 = 3
End Class
End Namespace
Main File
Imports System.IO
Module Module1
Public Sub Main()
Dim gf As New GlobalFunctions.CallingClass
gf.GlobalF2.DoSomthing()
End Sub
End Module

Related

Understanding Shared member in vb.net in the context explained below

I'm using a wrapper class for accessing sql server data in vb.net from this link
ADO.NET Data Access Component for SQL Server in C# and VB.NET
Now in this link if we see the vb.net class two class level variable(SqlComm & SqlDA ) are declared as
Public Class VBDataAccess(Of TConnection As IConnection)
Shared SqlComm As SqlCommand = Nothing
Shared SqlDA As SqlDataAdapter = Nothing
and these are used in shared method of the class as follows
Public Shared Function NonQuery(ByVal CommandText As String, _
ByVal ParameterValues As List(Of SqlParameter), _
ByVal CommandType As CommandType) As Integer
Dim res As Integer = 0
Dim SqlConn As SqlConnection = Connection
SqlConn.Open()
Try
SqlComm = New SqlCommand(CommandText, SqlConn)
SqlComm.CommandTimeout = 600
SqlComm.CommandType = CommandType
If (ParameterValues IsNot Nothing) Then
For Each Parameter In ParameterValues
SqlComm.Parameters.Add(Parameter)
Next
End If
res = SqlComm.ExecuteNonQuery()
Catch ex As Exception
Throw ex
End Try
Return res
End Function
How this SqlComm will behave in case of multiple users accessing the function at same time. Is it going to create any problem ?

Having issues when 2 users are working with the same program

Public Class DataAccess
Dim dataAcc As New DataAccess
Public Shared dtx As New DataTable
Private Shared ConStr As String = "Server = 10.18.206.30;database=PeajeFacturacion;User ID=FacturacionUsr;Password = ukShLq?U6&hNxDxN+67!XaYq"
Public Shared Function AddOneRecord(PK As String) As DataTable
Using cn As New SqlConnection(ConStr),
cmd As New SqlCommand("Select c.idCruce, c.FechaCruce, c.HoraCruce, c.claseVehiculo, c.Importe,
c.codigoCobro, n.nomCaseta
from dbo.Cruce AS c
JOIN dbo.nombre_caseta AS n
ON n.numCaseta=c.ClavePlaza
where c.CodigoCobro = #PK;", cn)
cmd.Parameters.Add("#PK", SqlDbType.VarChar).Value = PK
cn.Open()
dtx.Load(cmd.ExecuteReader)
End Using
Return dtx
End Function
End Class
I use that part to create the connection just like the example #Mary posted. Then:
Protected Sub btnAgregar_Click(sender As Object, e As EventArgs) Handles btnAgregar.ServerClick
Dim numTicket As String = txtNoTicket.Text
Dim dtx As New DataTable
Dim pk As String
pk = txtNoTicket.Text
Dim con2 As New SqlConnection
Dim cmd2 As New SqlCommand
Dim dr As SqlDataReader
Dim dtx2 As DataTable
Dim status As Boolean = False
'If Not Integer.TryParse(ticket.Text, pk) Then
If String.IsNullOrEmpty(pk) Then
'ScriptManager.RegisterStartupScript(Me, Page.GetType, "Script", "showDisplay();", True)
cFunciones.mostrarDivAlertaAA("Type a number", "dangerNormal", Me.Page, "")
Else
dtx = DataAccess.AddOneRecord(pk)
So when adding tickets the issue is the ticket 1 user adds, gets added to the other user even though they use different sessions and different computers. The program is in test fase right now.
You can get rid of Shared in the DatAccess class. Then each instance of the class will have its own data. Now you must declare an instance of the class and call the method on that instance.
Public Class DataAccess
Dim dataAcc As New DataAccess
Public dtx As New DataTable
Private ConStr As String = "Server = 10.18.206.30;database=PeajeFacturacion;User ID=FacturacionUsr;Password = ukShLq?U6&hNxDxN+67!XaYq"
Public Function AddOneRecord(PK As String) As DataTable
Using cn As New SqlConnection(ConStr),
cmd As New SqlCommand("Select c.idCruce, c.FechaCruce, c.HoraCruce, c.claseVehiculo, c.Importe,
c.codigoCobro, n.nomCaseta
from dbo.Cruce AS c
JOIN dbo.nombre_caseta AS n
ON n.numCaseta=c.ClavePlaza
where c.CodigoCobro = #PK;", cn)
cmd.Parameters.Add("#PK", SqlDbType.VarChar).Value = PK
cn.Open()
dtx.Load(cmd.ExecuteReader)
End Using
Return dtx
End Function
End Class
Protected Sub btnAgregar_Click(sender As Object, e As EventArgs) Handles btnAgregar.ServerClick
Dim dtx As New DataTable
Dim pk = txtNoTicket.Text
If String.IsNullOrEmpty(pk) Then
cFunciones.mostrarDivAlertaAA("Type a number", "dangerNormal", Me.Page, "")
Else
Dim datAcc As New DataAccess
dtx = datAcc.AddOneRecord(pk)
End If
End Sub

How to pass multiple attributes to WebApi?

I have a webapi made in VB.NET where I can get all data, data by month and data by year. Now I am trying to add the functionality to get data by data-range, in the constructor the method looks as the following:
Public Function TotaliDataData(ByVal inizio As String, ByVal fine As String) As IEnumerable(Of Totali)
Dim SQLConnect As String = "Server=127.0.0.1;Port=3306;Database=00168780351;Uid=root;Pwd=block;"
Dim cn As New MySqlConnection(SQLConnect)
Dim cmd As New MySqlCommand("SELECT NPV_TT, NCASSA_TT, DATA_TT, AZZ_TT, SUM(NSC_TT) AS NSC_TT, SUM(VENDITE_TT) AS VENDITE_TT, RESI_TT, ANNULLI_TT, SCONTI_TT, FATTURE_TT, NC_TT FROM totali WHERE DATA_TT BETWEEN '" & inizio & "' AND '" & fine & "' GROUP BY MONTH(DATA_TT);", cn)
cn.Open()
Dim reader As MySqlDataReader = cmd.ExecuteReader()
Dim totali As List(Of Totali) = ConvertReader(reader)
cn.Dispose()
Return totali
End Function
Here is my TotaliController.VB:
Public Class TotaliController
Inherits ApiController
Public Function GetTotali() As IEnumerable(Of Totali)
Dim Totali As Totali = New Totali
Return Totali.GetTotali()
End Function
Public Function GetTotaliByYear(ByVal anno As String) As IEnumerable(Of Totali)
Dim Totali As Totali = New Totali
Return Totali.TotaliAnno(anno)
End Function
Public Function GetTotaliByMonth(ByVal mese As String) As IEnumerable(Of Totali)
Dim Totali As Totali = New Totali
Return Totali.TotaliMese(mese)
End Function
Public Function TotaliDataData(ByVal inizio As String, ByVal fine As String) As IEnumerable(Of Totali)
Dim Totali As Totali = New Totali
Return Totali.TotaliDataData(inizio, fine)
End Function
Public Function GetDetails(ByVal annod As String) As IEnumerable(Of Totali)
Dim Totali As Totali = New Totali
Return Totali.GetDetails(annod)
End Function
End Class
Then I was trying to call localhost:port/api/totali/?inizio=2019-11-10&fine=2019-12-20 but it doesn't enter even inside the debug of controller while if I try to get data by month or year with single parameter it works fine..
So how could I pass multiple parameters to WebApi?
UPDATE:
When I try to run localhost:port/api/totali/?inizio=2019-11-10&fine=2019-12-20 it calls the default GetTotali() method from controller which returns all data from the DB.
Global:
Public Class WebApiApplication
Inherits System.Web.HttpApplication
Protected Sub Application_Start()
GlobalConfiguration.Configure(AddressOf WebApiConfig.Register)
GlobalConfiguration.Configuration.Formatters.
JsonFormatter.MediaTypeMappings.Add(New RequestHeaderMapping("Accept", "text/html", StringComparison.InvariantCultureIgnoreCase, True, "application/json"))
End Sub
End Class
WebApiConfig
Public Module WebApiConfig
Public Sub Register(ByVal config As HttpConfiguration)
' Servizi e configurazione dell'API Web
' Route dell'API Web
config.MapHttpAttributeRoutes()
config.Routes.MapHttpRoute(
name:="DefaultApi",
routeTemplate:="api/{controller}/{id}",
defaults:=New With {.id = RouteParameter.Optional}
)
End Sub
End Module
Apparently methods names in WebApi controller have to start with REST prefix so by changing the name of method TotaliDataData to GetTotaliDataData solved the problem.

Populating a Menu from a Database

I found some very useful code on populating a menu from a database and customised it a bit but I am struggling to create a third level to menu as in the below example(2.1.1 and 2.1.2)
Home
About Us
2.1 Management Team
2.1.1 Team Member 1
2.1.2 Team Member 2
2.2 Company Information
Contact Us
I have listed my code below.
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports iconCloud_BL
Partial Class Main
Inherits System.Web.UI.MasterPage
Public Params As New List(Of SqlParameter)
Dim clsDatabase As New clsDatabaseLogic
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not Me.IsPostBack Then
Dim dt As DataTable = Me.GetData(0, 2)
PopulateMenu(dt, 0, Nothing)
End If
End Sub
Private Function GetData(parentMenuId As Integer, role As Integer) As DataTable
Dim query As String = "SELECT [menusMenuId], [menusTitle], [menusDescription], [menusUrl] FROM [configMenus] WHERE menusParentMenuId = #ParentMenuId AND menusRole = #Role"
Dim constr As String = ConfigurationManager.ConnectionStrings("iconDataConnections").ConnectionString
Using con As New SqlConnection(constr)
Dim dt As New DataTable()
Using cmd As New SqlCommand(query)
Using sda As New SqlDataAdapter()
cmd.Parameters.AddWithValue("#ParentMenuId", parentMenuId)
cmd.Parameters.AddWithValue("#Role", role)
cmd.CommandType = CommandType.Text
cmd.Connection = con
sda.SelectCommand = cmd
sda.Fill(dt)
End Using
End Using
Return dt
End Using
End Function
Private Sub PopulateMenu(dt As DataTable, parentMenuId As Integer, parentMenuItem As MenuItem)
Dim dtChild As DataTable
Dim currentPage As String = Path.GetFileName(Request.Url.AbsolutePath)
For Each row As DataRow In dt.Rows
Dim rowcount = getMaxRows()
Dim menuItem As New MenuItem() With {
.Value = row("menusMenuId").ToString(),
.Text = row("menusTitle").ToString(),
.NavigateUrl = row("menusUrl").ToString(),
.Selected = row("menusUrl").ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase)
}
If parentMenuId = 0 Then
mainMenu.Items.Add(menuItem)
dtChild = Me.GetData(Integer.Parse(menuItem.Value), 2)
PopulateMenu(dtChild, Integer.Parse(menuItem.Value), menuItem)
ElseIf parentMenuId > 0 Then
For i As Integer = 0 To rowcount
mainMenu.Items.Add(menuItem)
dtChild = Me.GetData(Integer.Parse(i), 2)
PopulateMenu(dtChild, Integer.Parse(i), menuItem)
Next
Else
parentMenuItem.ChildItems.Add(menuItem)
End If
Next
End Sub
Public Function getMaxRows()
clsDatabase.SQLCmd.CommandText = "sp_iconCloud_configMenuRowsCount"
clsDatabase.SQLCmd.CommandType = CommandType.StoredProcedure
clsDatabase.SQLCmd.Connection = clsDatabase.SQLConn
clsDatabase.SQLConn.Open()
Dim count As Integer = clsDatabase.SQLCmd.ExecuteScalar()
clsDatabase.SQLConn.Close()
clsDatabase.SQLCmd.Parameters.Clear()
Return count
End Function
End Class

value of type 'cfeedback' cannot be converted to 'system.collections.arraylist'

Firstly, i have a grdData at my main page. After choosing the data i want and went to another page using
Request.QueryString("id")
In that page i would like to make another grdData using the
Request.QueryString("id")
but came upon an error by
Value of type 'cfeedback' cannot be converted to 'system.collections.arraylist'
Below are my codes
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim objArrayList As New ArrayList
Dim objCDBFeedback As New CDBFeedback
Dim intGuestID2 As Integer
intGuestID2 = Request.QueryString("id")
objArrayList = objCDBFeedback.getFeedBack(intGuestID2)
grdResult.DataSource = objArrayList
grdResult.DataBind()
grdResult.HeaderRow.BackColor = Drawing.Color.AliceBlue
grdResult.RowStyle.BackColor = Drawing.Color.BlanchedAlmond
grdResult.AlternatingRowStyle.BackColor = Drawing.Color.LightSalmon
grdResult.Columns(0).Visible = True
End Sub
My Function
Public Function getFeedBack(ByVal pintGuestID1 As Integer) As CFeedback
Dim objCmd As New MySqlCommand
Dim objCn As New MySqlConnection(connectionString)
Dim objAdapter As New MySqlDataAdapter
Dim strSQL As String = ""
Dim objDs As New DataSet
Dim objDataRow As DataRow
strSQL = "SELECT * FROM tblFeedback WHERE strGuestCodeFB=" & pintGuestID1
objCmd.CommandText = strSQL
objCmd.Connection = objCn
objAdapter.SelectCommand = objCmd
objCn.Open()
objAdapter.Fill(objDs, "tblFeedback")
objDataRow = objDs.Tables("tblFeedback").Rows(0)
Dim objCFeedback As New CFeedback
objCFeedback.Feedback = objDataRow.Item("strGuestCompanyTI")
objCn.Close()
Return objCFeedback
End Function
My Class
Public Class CFeedback
Private strGuestCodeFB As Integer
Private strFeedBackFB As String
Public Property GuestId() As String
Get
Return strGuestCodeFB
End Get
Set(ByVal value As String)
strGuestCodeFB = value
End Set
End Property
Public Property Feedback() As String
Get
Return strFeedBackFB
End Get
Set(ByVal value As String)
strFeedBackFB = value
End Set
End Property
End Class
So is it possible to have a grdData base on querystring?
The very first thing that you need to do is edit your code behind and add the following two lines at the top:
Option Explicit On
Option Strict On
This will show you at least one error: assigning a type of CFeedback to a type of ArrayList.
You will need to determine what the appropriate resolution to this is, but I suspect that you want to return an ArrayList or generic List from GetFeedback instead of just the one item.
So, among other changes, you will want to change pageload to look something like:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim objCDBFeedback As New CDBFeedback
Dim intGuestID2 As Integer
intGuestID2 = CInt(Request.QueryString("id"))
Dim cValues As System.Collections.Generic.List(Of CFeedback)
cValues = objCDBFeedback.getFeedBack(intGuestID2)
grdResult.DataSource = cValues
grdResult.DataBind()
grdResult.HeaderRow.BackColor = Drawing.Color.AliceBlue
grdResult.RowStyle.BackColor = Drawing.Color.BlanchedAlmond
grdResult.AlternatingRowStyle.BackColor = Drawing.Color.LightSalmon
grdResult.Columns(0).Visible = True
grdResult.Visible = cValues.Count <> 0
End Sub
And the getFeeback method to look something like:
Public Function getFeedBack(ByVal pintGuestID1 As Integer) As System.Collections.Generic.List(Of CFeedback)
Dim cValues As New System.Collections.Generic.List(Of CFeedback)
Using objCn As New MySqlConnection(connectionString)
Using objCmd As New MySqlCommand
Dim strSQL As String = ""
strSQL = "SELECT * FROM tblFeedback WHERE strGuestCodeFB=" & pintGuestID1
objCmd.CommandText = strSQL
objCmd.Connection = objCn
objCn.Open()
Using oReader As MySqlDataReader = objCmd.ExecuteReader
Do While oReader.Read
Dim objCFeedback As New CFeedback
objCFeedback.Feedback = oReader.Item("strGuestCompanyTI")
cValues.Add(objCFeedback)
Loop
End Using
objCn.Close()
End Using
End Using
Return cValues
End Function