ASP.net MVC Archives - Page 2 of 5 - Digital Tool Factory blog ASP.net MVC Archives - Page 2 of 5 - Digital Tool Factory blog

The Digital Tool Factory Blog

How to use query strings in framesets with asp.net mvc 5 routing

The problem – I was working on a project that required frames – and I was trying to pass a querystring value to the frameset, as in /FramePage/?page=/SomePageOffSite.aspx – my first thought was to just pass the url of one of the frames to the frameset page as a string.  I made the model for the view a string and attempted to pass it via the usual way in the controller, i.e.

return View(“MyFramedInPage.aspx”);

My thought was that I could just use the Model property as the url, as in

frame src=”@Model” name=”main” noresize scrolling=”auto” marginheight=”0″ marginwidth=”0″

However, whenever I did that MVC would try to find a view with the url of the string (in this case SomePageOffSite.aspx – which did not exist) I was passing in the model.  I eventually figured it out – there is a feature I never use on return View – to wit – you can redirect it to another view simply by passing in the view name (I always used the redirect option) – therefore you can’t ever use a model as a string.  Lesson learned.


11
Feb 15


Written By Steve French

 

Five things should should know about the new asp.net identity membership system

I’m trying my first asp.net mvc 5 project, which more or less forces you to use the new asp.net identity framework for membership. It’s in the using Microsoft.AspNet.Identity namespace.

While a vast improvement over the original asp.net membership – I do not see any massive benefit over the MVC 4 Simple Membership system.  Here are 5 things you need to know about the asp.net identity system before you upgrade

  1. The ID column is stored as a guid, and not an int – One of my favorite things about the simple membership system was being able to use int columns for ID – no more of that
  2. In the default project, all of the membership tables will be stored in Local DB, even if you change the connection string in the web.config
  3. MVC introduces a peculiar (to me at least) way of creating the Database tables for membership in the LocalDB – in the IdentityModel.cs file in the Models folder, you will see the following bit of code

    public class ApplicationDbContext : IdentityDbContextWithCustomUser
    {
    }

    this will create the following tables in the Local DB

    • ASPNetUsers
    • ASPNeRoles
    • ASPNeTokens
    • ASPNetUserClaims
    • ASPNetUserLogins
    • ASPNetUserManagements
    • ASPNetUserRoles
    • ASPNetUserSecrets

    if you are running a separate database you will find it quite confusing to get the membership and the other data in the same context (the error message are rather opaque.  To fix the matter, add in the following code in your regular data context class and comment out the ApplicationDbContext : IdentityDbContextWithCustomUser in IdentityModel.cs

    public DbSet ApplicationUsers { get; set; }
    public DbSet Roles { get; set; }
    public DbSet Tokens { get; set; }
    public DbSet UserClaims { get; set; }
    public DbSet UserLogins { get; set; }
    public DbSet UserManagements { get; set; }
    public DbSet UserRoles { get; set; }
    public DbSet UserSecrets { get; set; }

    and everything will both be in the same database and the same data context.

  4. The quick and easy way of getting the User ID (comparable to WebSecurity.CurrentUserID is User.Identity.GetUserID() – that will return the guid of the user.
  5. It is pleasantly integrated with entity framework code first, and will probably be a positive feature over time.

05
Oct 13


Written By Steve French

 

How to track outbound links in the new version of Google Analytics

So the Gods of Google have gone and changed their basic Google Analytics code to something that works slightly better, and now your outbound link tracking code doesn’t work.

Here is how you fix that – first make sure you have the most recent (as of July 2013 Google Analytics code, it looks something like this)

<script>
(function (i, s, o, g, r, a, m) {
i[‘GoogleAnalyticsObject’] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, ‘script’, ‘//www.google-analytics.com/analytics.js’, ‘ga’);

ga(‘create’, ‘UA-XXXXXXXX-1’, ‘mydomain.com’);
ga(‘send’, ‘pageview’);

var clientId = ”;
ga(function (tracker) {
clientId = tracker.get(‘clientId’);
});
</script>

 

If it does not look more or less like that, then do not use the code below.

Now make the links you want to track look  like this

<a href=”http://www.SomeOtherDomain.com” onClick=”ga(‘send’, ‘event’, ‘Outbound Links’, ‘click’, ‘http://www.SomeOtherDomain.com’)” target=”_blank”>www.SomeOtherDomain.com</a>

Note the onclick event – that is the key thing.

 

Where can you see the result?  They do not show up as page views  (like they used to) instead they are treated as “Events”.  To see them, go to (in the main Google Analytics screen)

1.  Standard View

2. Content

3.Events

4. OverView

5. Event Label

And there you are.  Not exactly intuitive, but not bad.

 


08
Jul 13


Written By Steve French

 

How to fix the infamous “Unable to cast object of type ‘System.Int32’ to type ‘System.String’ error in asp.net mvc

The Problem

You have created a lovely model in asp.net mvc 4, using Entity Framework and a whole host of attributes.  One of the properties of your model looks like this

[Required]
[Display(Name = “Expiration Month (MM)”)]
[StringLength(2,ErrorMessage = “You must enter two digits”, MinimumLength = 1)]
[Range(1,12, ErrorMessage = “You must enter a valid month”)]
public int ExpirationMonth { get; set; }

That yields an error of

Unable to cast object of type ‘System.Int32’ to type ‘System.String

When the form is submitted, but not when the object is created (which is a bit odd)

The Cause

It turns out that you cannot use the StringLength data attribute on an int data type.  You would think you could since all you are actually interested in with that data attribute is the number of digits, but the data gods have decreed that you can’t.

The Solution

Just comment out StringLength and use the Range Attribute.


17
Jan 13


Written By Steve French

 

How to fix problems with data cacheing in ASP.net MVC 4, SignalR and Entity Framework

The Problem

I was using the wonderful SignalR libraries to create a status window (I have a VERY long running process in my new Data Hammer project, it takes about 15 minutes to run) and I need to inform the user on where the process is at any given time.  My original code looked like this

public class Chat : Hub
{
public void Send(int id)
{

DataHammerContext ctx = new DataHammerContext();

while (true)
{

string strName=ctx.ProcessSteps.Find(id).Name;
Clients.All.addMessage(“Status: ” + strName);
Thread.Sleep(1000);
}
}
}

And this would always display the same status, quite maddening.

The Cause

After much investigation I realized that my model of how Signal R works was flawed.  For whatever reason (by which I mean too long to go into here) the data context does not update with the while loop.

The Solution

The fix is simple, just recreate the data context every time and everything works like it should – here is a sample of the updated code.

 

public class Chat : Hub
{
public void Send(int id)
{

 

while (true)
{

DataHammerContext ctx = new DataHammerContext();
string strName=ctx.ProcessSteps.Find(id).Name;
Clients.All.addMessage(“Status: ” + strName);
Thread.Sleep(1000);

}
}
}


16
Jan 13


Written By Steve French

 

How to configure wildcard routing in asp.net mvc 4

The Problem

You are trying to configure Widlcard routing (i.e. something like http://domain.com/SomeUserName/) and find it problematic.

The Cause

That is largely by design – wildcard routing is resource intensive and rarely needed.

The Solution

If you want to do it anyway, use the following routes

routes.MapRoute(“Default”, “”, new { controller = “Home”, action = “Index”, id = UrlParameter.Optional });
routes.MapRoute(“CatchAll”, “{*id}”, new { controller = “Home”, action = “Handle”, id = “” });

Things to note

 

  • The Catch-All route is AFTER the home route
  • The syntax is *id – this will ensure that the value of ID is sent to the “Handle” action
  • The purpose of this route is to throw control to the “Handle” action with the appropriate value – Handle must be set up to use that value.

 

Okay, after some more digging (and some failed integration tests) here is what you have to do

Add in the following routes

routes.MapRoute(“Handle”, “Home/Handle/{id}”, new { controller = “Home”, action = “Handle”, id = “” });
routes.MapRoute(“User”, “{*id}”, new { controller = “Home”, action = “Index”, id = “” });
routes.MapRoute(“Default”, “{controller}/{action}/{id}”, new { controller = “Home”, action = “Index”, id = UrlParameter.Optional });

And then create an action called “Handler”, and change your Index action on your home controller to look like this

public ActionResult Index(string id=””)
{
if (!string.IsNullOrWhiteSpace(id))
{
return RedirectToAction(“Handle”, new {@id = id});
}
else {
return View();
}

What does this do?  It routes all wildcard traffic to your Index controller, which then hands it off to the “Handle” Action.  You would think that you could just hand everything off to the Handle action, but if you do that, then your Index action becomes inaccessible,  and in some circumstances you get a recursive loop where the handle action is called endlessly.  That does show an interesting error screen though.

One annoying side effect of this course of action is the need to map out each and every route explicitly, otherwise the wildcard route will pick it up and hand it off to the “Handle” action, which will take it somewhere where you do not want it to go.


04
Jan 13


Written By Steve French

 

How to fix problems with entity framework decimal precision

The Problem

You are attempting to change a database column of type decimal from a precision of two decimal place to one decimal place via data annotations, and there does not seem to be a good way to do it.

The Cause

There isn’t a good way to do it.

The Solution

However, there is at least one non-elegant way to do it – in your OnModelCreating code in your data context, enter in the following piece of code

protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
modelBuilder.Entity().Property(xx=>xx.Handicap).HasPrecision(12, 1);
base.OnModelCreating(modelBuilder);

}
The “HasPrecision” part is the key – the second parameter is the number of decimal places to use


12
Dec 12


Written By Steve French

 

How to fix problems with asp.net mvc 4 javascript bundling

The Problem

You are using the new JavaScript bundling and minification features in asp.net mvc 4, and some of your JavaScript files are not being included

The Cause

The minification process – in it’s strange wisdom, does not include .min files when it bundles.  Therefore something like

.Include(“~/Scripts/jHtmlArea-0.7.0.min.js”)

will not be included, leading to JavaScript errors.

The Solution

Just use the non-minified version of the script file –

.Include(“~/Scripts/jHtmlArea-0.7.0.js”)

will work just fine – it seems that the asp.net mvc bundler prefers to do it’s own minification.


04
Dec 12


Written By Steve French

 

How to fix the “Unable to launch the visual studio development server because port 9452 is in use” error

The Problem

You are coding away, Visual Studio locks up for one of it’s many reasons, and reopen your project and run it again. You then get the “Unable to launch the visual studio development server because port 9452 is in use” error

The Cause

When Visual Studio crashed, the Web Server did not, so basically it thinks you are trying to run two instances at the same time, which is not allowed.

The Solution

Open up the process manager, go to the Processes tab, and select “WebDev.WebServer40.exe” and click “End Process”. Then try running your project again. Visual Studio will now start the project fresh and the problem should go away.


01
Aug 12


Written By Steve French

 

How to fix problems with Ajax Page Caching in asp.net mvc 4

The Problem

'Error' photo (c) 2008, Nick Webb - license: http://creativecommons.org/licenses/by/2.0/You’re using the otherwise awesome ASP.net MVC 4 and you can use an ajax function once, via the @Ajax.ActionLink tool, but you try it again, and it does nothing.

The Cause

For whatever reason the browser thinks it is a cache page and pulls it from the cache – I’m not 100% sure of this.

The Solution

Just add a DateTime.Now as a parameter, this forces the browser to send the data every time.


28
Jun 12


Written By Steve French

 




Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.