Adding a new record to DB, key is always zero - entity-framework

I have an existing App written using Microsoft Visual C++ 2017, ASP.NET, MVC 5.2.7.0, Entity Framework Version=5, DB is SQL Server. When I add a new record to my DB, the key (ParkID) that results is a zero and when I try and save the change. I get an error.
Cannot insert the value NULL into column 'ParkID', table 'N_CWBFM-20170818.dbo.Park'; column does not allow nulls. INSERT fails.
The database N_CWBFM-20170818 was downloaded from the HOST where my app runs.
Confession, this is a hobby, so I may not use the correct terminology and translating other ways of adding data to a DB to the method I am using.
Model
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CWBFM.Models
{
public class Park
{
[Key]
public int ParkID { get; set; }
public bool ParkChangePending { get; set; } // change pending true/false
public int ParkChangeCount { get; set; } // Count the number of changes to this record
public int ParkPrevRec { get; set; } // points backwards to the previous version
public int ParkNextRec { get; set; } // ID of previous record
Omitted
DB Context
using CWBFM.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace CWBFM.DAL
{
public class CWBFMContext : DbContext
{
public DbSet<Park> Parks { get; set; }
public DbSet<Photo> Photo { get; set; }
public DbSet<StateFilter> StateFilters { get; set; }
Omitted
Controller
using System;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using CWBFM.Models;
using CWBFM.DAL;
namespace CWBFM.Controllers
{
public class ParkController : BaseController
{
private CWBFMContext db = new CWBFMContext();
Omitted
// POST: /Park/Create
[HttpPost]
[Authorize]
public ActionResult ParkCreate(Park park)
{
setYesNo(); //set the values for the dropdown box (Yes, No, Unknown)
if (ModelState.IsValid)
{
park.ParkChangePending = false;
park.ParkChangeCount = 0;
park.ParkDateCreated = DateTime.Now;
park.ParkDateChange = DateTime.Now;
park.ParkCreatedBy = #User.Identity.Name;
park.ParkChangedBy = #User.Identity.Name;
park.ParkStatus = "N";
db.Parks.Add(park);
int stop = park.ParkID;
db.SaveChanges();
park.ParkRecID = "Park" + park.ParkID.ToString();
db.SaveChanges();
return RedirectToAction("ParkDetails", new { id=park.ParkID });
}
return View(park);
}
Config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<!-- <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
<add namespace="Telerik.Web.Mvc.UI" />
</namespaces>
</pages>
<httpRuntime targetFramework="4.6.1" maxRequestLength="20971520" />
<!-- This will handle requests up to 20MB -->
<profile inherits="CWBFM.Models.MyUserProfile" defaultProvider="DefaultProvider">
<providers>
<clear />
<add name="DefaultProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<!--<profile defaultProvider="DefaultProfileProvider">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>-->
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="DefaultRoleProvider">
<providers>
<add connectionStringName="DefaultConnection" applicationName="/" name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</providers>
</roleManager>
<!--
If you are deploying to a cloud environment that has multiple web server instances,
you should change session state mode from "InProc" to "Custom". In addition,
change the connection string named "DefaultConnection" to connect to an instance
of SQL Server (including SQL Azure and SQL Compact) instead of to SQL Server Express.
-->
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
<httpHandlers>
<add verb="GET,HEAD" path="asset.axd" validate="false" type="Telerik.Web.Mvc.WebAssetHttpHandler, Telerik.Web.Mvc" />
</httpHandlers>
<httpModules>
<add name="CompilableFileModule" type="SassAndCoffee.CompilableFileModule" />
</httpModules>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!-- This will handle requests up to 1024MB (1GB) -->
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="asset" />
<add name="asset" preCondition="integratedMode" verb="GET,HEAD" path="asset.axd" type="Telerik.Web.Mvc.WebAssetHttpHandler, Telerik.Web.Mvc" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" /><remove name="OPTIONSVerbHandler" /><remove name="TRACEVerbHandler" /><add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /></handlers>
<modules>
<remove name="CompilableFileModule" />
<add name="CompilableFileModule" type="SassAndCoffee.CompilableFileModule" />
</modules>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<connectionStrings>
It dies on the save (db.SaveChanges();). A breakpoint at int stop = park.ParkID; shows that the ParkID is zero.
ParkID = 0
I have looked at several proposed solutions, but just can’t find one that works. Any suggestions. Could I have missed an update in my config when I changed to EF 5?

This can occur if the database was set up without an Identity column set on the PK, but EF will automatically expect an identity column on keys named "Id" or with the "Id" suffix on the class name. (I.e. Park.ParkId) If the DB is not actually set up to use an Identity but EF is configured for an Identity column (DatabaseGeneratedOption.Identity) the resulting insert statements will not include the ParkId column, resulting in a #null failure in the database.
I generally recommend being explicit with configuration rather than relying on EF's conventions for behaviour:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ParkId { get; set; }
If you expect the new records to be given a PK value automatically by the database then update the database schema to mark these PKs as Identity columns. If your schema is code-first and generating Migrations then there should be a way to apply a migration to update the PKs to identity columns. Otherwise simply make the change within SSMS.
If instead you want to provide PKs from your code, (such as part of data imports from other data sources) then you need to configure EF to not treat the PK as an Identity.
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ParkId { get; set; }

Related

The type or namespace name 'HtmlEditorExtender' does not exist in the namespace 'AjaxControlToolkit'

<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager><ajaxToolkit:ToolkitScriptManagerID="ToolkitScriptManager1"runat="server">
</ajaxToolkit:ToolkitScriptManager>
<asp:TextBox ID="TxtEditor" runat="server"/>
<ajaxToolkit:HtmlEditorExtender ID="HtmlEditorExtender1" runat="server" TargetControlID="TxtEditor">
</ajaxToolkit:HtmlEditorExtender>
<br/>
<asp:Button runat="server" Text="Submit" OnClick="Submit"/>
</form>
This is the design page and I add "<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>" at the top of the page
protected global::AjaxControlToolkit.HtmlEditorExtender HtmlEditorExtender1;
I am getting error on this line.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="system.web">
<section name="sanitizer" requirePermission="false" type="AjaxControlToolkit.Sanitizer.ProviderSanitizerSection, AjaxControlToolkit" />
</sectionGroup>
<section name="ajaxControlToolkit" type="AjaxControlToolkit.AjaxControlToolkitConfigSection, AjaxControlToolkit" /></configSections>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</assemblies>
</compilation>
<sanitizer defaultProvider="HtmlAgilityPackSanitizerProvider">
<providers>
<add name="HtmlAgilityPackSanitizerProvider" type="AjaxControlToolkit.Sanitizer.HtmlAgilityPackSanitizerProvider"></add>
</providers>
</sanitizer>
<pages>
<controls>
<add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
</controls>
</pages></system.web>
<ajaxControlToolkit htmlSanitizer="AjaxControlToolkit.HtmlEditor.Sanitizer.DefaultHtmlSanitizer, AjaxControlToolkit.HtmlEditor.Sanitizer" />
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="AjaxControlToolkit" publicKeyToken="28f01b0e84b6d53e" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.0.20229.24049" newVersion="1.0.20229.24049" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
This is my web.config page
You register "AjaxControlToolkit" namespace with "asp" tag prefix, but access HtmlEditorExtender with "ajaxToolkit" prefix.
Change it to "ajaxToolkit" everywhere.

The ADO.NET provider with invariant name 'System.Data.SqlServerCe.4.0' is either not registered

We're trying to deploy our MVC solution to a customer, but they're getting an error while trying to log in.
I have searched for similar issues, but have not yet found a solution.
It does have SQL CE 4.0 installed.
I have checked app.config, but it seems fine. It has the lines as suggested here
Could someone shed some light on the following error log?
2015-10-05 09:59:54,259 [ 34] FATAL - [] Exception caught
System.Data.DataException: An exception occurred while initializing the database. See the InnerException for details. ---> System.Data.Entity.Core.MetadataException: Schema specified is not valid. Errors:
(0,0) : error 0175: The ADO.NET provider with invariant name 'System.Data.SqlServerCe.4.0' is either not registered in the machine or application config file, or could not be loaded. See the inner exception for details.
at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Loader.ThrowOnNonWarningErrors()
at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Init(IEnumerable1 xmlReaders, IEnumerable1 filePaths, Boolean throwOnError, IDbDependencyResolver resolver, DbProviderManifest& providerManifest, DbProviderFactory& providerFactory, String& providerInvariantName, String& providerManifestToken, Memoizer2& cachedCTypeFunction)
at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection..ctor(IEnumerable1 xmlReaders)
at System.Data.Entity.Utilities.XDocumentExtensions.GetStorageMappingItemCollection(XDocument model, DbProviderInfo& providerInfo)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, Lazy1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
at System.Data.Entity.Migrations.DbMigrator.IsModelOutOfDate(XDocument model, DbMigration lastMigration)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.MigrateDatabaseToLatestVersion2.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
--- End of inner exception stack trace ---
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action)
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 source, Expression1 predicate)
at TWP.Areas.Core.Models.Authorization.DatabaseMembershipProvider.ValidateUser(String userName, String password)
at TWP.Areas.Core.Models.Account.AccountProvider.Logon(TwpMembershipProvider membership, LogOnViewModel model)
at TWP.Areas.Core.Controllers.AccountController.LogOn(LogOnViewModel model, String returnUrl)
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor, IDictionary2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
Web.config:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
<section name="twpSettings" type="TWP.Areas.Core.Models.Settings.TwpSettingsSection, TWP"/>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</configSections>
<!-- Path to the configuration file for custom TWP settings -->
<twpSettings configSource="Config\Twp.config"/>
<appSettings>
<!-- Setting for increasing the max size of http requests -->
<add key="aspnet:MaxHttpCollectionKeys" value="10000"/>
<!-- Path to the configuration file for log4net -->
<add key="log4net.Config" value="Config\log4net.config"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<connectionStrings>
<add name="ADConnectionString1" connectionString="xxxxxx,OU=xxxxxx,DC=xxxxxx,DC=xxx"/>
<add name="TWPConnectionString" connectionString="Data Source=xxxxxx;Initial Catalog=xxxxxxxxx;Persist Security Info=True;User ID=xxxxxxxxxx;Password=xxxxxxxxxxxxxxx" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<customErrors mode="Off"/>
<compilation debug="false" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</assemblies>
</compilation>
<!-- Default culture -->
<globalization uiCulture="en-GB" culture="en-GB"/>
<authentication mode="Forms">
<forms loginUrl="~/Core/Account/LogOn" timeout="2880"/>
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers"/>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
<add namespace="System.Web.WebPages"/>
<add namespace="TWP.Areas.Core.Models"/>
</namespaces>
</pages>
<httpRuntime maxRequestLength="10240"/>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="1.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages.Deployment" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="1.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Razor" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.serviceModel>
<!-- Clients -->
<client>
(removed)
</client>
<!-- Services -->
<services>
(removed)
</services>
<!-- Service Hosting Environment -->
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
<!-- Bindings -->
<bindings>
<wsHttpBinding>
<binding name="wsHttpBinding_DccWcfLibrary" closeTimeout="00:00:10" openTimeout="00:00:10" sendTimeout="00:00:10" maxReceivedMessageSize="4194304" />
</wsHttpBinding>
<webHttpBinding>
<binding name="webHttpBinding_Large" maxReceivedMessageSize="1655360">
<readerQuotas maxDepth="32" maxStringContentLength="163840" maxArrayLength="163840" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None" />
</binding>
</webHttpBinding>
</bindings>
<!-- Behaviors -->
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="geocodingBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
</providers>
</entityFramework>
</configuration>
I'm not sure what was wrong with SQL CE 4.0, but reinstalling it fixed the issue.

Sqlite not work with Entity Framework 6

I have a small project with sqlite and entity framework 6.
I install sqlite by Package Manager Console: PM>Install-Package System.Data.SQLite
In my web.config:
<connectionStrings>
<remove name="demoSQLiteonnectionString" />
<add name="demoSQLiteonnectionString" connectionString="Data Source=|App_Data|DemoData.s3db" providerName="System.Data.SQLite.EF6" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite" />
<add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".Net Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
<remove invariant="System.Data.SQLite.EF6" />
<add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".Net Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
</DbProviderFactories>
</system.data>
In my context class:
public class DataContext : DbContext
{
public DataContext()
: base("demoSQLiteonnectionString")
{
Database.SetInitializer(new CreateDatabaseIfNotExists<DataContext>());
}
public DbSet<Client> Client { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Chinook Database does not pluralize table names
modelBuilder.Conventions
.Remove<PluralizingTableNameConvention>();
}
}
When get instance of context: var context = new DataContext(),
it shows this error:
Additional information: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SQLite'. Make sure the provider is registered in the 'entityFramework' section of the application config file. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.
How to fix this problem?
You Should change the app config file to
<providers>
<provider invariantName="**System.Data.SQLite.EF6**" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
</providers>
to
<providers>
<provider invariantName="**System.Data.SQLite**" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
</providers>
and change the configuration file to :
public class DataContext : DbContext
{
public DataContext()
: base("demoSQLiteonnectionString")
{
}
public DbSet<Client> Client { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Chinook Database does not pluralize table names
modelBuilder.Conventions
.Remove<PluralizingTableNameConvention>();
Database.SetInitializer(new SqliteCreateDatabaseIfNotExists<DataContext>(modelBuilder));
}
}

Crystal Report unable to generate in VS 2012

Bobj is undefined error when I used debug in VS 2012. tried everything but I am running out of ideas why my crystal report is unable to work.
web.config
<?xml version="1.0"?><!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
--><configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
<sectionGroup name="businessObjects">
<sectionGroup name="crystalReports">
<section name="rptBuildProvider" type="CrystalDecisions.Shared.RptBuildProviderHandler,CrystalDecisions.Shared,Version=13.0.2000.0,Culture=neutral,PublicKeyToken=692fbea5521e1304,Custom=null"/>
<section name="crystalReportViewer" type="System.Configuration.NameValueSectionHandler"/>
</sectionGroup>
</sectionGroup>
</configSections>
<appSettings>
<add key="CrystalImageCleaner-AutoStart" value="true" />
<add key="CrystalImageCleaner-Sleep" value="60000" />
<add key="CrystalImageCleaner-Age" value="120000" />
</appSettings>
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-WebApplication1-20130616171922;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-WebApplication1-20130616171922.mdf"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"/>
<add assembly="CrystalDecisions.Shared, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"/>
<add assembly="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"/>
<add assembly="CrystalDecisions.ReportSource, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"/>
<add assembly="CrystalDecisions.ReportAppServer.Controllers, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"/>
<add assembly="CrystalDecisions.ReportAppServer.DataDefModel, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"/>
<add assembly="CrystalDecisions.CrystalReports.Engine, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"/>
<add assembly="CrystalDecisions.ReportAppServer.ClientDoc, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/></assemblies>
</compilation>
<httpRuntime targetFramework="4.5"/>
<pages>
<namespaces>
<add namespace="System.Web.Optimization"/>
</namespaces>
<controls>
<add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt"/>
</controls>
</pages>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880"/>
</authentication>
<profile defaultProvider="DefaultProfileProvider">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/"/>
</providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
</providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/"/>
</providers>
</roleManager>
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection"/>
</providers>
</sessionState>
<httpHandlers><add verb="GET" path="CrystalImageHandler.aspx" type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/></httpHandlers></system.web>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0"/>
</parameters>
</defaultConnectionFactory>
</entityFramework>
<system.webServer>
<handlers>
<add name="CrystalImageHandler.aspx_GET" verb="GET" path="CrystalImageHandler.aspx" type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" preCondition="integratedMode"/></handlers><validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
<businessObjects>
<crystalReports>
<rptBuildProvider>
<add embedRptInResource="true"/>
<crystalReportViewer>
<add key="ResourceUri" value="~/crystalreportviewers13"/>
</crystalReportViewer>
</rptBuildProvider>
</crystalReports>
</businessObjects>
</configuration>
InvoiceReport.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="InvoiceReport.aspx.cs" Inherits="WebApplication1.InvoiceReport" %>
<%# Register assembly="CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" namespace="CrystalDecisions.Web" tagprefix="CR" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<p>
<br />
Invoice Report</p>
<p>
</p>
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="True" Height="1202px" ReportSourceID="CrystalReportSource1" ToolPanelView="None" ToolPanelWidth="200px" Width="950px" HasCrystalLogo="False" HasToggleGroupTreeButton="false" HasToggleParameterPanelButton="false" EnableParameterPrompt="False" />
<CR:CrystalReportSource ID="CrystalReportSource1" runat="server">
<Report FileName="CrystalReport1.rpt">
</Report>
</CR:CrystalReportSource>
<p>
</p>
</asp:Content>
InvoiceReport.cs
public partial class InvoiceReport : System.Web.UI.Page
{
CrystalReport1 m_Invoicerpt = null;
protected void Page_Load(object sender, EventArgs e)
{
ReportDocument crystaldoc = new ReportDocument();
crystaldoc.Load(Server.MapPath("CrystalReport1.rpt"));
crystaldoc.SetDatabaseLogon("xx","xx",#"xx","xx");
CrystalReportViewer1.ReportSource=crystaldoc;
}
}
}
would like to know how to make the crystal reports work. OS is in windows7
used v_13_0_5 and supportpack 5
http://scn.sap.com/docs/DOC-7824
using .net framework 4.5 in my web application project

ASP.NET MVC 2 Membership users table mdf file

I have an MVC 2 project where I have my own *.mdf file in the App_Data directory. The *.mdf file contains my normal tables but not a users table.
Is it possible to add a Users table to my *.mdf file and work with that instead of the simple register form? (if so: how could this be done?)
Because I don't know how to do these things above, I searched and only found steps to add build in Membership to my mdf file and I tried it:
I tried to add normal build in Membership to my *.mdf file with this:
aspnet_regsql.exe -C CONSTRINGHERE -d PATHTOMDFFILEHERE -A all
and I changed my Web.config file to this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="CompanyDBEntities" connectionString="metadata=res://*/Models.CompanyDB.csdl|res://*/Models.CompanyDB.ssdl|res://*/Models.CompanyDB.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\CompanyData.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership defaultProvider="CompanyDBSqlProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add name="CompanyDBSqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="CompanyDBEntities"
applicationName="/"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
requiresUniqueEmail="true"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""
/>
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider"
connectionStringName="CompanyDBEntities" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider"
connectionStringName="CompanyDBEntities" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
I did not modify anything else. I did not change the AccountController or something.
I builded and ran my MVC 2 application and went to LogOn and registered an account but got stuck there:
Account creation was unsuccessful. Please correct the errors and try again.
* The password retrieval answer provided is invalid. Please check the value and try again.
Summary:
I thought that it would be better to have a Users table in my *.mdf file but I don't know how to do the register/login/logout/membership/etc... things with an own users table.
So I tried adding Membership to my own *.mdf file so that everything would be in that one *.mdf file but that gives me also problems.
Maybe this info is important:
In the future I want it to be possible to let users register and login via Hotmail, Gmail, OpenId and I should need more fields like website, nickname, avatar, etc... other than the basic register form now. Also would need to show a profilepage from the user on the website.
Could anybody help me out?
PS: I don't have experience with Membership in ASP.NET :s
I encountered the same problem. You can customize the user register table by doing these:
First of all, configure the sqlmemberprovider service in web.config:
' add connectionStringName="PhotoSocialMemberService" applicationName="PhotoSocial"
minRequiredPasswordLength="5" minRequiredNonalphanumericCharacters="0"
requiresQuestionAndAnswer="true"
name="PhotoSocailMember" type="System.Web.Security.SqlMembershipProvider" /'
Edit the AccountModel.cs., look for
the method "CreateUser", the
abstract class should be like this:
public abstract class MembershipProvider : ProviderBase
{...
public abstract MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status);
}
in the AccountModel.cs you can find implementation of the abstract method in
public interface IMembershipService
{
int MinPasswordLength { get; }
bool ValidateUser(string userName, string password);
MembershipCreateStatus CreateUser(string userName, string password, string email, string passwordquestion, string passwordanswer);
bool ChangePassword(string userName, string oldPassword, string newPassword);
}
and in
public MembershipCreateStatus CreateUser(string userName, string password, string email, string passwordquestion, string passwordanswer)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
MembershipCreateStatus status;
_provider.CreateUser(userName, password, email, passwordquestion, passwordanswer, true, null, out status);
return status;
}
add as many as parameters as you like.
Edit the register model in RegisterModel in AccountModel.cs, add string you want to put into the registerModel:
public class RegisterModel
{[Required]
[DisplayName("User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[DisplayName("Email address")]
public string Email { get; set; }
[Required]
[ValidatePasswordLength]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Confirm password")]
public string ConfirmPassword { get; set; }
[Required]
[DisplayName("Password security question")]
public string PasswordQuestion { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Password security answer")]
public string PasswordAnswer { get; set; }
}
Last, rewrite the Register.aspx page, add the html tag:
Html.LabelFor(m => m.PasswordQuestion)
Most important, you need to change the _provider from readonly to private
public class AccountMembershipService : IMembershipService
{
private MembershipProvider _provider;
}
You can add your validation methods through this progress.