.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

OneLogin is a great service that allows companies to use Single Sign On to allow their employees or customers to access a multitude of other applications using a single username and password. We are currently using it to do just that for a client – allow their customers to sign into their WordPress platform and other linked applications using just its authentication. Once the user is in WordPress, we can use the Embedded API and the Launch API offered by OneLogin give them a customized portal that utilizing single signon. Here’s how we did it on a high level.

Solution:

  1. Configure your application and your users. To attach an application to a user, open up your app.onelogin.com interface. In the top taps, go to “People”. Click “edit” next to the user you wish to add an application for. Then, to go to “Apps” tab for that person and click “add app“.
  2. Get the Embedded API security token. This can be found at https://app.onelogin.com/embedding. Check the “Embedding API can be used” checkbox and submit the form. If a token isn’t shown, click “Generate a new token“.
  3. Download and parse the apps XML file from OneLogin. The endpoint for this is https://app.onelogin.com/client/apps/embed2?token={security token}&email={email for requested user}
  4. Use the ID from the parsed XML to create a Launch API link. The URL for a Launch API link is https://app.onelogin.com/launch/{app id}

All you need to do is supply your security token to the class, pass the email to get_apps_for_user() function, and pass your HTML templates to the toHtml() function. The example on that GitHub page will show you how to use this inside of WordPress. Feel free to comment if you have questions or comments.

 

Want to see what kind of website or WordPress integrations we can offer your company? Check out our Website Development page and contact us!

Dumping a MongoDB database is done using the “mongodump” utility in the command prompt. This dump creates a binary export of the database. This export can be restored using the “mongorestore” utility.

A basic dump of a local MongoDB database can be code as follows:

mongodump --db mymongodatabase

To dump a specific collection, simply specify the collection:

mongodump --collection collection --db mymongodatabase

Also, you can dump the database to a specific server location:

mongodump --db mymongodatabase --dbpath /var/mypath/mongodumps

We wanted to create a utility that would allow our client to backup their WordPress-integrated MongoDB database using an admin utility. To do this, we built a PHP class that allows us to enter the database name, the dump location, and go. This tool also ZIPs the binary files for us, allowing us to conserve disk space and contain each dump in one file. You can access this class here: https://github.com/KerryRitter/MongoDumper

A basic usage of this class is done as follows:

$dumper = new MongoDumper("/var/mypath/mongodumps");
$dumper->run("mydb", true); // 'true' shows debug info

This will dump the local ‘mydb’ database to /var/mypath/mongodumps/mydb_[timestamp].zip and display the shell output and various debug info. To remove the debug info, remove the “true” parameter in the “run” function call.

To restore, unzip the BSON and JSON files and upload to a folder on the server with the name of the database you wish to restore to. For example, if you wish to restore “mydatabase”, you will need to put the files in a path such as /var/mypath/mongodumps/mydatabase. To restore the database, use the following command in your command prompt:

mongorestore /var/mypath/mongodumps/mydatabase

There are a number of options available for restoration that you can find in the documentation: http://docs.mongodb.org/manual/tutorial/backup-with-mongodump/

Please note that the published MongoDumper class is the simple core; there are security concerns with using shell_exec that need to be addressed before you use it on a publicly accessible site. If there is an error given by the dump or the dump did not work, make sure to check the MongoDumper.php file and the backup folder’s permissions.

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.

Our ecommerce team was having trouble with Magento cron jobs, so we researched the various mechanisms to test and debug them.  The jobs did not run at the expected time and we couldn’t see why.

Magento

The Magento cron jobs run as apache.  You can see them by typing:

crontab -u apache -l

You can edit them with

crontab -u apache –e

 

To see if they are running without errors:

tail /var/log/cron

 

Also, the results of cron jobs are emailed to your apache user.  You can check that account with:

mail -u myApacheAccount

If you have problems with the cron job permissions, you will see them in the cron log or the mail messages.

 

References

http://www.adminschoice.com/crontab-quick-reference/

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

 

SQL

In his excellent book, Star Schema, Christopher Adamson begins Chapter 7, “Hierarchies and Snowflakes,” with the following language:

It is possible to describe a dimension table as a series of parent-child relationships among groups of attributes. Days make up months, months fall into quarters, and quarters fall into years, for example. This chapter explores these attribute hierarchies and their implications for the design and use of dimensional databases.

Page 147. This understanding appears fully consistent with the definition of found in MSDN:

Attribute hierarchy

An attribute hierarchy is a hierarchy of attribute members that contains the following levels:

  • A leaf level that contains each distinct attribute member, with each member of the leaf level also known as a leaf member.
  • Intermediate levels if the attribute hierarchy is a parent-child hierarchy.
  • An optional (All) level (IsAggregatable=True) containing the aggregated value of the attribute hierarchy’s leaf members, with the member of the (All) level also known as the (All) member.

http://msdn.microsoft.com/en-us/library/ms144884.aspx
It may seem intuitively obvious what the phrase “Attribute Hierarchy” means, and the descriptions given by Mr. Adamson and the definition given in MSDN probably fit neatly with your intuition. If you follow your intuition, however, other documentation for Microsoft SQL Server Analysis Services (SSAS) becomes confusing, and you are unlikely to leverage features of the product that will make it more useful and responsive.

Microsoft Documentation

To cut to the chase, what you need to know is this: In most of Microsoft’s documentation (other than the definition shows above) and within the user interface of Business Intelligence Development Studio (“BIDS”), “attribute hierarchy” means a hierarchy with exactly one attribute. Intuitively, a hierarchy with only one attribute may not seem like much of a hierarchy at all to most people. By default, however, it does contain two levels: The All level and the level under the All level with (by default) the same name as the attribute.

MSDN defines an additional type of hierarchy, the “user-defined hierarchy.” It is defined in the following way (Attribute Hierarchies, from MSDN attributes and attribute hierarchies) :

User-defined hierarchy

A user-defined hierarchy is a balanced hierarchy of attribute hierarchies that is used to facilitate browsing of cube data by users. User-defined hierarchies do not add to cube space. Levels in a user-defined hierarchy can be hidden under certain circumstances and appear unbalanced.

Clearly, this definition contemplates the possibility of more than two levels created from more than one attribute, and this definition of “user-defined hierarchy” seems to be the same as our intuitive understanding of “attribute hierarchy.” But they are in fact different within the Microsoft world.

So… Why should we care?

Why do we care? Because in SSAS, individual attributes contained in dimensions have properties that only make sense if a stricter definition of attribute hierarchy is used–a definition that refers to hierarchy with exactly one attribute level and (usually) an All level. Look at the properties window for a single attribute contained in a dimension:

SSAS Screen Shot

Notice that there are several properties of the attribute that have “Attribute Hierarchy” contained within them and that these properties are not properties of a user-defined hierarchy. The description contained in gray-highlighted box at the bottom of the properties window only makes sense if “attribute hierarchy” and “user-defined hierarchy” mean different things.

Developers define user-defined hierarchies in the “Hierarchies” panel of the Dimension Structure tab.

SSAS Screenshot SQL

In conclusion, be aware that when you are reading Microsoft documentation and using the SSAS interface, “attribute hierarchy” and “user-defined hierarchy” are two very distinct things, and failing to understand this will result in confusing properties that only apply to attribute hierarchies to user-defined hierarchies.