Category Archives: ASP.NET

QuickBytes: Visual Studio 2013 and JavaScript Debugging

Yesterday I found out something new about Visual Studio. Documentation indicates that it has been with us since VS 2012 (maybe earlier) but I encountered it yesterday.

I have a MVC4 project created in VS2010 and some CSHTML files have accrued some JavaScript crud in form of inline <script>…</script>. I usually refactor them out whenever I can but yesterday I was doing something else and wasn’t in a position to refactor the code at that point. So I tried to put in a breakpoint inside one of these script chunks and I couldn’t. So far, I’ve put breakpoints in the runtime page that comes up in Visual Studio’s Solution Explorer and they were are hit when executing in the browser, but yesterday I couldn’t even set a breakpoint.

After a little bit of ducking around I found that you could add the following line in the JavaScript to force the debugger where you want to start debugging and then continue with F10/F11 as usual

debugger;

I was initially indignant at Visual Studio that it ‘made’ me do this by default instead of allowing me to set the breakpoint. Looks a step backward, but then I realized that it was likely some setting in my Dev Setup is not right. I haven’t had a chance to investigate what’s not right, and I used the above hack to resolve my current issues. If you know of a way that kicks VS2013 into enabling breakpoints in inline JS code, do let me know.

Inline JS code is BAD and shouldn’t be used, period. But at times when you are prototyping you tend to take liberties, also not everyone in the team has 15 years of experience writing code, so cruft sometimes comes in. If VS is forcing my hand by making me write clean JavaScript code by default, that’s good, but I also want to know the ‘evil’ way to workaround Winking smile, Cheers!

Tagged , ,

QuickBytes: Visual Studio 2013 refuses to load some projects from a VS2010 solution

Last night I opened an ASP.NET MVC project in Visual Studio 2013 that was originally created in Visual Studio 2010 and found that 4 of the six projects in the solution were not loading. This solution was working in VS 2012 earlier so I was wondering what went wrong!

After goofing around I found the Output Window (the Window menu has been split up and moved around in VS2013 – It’s at Debug->Windows->Output; Who moved my cheese!!!). On selecting Solution from the ‘Show output from’ dropdown, I saw one such error for each project that was not loaded:

C:\Users\SKM\Documents\My Projects\[redacted].csproj : error  : The imported project “C:\Users\SKM\Documents\My Projects\[redacted]\.nuget\nuget.targets” was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.  C:\Users\SKM\Documents\My Projects\[redacted].csproj

That’s when it struck me the code dump was created using the Visual Studio Extension SolZip, which excludes the .nuget folder and thus Nuget Package Restore was failing. So the fix was easy:

1. Right click on Solution
2. Enable Nuget Package Restore
3. Reload each project or save->close->and re-open solution
4. Restore Packages from Nuget and you are done!

This is more of a reminder for myself!

Tagged , , ,

A Minor Gotcha when using jquery.mobile in MVC4

Yesterday I was playing around with the jquery.mobile package from Nuget and found an interesting gotcha.

I had a project from the MVC4 WebAPI template (note: WebAPI doesn’t have anything to do with it). I wanted to add Mobile support to it, so I installed the jquery.Mobile.Mvc package through the package manager console. The idea was I would use the ViewSwitcher framework to create mobile views with appropriate extensions. But to my surprise my edit views started getting buttons that looked like Mobile buttons.

image

I also got exceptions in jquery.mobile js module like the following.

image

I started scratching my head wondering why was the mobile rendering kicking in when I didn’t have any mobile views created?

Turns out, that when you install jquery.Mobile.MVC or the standalone jquery.mobile nuget packages, the new MVC4 Bundling and minification functionality rolls up all the js files together in the _Layout.cshtml. As a result jquery.mobile kicks in and tries to convert everything into mobile layout.

image

Possible Solution

There is an easy way out.

After you have installed jQuery.mobile under the Scripts folder create a ‘Mobile’ folder and move jquery.mobile* files there.

Before                                    After   

image image

This will ensure the regular views don’t load jQuery Mobile scripts.

Now update the _layout.Mobile.cshtml to point to the updated location for jQuery.mobile scripts

image

You can do the same for the css to if you want to keep a clear separation.

Hope this helps you some head scratching. To me it seems the Nuget Package should be updated. But I’ll leave the solution to the biggies Smile.

Tagged , , , , ,

Fun with @SignalR

This article has grown a little long in the tooth because SignalR has changed significantly since this was written more than a year ago.
I recently co-wrote a new article with Suprotim Agarwal in the DNC Magazine. If you are a .NET Dev I strongly recommend you subscribe to this Free Bi-monthly Magazine. The source code for the article is on Github Repository of DotNetCurry. You can see the sample live here.

Background

For the past several months I have noticed David Fowler, Damien Edwards, Phil Haack and a few other MS Techies I follow on twitter, tweet excitedly about a new framework called SignalR. I didn’t understand the excitement fully and to be honest didn’t try too hard to figure out.

Yesterday Scott Hanselman published this article and re-distributed a link to an article which he wrote end of August, 2011. After going through both, I really wanted to take a closer look at SignalR, and while trying to get his ‘…monkey typing Shakespeare…’ code working I finally had the ‘Ah ha!’ moment.

I just had to come up with this quick and dirty sample to demonstrate a use for SignalR and since I want the bragging rights for it, I am going to throw it up as is without bothering about the niceties of a Nuget package or sample.

UPDATE: I have deployed a working sample of this application at http://apps.apphb.com/funwithsignalr

The Idea

First time I saw Google Wave’s technology demo where they showed multiple people editing/reviewing the document at the same time, it blew me away. I was fascinated by it, but told myself I was too ‘javasciptically challenged’ to design such an Async client side framework.

When my tubelight** finally came on, SignalR was the obvious way to do it. Following is my first rough cut that as of now only syncs content. We’ll get to the fancy colored carets at a later point (hopefully in another article).

**In India one is referred to as a tubelight if something strikes late. Back in the days of non-electronic ballasts for fluorescent lighting, the tubes used to flicker for few seconds before turning on.

Please go through Scott’s articles or SignalR documentation to understand SignalR better. I make no attempts to explain SignalR here (partly because I know precious little and partly it’s such a fantastic framework that you need very little up front to get going).

Head-first into SignalR

To build a scaffolding for SignalR framework you can use plain html with a backend server side SignalR Hub class as Scott demonstrated. But I chose to start off with an ASP.NET MVC 3 project. (Actually my first attempt at ASP.NET MVC 4 using VS 2011 Dev Preview didn’t quite go so well, so I rolled back to the stable releases of ASP.NET MVC 3 on Win 7 using VS 2010).

Setting up a support app as an ASP.NET MVC 3 web project

image

image

I called it ‘FunWithSignalR’ and set it up as an Intranet Application

Adding SignalR to your project using Package Manager Console

image

The package manager console helps you download Nuget packages among other things. If you don’t have it visible you can bring it up from the above menu (in VS 2010)

SignalR is available as a nuget package and all you have to do to include is run the following command in the Package Manager Console

Install-package SignalR

The above command will get all the dependencies you need for SignalR and if your jQuery script files are not up to speed, will get the latest libraries for jQuery too (SignalR client uses jQuery hence the dependency check results in the upgrade). The output will looks something similar to

image

Update jQuery dependencies in Views\Shared\_Layout.cshtml by pointing to the most recently updated jQuery version. As per above image the latest version for me today is jquery-1.6.4.min.js because that’s the one the package manager installed.

Setup the Code First EF Model

We’ll setup a very simple code first model by adding one Entity called BlogPost in our Model folder.

image

Add the DbContext for the BlogPost.

image

Build the solution at this point.

Scaffold the Controller and UI

To use the default scaffold tooling that comes with MVC 3, right click on the Controllers folder and select Add –> Controller.

image

Select the Template, Model and Data Context values as shown above and click Add.

At this point you will have the scaffolding necessary to Add/Edit/Delete BlogPosts.

Adding the ‘Review’ Action

Open the BlogPostController and Copy paste the Get and Post action methods for the Edit action. Change Edit to Review as shown below.

image

Copy the Edit.cshtml and paste it in the View folder. Rename it to Review.cshtml

Update the Index.cshtml such that a ‘Review’ link comes up in the Index

image

Getting SignalR into the game

The Server Side

In your web project create a folder called SignalR (You can call it anything you want, in a real life project this as server side component and could very well reside in a dll of it’s own).

In the SignalR project add a class BlogHub.cs

Add the following code to it


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SignalR.Hubs;

namespace FunWithSignalR.SignalR
{
[HubName("blogHub")]
public class BlogHub : Hub
{
///
<summary> /// The method called from SignalR client (JS)
/// </summary>
///String Data
///Session ID: Used in this sample to track users
///A boolean value used in the example indicating
/// if incoming value should be appended or overwritten when sent back to
/// other clients
public void Send(string message, string sessnId, bool append)
{
Clients.addMessage(message, sessnId, append);
}
}
}

The Client Side

  • Open Review.cshtml and add the following script references

image

Note: json2.min.js is not packaged with the SignalR nuget. I have packaged it as a part of my code. I got it from Scott’s ‘Shakespeare demo’.

Note 2: /signalr/hubs is dynamically generated at runtime. So don’t worry if it gives a green squidgy right now. It works fine at runtime. Without this reference SignalR client won’t work.

  • Change the Html helper for the Post property from Html.EditorFor(…) to Html.TextAreaFor(…).
  • Add a hidden field to save the session Id in it (this maybe a security hole, need to investigate best practices)

<input id="sessinId" type="hidden" value="@Session.SessionID" />

  • Drop the following script in
<script type="text/javascript">// <![CDATA[
$(function () {
// Proxy created on the fly
var blog = $.connection.blogHub;
// Declare a function on the blog hub so the server can invoke it
blog.addMessage = function (message, sessnId, append) {

var sessId = $('#sessinId').val();

if (sessId != sessnId) {
if (append) {
$('#Post').append(message);
}
else {
$('#Post').val(message);
}
}
};

// Start the connection
$.connection.hub.start();

$("#Post").keyup(function (event) {
// Call the send method on the server

var sessId = $("#sessinId").val();
if (event.keyCode >= 65 && event.keyCode <= 122) {
if (event.shiftKey || (event.keyCode == 32)) {

blog.send(String.fromCharCode(event.keyCode), sessId, true);
}
else {
blog.send(String.fromCharCode(event.keyCode + 32), sessId, true);
}
}
else {
blog.send($("#Post").val(), sessId, false);
}
});
});
// ]]></script>

  • If you see closely this is pretty similar to Scott’s 11 lines of code to get a chat client going.

Changes I have made are:

1. Send message to server on KeyUp event of the Post text area, instead of an explicit button push

2. Send more meta information like the current sessionId and if the keystroke means an append action should take place at the client action of an overwrite action should take place at the client option.

Let it Roll

Run the application and navigate to the BlogPost Index

image

Add a new Post

image

Click on Review

image

Press Ctrl+N to start a new browser instance with the same page. Hit F5 so the session id (the text field next to Save button) changes. Arrange the two browsers side by side.

Type in one Post text area and watch the other one change almost simultaneously

image

As Scott says, Kabooom! brain explodes…..

In Conclusion

To wrap up, we saw how mind numbingly easy it is to use SignalR.

It’s a fantastic abstraction over various techniques available for persistent connections over http. Under the hood it can use websockets or longpolling depending on what’s available.

You can get infinitely creative with it and build fantastic collaborative ASP.NET apps using SignalR backend.

Some day (hopefully) in the near future, I would have overcome my javascript challenges and built a real collaborative editor with all the fancy bells an whistles of Google Docs.

Finally, David Fowler and team, a million thanks for such a fantastic framework. I am loving the ‘just works’ motto Smile. And Scott Hanselman for providing the ‘Aah ha!’ moment, without which I probably would have not given SignalR a look yet.

The Code

The code can be downloaded from here (size 844 KB) (skydrive). It is provided AS IS, with no warranties expressed or implied. You are free to use it without any attribution (but I would love it if you do feed my ego Winking smile).

I have now made the code available on bitbucket Mercurial repository. You can get it from here https://bitbucket.org/sumitmaitra/funwithsignalr

Update

The code in bitbucket now uses Google’s diff-match-patch implementation and is hence Apache licensed now.

Tagged , , , ,

Entity Framework and MS Web Stack of Love – First Steps

Things they didn’t show you at MIX keynotes Winking smile

Okay, so you saw the MIX keynotes and were really really impressed with what MVC, EF 4.1 Code First and Scaffolding could do for you and excitedly sat down to try and get your old lumbering enterprise app transformed using the Web Stack of Love. Couple of steps in and you start stumbling around. Visual Studio throws errors, things stop working and you are scratching your head as to where you went wrong! Well happened to me and I got lucky in finding the solutions quickly with help from the community. Here are the details.

Model First or Database First with EF 4.1

As mentioned above the first thing I tried to do was get my old lumbering enterprise app moved to the new MVC platform. Now when you have an enterprise platform you can’t throw it away with the accumulated data of last 5 years. So the easiest way is to go Database first, reverse engineer the database to generate your data model. Below are the steps you would follow

  • Create an ASP.NET MVC Web Application using the new project template
  • Create a generic Class library project
  • Add ADO.NET Entity Data Model file (edmx) to the class library
  • Generate model from DB Connection by connecting to the database. So far so good, no issues.
  • Now you add reference to your database project to the web project, copy the connection string over from the class library’s app.config to web app’s web.config, and build it. Everything builds fine.
  • You right click on the Controller folder and select Add Controller and the MVC tooling wizard comes up. You select your root entity name and ask it to generate the controller, Visual Studio whirrs for a while and bam! Error!

    —————————
    Microsoft Visual Studio
    —————————
    Unable to retrieve metadata for ‘Your.Data.Entity’. The type ‘Your.Data.Entity’ was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject.
    —————————
    OK  
    —————————

  • So what did you miss. Well EF is all code first so the old style generation of Entities (EF < v4) fail to work. If you read the last line of the error ‘… and does not inherit from EntityObject’ it gives you a hint.
  • What now? Manually edit everything? That would defeat the whole purpose of O-R mapping right? Well solution was provided by Julie Lerman (MS MVP) in her blog here. I’ll summarize here.
  • Go back to EDMX file and open the EDMX designer.
  • Right click and select ‘Add Code Generation Item’.
  • From the ‘Add New Wizard’ select ADO.NET DBContext Generator. You’ll see it gives a Model1.tt (t4 template) name. Change the name if you want to and select Add.

image

  • You will see under in the class library a node gets added with the t4 template. When you expand the node you have the C# (or VB) classes for your entities.
  • Now build and re-try scaffolding the Controller and things will go through smoothly.

Taming the SQL Compact 4.0 for Model First Development

Here is another workaround for people who want to do Model First Development. Since SQL Compact 4.0 was released out of band from Visual Studio and .NET 4.0 releases, somewhere in the tooling chain something broke. As a result, when you try to add a new Connection using Generate Database Wizard you don’t see SQL Compact 4.0. You see up to 3.5 only. So how do you get 4.0 goodness?

Refer to the selected answer from this stackoverflow.com thread

The answer is pretty to the point so I won’t repeat it here.

Trouble with Modernizer.js  (ver 1.7.x only on VMs)

If you run your dev environment on a VM (like VM Ware on Mac), IE9 disables hardware rendering and the modernizer.js that ships by default keeps throwing exception ‘Microsoft JScript runtime error: Unexpected call to method or property access’. This happens for every page and become very irritating quickly.
Solution is to go to www.modernizer.com and download their latest library (2.0.6 at the time of writing this). Remove the 1.7.x reference from your web application and add 2.0.x version. Voila!

 

That’s about it for now. I’ll put down more of my experiences as I go forward with my EF adventures. When I started this article we had only 4.1 now we have 4.2 CTP out Smile. Fast! Very Fast!

Tagged , , , , , , , , , , , ,
%d bloggers like this: