The Acumen software design blog provides you with helpful articles about .NET Development.

Several web sites provide a good overview.

Official Microsoft .NET Development Overview  .NET Development Wikipedia

Visual Studio, Entity Framework (EF)

Visual Studio, Entity Framework or EF

C#.net/vb.net asp.net 4.5

EF error 6.0

Visual Studio 2013

Errors:

Object reference not set to an instance of an object.

An exception of type ‘System.NullReferenceException’ occurred

Web page error:

System.NullReferenceException was unhandled by user code

Message=Object reference not set to an instance of an object.

Source=System.Data.Entity

StackTrace:

at System.Data.EntityKey.AddHashValue(Int32 hashCode, Object keyValue)

Solution/Resolution      

The IQueryable query string is valid and returns results, but EF throws and exception anyway when you call ToList().

You can copy the query to SQL Server Management Studio and execute the query successfully.

This can occur if one of your class variables of type “string” has a null value in the query response.

For more information about how Acumen can help with your other Software needs, contact us today!

For additional help, feel free to click on Microsoft’s Support page below:

https://support.microsoft.com/en-us/contactus/

Recently, while trying to implement Bootstrap’s typeahead.js to an ASP.NET MVC project, we ran into a couple problems. To start, we were using the following articles as a guide:

http://deanhume.com/home/blogpost/twitter-bootstrap-typeahead-and-asp-net-mvc—key-value-pairs/88

http://yassershaikh.com/using-twitter-typeahead-js-with-asp-net-mvc-web-api/

The code within these articles worked just fine for the purpose of dealing with in-memory data. For instance, creating a handmade List<Company> would execute without flaws. However, these articles didn’t work for our particular situation because we were dealing with an Entity Framework generated class containing data from a database. This being the case, we figured we could make an equivalent list using an Entity Framework query like so:

var companies = db.Companies.Where(m => m.Name.StartsWith(query)).Select(c => new { c.Name, c.CompanyID });

This turned out to be only half of the battle. We were still having issues so we began logging some JavaScript objects in the console. With the handmade list, the console showed a conventional JSON object. On the other hand, when we passed the Entity Framework JSON serialized object we got numerous errors, including:

A circular reference was detected while serializing an object of type ‘System.Data.Entity.DynamicProxies.Company_983FFFBF6539DF8F813E1EAB1A1565F8743CF808D3B09F748B8A4906B756C4EF’.

We tried manually serializing, but it gave a similar error:

Using JsonConvert.SerializeObject
In Visual Studio before getting to client:
Self referencing loop detected for property ‘Company’ with type ‘System.Data.Entity.DynamicProxies.Company_983FFFBF6539DF8F813E1EAB1A1565F8743CF808D3B09F748B8A4906B756C4EF’. Path ‘[0].SalesCalls[0]’.

So, the big problem was trying to serialize an Entity Framework object. This can be done by changing a particular setting to false. In your code, you can simply call the following:

context.Configuration.ProxyCreationEnabled = false;

After adding that, we had no more issues. Our final action method looked like this:

public ActionResult GetCompanies(string query) {

    // Enable json serialization of the object.
    db.Configuration.ProxyCreationEnabled = false;

    var companies = db.Companies.Where(m => m.Name.StartsWith(query)).Select(c => new { c.Name, c.CompanyID });

    return Json(companies, JsonRequestBehavior.AllowGet);
}

.net MVC

.net mvc

Our .net MVC development team started working with the new Web API 2 controllers released with Visual Studio 2013, and quickly hit some important issues.

Routing and AttributeRouting and using Web API 2 controllers inside an Area in an ASP.NET MVC5 project

Currently, this IS possible. It was not possible with Web API and it seems like it was also not possible in beta, but this can be done with Web API 2 and MVC 5. I used the following configurations:

 // File: ~/Areas/API/APIAreaRegistration.cs
    using System.Web.Http;
    using System.Web.Mvc;

    namespace MySolution.Areas.API {
        public class APIAreaRegistration : AreaRegistration {
            public override string AreaName {
                get {
                    return "API";
                }
            }

            public override void RegisterArea(AreaRegistrationContext context) {
                context.Routes.MapMvcAttributeRoutes();
                context.Routes.MapHttpRoute(
                    name: this.AreaName,
                    routeTemplate: this.AreaName + "/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    }
 // File: ~/Global.asax.cs
    using System.Linq;
    using System.Web.Http;
    using System.Web.Mvc;
    using System.Web.Routing;
    using Newtonsoft.Json.Serialization;
    using WebMatrix.WebData;
    using AcumenSystem5.Models;
    using System.Threading;
    using System.Web.Optimization;

    namespace MySolution {
        public class MvcApplication : System.Web.HttpApplication {
            protected void Application_Start() {
                AreaRegistration.RegisterAllAreas();
                GlobalConfiguration.Configure(config => { // This HAS to be here. Having it last caused routing to not work.
                    config.MapHttpAttributeRoutes(); // This allows us to use AttributeRouting

                    // This sets JSON as the default return format and removes any circular references
                    var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
                    config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
                    var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
                    json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 
                });
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
                LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
            }
        }
    }

AttributeRouting and WebAPI Routing not working correctly and returning 404 Errors – .net MVC

After struggling with areas, I hit this issue when adding the Web API 2 controller to the root controllers folder. I discovered that the ordering of configuration mattered. So, like as shown in the Global.asax.cs above, the order needs to be as follows to work correctly:
protected void Application_Start() {

     // Full file code in example above
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(config => { // This HAS to be here. Having it last caused routing to not work.
            config.MapHttpAttributeRoutes(); // This allows us to use AttributeRouting

            config.Routes.MapHttpRoute( // This allows us to use conventional HTTP routing
                    name: "Name",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                ); ;

            // This sets JSON as the default return format and removes any circular references
            var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
            var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 
        });
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
    }

Hope this helps!

Check out our ASP.NET MVC to see what we can do for you.

For more information on .net MVC, click on the link below:

https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/asp-net-mvc-routing-overview-cs

Recently, while developing an application using Entity Framework, I ran into several compilation errors after adding an additional table to my database. Most notably was this error when trying to declare a couple of variables that had once worked before:

Compiler Error Message: CS1061: … does not contain a definition for … and no extension method … accepting a first argument of type … could be found (are you missing a using directive or an assembly reference?)

When searching around in my .edmx file for reasons as to why my relationships were not working, I ran into this message under the mapping details:

“Mappings are not allowed for an association over exposed foreign keys.”

I wanted to note that this message is not relevant to the issue at hand. After I solved the problem, I still received this message.

I quickly realized that the error had to do with the relationships between tables that I had previously established. When I had added the new table, I deleted the diagram from my .edmx file and updated the model from the database like I normally do when adding a new table. However, this time, Entity Framework did not properly regenerate the code associated with my database. Each property was stored as a class member within the entity class as expected, but my relationships were not. This was despite the fact that my .edmx diagram showed the relationships exactly as they should be.

After hours of Googling different phrases and errors, I ran into this ticket

As it turns out, this is a bug with Entity Framework inside of VS2012, and if your Visual Studio is out of date, you are likely to experience it. Because of this bug, if your .edmx file is nested within a project folder, Entity Framework will sometimes fail to generate code properly. Fortunately, the solution is much easier to implement than it is to find. You can do any of the following:

  • Update your Visual Studios here
  • Right click on the .tt file and select “Run Custom Tool”.
  • Drag the .edmx file out of the project folder.

Data Annotations

Summary:

You may have found code samples to generate your own Data Annotations handler for Web Forms.  You may have found incomplete or broken examples.  Stop.  Use this instead:  http://davalidation.codeplex.com/

You can do client validation in C# .Net using Data Annotations using this commonly referenced page by Gil Fink:

http://blogs.microsoft.co.il/blogs/gilf/archive/2010/04/08/building-asp-net-validator-using-data-annotations.aspx

From this article, it is important to note that the DataAnnotationValidator class MUST be in a Server Control project and referenced as an Assembly.  It is possible that this can be resolved by putting the class in App_Code and removing Assembly from your Register directive:

Create a new Web Server Control Project in your Solution.  Delete the automatically created class file and replace it with the contents from the web page listed above.

Reference the new Assembly/Project in your original Project.

 

If you try the App_Code technique you will need to change:

<%@ Register TagPrefix=”val” Namespace=”Validator” Assembly=”dotNetValidator” %>

to <%@ Register TagPrefix=”val” Namespace=”Validator” %>

Unfortunately, the App_Code technique didn’t work for me in Visual Studio 2010, which doesn’t want to make an App_code folder.

 

NOTE:  Here is similar code for client validation in VB:

http://adventuresdotnet.blogspot.com/2009/08/aspnet-webforms-validation-with-data.html#!/2009/08/aspnet-webforms-validation-with-data.html

    I have not tried this code and don’t know if it suffers from the same problem.  Perhaps it doesn’t in VB.net.

 

Unfortunately, the C# code doesn’t work because it tests the class Type in the Assembly instead of in the calling Web Project.  This causes an InvalidOperationException error in GetValidatedType. (The returned Type is null.)

This problem was noticed by Alex Ford on stackoverflow:  http://stackoverflow.com/questions/5600707/how-do-you-do-web-forms-model-validation. However, the posted solution has the same problem and wasn’t explained in detail.  But is does accurately describe the problem.  And ultimately, this code cannot get the PropertyName validation info necessary.  Stick with the original code.

Data Annotations Solution

So, how do you request a Type check against the calling Assembly?  I found this:  http://generally.wordpress.com/2007/06/01/typegettype-and-referred-assemblies/. Which accurately describes how to dictate the Assembly to search for the Type.

Referring back to Gil’s original article, this syntax was used but not explained.  The calling Assembly , and due to the brief code provided did not state the behaviour or syntax of SourceTypeName.

When using SourceTypeName, you MUST indicate the class name and the calling assembly like this:

<val:DataAnnotationValidator ID=”valID” runat=”server” ControlToValidate=”MyWebControlToValidate” PropertyName=”MyClassVariableToValidate” SourceTypeName=”MyClassToValidateAVariable, MyApplicationAssemblyName” /

 

Example:

<val:DataAnnotationValidator ID=”valID” runat=”server” ControlToValidate=”FirstName” PropertyName=”FirstName” SourceTypeName=”Person, MyWebApp”

 

For a completely different approach and a complete NuGet package: amanek.com/building-data-annotations-validator-control-with-client-side-validation/

To validate a control before submit: http://www.codeproject.com/Articles/185943/Validation-in-NET-Framework-4

See our Contact Page for more information!

On Dec 29, 2011,   Microsoft released a security update KB2656356 / MS11-100 for ASP.NET to address a potential Denial of Service vulnerability.  In the update, Microsoft introduced a limit to the number of data elements on an ASP.NET form.   The default limit is 1000 data elements.   Exceeding the limit will cause a ThrowIfMaxHttpCollectionKeysExceeded error.

After applying the patch to your webserver, forms that exceed the limit will generate the following error when posting:

System.Web.HttpException: The URL-encoded form data is not valid. —> System.InvalidOperationException: Operation is not valid due to the current state of the object.

at System.Web.HttpValueCollection.ThrowIfMaxHttpCollectionKeysExceeded()

at System.Web.HttpValueCollection.FillFromEncodedBytes(Byte[] bytes, Encoding encoding)

at System.Web.HttpRequest.FillInFormCollection()

To change the default MaxHttpCollectionKeys limit, add the following to your web.config file in the appSettings section and put a large value.  If it isn’t big enough, make it bigger:


<appsettings>

<add key=”aspnet:MaxHttpCollectionKeys” value=”2000″></add>

</appsettings>

References

Microsoft KB Article

December 2011 Out-Of-Band Security Bulletin Webcast Q&A

Stackoverflow Post

Keywords

.net dotnet appSettings asp.net

See our .Net Development Page for information on .net development consulting and outsourcing.