Created
May 16, 2017 03:47
-
-
Save damieng/0ed562e20c4f261e2f549e01ae2530da to your computer and use it in GitHub Desktop.
Page View Count function in C# for Azure Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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