Skip to content

Instantly share code, notes, and snippets.

@mikebrind
Last active August 24, 2017 16:49
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 mikebrind/e36fda6c6b041cd5bdad80da13df62ff to your computer and use it in GitHub Desktop.
Save mikebrind/e36fda6c6b041cd5bdad80da13df62ff to your computer and use it in GitHub Desktop.
using Microsoft.Extensions.Primitives;
using System;
using System.Data.SqlClient;
namespace RazorEngineViewOptionsFileProviders
{
public class DatabaseChangeToken : IChangeToken
{
private string _connection;
private string _viewPath;
public DatabaseChangeToken(string connection, string viewPath)
{
_connection = connection;
_viewPath = viewPath;
}
public bool ActiveChangeCallbacks => false;
public bool HasChanged
{
get
{
var query = "SELECT LastRequested, LastModified FROM Views WHERE Location = @Path;";
try
{
using (var conn = new SqlConnection(_connection))
using (var cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@Path", _viewPath);
conn.Open();
using (var reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
if (reader["LastRequested"] == DBNull.Value)
{
return false;
}
else
{
return Convert.ToDateTime(reader["LastModified"]) > Convert.ToDateTime(reader["LastRequested"]);
}
}
else
{
return false;
}
}
}
}
catch (Exception)
{
return false;
}
}
}
public IDisposable RegisterChangeCallback(Action<object> callback, object state) => EmptyDisposable.Instance;
}
internal class EmptyDisposable : IDisposable
{
public static EmptyDisposable Instance { get; } = new EmptyDisposable();
private EmptyDisposable() { }
public void Dispose() { }
}
}
@nokturnal
Copy link

Hey Mike, I love this but am having an issue where no matter what I do in DatabaseChangeToken the views are cached. If I simply return "true" in HasChanged get{} everything is still cached... Any insight as to why?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment