I have changed my application to another server and got the following error when I try to register something into the database
Server Error in '/' Application. 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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: 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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Blockquote
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SqlException (0x80131904): 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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)]
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager) +1431
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +1085
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +70
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +964
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +109
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1529
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +156 System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource
1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +258
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) +312 System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource
1 retry) +202
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry) +413 System.Data.SqlClient.SqlConnection.Open() +128 System.Data.Entity.Infrastructure.Interception.InternalDispatcher
1.Dispatch(TTarget target, Action2 operation, TInterceptionContext interceptionContext, Action
3 executing, Action3 executed) +104 System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext) +503 System.Data.Entity.SqlServer.<>c__DisplayClass33.<UsingConnection>b__32() +560 System.Data.Entity.SqlServer.<>c__DisplayClass1.<Execute>b__0() +18 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func
1 operation) +234
System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action1 act) +927 System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable
1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript) +124
System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection) +221 System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection) +125 System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +156 System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) +116 System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func
3 createMigrator, ObjectContext objectContext) +124
System.Data.Entity.Database.Create(DatabaseExistenceState existenceState) +292
System.Data.Entity.CreateDatabaseIfNotExists1.InitializeDatabase(TContext context) +187 System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +75 System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +482 System.Data.Entity.Internal.RetryAction
1.PerformAction(TInput input) +177
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action) +289 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +20 System.Data.Entity.Internal.Linq.InternalSet
1.Initialize() +69
System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext() +21 System.Data.Entity.Infrastructure.DbQuery
1.System.Linq.IQueryable.get_Provider() +59
System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable1 source, Expression
1 predicate, CancellationToken cancellationToken) +206
System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable1 source, Expression
1 predicate) +172
Microsoft.AspNet.Identity.EntityFramework.d__67.MoveNext() +469
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60
Microsoft.AspNet.Identity.CultureAwaiter1.GetResult() +43 Microsoft.AspNet.Identity.<ValidateUserName>d__14.MoveNext() +648 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60 Microsoft.AspNet.Identity.<ValidateAsync>d__13.MoveNext() +339 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60 Microsoft.AspNet.Identity.<CreateAsync>d__73.MoveNext() +525 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60 Microsoft.AspNet.Identity.<CreateAsync>d__79.MoveNext() +662 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60 ListaDosAmigosDosAnimais.Controllers.<Register>d__17.MoveNext() in C:\Users\DFX_M\Documents\ListaDosAmigosDosAnimais\ListaDosAmigosDosAnimais\Controllers\AccountController.cs:292 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60 System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +92 System.Web.Mvc.Async.<>c__DisplayClass8_0.<BeginInvokeAsynchronousActionMethod>b__1(IAsyncResult asyncResult) +22 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +42 System.Web.Mvc.Async.<>c__DisplayClass11_0.<InvokeActionMethodFilterAsynchronouslyRecursive>b__0() +80 System.Web.Mvc.Async.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +387 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +42 System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__4() +50 System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult) +188 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38 System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +26 System.Web.Mvc.Async.WrappedAsyncVoid
1.CallEndDelegate(IAsyncResult asyncResult) +68
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +39 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38 System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +40 System.Web.Mvc.Async.WrappedAsyncVoid
1.CallEndDelegate(IAsyncResult asyncResult) +68
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +602
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +195
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +128
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3535.0
Blockquote
Could someone please take an interest in this particular problem.
I will add more information if needed.
My code is the following:
enter code here
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(NovoRegistoModel novoRegisto)
{
tblUtilizador utilizador = new tblUtilizador();
List<tblListaDeServicos> lstServicos = db.tblListaDeServicos.ToList();
utilizador.ServicosCollection = lstServicos;
novoRegisto.tblUtilizador.ServicosCollection = utilizador.ServicosCollection;
List<tblLocaisDeActuacao> lstLocais = db.tblLocaisDeActuacao.ToList();
utilizador.LocaisCollection = lstLocais;
novoRegisto.tblUtilizador.LocaisCollection = utilizador.LocaisCollection;
var errors = ModelState.Values.SelectMany(v => v.Errors);
var result = IdentityResult.Success;
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = novoRegisto.registerViewModel.Email, Email = novoRegisto.registerViewModel.Email };
var Email = db.tblUtilizador.Where(x => x.Email == novoRegisto.registerViewModel.Email).FirstOrDefault();
if (Email != null)
{
ModelState.AddModelError("", "Este utilizador já se encontra registado");
return View(novoRegisto);
}
else
{
if (novoRegisto.tblUtilizador.PoliticaPrivacidade == false || novoRegisto.tblUtilizador.TermosCondicoes == false)
{
if (novoRegisto.tblUtilizador.PoliticaPrivacidade == false)
{
ModelState.AddModelError("tblUtilizador.PoliticaPrivacidade", "É necessário que aceite a Política de Privacidade!");
}
if (novoRegisto.tblUtilizador.TermosCondicoes == false)
{
ModelState.AddModelError("tblUtilizador.TermosCondicoes", "É necessário que aceite os Termos e Condições de Utilização!");
}
return View("Register", novoRegisto);
}
///////////////////////////////////////////////////////////////////////////////////////Validação dos Arrays dos Locais e dos Serviços/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////Verifica se existe alguma coisa nos arrays, Caso exista junta-lhe uma "," Torna possível colocar vários Locais e Serviços num único campo da base de dados/////////////////////////////////////////////////////////////////
if (novoRegisto.tblUtilizador.SelectedLocalArray != null)
{
novoRegisto.tblUtilizador.LocalSelecionado = string.Join(",", novoRegisto.tblUtilizador.SelectedLocalArray);
}
if (novoRegisto.tblUtilizador.SelectedServicoArray != null)
{
novoRegisto.tblUtilizador.ServicoSelecionado = string.Join(",", novoRegisto.tblUtilizador.SelectedServicoArray);
}
//////////////////////////////////////////////////////////////////////////////////////Verifica se foram inseridos Serviços e Locais/////////////////////////////////////////////////////////////////////////////////////////////////////
if (novoRegisto.tblUtilizador.LocalSelecionado == null || novoRegisto.tblUtilizador.ServicoSelecionado == null)
{
if (novoRegisto.tblUtilizador.LocalSelecionado == null)
{
ModelState.AddModelError("tblUtilizador.LocalSelecionado", "Selecione pelo menos um Local!");
}
if (novoRegisto.tblUtilizador.ServicoSelecionado == null)
{
ModelState.AddModelError("tblUtilizador.ServicoSelecionado", "Selecione pelo menos um Serviço!");
}
return View ("Register", novoRegisto);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////Validação da Fotografia////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////Verifica se foi inserida uma fotografica, Caso seja inserida é convertida para stringBase64 e guardada na base de dados, Senão é colocada a fotografia predefinida que se encontra na pasta Media///////////////////////
HttpPostedFileBase file = Request.Files[0];
if (file != null && !file.ContentLength.Equals(0))
{
byte[] convertParaByte = ConvertToBytes(file);
string convertbytesFotografiaParaStringBase64 = Convert.ToBase64String(convertParaByte);
novoRegisto.tblUtilizador.Fotografia = convertbytesFotografiaParaStringBase64;
}
else
{
string path = AppDomain.CurrentDomain.BaseDirectory + @"\Media\empty-avatar.png";
using (Image image = Image.FromFile(path))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string imagemPredefinida = Convert.ToBase64String(imageBytes);
novoRegisto.tblUtilizador.Fotografia = imagemPredefinida;
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
novoRegisto.tblUtilizador.DataDeRegisto = DateTime.Now;
novoRegisto.tblUtilizador.Disponibilidade = false;
novoRegisto.tblUtilizador.ID = user.Id;
novoRegisto.tblUtilizador.Email = novoRegisto.registerViewModel.Email;
novoRegisto.tblUtilizador.Password = novoRegisto.registerViewModel.Password;
novoRegisto.tblUtilizador.Bloqueado = false;
db.tblUtilizador.Add(novoRegisto.tblUtilizador);
db.SaveChanges();
result = await UserManager.CreateAsync(user, novoRegisto.registerViewModel.Password);
}
if (result.Succeeded)
{
//await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Confirmação de Registo", "Seja bem-vindo à Lista dos Amigos dos Animais!" + "<br />" + "<br />" + "Clique no link abaixo para confirmar o seu registo!" + "<br />" + "<br />" + "<a href=\"" + callbackUrl + "\">Confirmo o meu registo!</a>");
//return RedirectToAction("RegisterConfirmation", "Account");
return View("RegisterConfirmation");
}
else
{
var erros = result.Errors;
var message = string.Join(", ", erros);
ModelState.AddModelError("", message);
//ModelState.AddModelError("", "Registo inválido, contacte o suporte!");
return View("Register", novoRegisto);
}
}
// If we got this far, something failed, redisplay form
return View("Register",novoRegisto);
}
When it reaches the following position:
enter code here
db.tblUtilizador.Add(novoRegisto.tblUtilizador); db.SaveChanges(); result = await UserManager.CreateAsync(user, novoRegisto.registerViewModel.Password);
It says that the email is already taken and the username is already taken like shown in the picture below.
User contributions licensed under CC BY-SA 3.0