Umbraco 7 and MVC – Contact Form

This is the fifth part of a series of practical examples with Umbraco 7 and MVC.

Contact Forms

In Umbraco, forms need a controller that handles when the form is displayed and when it is posted back by the user.

The only way to add a controller to our project is from Visual Studio. Go to the Controllers folder and add a new empty Controller. Umbraco controllers need to inherit from SurfaceController.

Surface controllers do not render entire pages, Umbraco nodes do that. Instead, you use Surface controllers to Render Child Actions so your controller actions will often have the [ChildActionOnly] attribute.

Let’s create 2 actions public ActionResult ContactForm() and public ActionResult ContactForm(ContactModel model). The first action displays the form. You can use this action to get any necessary information from the user or pre-fill lists, etc.. The second action is the POST action used to process the information received.

The controller uses a ViewModel called ContactModel which should be created inside Models folder.

See a snippet code of the controller below.

Because it is a child action, Umbraco requires you to use RedirectToCurrentUmbracoPage or CurrentUmbracoPage as return action results. Therefore, the only way to send data back to the page is by using TempData. We send InfoMessage and ErrorMessage.

The controller is now ready to be used. Similarly to Search Results and Sitemaps, you need a Macro that is rendered inside a Text page.

Go to Developer > Partial View Macro Files > ‘…’ > Create > In Filename enter ContactForm > In Snippet choose Empty and leave create a Macro ticked. Add the following code to your Partial View Macro file:

@inherits Umbraco.Web.Macros.PartialViewMacroPage

@Html.Action("ContactForm", "Contact")

This code snippet only Renders an action from the Controller.

Now you have a Macro that was also created. So that you can add it to a page, go to Developer > Right click on Macros > Reload nodes > and select ContactForm. Tick use in Rich text editors and save.

Now go to Content > Home > ‘…’ > Create > Text Page > Call it Contact Us. In the main body text editor insert a Macro and select ContactForm. 

Umbraco Contact us

Umbraco 7 and MVC – Multilanguage

This is the forth part of a series of practical examples with Umbraco 7 and MVC.

Multilanguage

Having a multilangual website with Umbraco is relatively simple. You need to create multiple Home pages, one for each language and map a host header on each. Host headers can be subdomains or subdirectories. Go to Content > Content again > ‘…’ > Select Home > Enter Home Spanish and fill in the rest of fields in spanish. You are actually re-creating the whole site but on a different language which is going to be very time-consuming. An easier way is to copy the existing nodes, duplicate them and update them on another language. First Go to Settings > Document Types > Master > Home > Structure tab > Tick Allow at Root to Yes Now go to Content > Right click HomeCopy > Select Content > Copy.

umbraco recreated home

This will re-create everything for you. Rename Home(1) to ES and start updating some content so you see the different languages. When you finish republish everything Go to Content > Right click ES > Publish > Tick Publish ES and all its subpages.

Create multiple languages

Go to Settings > Languages > ‘…’ > Create > Choose Spanish (Peru) > Create Now go back to Content > Right click ES > Select Culture and Hostnames > Select es-PE > Add new Domain > Enter http://localhost:55896/es > Select es-PE. You should also do the same for the English home directory: Go to Content > Right click Home > Select Culture and HostnamesAdd new Domain >and enter http://localhost:55896/ In this example, I will be accessing different languages using subdirectories on a single domain as explained here.

So one more step would be to change the web.config setting umbracoHideTopLevelNodeFromPath to false

You will now be able to access that URL and see the translatated content:

umbraco already translated content

Use a Dictionary

The dictionary is useful so you can store words in multiple languages. Go to Settings > Dictionary > ‘…’ > Create > Enter “Search” as it’s name (case sentitive). You will get 2 textboxes, one of each language. Enter “search” for English and “buscar” for Spanish, and save. Now you only need to alter your templates to use the dictionary instead of a static word:

<input type="text" name="keywords" class="field" placeholder="@Umbraco.GetDictionaryValue("Search")"/><button type="submit">Search</button>

The result is simply a translated content appearing on your pages:

 

umbraco dictionary

 

Read more about setting up a multilanguage site on this blog post: http://webmove.be/home/blog/blog/2011/august/multilanguage-websites-with-umbraco-part2

Umbraco 7 and MVC – Search and Sitemap

This is the third part of a series of practical examples with Umbraco 7 and MVC.

Global Search

A global search is a simple textbox on the header that searches on every page looking for specific keywords. The results is a simple page listing all the results including their page title, URL and a extract of the content. Let’s first create and style the search box + button which will appear as one more item on the menu:

This form is only a redirection form. That means that when you submit it will simply redirect to /search-results?keywords=XXXX So we need to create the search results page that takes the keywords parameter on the query string and display the results. For this we are going to use a macro which can be placed on a simple Text page. Go to Developer > Macros > ‘…’ > Create > Enter ‘Search Results’Create Macros can use Razor, XLST or User Controls. Now we are going to use an MVC Partial view but we need to create it first. Go to Developer > Partial View Macro Files > ‘…’ > Create > Enter ‘SearchResults‘ without .cshtml, choose an Empty Snippet, and untickcreate a macro‘ > Create. The code for the razor is the following: Now relate the Macro to the MVC Partial View. Go back to Developer > Macros > Search Results > In 

umbraco search marcro

Our macro is now ready but we need to display it on a page. Go to Content > Home > ‘…’ > Select Text Page > Enter Search Results. Enter the Title for this page and scroll down to Content > Insert Macro into Rich Text Editor.

umbraco insert search marcro

Go back to the front end and execute a search.

umbraco search page

Umbraco uses Examine to create indexes on every node inside Umbraco. This can be configured in /config/ExamineSettings.config. You can include or exclude fields. You may also need to delete the contents of the index folder in \App_Data\TEMP\ExamineIndexes so that your changes refresh.

 

Sitemaps

A sitemap is a page that displays a list of all your published pages in the site. It is very simple to create a sitemap. You only will need a Macro and a Partial View Macro File that contains the razor code for the template. Go to Developer > Partial View Macro Files > ‘…’ > Create > In Filename enter Sitemap > In Snippet choose Empty and leave create a Macro ticked. Note: I am not using the pre-built template because it doesn’t work as I want it to. Add the following code to your Partial View Macro file:

This code snippet excludes pages that have hideFromSitemap as true. However this property does not exist yet. Go to Settings > Document Types > click on Master > Generic Properties > Add a new property with alias hideFromSitemap type: True/False.

Now you have a Macro that was also created. So that you can add it to a page, go to Developer > Right click on MacrosReload nodes > and select Sitemap. Tick use in Rich text editors and save.

Now go to Content > Home > ‘…’ > Create > Text Page > Call it Sitemap. In the main body text editor insert a Macro and select sitemap. Also, go to Properties and tick Hide in navigation and Hide From Sitemap so that this page doesn’t appear on the top menu or itself in the sitemap. Finally Save and Publish. Another page that should be hidden from the sitemap is the search results. So go to Content > Home > Click on Search Results > Properties and tick Hide From Sitemap.

Add some final styles to indent every level and access your /sitemap:

Umbraco Sitemap

Umbraco 7 and MVC – Banners

This is the second part of a series of practical examples with Umbraco 7 and MVC.

Banner Carousels

Create a banner slider in the home page, one that has multiple images playing automatically. Each banner can also contain headings, text and links that appear on every slide.

Store data using Media Types

First we need to create the containers to store the data for each banner. We can use the Media section to store every banner and it’s information. The idea is to have a folder that contains every images

Because we still need the headings and the text we need create first a new media type. You can do this in

Settings > Media Types > Click on the “…” icon > Create > Enter “Banner” > Create. Add every property that every banner is going to have and save (see screenshot below)

umbraco banner properties

Now go to Settings > Media Type > Folder > Structure tab and check the “Allowed child nodetypes: Banner.

umbraco media folder child

 

This will let you create banners insde a folder in your Media library:

umbraco banner create

Create all of them.

Now that you have uploaded the images and content for each banner you need to display it on your home page.

First, change your Home page to be able to select a Media folder which contains all your banners (the current starter kit already contains fields for 1 banner. But do not get confused with these as we are trying to have multuple banners):

Go to Settings > Document Types > Master > Home > Generic Properties > Add a new Property > call it “Banners Media Folder“, type: “Media Picker”, tab: “Banner”

Now go to Content > Home > Banner > Scroll down > Click on + next to Banners Media Folder. Click on select which appears below the folder (not the folder itself)

umbraco banner properties

Display Your Banners with a Partial View

The next step is to create a partial view that queries and displays all the banners

Just go to Settings > Partial Views > and create a new Razor partial called “homepageManyBanners.cshtml

Import your preferred script. In this example I am using CarouFredSel so I only need to paste jquery.carouFredSel-6.2.1.js inside the folder /scripts/ You can do this directly on your system files and refresh Umbraco for it it pick it up.

homepageManyBanners.cshtml contains this:

We need to add a stylesheet to our banners which is also required by our jquery plugin. For now, instead of modifying the original files from the Starter kit we are going to create a new CSS file. Using you file system, add a new CSS file inside /css/ called custom.css (refresh Umbraco so you see it there). You now need to render that partial within the home page:

@{ Html.RenderPartial("homepageManyBanners"); }

That’s it. Refresh the site and now you have a list of banners going around in your home page: umbraco banners carousel

Umbraco 7 and MVC Practical Examples

umbraco7-header

Umbraco is the most powerful .Net CMS you hoped existed.

However, it is hard to learn.

When I first started I wished there were practical examples in Umbraco in an actual live project with code examples from start to finish. This is exactly what I intend to do in this post by showing you how to build a website in Umbraco 7 with MVC from scratch and give you some sample code that you can use in your own projects.

Dedicate 15 minutes of your day to this article and you will see it is not that hard after all.

This post is an alternative to another article I wrote on how to get started with Umbraco 6 but this time using Umbraco 7. This post will include more code examples on how to achieve the most common functionality that unfortunately does not come out of the box.

Umbraco 7 and MVC Practical Examples

This guide will use Visual Studio 2012 so that we can use MVC Controllers and Razor views directly from Visual Studio. Also, you will get the benefit of intellisense and autocomplete which you could not get by using Umbraco online.

Umbraco 7 is extremely easy to get started. You will get up and running in seconds.

First, open Visual Studio and create an empty MVC project.

Now Go to Tools > Library Package Manager > Manage Nuget Package for Solution. Search online: “umbraco” and Install Umbraco Cms. This will install the latest version of Umbraco (in my case 7.1.1).

installing umbraco nuget

Accept any licenses if Visual Studio prompts you to do so (or first read the license if you feel like). Also confirm that you want to overwrite the web.config.

That’s it. Now you can run (Ctrl+F5) the project and see what happens.

installing umbraco nuget

Start by filling in this form.

If you click on customize you will be able to change the database engine (SQL Compact, SQL Server and MySQL) and the Starter Kit. There are by default 2 starter kits plus the option to not use either. I recommend you to use the default Starter Kit because it already contains a structure that it is useful for any kind of project.

So for now just press that green button that says “install” so that it installs the default Starter Kit and use SQL Compact.

installing umbraco first screen

You did it!

Open a new tab that points to the root of your URL. You now have a working Umbraco site with simple pages like: Home, TextPages (x4) and News.

installing umbraco skarter kit

The basics of Umbraco are: Document Types, Templates and Content Nodes as explained in this other post. In order to create your content, you first need a structure that indicates how this content is saved (types and properties).

Open Visual Studio. Because we created an empty MVC project all new files created by Umbraco are not included in the project. From the solution explorer select “Show all files” and include all Views, CSS, Images and JS files into the solution.

installing umbraco Show all files

Now that you have a basic Umbraco site set up, I will show you how to do some of the most common features of many websites.

For these examples I am using the starter kit TXT 2.0 created by HTML5 UP as a base. I will be modifying the existing document types and adding more templates to it.

Click on one of the following posts:

 

Download the Source Code

That’s it!, I tried to cover the most common practical uses of Umbraco 7 which hopefully can help you get started with Umbraco. You can download the full source code here. It contains the whole Visual Studio 2012 solution + a SQL CE database with the new Document types as per the examples above.
If you have any questions, feel free to ask Google. If Google does not help, then post a comment below. Remember that a single conversation with a wise man is better than ten years of study.

How Spotify Builds a Product

how spotify builds a product

I recently found this tweet that got stuck in my head for many days (literally).

“How Spotify Builds a Product” is such a powerful graphic that describes the right way of how to build something. Spotify takes a phased approach and delivers value on every stage by releasing a working product that can be used by their customers. It is not the final product what they deliver at first but it still usable and does the job. Then, they enhance it ‘progressively’ on every stage until it reaches what was foreseen. The idea is turn around something tangible as early as possible and concentrate on each stage at a time.

Running Lean: Agile Processes and Agile Products

The graphic above reminds me of a widely used project management approach: Agile. We all know that agile is ‘good’ because it forces us to think of working products on each sprint (not only because it sounds better than waterfall, right?). Nonetheless, the practice of agile is mainly a change of processes, in how people work together and how fast something can be done. However, agile can also be a change in how a product is built. Concentrate on small chunks of work at a time and finish it from start to finish (a few weeks tops!). After this, get feedback, iterate, improve and repeat.

This is also call ‘Lean’ which Ash Maurya tells you all about in his book: Running Lean – Ash Maurya

“Running Lean: Iterate from Plan A to a Plan That Works” is a book that tells you how start-ups iterate and evolve. In the same way as Spotify launching a working product stage by stage.

Although, it may be difficult for some to get this ‘Lean’ approach, it makes sense and you will see that it works. Do not complicate yourself trying to build something awesome in one go. Remember: “Perfect is the enemy of good“.

Host a website using Github

I recently came accross many websites that were subdomains of github.io and asked myself how this was possible? I had heard before that it was possible to host your own website (for free) just by using a Github repository. Exactly, just like in the old days when you could host a site for free with Geocities.

Github allows you to physically have a website running locally and every time you make changes to it, you only need to sync it up, and these changes will appear instantaneously on your live website. This is all very possible thanks to: https://pages.github.com/

Host a website on Github

Setting up a Github account is relatively easy. There is no point in repeating something that so many other people have covered, so you can go and read it all from here: http://blog.teamtreehouse.com/using-github-pages-to-host-your-website and https://github.com/blog/272-github-pages. In the end you will end up with a website like this one: http://carlosmartinezt.github.io/

 

In addition to this goodness, there is also another goodie that you can obtain for free which is Jekyll, a blog engine that, without using a database, lets you create posts using physical files in markdown format (files ending in .md) https://daringfireball.net/projects/markdown/. Markdown is just the simplest way to create content in HTML (without using HTML)

To install Jekyll you have to download Ruby first. Go here http://rubyinstaller.org/downloads/ and download the latest RubyInstaller for Windows and one of the development kits. I downloaded these two for example:

All the steps to be taken can be found in the documentation of Jekyll. What I did was:

Went to C:\ and created a folder “RubyDevkit” (it could have been any name). Then extracted the kit into that folder. Then openned the Command Prompt (Run -> cmd). CD to it, and run “ruby dk.rb init” and “ruby dk.rb install” to bind it to ruby installations in your path. Then I ran [gem install jekyll]

More information about the Devkit installation insutructions can be found here: https://github.com/oneclick/rubyinstaller/wiki/Development-Kit

When everything is ready you only need to add files and make changes to your local repositories (for example: C:\Users\Carlos\Documents\GitHub\carlosmartinezt.github.io) which you will then push live.

Good luck blogging (or good luck trying)!

10 More CSS Tricks for 2014 – Part 2

This is the second part of the list of CSS Tricks for 2014. In part 1 (http://carlosmartinezt.com/2014/04/css-tricks-for-2014/) I showed you live examples of the first 14 tricks and now in this part you will have 10 more!.

These 10 more tricks are awesome and could be useful to many websites today. If can also be useful to you as web developer because understanding these can help you learn many new properties and practical applications of CSS3.
Read more… »

CSS Tricks for 2014 – Part 1

net

I recently read a featured article in the recent issue of my favourite magazine net magazine. It shows a list of 25 Smart CSS tips that I thought were incredible! These are the latest trends in CSS with actual wide browser support that you can start using today. Each tip is excellent and well explained; However, I thought it was difficult to see or imagine just by reading it. I thought is was necessary to show actual examples at leat for the most interesting ones. This is what I intent to do in this post.

I will list each but give you only a brief explanation. I recommend you to buy this net magazine issue #253 and get the full information from there. Read more… »

Retore a SQL Backup while DB is in use

This is a very quick post just to keep track of a small SQL script that I always need when I restore a SQL backup file.

The problem is that sometimes when we restore a SQL backup, this is in use and it prevents me for restoring. I receive the following error:

Msg 3101, Level 16, State 1, Line 2
Exclusive access could not be obtained because the database is in use.
Msg 3013, Level 16, State 1, Line 2
RESTORE DATABASE is terminating abnormally.

Retore a SQL Backup while DB is in use

The solution is to set the database offline and then back online again.

ALTER DATABASE [DbName]
SET OFFLINE WITH ROLLBACK IMMEDIATE
ALTER DATABASE [DbName]
SET ONLINE
RESTORE DATABASE [DbName]
FROM DISK = N'C:\DbName_backup_2014_01_29_000916_5754572.bak' WITH FILE = 1, 
MOVE N'DbName' TO N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DBName.mdf', 
MOVE N'DbName_log' TO N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DbName.LDF', 
NOUNLOAD, REPLACE, STATS = 5