public void DeleteLite([Required, FromBody] LiteOperationRequest request) { OperationLogic.ServiceDelete(request.lite, request.GetOperationSymbol(request.lite.EntityType), request.Args); }
public EntityPackTS ExecuteLite([Required, FromBody] LiteOperationRequest request) { var entity = OperationLogic.ServiceExecuteLite(request.lite, request.GetOperationSymbol(request.lite.EntityType), request.Args); return(SignumServer.GetEntityPack(entity)); }
public void DeleteEntity([Required, FromBody] EntityOperationRequest request) { OperationLogic.ServiceDelete(request.entity, request.GetOperationSymbol(request.entity.GetType()), request.Args); }
public EntityPackTS?ConstructFromEntity([Required, FromBody] EntityOperationRequest request) { var entity = OperationLogic.ServiceConstructFrom(request.entity, request.GetOperationSymbol(request.entity.GetType()), request.Args); return(entity == null ? null : SignumServer.GetEntityPack(entity)); }
public EntityPackTS?ConstructFromLite([Required, FromBody] LiteOperationRequest request) { var entity = OperationLogic.ServiceConstructFromLite(request.lite, request.GetOperationSymbol(request.lite.EntityType), request.Args); return(entity == null ? null : SignumServer.GetEntityPack(entity)); }
public EntityPackTS ConstructFromEntity(EntityOperationRequest request) { var entity = OperationLogic.ServiceConstructFrom(request.entity, request.operarionSymbol, request.args); return(SignumServer.GetEntityPack(entity)); }
public static Dictionary <string, TypeInfoTS> GetEntities(IEnumerable <Type> allTypes) { var models = (from type in allTypes where typeof(ModelEntity).IsAssignableFrom(type) && !type.IsAbstract select type).ToList(); var queries = QueryLogic.Queries; var schema = Schema.Current; var settings = Schema.Current.Settings; var result = (from type in TypeLogic.TypeToEntity.Keys.Concat(models) where !type.IsEnumEntity() && !ReflectionServer.ExcludeTypes.Contains(type) let descOptions = LocalizedAssembly.GetDescriptionOptions(type) let allOperations = !type.IsEntity() ? null : OperationLogic.GetAllOperationInfos(type) select KVP.Create(GetTypeName(type), OnAddTypeExtension(new TypeInfoTS { Kind = KindOfType.Entity, FullName = type.FullName, NiceName = descOptions.HasFlag(DescriptionOptions.Description) ? type.NiceName() : null, NicePluralName = descOptions.HasFlag(DescriptionOptions.PluralDescription) ? type.NicePluralName() : null, Gender = descOptions.HasFlag(DescriptionOptions.Gender) ? type.GetGender().ToString() : null, EntityKind = type.IsIEntity() ? EntityKindCache.GetEntityKind(type) : (EntityKind?)null, EntityData = type.IsIEntity() ? EntityKindCache.GetEntityData(type) : (EntityData?)null, IsLowPopulation = type.IsIEntity() ? EntityKindCache.IsLowPopulation(type) : false, IsSystemVersioned = type.IsIEntity() ? schema.Table(type).SystemVersioned != null : false, ToStringFunction = typeof(Symbol).IsAssignableFrom(type) ? null : LambdaToJavascriptConverter.ToJavascript(ExpressionCleaner.GetFieldExpansion(type, miToString)), QueryDefined = queries.QueryDefined(type), Members = PropertyRoute.GenerateRoutes(type).Where(pr => InTypeScript(pr)) .ToDictionary(p => p.PropertyString(), p => { var mi = new MemberInfoTS { NiceName = p.PropertyInfo?.NiceName(), TypeNiceName = GetTypeNiceName(p.PropertyInfo?.PropertyType), Format = p.PropertyRouteType == PropertyRouteType.FieldOrProperty ? Reflector.FormatString(p) : null, IsReadOnly = !IsId(p) && (p.PropertyInfo?.IsReadOnly() ?? false), Unit = UnitAttribute.GetTranslation(p.PropertyInfo?.GetCustomAttribute <UnitAttribute>()?.UnitName), Type = new TypeReferenceTS(IsId(p) ? PrimaryKey.Type(type).Nullify() : p.PropertyInfo?.PropertyType, p.Type.IsMList() ? p.Add("Item").TryGetImplementations() : p.TryGetImplementations()), IsMultiline = Validator.TryGetPropertyValidator(p)?.Validators.OfType <StringLengthValidatorAttribute>().FirstOrDefault()?.MultiLine ?? false, MaxLength = Validator.TryGetPropertyValidator(p)?.Validators.OfType <StringLengthValidatorAttribute>().FirstOrDefault()?.Max.DefaultToNull(-1), PreserveOrder = settings.FieldAttributes(p)?.OfType <PreserveOrderAttribute>().Any() ?? false, }; return(OnAddPropertyRouteExtension(mi, p)); }), Operations = allOperations == null ? null : allOperations.ToDictionary(oi => oi.OperationSymbol.Key, oi => OnAddOperationExtension(new OperationInfoTS(oi), oi, type)), RequiresEntityPack = allOperations != null && allOperations.Any(oi => oi.HasCanExecute != null), }, type))).ToDictionaryEx("entities"); return(result); }
public void SmartSaveMListOrder() { using (var tr = new Transaction()) using (OperationLogic.AllowSave <LabelEntity>()) using (OperationLogic.AllowSave <CountryEntity>()) using (OperationLogic.AllowSave <AlbumEntity>()) using (OperationLogic.AllowSave <ArtistEntity>()) { var artist = Database.Query <ArtistEntity>().First(); var album = new AlbumEntity { Name = "Test album", Author = artist, Year = 2000, Songs = { new SongEmbedded { Name = "Song 0" }, new SongEmbedded { Name = "Song 1" }, new SongEmbedded { Name = "Song 2" }, }, State = AlbumState.Saved, Label = new LabelEntity { Name = "Four Music", Country = new CountryEntity { Name = "Germany" }, Node = MusicLoader.NextLabelNode() }, }; album.Save(); AssertSequenceEquals(album.MListElements(a => a.Songs).OrderBy(a => a.Order).Select(mle => KeyValuePair.Create(mle.Order, mle.Element.Name)), new Dictionary <int, string> { { 0, "Song 0" }, { 1, "Song 1" }, { 2, "Song 2" } }); var ids = album.MListElements(a => a.Songs).Select(a => a.RowId).ToHashSet(); album.Songs.SortDescending(a => a.Name); album.Save(); var ids2 = album.MListElements(a => a.Songs).Select(a => a.RowId).ToHashSet(); AssertSequenceEquals(ids.OrderBy(), ids2.OrderBy()); AssertSequenceEquals(album.MListElements(a => a.Songs).OrderBy(a => a.Order).Select(mle => KeyValuePair.Create(mle.Order, mle.Element.Name)), new Dictionary <int, string> { { 0, "Song 2" }, { 1, "Song 1" }, { 2, "Song 0" } }); var s3 = album.Songs[0]; album.Songs.RemoveAt(0); album.Songs.Insert(1, s3); album.Save(); AssertSequenceEquals(album.MListElements(a => a.Songs).OrderBy(a => a.Order).Select(mle => KeyValuePair.Create(mle.Order, mle.Element.Name)), new Dictionary <int, string> { { 0, "Song 1" }, { 1, "Song 2" }, { 2, "Song 0" } }); AssertSequenceEquals(album.ToLite().RetrieveAndRemember().Songs.Select(a => a.Name), new[] { "Song 1", "Song 2", "Song 0" }); //tr.Commit(); } }
//Errors with CNTK: https://github.com/Microsoft/CNTK/issues/2614 public void Train(PredictorTrainingContext ctx) { InitialSetup(); tf.compat.v1.disable_eager_execution(); var p = ctx.Predictor; var nn = (NeuralNetworkSettingsEntity)p.AlgorithmSettings; Tensor inputPlaceholder = tf.placeholder(tf.float32, new[] { -1, ctx.InputCodifications.Count }, "inputPlaceholder"); Tensor outputPlaceholder = tf.placeholder(tf.float32, new[] { -1, ctx.OutputCodifications.Count }, "outputPlaceholder"); Tensor currentTensor = inputPlaceholder; nn.HiddenLayers.ForEach((layer, i) => { currentTensor = NetworkBuilder.DenseLayer(currentTensor, layer.Size, layer.Activation, layer.Initializer, p.Settings.Seed ?? 0, "hidden" + i); }); Tensor output = NetworkBuilder.DenseLayer(currentTensor, ctx.OutputCodifications.Count, nn.OutputActivation, nn.OutputInitializer, p.Settings.Seed ?? 0, "output"); Tensor calculatedOutput = tf.identity(output, "calculatedOutput"); Tensor loss = NetworkBuilder.GetEvalFunction(nn.LossFunction, outputPlaceholder, calculatedOutput); Tensor accuracy = NetworkBuilder.GetEvalFunction(nn.EvalErrorFunction, outputPlaceholder, calculatedOutput); // prepare for training Optimizer optimizer = NetworkBuilder.GetOptimizer(nn); Operation trainOperation = optimizer.minimize(loss); Random rand = p.Settings.Seed == null ? new Random() : new Random(p.Settings.Seed.Value); var(training, validation) = ctx.SplitTrainValidation(rand); var minibachtSize = nn.MinibatchSize; var numMinibatches = nn.NumMinibatches; Stopwatch sw = Stopwatch.StartNew(); List <FinalCandidate> candidate = new List <FinalCandidate>(); var config = new ConfigProto { IntraOpParallelismThreads = 1, InterOpParallelismThreads = 1, LogDevicePlacement = true }; ctx.ReportProgress($"Deleting Files"); var dir = PredictorDirectory(ctx.Predictor); if (Directory.Exists(dir)) { Directory.Delete(dir, true); } Directory.CreateDirectory(dir); ctx.ReportProgress($"Starting training..."); var saver = tf.train.Saver(); using (var sess = tf.Session(config)) { sess.run(tf.global_variables_initializer()); for (int i = 0; i < numMinibatches; i++) { using (HeavyProfiler.Log("MiniBatch", () => i.ToString())) { var trainMinibatch = 0.To(minibachtSize).Select(_ => rand.NextElement(training)).ToList(); var inputValue = CreateNDArray(ctx, trainMinibatch, ctx.InputCodifications.Count, ctx.InputCodificationsByColumn); var outputValue = CreateNDArray(ctx, trainMinibatch, ctx.OutputCodifications.Count, ctx.OutputCodificationsByColumn); using (HeavyProfiler.Log("TrainMinibatch", () => i.ToString())) { sess.run(trainOperation, (inputPlaceholder, inputValue), (outputPlaceholder, outputValue)); } if (ctx.StopTraining) { p = ctx.Predictor = ctx.Predictor.ToLite().RetrieveAndRemember(); } var isLast = numMinibatches - nn.BestResultFromLast <= i; if (isLast || (i % nn.SaveProgressEvery) == 0 || ctx.StopTraining) { float loss_val; float accuracy_val; using (HeavyProfiler.Log("EvalTraining", () => i.ToString())) { (loss_val, accuracy_val) = sess.run((loss, accuracy), (inputPlaceholder, inputValue), (outputPlaceholder, outputValue)); } var ep = new EpochProgress { Ellapsed = sw.ElapsedMilliseconds, Epoch = i, TrainingExamples = i * minibachtSize, LossTraining = loss_val, AccuracyTraining = accuracy_val, LossValidation = null, AccuracyValidation = null, }; ctx.ReportProgress($"Training Minibatches Loss:{loss_val} / Accuracy:{accuracy_val}", (i + 1) / (decimal)numMinibatches); ctx.Progresses.Enqueue(ep); if (isLast || (i % nn.SaveValidationProgressEvery) == 0 || ctx.StopTraining) { using (HeavyProfiler.LogNoStackTrace("EvalValidation")) { var validateMinibatch = 0.To(minibachtSize).Select(_ => rand.NextElement(validation)).ToList(); var inputValValue = CreateNDArray(ctx, validateMinibatch, ctx.InputCodifications.Count, ctx.InputCodificationsByColumn); var outputValValue = CreateNDArray(ctx, validateMinibatch, ctx.OutputCodifications.Count, ctx.OutputCodificationsByColumn); (loss_val, accuracy_val) = sess.run((loss, accuracy), (inputPlaceholder, inputValValue), (outputPlaceholder, outputValValue)); ep.LossValidation = loss_val; ep.AccuracyValidation = accuracy_val; } } var progress = ep.SaveEntity(ctx.Predictor); if (isLast || ctx.StopTraining) { Directory.CreateDirectory(TrainingModelDirectory(ctx.Predictor, i)); var save = saver.save(sess, Path.Combine(TrainingModelDirectory(ctx.Predictor, i), ModelFileName)); using (HeavyProfiler.LogNoStackTrace("FinalCandidate")) { candidate.Add(new FinalCandidate { ModelIndex = i, ResultTraining = new PredictorMetricsEmbedded { Accuracy = progress.AccuracyTraining, Loss = progress.LossTraining }, ResultValidation = new PredictorMetricsEmbedded { Accuracy = progress.AccuracyValidation, Loss = progress.LossValidation }, }); } } } if (ctx.StopTraining) { break; } } } } var best = candidate.MinBy(a => a.ResultValidation.Loss !.Value) !; p.ResultTraining = best.ResultTraining; p.ResultValidation = best.ResultValidation; var files = Directory.GetFiles(TrainingModelDirectory(ctx.Predictor, best.ModelIndex)); p.Files.AddRange(files.Select(p => new Entities.Files.FilePathEmbedded(PredictorFileType.PredictorFile, p))); using (OperationLogic.AllowSave <PredictorEntity>()) p.Save(); }
public static bool LoginAzureADAuthentication(ActionContext ac, string jwt, bool throwErrors) { using (AuthLogic.Disable()) { try { var ada = (ActiveDirectoryAuthorizer)AuthLogic.Authorizer !; if (!ada.GetConfig().LoginWithAzureAD) { return(false); } var principal = ValidateToken(jwt, out var jwtSecurityToken); var ctx = new AzureClaimsAutoCreateUserContext(principal); UserEntity?user = Database.Query <UserEntity>().SingleOrDefault(a => a.Mixin <UserOIDMixin>().OID == ctx.OID); if (user == null) { user = Database.Query <UserEntity>().SingleOrDefault(a => a.UserName == ctx.UserName) ?? (ctx.UserName.Contains("@") && ada.GetConfig().AllowMatchUsersBySimpleUserName ? Database.Query <UserEntity>().SingleOrDefault(a => a.Email == ctx.UserName || a.UserName == ctx.UserName.Before("@")) : null); if (user != null) { using (AuthLogic.Disable()) using (OperationLogic.AllowSave <UserEntity>()) { user.Mixin <UserOIDMixin>().OID = ctx.OID; user.UserName = ctx.UserName; user.Email = ctx.EmailAddress; if (!UserOIDMixin.AllowUsersWithPassswordAndOID) { user.PasswordHash = null; } user.Save(); } } } if (user == null) { user = ada.OnAutoCreateUser(ctx); if (user == null) { return(false); } } AuthServer.OnUserPreLogin(ac, user); AuthServer.AddUserSession(ac, user); return(true); } catch (Exception ex) { ex.LogException(); if (throwErrors) { throw; } return(false); } } }
public void SmartSaveMList() { using (var tr = new Transaction()) using (OperationLogic.AllowSave <LabelEntity>()) using (OperationLogic.AllowSave <CountryEntity>()) using (OperationLogic.AllowSave <AlbumEntity>()) using (OperationLogic.AllowSave <ArtistEntity>()) { var maxRowId = Database.MListQuery((AlbumEntity a) => a.Songs).Max(a => a.RowId); var artist = Database.Query <ArtistEntity>().First(); var album = new AlbumEntity { Name = "Test album", Author = artist, Year = 2000, Songs = { new SongEmbedded { Name = "Song 1" } }, State = AlbumState.Saved, Label = new LabelEntity { Name = "Four Music", Country = new CountryEntity { Name = "Germany" }, Node = MusicLoader.NextLabelNode() }, }; var innerList = ((IMListPrivate <SongEmbedded>)album.Songs).InnerList; Assert.Null(innerList[0].RowId); //Insert and row-id is set album.Save(); Assert.NotNull(innerList[0].RowId); Assert.True(innerList[0].RowId > maxRowId); album.Songs.Add(new SongEmbedded { Name = "Song 2" }); Assert.Null(innerList[1].RowId); album.Save(); //Insert and row-id is set Assert.NotNull(innerList[1].RowId); var song = innerList[0]; album.Songs.Remove(song.Element); //Delete album.Save(); { var album2 = album.ToLite().RetrieveAndRemember(); Assert.True(album.Songs.Count == album2.Songs.Count); Assert.True(innerList[0].RowId == ((IMListPrivate <SongEmbedded>)album2.Songs).InnerList[0].RowId); Assert.True(!album.MListElements(a => a.Songs).Any(mle => mle.RowId == song.RowId)); } album.Songs[0].Name += "*"; //Update album.Save(); { var album2 = album.ToLite().RetrieveAndRemember(); Assert.True(album.Songs.Count == album2.Songs.Count); Assert.True(innerList[0].RowId == ((IMListPrivate <SongEmbedded>)album2.Songs).InnerList[0].RowId); Assert.True(album.Songs[0].Name == album2.Songs[0].Name); Assert.True(!album.MListElements(a => a.Songs).Any(mle => mle.RowId == song.RowId)); } //tr.Commit(); } }
public void DeleteLite(LiteOperationRequest request) { OperationLogic.ServiceDelete(request.lite, request.operarionSymbol, request.args); }
public void DeleteEntity(EntityOperationRequest request) { OperationLogic.ServiceDelete(request.entity, request.operarionSymbol, request.args); }
public EntityPackTS ExecuteLite(LiteOperationRequest request) { var entity = OperationLogic.ServiceExecuteLite(request.lite, request.operarionSymbol, request.args); return(SignumServer.GetEntityPack(entity)); }
public Dictionary <OperationSymbol, string> GetCanExecuteAll(Entity entity) { return(Return(MethodInfo.GetCurrentMethod(), entity.GetType().Name, () => OperationLogic.ServiceCanExecute(entity))); }
public static void Start(string connectionString) { using (HeavyProfiler.Log("Start")) using (var initial = HeavyProfiler.Log("Initial")) { StartParameters.IgnoredDatabaseMismatches = new List <Exception>(); StartParameters.IgnoredCodeErrors = new List <Exception>(); string logDatabase = Connector.TryExtractDatabaseNameWithPostfix(ref connectionString, "_Log"); SchemaBuilder sb = new CustomSchemaBuilder { LogDatabaseName = logDatabase, Tracer = initial }; sb.Schema.Version = typeof(Starter).Assembly.GetName().Version; sb.Schema.ForceCultureInfo = CultureInfo.GetCultureInfo("en-US"); MixinDeclarations.Register <OperationLogEntity, DiffLogMixin>(); MixinDeclarations.Register <UserEntity, UserEmployeeMixin>(); OverrideAttributes(sb); var detector = SqlServerVersionDetector.Detect(connectionString); Connector.Default = new SqlConnector(connectionString, sb.Schema, detector.Value); CacheLogic.Start(sb); DynamicLogicStarter.Start(sb); DynamicLogic.CompileDynamicCode(); DynamicLogic.RegisterMixins(); DynamicLogic.BeforeSchema(sb); TypeLogic.Start(sb); OperationLogic.Start(sb); ExceptionLogic.Start(sb); MigrationLogic.Start(sb); CultureInfoLogic.Start(sb); FilePathEmbeddedLogic.Start(sb); SmtpConfigurationLogic.Start(sb); EmailLogic.Start(sb, () => Configuration.Value.Email, (et, target) => Configuration.Value.SmtpConfiguration); AuthLogic.Start(sb, "System", null); AuthLogic.StartAllModules(sb); ResetPasswordRequestLogic.Start(sb); UserTicketLogic.Start(sb); SessionLogLogic.Start(sb); ProcessLogic.Start(sb); PackageLogic.Start(sb, packages: true, packageOperations: true); SchedulerLogic.Start(sb); QueryLogic.Start(sb); UserQueryLogic.Start(sb); UserQueryLogic.RegisterUserTypeCondition(sb, SouthwindGroup.UserEntities); UserQueryLogic.RegisterRoleTypeCondition(sb, SouthwindGroup.RoleEntities); ChartLogic.Start(sb); UserChartLogic.RegisterUserTypeCondition(sb, SouthwindGroup.UserEntities); UserChartLogic.RegisterRoleTypeCondition(sb, SouthwindGroup.RoleEntities); DashboardLogic.Start(sb); DashboardLogic.RegisterUserTypeCondition(sb, SouthwindGroup.UserEntities); DashboardLogic.RegisterRoleTypeCondition(sb, SouthwindGroup.RoleEntities); ViewLogLogic.Start(sb, new HashSet <Type> { typeof(UserQueryEntity), typeof(UserChartEntity), typeof(DashboardEntity) }); DiffLogLogic.Start(sb, registerAll: true); ExcelLogic.Start(sb, excelReport: true); ToolbarLogic.Start(sb); SMSLogic.Start(sb, null, () => Configuration.Value.Sms); SMSLogic.RegisterPhoneNumberProvider <PersonEntity>(p => p.Phone, p => null); SMSLogic.RegisterDataObjectProvider((PersonEntity p) => new { p.FirstName, p.LastName, p.Title, p.DateOfBirth }); SMSLogic.RegisterPhoneNumberProvider <CompanyEntity>(p => p.Phone, p => null); NoteLogic.Start(sb, typeof(UserEntity), /*Note*/ typeof(OrderEntity)); AlertLogic.Start(sb, typeof(UserEntity), /*Alert*/ typeof(OrderEntity)); FileLogic.Start(sb); TranslationLogic.Start(sb, countLocalizationHits: false); TranslatedInstanceLogic.Start(sb, () => CultureInfo.GetCultureInfo("en")); HelpLogic.Start(sb); WordTemplateLogic.Start(sb); MapLogic.Start(sb); PredictorLogic.Start(sb, () => new FileTypeAlgorithm { GetPrefixPair = f => new PrefixPair(Starter.Configuration.Value.Folders.PredictorModelFolder) }); PredictorLogic.RegisterAlgorithm(CNTKPredictorAlgorithm.NeuralNetwork, new CNTKNeuralNetworkPredictorAlgorithm()); PredictorLogic.RegisterPublication(ProductPredictorPublication.MonthlySales, new PublicationSettings { QueryName = typeof(OrderEntity) }); //ProductPredictorPublication RestLogLogic.Start(sb); RestApiKeyLogic.Start(sb); WorkflowLogicStarter.Start(sb, () => Starter.Configuration.Value.Workflow); EmployeeLogic.Start(sb); ProductLogic.Start(sb); CustomerLogic.Start(sb); OrderLogic.Start(sb); ShipperLogic.Start(sb); StartSouthwindConfiguration(sb); TypeConditionLogic.Register <OrderEntity>(SouthwindGroup.UserEntities, o => o.Employee == EmployeeEntity.Current); TypeConditionLogic.Register <EmployeeEntity>(SouthwindGroup.UserEntities, e => EmployeeEntity.Current.Is(e)); TypeConditionLogic.Register <OrderEntity>(SouthwindGroup.CurrentCustomer, o => o.Customer == CustomerEntity.Current); TypeConditionLogic.Register <PersonEntity>(SouthwindGroup.CurrentCustomer, o => o == CustomerEntity.Current); TypeConditionLogic.Register <CompanyEntity>(SouthwindGroup.CurrentCustomer, o => o == CustomerEntity.Current); ProfilerLogic.Start(sb, timeTracker: true, heavyProfiler: true, overrideSessionTimeout: true); DynamicLogic.StartDynamicModules(sb); DynamicLogic.RegisterExceptionIfAny(); SetupCache(sb); Schema.Current.OnSchemaCompleted(); } }
public Dictionary <OperationSymbol, string> GetCanExecuteLiteAll(Lite <Entity> lite) { return(Return(MethodInfo.GetCurrentMethod(), lite.EntityType.Name, () => OperationLogic.ServiceCanExecute(Database.Retrieve(lite)))); }
private static DateTime?SaveEmail(Pop3ConfigurationEntity config, Pop3ReceptionEntity reception, IPop3Client client, MessageUid mi) { DateTime?sent = null; { using (OperationLogic.AllowSave <EmailMessageEntity>()) using (Transaction tr = Transaction.ForceNew()) { string rawContent = null; try { var email = client.GetMessage(mi, reception.ToLite()); email.Subject = email.Subject == null ? "No Subject" : email.Subject.Replace('\n', ' ').Replace('\r', ' '); if (email.Recipients.IsEmpty()) { email.Recipients.Add(new EmailRecipientEntity { EmailAddress = config.Username, Kind = EmailRecipientKind.To, }); } Lite <EmailMessageEntity> duplicate = Database.Query <EmailMessageEntity>() .Where(a => a.BodyHash == email.BodyHash) .Select(a => a.ToLite()) .FirstOrDefault(); if (duplicate != null && AreDuplicates(email, duplicate.Retrieve())) { var dup = duplicate.Entity; email.AssignEntities(dup); AssociateDuplicateEmail?.Invoke(email, dup); } else { AssociateNewEmail?.Invoke(email); } email.Save(); sent = email.Mixin <EmailReceptionMixin>().ReceptionInfo.SentDate; tr.Commit(); } catch (Exception e) { e.Data["rawContent"] = rawContent; var ex = e.LogException(); using (Transaction tr2 = Transaction.ForceNew()) { new Pop3ReceptionExceptionEntity { Exception = ex.ToLite(), Reception = reception.ToLite() }.Save(); tr2.Commit(); } } } } return(sent); }