The .NET MVC model has to have a parameterless constructor

When you create a class to be used as the model in a .NET MVC application, the class has to have a parameterless constructor. It is called during the POST when the user clicks the submit button of the form. If the class does not have a parameterless constructor, we will get the following generic error message. None of the breakpoints can help you to find the cause, and there is no entry in the event log.

The website cannot display the page
HTTP 500

Most likely causes:
•The website is under maintenance.
•The website has a programming error.

What you can try:
Refresh the page.
Go back to the previous page.
More information

No mapping specified for instances of the EntitySet and AssociationSet in the EntityContainer

When you move your Visual Studio solution to another workstation you may encounter the following error message:

System.Data.Entity.Core.MappingException was unhandled by user code
HResult=-2146232032
Message=Schema specified is not valid. Errors:
: error 2062: No mapping specified for instances of the EntitySet and AssociationSet in the EntityContainer …
Source=EntityFramework

 

In this case it may help if you re-import the database objects into the .edmx file.

To import all objects again:

  • Open the .edmx file,
  • Press the Ctrl-A keys to select all tables in the diagram,
  • Press the delete key on the keyboard to delete all tables,
  • Right click the white area and select Model Browser,
  • In the Model Browser expand the {model name}.Store, and the Stored Procedures / Functions element
  • Delete all functions and stored procedures
  • In the {model name} element (the element above the {model name}.Store) expand the Function Imports element
  • Delete all function imports
  • Save the .edmx file
  • Right click the white area of the .edmx file and select Update Model from Database
  • Select all necessary tables, stored procedures, and functions and import them.

If you re-import the tables, but do not delete the stored procedures, functions, and function imports you may get the following error message:

HResult=-2146233079
Message=The function import ‘Tobacco_WebEntities.spGetAgeGroupId’ cannot be executed because it is not mapped to a store function.
Source=EntityFramework

 

Save the key file password in Visual Studio

When you have already set up the project signing of the C# application for ClickOnce deployment, and move the solution to another workstation you may get the following error message when you build the solution:

Severity Code Description Project File Line Suppression State
Error Cannot import the following key file: .....pfx. The key file may be password protected. To correct this, try to import the certificate again or manually install the certificate to the Strong Name CSP with the following key container name: VS_KEY_....

We get this message, because the new workstation does not know the key file password. To solve this problem, we have to save the key file password on the new workstation.

To make your solution work again

  • Open the Visual Studio project properties window,
  • On the Signing tab click the pull down that shows the name of the key file.
  • Select Browse,
  • Select the key file,
  • Enter the password in the Password text box.

There is already an open DataReader associated with this Command which must be closed first

When your MVC 5 web application page tries to read the database using the Entity Framework in a loop you may get the following error message:

InnerException: System.InvalidOperationException
HResult=-2146233079
Message=There is already an open DataReader associated with this Command which must be closed first.
Source=System.Data

This usually happens when a cshtml page receives an IEnumerable<> model from the database and makes repeated calls to retrieve the rows one-by-one in a foreach loop.

If your page does not display paged data, read the rows into a List  with the ToList() method and send the list to the cshtml page to iterate through it. This forces the application to read all appropriate rows with one call from the database.

Sometimes you can also eliminate the problem if you add the following to the connection string in the web.config file:

;multipleactiveresultsets=True

Windows web service authentication in IIS Express

When you develop a SOAP web service in Visual Studio 2013 the IDE uses IIS Express for testing. To set up Windows authentication in IIS Express follow the steps below:

Create a Local Security Group on your computer

  • Right click Computer and select Manage
  • On the left side expand Local Users and Groups
  • Right click the Groups folder and select New Group
  • Create a group with the name WebserviceUsers for the users of the web service
  • Right click the Users folder and select New User
  • Create a user and add it to the WebserviceUsers security group

Add the following lines to the  <system.web> section of the Web.config file of your web service application

<authentication mode=”Windows”/>
<authorization>
<allow roles=”WebserviceUsers”/>
<deny users=”*”/>
</authorization>

Set up IIS Express for Windows authentication

  • Select the web service project in the Solution Explorer
  • In the View menu select Properties Window
  • Disable Anonymous Authentication and enable Windows Authentication
    Visual Studio IIS Express Windows Authentication Properties Window

 

In the caller application call the web service with user name and password

  • Add the following lines to your class to supply the credentials
private Webservice.Service _Webservice = new Service();

// Constructor
public Business() {
    string webserviceUrl = "Webservice_Url";
    string webserviceUserName = "Webservice_UserName";
    string webservicePassword = "Webservice_Password";
    _Webservice.Url = webserviceUrl;
    ICredentials credentials = new NetworkCredential(webserviceUserName, webservicePassword);
    _Webservice.Credentials = credentials;
}

How to add tooltip to a Windows Form

In Windows Form applications the tooltip functionality is not built into the controls as in HTML objects.

To add tooltip to your controls on Windows Forms

  • Open the Windows Form in the designer
  • Drag the ToolTip control from the Common Controls section of the Toolbox to the form. The ToolTip control will be placed at the bottom margin of the design surface outside of the visible area of the form.
  • A new item appears in the Misc section of the property list of the form controls (buttons, textboxes, etc): ToolTip on toolTip1
  • Enter the text there you want the users to see when they hover above the control.

How to add a DataGridView to a Windows Form

To display data in a DataGridView on a Windows Form

  • Add a new form to the Win Form Application project
  • Drag a BindingSource from the Toolbox to the form
    Visual Studio Toolbox Data

 

  • The bindingSource object appears below the form
    Visual Studio DataGridview Binding DatSource insert

 

  • Rename the Binding Source
    • Select the bindingSource1 object below the form
    • Press F4 to display the Properties
    • Change the Name property to reflect the purpose of the object
      Visual Studio DataGridview Binding DatSource properties

 

  • Select the DataSource item in the Data section and click the Add Project Data Source… link
    Visual Studio DataGridview Binding DatSource properties select data source

The name is misleading. At this step we are not selecting the source of the data, we are selecting the object that describes the data row. The DataGridView will generate the columns based on the object we will select here.

  • To load the data from a class select Object as the Data Source Type and click Next
    Visual Studio DataGridview Binding Data Source properties choose data source type

 

  • Select the object that describes the data row you want to display
    Visual Studio DataGridview Binding Data Source properties select data object

 

  • Drag a DataGridView from the Toolbox to the form
    Visual Studio Toolbox Data data grid view

 

  • Select the small arrow at the upper right corner of the DataGridView to open the Tasks dialog
  • Click the down arrow next tot the Choose Data Source list
  • Select the Binding Data Source that you added to the form
    Visual Studio DataGridview select binding data source

 

  • Click the Edit Columns link to set the visibility of the columns
    Visual Studio DataGridview Edit Columns

 

  • To hide a column set the Visible attribute in the Appearance section to False
    Visual Studio DataGridview Column visibility
  • To load data into the DatGridView add the following code to the constructor of the form. In this example the GetUsers() method returns an array of UserView objects
    // Load the data into the DataGridView
    bindingSourceUsers.DataSource = _business.GetUsers();
  • To hide the row selector column on the left side of the data add the following to the constructor of the form. This option is not included in the property sheet of the DataGridView, so we have to set it in the code.
    dataGridView1.RowHeadersVisible = false;

DbArithmeticExpression arguments must have a numeric common type

The Microsoft Visual Studio 2013 Entity Framework database query does not support the subtraction of two dates to calculate TimeSpan.

For example the following statement will throw a runtime error:

site.VisitFrequencySec < ((TimeSpan)(dtNow - site.LastVisitDate)).TotalSeconds)

To solve the problem create a computed database column to calculate the difference between the dates and use the computed value for comparison.

Column definition:

[SecondsSinceLastVisit]  AS (datediff(second,[LastVisitDate],getdate()))

Now you can use the computed column in the C# Entity Network comparison.

site.VisitFrequencySec < site.SecondsSinceLastVisit

The underlying provider failed on Open

When you get the following error message in Microsoft Visual Studio 2013 check the inner exception.

System.Data.Entity.Core.EntityException was unhandled
  HResult=-2146233087
  Message=The underlying provider failed on Open.
  Source=EntityFramework

The inner exception gives you detailed information on the real cause of the error. Most of the time the inner exception is the following:

InnerException: System.Data.SqlClient.SqlException
       HResult=-2146232060
       Message=Cannot open database “…” requested by the login. The login failed.
Login failed for user ‘…’.
       Source=.Net SqlClient Data Provider
       ErrorCode=-2146232060

Check the rights of the user. Most likely the specified user does not have access to the database.

 

The Entity Framework provider … could not be loaded

When you create a new Microsoft Visual Studio 2013 project that uses the Entity Framework you may get the following error message:
The Entity Framework provider type ‘System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer’ registered in the application config file for the ADO.NET provider with invariant name ‘System.Data.SqlClient’ could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.

  • Add the EntityFramework NuGet package to the Data Access project that accesses the database and the Web Application or Web Service project that calls the project
    • Right click the project in Solution Explorer
    • Select Manage NuGet Packages
    • On the left side select Online
    • On the right side enter EntityFramework into the search field
    • Click Install next to the EntityFramework package
  • Make sure your app config file contains the following lines:

 

<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" />
  </providers>
</entityFramework>
  • Your project should contain a reference to EntityFramework.SqlServer.dll
  • Add the following line to the constructor of the class that accesses the database
var type = typeof(System.Data.Entity.SqlServer.SqlProviderServices);
  • Add the System.Data.Entity reference to the project accessing the database