Since Visual Studio 2012, we can always find this file called modernizr-(version).js in the default ASP .NET 4.5 MVC template. So, what is Modernizr (can be downloaded from Nuget)?
With this information, we will then be able to provide alternative look-and-feel for those users who are using older versions of browser instead of telling those users “Best view in version xxx of browser yyy”.
With YepNope.js, we will also be able to tell Modernizr what to test and then what JS/CSS to load if the test passes or fails.
Finally, please remember that Modernizr only provides us information about which features are (not) supported. It won’t magically enable those features for us. We need to write corresponding JS/CSS to provide alternative views when the features are not supported on the browser.
In short, Modernizr is a good tool for designers to implement the idea of Progressive Enhancement.
The famous border-radius feature in CSS3 is supported in modern browsers like IE11, Edge, Chrome, and Firefox but it’s not supported in Internet Explorer 7 and 8. Does this stop us from using border-radius in our website? Nope. This is because for users who are still using IE7/8, they can still use the website in the same way as those who are using modern browsers. Just that those who are using old browsers cannot see the beautiful effect of border-radius.
When I first worked as web developer after graduation, I used to think what I knew about web development was already enough. However, as I learned more from friends and colleagues, I realized how difficult the field is, even though in Easibook.com we were just dealing with ASP .NET for web development.
New Ideas
Singapore .NET Developers Community meetup (Photo Credit: .NET Developers Singapore)
I participated in the Singapore .NET Developers Community meetup with my colleagues on 28 January. The theme is about web development. We had the chance to learn about ASP .NET MVC 5, Dependency Injection and how ASP .NET MVC 5 works with Angular JS.
What interested me is the ASP .NET MVC 5 talk given by Nguyen Quy Hy. In work, I was always using ASP .NET Web Forms. When I first started the ASP .NET MVC project in Visual Studio, I was already shocked by new terminologies like Razor, Identity, Scaffold, and all sort of folders, such as Models, Views, Controllers, App_Start, etc. Those are basically not found in my existing Web Forms project.
Working in a startup, there is always more to do and even more to learn, no matter the size of business. In many ways, my job changes frequently. I have to always take time to learn and challenge myself to play with new technology. Hence, learning ASP .NET MVC becomes my new challenge in this year.
I thus decided to write this post to share about what I’ve learned in my ASP .NET MVC 4/5 projects in February.
Bootstrap
Let’s start with simple stuff first. The GUI.
It’s nowadays quite common that people want a website which is responsive and mobile friendly. Luckily, there are frameworks to help. A even better news is that Visual Studio web application template by default is using Bootstrap, a framework providing design and theming features.
Previously we were using VS 2008. There was no such thing as bootstrap in our Web Forms application. Hence, I only started playing with Bootstrap when I did my first ASP .NET MVC 4 project in VS 2012.
ASP .NET web server controls can no longer be seen in ASP .NET MVC project. I was once asked about how GridView and paging were going to be handled in ASP .NET MVC without the use of the web server controls. I found some online discussions and articles which gave good answer to the question.
12-Column Grid System is another thing I learnt when playing with Bootstrap. The grid system allows us to easily create complex grid layouts for different devices.
Grid System of Bootstrap 3
With the help of Bootstrap, even before I do anything, my web application is already responsive and mobile friendly. It’s true that technology is just a tool but with the right tools, we are able to work more efficiently and productively. =)
Native Support of Clean URL: Good News for SEO
My colleague, who was doing SEO, always received requests to do URL Rewrite in our existing Web Forms applications. Whenever there is a new page created, he has to add a new rule to web.config, sometimes just to get rid of the .aspx thingy.
If there are one thousand pages, then there will be same amount of rules. So in the end, we even need to create separate config file just to keep the rules for URL rewrite.
In ASP .NET MVC 5, with the help of ASP .NET Routing, URLs no need to be mapped to specific web pages. Hence, in MVC web application, we can always see clean URLs which is friendly to not only the web crawler but also sometimes to the users. This is one of the features that I love in ASP .NET MVC.
Identity and Social Network Login
Whenever I visit an online store, I always find it more customer-friendly to accept Facebook or Google login.
Fortunately, ASP .NET Identity is powerful enough to not just accept application-wise user name and password, but also allows the connections from social websites like Facebook, Twitter, and Google+.
I only need to create a Facebook app and then key in the https URL of my website. After that, I put both the application ID and secret key to Startup.Auth.cs. Tada, users can now login to my website with their Facebook credentials.
Just in case if you also encounter exception saying “Object reference not set to an instance of an object” on the line with AuthenticationManager.GetExternalLoginInfoAsync(), as shown in the following screenshot, please update Microsoft.Owin.Security.Facebook Nuget package.
I like how easy it is to have all my tables created auto-magically by just defining model using classes. Then after that, I can create new views and controller by adding Scaffold.
Easily create MVC controller and views with Scafolding
Headache with Migrations
In order to have database scheme updated when the model is changed, I have enabled migration by running the Enable-Migrations command.
Ran Enable-Migrations command in the Package Manager Console
After that, whenever I changed my model classes, I will run Update-Database to have database schema updated as well. However, soon I encountered a problem.
When I was working on an ASP .NET MVC 4 project with VS2012, the Id in the Users table is integer. So, in VS2013, I assumed it to be the same when I created the model classes and updated the database. Unfortunately, nope. The default web application of VS2013 uses GUID for user ID. There is an online tutorial on how to change the primary key of Users back to integer, if you are interested.
Due to the fact that my project is a totally new project, so what I am going to do is just to change my model classes to use GUID as the type of storing user ID in other tables. However, when I ran the Update-Database command, the console prompted me an error message, saying “Operand type clash: int is incompatible with uniqueidentifier”. To quickly get rid of this problem, I deleted my tables (Don’t do this at home. =P) from the database. Then when I ran Update-Database command again, it complaint the table was missing. Finally, I had no choice but deleting the relevant records in __MigrationHistory table before making Update-Database to work again. =P
Yay, successfully updated database schema after deleting migration history.
Yay with Entity Framework
Before using Entity Framework, I played with stored procedure for few years. My colleagues have always been complaining that sometimes the logic was being hidden in stored procedures and thus made the debugging difficult. Also, having logic in stored procedures means that our business logic is actually split up into both C# and SQL. So, sometimes the developers need to spend a few hours debugging the C# code before realizing the store procedure was actually the culprit.
With Entity Framework, I am now able to modify the table structure and logic all in C# code which helps developers to easily find out where goes wrong.
Still, sometimes it is good to group related functions into one well-defined stored procedure so that the system only needs to call to the database once to get all the work done. However, after reading a 400-line store procedure once, I decided that doing this may not be the best option because no one in my team was interested to debug SQL code.
Review a long stored procedure?
There are more related topics online regarding Entity Framework vs. Stored Procedures, as listed below. If you are interested, feel free to check them out.
Using MySQL Instead of Default SQL Server: I Was Having a Hard Time
By default, the data provider of ASP .NET Identity with Entity Framework is set to be MS SQL in VS 2013. However, MS SQL Server is not free. So, I decided to use MySQL instead. Hence, I need to find ways to configure Entity Framework on my project to work with MySQL.
However, if I am not wrong, part of these can be done easily by just including the related MySQL nuget packages. I chose four of them to be installed in my project: MySQL.Data, MySQL.Data.Entity, MySQL,Data.Entities, and MySQL.Web.
Install related NuGet packages to make Entity Framework Code First works with MySQL.
After changing web.config, I followed the tutorial to introduce two new classes in the project. One is MySqlHistoryContext.cs which will sync the model changes with the database schema using MySQL standard and not MS SQL.
According to an online post, I added extra one line to the OnModelCreating method MySQLHistoryContext.cs. It’s to fix the exception of the famous Error 0040: The Type nvarchar(max) is not qualified with a namespace or alias. Only primitive types can be used without qualification.
However, the Error 0040 didn’t disappear because of this line. I will share later the other steps I took to fix this problem.
The famous Error 0040 encountered when doing migrations for MySQL.
Another new class is called MySqlConfiguration which is used to make sure the Entity Framework will use MySqlHistoryContext, instead of the default one.
Besides, I also made changes to Configuration.cs. Remember the Error 0040? A discussion thread on Github actually suggested to add the following line to fix it.
SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
The sentence basically says that due to the fact that the migration earlier done in SQL Server and thus some data types are not compatible with MySQL, we need to delete the Migrations folder. So, after I excluded the 201502231459263_InitialCreate.cs file (which was created when I am still using MS SQL for my project) in Migrations folder from the project, the Error 0040 was gone when I did Update-Database. Yay!
So yup, sometimes it’s very, very useful to know more than one language. And yup, I spent half of my holiday to figure out how to make Entity Framework to work with MySQL. =)
Oh well, half day gone just to make MySQL work in my little project.
By the way, the Chinese web page mentioned above was already not available. What I shared with you is actually a link to its Google cached copy. I am not sure if the cache is still around when you visit it.
Self Learning ASP .NET MVC on MVA during Chinese New Year
The talks given during the community meetup are good. However, in order to learn more, I also need to get advice from my colleagues who have more experience with ASP .NET MVC.
Yup, people from Malaysia are watching the live too!
The End of the Beginning
I am now still a beginner in ASP .NET MVC. I always find that there are many new things to learn in just web development. Actually, it’s very challenging. For example, to get Entity Framework Code First to work with MySQL already takes me half day to figure it out.
Anyway, this is just a post sharing how I get started on ASP .NET MVC. In the future, I will do my best to share with you all more about what I learn in this cool technology. =)
I already forgot how I got to know about Microsoft hackathon back in 2012, few months after I entered my first job.
Dream Build Launch, Wowzapp~
The first hackathon that I took part in is Dream Build Launch. I worked together with my C# guru, Desmond, to build our first Windows 8 app (which was called Metro App back then). We successfully published the app to Windows Store after two rounds of Microsoft Premier Field Engineer (PFE) consultation sessions. We named our first Windows 8 app “EsplanadeGo!”, which has 51 downloads today.
HTML5 for Metro Apps talk given by Alex Goh during Dream Build Launch event. Photo Credits: Spiffy
In December 2012, I participated in another Microsoft hackathon, Wowzapp. That was the first time I won the first prize in Microsoft competition after I graduated from university. The app that I built was called Entertainment Connect, also a Windows 8 app. User can use it to connect to his/her Dropbox account to retrieve media files and then play them in the app.
Near the end of the Wowzapp hackathon, one of the judges from Microsoft Singapore, Eugene, suggested me to build another app which connected to SkyDrive (which was later renamed to OneDrive) because he would love to use such an app and SkyDrive API was still quite new back then.
Because of Eugene’s idea of the app, I challenged myself again in the hackathon organized by Microsoft Singapore in 2014, //publish/. I decided to make Eugene’s dream come true.
//publish/
The special thing about //publish/ was that participants were allowed to bring their own existing Windows 8/8.1 projects. The focus of the event was more about publishing app to Windows Store. Hence, I took the opportunity to complete my second personal Windows 8 app, Entertainment Connect.
//publish/ hackathon was actually a 2D1N event happening worldwide. Personally, I thought the one in Singapore was the most special one because Inori Aizawa was invited as special guest to the event as well! Participants got the chance to take photo with her and won cute prizes. Also, we had the chance to try out Xbox One, the device that people were willing to queue up at Funan DigitaLife Mall for a few hours just to buy one.
Where else can you see Inori Aizawa playing Xbox One? Photo Credits: Microsoft Singapore//publish/ organized by Microsoft in Singapore. Photo Credits: Microsoft Singapore
The event took place at The Co., a very comfortable place just next to my office. So, I got to bring laptop external keyboard and mouse, which helped to improve my coding speed.
There were tech talks given in the first morning. One of them was about Push Notification with Microsoft Azure. This talk in fact helped me a lot in my work when our company decided to do a push notification to Android and iOS phone.
Tech talk about Cortana delivered by Chun Siong. Photo Credits: Microsoft Singapore
Meet People
One of the great things that I love about Microsoft hackathon is that I always can meet imba people here. By just having a chat with them, I get to learn more technologies out there, such as Arduino, Azure Media Services, iOS development, and so on.
Entertainment Connect is my submission for //publish/ in 2014.
Entertainment Connect (Available now at Windows Store)
What’s so special about Entertainment Connect? Isn’t it just a media player that can play videos and songs? What else?
Firstly, yes, it is a media player. However, it is not a normal media player which can only play the local media files. It connects to your OneDrive account and retrieves available media files from there.
Secondly, I make it so that when you switch from one media file to another, the previous media file is paused and is hidden in the background. So, you can, let’s say, click on one video, play it halfway, then click on another song, then jump back to the same video again and continue from where you stop earlier. So this is actually similar to the “Parallel Video Downloading” feature that I introduced back then in YouTube Re-Player (Desktop) in 2009. The only difference is that now it does not limit the number of videos to be just 5.
Parallel Media Downloading from OneDrive to Entertainment Connect
Thirdly, it supports playing audio in the background. This means that even though the app is running in the background, users can still continue listening to the music and at the same time they can also control the media player.
SystemMediaTransportControls
Finally, it can loop songs and videos. Yup, re-playing is always the must-have feature in the media player programs that I build. =)
Wait, It Was 6 Months Ago!
Some of the readers by now should have realized that //publish/ actually happened 6 months ago. Why do I only blog about it now? Well, the answer is that I choose to blog about it after I successfully publish Entertainment Connect to Windows Store. So, why does it take so long for me to publish an app? This is because I have little time to work on it after the event.
Simple to-do list kept in OneNote
I have learnt the key to finishing a personal project is to work on the project every day. However, I have a full-time work which requires me to OT always. Sleeping has thus become my top priority after work. However, I still try to at least work on the project by writing a few lines of code or just staring at Visual Studio for a few minutes. So, after 6 months of doing so, I am finally able to publish Entertainment Connect.
There is a saying, “Only do side projects you are absolutely crazy about.” Hence, I also installed Entertainment Connect on my laptop so I got to use it daily. The reason of doing so is to force me to remember about the project and to easily find out bugs in the app.
Today, I am happy that I successfully realize the dream of Eugene about a Windows 8 app that he can use to connect to play the media files stored in his OneDrive. In fact, I am very happy to have taken up this challenge and complete the app by myself even though the entire process is tiring.
Prize
Prize is Nokia Lumia 1520!
I’d also like to take this chance to thank Microsoft Singapore team for giving me a special prize for Entertainment Connect during //publish/. It was a brand new Nokia Lumia 1520. Coincidentally, my Android phone stopped functioning few days before the event. So, I managed to get a new modern smart phone for free.
I should blog about the phone next time to show how good/bad Nokia Lumia 1520 is. =P
February is a short month so I have to plan my self-learning accordingly so that I can get myself more focused. Due to the fact that I can only spend on average one hour per day to work on my personal project and self-learning, I choose to learn not only something which is easier, faster to learn, but also a technology that is more interesting. So, the topic of February self-learning is HTML5! (Notice/Joke: ! is exclamation mark here. It doesn’t mean 5! which equals to 120).
I do a firefly animation by using this new <canvas> element in a simple way. Firstly, I draw some fireflies on the canvas.
cxt.globalAlpha = 0.4;
cxt.beginPath();
cxt.arc(x, y, ((fireflyLightMaxDiameter - fireflyDiameter) * brightnessRatio) + fireflyDiameter, 0, Math.PI * 2, true);
cxt.closePath();
var grd = cxt.createRadialGradient(x, y, 1, x, y, 4);
grd.addColorStop(0, "#FFFFFF"); // white
grd.addColorStop(1, "#FFFF00"); // yellow
cxt.fillStyle = grd;
cxt.fill();
cxt.globalAlpha = brightnessRatio;
cxt.fillStyle = "#99FF00";
cxt.beginPath();
cxt.arc(x, y, fireflyDiameter, 0, Math.PI * 2, true);
cxt.closePath();
cxt.fill();
Secondly, I will redraw the whole canvas for every 60 milliseconds. Then in each redraw function, I randomly assign flying speed and direction to every single firefly. Also, there is a counter set so that the firefly won’t change its direction too often.
dx = Math.floor(Math.random() * fireflyMaxSpeed);
dy = Math.floor(Math.random() * fireflyMaxSpeed);
firefliesDx[i] = dx;
firefliesDy[i] = dy;
x += dx * directionX[i];
y += dy * directionY[i];
if (callCounter % 40 == 0) { // Don't change the flying direction too often
directionX[i] = ((Math.floor(Math.random() * 10) < 5) ? 1 : -1);
directionY[i] = ((Math.floor(Math.random() * 10) < 5) ? 1 : -1);
}
Thirdly, I set a counter to do the brightness changing of each firefly.
So, yup, that’s the basic idea on how I do firefly animation in <canvas>. Since this year is the tourism year in my country, I apply the firefly animation in a page about watching fireflies in Kuala Selangor, Malaysia. To get the source code, you can visit my page of this animation in the Mozilla Demo Studio. Don’t forget to click “Like It” button if you really like it. =P
Firefly HTML5 Animation: The page is to promote Kuala Selangor, the world’s biggest firefly colony
Popcorn.js: Integrating Video and the Web Content
However, promoting just one attraction in my country is not enough. So, I am thinking of building a page which will guide the viewer through different places in Malaysia.
I get a promotional video about Malaysia tourism from YouTube. In the video, it shows several famous tourist attractions in Malaysia. I want to build a web page showing a short introduction as well as a map (or even street view) about those places. I thus chose Popcorn.js.
Popcorn.js is an open-source HTML5 video framework which allows us to create time-based interactive media on the web. So, we can now bring content in a web page into a video easily. People watching a video on the website now can also read a web page content which is relevant to the video content. So, this JavaScript library basically allows to add value to a video.
The following screenshot shows how the page looks when the video is displaying a picture of Pulau Tenggol.
Popcorn.js in action.
YouTube Plug-in Issue in Popcorn.js
There is a problem if we are using the YouTube plug-in offered in the Popcorn.js. After the video ends, the YouTube player will show a group of relevant videos. So it basically allows the viewer to change the content of the video player. Hence, to solve this problem, I added one value to the playerVars in popcorn.js.
Although it’s not encouraged to use CSS to do complicated drawing on the web pages, thanks to the CSS3, we can now create animations with CSS by using @keyframes. For example, the following is part of my CSS which does the animation of the name of each attraction in the web page.
So, if you haven’t visited Malaysia before, please bring your family and friends to this lovely country and join us in this grand tourism celebration. However, before that, kindly vote for my following two demos by clicking the “Like It” button. Thanks. =D
Enjoy the HTML5 firefly animation here.Take a tour to Malaysia with HTML5 here.