The Acumen software design blog provides you with helpful articles about C#.

Several web sites provide a good overview.

Official Microsoft C# Overview

C# Wikipedia

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

When our mobile app development team started working with Google Maps on Xamarin, we found that there were a lot of conflicting methods of initializing a map view for Android using Xamarin. Here is a step-by-step breakdown of what needs to be done to add Google Maps to your Android Xamarin application.

1. Update your Properties/AndroidManifest.xml file.

<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="17" />

<!– Google Maps for Android v2 requires OpenGL ES v2 –>
<uses-feature android:glEsVersion=”0x00020000″ android:required=”true” />

<!– We need to be able to download map tiles and access Google Play Services–>
<uses-permission android:name=”android.permission.INTERNET” />

<!– Allow the application to access Google web-based services. –>
<uses-permission android:name=”com.google.android.providers.gsf.permission.READ_GSERVICES” />

<!– Google Maps for Android v2 will cache map tiles on external storage –>
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />

<!– Google Maps for Android v2 needs this permission so that it may check the connection state as it must download data –>
<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />

<!– These are optional, but recommended. They will allow Maps to use the My Location provider. –>
<uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION” />
<uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” />

<application android:label=”MapTracker” android:icon=”@drawable/Icon”>
<!– Put your Google Maps V2 API Key here. –>
<meta-data android:name=”com.google.android.maps.v2.API_KEY” android:value=”get_an_api_key” />
<meta-data android:name=”com.google.android.gms.version” android:value=”@integer/google_play_services_version” />
</application>

This configuration first sets up the permission requests you will need to make to use Google Maps. First, change the uses-sdk attributes to set whatever minimum and maximum SDKs you plan to target. After that, you will need to get a Google Maps V2 API key [https://developers.google.com/maps/documentation/android/start#obtain_a_google_maps_api_key].

2. Add a map fragment to your activity’s .axml file.

Google Maps will need to use a fragment element to render. So, we will need to add this fragment using the following code:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />

This will add the blank fragment to your activity.

3. Initialize the Google Map object using the fragment.

I added the following properties to my activity:

private GoogleMap Map { get; set; }
private MapFragment MapFragment { get; set; }

I then created the following functions and overrides:

protected override void OnResume() {
this.IntializeGoogleMap();
base.OnResume();
}

private void IntializeGoogleMap() {
if (this.MapFragment != null) return;

this.MapFragment = (MapFragment)FragmentManager.FindFragmentById(Resource.Id.map);
this.Map = this.MapFragment.Map;

if (this.Map == null) return;

this.Map.MapLongClick += HandleLongClick;

this.CreateMarker(“Acumen Consulting”, new LatLng(38.626845, -90.340147));

this.UpdateLocation(this.GetCurrentLocation());
}

void HandleLongClick(object sender, GoogleMap.MapLongClickEventArgs e) {
this.CreateMarkerDialog(e.P0);
}

private void CreateMarker(string name, LatLng location) {
var marker = new MarkerOptions();
marker.SetPosition(location);
marker.SetTitle(name);
this.Map.AddMarker(marker);
}

protected void CreateMarkerDialog(LatLng location) {
var alert = new AlertDialog.Builder(this);

alert.SetTitle(“Title”);
alert.SetMessage(“Message”);

// Set an EditText view to get user input
var input = new EditText(this);
alert.SetView(input);

alert.SetPositiveButton(“Create”, (sender, args) => {
this.CreateMarker(input.Text, location);
alert.Dispose();
});
alert.SetNegativeButton(“Cancel”, (IDialogInterfaceOnClickListener)null);
alert.Show();
}
private LatLng GetCurrentLocation() {
var service = (LocationManager)GetSystemService(LocationService);
var criteria = new Criteria();
var provider = service.GetBestProvider(criteria, false);
var location = service.GetLastKnownLocation(provider);
return (location != null) ? new LatLng(location.Latitude, location.Longitude) : new LatLng(50, 3);
}

OnResume gets called whenever the user opens or returns to the app. This fires off the initialization for the Google Map (InitializeGoogleMap()). This should load the map in the application.

In InitializeGoogleMap(), you will see I added a couple other methods of mine to help you out. MapLongClick is when the user taps and holds on a location. This lets the user create a marker of their own on the map, giving them alert to ask for the title of the location. CreateMarker() allows you to cleanly create a new marker on the map by passing a title and coordinate. UpdateLocation() is also a wrapper function that allows you to pass a LatLng and update the map camera to that spot. You will see that it currently passes the value of GetCurrentLocation(), which uses the LocationManager to get the location of the user when they resumed the app.

I hope this helps you get started with using Google Maps on the Xamarin Android platform. If you have any questions, feel free to comment below!

Are you looking for Android Development services? Check out our Android Phone development page and contact us! Or, if you are looking for cross-platform solutions, we are also Xamarin Development experts.

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!