Archive for the ‘.net’ Tag

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!

How to make ASP.NET GridView emit proper tags

I know I know, ASP.NET WebForms is a passe and MVC is the king of the ring, but if you, like me, still have to work with legacy WebForm components then more often than not you’ll need to use the GridView control. When using GridView control if you want to use jQuery and jQuery plugins to jazz up your grid, you’ll hit a wall because the GridView control emit straight <td> <tr> instead of the more ‘compliant’ <thead> <tr> <th> and <tbody> <tr> <td>

As a result most jQuery plugin’s don’t work. I was despairing at this thought when I came across this article on www.dotnetcurry.com

The article demonstrates tips and tricks with GridView, but it had the hidden gem of how to get the GridView to render <thead> tags. Recipe is simple, handle the GridView’s PreRender event and put the following code in

if (myGridView.Rows.Count > 0)
{
 myGridView.UseAccessibleHeader = true;
 myGridView.HeaderRow.TableSection = TableRowSection.TableHeader;
}

With this done, the whole wide world of jQuery goodness opens up. In the following example I use the DataTables plug-in to add a nifty search functionality and frozen header and vertical scrolling.

Example

We will create a new ASP.NET web application and use the DataTables jQuery plugin to jazz up our grid view control.

Step 1 – Getting Started

Fire up Visual Studio (whichever version you have) and create a new ASP.NET Web Application

image

Step 2 – Finding a Data Source (ignore this and Step 3 if you already have a data source handy)

In Solution Explorer, right click on App_Data folder and select Add Existing Item. I have SQL Server compact edition installed which installs the NorthwindDB.sdf file in the following folder location

C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0\Samples\Northwind.sdf

If you don’t have Compact Edition 4.0 you can download it from here

Step 3 – Connecting to Northwind database

Bring up Server Explorer and double click on Northwind.sdf to connect to it. Change the header to something like “Products From Northwind Database” and remove the other default paragraphs.

Step 4 – Add the GridView

Double click on Default.aspx to open the designer. Switch to Split or Design mode and Drag and Drop the GridView control

Step 5 – Do the magic to render proper table tags

Change the Name of the gridview to jqDemoGridView. Add a PreRender event handler and place the above code in the event handler to ensure the GridView emits proper table tags in HTML.

Step 6 – Get the scripts

a. If you are using derivatives of Visual Studio 2010 your project should come with jQuery included by default under the Scripts folder. I got version 1.4.1 with my project. You can get the latest version from here and place it in your Scripts folder.

b. Next we will get the DataTables plugin scripts from here (~8Mb).
Download the zip file and extract it. Open Windows Explorer and navigate to the extracted folder. There should be three folders from the zip, examples, extras and media.

c. From the media folder select the images and js folder and press Ctrl+C to copy them
Go to Visual Studio, select the Scripts folder in Solution Explorer and press Ctrl+V to add the folders.

d. From the media\css folder select all the css files and paste it in Solution View’s Styles folder.

e. From the examples\example_support\themes\smoothness folder copy the jquery-ui-1.8.4.custom.css and the images folder. Paste is under Sytles folder

f. Exclude the jquery.dataTables.js, jquery.js and jquery.dataTables.min.js.gz files. The rest of the files are enough. (the .min.js version is minified meaning it doesn’t have any kind of whitespaces and reduced in size as much as possible. It’s not at all readable so if you want to go through the js to understand it, use the non-minified version) Your solution explorer should looks something like the following.

image

Step 7 – Connect to Data Source

I will connect to the above data using the Entity Data Source. You can select your own data connection mechanism. Basically the idea is to get the GridView populated with enough data that requires a vertical scrollbar. If you are using SQL CE 4.0 like me follow along.

a. Right Click on Solution Explorer and Select Add New Item. Select Data from the Installed Templates and ADO.Net Entity Data Model. Name it NorthwindModel.edmx

image

b. Select the default ‘Generate from Database’ and click Next.

image

c. If Northwind.sdf connection was open it will select it by default and the next screen should look something like the following.

image

d. The Wizard will connect to the DB and load up the schema. Select all the tables and click Finish.

image

e. Save solution and do a ‘Build All’.

Step 7 – Tie the GridView to the data source

a. In the designer click on the GridView smart tag and bring up the Choose Data Source Dialog

image

b. Click Ok to bring up the Configure ObjectContext wizard. It should select the NorthwindEntites connection it created while building the data source by default. If you named it differently in Step 6.c. select the name that you gave it. The DefaultContainerName will come up automatically once you select the Named Connection. Click Next.

image

c. Select the EntitySetName (table) that you want to show. I’ve selected the Products table and opted to show all the columns. You can pick and choose. As of now we are not doing any Inserts/Updates or Deletes, keep them unchecked. Click Finish

image

If you run your application at this point you will see the grid populated with data from the products table. Just for kicks right click on the browser to bring up source, you will see the <thread><tr><th> rendering for the table in the final HTML. So far so good.

Step 8 – Bring in the jQuery Goodies

Here comes the fun part now. Let’s tie up our grid with jQuery and datatables goodness.

a. Open Site.Master and drag and drop the demo_table_jui.css from the Scripts\css folder on to the header area

b. Open the Default.aspx and in the BodyContent area, drop the jQuery script file and the jquery.dataTables.min.js file.

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="Scripts/js/jquery.dataTables.min.js" type="text/javascript"></script>

c. Add the following script to apply the plugin to the GridView

<script type="text/javascript" charset="utf-8">
 $(document).ready(function ()
 {
   $('#<%= jqDemoGridView.ClientID %>').dataTable({
           "bJQueryUI": true,
           "bPaginate": false,
           "bLengthChange": false,
           "bFilter": true,
           "bSort": true,
           "bAutoWidth": false,
           "sScrollY": 300,
           "sScrollX": "100%",
           "sScrollXInner": "110%"
      });
 });
</script>

The dataTable method is taking an object as a parameter. The object is defined in JSON. Let’s look at each parameter and try to get what it is
i. bJqueryUI : A boolean parameter indicating if JqueryUI should be used to beautify the grid. We set it to true
ii. bPaginate: A boolean parameter indicating if pagination should be enabled. We set it to false to force vertical scrollbars
iii. bLengthChange: A boolean parameter (not sure what it does, it’s set to false in our code).
iv. bFilter: A boolean parameter indicating if Filtering should be enabled. We set it to true.
v. bSort: A boolean parameter indicating if Sorting should be enabled. We set it to true.
vi. bAutoWidth: A boolean parameter indicating if datatables should try to set the width of the columns. We set it to false
vii. sScrollY: A integer parameter indicating the fixed height of the table. Scrolling is enabled after rows of data exceed this height.
viii. sScrollX and sScrollXInner: Parameters that help enable horizontal scrolling.

For a complete reference to possible parameters refer to DataTables’ excellent documentation on their site. A quick reference guide is available here
Clean up the Default.aspx by removing the default messages and run the application.

Lo and behold!

image

Step 9 – Playing around with the ‘jQuerified Grid’

a. Type in Anton in the search text box and see the grid filter data down to 2 rows of data showing Chef Anton

b. Click on any of the headers and watch the grid get sorted without any postback (entirely on the client side)

c. Scroll horizontally and vertically and see how the headers remain aligned.

In Conclusion

We started off with the small goal of figuring out how to emit thead for a GridView control and ended up applying a jQuery plugin to add rich client side functionality thanks to the proper rendering of thead and tbody tags. This opens up a vast playground for jQuery enabled ASP.NET sites with interactive GridView. Notice we haven’t used Microsoft’s Ajax Control Tool Kit anywhere. Though I have used DataTables and jquery and Ajax Control Toolkit all in the same page and they do work together. But that’s another story. I am trying to make a clean break from ACT and do things in jQuery only. Hopefully sometime soon, I’ll be able to demonstrate use of more jQuery plugins with more functionality like Edit/Update/Delete from the grid view control.

The entire source code including the Northwind.sdf file is uploaded here (hosted on SkyDrive – 714KB download size).

This code uses DataTables.net which is released under GPL v2. Please respect open source licensing model. Whatever little I have written is made available As Is.

Have fun coding!

Why are .NET Devs in knots after Windows 8 demo?

Okay, I had to throw my hat in the ring/shit storm/tornado that’s hit the .NET world after Microsoft demoed Windows 8. At the eye of the storm is the remark made during the demo implying HTML5 and Javascript tooling would be made available to developers to develop for Windows 8.

Now, if you take a bird’s eye view of this statement, you can look at it in all sorts of positive ways like

1. Javascript was finally becoming mainstream in MS world
2. We would have another ‘language’ in our repertoire to develop windows applications on.
3. IE engine was replacing the static desktop with dynamic desktop (fact that it’s been around since IE4 can be set aside for a moment) for Windows and heck they managed to put both (IE and classic desktop) side by.

Beyond this everything else is conjecture. However you put it, except for people working for MS in Windows and .NET team, no one knows any better. Then why this shit-storm and name calling and juvenile behavior from so many .NET devs?

Let’s delve a little deeper but continue with the positive stream of thought. Microsoft has been giving mixed signals about Silverlight and I would consider ONLY Bob Muglia’s comment to Mary Jo Foley (here) regarding what MS thinks of SL’s placement as a development platform – LoB and Mobile. Anything outside this, like posts, by Scott Barnes (@Mossyblog) or Mary Jo Foley (@maryjofoley) proclaiming death of SL or WPF is still conjecture. They may have ‘inside sources’ but unless MS officially declares ‘End of life’ for any of the products/tools in debate, it’s nothing but hot air.

However, it’s not hard to imagine in a huge bureaucratic company like MS (again that’s my assumption, I don’t know anyone personally in MS who could tell me so) there will be power struggles and duplication of work and more power struggle. So let’s for a minute assume Windows 8 team didn’t like the existing client development tools and decided to roll a new platform, I would say SO WHAT! They are still Microsoft, if one team gets an upperhand in a power-struggle then the other team will have to fall in line sooner or later. What does that mean? Well that means if HTML5 and Javascript is the new mantra, the developer tools will follow.

That brings us to the arguments – ‘what happens to my investment in SL/WPF/.NET’? I find this question silly, and here are the reasons why:

1. If you made an investment in SL/WPF/.NET stick with it, MS didn’t say they are pulling plug on SL or WPF or .NET in Windows 8 or anytime soon. Now let’s see what type of investment you made:

  • You built an enterprise app on SL that works great, it will work for the next 10 years probably but I doubt your business will need the same app for 10 years.
  • You built 5 Windows Phone apps, great, keep them in SL till a mature HTML 5/JS platform appears that can do more that what your SL app can do.
  • You built a LoB app, great, keep it around till Business doesn’t need it anymore.
  • I really don’t see where your investment is going! Much less going down the drain!

2. Software Development has always ‘evolved’ and software developers have evolved with it. Crying about why SL/WPF is not a ‘first class’ platform in a future OS falls in the ‘spoilt-brat’ or ‘lazy-ass’ category. GROW UP and improve your skills as and when required!

3. What makes you think Microsoft’s development products division won’t come up with creative ways to continue to use all your existing front end/UI and .NET knowledge to serve up native Windows 8 apps (that are actually HTML and JS)?  In fact today there is a mono compiler that converts IL to JS (https://github.com/kevingadd/JSIL).

4. Are we cribbing just because it’s HTML and javascript? That’s snobbish behavior best left to ‘others’. OMG JavaScript! is just not an argument and one who is making it doesn’t know javascript, period!

A lot of us (so called loyal MS fans) have often cribbed how MS always rolls it’s own, never follows standards and acts like a bully! If that’s true, then hey, this time they got it bang on target right? Then why this hullaboo?

Personally, I started my career as a VB6 developer (mind you all VB6 and rich client and no ASP). Three years down I moved on to C#, since then I’ve tried Java and VB.NET for ‘non UI’ development. But sometime around 5 years ago I realized Rich Client platform wasn’t going to ‘cut-it’ and started on ASP.NET skills, rolled my own MVC framework using ASP.NET Webforms and didn’t feel a bit dis-concerting when MS came out with MVC framework themselves. In fact I couldn’t be happier. Did I throw out my work overnight? No, the app still works on the custom framework I built for it, but when I need it to do something that’s much easier or already handled in the new framework I’ll move to the new one. I have done very little work on WPF (only a couple of prototypes, one of which is available for download on this site) and minimal work with SL (built a multiple file upload and preview control in the above web app). I have been leaning towards learning/using Javascript better and using some of the existing javascript libraries, because just like I felt ‘Rich-client’ wasn’t cutting it, I can now see the ‘server-side’ event model and post-backs on web apps aren’t cutting it. Partial postback and async is the name of the game. Doing it without plugins is an added bonus. If MS just upped the ante on that front, by enabling windows applications using HTML/javascript, I would go for it… Just don’t forget to ‘show me the dev-tools baby’ because I don’t want to work with any other dev tools…

To conclude, the .NET devs should just quit being juvenile or just quit. They are making a mockery out of not just themselves but the entire .NET community. I was initially confused at @Pete_Brown’s comments on twitter till he pointed us to the silverlight forum where I found a long list of comments that he had to moderate. Feel sorry for you Pete, indeed your employers have put you between a rock and a hard place. Don’t worry there are plenty of us, eagerly waiting to see what comes out of //Build/

Finally to MS, keep your in-fighting to yourselves just show us a happy face everytime and we’ll continue put faith in your OS and Dev tools. Last but not least, super awesome demo of Windows8. Let’s kick some competitors’ butts with it.

Follow

Get every new post delivered to your Inbox.

Join 316 other followers