Skip to content

Instantly share code, notes, and snippets.

@damieng
Created May 16, 2017 03:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damieng/0ed562e20c4f261e2f549e01ae2530da to your computer and use it in GitHub Desktop.
Save damieng/0ed562e20c4f261e2f549e01ae2530da to your computer and use it in GitHub Desktop.
Page View Count function in C# for Azure Functions
#r "Microsoft.WindowsAzure.Storage"
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System.Net;
public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
{
var page = req.GetQueryNameValuePairs().FirstOrDefault(kv => string.Compare(kv.Key, "page", true) == 0);
if (String.IsNullOrEmpty(page.Value)) return req.CreateResponse(HttpStatusCode.BadRequest);
var cloudService = CloudStorageAccount.Parse("ConnectionStringHere");
var table = cloudService.CreateCloudTableClient().GetTableReference("PageViewCounts");
var retrievedResult = table.Execute(TableOperation.Retrieve<PageViewCount>("damieng.com", page.Value));
var pageView = (PageViewCount)retrievedResult.Result;
if (pageView == null) {
pageView = new PageViewCount(page.Value) { ViewCount = 1 };
table.Execute(TableOperation.Insert(pageView));
} else {
pageView.ViewCount++;
table.Execute(TableOperation.Replace(pageView));
}
return req.CreateResponse(HttpStatusCode.OK, new {
page = page.Value,
viewCount = pageView.ViewCount
});
}
public class PageViewCount : TableEntity
{
public PageViewCount(string pageName)
{
this.PartitionKey = "damieng.com";
this.RowKey = pageName;
}
public PageViewCount() { }
public int ViewCount { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment