0

So I am having trouble connecting to sql server from ubuntu 14.0.4 with dotnetcore 1.1. It is one of those sql instances where it is like ipaddress\nameofinstance where leaving out nameofinstance leads you to a different instance of sql server.

Code:

public void SetStatus(long id, LRStatus status, bool increment = false)
{
    DynamicParameters param = new DynamicParameters();
    param.Add("@id", id);
    param.Add("@status", status == LRStatus.Initial ? null : status.ToString());
    param.Add("@increment", id);
    using (IDbConnection con = new SqlConnection(connectionStr))
    {
        con.Open();
        con.ExecuteScalar<LRStaging>(sql: "usp_LR_SetStatus", param: param, commandType: CommandType.StoredProcedure);
    }
}

Connection string(scrubbed):

Data Source=255.255.255.255\\nameofinstance;User Id=UserName;Password=Password;Initial Catalog=DatabaseOne;MultipleActiveResultSets=True;

Stacktrace:

System.Data.SqlClient.SqlException: 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: TCP Provider, error: 35 - An internal exception was caught) ---> System.AggregateException: One or more errors occurred. (No such device or address) ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: No such device or address
   at System.Net.Dns.HostResolutionEndHelper(IAsyncResult asyncResult)
   at System.Net.Dns.EndGetHostAddresses(IAsyncResult asyncResult)
   at System.Net.Dns.<>c.<GetHostAddressesAsync>b__14_1(IAsyncResult asyncResult)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Data.SqlClient.SNI.SNITCPHandle.<ConnectAsync>d__22.MoveNext()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait(TimeSpan timeout)
   at System.Data.SqlClient.SNI.SNITCPHandle..ctor(String serverName, Int32 port, Int64 timerExpire, Object callbackObject, Boolean parallel)
   --- End of inner exception stack trace ---
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling)
   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.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at Shared.DataLayer.Db.SetStatus(Int64 id, LRStatus status, Boolean increment) in /home/name/Github/sln/Shared/DataLayer/Db.cs:line 41
   at Worker.Automata.Automata.OnTransitionedAction(Transition transition) in /home/name/Github/sln/Worker/Automata/Automata.cs:line 307
   at Stateless.StateMachine`2.InternalFireOne(TTrigger trigger, Object[] args)
   at Stateless.StateMachine`2.InternalFire(TTrigger trigger, Object[] args)
   at Worker.Automata.Automata.Start(LRStaging job) in /home/name/Github/sln/Worker/Automata/Automata.cs:line 95
   at Worker.Program.processJob(Object sender, BasicDeliverEventArgs e) in /home/name/Github/sln/Worker/Program.cs:line 98
ClientConnectionId:00000000-0000-0000-0000-000000000000

Any input is welcome!

Edit: I would like to add that this code executes flawlessly on windows connecting to ipaddress\nameofinstance.

Edit 2: I decided to try and connect to the db using another language and it was a success.

Here is the code I used to establish a connection and to execute a procedure(Golang for the win).

package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/denisenkom/go-mssqldb"
)

func main() {
    connString := fmt.Sprintf("server=%s;user id=%s;password=%s;database=%s", "255.255.255.255\\instance", "user", "password", "database")
    fmt.Printf(" connString:%s\n", connString)
    db, err := sql.Open("mssql", connString)
    if err != nil {
        log.Print("Open error")
        log.Print(err.Error())
    }
    defer db.Close()
    perr := db.Ping()
    if perr == nil {
        log.Print("No error")
    } else {
        log.Print("Ping error")
        log.Print(perr.Error())
    }

    rows, err := db.Query("using IQDataOps; exec usp_GetMachineKeyValue ?, ?", "Machine1", "key")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()
    var Value string
    for rows.Next() {
        err := rows.Scan(&Value)
        if err != nil {
            log.Fatal(err)
        }
        log.Println(Value)
    }
    log.Print("Complete")
}
BillHaggerty
  • 6,157
  • 10
  • 35
  • 68
  • Did you try pinging the SQL server from Ubunutu or try telnet to the SQL port from ubunutu? Also to test the username/pwd you can try and connect to sql instance from ubunutu using some SQL tools. If any of those doesn't work then you have to configure either your firewall or sql correctly. – Nachi Jun 21 '17 at 17:27
  • I can ping the ip address, but not the whole path. Is that normal? Ill try telneting it. fyi, I can also connect to the instance at the ip just not ip\\otherinstance. – BillHaggerty Jun 21 '17 at 17:32
  • Failed: telnet 255.255.255.255/instancename:1443 telnet: could not resolve 255.255.255.255/instancename:1443/telnet: Name or service not known – BillHaggerty Jun 21 '17 at 17:38
  • Looks like your ping is working, I don't think you can telnet to an instance. So telnet with instance name is not going to work. Try this [post](http://www.sqlservercentral.com/blogs/brian_kelley/2011/03/10/sql-server-connectivity-issues-with-named-instances/) as well. – Nachi Jun 21 '17 at 17:41
  • How do I find out what port a named instance is listening too. Doesn't seem to be a way to figure it out from ssms while connected. – BillHaggerty Jun 21 '17 at 17:53
  • You need to use the Configuration manager to enable client connections...which is an MMC snapin. See: https://learn.microsoft.com/en-us/sql/relational-databases/sql-server-configuration-manager – Clay Jun 22 '17 at 14:03
  • I am able to connect to the database using the same code on windows. Do you manage client connection permissions by os? – BillHaggerty Jun 22 '17 at 14:44
  • @Theyouthis have you solved this problem? I'm running into the same issue as well, only everything is on Windows and on the same dev machine. – trailmax Aug 21 '18 at 12:15
  • @trailmax I think updating my version of dotnet core solved this issue for me. If that doesn't work for you then I'm at a loss... – BillHaggerty Aug 21 '18 at 13:35
  • @Theyouthis OK, can't update any further, the project is a few days old with everything latest. Thanks for replying anyway. – trailmax Aug 21 '18 at 14:09
  • @trailmax I noticed that I got a whole bunch of updates for my dotnet core run time and sdk this morning. There are probably updates available to you, but I am doubtful that it will help if everything is that recent. – BillHaggerty Aug 21 '18 at 16:37

0 Answers0