I have deployed this MVC app on my localhost(on my machine running windows 8) and it runs as expected. The only difference between my installation folder and the one which is on the server, is the connection string. But when I try to deploy it on the server machine(Windows Server 2008) I get this strange error :
[NullReferenceException: Object reference not set to an instance of an object.]
PicknikMVC.ViewModels.ApplicationViewModel..ctor(Application app) in c:\Builds\workspace\Picknik\AppStoreService\target\checkout\AppStoreService\PicknikMVC\ViewModels\Application\ApplicationViewModel.cs:23
PicknikMVC.Controllers.Application.ShowController.Execute(String appid) in c:\Builds\workspace\Picknik\AppStoreService\target\checkout\AppStoreService\PicknikMVC\Controllers\Application\ShowController.cs:59
lambda_method(Closure , ControllerBase , Object[] ) +126
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters)+247
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +38
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +119
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +452
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +31
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +230
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
The code in the app where this happens is basically instantiating a new object of particular class with some information from the database. Do you see any obvious problem? Could it be a problem with the connection string or it is something else?
AppViewModel:
public class ApplicationViewModel
{
public int App_ID { get; set; }
public string Title { get; set; }
public string Developer { get; set; }
public string DeveloperURL { get; set; }
public bool IsImportant { get; set; }
public IEnumerable<ScreenshotPairViewModel> Screenshots { get; set; }
public ApplicationViewModel(PicknikData.Application app)
{
App_ID = app.App_ID;
Title = app.Title;
Developer = app.Developer;
DeveloperURL = app.DeveloperURL;
if (app.IsImportant.HasValue)
{
IsImportant = app.IsImportant.Value;
}
Screenshots = app.ScreenshotURLs.Select(p => new ScreenshotPairViewModel(p.Screenshot_URL,p.FK_Device)).ToList();
}
}
and the code for the controller:
viewModel.Application = new ApplicationViewModel(app);
It is hard to tell from the info provided, but I'll have a bash at helping.
If the connection string is different, I assume the data might be too.
When you see object not set, it is usually something not instantiated in the code. In this case though, it could be the data. Assuming everything is instantiated somewhere, it is possible there are no ScreenshotURLs? The error message details a lambda error, so I assume the it relates to the select statement.
Related
I'm running into following error after i've deploid my website in IIS and try to view the page in the browser.
Could not load type 'DienstbulletinApp.DienstbulletinContext' from
assembly 'DienstbulletinApp'. 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.TypeLoadException: Could not load type
'DienstbulletinApp.DienstbulletinContext' from assembly
'DienstbulletinApp'.
When i run my application in visual studio 2019, i don't have this error.
I have removed the contexts from my webconfig file but nothing seems to be the sollution
<contexts>
<context type="DienstbulletinApp.DAL.DienstbulletinAppContext, DienstbulletinApp, Version=1.0.0.0, Culture=neutral">
<databaseInitializer type="DienstbulletinApp.DAL.DienstbulletinAppInitializer, DienstbulletinApp, Version=1.0.0.0, Culture=neutral" />
</context>
</contexts>
DienstbulletinContext:
public class DienstbulletinAppContext : DbContext
{
public DienstbulletinAppContext() : base("name=DienstbulletinDBConnectionString")
{
Database.SetInitializer(new DienstbulletinAppInitializer());
}
public DbSet<Dienstbulletin> Dienstbulletins { get; set; }
public DbSet<Voertuig> Voertuigen { get; set; }
public DbSet<Opdracht> Opdrachts { get; set; }
public DbSet<DienstbulletinDetail> DienstbulletinDetails { get; set; }
public DbSet<Locatie> Locaties { get; set; }
public DbSet<Gebruiker> Gebruikers { get; set; }
public DbSet<Persoon> Personen { get; set; }
public DbSet<OpdrachtType> OpdrachtTypes { get; set; }
public DbSet<Aandachtspunt> Aandachtspunten { get; set; }
public DbSet<Gsm> Gsms { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Persoon>().ToTable("t_Persoon");
modelBuilder.Entity<Voertuig>().ToTable("t_Voertuig");
modelBuilder.Entity<Gebruiker>().ToTable("t_Gebruiker");
modelBuilder.Entity<OpdrachtType>().ToTable("t_OpdrachtType");
modelBuilder.Entity<Opdracht>().ToTable("t_Opdracht");
modelBuilder.Entity<Dienstbulletin>().ToTable("t_Dienstbulletin");
modelBuilder.Entity<DienstbulletinDetail>().ToTable("t_DienstbulletinDetail");
modelBuilder.Entity<Locatie>().ToTable("t_Locatie");
modelBuilder.Entity<Aandachtspunt>().ToTable("t_Aandachtspunt");
modelBuilder.Entity<Gsm>().ToTable("t_Gsm");
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
}
I'm using .Net Framework version 4.0.30319 and ASP.NET 4.7.3535.0
I know that all DLL must be referenced in the solution but the files where i get an error are my own classes of my application.
here's the full error:
[TypeLoadException: Could not load type 'DienstbulletinApp.DienstbulletinAppContext' from assembly 'DienstbulletinApp'.]
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type) +0
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName) +95
System.Type.GetType(String typeName, Boolean throwOnError) +63
System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type requiredContextType, String contextTypeName, String initializerTypeName, Boolean isDisabled, Func1 initializerArgs, Func3 exceptionMessage) +46
[InvalidOperationException: Failed to set database initializer of type 'DienstbulletinApp.DienstbulletinAppInitializer, DienstbulletinApp' for DbContext type 'DienstbulletinApp.DienstbulletinAppContext, DienstbulletinApp' specified in the application configuration. Entries should be of the form 'key="DatabaseInitializerForType MyNamespace.MyDbContextClass, MyAssembly" value="MyNamespace.MyInitializerClass, MyAssembly"' or 'key="DatabaseInitializerForType MyNamespace.MyDbContextClass, MyAssembly" value="Disabled"'. Also verify that 'DatabaseInitializerArgumentForType' entries are present for every parameter of the database initializer constructor. See inner exception for details. Consider using the configuration section to set the database initializer (http://go.microsoft.com/fwlink/?LinkID=237468).]
System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type requiredContextType, String contextTypeName, String initializerTypeName, Boolean isDisabled, Func1 initializerArgs, Func3 exceptionMessage) +327
System.Data.Entity.Internal.InitializerConfig.TryGetInitializerFromLegacyConfig(Type contextType) +644
System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type contextType) +39
System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetServiceFactory(Type type, String name) +513
System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory) +87
System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetService(Type type, Object key) +187
System.Linq.WhereSelectArrayIterator2.MoveNext() +78
System.Linq.Enumerable.FirstOrDefault(IEnumerable1 source, Func2 predicate) +115
System.Data.Entity.Infrastructure.DependencyResolution.CompositeResolver2.GetService(Type type, Object key) +41
System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +159
System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input) +171
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action) +269
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +20
System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +69
System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext() +21
System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider() +59
System.Linq.Queryable.FirstOrDefault(IQueryable1 source, Expression1 predicate) +61
DienstbulletinApp.Controllers.GebruikerController.Login() in D:\Plastic\Dienstbulletin\Dienstbulletin\Controllers\GebruikerController.cs:24
lambda_method(Closure , ControllerBase , Object[] ) +87
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +35
System.Web.Mvc.Async.<>c.b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +39
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +70
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.WrappedAsyncVoid1.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.WrappedAsyncVoid1.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
Found the error removing the version and culture=neutral from contexts solved the issue:
<contexts>
<context type="DienstbulletinApp.DAL.DienstbulletinAppContext, DienstbulletinApp">
<databaseInitializer type="DienstbulletinApp.DAL.DienstbulletinAppInitializer, DienstbulletinApp" />
</context>
</contexts>
Note as of 9/16/2019 at 3:30 EDT
I have disabled the parts of my app that use the SQL Server DB so my site would not crash. Just as info, in case anyone access my site and can't reproduce the error.
I have read most if not all of the similar threads to no avail. My site uses BOTH MySQL and SQLserver. Everything works fine on my PC [localhost]. I issued the code for the first time this weekend, and have run into this problem with the published code on my hosting site. I am able to access the MySQL DB just fine, but when I try and access the SQLServer, I get the error -- Keyword not supported: 'data source HOST.com;initial catalog'.
Web.config
<connectionStrings>
<add name='DefaultConnection' providerName='System.Data.SqlClient' connectionString='Data Source=[HOST Server];Initial Catalog=aspnet-Lat34North-20190423140228;Integrated Security=SSPI' />
<add name='Lat34NorthContext' providerName='System.Data.SqlClient' connectionString='Data Source=[HOST Server];Initial Catalog=Lat34North;Integrated Security=False;User Id=[user id 1]; Password=[password 1]' />
<!-- Production -->
<add name="CitiesContext" connectionString="Data Source=[HOST Server]; Database=Lat34CitiesSQL; uid=[user id 2]; pwd=[password 2];" providerName="MySql.Data.MySqlClient" />
DAL
using Lat34North.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace Lat34North.DAL
{
public class Lat34NorthContext : DbContext
{
public DbSet<Photo> Photo { get; set; }
public DbSet<MarkersPrevNext> MarkersPrevNext { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Photo>().Property(p => p.PhotoFile).HasColumnType("image");
modelBuilder.Entity<MarkersPrevNext>().HasKey(t => new { t.StateCounty, t.Sequence });
}
}
}
Controller
using System;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using System.Data.Entity.Spatial;
using Lat34North.DAL;
using Lat34North.Models;
namespace Lat34North.Controllers
{
public class HistoricMarkersALController : BaseController
{
private ALMarkersContext db = new ALMarkersContext();
private Lat34NorthContext db2 = new Lat34NorthContext();
---- skip ahead --
int CurrentCount = CountPrevNext(PrevNextLocation, "M"); // Count number if records created today
if (CurrentCount == 0)
{
var temps = db.ALHistoricMarkers.Where(t => t.County == county_name).OrderBy(t => t.Title).ToList();
string dateCreated = DateTime.Now.ToString("yyyy-MM-dd");
int i = 0;
foreach (var temp in temps)
{
db2.MarkersPrevNext.Add(new MarkersPrevNext() ***<--Error here***
{
StateCounty = PrevNextLocation,
Sequence = i,
Type = "M", // Type M - marker
MarkerKey = temp.MarkerKey,
CraetedDate = dateCreated
});
i++;
}
db2.SaveChanges();
}
return View(vModel);
}
Error
Server Error in '/' Application.
________________________________________
Keyword not supported: 'data source HOST.com;initial catalog'.
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.ArgumentException: Keyword not supported: 'data source HOST.com;initial catalog'.
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:
[ArgumentException: Keyword not supported: 'data source {Server name.com];initial catalog'.]
System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) +418
System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) +99
System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +59
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +25
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +166
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) +57
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +148
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<SetConnectionString>b__18(DbConnection t, DbConnectionPropertyInterceptionContext`1 c) +12
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +72
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.SetConnectionString(DbConnection connection, DbConnectionPropertyInterceptionContext`1 interceptionContext) +360
System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection) +270
System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config) +32
System.Data.Entity.Internal.LazyInternalConnection.Initialize() +129
System.Data.Entity.Internal.LazyInternalConnection.get_ProviderName() +13
System.Data.Entity.Internal.LazyInternalContext.get_ProviderName() +11
System.Data.Entity.Internal.DefaultModelCacheKeyFactory.Create(DbContext context) +92
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +515
System.Data.Entity.Internal.InternalContext.Initialize() +20
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +16
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +53
System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +15
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +38
System.Linq.Queryable.Where(IQueryable`1 source, Expression`1 predicate) +83
Lat34North.Controllers.BaseController.DeletePrevNext(String PrevNextLocation, String type) in c:\Lat34North\Lat34North\Controllers\CommonController.cs:71
Lat34North.Controllers.HistoricMarkersALController.SearchChurches(String option, String search) in c:\Lat34North\Lat34North\Controllers\HistoricMarkersALController.cs:459
lambda_method(Closure , ControllerBase , Object[] ) +147
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.<>c.<BeginInvokeSynchronousActionMethod>b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__11_0() +50
System.Web.Mvc.Async.<>c__DisplayClass11_1.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__1(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__3() +35
System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +577
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +132
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
change your config to the following. you missed a closing ' for connectionString=''
<add name='Lat34NorthContext' connectionString='Data Source=[HOST Server];Initial Catalog=Lat34North;Integrated Security=False;User Id=[user id 1]; Password=[password 1];Min Pool Size=20; Max Pool Size=200;' providerName="System.Data.SqlClient" />
If your SQL Server is on one domain controller and you are trying to connect to it from another domain controller then you will get this error when IntegratedSecurity = true;
Integrated security means simply - use your windows credentials for login verification to SQL Server. So, if you are logged in to a different domain controller then it will fail. In the case where you are on two different domain controllers then you have no choice but to use IntegratedSecurity = false;
This seems like a straightforward question. I am beginning to suspect a bug in razor.
if (Model.athleteImages .Any()){
//some code
}
I have replaced the above with the following:
if (Model.athleteImages.Count > 0)
{
var i = 0;
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
while (i + 1 < Model.athleteImages.Count())
{
i++;
<li data-target="#carousel-example-generic" data-slide-to="#i"></li>
}
}
This always throws "Sequence contains no elements" for collections with no elements e.g. Count() = 0.
Any() is supposed to test if a Sequence contains elements. That is its entire purpose.
I have also tried
if (Model.athleteImages.FirstOrDefault().[fieldName] != null){
//some code
}
Same result.
here is some relevant code from the controller for those wondering what the Images collection is
var adImages = from i in db.athleteImages
where thisAd.albumId == i.albumId
where i.deleted == false
select i;
viewModel.athleteImages = athleteImages.ToList();
Here is the View Model Class
public class ListingViewModel
{
public site site { get; set; }
public userAd userAd { get; set; }
public List<athleteImage> athleteImages { get; set; }
public string categoryName { get; set; }
public int categoryId { get; set; }
public string subcategoryName { get; set; }
public int subcategoryId { get; set; }
}
Stack Trace
[InvalidOperationException: Sequence contains no elements]
System.Linq.Enumerable.First(IEnumerable`1 source) +269
ASP._Page_Views_userAds_Listing_cshtml.Execute() in c:\Users\Bill\Documents\Visual Studio 2013\Projects\CuriousMarketplaces\CuriousMarketplaces\Views\userAds\Listing.cshtml:32
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +198
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +64
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +173
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651116
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
If what you really care about is whether or not there are any images in the collection, something like this might make more sense:
if (Model.Images.Count > 0) {
}
Any() will throw an exception if the source is null, this is documented behavior and how it is supposed to work: http://msdn.microsoft.com/en-us/library/vstudio/bb534972%28v=vs.100%29.aspx
Dave's solution is pretty good but I would add a null check, Count will also throw an exception if the object is null.
if(Model.Images != null && Model.Images.Count > 0) {
}
Dan gave me the hint I needed.
Even though the debugger was indicating that the error was occurring at the closing block of my if block, that was not the case.
In a later block of code in the same view, I have this:
<div class="item active" id="0">
<div style="width:400px;height:300px;text-align:center;background-color:black;">
<img src="/Content/Images/Deals/1/#Model.athleteImages.First().fullImage" style="height:300px;" alt="...">
<div class="carousel-caption">
some caption
</div>
</div>
</div>
To fix the problem, I need to test again. so:
if (Model.athleteImages.Count > 0)
{
<div class="item active" id="0">
<div style="width:400px;height:300px;text-align:center;background-color:black;">
<img src="/Content/Images/Deals/1/#Model.athleteImages.First().fullImage" style="height:300px;" alt="...">
<div class="carousel-caption">
some caption
</div>
</div>
</div>
}
What fries my brain is that the error message indicated a problem at line 32. In reality it was on line 37.
My problem is with a system i developed for school. We are experiencing some issues for some users. this is the error:
[NullReferenceException: Object reference not set to an instance of an object.]
_360Feedback.Controllers.SurveyController.Answers() +170
lambda_method(Closure , ControllerBase , Object[] ) +78
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +273
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +38
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +119
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +452
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +33
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +240
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
For some reason the student id is not retained by the session object. I cannot regenerate the error so it is very hard for me to find the reason what is causing this.
Setting the session to cookieless seemed to cause less errors for users, but still generated the error for some users.
I can see that for about 90% of the users everything is working fine. I will post the controller code where this session id is used. I hope you guys can help me.
public ActionResult Start(string x)
{
string decryptedstudentIDString = EncryptionHelper.Decrypt(x);
int studentID = Convert.ToInt32(decryptedstudentIDString);
Student student = repo.FindStudentWithID(studentID);
Session["StudentName"] = student.Name;
Session["StudentID"] = student.StudentID;
if (student.CompletedAnswers == true)
{
return RedirectToAction("Completed");
}
return View(student);
}
public ActionResult Answers()
{
Student student = repo.FindStudentWithID(Convert.ToInt32(Session["StudentID"]));
if (student.CompletedAnswers == true)
{
return RedirectToAction("Completed");
}
List<Student> remainingStudentInGroup = repo.GetRemainingStudentIDsInGroup(student.StudentID);
student.Answers.Add(new AnswerSet() { AssociatedStudentID = student.StudentID, AssociatedStudentName = student.Name });
foreach (var studentInGroup in remainingStudentInGroup)
{
student.Answers.Add(new AnswerSet() { AssociatedStudentID = studentInGroup.StudentID, AssociatedStudentName = repo.FindStudentWithID(studentInGroup.StudentID).Name });
}
Group group = repo.GetGroupAssociatedWithStudent(student.StudentID);
Session["StudentID"] = student.StudentID;
Session["GroupSize"] = group.Students.Count;
return View(student);
}
[HttpPost]
public ActionResult Answers(Student student)
{
int s = repo.FindStudentWithID(Convert.ToInt32(Session["StudentID"])).StudentID;
foreach (var answerSet in student.Answers)
{
repo.AddAnswerSetToStudent(answerSet, s);
}
return RedirectToAction("Completed");
}
public ActionResult Completed()
{
Student student = repo.FindStudentWithID(Convert.ToInt32(Session["StudentID"]));
if (student.CompletedAnswers == false)
{
repo.SetBooleanForCompletedAnswerToTrue(student.StudentID);
Group group = repo.GetGroupAssociatedWithStudent(student.StudentID);
ExcelHelper.FillExcelWithAnswersForStudent(group.ExcelFilePath, student);
ExcelHelper.CheckIfAllStudentAnswered(group);
}
return View();
}
Error occurs when users submit form, StudentID is null when they post there answers.
I'm trying to call an action method in an MVC4 application using jQuery. I'm using a button on Edit form shown in fancybox:
<input type="button" value="Approve" id="Approve" />
I'm using a jquery $.post on this button click
$("#Approve").click(function () {
debugger;
var ID = $("#AjaxGrid tbody tr:first").attr("data-pkey");
debugger;
var postParams = { Id: ID }
$.post('#Html.Raw(Url.Action("Approve"))', postParams)
.fail(function () {
alert("error occured while Approving");
});
});
In the controller the following is my action method:
[HttpPost]
public ActionResult Approve(long id)
{
Evaluation evaluation = db.EvaluationRepository.GetByID(id);
evaluation.EvaluationStatusID = Convert.ToInt32(EvaluationStatusType.Approved);
return PartialView(evaluation);
}
But I always get the same result i.e. error occured while Approving
Can any one help me in finding what's wrong?
got this error with F12 on browser
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and this annoying detail
Server Error in '/' Application.
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int64' for method 'System.Web.Mvc.ActionResult Approve(Int64)' in 'CubicHRMWeb.Areas.Employees.Controllers.EvaluationController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
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.ArgumentException: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int64' for method 'System.Web.Mvc.ActionResult Approve(Int64)' in 'CubicHRMWeb.Areas.Employees.Controllers.EvaluationController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
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:
[ArgumentException: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int64' for method 'System.Web.Mvc.ActionResult Approve(Int64)' in 'CubicHRMWeb.Areas.Employees.Controllers.EvaluationController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters]
System.Web.Mvc.ActionDescriptor.ExtractParameterFromDictionary(ParameterInfo parameterInfo, IDictionary2 parameters, MethodInfo methodInfo) +654635
System.Web.Mvc.<>c__DisplayClass1.<Execute>b__0(ParameterInfo parameterInfo) +18
System.Linq.WhereSelectArrayIterator2.MoveNext() +85
System.Linq.Buffer1..ctor(IEnumerable1 source) +217
System.Linq.Enumerable.ToArray(IEnumerable1 source) +78
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +133
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
System.Web.Mvc.Async.<>c__DisplayClass81.b__7(IAsyncResult ) +12
System.Web.Mvc.Async.WrappedAsyncResult1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +58
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +237
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +12
System.Web.Mvc.Async.WrappedAsyncResult1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c_DisplayClass2a.b_20() +24
System.Web.Mvc.Async.<>c_DisplayClass25.b_22(IAsyncResult asyncResult) +126
System.Web.Mvc.Async.WrappedAsyncResult1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +61
System.Web.Mvc.Async.<>c_DisplayClass4.b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +49
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +49
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8862381
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.225
HTML:
<input type="button" value="Approve" id="Approve" data-action="#Url.Action("Approve")" />
JS:
Number.tryParseInt = function(value) {
return value.toString().match(/^(\d)/) != null;
}
Number.tryParseFloat = function(value) {
return value.toString().match(/^(\d|\d\.|\.\d)/) != null;
}
$("#Approve").click(function () {
var
id = $("#AjaxGrid tbody tr:first").data('pkey'),
postParams = { id: 0 };
if (!Number.tryParseFloat(id)) {
alert('id "' + id + '" is not a number');
return false;
}
postParams.id = parseInt(id);
$.post($(this).data('action'), postParams)
.done(function(data) {
alert('ok Approving: ' + data.EvaluationStatusID);
})
.fail(function () {
alert('error occured while Approving');
});
return false;
});
C#:
Why you are using ActionResult if not using the return?
[HttpPost]
public JsonResult Approve(long id)
{
Evaluation evaluation = db.EvaluationRepository.GetByID(id);
evaluation.EvaluationStatusID = Convert.ToInt32(EvaluationStatusType.Approved);
return Json(evaluation);
}
Need you a larger number of '2.147.483.647'?, if you continue with the error, try using int:
[HttpPost]
public JsonResult Approve(int id)
{
Evaluation evaluation = db.EvaluationRepository.GetByID(id);
evaluation.EvaluationStatusID = Convert.ToInt32(EvaluationStatusType.Approved);
return Json(evaluation);
}
From your stack trace it appears the id parameter of your AJAX call is null, data-pkey is empty for the selected element.
Without seeing your HTML I can't tell you why this is but you need to look at and change the $("#AjaxGrid tbody tr:first") selector.
I think there is a Circular Refrence Issue
My Model Class
public class Evaluation
{
[Key]
public int ID {get; set;}
public int UserID {get; set;} //whose evaluation is due
public DateTime EvaluationDueOn {get; set;}
public DateTime EvaluatedOn {get; set;}
public decimal evaluationAmount {get; set;}
public string comments {get; set;}
public string ApproverID {get; set;} //(userid of staff doing approval)
public int EvaluationStatusID { get; set; }
public virtual Users EvaluatedUser { get; set; }
public virtual Users ApprovingUser { get; set; }
}
uses Navigational properties like
public virtual Users EvaluatedUser { get; set;
public virtual Users ApprovingUser { get; set; }
and Serialization problem occurs due to this Circular Refrence