SQLserver SMO Access is denied to Server

I am Sysadmin on this sql server , but when i run this code

Capture11.PNG
i am getting , this error

Microsoft.SqlServer.Management.Common.ConnectionFailureException was unhandled
  HResult=-2146233087
  Message=Failed to connect to server MyServer.
  Source=Microsoft.SqlServer.ConnectionInfo
  StackTrace:
       at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()
       at Microsoft.SqlServer.Management.Common.ConnectionManager.PoolConnect()
       at Microsoft.SqlServer.Management.Common.ConnectionManager.get_ServerVersion()
       at Microsoft.SqlServer.Management.Smo.ExecutionManager.GetServerVersion()
       at Microsoft.SqlServer.Management.Smo.SqlSmoObject.get_ServerVersion()
       at Microsoft.SqlServer.Management.Smo.Information.get_Version()
       at PermSysSrv.Program.Main(String[] args) in \\some_dir\Program.cs:line 24
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.Data.SqlClient.SqlException
       HResult=-2146232060
       Message=A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
       Source=.Net SqlClient Data Provider
       ErrorCode=-2146232060
       Class=20
       LineNumber=0
       Number=5
       Server=""
       State=0
       StackTrace:
            at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
            at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
            at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover)
            at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
            at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
            at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
            at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData)
            at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
            at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
            at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
            at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
            at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
            at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
            at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
            at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
            at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
            at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
            at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
            at System.Data.SqlClient.SqlConnection.Open()
            at Microsoft.SqlServer.Management.Common.ConnectionManager.InternalConnect(WindowsIdentity impersonatedIdentity)
            at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()
       InnerException: System.ComponentModel.Win32Exception
            HResult=-2147467259
            Message=Access is denied
            ErrorCode=-2147467259
            NativeErrorCode=5
            InnerException:

why???
center1010Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Lokesh B RDeveloperCommented:
Hi,

Make sure you have permissions to connect to MyServer using your windows authentication.

If you don't have the permissions then you get the Error as you mentioned.

https://msdn.microsoft.com/en-in/library/ms162132.aspx
0
center1010Author Commented:
I have permissions to connect to MyServer using your windows authentication, i connect with SSMS to the same server using  my  windows user.
0
Lokesh B RDeveloperCommented:
Hi,

Please make sure the server name is correct.

Working Example:

static void Main(string[] args)
        {
            try
            {
                Server srv;
                srv = new Server(@"MyName\SQLEXPRESS");
                Console.WriteLine(srv.Information.Version);
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }

Open in new window

0
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

center1010Author Commented:
sorry,

 my not working, same error

what more could be the problem?
0
Vitor MontalvãoMSSQL Senior EngineerCommented:
I'm a SQL Server guy but I think you're missing the connection string:
using System.Data.SqlClient;

SqlConnection myConnection = new SqlConnection("server=servername;Trusted_Connection=yes;database=database");

myConnection.Open();

Open in new window

0
Lokesh B RDeveloperCommented:
Hi,

try this

static void Main(string[] args)
        {
            try
            {
                Microsoft.SqlServer.Management.Common.ServerConnection serverConnection = new Microsoft.SqlServer.Management.Common.ServerConnection();
                serverConnection.LoginSecure = true;
                
                serverConnection.ServerInstance = "Your Instance Name";
                Server server = new Server(serverConnection);

                Server srv = new Server(serverConnection);
                if (server != null)
                {
                    Console.WriteLine(srv.Information.Version);
                }
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }

Open in new window

0
center1010Author Commented:
Solved,  the problem was on the IDE,  the project directory was on the net  with limited access, i relocate it to local
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
center1010Author Commented:
it works
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.