Error when I add connection string in a UserControl - vb.net

I am facing a weird problem, I am trying to create Usercontrol (Add_companies)and add it to panel
Everything work fine but when I add the connection to the user control I face this error :
The variable 'Add_companies1' is either undeclared or was never assigned.
And this is my connection:
Protected configuracion As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("Conn")
Dim Conn As New SqlConnection(configuracion.ConnectionString)
Public Cmd As SqlCommand
Error one image
where the error code must be
and when i go to the code line error there's nothing.

Protected configuracion As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("Conn")
Dim Conn As New SqlConnection(configuracion.ConnectionString)
Public Cmd As SqlCommand
You indicate that you placed this code in your UserControl and now the Form designer is throwing errors. The VS IDE is loading and running an instance of the usercontrol when it is placed on the design surface.
These three lines of code would have to be placed at the class level to support the Protected and Public access modifiers. The issue is that the designer is not able to retrieve ConfigurationManager.ConnectionStrings("Conn") so configuracion is null when it is used in Dim Conn As New SqlConnection(configuracion.ConnectionString).
When you use the syntax: Dim var as New Something() at the class level, the compiler converts that to Dim var as Something and places var = New Something() into the class constructor (Sub New) code.
To fix this problem you need to prevent code that will throw an error while in design mode from executing. All controls have a Boolean property named DesignMode for this purpose. Note that DesignMode will not be valid if used in the constructor code, so trying to use it there will fail.
Imports System.Configuration
Imports System.Data.SqlClient
Public Class Add_companies
Protected configuracion As ConnectionStringSettings
Private Conn As SqlConnection
Public Cmd As SqlCommand
Private Sub Add_companies_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If Not Me.DesignMode Then
configuracion = ConfigurationManager.ConnectionStrings("Conn")
Conn = New SqlConnection(configuracion.ConnectionString)
End If
End Sub
End Class

Related

Error in SQL Connection String: Type is not defined

I'm using Visual Studio 2008 and I wrote this code:
Public sqlConn As New SqlConnection
Dim SQLConn As SqlConnection
'on form load
Sub FMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sqlConn.ConnectionString = "Data Source=...."
Upon executing it, I recieve this error:
Error 1 Type 'SqlConnection' is not defined.
What exactly is the problem here?
Your title says that there's an error in a connection string but that error has nothing to do with connection strings. The SqlConnection class is a member of the System.Data.SqlClient namespace. If you don't qualify the type name in code then you have to import the namespace. As the System.Data namespace is imported by default, you can refer to it in code like this:
Public sqlConn As New SqlClient.SqlConnection
You can also import the namespace at the file level by adding this line at the top of the file:
Imports System.Data.SqlClient
My preferred option for this namespace though, would be to import it at the project level. That's because it's a namespace whose members you will tend to use in multiple files. You can work with project-level imports on the bottom half of the References page in the project properties.

'Sub Main' was not found. Service management console application error?

There is possibly a few things wrong with the below. Haven't had a chance to test/debug the code yet as can't run it. It stating that no main method has been found. But there is? i've even changed it to shared etc. It's probably something obvious?
It's flagging - 'Sub Main' was not found in 'ConsoleApplication1.Module1' error.
Also the main method wasn't always a separate class, I was just trying stuff. I'm importing a reference - system.processes. Was initially created as a vb.form but realised i didn't want the form part and recreated as a console app (which is very possibly where the problem lies as it's one of the first console apps i've done).
Code is basically planned to act on a service dying. Report and try and manage the restart (not finished, ideas welcome).
Imports System
Imports System.Management
Imports System.ServiceProcess
Imports System.Diagnostics
Imports System.Threading
Imports System.IO
Module Module1
Public Class Control
Public Sub Main() 'Public Sub Main(ByVal sArgs() As String)
Dim restart As New Rest
restart.startTime = DateTime.Now()
restart.cr20Services()
restart.Report()
End Sub
End Class
Public Class Rest
public startTime As String
Dim logPath As String = "C:\cr20\restart.txt"
'Dim fileExists As Boolean = File.Exists(strFile)
Dim arrcr20ServicesInitialStatus As New ArrayList
Dim failedServices As New ArrayList
Dim arrcr20Services As New ArrayList
Public Sub cr20Services()
'cr20 Services
arrcr20Services.Add("cr20 service")
arrcr20Services.Add("cr20 router")
For Each cr20Service In arrcr20Services
arrcr20ServicesInitialStatus.Add(cr20Service & " - " & cr20Status(cr20Service))
cr20Restore(cr20Service)
Next
End Sub
Private Function cr20Status(ByVal cr20Service As String)
Dim service As ServiceController = New ServiceController(cr20Service)
Return service.Status.ToString
End Function
Private Sub cr20Restore(ByVal cr20Service As String)
Dim service As ServiceController = New ServiceController(cr20Service)
'Dim p() As System.Diagnostics.Process = System.Diagnostics.Process.GetProcessesByName("calc")
If (service.Status.Equals(ServiceControllerStatus.Stopped)) Or (service.Status.Equals(ServiceControllerStatus.StopPending)) Then
failedServices.Add(service)
service.Stop()
Thread.Sleep(10000) 'give service 10 seconds to stop
service.Start()
End If
End Sub

Error with DotNetOpenAuth2 with VB.Net

My new project demands the implementation OpenAuth. Following is my code.
The line
scopes.Add(CalendarService.Scopes.Calendar.GetStringValue())
in the GetAuthorization gives the following error.
Overload resolution failed because no accessible...
GetStringValue is the most specific for these argument. I can understand that GetStringValue is not the method/argument found in the calendarservice.scopes.calendar but my question is why so? I have downloaded this code from some website and most website is giving example in C# but there are hardly any site that is showing any example in VB.Net. Can anyone help me here.
Regards
P.S. I am using Visual Studio 2008.
Imports System
Imports System.Diagnostics
Imports DotNetOpenAuth.OAuth2
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Calendar.v3
Imports Google.Apis.Util
Imports Google.Apis.Calendar.v3.Data
Imports Google.Apis.Tasks.v1
Imports Google.Apis.Tasks.v1.Data
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim provider = New NativeApplicationClient(GoogleAuthenticationServer.Description)
provider.ClientIdentifier = "Client ID Here"
provider.ClientSecret = "Client Secret Here"
Dim auth = New OAuth2Authenticator(Of NativeApplicationClient)(provider, AddressOf GetAuthorization)
Dim service = New CalendarService(auth)
Dim first = service.CalendarList.List.Fetch().Items().First()
Label1.Text = first.Summary
End Sub
Private Function GetAuthorization(ByVal arg As NativeApplicationClient) As IAuthorizationState
Dim scopes As New System.Collections.Generic.List(Of String)
scopes.Add(CalendarService.Scopes.Calendar.GetStringValue())
Dim state As IAuthorizationState = New AuthorizationState(scopes)
state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
Dim authUri As Uri = arg.RequestUserAuthorization(state)
Process.Start(authUri.ToString())
' Open a modal dialogue for user to paste the authorization code from Browser = authCode
Dim authCode As String = Console.ReadLine()
Return arg.ProcessUserAuthorization(authCode, state)
End Function
End Class
GetStringValue is en extension method defined on Google.Apis.Util.Utilities.
Similar VB.NET code to this worked for me on VS2012 with the latest version of the library.
You can find my VB.NET sample in https://codereview.appspot.com/7007048/, but it still wasn't approved, so be careful using it.
In the samples repository (http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FDiscovery.VB.ListAPIs), there is currently only one VB.NET sample, but hopefully the sample above will be approved soon and it will be added to the repository.
Please elaborate more on the references that you have in your project and the stack trace.
It looks like there is another overloading to this GetStringValue somewhere else (http://msdn.microsoft.com/en-us/library/2hx4ayzs(v=vs.80).aspx) in your code or in a reference assembly.

RenderControl for radiobuttonlist using class not working vb.net

I built a simple class
Imports Microsoft.VisualBasic
Imports System.IO
Public Class buildcntrl
Function buildcontrol() As String
Dim SB As New StringBuilder()
Dim SW As New StringWriter(SB)
Dim o As New HtmlTextWriter(SW)
Dim d As New RadioButtonList
d.Items.Add("True")
d.Items.Add("False")
d.RenderControl(o)
Return SB.ToString()
End Function
End Class
When I use the class from an asp.net page like this
Dim t As New buildcntrl
Response.Write(t.buildcontrol)
it works fine but when use a class to call the same class I receive an error
System.NullReferenceException: Object reference not set to an instance of an object. at System.Web.UI.WebControls.RadioButtonList.Render(HtmlTextWriter writer)
When I debugged the problem it throws an error when trying to execute d.RenderControl(o)
This works fine for all the other objects except for RadioButtonList

Error with the Using Statement and Lazy Initialized Property

The code below will throw an InvalidOperationException: The ConnectionString property has not been initialized. The exception is thrown at the line calling Connection.Open() in the Load method. If I use the try-finally statement instead of the using statement, everything works correctly. Can anyone explain why the exception occurs with the using statement?
Public Class SomeEntity
Private _Connection As SqlClient.SqlConnection
Private _ConnectionString As String
Protected ReadOnly Property Connection() As SqlClient.SqlConnection
Get
If _Connection Is Nothing Then
_Connection = New SqlClient.SqlConnection(_ConnectionString)
End If
Return _Connection
End Get
End Property
Public Sub New(ByVal connectionString As String)
_ConnectionString = connectionString
End Sub
Public Sub Load(ByVal key As Integer)
Using Connection
Connection.Open()
...
End Using
End Sub
End Class
You failed to mention a key piece of information: It succeeds the first time Load() is called, but then fails forever after.
When using Using, Dispose() is called on the used variable when the Using block exits. So in your scenario:
Load() gets called
The Using statement calls the Connection property's Get
_Connection gets set to a new SqlConnection and returned
The returned connection gets opened and used normally
The Using block exits, calling Dispose() on the connection
At this point, the SqlConnection object still exists, and is still pointed to by _Connection. It's no longer in a usable state though, since it's been Dispose()d. When the second call to Load() comes in:
Load() gets called
The Using statement calls the Connection property's Get
_Connection is still pointing to a (useless) SqlConnection object, therefore it's not Nothing, and doesn't get set to a new SqlConnection object
The (useless) connection gets returned
Open() gets called on the connection--which is in an unusable state--and triggers the InvalidOperationException
You're mixing conflicting approaches to connection management. Keeping the connection object around as a member of the class implies that you want to keep the connection alive for the life of the SomeEntity object, but using Using implies that you want to create and destroy the connection on the fly with each usage.
Connection in your Using statement is not being initialized or declared. Your code should read more like:
Public Sub Load(ByVal key As Integer)
Using myConnection as SqlClient.SqlConnection = Me.Connection
Connection.Open()
...
End Using
End Sub