Category Archives: Tips & tricks

Cross-platform browser keyboard shortcuts

As of recently I began working on a Mac-book pro and I have to get used to a keyboard with different keys and different layout. One of the most used piece of software today is a browser. I routinely use Opera but there are still sites that don’t work well with it, although it uses pretty much the same rendering engine like Chrome.

I suspect these issues arise from the fact that Chrome tends to become the new IE 6 for many web developers (i.e. : write a page, test it in Chrome, it works, the rest of browsers doesn’t matter to me, continue to next page etc.).

I consider, just like Scott Hanselman, that using the keyboard is the most efficient way to command a computer (and not the mouse / touchpad) therefore I strive to use it to the max. However, switching from OS X to the Windows virtual machine back and forth can be confusing since there are different shortcuts. For example F5 in Windows refreshes the window while in OS X it doesn’t (be it because by default you have to press Fn and then F5 in order to send F5 otherwise a media function will be sent or because this key does not do this function).

Therefore I gathered a few useful shortcut keys that work in both Windows and OS X so I can use them. Many of them work across all major browsers (IE, Firefox, Chrome, Opera and Safari). Use Command (Cmd) key in OS X and Control (Ctrl) in Windows. I’ll include only the secondary key(s) in the table below since the primary key should be held down. I am planning to update this table several times.

Function Second key Internet Explorer Opera for Windows Opera for Mac Chrome for Windows Chrome for Mac
Quit (Close) app Q  x
Close tab (window) W  ✓
Refresh tab R  ✓
Open a new tab T  ✓
Open last closed tab SHIFT-T  ✓
View source U  ✓  x
Print page P  ✓
Select all page content A  ✓
Save current page to computer S  ✓
Add to favorites / bookmark D  ✓
Find in page F  ✓
Find again G  ✓
Show history H  ✓  x
View downloads J  ✓  x
Focus the address bar L  ✓
Undo Z  ✓
Cut X  ✓
Copy C  ✓
Paste V  ✓
Open a new window N  ✓
Open a new private window SHIFT-N  ✓

✓ = available
x = unavailable
[white_space] = not yet verified

(work in progress)

Dear readers, what other useful shortcuts is this table missing?

Building Client (JavaScript) Custom Validation in ASP.NET MVC 4 using jQuery

Introduction

I was recently asked by some students of mine how exactly is client custom validation done in ASP.NET MVC (4). I did this once before unobtrusive validation and jQuery in ASP.NET MVC 2.0 but then I lost contact with the implementation details.

In ASP.NET MVC 4 (this started in MVC 3) there is jQuery unobtrusive validation that works hand-in-hand with Data Annotations (a set of validation attributes that can decorate properties or even (view)model classes). I just remembered that you need to create a ValidationAttribute subclass and also implement IClientValidatable on it. Also you must decorate a property of the (View)Model with this attribute.

On the client side you need to write JavaScript code that provides a validation adapter and a validation function.

Let’s suppose we’d want to create an URL shortening service and on the “Add URL” page we’d have three fields :
– Original URL (textbox)
– Use custom slug (checkbox)
– Custom slug (textbox)

The “Original URL” textbox would be mandatory and the input format should be of a fully-qualified URL (for example “http://blog.andrei.rinea.ro” :P)

The custom slug textbox would be mandatory ONLY if the “Use custom slug” checkbox would be checked. This is the tough part since validating this field requires knowledge of another field’s value (the checkbox in this case). And by tough I mean having to write actual code because there is no out-of-the-box validator for this (not on the server-side nor on the client-side).

This small tutorial will asume that you have knowledge of the ASP.NET MVC platform and C#. I will not go into detail on matters such as what is the MVC pattern, what is the controller, view etc.

 

Implementation – server side

Let’s start by creating a new ASP.NET MVC 4 web project (select “Internet site” template).
We’ll create a UrlController controller with an action called Add :

using System.Web.Mvc;

namespace MVC4_jQuery_Unobtrusive_Custom_Validation.Controllers
{
    public class UrlController : Controller
    {
        [HttpGet]
        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Add(AddUrlViewModel userInput)
        {
            if (ModelState.IsValid)
            {
                // store the data
                // ...
                return RedirectToAction("Index", "Home");
            }
            return View();
        }
    }
}

Read more »

Windows Explorer contextual menu gotcha

Recently I had to extract the public key from a signed .NET assembly and I needed to run the sn.exe tool in order to obtain it. That required opening a command prompt and then setting the current directory to the one in which the assembly resided.

Typically I did :

  1. Win+R (Run)
  2. cmd
  3. Enter
  4. F: [ENTER] (or whatever the drive was)
  5. CD and either type the directory (using the TAB autocomplete or not) or copy the folder path and pasting it into the command prompt [ENTER]

Then I thought how can I simplify this little tedious task, which I sometimes do many times a day. After looking for Microsoft PowerToys which is no longer available I found out a little gem hidden in Windows Explorer. This is what my contextual menu looks like normally :

But just pressing (and keeping pressed) SHIFT before the right-click will give you this :

Selecting this command will do the opening of the command prompt and setting the drive and path in one click.

Of course, the next thing is to add the path to SN.EXE in the Environment Variable PATH in order to be able to execute it “anywhere”.

I hope this helps at least some of us 🙂

ReSharper hidden features – Generate Delegating Members

A frequently-used design pattern is the Decorator. This is also known as a mixin (or they might not be the very same thing but certainly they are related).

Typically you might need to create a class that implements a certain interface and uses another class that implements that exact interface but you need to provide some additional feature(s). An example would be a class that adds transactional behavior to an existing data-access class (a naive example) :


public interface IDataAccess
{
    void AddCustomerInvoice(Invoice invoice, User user);
}

public class DataAccess : IDataAccess
{
    public void AddCustomerInvoice(Invoice invoice, User user)
    {
        InsertInvoice(invoice, user);
        UpdateCustomerDebt(user, invoice.Total);
    }

    // ... the rest of the implementation
}

public class TransactionalDataAccess : IDataAccess
{
    private readonly IDataAccess _dataAccess;

    public TransactionalDataAccess(IDataAccess dataAccess)
    {
        if (dataAccess == null)
        {
            throw new ArgumentNullException();
        }
        _dataAccess = dataAccess;
    }

    public void AddCustomerInvoice(Invoice invoice, User user)
    {
         using(var tx = new TransactionScope())
         {
             _dataAccess.AddCustomerInvoice(invoice, user);
             tx.Complete();
         }
    }

    // ... the rest of the implementation
}

Another type of example would be the Adapter design pattern. An example would be providing access to a (static) class (that may be out of your control) in a mock-able manner. That is, implement another class, non-static, which implements a defined interface and eases unit-testing :

Read more »

A useful custom configuration section for inline unconstrained XML

As I was writing a small TCP server for serving a Silverlight local TCP policy, I came across a certain need. Inspired by Dan Wahlin’s server implementation, I chose to write a simplified version for myself. I needed to keep some XML in the App.config without constraining it with a schema.

The normal solution in this case is a custom section, sibling to appSettings if you wish. So my App.Config looked at first like this:

<configuration>
  <appSettings>
    <add key="ipAddress" value="127.0.0.1"/>
  </appSettings>
  <access-policy>
    <cross-domain-access>
      <policy>
        <allow-from>
          <domain uri="*" />
        </allow-from>
        <grant-to>
          <socket-resource port="4502" protocol="tcp" />
        </grant-to>
      </policy>
    </cross-domain-access>
  </access-policy>
</configuration>

Upon running the program, even addressing the “ipAddress” key in the appSettings section throws an exception like:

System.Configuration.ConfigurationErrorsException was unhandled
  Message="Configuration system failed to initialize"
  Source="System.Configuration"
  BareMessage="Configuration system failed to initialize"
  Line=0
  StackTrace:
       at System.Configuration.ConfigurationManager.PrepareConfigSystem()
       at System.Configuration.ConfigurationManager.GetSection(String sectionName)
       at System.Configuration.ConfigurationManager.get_AppSettings()
       at ConsoleApplication1.Program.Main(String[] args) in C:\Users\Andrei\Documents\Visual Studio 2008\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 21
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.Configuration.ConfigurationErrorsException
       Message="Unrecognized configuration section access-policy. 
               (C:\\Users\\Andrei\\Documents\\Visual Studio 2008\\Projects\\ConsoleApplication1\\ConsoleApplication1\\bin\\Debug\\ConsoleApplication1.vshost.exe.config line 8)"
       Source="System.Configuration"
       BareMessage="Unrecognized configuration section access-policy."
       Filename="C:\\Users\\Andrei\\Documents\\Visual Studio 2008\\Projects\\ConsoleApplication1\\ConsoleApplication1\\bin\\Debug\\ConsoleApplication1.vshost.exe.config"
       Line=8
       StackTrace:
            at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
            at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
            at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
            at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
       InnerException:

So something is wrong. We need to tell the runtime that the “access-policy” section is allowed.

<configuration>
  <strong>
   <configSections>
    <section name="access-policy" type="CustomSections.InlineXmlSection, CustomSections"/>
   </configSections>
  </strong>
  ...

At first, I didn’t place the type attribute in the “section” element, but it turned out it had to be specified and not be empty. Moreover, it must contain the fully-qualified class name and the assembly which contains it. The class must inherit from System.Configuration.ConfigurationSection.

So, I created an assembly called CustomSections, and added references to the System.Configuration assembly and the System.Xml assembly.

All you need to do is override the DeserializeSection method and load the XML document in there:

using System.Configuration;
using System.Xml;

namespace CustomSections
{
  public class InlineXmlSection : ConfigurationSection
  {
    public XmlDocument Content { get; private set; }

    protected override void DeserializeSection(XmlReader reader)
    {
      (this.Content = new XmlDocument()).Load(reader);
    }
  }
}

The code is pretty self-explanatory: we instantiate a new XmlDocument and load it from the XmlReader provided to us by the configuration infrastructure. If anything goes bad, the exception handling will be the responsibility of the caller. In this case, the first call to ConfigurationManager.

Now, let’s put the code to use:

private static void Main(string[] args)
{
  expectedRequestBytes = Encoding.UTF8.GetBytes("<policy-file-request/>");
  listener = new TcpListener(IPAddress.Parse(ConfigurationManager.AppSettings["ipAddress"]), 943);
  var policySection = (InlineXmlSection)ConfigurationManager.GetSection("access-policy");
  policyBytes = Encoding.UTF8.GetBytes(policySection.Content.OuterXml);
  ...
}

The underlined code is the relevant portion (the rest is provided for context). We get the section via ConfigurationManager.GetSection, and we have to cast the result to the desired section type. Then we use the section as we see fit.