Monday, March 26, 2012

Easy Question: Handling Login Exceptions

I have some very simple code that connects to an SQL Server instance using the SMO Server object. I have everything working fine, but I would like to be able to know if the login failed and respond to the error. Does anyone have a snippet that will do this? Do have to catch an exception or handle an event or....

Thanks!

This is how I connect in SMO (VB.Net):

' Connect to the server

Dim srvMgmtServer As Server

srvMgmtServer = New Server("MyServer\MyInstance")

Dim srvConn As ServerConnection

srvConn = srvMgmtServer.ConnectionContext

srvConn.LoginSecure = True

Hope that helps.

|||Ok, that is fine, but what if "MyServer\MyInstance" doesn't exist, or the user supplies invalid credentials? I want to be able to tell the user the login failed and why. There must be an exception thrown somewhere, but I can’t find a simple way to handle an invalid login. Right now I am opening the connection to the server right after I create the instance, and then catching any exceptions, but this seems like a bit of a hack. There has to be a way to do something like this:

try
{

srvMgmtServer = New Server("MyServer\MyInstance")

}
catch(SomeException)
{

//Do Stuff Because The Login Failed

}
|||

Yes, I'm sorry. The method of handling the exception is exactly what you've shown. If you catch(ex), then you can scroll through the InnerException property until you get to the base level. When I just catch the error at the top level the Message property contains ""Failed to connect to server MyServer\MyInstance."

In VB.Net the code looks something like this:

Catch ex As Exception
Console.WriteLine("There has been a VB error. " + ex.Message)
Do While ex.InnerException IsNot (Nothing)
Console.WriteLine(ex.InnerException.Message)
ex = ex.InnerException
Loop
End Try

Hope that helps.

No comments:

Post a Comment