Serving a single page with a Cloudflare Worker

Serving a single page with a Cloudflare Worker

Ok, so I may have gone overboard on the dot dev domains, obviously, I purchased melodious.dev and forwarded it to this website but I also purchased two random domains:

I could have just forwarded these domains to melodiouscode.net, but on my lunch break, I decided to chuck some single page sites at them for giggles. I, however, did not want to spend any more money than I already do on domain-related things. In steps Cloudflare workers.

For those that do not know about workers; they are small chunks of javascript that you can run on the “edge” of Cloudflare. This means that you can execute code at the moment that a page is requested from your site. In the case of my serverless approach, the code executes before the page request has the chance to realise there is no web server!

The above code binds to the “page fetch” event before the page request is processed the worker code jumps in and grabs a static piece of HTML from my Azure Blob storage and returns that instead!
It is that simple, with just a few lines of javascript I can serve a simple web page without the need for a web server and at near-zero cost (seeing as I already pay for the workers and the blob storage cost is almost zero).

A quick post for a quick website! I may at some point put something more useful/meaningful/silly onto both of these domains, but for now, remember that you are a great dev because it works on your machine!

Update (15/03/2019)

Whilst monitoring a database migration this evening I decided to have a play with Cloudflare Workers again; i-am-a-great.dev is now purely served using a worker (no blob storage). On top of that, it also uses the Workers ‘Key Value Pair’ API to store a counter that is incremented each time the page is visited.

async function handleRequest(request) {
  let counter = await iamagreatdev.get("counter")
  let increment = parseInt(counter) + 1

  await iamagreatdev.put("counter",increment);

  let html = "...THE HTML FOR THE PAGE!..."
  
  html = html.replace("", increment)
  
  let securityHeaders = {
     //...
     //various headers
     //...
  }

  return new Response(html, {
    status: 200,
    statusText: "OK",
    headers: securityHeaders
  })
}

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

Thank you to Jamie Street on Unsplash for providing the header image for this post.

Read more

Passing multiple parameters to an ICommand in WPF

Passing multiple parameters to an ICommand in WPF

The project I am currently working on is a sizable line-of-business desktop program written using the WPF framework; a framework I particularly like working with due to its extensibility and ease of design (via XAML).
One of the powerful parts of WPF is the ICommand system for binding buttons to ViewModel methods; I won’t go into the details of it here as it deserves an article of its own. However one of its basic functions is the ability to pass a parameter from the UI back to the ViewModel’s ICommand property, such as the selected item in a data table.

The application I am currently working on has lots of nested UI components, and some of the button events need to pass back multiple parameters (something I had not done before). It seems that it is perfectly possible to pass more than one parameter from the XAML View up to the ViewModel.
The XAML is simple, you nest a MultiValueConverter inside your buttons CommandParameter element; you also need to provide a reference to an IMultiValueConverter (which you can define statically in a resource elsewhere in your application).

<Button Command="{Binding DeleteQuestionRuleCommand}" Content="Delete">
  <Button.CommandParameter>
    <MultiBinding Converter="{StaticResource ArrayMultiValueConverter}">
	  <Binding Path="SelectedItem" ElementName="comboPages" />
	  <Binding Path="SelectedItem" ElementName="gridQuestions" />
	  <Binding Path="SelectedItem" ElementName="gridRules" />
	</MultiBinding>
  </Button.CommandParameter>
</Button>

The easiest way to pass multiple parameters is as a simple object array; you can then test the objects are there and are the correct type in your CanExecute method. To do this you require an instance of an IMutiValueConverter; the following provides for the array based approach.

public class ArrayMultiValueConverter : IMultiValueConverter {
	#region interface implementations

	public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
		return values.Clone();
	}

	public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) {
		throw new NotImplementedException();
	}

	#endregion
}

Once your XAML and IMultiValueConverter are setup you will need to access the values within both your CanExecure and OnExecute methods, something which you can simply achieve by casting the passed in object argument to an object array.

private bool CanDeletePageRule(object obj) {
	if (obj is object[] parameters) {
		if (!(parameters[0] is QnaPageDefWrapper)) {
			return false;
		}

		if (!(parameters[1] is QnaRuleDefWrapper)) {
			return false;
		}
	}
	return true;
}

private void OnDeletePageRule(object obj) {
	if (!CanDeletePageRule(obj)) {
		return;
	}

	var parameters = (object[]) obj;

	var ruleToDelete = (QnaRuleDefWrapper) parameters[1];
	var pageToDeleteFrom = (QnaPageDefWrapper) parameters[0];

	pageToDeleteFrom.Rules.RemoveItem(r => r.RuleId == ruleToDelete.RuleId);

	RaiseUpdateMessage?.Invoke(this, "SelectedPageRule");
}

It really is that simple, two or more parameters can easily be passed using this approach.

The header image for this post was provided for free on unsplash.com by Hannah Joshua. Thanks Hannah!

Read more

Passing Enumerables to a SQL Stored Procedure

Passing Enumerables to a SQL Stored Procedure

I have been asked the question “Can you pass an enumerable to a procedure?” or “How do you pass a table to a stored procedure” several times in the past. The simple answer is “yes”, the slightly more complex answer is “yes, and this is how”!

How to pass an Enumerable to a SQL Stored Procedure in .NET

Although my example code here is in C# the same process applies to other .NET languages.
You can indeed pass an enumerable object to your Stored Procedure by using a special type of SQL object called a “User Defined Table Type”. UDTTs can be used to create tempory tables in a SQL Query without the need to fully write out the TABLE statement; in much the same way they can be used to pass a tempory table to a stored procedure. The only restriction is that the parameter passed into the query must be marked as read-only.
An example SQL statement to create a User Defined Table Type is as follows:

An example of using that type in a procedure is also as follows:

Now the question is how to execute a procedure from a .NET application passing in your enumerable? The easiest way is to create a Data Table with a matching schema to the UDTT.

You can then execute your stored procedure in the normal way, passing the table to the parameter on creation (or in your preferred way); just make sure you also set the TypeName of the parameter and set the type to Structured.

I neglected to take a screenshot of this bit when mocking the above code, so this is from a project I am working on! Sorry for the differing paramter names, but @LookupList would be @Table, and [FSD].[DetailLookup] is [dbo].[MyTableType].

Read more

Obtaining the meta data from a SQL Query

Obtaining the meta data from a SQL Query

I recently had a need to find a way of obtaining just the column names returned by a SQL Server Query; the query in question is ad-hoc and entered into an application by the user (in this case my application is a WPF desktop application, and the query is Microsoft T-SQL).

One quick and simple way of obtaining the column names would be to execute the query; I will not go into the details of why executing arbitrary SQL statements pasted into a text box by your users is a bad idea. Suffice to say it is a very bad idea; especially if your application is run with higher privileges. In my case, these pasted queries are also persisted in the database if a user with low rights passed a dangerous query someone with higher rights could come across it in the future causing it to be executed.

I needed to find an alternative; I contemplated a couple of things:

  • A complicated Regular Expression (RegEx)
  • Wrapping the execution in a BEGIN TRANSACTION and ROLLBACK TRANSACTION.
  • Running the query under a low (db_reader only) privilege account

Whichever way I looked at it the options didn’t seem great, and I thought there must be an alternative. It turns out there is!

Obtaining the SQL Query Meta Data (Columns) of a recordset without executing it!

From SQL Server 2012 a new Dynamic Management View (DMV) exists called sys.dm_exec_describe_first_result_set; this view allows you to obtain the metadata for the first possible result set in a T-SQL batch. Put simply it returns information about the columns returned from the first SELECT statement a query will hit (it is a little more complicated in that IF statements and the such can affect it, but basic queries work fine). The command takes an NVARCHAR parameter which will be analysed (but not executed); a table of results is then provided in the normal way. ![dm_exec_descrive_first_result_set__example-min](/images/content/dm_exec_descrive_first_result_set__example-min.PNG) In my use scenario I created a stored procedure which takes an NVARCHAR(MAX) string as a parameter and passes it to this command; returning to me a result set containing (amongst other things) all the column names in order.

It’s easy once you know how! I urge anyone who is reading this to check out the Microsoft Docs article on this command; as we all know you shouldn’t just run the code you find on some guy’s blog!

Read more