rc20-alpha8

mailling [WIP]
vnext
Paul Schneider 6 years ago
parent ae56b1b1a9
commit e2e74c50d5
24 changed files with 79 additions and 9383 deletions

@ -22,18 +22,22 @@ Yavsc.Server-deploy-pkg: Yavsc.Server
Yavsc.Abstract-deploy-pkg: Yavsc.Abstract
make -C Yavsc.Abstract deploy-pkg
cli-deploy-pkg: cli
cli-deploy-pkg: cli check
make -C cli deploy-pkg
cli: Yavsc-deploy-pkg
cli: Yavsc-deploy-pkg Yavsc.Server-deploy-pkg Yavsc.Abstract-deploy-pkg
make -C cli restore
make -C cli
undoLocalYavscNugetDeploy:
rm -rf ~/.dnx/packages/Yavsc.Abstract/$(VERSION)
rm -rf ~/.dnx/packages/Yavsc.Server/$(VERSION)
rm -rf ~/.dnx/packages/Yavsc.Abstract.$(VERSION).nupkg
rm -rf ~/.dnx/packages/Yavsc.Server.$(VERSION).nupkg
rm -rf ~/.dnx/packages/Yavsc.$(VERSION).nupkg
deploy-pkgs: Yavsc-deploy-pkg cli-deploy-pkg
check: cli
make -C cli check
deploy-pkgs: Yavsc-deploy-pkg Yavsc.Server-deploy-pkg Yavsc.Abstract-deploy-pkg cli-deploy-pkg
memo:
vim ~/TODO.md

@ -5,6 +5,14 @@ namespace Yavsc.Services
{
public interface IEmailSender
{
Task<bool> SendEmailAsync(string username, string email, string subject, string message);
/// <summary>
/// Sends en email.
/// </summary>
/// <param name="username">user name in database</param>
/// <param name="email">user's email</param>
/// <param name="subject">email subject</param>
/// <param name="message">message</param>
/// <returns>the message id</returns>
Task<string> SendEmailAsync(string username, string email, string subject, string message);
}
}

@ -98,8 +98,9 @@ namespace Yavsc.Services
return await NotifyEvent<HairCutQueryEvent>(registrationIds, ev);
}
public Task<bool> SendEmailAsync(string username, string email, string subject, string message)
public Task<string> SendEmailAsync(string username, string email, string subject, string message)
{
string messageId=null;
try
{
MimeMessage msg = new MimeMessage();
@ -112,6 +113,9 @@ namespace Yavsc.Services
Text = message
};
msg.Subject = subject;
msg.MessageId = MimeKit.Utils.MimeUtils.GenerateMessageId(
siteSettings.Authority
);
using (SmtpClient sc = new SmtpClient())
{
sc.Connect(
@ -119,13 +123,14 @@ namespace Yavsc.Services
smtpSettings.Port,
SecureSocketOptions.None);
sc.Send(msg);
messageId = msg.MessageId;
}
}
catch (Exception)
{
return Task.FromResult(false);
return Task.FromResult<string>(null);
}
return Task.FromResult(true);
return Task.FromResult(messageId);
}
public Task<bool> ValidateAsync(string purpose, string token, UserManager<ApplicationUser> manager, ApplicationUser user)

@ -38,8 +38,7 @@
]
},
"embed": [
"Resources/**/*.resx",
"Resources/ansi2html.sh"
"Resources/**/*.resx"
]
},
"tooling": {

@ -220,7 +220,7 @@ namespace Yavsc.Controllers
var emailSent = await _emailSender.SendEmailAsync(model.UserName, model.Email, _localizer["ConfirmYourAccountTitle"],
string.Format(_localizer["ConfirmYourAccountBody"], _siteSettings.Title, callbackUrl, _siteSettings.Slogan, _siteSettings.Audience));
await _signInManager.SignInAsync(user, isPersistent: false);
if (!emailSent)
if (emailSent==null)
{
_logger.LogWarning("User created with error sending email confirmation request");
this.NotifyWarning(
@ -255,9 +255,11 @@ namespace Yavsc.Controllers
{
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
var res = await _emailSender.SendEmailAsync(user.UserName, user.Email, "Confirm your account",
"Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
return res;
var res = await _emailSender.SendEmailAsync(user.UserName, user.Email,
this._localizer["ConfirmYourAccountTitle"],
string.Format(this._localizer["ConfirmYourAccountBody"],
_siteSettings.Title, callbackUrl, _siteSettings.Slogan, _siteSettings.Audience));
return res!=null;
}
//
// POST: /Account/LogOff

@ -1,22 +0,0 @@
all: build
build: project.lock.json
dnu build
deploy-pkg:
restore:
touch project.json
dnu restore
project.lock.json: project.json
dnu restore
run: project.lock.json
ASPNET_ENV=Development ASPNET_LOG_LEVEL=Debug dnx run

@ -1,48 +0,0 @@
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using System.Globalization;
using System.Reflection;
// using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Builder;
// using Microsoft.AspNet.Diagnostics;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Localization;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Filters;
using Microsoft.AspNet.Mvc.Razor;
using Microsoft.Net.Http.Headers;
using Microsoft.AspNet.Razor;
using Microsoft.Extensions.DependencyInjection.Abstractions;
using Microsoft.Extensions.PlatformAbstractions;
using cli.Services;
namespace cli
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder();
var hostengnine = host
.UseEnvironment("Development")
.UseServer("cli")
.UseStartup<Startup>()
.Build();
var app = hostengnine.Start();
var mailer = app.Services.GetService<EMailer>();
var loggerFactory = app.Services.GetService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<Program>();
mailer.AllUserGen(2,"UserOrientedTemplate");
logger.LogInformation("Finished");
}
}
}

@ -1,171 +0,0 @@
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.AspNet.Razor;
using Microsoft.AspNet.Razor.Generator;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.CSharp;
using Yavsc.Models;
using Yavsc.Models.Identity;
using System.Reflection;
using Yavsc.Templates;
using Yavsc.Abstract.Templates;
using Microsoft.AspNet.Identity.EntityFramework;
namespace cli.Services
{
public class EMailer
{
RazorTemplateEngine razorEngine;
IStringLocalizer<EMailer> stringLocalizer;
ILogger logger;
ApplicationDbContext dbContext;
const string DefaultBaseClassName = "ATemplate";
const string DefaultBaseClass = nameof(UserOrientedTemplate);
const string DefaultNamespace = "CompiledRazorTemplates";
RazorEngineHost host;
public EMailer(ApplicationDbContext context, IStringLocalizer<EMailer> localizer, ILoggerFactory loggerFactory)
{
stringLocalizer = localizer;
logger = loggerFactory.CreateLogger<EMailer>();
var language = new CSharpRazorCodeLanguage();
host = new RazorEngineHost(language)
{
DefaultBaseClass = DefaultBaseClass,
DefaultClassName = DefaultBaseClassName,
DefaultNamespace = DefaultNamespace
};
host.NamespaceImports.Add("System");
host.NamespaceImports.Add("Yavsc.Templates");
host.NamespaceImports.Add("Yavsc.Models");
host.NamespaceImports.Add("Yavsc.Models.Identity");
host.NamespaceImports.Add("Microsoft.AspNet.Identity.EntityFramework");
host.InstrumentedSourceFilePath = "bin/output/approot/src/";
host.StaticHelpers = true;
dbContext = context;
this.razorEngine = new RazorTemplateEngine(host);
}
public string GenerateTemplateObject(string baseclassName = DefaultBaseClassName)
{
throw new NotImplementedException();
}
public void AllUserGen(long templateCode, string baseclassName = DefaultBaseClassName)
{
string className = "Generated" + baseclassName;
string subtemp = stringLocalizer["MonthlySubjectTemplate"].Value;
logger.LogInformation($"Generating {subtemp}[{className}]");
var templateInfo = dbContext.MailingTemplate.FirstOrDefault(t => t.Id == templateCode);
logger.LogInformation($"Using code: {templateCode} and subject: {subtemp} ");
using (StringReader reader = new StringReader(templateInfo.Body))
{
// Generate code for the template
var razorResult = razorEngine.GenerateCode(reader, className, DefaultNamespace, "fakeFileName.cs");
logger.LogInformation("Razor exited " + (razorResult.Success ? "Ok" : "Ko") + ".");
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(razorResult.GeneratedCode);
string assemblyName = Path.GetRandomFileName();
MetadataReference[] references = new MetadataReference[]
{
MetadataReference.CreateFromFile( typeof(object).Assembly.Location),
MetadataReference.CreateFromFile( typeof(Enumerable).Assembly.Location),
MetadataReference.CreateFromFile( typeof(IdentityUser).Assembly.Location),
MetadataReference.CreateFromFile( typeof(ApplicationUser).Assembly.Location),
MetadataReference.CreateFromFile( typeof(Template).Assembly.Location)
};
var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
.WithModuleName("Yavsc.Absctract").WithModuleName("Yavsc")
.WithAllowUnsafe(true).WithOptimizationLevel(OptimizationLevel.Release)
.WithOutputKind(OutputKind.DynamicallyLinkedLibrary).WithPlatform(Platform.AnyCpu);
CSharpCompilation compilation = CSharpCompilation.Create(
assemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: compilationOptions);
foreach (var mref in references) logger.LogInformation($"ctor used ref to {mref.Display}[{mref.Properties.Kind}]");
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
foreach (Diagnostic diagnostic in result.Diagnostics.Where(diagnostic =>
diagnostic.Severity < DiagnosticSeverity.Error && !diagnostic.IsWarningAsError))
{
logger.LogWarning("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
logger.LogWarning("{0}: {1}", diagnostic.Id, diagnostic.Location.GetLineSpan());
}
if (!result.Success)
{
logger.LogInformation(razorResult.GeneratedCode);
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
logger.LogCritical("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
logger.LogCritical("{0}: {1}", diagnostic.Id, diagnostic.Location.GetLineSpan());
}
}
else
{
logger.LogInformation(razorResult.GeneratedCode);
ms.Seek(0, SeekOrigin.Begin);
Assembly assembly = Assembly.Load(ms.ToArray());
Type type = assembly.GetType(DefaultNamespace + "." + className);
var generatedtemplate = (UserOrientedTemplate)Activator.CreateInstance(type);
foreach (var user in dbContext.ApplicationUser)
{
logger.LogInformation("Generation for " + user.UserName);
generatedtemplate.Init();
generatedtemplate.User = user;
generatedtemplate.ExecuteAsync();
logger.LogInformation(generatedtemplate.GeneratedText);
}
/* ... type.InvokeMember("Write",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
model,
new object[] { "Hello World" }); */
}
}
}
}
}
}

@ -1,97 +0,0 @@
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using System.Globalization;
using System.Reflection;
// using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Builder;
// using Microsoft.AspNet.Diagnostics;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Localization;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Filters;
using Microsoft.AspNet.Mvc.Razor;
using Microsoft.Net.Http.Headers;
using Microsoft.AspNet.Razor;
using Microsoft.Extensions.DependencyInjection.Abstractions;
using Microsoft.Extensions.PlatformAbstractions;
using cli.Services;
using Yavsc;
using Yavsc.Models;
using Yavsc.Server.Helpers;
using Yavsc.Services;
using Yavsc.Templates;
namespace cli
{
public class Startup
{
public string ConnectionString
{
get { return DbHelpers.ConnectionString; }
private set { DbHelpers.ConnectionString = value; }
}
public static SiteSettings SiteSetup { get; private set; }
public static SmtpSettings SmtpSettup { get; private set; }
public static IConfiguration Configuration { get; set; }
public static string HostingFullName { get; private set; }
ILogger logger;
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var devtag = env.IsDevelopment()?"D":"";
var prodtag = env.IsProduction()?"P":"";
var stagetag = env.IsStaging()?"S":"";
HostingFullName = $"{appEnv.RuntimeFramework.FullName} [{env.EnvironmentName}:{prodtag}{devtag}{stagetag}]";
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddEnvironmentVariables()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
Configuration = builder.Build();
}
public void ConfigureServices (IServiceCollection services)
{
services.AddOptions();
var siteSettingsconf = Configuration.GetSection("Site");
services.Configure<SiteSettings>(siteSettingsconf);
var smtpSettingsconf = Configuration.GetSection("Smtp");
services.Configure<SmtpSettings>(smtpSettingsconf);
services.AddInstance(typeof(ILoggerFactory), new LoggerFactory());
services.AddTransient(typeof(IEmailSender), typeof(MessageSender));
services.AddTransient(typeof(RazorEngineHost), typeof(YaRazorEngineHost));
services.AddEntityFramework().AddNpgsql().AddDbContext<ApplicationDbContext>();
services.AddTransient((s) => new RazorTemplateEngine(s.GetService<RazorEngineHost>()));
services.AddLogging();
services.AddTransient<EMailer>();
services.AddLocalization(options =>
{
options.ResourcesPath = "Resources";
});
}
public void Configure (IApplicationBuilder app, IHostingEnvironment env,
IOptions<SiteSettings> siteSettings, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
logger = loggerFactory.CreateLogger<Startup>();
logger.LogInformation(env.EnvironmentName);
var cxstr = Configuration["Data:DefaultConnection:ConnectionString"];
DbHelpers.ConnectionString = cxstr;
}
}
}

@ -1,12 +0,0 @@
using System;
using Microsoft.AspNet.Razor;
namespace cli
{
public class YaRazorEngineHost: RazorEngineHost
{
public YaRazorEngineHost(): base()
{
}
}
}

@ -1,24 +0,0 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.Hosting.Server;
using Microsoft.AspNet.Http.Features;
using Microsoft.Extensions.Configuration;
using Yavsc.Models;
namespace Yavsc.Server
{
public class YavscServerFactory : IServerFactory
{
public IFeatureCollection Initialize(IConfiguration configuration)
{
FeatureCollection featureCollection = new FeatureCollection();
return featureCollection;
}
public IDisposable Start(IFeatureCollection serverFeatures, Func<IFeatureCollection, Task> application)
{
var task = application(serverFeatures);
return task;
}
}
}

@ -1,19 +0,0 @@
{
"Site": {
"Authority": "dev.pschneider.fr",
"Title": "Yavsc dev",
"Slogan": "Yavsc : WIP.",
"Banner": "/images/yavsc.png",
"HomeViewName": "Home",
"FavIcon": "/favicon.ico",
"Icon": "/images/yavsc.png"
},
"Logging": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Debug",
"System": "Warning",
"Microsoft": "Warning"
}
}
}

@ -1,9 +0,0 @@
{
"sdk": {
"version": "2.1.4",
"runtime": "mono",
"architecture": "x64"
}
}

@ -1,60 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.AspNet.Server.Kestrel" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="EntityFramework.Relational.Design" version="7.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.AspNet.Hosting.Abstractions" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="EntityFramework.Core" version="7.0.0-rc1-final" targetFramework="net451" />
<package id="EntityFramework.Relational" version="7.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.AspNet.Identity.EntityFramework" version="3.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.AspNet.Mvc.Razor" version="6.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.CodeAnalysis.Analyzers" version="1.0.0" targetFramework="net451" />
<package id="Microsoft.CodeAnalysis.Common" version="1.1.0-rc1" targetFramework="net451" />
<package id="Microsoft.CodeAnalysis.CSharp" version="1.1.0-rc1" targetFramework="net451" />
<package id="Microsoft.Dnx.Compilation.Abstractions" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Dnx.Compilation.CSharp.Abstractions" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Dnx.Compilation.CSharp.Common" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Extensions.Caching.Abstractions" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Extensions.Caching.Memory" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Extensions.Configuration" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Extensions.Configuration.Abstractions" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Extensions.Configuration.FileExtensions" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Extensions.Configuration.Json" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Extensions.DependencyInjection" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Extensions.Localization" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Extensions.Localization.Abstractions" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Extensions.Logging" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Extensions.Logging.Abstractions" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Extensions.MemoryPool" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Extensions.OptionsModel" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Extensions.PlatformAbstractions" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Extensions.Primitives" version="1.0.0-rc1-final" targetFramework="net451" />
<package id="Microsoft.Framework.ConfigurationModel" version="1.0.0-beta4" targetFramework="net451" />
<package id="Microsoft.Framework.ConfigurationModel.Interfaces" version="1.0.0-beta4" targetFramework="net451" />
<package id="Microsoft.Framework.ConfigurationModel.Json" version="1.0.0-beta4" targetFramework="net451" />
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net451" />
<package id="Remotion.Linq" version="2.0.1" targetFramework="net451" />
<package id="System.Collections" version="4.0.11" targetFramework="net451" />
<package id="System.Collections.Immutable" version="1.1.37" targetFramework="net451" />
<package id="System.Diagnostics.Debug" version="4.0.11" targetFramework="net451" />
<package id="System.Diagnostics.DiagnosticSource" version="4.0.0-beta-23516" targetFramework="net451" />
<package id="System.Diagnostics.Tracing" version="4.0.0" targetFramework="net451" />
<package id="System.Globalization" version="4.0.11" targetFramework="net451" />
<package id="System.IO" version="4.0.0" targetFramework="net451" />
<package id="System.Linq" version="4.1.0" targetFramework="net451" />
<package id="System.Reflection" version="4.1.0" targetFramework="net451" />
<package id="System.Reflection.Extensions" version="4.0.0" targetFramework="net451" />
<package id="System.Reflection.Metadata" version="1.1.0" targetFramework="net451" />
<package id="System.Reflection.Primitives" version="4.0.0" targetFramework="net451" />
<package id="System.Resources.ResourceManager" version="4.0.1" targetFramework="net451" />
<package id="System.Runtime" version="4.0.0" targetFramework="net451" />
<package id="System.Runtime.Extensions" version="4.1.0" targetFramework="net451" />
<package id="System.Runtime.InteropServices" version="4.1.0" targetFramework="net451" />
<package id="System.Text.Encoding" version="4.0.0" targetFramework="net451" />
<package id="System.Text.Encoding.Extensions" version="4.0.0" targetFramework="net451" />
<package id="System.Threading" version="4.0.0" targetFramework="net451" />
<package id="Yavsc.Abstract" version="1.0.5-rc9" targetFramework="net451" />
<package id="Yavsc.Server" version="1.0.5-rc9" targetFramework="net451" />
</packages>

@ -1,52 +0,0 @@
{
"version": "1.0.5-*",
"commands": {
"run": "cli"
},
"resource": "Resources/**/*.resx",
"buildOptions": {
"debugType": "full",
"emitEntryPoint": true,
"compile": {
"include": "*.cs",
"exclude": [
"contrib"
]
},
"embed": [
"Resources/**/*.resx"
]
},
"dependencies": {
"EntityFramework7.Npgsql": "3.1.0-rc1-3",
"MailKit": "1.12.0",
"Microsoft.CodeAnalysis": "1.0.0-rc1",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-*",
"Microsoft.AspNet.Hosting": "1.0.0-rc1-final",
"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-*",
"Microsoft.AspNet.Identity": "3.0.0-rc1-*",
"Microsoft.Framework.Configuration.Json": "1.0.0-beta8",
"Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta4",
"Microsoft.Extensions.DependencyInjection": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Abstractions": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.TraceSource": "1.0.0-rc1-final",
"Microsoft.Extensions.Globalization.CultureInfoCache": "1.0.0-rc1-final",
"Microsoft.Extensions.Localization": "1.0.0-rc1-final",
"Microsoft.Extensions.Localization.Abstractions": "1.0.0-rc1-final",
"Microsoft.Extensions.WebEncoders.Core": "1.0.0-rc1-final",
"Microsoft.Extensions.Options": "0.0.1-alpha",
"Microsoft.Extensions.WebEncoders": "1.0.0-rc1-final",
"Microsoft.Extensions.CodeGeneration": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
"Microsoft.Extensions.DependencyInjection.Abstractions": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
"Yavsc.Abstract": { "version": "1.0.5-rc14", "target": "package" },
"Yavsc": { "version": "1.0.5-rc14", "target": "package" }
},
"frameworks": {
"dnx451": {}
}
}

File diff suppressed because it is too large Load Diff

@ -1,26 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "cli", "cli\cli.csproj", "{DC25DCD0-19CB-4458-923A-40CE069A56BD}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{DC25DCD0-19CB-4458-923A-40CE069A56BD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DC25DCD0-19CB-4458-923A-40CE069A56BD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DC25DCD0-19CB-4458-923A-40CE069A56BD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DC25DCD0-19CB-4458-923A-40CE069A56BD}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
Policies = $0
$0.DotNetNamingPolicy = $1
$1.DirectoryNamespaceAssociation = PrefixedHierarchical
$0.TextStylePolicy = $2
$2.inheritsSet = null
$2.scope = application/json
$0.StandardHeader = $3
EndGlobalSection
EndGlobal

@ -8,6 +8,8 @@ all: $(BINTARGETPATH)
msbuild-restore:
$(MSBUILD) cli.csproj /t:Restore
check: run
run: project.lock.json
ASPNET_ENV=$(ASPNET_ENV) dnx run --configuration=$(CONFIGURATION)

@ -40,9 +40,8 @@ namespace cli
var mailer = app.Services.GetService<EMailer>();
var loggerFactory = app.Services.GetService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<Program>();
mailer.AllUserGen(2,"UserOrientedTemplate");
mailer.SendMonthlyEmail(2,"UserOrientedTemplate");
logger.LogInformation("Finished");
}
}
}

@ -62,7 +62,7 @@ namespace cli.Services
host.NamespaceImports.Add("Yavsc.Models");
host.NamespaceImports.Add("Yavsc.Models.Identity");
host.NamespaceImports.Add("Microsoft.AspNet.Identity.EntityFramework");
host.InstrumentedSourceFilePath = "bin/output/approot/src/";
host.InstrumentedSourceFilePath = ".";
host.StaticHelpers = true;
dbContext = context;
razorEngine = new RazorTemplateEngine(host);
@ -73,7 +73,7 @@ namespace cli.Services
throw new NotImplementedException();
}
public void AllUserGen(long templateCode, string baseclassName = DefaultBaseClassName)
public void SendMonthlyEmail(long templateCode, string baseclassName = DefaultBaseClassName)
{
string className = "Generated" + baseclassName;
@ -83,37 +83,47 @@ namespace cli.Services
var templateInfo = dbContext.MailingTemplate.FirstOrDefault(t => t.Id == templateCode);
logger.LogInformation($"Using code: {templateCode} and subject: {subtemp} ");
logger.LogInformation($"Using code: {templateCode}, subject: {subtemp} ");
logger.LogInformation("And body:\n"+templateInfo.Body);
using (StringReader reader = new StringReader(templateInfo.Body))
{
// Generate code for the template
var razorResult = razorEngine.GenerateCode(reader, className, DefaultNamespace, "fakeFileName.cs");
var razorResult = razorEngine.GenerateCode(reader, className, DefaultNamespace, DefaultNamespace+".cs");
logger.LogInformation("Razor exited " + (razorResult.Success ? "Ok" : "Ko") + ".");
logger.LogInformation(razorResult.GeneratedCode);
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(razorResult.GeneratedCode);
string assemblyName = Path.GetRandomFileName();
MetadataReference[] references = new MetadataReference[]
logger.LogInformation("CSharp parsed");
List<MetadataReference> references = new List<MetadataReference>();
foreach (var type in new Type[] {
typeof(object),
typeof(Enumerable),
typeof(IdentityUser),
typeof(ApplicationUser),
typeof(Template),
typeof(UserOrientedTemplate)
} )
{
MetadataReference.CreateFromFile( typeof(object).Assembly.Location),
MetadataReference.CreateFromFile( typeof(Enumerable).Assembly.Location),
MetadataReference.CreateFromFile( typeof(IdentityUser).Assembly.Location),
MetadataReference.CreateFromFile( typeof(ApplicationUser).Assembly.Location),
MetadataReference.CreateFromFile( typeof(Template).Assembly.Location),
MetadataReference.CreateFromFile( typeof(UserOrientedTemplate).Assembly.Location)
};
logger.LogInformation("typeof(Template).Assembly.Location: "+typeof(Template).Assembly.Location);
var location = type.Assembly.Location;
if (!string.IsNullOrWhiteSpace(location)) {
references.Add(
MetadataReference.CreateFromFile(location)
);
logger.LogInformation($"Assembly for {type.Name} found at {location}");
} else logger.LogWarning($"Assembly Not found for {type.Name}");
}
logger.LogInformation("Compilation creation ...");
var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
.WithAllowUnsafe(true).WithOptimizationLevel(OptimizationLevel.Release)
.WithAllowUnsafe(true).WithOptimizationLevel(OptimizationLevel.Debug)
.WithOutputKind(OutputKind.DynamicallyLinkedLibrary).WithPlatform(Platform.AnyCpu)
.WithUsings("Yavsc.Templates")
;
string assemblyName = DefaultNamespace;
CSharpCompilation compilation = CSharpCompilation.Create(
assemblyName,
syntaxTrees: new[] { syntaxTree },
@ -121,9 +131,9 @@ namespace cli.Services
options: compilationOptions
);
using (var ms = new MemoryStream())
{
logger.LogInformation("Emitting result ...");
EmitResult result = compilation.Emit(ms);
foreach (Diagnostic diagnostic in result.Diagnostics.Where(diagnostic =>
diagnostic.Severity < DiagnosticSeverity.Error && !diagnostic.IsWarningAsError))
@ -151,7 +161,9 @@ namespace cli.Services
Type type = assembly.GetType(DefaultNamespace + "." + className);
var generatedtemplate = (UserOrientedTemplate)Activator.CreateInstance(type);
foreach (var user in dbContext.ApplicationUser)
foreach (var user in dbContext.ApplicationUser.Where(
u => u.AllowMonthlyEmail
))
{
logger.LogInformation("Generation for " + user.UserName);
generatedtemplate.Init();
@ -160,13 +172,6 @@ namespace cli.Services
logger.LogInformation(generatedtemplate.GeneratedText);
}
/* ... type.InvokeMember("Write",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
model,
new object[] { "Hello World" }); */
}
}
}

@ -1,44 +0,0 @@
{
"Site": {
"Authority": "dev.pschneider.fr",
"Title": "Yavsc dev",
"Slogan": "Yavsc : WIP.",
"Banner": "/images/yavsc.png",
"HomeViewName": "Home",
"FavIcon": "/favicon.ico",
"Icon": "/images/yavsc.png",
"Owner": {
"Name": "Paul",
"EMail": "paul@pschneider.fr",
"PostalAddress": {
"Street1": "2 Blv A. Briand",
"Street2": "Apt 284 - Bat V",
"PostalCode": "92150",
"City": "Suresnes",
"State": "France",
"Province": null
}
},
"Admin": {
"Name": "Paul",
"EMail": "contact@pschneider.fr"
},
"UserFiles": {
"Avatars": "Avatars-Dev",
"Quota": 200000000,
"Bills": "Bills-Dev",
"Blog": "Blog-Dev"
},
"TempDir": "Temp-Dev"
},
"Smtp": {
"Host": "localhost",
"Port": 25,
"EnableSSL": false
},
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=localhost;Port=5432;Database=YavscDev;Username=yavscdev;Password=admin;"
}
}
}

@ -1,7 +1,7 @@
{
"version": "1.0.5-*",
"commands": {
"run": "cli"
"run": "run"
},
"resource": "Resources/**/*.resx",
"buildOptions": {
@ -44,9 +44,13 @@
"Microsoft.Framework.Configuration.Json": "1.0.0-beta8",
"Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta4",
"Newtonsoft.Json": "9.0.1",
"Yavsc": { "version": "1.0.5-rc20-alpha7", "target": "package" }
"Yavsc": { "version": "1.0.5-rc20-alpha8", "target": "package" },
"Yavsc.Abstract": { "version": "1.0.5-rc20-alpha8", "target": "package" },
"Yavsc.Server": { "version": "1.0.5-rc20-alpha8", "target": "package" }
},
"frameworks": {
"dnx451": {}
"dnx451": {
"System.Net": "4.0.0"
}
}
}

@ -1 +1 @@
20-alpha7
20-alpha8

Loading…