Razor and the @ symbol

May 18th, 2016

Another programmer asked me about when you use the @ symbol in Razor. This was my reply…

The @ sign is used for switching in and out of code. It is a razor thing – a bit like for most things. It can be used in the following ways (might be others I have missed too): -

To set the ModelType at the top
You can add in a block of code with
@Code

End Code
When you are in HTML, to call a function that outputs HTML or text
It usually works out where the end of the function call is by itself and switches back to HTML
If it doesn’t get it right, you can put brackets in – eg. @(Now.ToString(“dd/MM/yyyy”))
You can also use it to include an If/Using/With/loop in HTML – eg.

@For Each o in Orders
@

Next

When you are in code, to switch back to HTML, by placing it before an HTML tag
eg.
For Each o in Orders
@

Next
If you don’t want to output an HTML tag, you can use @ to switch back
When you are in code, you can use it to write the output of a function into the HTML – eg.

For Each o in Orders
@o.CustomerName @
Next

It is worth noting that you can call these functions from within code – eg. Html.LabelFor, but if you don’t stick the @ on the beginning, they won’t get written to the HTML – the result won’t go anywhere!

Also worth pointing out that you can nest back and forwards between HTML and code – eg..

@Code
If Model.Data.Count>0 Then
@

@For Each o in Model.Data
@


Next

Order ID Customer Name
@o.ID @o.Customer.Name

Else
@No results
End If
End Code

Lambda functions/subs in VB.NET

May 18th, 2016

Another programmer was asking me why you sometimes need “End Sub” on a Lambda Sub and sometimes you don’t. This was my reply…

There are 2 types of Lambda methods – inline and multi line. Inline is all on one line, so you can do…

Sub (x) DoSomethingWith(x)

nb. this is the same as

Sub (x) _
DoSomethingWith(x)

because VB.NET considers that multiple lines with _ at the end are all one. However, without the _ it is multiline…

Sub (x)
DoSomethingWith(x)
YouCanAlsoDoSomethingElseWith(x)
End Sub

That’s when you need End Sub – even if it is only one line in the body, you need to end it if you aren’t doing the body on the same line as the declaration.

nb. Functions work the same way, although there is one other difference with functions. Multiline functions work the same way as usual in terms of how you return from them, but inline you don’t use the Return keyword, so you would just do eg.

Function (x) x*2

In all of the above examples, you would want to provide types on the parameters (eg. x As Decimal). For inline functions, you can usually let the compiler work out the return type, but for multiline you should usually explicitly declare the return type (eg. Function(x As Decimal) As Decimal)

DOM and jQuery

December 16th, 2012

You may have seen references to a DOM, or Document Object Model.  What this is is a programmatic way of accessing elements within a document.  It most commonly refers to HTML, but there are other DOMs as well.

Traditionally in Javascript, DOM objects are accessed using functions such as document.getElementById. However, these days, script libraries such as jQuery have easier and more flexible ways to access objects. jQuery allows you to use CSS style selectors to identify a set of elements which meet your criteria. The way that the whole library is structured is primarily to focus on dealing with a set of elements instead of a single one. Because the functions generally return the selected elements, you can generally chain together a number of calls into a single line of (surprisingly readable) code very efficiently. For example, to select all anchor tags on a page, give them a CSS class of “test” and make them all fire an alert box when clicked, you would do something like this…

$(‘a’).addClass(‘test’).click(function(){alert(‘Link clicked!’);});

E-commerce frustrations in real life

December 16th, 2012

Google have posted a brilliant set of YouTube videos on the Analytics blog showing what kind of problems to look out for when considering usability of your online shop.  Well worth watching!

Do you know what a Nybble is?

December 13th, 2012

It isn’t really referred to very often, but a nybble is half a byte, or 4 bits.

Linq and IQueryable

December 13th, 2012

An IQueryable (and the Generic IQueryable(Of T)) in .NET is the main type that is used to store a Linq query. It is particularly useful as it is enumerable and has to implement IEnumberable too (and the generic equivalent).

It has 3 members: -

  • ElementType
  • Expression
  • Provider

ElementType is very simply the type of each individual item/record returned by the query.

Expression represents the query as an expression tree.  I have already touched on that in my previous posts.

Provider is the object which is able to take the expression and use it to retrieve data.  Typical providers include Linq to SQL, Linq to Entities (for the Entity Framework), Linq to XML etc.  There are many other implementations of Linq providers for all sorts of uses, including Linq to Amazon, Linq to Google etc.

A little about Linq

December 9th, 2012

Linq is a creation of Microsoft.  It is designed to solve a number of problems.  Part of the idea of Linq is to be able to abstract queries from the type of data source.  This enables all sorts of useful things.

So, for example, if we have a query

From c in Customers Where c.Tel <> “”

We don’t actually know what Customers is – it could be from a database, XML file, a set of objects in memory, from a web service, a text file, a third party API or any number of different sources.  The point is that we can write that query without worrying about that, and if we decide later to change what we are querying, or to use that same query for multiple sources, it should work just as well.

So how does that work then?  What happens when you write a Linq query is that the query is built into an Expression tree.  Expressions are the basic building blocks of the query.  An expression may be something like c.Tel <> “”, which would be broken down into…

  1. Access a property on the parameter c called Tel
  2. A constant, which is an empty string
  3. Take 1. and 2. (above) and use as the 2 sides of a binary operator, where the operator is not equals

What then happens is that when the query is executed, the provider for the particular type of data source will take those expressions and convert them into a form that it can execute (or possibly execute them directly).  For example, the Linq to SQL provider will take the parameter c and convert it into a string of “[c]“.  The property access on it will then get tacked on the end as “.[Tel]“, giving “[c].Tel”.  The empty string constant will be another string – “”’” (that’s two single quotes).  The not equals operator would be “<>” with the above stuck on either side, giving “[c].[Tel] <> ””.  The rest of the query would be compiled this way into SQL and then run to get the results.  The results would then be translated back into appropriate objects.

Now, if the same query was run on a set of objects in memory, the Linq provider would probably convert the expression into a lambda function, which would probably look like Function (c as Customer) c.Tel <>”".  It would then run a loop with some code a bit like the following (this is simplified a little)…

Dim WhereFunc = Function (c as Customer) c.Tel <> “”
Dim ret as New List(of Customer)
For Each c in Customers
If WhereFunc(c) Then ret.Add(c)
Next c
Return ret

As I said, this is a little over-simplified.  In actual fact, Linq queries are not executed until you explicitly try to access the results.  This is typically either using one of the extension methods suck as ToArray, ToList, Single, SingleOrDefault, First, FirstOrDefault or just starting to iterate through the data typically with a loop.

One of the more interesting things that you can do with Linq queries is that you can actually build queries on top of queries.  What this does behind the scenes is to actually create a new expression tree, usually containing a copy of the old one.

So, for example…

Dim cs = From c in Customers Where c.Tel<>”"
If MobileRequired Then cs = From c in cs Where c.Mobile<>”"

This is a very useful way of implementing a search form.  The effective query at the end if MobileRequired=True will be similar to (in SQL)
SELECT * FROM Customer c WHERE c.Tel<>”" AND c.Mobile<>”"

It is also possible to manipulate expression trees in order to create new modified versions of them to execute.  This can be useful in all sorts of ways, but it is too large a topic to include in this post, so I will hopefully come back to it at some point in the future.

Another benefit of Linq that I haven’t mentioned is that because it is part of the actual language, the compiler is aware of whether a query is well formed and querying actual existing fields.  This also means that Linq works well with intellisense, so Visual Studio can provide you with suggestions as you type a query, which is a very useful time saving feature.

Anything you think I’ve missed?  Please let me know!

Minimising downtime when transferring websites from one server to another

December 7th, 2012

Over the years, I’ve needed to do a lot of transfers of websites from one server to another.  I’ve found the following is the best way to do it for critical sites where you want to minimise downtime.  The red section is best done late at night or when the site is quiet and as quickly as possible so as to minimise disruption

  1. Set up space on new server
  2. Copy website files to new server
  3. If necessary, update config files on new server so that the website accesses data from the old one
  4. Update hosts file to test website on new server
  5. Test website on new server thoroughly
  6. Set up database user(s) on the new server and copy the database over and attach to test.  You may need to use this to re-attach users correctly on SQL Server
  7. Update the config file on the new server to point to the new database(s)
  8. Test that it is working again
  9. You may need to redo some of steps 2-8 a couple of times if things get changed on the original server while you are testing
  10. Remove hosts file entry used for testing
  11. Ensure that the firewall(s) allow access to the DB on the new server from the old one
  12. Once you are ready to finalise the transfer: Detach the database(s) on the old server or backup and detach
  13. Copy the database(s) to the new server (you may wish to zip them for transfer)
  14. While the database(s) are transferring, update the config on the site on the old server to connect to the new one
  15. Re-attach or restore the database on the new server.  You may need to re-attach users again
  16. Test that site is working on old server
  17. Re-set up hosts file entry for testing
  18. Re-test that site is working on new server
  19. Update DNS entries/name servers
  20. Remove hosts entry again
  21. If possible, test on another machine and connection which won’t have the DNS settings cached.  If not, wait for propagation and re-test

Whilst I primarily use this these days for IIS/MS SQL Server sites, it does work equally well for php/MySQL or any other platforms.  Also, although I am referring to sites on a single server, the same should also work for transferring between clusters.

jQuery can’t find element

December 7th, 2012

I keep having an annoying problem with jQuery where it doesn’t appear to be able to find an element.  This is actually a silly mistake on my part.  eg.

<div id=”msg”>Hello World</div>

<script type=”text/javascript”>

$(‘msg’).hide();

</script>

This is actually not a bug in jQuery at all – it is functioning correctly.  It should be $(‘#msg’).show(); since jQuery uses CSS style selectors.  $(‘msg’) would be looking for a tag named msg (ie. <msg>).

I figure that a lot of other people make the same mistake as it is easy to think of $() as being like document.getElementById, when it isn’t!  The reason that I’ve bothered posting about it is that I’ve ended up spending quite a bit of time trying to spot what I’ve done wrong!

Tagging and organisation of posts

December 7th, 2012

I made a conscious decision today to forget bothering to keep the posts organised here.  I feel that I’ve had a long break from the blog because I felt under pressure to tag and cross reference everything neatly.  Whilst it is no doubt better to, I think it is more important that I get around to posting at all, so I apologise for any inconvenience, but you’ve probably found this from Google anyway!