Skip to content

Instantly share code, notes, and snippets.

Created September 11, 2017 08:13
Show Gist options
  • Save anonymous/4e3febc8dcfb3c38fe0f590e0b6767c3 to your computer and use it in GitHub Desktop.
Save anonymous/4e3febc8dcfb3c38fe0f590e0b6767c3 to your computer and use it in GitHub Desktop.
var engine = new EngineFactory().Create(new StringContentRazorProject(
getContentFunc: key =>
{
var template = _templateRepository.GetByIdAsync(Guid.Parse(key)).Result;
if (template == null)
throw new Exception("Template is null");
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(template.BodyContent);
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
return stream;
},
existsCheckFunc: key =>
{
var template = _templateRepository.GetByIdAsync(Guid.Parse(key)).Result;
return template != null;
}));
public class StringContentRazorProject : RazorLightProject
{
public StringContentRazorProject(Func<string, Stream> getContentFunc, Func<string, bool> existsCheckFunc)
{
this.GetContentFunc = getContentFunc;
this.ExistsCheckFunc = existsCheckFunc;
}
public Func<string, Stream> GetContentFunc { get; }
public Func<string, bool> ExistsCheckFunc { get; }
public override Task<RazorLightProjectItem> GetItemAsync(string templateKey)
{
var item = new StringContentRazorProjectItem(templateKey, getContentFunc: GetContentFunc, existsCheckFunc: ExistsCheckFunc);
return Task.FromResult((RazorLightProjectItem)item);
}
public override Task<IEnumerable<RazorLightProjectItem>> GetImportsAsync(string templateKey)
{
return Task.FromResult(Enumerable.Empty<RazorLightProjectItem>());
}
}
public class StringContentRazorProjectItem : RazorLightProjectItem
{
public StringContentRazorProjectItem(string key, Func<string, Stream> getContentFunc, Func<string, bool> existsCheckFunc)
{
Key = key;
this.GetContentFunc = getContentFunc;
this.ExistsCheckFunc = existsCheckFunc;
}
public override string Key { get; set; }
public Func<string, Stream> GetContentFunc { get; }
public Func<string, bool> ExistsCheckFunc { get; }
public override bool Exists
{
get
{
return ExistsCheckFunc(Key);
}
}
public override Stream Read()
{
return GetContentFunc(Key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment