Archive for September, 2015

IE and the CSS margin-top tag

Oh, the joy of web design. Chrome was behaving as it should, but Internet Explorer 11 wasn’t. I had a header div element on my body, but the background from the main page was showing above the header. I was using a negative margin along the top, like so:

 margin-top: -10px;

What worked for me was modify the units for the margin-top statement to “vh” instead of “px”:

 margin-top: -1.4vh;

This did throw off the Chrome alignment slightly, and it wasn’t exactly vertically centered as it was before, but it was pretty close, and I was happy enough with the result to not throw things at the screen.

Advertisements

Leave a comment

Data not refreshing in MVC view with IE, but was in Chrome

I had some basic code binding to my model, and here is a beautiful snippet:

@using (Html.BeginForm("Manage", "Account", FormMethod.Post)) {
        <label>Select User</label>
        <select id="users" onchange="getUser()">
            <option selected="selected" value="0">Add User</option>
        </select>
        @Html.LabelFor(m => m.UserName)
        @Html.TextBoxFor(m => m.UserName)
       <input type="submit" id="save" value="Save" />
}

Yes, I used an HTML select list in MVC – don’t judge me.

I also had some jQuery calls. The first would populate the awesome (and easy to use) select control, and the second would be called when a user selected an item in my awesome (and easy to use) select list:

    function getUsers() {
        $.ajax({
            url: '@Url.Content("~/Account/Users")',
            method: "GET",
            dataType: 'json',
            async: false,
            success: function (data) {
                var options = $("#users");
                $.each(data, function (i, val) {
                    options.append($("<option />").val(val.UserId).text(val.UserName));
                });
            }
        });
    }
    function getUser() {
        $.ajax({
            url: '@Url.Content("~/Account/GetUser")',
            method: "GET",
            dataType: 'json',
            data: { 'userId': $("#users").val() },
            async: false,
            success: function (data) {
                $("#UserName").val(data.UserName);
            }
        });

With Chrome, everything was fine, and there was much happiness abounding at my stand up desk. But when using IE, the Sad Clown of Life paid a visit, and neither my select list nor my fields were updated after I would choose a record, update it, and click the save button.

The problem was that IE was caching my data. I understand, it was great data, but sometimes, you just need to let go. The key was adding the “cache: false” tag to the jQuery function, like so:

    function getUser() {
        $.ajax({
            url: '@Url.Content("~/Account/GetUser")',
  cache: false,
  …
        });

Success – I got data in IE.

,

Leave a comment

MVC CheckBox returning “true,false”

Have you noticed that if you create a CheckBox in an MVC view like so:

@Html.CheckBox("SendPassword")

And then check the value of this control in the controller after you have checked it:

Request["SendPassword"]

You see this instead of “true”:

true,false

You can handle this a couple of ways, but I chose to roll with the punches. I receive the value as a string and if the value is “true,false”, then that means true:

string result = Request["SendPassword"].ToString();
bool isChecked = result.Contains("true,false");
if (isChecked) {
 // Stuff
}

,

Leave a comment

Inconsistent accessibility error in MVC

I had a fairly simple scenario involving MVC and EF. I was implementing an interface like so:

    public class EntityDetailRepository : EntityRepository<EntityDetail>, IEntityDetailRepository {
  public EntityDetailRepository()
   : base() {
  }

However, for my troubles, I was getting this error:

Inconsistent accessibility: base interface ‘Yada.IEntityRepository<EntityDetail>’ is less accessible than interface ‘Yada.IEntityDetailRepository’

The interfaces were declared “public”, so the compiler was obviously deranged, and close to going all HAL on me. Luckily, before it could do that, I discovered that the underlying type, EntityDetail, was not:

    class EntityDetail {
        public int ID { get; set; }
    }

See, no “public”. After I made the type public, all was well:

    public class EntityDetail {
        public int ID { get; set; }
    }

,

Leave a comment

Updating the ELMAH database for handled exceptions

I had installed ELMAH via NuGet into my MVC application. I wanted to log errors to the database, so my next step was to download the scripts to create the SQL Server objects at https://code.google.com/p/elmah/downloads/detail?name=ELMAH-1.2-db-SQLServer.sql. After running the scripts in my database of choice, I had in my possession an awesome new database table and a few stored procedures.

Then I dug into the web.config to add to tell ELMAH to log unhandled exceptions to this new table. That last property, “applicationName”, is the value that is stored in the “Application” column when ELMAH logs an unhandled exception.

  <elmah>
    <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="DefaultConnection" applicationName="ScottsApp" />
  </elmah>

For handled exceptions, ELMAH comes with the handy ErrorSignal class to handle that exception and, in my case, store it in the database:

try {
     // Code that I'm sure would never, ever cause an error. But just in case…
} catch (Exception ex) {
     ErrorSignal.FromCurrentContext().Raise(ex);
}

But I also wanted to use the ELMAH table, ELMAH_Error, to act as a logging store for certain events such as invalid logins. So I created a method using the Entity Framework library:

        public void LogError(string errorType, string message, string user, string stackTrace) {
            DbContext o = new DbContext(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
            string app = ConfigurationManager.AppSettings["applicationName"];
            List<object> os = o.Database.SqlQuery<object>("exec ELMAH_LogError @ErrorId, @Application, @Host, @Type, @Source, @Message, @User, @AllXml, @StatusCode, @TimeUtc", new SqlParameter("@ErrorId", Guid.NewGuid())
                , new SqlParameter ("@Application", app )
                , new SqlParameter ("@Host", System.Environment.MachineName)
                , new SqlParameter ("@Type", errorType)
                , new SqlParameter ("@Source", app)
                , new SqlParameter ("@Message", message)
                , new SqlParameter ("@User", user)
                , new SqlParameter ("@AllXml", stackTrace)
                , new SqlParameter ("@StatusCode", "0")
                , new SqlParameter ("@TimeUtc", DateTime.Now)
                ).ToList();
        }

I used a DbContext object, and then called the Database.SqlQuery method to call the ELMAH-created stored procedure, ELMAH_LogError. I had a problem where code similar to that above didn’t execute. No error, just nothing happened. The problem in my case is that I was missing the ToList() call. I actually needed a call to execute the query I had built with “SqlQuery”, and an action like ToList() did just that.

Notice that the SqlQuery format of:

 exec spName @paramName, @paramName, ...

If you don’t properly separate the parameters with commas, you’ll see this error:
Procedure or function ‘ELMAH_LogError’ expects parameter ‘@ErrorId’, which was not supplied.

Don’t let that happen to you.

Leave a comment

MVC – JavaScript runtime error: ‘$’ is undefined

I was getting this error when I tried to add some jQuery code to a View, something really simple like this:

    alert($("#users").val());

Blammo – the “JavaScript runtime error: ‘$’ is undefined” message. Luckily, it was straight-forward to fix. I simply went into the “_Layout.cshtml” file in my Views\Shared folder and added “@Scripts.Render(“~/bundles/jquery”)” inside the <head> tag:

    <head>
        …..
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/modernizr")
    </head>

,

Leave a comment

The requested page cannot be accessed because the related configuration data for the page is invalid

I needed to test a new web site locally before I sent it off to the IT team for further deployment work. I didn’t have IIS installed on my Windows 8 machine, so I installed it and I was happy.

After successfully creating my marvelous site (consisting of a grand total of one ASPX page), I published it via the handy dandy publish window. And off the files went, to my brand new local instance of IIS. And I was greeted with an error page that hated me:

 “The requested page cannot be accessed because the related configuration data for the page is invalid.”

The line in question was:

 <modules runAllManagedModulesForAllRequests="true"/>

Once again, Stack Overflow was my friend. And it turned out, I hadn’t installed ASP.NET. Yes, I could see how that could be a problem. So I ran this command:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis -I

Bing bang, it worked. Happiness in Scott land.

Leave a comment