Using Sass Maps to Save Time in CSS

Sass is a superset of CSS that “compiles” down to regular CSS usable by any browser. It adds features such as functions, logic, and loads more.

Sass already had the concept of lists that allow a one-dimensional list of values to be defined; Sass 3.3 introduced maps – a series of key-value pairs.

Defining a Sass Map

To define a variable called team-colors containing a map of values (in this case a map of soccer teams and their colors):

$team-colors: (
    australia: #F7AD31,
    england: #FFF,
    sweden: #FFE700,
    japan: #435AAD
);

Iterating over a Sass Map

Now we can iterate through all the team names and access their color values:

@each $team, $color in $team-colors{
    .#{$team} {   
        background-color: $color;
  }
}

This will create a CSS class with the name of the team (using Sass interpolation syntax) and its associated background color:

.australia {
  background-color: #F7AD31;
}

.england {
  background-color: #FFF;
}

.sweden {
  background-color: #FFE700;
}

.japan {
  background-color: #435AAD;
}

There’s also a number of functions for manipulating maps such as map-get and map-has-key.

 

To learn how to simplify your CSS and save time writing it with Sass, check out my Pluralsight course.

You can start watching with a Pluralsight free trial.

SHARE:

Create More Maintainable CSS in Less Time with Sass and Visual Studio

My new Pluralsight course was recently released that shows how to use Sass when developing ASP.Net web applications.

Sass (CSS with superpowers) allows the creation of regular CSS, but produce it with loads of cool features that regular programmers know such as variables and functions.

Sass is a superset of CSS and has a .scss file extension. A CSS file is a valid Sass (.scss) file.

A tool “compiles” the Sass .scss file to regular CSS. One way to do this in Visual Studio is to install the free Web Workbench extension. Once installed, whenever you save the .scss file, Web Workbench will create the accompanying .css file as shown in the following screenshot:

CSS files generated from Sass

(Notice here the minified version is being created by Web Workbench because the full version is installed.)

Sass Variables

Sass variables can be defined and then used wherever regular CSS property values are used. For example, the following shows 3 variables declared and used in the .scss file:

$main-brand-color: pink;
$secondary-brand-color: #111;
$base-font-size: 50px;

body {
    background-color: $main-brand-color;
    color: $secondary-brand-color;
    font-size: $base-font-size;
}

This produced the following .css:

body {
  background-color: pink;
  color: #111111;
  font-size: 50px; }

Mixins

Mixins decrease the amount of boilerplate CSS we need to write. For example using vendor prefixes throughout the stylesheet. Rather than writing all the prefixes by hand we can declare and invoke a mixin:

@mixin border-radius($radius){
    -webkit-border-radius: $radius;
    -moz-border-radius: $radius;
    border-radius: $radius;
}

.border {
    @include border-radius(10px);
}

This produces the following CSS:

.border {
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  border-radius: 10px; }

Inheritance

Repetition can be reduced with Sass inheritance. In the following example, happy and sad inherit from greeting:

.greeting {
  border: 1px solid #000;
  padding: 10px;
}

.happy {
  @extend .greeting;
  border-color: yellow;
}

.sad {
  @extend .greeting;
  border-color: grey;
}

This produces:

.greeting, .happy, .sad {
  border: 1px solid #000;
  padding: 10px; }

.happy {
  border-color: yellow; }

.sad {
  border-color: grey; }

Now in the HTML, when the happy or sad class is used, the element will also get the greeting styles without having to apply both classes explicitly.

These examples just scratch the surface of the feature set of Sass. To learn more check out the official site or my Simplifying CSS in Visual Studio With Sass Pluralsight course.

You can start watching with a Pluralsight free trial.

SHARE:

Using Server Side Timers and SignalR in ASP.NET MVC Applications

I thought it would be fun to create an “Internet uptime” page that you can see live here on Azure Websites. It shows how long the Internet (since ARPANET) has been around for.

image

Creating a Class that can be Managed by ASP.NET

The HostingEnvironment.RegisterObject method can be used to register an instance of an object that has its lifetime managed by the hosting environment.

To register an object it must implement the IRegisteredObject interface.

This interface defines a Stop method which gets called when ASP.NET needs to shutdown the app domain.

So, in the application start we can create an instance of our class and register it:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);

    HostingEnvironment.RegisterObject(new BackgroundUptimeServerTimer());
}

Creating a SignalR Hub to Send Messages from the Server to Client

Next we create a SignalR hub and the HTML.

So the hub class is called UptimeHub:

public class UptimeHub : Hub
{
}

We can get the server to call a client JavaScript method called “internetUpTime” in the HTML page and have this client code display the what’s been sent from the server timer.

The following shows the complete HTML for the page. Notice the “hub.client.internetUpTime = function (time) …” this function will get executed every time our server timer event fires.

More...

SHARE:

Vertically Center Div in Browser Window using Viewport-Relative Lengths

I found out about these units this week so I wanted to have a play with them.

The CSS units: vw, vh, vmin, and vmax allow sizes to be specified relative the the browser window size (or the “initial containing block”).

So 1 vw is equal to 1% of the viewport width and 1 vh is equal to 1% of the viewport height.

vmin and vmax return the smaller and larger respectively of vw or vh.

There is good support  for vw and vh in modern browsers with some partial support for vmax, overall about 55% of browsers offer full support, 20% partial support.

So for example to center a div vertically in the browser we could set its height to “50vh”  (50% of the viewport height) and set its top margin to be “25vh” (or a quarter of the viewport height), thus leaving a quarter below the div.

So here’s a screenshot of this in action in a tiny browser window (the white is the div):

image

And after resizing the browser:

More...

SHARE:

On Staying Positive and Subconscious Prejudices

So I was toying with an idea using SignalR on Azure.

In the client code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Internet Uptime</title>
</head>
<body>   
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery.signalR-2.1.0.min.js"></script>
    <script src="/signalr/hubs"></script>
        
    <script>
        $(function () {
            var hub = $.connection.uptimeHub;            

            $.connection.hub.start();           

            hub.client.internetUpTime = function (time) {
                $('body').text(time);
                
            };           
        });
    </script>    
</body>
</html>

So when the server sends  an “internetUpTime” message, the <body> is being set to the content of the string sent from the server.

More...

SHARE:

Making An Awesome Windows 8 Pinned Tile for your Website

With Windows 8 and the metro "Modern Windows New UI Store Experience Style" version of Internet Explorer 10, you can pin a web site to the start menu and provide a hi-res image to be displayed on the tile. This is a nice little touch to "delight the user" and requires very little effort.

There are also some cool things you can do to enable your pinned tile to display notification badges, though this requires a little extra work.

Customising the Pinned Site Tile Image

By default the tile that gets pinned to your start menu will either appear with the site favicon or the default Internet Explorer logo.

Either way it doesn't look super great.

You can create a larger PNG image and tell Windows 8 to use this hi-res image rather than the small lo-res favicon or default IE logo. The image must be 144px high and 144px wide and it's recommended by Microsoft that you use a transparent background.

More...

SHARE:

Getting Started with SASS for Microsoft Developers

Sass (Syntactically Awesome Style Sheets) tries to make CSS fun again.

It's a set of "extensions" on top of standard CSS that make it easier to write and maintain style sheets.

A Sass file compiles down to regular CSS so it doesn't require any special browser plug-ins.

This article is aimed at Microsoft developers but the Sass language sections apply to anyone wanting to get an overview of Sass, regardless of the web programming platform or IDE you're using.

More...

SHARE:

Controlling HTML IDs in ASP.NET 4.0 Webforms

ASP.NET 4 introduces more control over how client-side IDs are rendered by ASP.NET controls. By default ASP.NET 4 will render client IDs in the same way as ASP.NET 3.5 and earlier.

To change the way IDs are generated, the ClientIDMode property can be set - this can either be done on individual controls or at the page level in the @Page directive.

The default ClientIDMode value for controls is Inherit and the default for the Page is AutoID - if we change ClientIDMode at the Page level, the controls on that page will inherit the setting.

The options for ClientIDMode are:

  • AutoID: (Page default) generates IDs the same way as prior versions. Use for backward compatibility or when you don't care about what IDs are generated.
  • Inherit: (Control default): uses the value from the parent container.
  • Static: always sets the client-side ID to the same as the server-side ID property. Use to guarantee the client-side ID of a control - may result in duplicate IDs on the client which may cause problems if you have JavaScript looking for the control by ID.
  • Predictable: Can be used for content inside a databound GridView or ListView to append the unique id/key of the bound object (e.g. the primary key of a databound database record).

The following snippets of HTML output shows how the different settings change client-side IDs when a Label control called "NumberInStockLabel" is used inside a databound ListView.

AutoID, No ClientIDRowSuffix Specified

<td><span id="AutoIDListView_ctrl0_NumberInStockLabel">22</span></td>

Predictable, ClientIDRowSuffix=ProductID

<td><span id="PredictableListView_NumberInStockLabel_44">22</span></td>

The 44 at the end of the ID is the ProductID property from the underlying databound item.

Predictable, No ClientIDRowSuffix Specified

<td><span id="PredictableListViewNoClientIDRowSuffix_NumberInStockLabel_0">22</span></td>

The 0 at the end of the ID is a simple sequential number generated by ASP.NET, this is because we have not specified a value for ClientIDRowSuffix; subsequent rows would end _1 _2 _3 etc.

Static, No ClientIDRowSuffixSpecified

<td><span id="NumberInStockLabel">22</span></td>

The id is exactly the same as the one we set in markup; subsequent rows would all have exactly the same id.

Complete Source Markup

<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="Products.aspx.cs"
Inherits="clientIDs.Products"
ViewStateMode="Disabled" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>


        <asp:ObjectDataSource ID="odsProducts" runat="server"
            SelectMethod="GetProducts"
            TypeName="clientIDs.MockProductDB" />


        <h3>ListView, AutoID, No ClientIDRowSuffix</h3>
        <table>
            <tr>
                <th>Product ID</th>
                <th>Description</th>
                <th>Stock</th>
            </tr>
            <asp:ListView ID="AutoIDListView" runat="server"
                DataSourceID="odsProducts"
                ClientIDMode="AutoID"
                ClientIDRowSuffix="ProductID">
                <ItemTemplate>
                    <tr>
                        <td><%# Eval("ProductID") %></td>
                        <td><%# Eval("Description")%></td>
                        <td><asp:Label ID="NumberInStockLabel" runat="server" Text='<%# Eval("NumberInStock") %>' /></td>
                    </tr>
                </ItemTemplate>
            </asp:ListView>
        </table>



        <h3>ListView, Predictable, ClientIDRowSuffix=ProductID</h3>
        <table>
            <tr>
                <th>Product ID</th>
                <th>Description</th>
                <th>Stock</th>
            </tr>
            <asp:ListView ID="PredictableListView" runat="server"
                DataSourceID="odsProducts"
                ClientIDMode="Predictable"
                ClientIDRowSuffix="ProductID">
                <ItemTemplate>
                    <tr>
                        <td><%# Eval("ProductID") %></td>
                        <td><%# Eval("Description")%></td>
                        <td><asp:Label ID="NumberInStockLabel" runat="server" Text='<%# Eval("NumberInStock") %>' /></td>
                    </tr>
                </ItemTemplate>
            </asp:ListView>
        </table>



         <h3>ListView, Predictable, No ClientIDRowSuffix set</h3>
        <table>
            <tr>
                <th>Product ID</th>
                <th>Description</th>
                <th>Stock</th>
            </tr>
            <asp:ListView ID="PredictableListViewNoClientIDRowSuffix" runat="server"
                DataSourceID="odsProducts"
                ClientIDMode="Predictable">
                <ItemTemplate>
                    <tr>
                        <td><%# Eval("ProductID") %></td>
                        <td><%# Eval("Description")%></td>
                        <td><asp:Label ID="NumberInStockLabel" runat="server" Text='<%# Eval("NumberInStock") %>' /></td>
                    </tr>
                </ItemTemplate>
            </asp:ListView>
        </table>





        <h3>ListView, Static, No ClientIDRowSuffix set</h3>
        <table>
            <tr>
                <th>Product ID</th>
                <th>Description</th>
                <th>Stock</th>
            </tr>
            <asp:ListView ID="StaticListView" runat="server"
                DataSourceID="odsProducts"
                ClientIDMode="Static">
                <ItemTemplate>
                    <tr>
                        <td><%# Eval("ProductID") %></td>
                        <td><%# Eval("Description")%></td>
                        <td><asp:Label ID="NumberInStockLabel" runat="server" Text='<%# Eval("NumberInStock") %>' /></td>
                    </tr>
                </ItemTemplate>
            </asp:ListView>
        </table>



    </div>
    </form>
</body>
</html>

 

Complete HTML Output

 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
 
</title></head>
<body>
    <form method="post" action="Products.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTkwMjEwMjAxN2QYBAUOU3RhdGljTGlzdFZpZXcPFCsADmRkZGRkZGQ8KwAEAAIEZGRkZgL/////D2QFJlByZWRpY3RhYmxlTGlzdFZpZXdOb0NsaWVudElEUm93U3VmZml4DxQrAA5kZGRkZGRkPCsABAACBGRkZGYC/////w9kBRNQcmVkaWN0YWJsZUxpc3RWaWV3DxQrAA5kZGRkZGRkPCsABAACBGQVAQlQcm9kdWN0SUQUKwAEFCsAAQIsFCsAAQIDFCsAAQLIIhQrAAECYGYC/////w9kBQ5BdXRvSURMaXN0Vmlldw8UKwAOZGRkZGRkZDwrAAQAAgRkFQEJUHJvZHVjdElEFCsABBQrAAECLBQrAAECAxQrAAECyCIUKwABAmBmAv////8PZBoTurOO0ZN1r5PaB5cscPKdDFEGlp47JvHGSM55AYQ9" />
</div>
 
    <div>
       
 
 
 
 
        <h3>ListView, AutoID, No ClientIDRowSuffix</h3>
        <table>
            <tr>
                <th>Product ID</th>
                <th>Description</th>
                <th>Stock</th>
            </tr>
           
                    <tr>
                        <td>44</td>
                        <td>product 1</td>
                        <td><span id="AutoIDListView_ctrl0_NumberInStockLabel">22</span></td>
                    </tr>
               
                    <tr>
                        <td>3</td>
                        <td>product 2</td>
                        <td><span id="AutoIDListView_ctrl1_NumberInStockLabel">11</span></td>
                    </tr>
               
                    <tr>
                        <td>4424</td>
                        <td>product 3</td>
                        <td><span id="AutoIDListView_ctrl2_NumberInStockLabel">1</span></td>
                    </tr>
               
                    <tr>
                        <td>96</td>
                        <td>product 4</td>
                        <td><span id="AutoIDListView_ctrl3_NumberInStockLabel">0</span></td>
                    </tr>
               
        </table>
 
 
 
        <h3>ListView, Predictable, ClientIDRowSuffix=ProductID</h3>
        <table>
            <tr>
                <th>Product ID</th>
                <th>Description</th>
                <th>Stock</th>
            </tr>
           
                    <tr>
                        <td>44</td>
                        <td>product 1</td>
                        <td><span id="PredictableListView_NumberInStockLabel_44">22</span></td>
                    </tr>
               
                    <tr>
                        <td>3</td>
                        <td>product 2</td>
                        <td><span id="PredictableListView_NumberInStockLabel_3">11</span></td>
                    </tr>
               
                    <tr>
                        <td>4424</td>
                        <td>product 3</td>
                        <td><span id="PredictableListView_NumberInStockLabel_4424">1</span></td>
                    </tr>
               
                    <tr>
                        <td>96</td>
                        <td>product 4</td>
                        <td><span id="PredictableListView_NumberInStockLabel_96">0</span></td>
                    </tr>
               
        </table>
 
 
 
         <h3>ListView, Predictable, No ClientIDRowSuffix set</h3>
        <table>
            <tr>
                <th>Product ID</th>
                <th>Description</th>
                <th>Stock</th>
            </tr>
           
                    <tr>
                        <td>44</td>
                        <td>product 1</td>
                        <td><span id="PredictableListViewNoClientIDRowSuffix_NumberInStockLabel_0">22</span></td>
                    </tr>
               
                    <tr>
                        <td>3</td>
                        <td>product 2</td>
                        <td><span id="PredictableListViewNoClientIDRowSuffix_NumberInStockLabel_1">11</span></td>
                    </tr>
               
                    <tr>
                        <td>4424</td>
                        <td>product 3</td>
                        <td><span id="PredictableListViewNoClientIDRowSuffix_NumberInStockLabel_2">1</span></td>
                    </tr>
               
                    <tr>
                        <td>96</td>
                        <td>product 4</td>
                        <td><span id="PredictableListViewNoClientIDRowSuffix_NumberInStockLabel_3">0</span></td>
                    </tr>
               
        </table>
 
 
 
 
 
        <h3>ListView, Static, No ClientIDRowSuffix set</h3>
        <table>
            <tr>
                <th>Product ID</th>
                <th>Description</th>
                <th>Stock</th>
            </tr>
           
                    <tr>
                        <td>44</td>
                        <td>product 1</td>
                        <td><span id="NumberInStockLabel">22</span></td>
                    </tr>
               
                    <tr>
                        <td>3</td>
                        <td>product 2</td>
                        <td><span id="NumberInStockLabel">11</span></td>
                    </tr>
               
                    <tr>
                        <td>4424</td>
                        <td>product 3</td>
                        <td><span id="NumberInStockLabel">1</span></td>
                    </tr>
               
                    <tr>
                        <td>96</td>
                        <td>product 4</td>
                        <td><span id="NumberInStockLabel">0</span></td>
                    </tr>
               
        </table>
 
 
 
    </div>
    </form>
</body>
</html>

SHARE:

Managing ViewState in ASP.Net 4

ASP.Net 4 allows us to use an opt-in viewstate approach rather than an opt-out approach in previous ASP.Net versions (EnableViewState was available in prior versions, but if you disable viewstate, all children of the page/container also inherited this with no one to override and opt-in).

To use the opt-in approach in ASP.Net 4, the new ViewStateMode property can be used. The following example disables viewstate for the whole page (all children will inherit this disabled value) but Label2 opts in to viewstate. The codebehind sets the values of the labels only on the first page load - not any subsequent postbacks.

<%@ Page Language="C#" AutoEventWireup="true"
 CodeFile="Default.aspx.cs" Inherits="_Default"
 ViewStateMode="Disabled"
 %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <p><asp:Label ID="Label1" Text="not set" runat="server" /></p>
        <p><asp:Label ID="Label2" Text="not set" ViewStateMode="Enabled" runat="server" /></p>
        <p><asp:Button Text="do a postback" runat="server" /></p>
    </div>
    </form>
</body>
</html>

Code behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Label1.Text = "this text has been set from code behind only on the first load i.e. not set in any following postbacks.";
        Label2.Text = Label1.Text;
    }
}

The first time the page loads, the 2 text boxes show the text as set in the code behind:

 

 



Once a postback happens (in this case by clicking the button), no code is executed in the Page_Load event due to the if (!IsPostBack) check. This means that the Text property of the labels will be set to what's initially declared in the aspx mark-up (i.e. "not set"); however because we have set ViewStateMode="Enabled" on Label2, it's Text will be retained in viewstate between callbacks:

 

SHARE:

Setting Meta Tags in ASP.Net 4

ASP.Net 4 adds 2 new Meta tag related properties to the Page. They can be used to set meta tags for keywords and description.

You can set them in the code behind:

Page.MetaKeywords = "keyword1, keyword2, keyword3";
Page.MetaDescription = "Example of new meta tag support in ASP.Net 4";

You can also set in the @Page directive:

<%@ Page Language="C#" AutoEventWireup="true"
MetaKeywords="keyword1, keyword2, keyword3"
MetaDescription="Example of new meta tag support in ASP.Net 4"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

The ouput of either of these methods renders html similar to the following:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
    ASP.NET 4 Meta Tag Support
</title><meta name="description" content="Example of new meta tag support in ASP.Net 4" /><meta name="keywords" content="keyword1, keyword2, keyword3" /></head>
<body>
 </body>
</html>
 

SHARE: